eve 0.84.0 → 0.84.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/src/channel/cross-channel-receive.d.ts +4 -1
  3. package/dist/src/channel/cross-channel-receive.js +1 -1
  4. package/dist/src/channel/delivery.js +1 -1
  5. package/dist/src/channel/session.js +1 -1
  6. package/dist/src/channel/types.d.ts +2 -0
  7. package/dist/src/chunks/{use-eve-agent-BbbguIdB.js → use-eve-agent-DMeP0JOF.js} +26 -10
  8. package/dist/src/chunks/{use-eve-agent-DWjyzplb.js → use-eve-agent-DP5Rso9C.js} +26 -10
  9. package/dist/src/cli/commands/init.js +1 -1
  10. package/dist/src/client/delivery.d.ts +2 -0
  11. package/dist/src/client/delivery.js +1 -1
  12. package/dist/src/client/optimistic-message-submissions.js +1 -1
  13. package/dist/src/client/session-store.js +1 -1
  14. package/dist/src/client/session.js +1 -1
  15. package/dist/src/client/sessions.d.ts +1 -0
  16. package/dist/src/client/sessions.js +1 -1
  17. package/dist/src/client/types.d.ts +2 -0
  18. package/dist/src/compiled/.vendor-stamp.json +2 -2
  19. package/dist/src/compiled/@chat-adapter/slack/index.js +13 -13
  20. package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +75 -0
  21. package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +4 -0
  22. package/dist/src/compiled/@vercel/sandbox/command.d.ts +78 -0
  23. package/dist/src/compiled/@vercel/sandbox/drive.d.ts +41 -1
  24. package/dist/src/compiled/@vercel/sandbox/index.js +13 -13
  25. package/dist/src/compiled/@vercel/sandbox/network-policy.d.ts +35 -4
  26. package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +18 -4
  27. package/dist/src/compiled/@vercel/sandbox/session.d.ts +29 -3
  28. package/dist/src/compiled/@vercel/sandbox/utils/pipe-stdin.d.ts +19 -0
  29. package/dist/src/compiled/_chunks/client/{core-CspsxXR-.js → core-BsvaaMUJ.js} +1 -1
  30. package/dist/src/compiled/_chunks/node/{auth-Dztlx9pE.js → auth-v5pS3mLo.js} +1 -1
  31. package/dist/src/compiled/_chunks/node/is-stream-DsuQX_bd.js +1 -0
  32. package/dist/src/compiled/_chunks/node/token-DHGH-jVc.js +1 -0
  33. package/dist/src/compiled/_chunks/node/token-util-BH2pw9Qm.js +25 -0
  34. package/dist/src/compiled/_chunks/node/token-util-CcvxNv76.js +1 -0
  35. package/dist/src/compiled/_chunks/node/version-C2PfNyEv.js +1 -0
  36. package/dist/src/compiled/zod/index.js +1 -1
  37. package/dist/src/compiled/zod/v4/core.js +1 -1
  38. package/dist/src/compiled/zod-validation-error/index.js +1 -1
  39. package/dist/src/compiler/artifacts.d.ts +1 -0
  40. package/dist/src/compiler/artifacts.js +1 -1
  41. package/dist/src/compiler/manifest.d.ts +2 -2
  42. package/dist/src/compiler/manifest.js +1 -1
  43. package/dist/src/compiler/model-catalog.d.ts +8 -18
  44. package/dist/src/compiler/model-catalog.js +1 -1
  45. package/dist/src/compiler/normalize-agent-config.js +1 -1
  46. package/dist/src/compiler/normalize-manifest-types.d.ts +3 -0
  47. package/dist/src/compiler/normalize-manifest.js +1 -1
  48. package/dist/src/context/keys.d.ts +0 -8
  49. package/dist/src/context/keys.js +1 -1
  50. package/dist/src/eve-channel/index.js +1 -1
  51. package/dist/src/eve-channel/request.d.ts +1 -0
  52. package/dist/src/eve-channel/request.js +1 -1
  53. package/dist/src/eve-channel/support.js +1 -1
  54. package/dist/src/execution/agent-sessions/steps.js +1 -1
  55. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  56. package/dist/src/execution/sandbox/bindings/docker-cli.d.ts +2 -0
  57. package/dist/src/execution/sandbox/bindings/docker-cli.js +1 -1
  58. package/dist/src/execution/sandbox/bindings/docker-connection.js +1 -1
  59. package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
  60. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  61. package/dist/src/execution/sandbox/multiplexed-command.d.ts +11 -1
  62. package/dist/src/execution/sandbox/multiplexed-command.js +1 -1
  63. package/dist/src/execution/sandbox/session.js +1 -1
  64. package/dist/src/execution/session-inbox/address.d.ts +1 -0
  65. package/dist/src/execution/session-inbox/handle.d.ts +7 -0
  66. package/dist/src/execution/session-inbox/handle.js +1 -0
  67. package/dist/src/execution/session-inbox/owner.d.ts +4 -4
  68. package/dist/src/execution/session-inbox/owner.js +1 -1
  69. package/dist/src/execution/session-inbox/resume.d.ts +1 -0
  70. package/dist/src/execution/session-inbox/resume.js +1 -1
  71. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  72. package/dist/src/execution/workflow-runtime.js +1 -1
  73. package/dist/src/harness/model-call/call.d.ts +3 -1
  74. package/dist/src/harness/model-call/call.js +1 -1
  75. package/dist/src/harness/model-call/run.js +1 -1
  76. package/dist/src/harness/semantic-errors/rules/gateway.js +1 -1
  77. package/dist/src/internal/application/compiled-artifacts.d.ts +2 -0
  78. package/dist/src/internal/application/compiled-artifacts.js +2 -2
  79. package/dist/src/internal/application/optional-package-install.js +1 -1
  80. package/dist/src/internal/application/stamped-package-version.js +1 -1
  81. package/dist/src/internal/model-catalog.d.ts +39 -16
  82. package/dist/src/internal/model-catalog.js +1 -1
  83. package/dist/src/internal/nitro/host/dev-build-host.js +1 -1
  84. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  85. package/dist/src/protocol/delivery.d.ts +1 -0
  86. package/dist/src/public/nuxt/module.js +1 -1
  87. package/dist/src/reactions/kinds/model.js +1 -1
  88. package/dist/src/reactions/kinds/subagent.js +1 -1
  89. package/dist/src/runtime/agent/resolve-model.d.ts +3 -4
  90. package/dist/src/runtime/agent/resolve-model.js +1 -1
  91. package/dist/src/runtime/loaders/artifact-paths.d.ts +1 -0
  92. package/dist/src/runtime/loaders/artifact-paths.js +1 -1
  93. package/dist/src/runtime/loaders/bundled-artifacts.d.ts +2 -0
  94. package/dist/src/runtime/loaders/bundled-artifacts.js +1 -1
  95. package/dist/src/runtime/loaders/model-metadata.d.ts +4 -0
  96. package/dist/src/runtime/loaders/model-metadata.js +1 -0
  97. package/dist/src/runtime/resolve-agent.js +1 -1
  98. package/dist/src/runtime/sessions/compiled-agent-cache.d.ts +3 -0
  99. package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
  100. package/dist/src/runtime/subagents/dynamic-agent-config.d.ts +2 -2
  101. package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -1
  102. package/dist/src/runtime/subagents/workflow.js +1 -1
  103. package/dist/src/sandbox/provider.d.ts +2 -0
  104. package/dist/src/setup/flows/model-source-change.js +1 -1
  105. package/dist/src/setup/scaffold/create/project.js +1 -1
  106. package/dist/src/shared/agent-definition.d.ts +0 -1
  107. package/dist/src/shared/sandbox-session.d.ts +4 -0
  108. package/dist/src/svelte/index.js +1 -1
  109. package/dist/src/svelte/use-eve-agent.js +1 -1
  110. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  111. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  112. package/dist/src/vue/index.js +1 -1
  113. package/dist/src/vue/use-eve-agent.js +1 -1
  114. package/docs/agent-config.md +5 -4
  115. package/docs/concepts/default-harness.md +6 -0
  116. package/docs/evals/judge.mdx +13 -0
  117. package/docs/guides/client/overview.mdx +23 -1
  118. package/docs/reference/cli.md +1 -1
  119. package/docs/sandbox/custom-providers.mdx +1 -1
  120. package/docs/sandbox/index.mdx +1 -1
  121. package/docs/tools/workflows.mdx +4 -0
  122. package/package.json +2 -2
  123. package/dist/src/compiled/_chunks/node/token-Bedbhv5z.js +0 -1
  124. package/dist/src/compiled/_chunks/node/token-util-DpJNusVS.js +0 -1
  125. package/dist/src/compiled/_chunks/node/token-util-DwHQ2a3c.js +0 -1
  126. package/dist/src/compiled/_chunks/node/version-C__MqbLM.js +0 -1
  127. package/dist/src/runtime/agent/model-catalog.d.ts +0 -10
  128. package/dist/src/runtime/agent/model-catalog.js +0 -1
@@ -1,15 +1,15 @@
1
- import{i as e,o as t,t as n}from"../../_chunks/node/rolldown-runtime-tZXQYakl.js";import{n as r,t as i}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as a,t as o}from"../../_chunks/node/retry-hTJQ4iNT.js";import{t as s}from"../../_chunks/node/undici-B61sz6UT.js";import{t as c}from"../../_chunks/node/version-C__MqbLM.js";import{n as l,r as u,t as d}from"../../_chunks/node/token-util-DpJNusVS.js";import{Readable as f}from"stream";import p from"zlib";import m,{dirname as h,resolve as g}from"path";import{createWriteStream as _}from"fs";import{z as v}from"#compiled/zod/index.js";import y from"os";import{pipeline as b}from"stream/promises";import{mkdir as x}from"fs/promises";import*as S from"node:constants";import{setTimeout as C}from"node:timers/promises";var w=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},T=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const ee=`iad1`;function te(e){return e==null?[]:Array.isArray(e)?e:[e]}var ne=t(n(((e,t)=>{var n=o();function r(e,t){function r(r,i){var a=t||{},o;`randomize`in a||(a.randomize=!0),o=n.operation(a);function s(e){i(e||Error(`Aborted`))}function c(e,t){if(e.bail){s(e);return}o.retry(e)?a.onRetry&&a.onRetry(e,t):i(o.mainError())}function l(t){var n;try{n=e(s,t)}catch(e){c(e,t);return}Promise.resolve(n).then(r).catch(function(e){c(e,t)})}o.attempt(l)}return new Promise(r)}t.exports=r}))(),1);function re(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,ne.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new w(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await ie(e*1e3,n.signal),new w(o)}if(o.status>=500&&o.status<600)throw new w(o);return o}catch(e){if(ae(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof w)return e.response;throw e}}}async function ie(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function ae(e){return e!=null&&e.name===`AbortError`}const oe=new(s()).Agent({bodyTimeout:0});var se=class{constructor(e){this.fetch=re(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=oe}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))te(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function E(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function ce(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}const le=v.object({error:v.object({message:v.string()})});function ue(e){let t=le.safeParse(e);return t.success?t.data.error.message:void 0}async function de(e,t){let n=E(t.url),r;n||(r=ce(t.url));let i=await t.text().catch(e=>new w(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new w(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok){let e=ue(a);return new w(t,{message:e?`Status code ${t.status} is not ok: ${e}`:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r})}let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new w(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function D(e,t){let n=await de(e,t);if(n instanceof w)throw n;return n}const fe=v.object({exact:v.string().optional(),startsWith:v.string().optional(),regex:v.string().optional()}),pe=v.object({key:fe.optional(),value:fe.optional()}),me=v.object({path:fe.optional(),method:v.array(v.string()).optional(),queryString:v.array(pe).optional(),headers:v.array(pe).optional()}),he=v.object({domain:v.string(),headers:v.record(v.string(),v.string()).optional(),headerNames:v.array(v.string()).optional(),match:me.optional()}),ge=v.object({domain:v.string(),forwardURL:v.string(),match:me.optional()}),_e=v.object({headers:v.record(v.string(),v.string()).optional()}),ve=v.object({match:me.optional(),transform:v.array(_e).optional(),forwardURL:v.string().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),ye=v.object({allow:v.union([v.array(v.string()),v.record(v.string(),v.array(ve))]).optional(),subnets:v.object({allow:v.array(v.string()).optional(),deny:v.array(v.string()).optional()}).optional()}),be=v.union([v.object({mode:v.literal(`allow-all`)}).passthrough(),v.object({mode:v.literal(`deny-all`)}).passthrough()]),xe=v.object({mode:v.literal(`custom`),allowedDomains:v.array(v.string()).optional(),allowedCIDRs:v.array(v.string()).optional(),deniedCIDRs:v.array(v.string()).optional(),injectionRules:v.array(he).optional(),forwardRules:v.array(ge).optional()}).passthrough(),Se=v.union([be,ye.passthrough()]),Ce=v.union([be,xe]),O=v.object({id:v.string(),memory:v.number(),vcpus:v.number(),region:v.string(),runtime:v.string().optional(),timeout:v.number(),status:v.enum([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:v.number(),startedAt:v.number().optional(),requestedStopAt:v.number().optional(),stoppedAt:v.number().optional(),abortedAt:v.number().optional(),duration:v.number().optional(),sourceSnapshotId:v.string().optional(),snapshottedAt:v.number().optional(),createdAt:v.number(),cwd:v.string(),updatedAt:v.number(),interactivePort:v.number().optional(),networkPolicy:Ce.optional(),activeCpuDurationMs:v.number().optional(),networkTransfer:v.object({ingress:v.number(),egress:v.number()}).optional()}),k=v.object({url:v.string(),subdomain:v.string(),port:v.number()}),A=v.object({id:v.string(),sourceSessionId:v.string(),region:v.string(),regions:v.array(v.string()).optional(),status:v.enum([`created`,`deleted`,`failed`]),sizeBytes:v.number(),expiresAt:v.number().optional(),createdAt:v.number(),updatedAt:v.number(),lastUsedAt:v.number().optional(),creationMethod:v.string().optional(),parentId:v.string().optional()}),j=v.object({count:v.number(),next:v.string().nullable()}),we=v.object({id:v.string(),name:v.string(),args:v.array(v.string()),cwd:v.string(),sessionId:v.string(),exitCode:v.number().nullable(),durationMs:v.number().optional(),startedAt:v.number()}),Te=we.extend({exitCode:v.number()}),M=v.object({session:O.passthrough()}),Ee=M.extend({routes:v.array(k)}),De=v.object({url:v.string(),token:v.string()}),N=v.object({sessions:v.array(O.passthrough()),pagination:j}),Oe=v.object({command:we}),ke=v.object({command:Te}),Ae=v.object({}),je=v.object({data:v.string()}),Me=je.extend({stream:v.literal(`stdout`)}),Ne=je.extend({stream:v.literal(`stderr`)}),Pe=v.object({stream:v.literal(`error`),data:v.object({code:v.string(),message:v.string()})}),Fe=v.discriminatedUnion(`stream`,[Me,Ne,Pe]),Ie=v.object({snapshots:v.array(A),pagination:j}),Le=v.object({snapshot:A,siblings:v.array(A),count:v.string()}),Re=v.object({snapshots:v.array(Le),anchor:Le.optional(),pagination:j}),ze=v.object({snapshot:A,session:O.passthrough()}),Be=v.object({snapshot:A}),Ve=v.object({id:v.string(),name:v.string(),projectId:v.string(),region:v.string(),maxSizeBytes:v.number(),currentSessionId:v.string().optional(),currentSandboxName:v.string().optional(),createdAt:v.number(),updatedAt:v.number()}),He=v.object({drives:v.array(Ve),pagination:j}),Ue=v.object({drive:Ve}),We=v.object({name:v.string(),persistent:v.boolean(),region:v.string().optional(),failoverRegions:v.array(v.string()).optional(),vcpus:v.number().optional(),memory:v.number().optional(),runtime:v.string().optional(),image:v.string().optional(),timeout:v.number().optional(),networkPolicy:Ce.optional(),totalEgressBytes:v.number().optional(),totalIngressBytes:v.number().optional(),totalActiveCpuDurationMs:v.number().optional(),totalDurationMs:v.number().optional(),createdAt:v.number(),updatedAt:v.number(),expiresAt:v.number().optional(),currentSessionId:v.string(),currentSnapshotId:v.string().optional(),status:O.shape.status,statusUpdatedAt:v.number().optional(),cwd:v.string().optional(),tags:v.record(v.string(),v.string()).optional(),mounts:v.record(v.string(),v.object({drive:v.string(),mode:v.enum([`snapshot`,`read-write`,`read-only`]).optional()}).transform(e=>({drive:e.drive,mode:e.mode===`read-only`?`snapshot`:e.mode??`read-write`}))).optional(),snapshotExpiration:v.number().optional(),keepLastSnapshots:v.object({count:v.number(),expiration:v.number().optional(),deleteEvicted:v.boolean().optional()}).optional()}),Ge=v.object({session:O.passthrough(),sandbox:We.optional(),snapshot:A.optional()}),Ke=v.object({sandbox:We,session:O.passthrough(),routes:v.array(k),resumed:v.boolean().optional()}),qe=v.object({sandboxes:v.array(We),pagination:j}),Je=v.object({sandbox:We,routes:v.array(k).optional()});var Ye=n(((t,n)=>{n.exports=e(`events`)})),Xe=n(((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-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(e){return this.buffer[this.top]===void 0&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})),Ze=n(((e,t)=>{let n=Xe();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})),Qe=n(((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n){return b(e).toString(`hex`,t,n)}function C(e,t,n,r,i){return b(e).write(t,n,r,i)}function w(e,t){return b(e).readDoubleBE(t)}function T(e,t){return b(e).readDoubleLE(t)}function ee(e,t){return b(e).readFloatBE(t)}function te(e,t){return b(e).readFloatLE(t)}function ne(e,t){return b(e).readInt32BE(t)}function re(e,t){return b(e).readInt32LE(t)}function ie(e,t){return b(e).readUInt32BE(t)}function ae(e,t){return b(e).readUInt32LE(t)}function oe(e,t,n){return b(e).writeDoubleBE(t,n)}function se(e,t,n){return b(e).writeDoubleLE(t,n)}function E(e,t,n){return b(e).writeFloatBE(t,n)}function ce(e,t,n){return b(e).writeFloatLE(t,n)}function le(e,t,n){return b(e).writeInt32BE(t,n)}function ue(e,t,n){return b(e).writeInt32LE(t,n)}function de(e,t,n){return b(e).writeUInt32BE(t,n)}function D(e,t,n){return b(e).writeUInt32LE(t,n)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,toHex:S,write:C,readDoubleBE:w,readDoubleLE:T,readFloatBE:ee,readFloatLE:te,readInt32BE:ne,readInt32LE:re,readUInt32BE:ie,readUInt32LE:ae,writeDoubleBE:oe,writeDoubleLE:se,writeFloatBE:E,writeFloatLE:ce,writeInt32BE:le,writeInt32LE:ue,writeUInt32BE:de,writeUInt32LE:D}})),$e=n(((e,t)=>{let n=Qe();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})),et=n(((e,t)=>{let n=Qe();t.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(e){if(e.byteLength===0)return``;if(this.bytesNeeded===0&&r(e,0)===0)return this.bytesSeen=i(e),n.toString(e,`utf8`);let t=``,a=0;if(this.bytesNeeded>0){for(;a<e.byteLength;){let n=e[a];if(n<this.lowerBoundary||n>this.upperBoundary){t+=`�`,this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|n&63,this.bytesSeen++,a++,this.bytesSeen===this.bytesNeeded){t+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return t}let o=r(e,a),s=e.byteLength-o;s>a&&(t+=n.toString(e,`utf8`,a,s));for(let n=s;n<e.byteLength;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?(this.bytesSeen=0,t+=String.fromCharCode(r)):r>=194&&r<=223?(this.bytesNeeded=2,this.bytesSeen=1,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.bytesSeen=1,this.codePoint=r&15):r>=240&&r<=244?(r===240?this.lowerBoundary=144:r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.bytesSeen=1,this.codePoint=r&7):(this.bytesSeen=1,t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){t+=`�`,n--,this._reset();continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this._reset())}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this._reset(),e}_reset(){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191}};function r(e,t){let n=e.byteLength;if(n<=t)return 0;let r=Math.max(t,n-4),i=n-1;for(;i>r&&(e[i]&192)==128;)i--;if(i<t)return 0;let a=e[i],o;if(a<=127)return 0;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 0;let s=n-i;return s<o?s:0}function i(e){let t=e.byteLength;if(t===0)return 0;let n=e[t-1];if(n<=127)return 0;if((n&192)!=128)return 1;let r=Math.max(0,t-4),i=t-2;for(;i>=r&&(e[i]&192)==128;)i--;if(i<0)return 1;let a=e[i],o;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 1;if(t-i!==o)return 1;if(o>=3){let t=e[i+1];if(a===224&&t<160||a===237&&t>159||a===240&&t<144||a===244&&t>143)return 1}return 0}})),tt=n(((e,t)=>{let n=$e(),r=et();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(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 Error(`Unknown encoding: `+e)}}})),nt=n(((e,t)=>{t.exports=class e extends Error{constructor(t,n,r=e){super(t),this.code=n,Error.captureStackTrace&&Error.captureStackTrace(this,r)}static isStreamDestroyed(e){return e&&e.code===`STREAM_DESTROYED`}static isPrematureClose(e){return e&&e.code===`PREMATURE_CLOSE`}static isAborted(e){return e&&e.code===`ABORTED`}static isBadArgument(e){return e&&e.code===`BAD_ARGUMENT`}get name(){return`StreamError`}static STREAM_DESTROYED(){return new e(`Stream was destroyed`,`STREAM_DESTROYED`,e.STREAM_DESTROYED)}static PREMATURE_CLOSE(t=`Premature close`){return new e(t,`PREMATURE_CLOSE`,e.PREMATURE_CLOSE)}static ABORTED(){return new e(`Stream aborted`,`ABORTED`,e.ABORTED)}static BAD_ARGUMENT(t=`Bad argument`){return new e(t,`BAD_ARGUMENT`,e.BAD_ARGUMENT)}}})),rt=n(((e,t)=>{let{EventEmitter:n}=Ye(),r=Ze(),i=tt(),a=nt(),o=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,s=536870910,c=1024,l=2048,u=16384,d=32768,f=131072,p=536805375,m=536870143,h=536838143,g=536739839,_=2<<18,v=4<<18,y=8<<18,b=32<<18,x=64<<18,S=128<<18,C=512<<18,w=1024<<18,T=503316479,ee=268435455,te=262160,ne=8404992,re=8405006,ie=33587200,ae=33587215,oe=16527,se=270794767,E=Symbol.asyncIterator||Symbol(`asyncIterator`);var ce=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:i,byteLength:a,byteLengthWritable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||a||Ie,this.map=i||n,this.afterWrite=me.bind(this),this.afterUpdateNextTick=_e.bind(this)}get ending(){return!!(this.stream._duplexState&C)}get ended(){return!!(this.stream._duplexState&b)}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=y,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|C)&535822335}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&se)==2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=_;do{for(;(e._duplexState&se)==y;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)==C){e._duplexState|=262144,e._final(fe.bind(this));return}if((e._duplexState&14)==4){e._duplexState&ie||(e._duplexState|=te,e._destroy(pe.bind(this)));return}(e._duplexState&ae)==1&&(e._duplexState=(e._duplexState|te)&s,e._open(ye.bind(this)))}continueUpdate(){return this.stream._duplexState&S?(this.stream._duplexState&=T,!0):!1}updateCallback(){(this.stream._duplexState&35127311)==v?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&S||(this.stream._duplexState|=S,this.stream._duplexState&_||o(this.afterUpdateNextTick))}},le=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:i,byteLength:a,byteLengthReadable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||a||Ie,this.map=i||n,this.pipeTo=null,this.afterRead=he.bind(this),this.afterUpdateNextTick=ge.bind(this)}get ending(){return!!(this.stream._duplexState&c)}get ended(){return!!(this.stream._duplexState&u)}pipe(e,t){if(this.pipeTo!==null)throw a.BAD_ARGUMENT(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new de(this.stream,e,t),t&&this.stream.on(`error`,Le),N(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Le),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,D.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|c)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=p,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&p,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&oe)==128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=f,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&oe)==128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)==f;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=8192,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)==c&&(e._duplexState=(e._duplexState|u)&536869887,e.emit(`end`),(e._duplexState&re)==ne&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){e._duplexState&ie||(e._duplexState|=te,e._destroy(pe.bind(this)));return}(e._duplexState&ae)==1&&(e._duplexState=(e._duplexState|te)&s,e._open(ye.bind(this)))}continueUpdate(){return this.stream._duplexState&d?(this.stream._duplexState&=h,!0):!1}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&d||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}},ue=class{constructor(e){this.data=null,this.afterTransform=be.bind(e),this.afterFinal=null}},de=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&u)||!this.pipeToFinished)&&this.from.destroy(this.error||a.PREMATURE_CLOSE(`Writable stream closed`));return}if(e===this.from&&(this.from=null,this.to!==null)){e._duplexState&u||this.to.destroy(this.error||a.PREMATURE_CLOSE(`Readable stream closed`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function D(){this.stream._duplexState|=512,this.updateCallback()}function fe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=b,t.emit(`finish`)),(t._duplexState&re)==ne&&(t._duplexState|=4),t._duplexState&=402391039,t._duplexState&_?this.updateNextTick():this.update()}function pe(e){let t=this.stream;!e&&!a.isStreamDestroyed(this.error)&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,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 me(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&ve(this.drains),(t._duplexState&6553615)==4194304&&(t._duplexState&=532676607,(t._duplexState&x)==x&&t.emit(`drain`)),this.updateCallback()}function he(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=g),this.updateCallback()}function ge(){this.stream._duplexState&32||(this.stream._duplexState&=h,this.update())}function _e(){this.stream._duplexState&_||(this.stream._duplexState&=T,this.update())}function ve(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function ye(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=v),t.emit(`open`)),t._duplexState&=536608751,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function be(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function xe(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=133376,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=4096,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=x,this._writableState.updateNextTick())}var Se=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Re.bind(this))),this.on(`newListener`,xe)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState!==null||void 0}get writable(){return this._writableState!==null||void 0}get destroyed(){return!!(this._duplexState&8)}get destroying(){return!!(this._duplexState&14)}destroy(e){this._duplexState&14||(e||=a.STREAM_DESTROYED(),this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},Ce=class e extends Se{constructor(e){super(e),this._duplexState|=8519681,this._readableState=new le(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=g),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}static deferred(e,t){let n=new j(t);return e().then(e=>{if(e===null)return n.end();n.destroying||M(e,n,Le)}).catch(e=>n.destroy(e)),n}setEncoding(e){let t=new i(e),n=this._readableState.map||Ee;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(Ne(t))return t;if(t[E])return this._fromAsyncIterator(t[E](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return!!(e._duplexState&17422)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return!(e._duplexState&256)}[E](){let e=this,t=null,n=null,r=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,i),this.on(`close`,o),{[E](){return this},next(){return new Promise(function(t,i){n=t,r=i;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function i(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(i){r!==null&&(t?r(t):i===null&&!(e._duplexState&u)?r(a.STREAM_DESTROYED()):n({value:i,done:i===null}),r=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},O=class extends Se{constructor(e){super(e),this._duplexState|=16385,this._writableState=new ce(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=w}uncork(){this._duplexState&=ee,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return!!(e._duplexState&146800654)}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(ze(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&67108864?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},k=class extends Ce{constructor(e){super(e),this._duplexState=1|this._duplexState&f,this._writableState=new ce(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=w}uncork(){this._duplexState&=ee,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},A=class extends k{constructor(e){super(e),this._transformState=new ue(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(we.bind(this))}},j=class extends A{};function we(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function Te(...e){return new Promise((t,n)=>M(...e,e=>{if(e)return n(e);t()}))}function M(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 a.BAD_ARGUMENT(`Pipeline requires at least 2 streams`);let i=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],N(i)?i.pipe(o,l):(c(i,!0,e>1,l),i.pipe(o)),i=o;if(r){let e=!1,t=N(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:a.PREMATURE_CLOSE())))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,i);function i(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(a.PREMATURE_CLOSE())}}function l(e){if(e&&!s){s=e;for(let t of n)t.destroy(e)}}}function Ee(e){return e}function De(e){return!!e._readableState||!!e._writableState}function N(e){return typeof e._duplexState==`number`&&De(e)}function Oe(e){return!!e._readableState&&e._readableState.ending}function ke(e){return!!e._readableState&&e._readableState.ended}function Ae(e){return!!e._writableState&&e._writableState.ending}function je(e){return!!e._writableState&&e._writableState.ended}function Me(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&a.isStreamDestroyed(n)?null:n}function Ne(e){return N(e)&&e.readable}function Pe(e){return(e._duplexState&1)!=1||(e._duplexState&4)==4||!!(e._duplexState&ie)}function Fe(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ie(e){return Fe(e)?e.byteLength:1024}function Le(){}function Re(){this.destroy(a.ABORTED())}function ze(e){return e._writev!==O.prototype._writev&&e._writev!==k.prototype._writev}t.exports={pipeline:M,pipelinePromise:Te,isStream:De,isStreamx:N,isEnding:Oe,isEnded:ke,isFinishing:Ae,isFinished:je,isDisturbed:Pe,getStreamError:Me,Stream:Se,Writable:O,Readable:Ce,Duplex:k,Transform:A,PassThrough:j}})),it=n((e=>{let t=Qe(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
1
+ import{i as e,o as t,t as n}from"../../_chunks/node/rolldown-runtime-tZXQYakl.js";import{n as r,t as i}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as a,t as o}from"../../_chunks/node/retry-hTJQ4iNT.js";import{t as s}from"../../_chunks/node/undici-B61sz6UT.js";import{t as c}from"../../_chunks/node/version-C2PfNyEv.js";import{i as l,r as u,t as d}from"../../_chunks/node/token-util-BH2pw9Qm.js";import{Readable as f,Writable as p}from"stream";import m from"zlib";import h,{dirname as g,resolve as _}from"path";import{createWriteStream as v}from"fs";import{z as y}from"#compiled/zod/index.js";import b from"os";import{setTimeout as x}from"node:timers/promises";import{StringDecoder as S}from"node:string_decoder";import{pipeline as C}from"stream/promises";import{mkdir as w}from"fs/promises";import*as T from"node:constants";var E=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},D=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const ee=`iad1`;var te=t(n(((e,t)=>{var n=o();function r(e,t){function r(r,i){var a=t||{},o;`randomize`in a||(a.randomize=!0),o=n.operation(a);function s(e){i(e||Error(`Aborted`))}function c(e,t){if(e.bail){s(e);return}o.retry(e)?a.onRetry&&a.onRetry(e,t):i(o.mainError())}function l(t){var n;try{n=e(s,t)}catch(e){c(e,t);return}Promise.resolve(n).then(r).catch(function(e){c(e,t)})}o.attempt(l)}return new Promise(r)}t.exports=r}))(),1);function ne(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,te.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new E(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await re(e*1e3,n.signal),new E(o)}if(o.status>=500&&o.status<600)throw new E(o);return o}catch(e){if(ie(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof E)return e.response;throw e}}}async function re(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function ie(e){return e!=null&&e.name===`AbortError`}function ae(e){return e==null?[]:Array.isArray(e)?e:[e]}const oe=new(s()).Agent({bodyTimeout:0});var se=class{constructor(e){this.fetch=ne(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=oe}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))ae(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function ce(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function le(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}const ue=y.object({error:y.object({message:y.string()})});function de(e){let t=ue.safeParse(e);return t.success?t.data.error.message:void 0}async function fe(e,t,n){let r=ce(t.url),i;r||(i=le(t.url));let a=n??await t.text().catch(e=>new E(t,{message:`Can't read response text: ${String(e)}`,sessionId:r,sandboxName:i}));if(typeof a!=`string`)return a;let o;try{o=JSON.parse(a||`{}`)}catch(e){return new E(t,{message:`Can't parse JSON: ${String(e)}`,text:a,sessionId:r,sandboxName:i})}if(!t.ok){let e=de(o);return new E(t,{message:e?`Status code ${t.status} is not ok: ${e}`:`Status code ${t.status} is not ok`,json:o,text:a,sessionId:r,sandboxName:i})}let s=e.safeParse(o);return s.success?{json:s.data,response:t,text:a}:new E(t,{message:`Response JSON is not valid: ${s.error}`,json:o,text:a,sessionId:r,sandboxName:i})}async function O(e,t,n){let r=await fe(e,t,n);if(r instanceof E)throw r;return r}const pe=y.object({exact:y.string().optional(),startsWith:y.string().optional(),regex:y.string().optional()}),me=y.object({key:pe.optional(),value:pe.optional()}),he=y.object({path:pe.optional(),method:y.array(y.string()).optional(),queryString:y.array(me).optional(),headers:y.array(me).optional()}),ge=y.object({domain:y.string(),headers:y.record(y.string(),y.string()).optional(),headerNames:y.array(y.string()).optional(),match:he.optional()}),_e=y.object({domain:y.string(),forwardURL:y.string(),match:he.optional()}),ve=y.object({headers:y.record(y.string(),y.string()).optional()}),ye=new Set([`connection`,`content-length`,`transfer-encoding`]),be=new Set([204,205,304]),xe=y.object({statusCode:y.number().int().min(200).max(599),headers:y.record(y.string(),y.string()).optional(),body:y.string().optional(),contentType:y.string().optional()}).refine(({body:e,contentType:t})=>e===void 0||t!==void 0,{message:`contentType must be provided when body is set`}).refine(({statusCode:e,body:t})=>t===void 0||!be.has(e),{message:`body is not allowed on status codes 204, 205, and 304`}).refine(({headers:e})=>Object.keys(e??{}).every(e=>!ye.has(e.toLowerCase())),{message:`headers cannot set proxy-managed headers`}).refine(({headers:e})=>{let t=Object.keys(e??{}).map(e=>e.toLowerCase());return new Set(t).size===t.length},{message:`headers cannot contain duplicate names`}),Se=y.object({match:he.optional(),transform:y.array(ve).optional(),forwardURL:y.string().optional(),response:xe.optional()}).refine(({transform:e,forwardURL:t,response:n})=>[e,t,n].filter(e=>e!==void 0).length<=1,{message:`only one of transform, forwardURL, or response can be used per rule`}).refine(({transform:e,forwardURL:t,response:n})=>e!==void 0||t!==void 0||n!==void 0,{message:`transform, forwardURL, or response must be provided`}),Ce=y.object({allow:y.union([y.array(y.string()),y.record(y.string(),y.array(Se))]).optional(),subnets:y.object({allow:y.array(y.string()).optional(),deny:y.array(y.string()).optional()}).optional()}),we=y.union([y.object({mode:y.literal(`allow-all`)}).passthrough(),y.object({mode:y.literal(`deny-all`)}).passthrough()]),Te=y.object({mode:y.literal(`custom`),allowedDomains:y.array(y.string()).optional(),allowedCIDRs:y.array(y.string()).optional(),deniedCIDRs:y.array(y.string()).optional(),injectionRules:y.array(ge).optional(),forwardRules:y.array(_e).optional()}).passthrough(),Ee=y.union([we,Ce.passthrough()]),De=y.union([we,Te]),Oe=y.object({id:y.string(),memory:y.number(),vcpus:y.number(),region:y.string(),runtime:y.string().optional(),timeout:y.number(),status:y.enum([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:y.number(),startedAt:y.number().optional(),requestedStopAt:y.number().optional(),stoppedAt:y.number().optional(),abortedAt:y.number().optional(),duration:y.number().optional(),sourceSnapshotId:y.string().optional(),snapshottedAt:y.number().optional(),createdAt:y.number(),cwd:y.string(),updatedAt:y.number(),interactivePort:y.number().optional(),networkPolicy:De.optional(),activeCpuDurationMs:y.number().optional(),networkTransfer:y.object({ingress:y.number(),egress:y.number()}).optional()}),ke=y.object({url:y.string(),subdomain:y.string(),port:y.number()}),Ae=y.object({id:y.string(),sourceSessionId:y.string(),region:y.string(),regions:y.array(y.string()).optional(),status:y.enum([`created`,`deleted`,`failed`]),sizeBytes:y.number(),expiresAt:y.number().optional(),createdAt:y.number(),updatedAt:y.number(),lastUsedAt:y.number().optional(),creationMethod:y.string().optional(),parentId:y.string().optional()}),je=y.object({count:y.number(),next:y.string().nullable()}),k=y.object({id:y.string(),name:y.string(),args:y.array(y.string()),cwd:y.string(),sessionId:y.string(),exitCode:y.number().nullable(),durationMs:y.number().optional(),startedAt:y.number()}),Me=k.extend({exitCode:y.number()}),Ne=y.object({session:Oe.passthrough()}),Pe=Ne.extend({routes:y.array(ke)}),Fe=y.object({url:y.string(),token:y.string()}),Ie=y.object({sessions:y.array(Oe.passthrough()),pagination:je}),Le=y.object({command:k}),Re=Le.extend({bytesWritten:y.number().int().nonnegative().optional()}),ze=y.object({command:Me}),Be=y.object({}),Ve=y.object({data:y.string()}),He=Ve.extend({stream:y.literal(`stdout`)}),Ue=Ve.extend({stream:y.literal(`stderr`)}),We=y.object({stream:y.literal(`error`),data:y.object({code:y.string(),message:y.string()})}),Ge=y.discriminatedUnion(`stream`,[He,Ue,We]),Ke=y.object({snapshots:y.array(Ae),pagination:je}),qe=y.object({snapshot:Ae,siblings:y.array(Ae),count:y.string()}),Je=y.object({snapshots:y.array(qe),anchor:qe.optional(),pagination:je}),Ye=y.object({snapshot:Ae,session:Oe.passthrough()}),Xe=y.object({snapshot:Ae}),Ze=y.object({id:y.string(),parentDriveId:y.string().optional(),rootDriveId:y.string().optional(),name:y.string(),projectId:y.string(),region:y.string(),maxSizeBytes:y.number(),currentSessionId:y.string().optional(),currentSandboxName:y.string().optional(),createdAt:y.number(),updatedAt:y.number()}),Qe=y.object({drives:y.array(Ze),pagination:je}),$e=y.object({drive:Ze}),et=y.object({name:y.string(),persistent:y.boolean(),region:y.string().optional(),failoverRegions:y.array(y.string()).optional(),networkId:y.string().optional(),vcpus:y.number().optional(),memory:y.number().optional(),runtime:y.string().optional(),image:y.string().optional(),timeout:y.number().optional(),networkPolicy:De.optional(),totalEgressBytes:y.number().optional(),totalIngressBytes:y.number().optional(),totalActiveCpuDurationMs:y.number().optional(),totalDurationMs:y.number().optional(),createdAt:y.number(),updatedAt:y.number(),expiresAt:y.number().optional(),currentSessionId:y.string(),currentSnapshotId:y.string().optional(),status:Oe.shape.status,statusUpdatedAt:y.number().optional(),cwd:y.string().optional(),tags:y.record(y.string(),y.string()).optional(),mounts:y.record(y.string(),y.object({drive:y.string(),mode:y.enum([`snapshot`,`read-write`,`read-only`]).optional()}).transform(e=>({drive:e.drive,mode:e.mode===`read-only`?`snapshot`:e.mode??`read-write`}))).optional(),snapshotExpiration:y.number().optional(),keepLastSnapshots:y.object({count:y.number(),expiration:y.number().optional(),deleteEvicted:y.boolean().optional()}).optional()}),tt=y.object({session:Oe.passthrough(),sandbox:et.optional(),snapshot:Ae.optional()}),nt=y.object({sandbox:et,session:Oe.passthrough(),routes:y.array(ke),resumed:y.boolean().optional()}),rt=y.object({sandboxes:y.array(et),pagination:je}),it=y.object({sandbox:et,routes:y.array(ke).optional()});var at=n(((t,n)=>{n.exports=e(`events`)})),ot=n(((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-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(e){return this.buffer[this.top]===void 0&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})),st=n(((e,t)=>{let n=ot();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})),ct=n(((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n){return b(e).toString(`hex`,t,n)}function C(e,t,n,r,i){return b(e).write(t,n,r,i)}function w(e,t){return b(e).readDoubleBE(t)}function T(e,t){return b(e).readDoubleLE(t)}function E(e,t){return b(e).readFloatBE(t)}function D(e,t){return b(e).readFloatLE(t)}function ee(e,t){return b(e).readInt32BE(t)}function te(e,t){return b(e).readInt32LE(t)}function ne(e,t){return b(e).readUInt32BE(t)}function re(e,t){return b(e).readUInt32LE(t)}function ie(e,t,n){return b(e).writeDoubleBE(t,n)}function ae(e,t,n){return b(e).writeDoubleLE(t,n)}function oe(e,t,n){return b(e).writeFloatBE(t,n)}function se(e,t,n){return b(e).writeFloatLE(t,n)}function ce(e,t,n){return b(e).writeInt32BE(t,n)}function le(e,t,n){return b(e).writeInt32LE(t,n)}function ue(e,t,n){return b(e).writeUInt32BE(t,n)}function de(e,t,n){return b(e).writeUInt32LE(t,n)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,toHex:S,write:C,readDoubleBE:w,readDoubleLE:T,readFloatBE:E,readFloatLE:D,readInt32BE:ee,readInt32LE:te,readUInt32BE:ne,readUInt32LE:re,writeDoubleBE:ie,writeDoubleLE:ae,writeFloatBE:oe,writeFloatLE:se,writeInt32BE:ce,writeInt32LE:le,writeUInt32BE:ue,writeUInt32LE:de}})),lt=n(((e,t)=>{let n=ct();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})),ut=n(((e,t)=>{let n=ct();t.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(e){if(e.byteLength===0)return``;if(this.bytesNeeded===0&&r(e,0)===0)return this.bytesSeen=i(e),n.toString(e,`utf8`);let t=``,a=0;if(this.bytesNeeded>0){for(;a<e.byteLength;){let n=e[a];if(n<this.lowerBoundary||n>this.upperBoundary){t+=`�`,this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|n&63,this.bytesSeen++,a++,this.bytesSeen===this.bytesNeeded){t+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return t}let o=r(e,a),s=e.byteLength-o;s>a&&(t+=n.toString(e,`utf8`,a,s));for(let n=s;n<e.byteLength;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?(this.bytesSeen=0,t+=String.fromCharCode(r)):r>=194&&r<=223?(this.bytesNeeded=2,this.bytesSeen=1,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.bytesSeen=1,this.codePoint=r&15):r>=240&&r<=244?(r===240?this.lowerBoundary=144:r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.bytesSeen=1,this.codePoint=r&7):(this.bytesSeen=1,t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){t+=`�`,n--,this._reset();continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this._reset())}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this._reset(),e}_reset(){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191}};function r(e,t){let n=e.byteLength;if(n<=t)return 0;let r=Math.max(t,n-4),i=n-1;for(;i>r&&(e[i]&192)==128;)i--;if(i<t)return 0;let a=e[i],o;if(a<=127)return 0;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 0;let s=n-i;return s<o?s:0}function i(e){let t=e.byteLength;if(t===0)return 0;let n=e[t-1];if(n<=127)return 0;if((n&192)!=128)return 1;let r=Math.max(0,t-4),i=t-2;for(;i>=r&&(e[i]&192)==128;)i--;if(i<0)return 1;let a=e[i],o;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 1;if(t-i!==o)return 1;if(o>=3){let t=e[i+1];if(a===224&&t<160||a===237&&t>159||a===240&&t<144||a===244&&t>143)return 1}return 0}})),dt=n(((e,t)=>{let n=lt(),r=ut();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(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 Error(`Unknown encoding: `+e)}}})),ft=n(((e,t)=>{t.exports=class e extends Error{constructor(t,n,r=e){super(t),this.code=n,Error.captureStackTrace&&Error.captureStackTrace(this,r)}static isStreamDestroyed(e){return e&&e.code===`STREAM_DESTROYED`}static isPrematureClose(e){return e&&e.code===`PREMATURE_CLOSE`}static isAborted(e){return e&&e.code===`ABORTED`}static isBadArgument(e){return e&&e.code===`BAD_ARGUMENT`}get name(){return`StreamError`}static STREAM_DESTROYED(){return new e(`Stream was destroyed`,`STREAM_DESTROYED`,e.STREAM_DESTROYED)}static PREMATURE_CLOSE(t=`Premature close`){return new e(t,`PREMATURE_CLOSE`,e.PREMATURE_CLOSE)}static ABORTED(){return new e(`Stream aborted`,`ABORTED`,e.ABORTED)}static BAD_ARGUMENT(t=`Bad argument`){return new e(t,`BAD_ARGUMENT`,e.BAD_ARGUMENT)}}})),pt=n(((e,t)=>{let{EventEmitter:n}=at(),r=st(),i=dt(),a=ft(),o=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,s=536870910,c=1024,l=2048,u=16384,d=32768,f=131072,p=536805375,m=536870143,h=536838143,g=536739839,_=2<<18,v=4<<18,y=8<<18,b=32<<18,x=64<<18,S=128<<18,C=512<<18,w=1024<<18,T=503316479,E=268435455,D=262160,ee=8404992,te=8405006,ne=33587200,re=33587215,ie=16527,ae=270794767,oe=Symbol.asyncIterator||Symbol(`asyncIterator`);var se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:i,byteLength:a,byteLengthWritable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||a||Be,this.map=i||n,this.afterWrite=pe.bind(this),this.afterUpdateNextTick=ge.bind(this)}get ending(){return!!(this.stream._duplexState&C)}get ended(){return!!(this.stream._duplexState&b)}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=y,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|C)&535822335}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&ae)==2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=_;do{for(;(e._duplexState&ae)==y;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)==C){e._duplexState|=262144,e._final(fe.bind(this));return}if((e._duplexState&14)==4){e._duplexState&ne||(e._duplexState|=D,e._destroy(O.bind(this)));return}(e._duplexState&re)==1&&(e._duplexState=(e._duplexState|D)&s,e._open(ve.bind(this)))}continueUpdate(){return this.stream._duplexState&S?(this.stream._duplexState&=T,!0):!1}updateCallback(){(this.stream._duplexState&35127311)==v?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&S||(this.stream._duplexState|=S,this.stream._duplexState&_||o(this.afterUpdateNextTick))}},ce=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:i,byteLength:a,byteLengthReadable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||a||Be,this.map=i||n,this.pipeTo=null,this.afterRead=me.bind(this),this.afterUpdateNextTick=he.bind(this)}get ending(){return!!(this.stream._duplexState&c)}get ended(){return!!(this.stream._duplexState&u)}pipe(e,t){if(this.pipeTo!==null)throw a.BAD_ARGUMENT(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new ue(this.stream,e,t),t&&this.stream.on(`error`,Ve),k(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Ve),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,de.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|c)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=p,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&p,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&ie)==128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=f,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&ie)==128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)==f;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=8192,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)==c&&(e._duplexState=(e._duplexState|u)&536869887,e.emit(`end`),(e._duplexState&te)==ee&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){e._duplexState&ne||(e._duplexState|=D,e._destroy(O.bind(this)));return}(e._duplexState&re)==1&&(e._duplexState=(e._duplexState|D)&s,e._open(ve.bind(this)))}continueUpdate(){return this.stream._duplexState&d?(this.stream._duplexState&=h,!0):!1}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&d||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}},le=class{constructor(e){this.data=null,this.afterTransform=ye.bind(e),this.afterFinal=null}},ue=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&u)||!this.pipeToFinished)&&this.from.destroy(this.error||a.PREMATURE_CLOSE(`Writable stream closed`));return}if(e===this.from&&(this.from=null,this.to!==null)){e._duplexState&u||this.to.destroy(this.error||a.PREMATURE_CLOSE(`Readable stream closed`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function de(){this.stream._duplexState|=512,this.updateCallback()}function fe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=b,t.emit(`finish`)),(t._duplexState&te)==ee&&(t._duplexState|=4),t._duplexState&=402391039,t._duplexState&_?this.updateNextTick():this.update()}function O(e){let t=this.stream;!e&&!a.isStreamDestroyed(this.error)&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,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 pe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&_e(this.drains),(t._duplexState&6553615)==4194304&&(t._duplexState&=532676607,(t._duplexState&x)==x&&t.emit(`drain`)),this.updateCallback()}function me(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=g),this.updateCallback()}function he(){this.stream._duplexState&32||(this.stream._duplexState&=h,this.update())}function ge(){this.stream._duplexState&_||(this.stream._duplexState&=T,this.update())}function _e(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function ve(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=v),t.emit(`open`)),t._duplexState&=536608751,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ye(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function be(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=133376,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=4096,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=x,this._writableState.updateNextTick())}var xe=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,He.bind(this))),this.on(`newListener`,be)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState!==null||void 0}get writable(){return this._writableState!==null||void 0}get destroyed(){return!!(this._duplexState&8)}get destroying(){return!!(this._duplexState&14)}destroy(e){this._duplexState&14||(e||=a.STREAM_DESTROYED(),this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},Se=class e extends xe{constructor(e){super(e),this._duplexState|=8519681,this._readableState=new ce(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=g),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}static deferred(e,t){let n=new Ee(t);return e().then(e=>{if(e===null)return n.end();n.destroying||ke(e,n,Ve)}).catch(e=>n.destroy(e)),n}setEncoding(e){let t=new i(e),n=this._readableState.map||Ae;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(Le(t))return t;if(t[oe])return this._fromAsyncIterator(t[oe](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return!!(e._duplexState&17422)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return!(e._duplexState&256)}[oe](){let e=this,t=null,n=null,r=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,i),this.on(`close`,o),{[oe](){return this},next(){return new Promise(function(t,i){n=t,r=i;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function i(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(i){r!==null&&(t?r(t):i===null&&!(e._duplexState&u)?r(a.STREAM_DESTROYED()):n({value:i,done:i===null}),r=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},Ce=class extends xe{constructor(e){super(e),this._duplexState|=16385,this._writableState=new se(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=w}uncork(){this._duplexState&=E,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return!!(e._duplexState&146800654)}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Ue(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&67108864?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},we=class extends Se{constructor(e){super(e),this._duplexState=1|this._duplexState&f,this._writableState=new se(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=w}uncork(){this._duplexState&=E,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Te=class extends we{constructor(e){super(e),this._transformState=new le(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(De.bind(this))}},Ee=class extends Te{};function De(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function Oe(...e){return new Promise((t,n)=>ke(...e,e=>{if(e)return n(e);t()}))}function ke(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 a.BAD_ARGUMENT(`Pipeline requires at least 2 streams`);let i=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],k(i)?i.pipe(o,l):(c(i,!0,e>1,l),i.pipe(o)),i=o;if(r){let e=!1,t=k(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:a.PREMATURE_CLOSE())))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,i);function i(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(a.PREMATURE_CLOSE())}}function l(e){if(e&&!s){s=e;for(let t of n)t.destroy(e)}}}function Ae(e){return e}function je(e){return!!e._readableState||!!e._writableState}function k(e){return typeof e._duplexState==`number`&&je(e)}function Me(e){return!!e._readableState&&e._readableState.ending}function Ne(e){return!!e._readableState&&e._readableState.ended}function Pe(e){return!!e._writableState&&e._writableState.ending}function Fe(e){return!!e._writableState&&e._writableState.ended}function Ie(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&a.isStreamDestroyed(n)?null:n}function Le(e){return k(e)&&e.readable}function Re(e){return(e._duplexState&1)!=1||(e._duplexState&4)==4||!!(e._duplexState&ne)}function ze(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Be(e){return ze(e)?e.byteLength:1024}function Ve(){}function He(){this.destroy(a.ABORTED())}function Ue(e){return e._writev!==Ce.prototype._writev&&e._writev!==we.prototype._writev}t.exports={pipeline:ke,pipelinePromise:Oe,isStream:je,isStreamx:k,isEnding:Me,isEnded:Ne,isFinishing:Pe,isFinished:Fe,isDisturbed:Re,getStreamError:Ie,Stream:xe,Writable:Ce,Readable:Se,Duplex:we,Transform:Te,PassThrough:Ee}})),mt=n((e=>{let t=ct(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
2
2
  `)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
3
3
  `));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
4
- `);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(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 u(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 d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(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 p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(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 i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})),at=n(((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=rt(),a=Ze(),o=Qe(),s=it(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!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,null),this._gnuLongLinkPath&&=(this._header.linkname=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,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e))}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(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 e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})),ot=n(((t,n)=>{let r={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{n.exports=e(`fs`).constants||r}catch{n.exports=r}})),st=n(((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=rt(),a=Qe(),o=ot(),s=it(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})),ct=t(n((e=>{e.extract=at(),e.pack=st()}))(),1),lt=class{constructor(){let e=p.createGzip();this.pack=ct.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof f?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function ut(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function dt(e){if(!m.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!m.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=m.posix.isAbsolute(e.filePath)?m.posix.normalize(e.filePath):m.posix.join(e.cwd,e.filePath);return m.posix.relative(e.extractDir,t)}function ft(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Se.parse(t),t}function pt(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const P=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var mt=n(((t,n)=>{var r=e(`stream`).Transform;function i(e){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);e||={},r.call(this,{objectMode:!0}),this._memory=``,this._emitInvalidLines=e.emitInvalidLines||!1}i.prototype=Object.create(r.prototype),i.prototype._handleLines=function(e,t){for(var n=0;n<e.length;n++)if(e[n]!==``){var r=null,i=null;try{i=JSON.parse(e[n])}catch(t){t.source=e[n],r=t}if(r){if(this._emitInvalidLines)this.emit(`invalid-line`,r);else return t(r)}else this.push(i)}t(null)},i.prototype._transform=function(e,t,n){var r=(this._memory+e.toString()).split(`
5
- `);this._memory=r.pop(),this._handleLines(r,n)},i.prototype._flush=function(e){if(!this._memory)return e(null);var t=this._memory;this._memory=``,this._handleLines([t],e)},n.exports=i})),ht=n(((t,n)=>{var r=e(`stream`).Transform;function i(){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);r.call(this,{objectMode:!0})}i.prototype=Object.create(r.prototype),i.prototype._transform=function(e,t,n){var r;try{r=JSON.stringify(e)}catch(t){return t.source=e,n(t)}n(null,r+`
6
- `)},n.exports=i})),gt=n((e=>{var t=mt();ht(),e.parse=function(e){return new t(e)}})),_t=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}0&&(t.exports={SYMBOL_FOR_REQ_CONTEXT:u,getContext:d})})),vt=n(((e,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),d={};s(d,{getVercelOidcToken:()=>m,getVercelOidcTokenSync:()=>h}),n.exports=l(d);var f=_t(),p=u();async function m(e){let n=``,r;try{n=h()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await import(`../../_chunks/node/token-util-DwHQ2a3c.js`).then(e=>t(e.default)),await import(`../../_chunks/node/token-Bedbhv5z.js`).then(e=>t(e.default))]);(!n||i(r(n),e?.expirationBufferMs))&&(await a(e),n=h())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
7
- ${e.message}`),t?new p.VercelOidcTokenError(t):e}return n}function h(){let e=(0,f.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);return e}0&&(n.exports={getVercelOidcToken:m,getVercelOidcTokenSync:h})})),yt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),u={};o(u,{AccessTokenMissingError:()=>m.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>m.RefreshAccessTokenFailedError,getContext:()=>p.getContext,getVercelOidcToken:()=>f.getVercelOidcToken,getVercelOidcTokenSync:()=>f.getVercelOidcTokenSync,getVercelToken:()=>h.getVercelToken}),t.exports=c(u);var f=vt(),p=_t(),m=l(),h=d();0&&(t.exports={AccessTokenMissingError,RefreshAccessTokenFailedError,getContext,getVercelOidcToken,getVercelOidcTokenSync,getVercelToken})})),bt=t(gt(),1),xt=yt();function St(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var F=class extends se{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=St(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,xt.getVercelOidcToken)({expirationBufferMs:3e5,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=St(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${c} (Node.js/${process.version}; ${y.platform()}/${y.arch()})`,...t?.headers}})}async getSession(e){let t=P(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,D(Ee,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=P(e),n=e.runtime===void 0?`/v3/sandboxes`:`/v2/sandboxes`;return D(Ke,await this.request(n,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?ft(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async forkSandbox(e){let t=P(e);return D(Ke,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?ft(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await D(v.any(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new w(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new w(t,{message:`No response body`,sessionId:e.sessionId});let n=bt.parse();Ct(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new T(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=Oe.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new T(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=ke.parse(t.value);return e}let n=Fe.parse(t.value);if(n.stream===`error`)throw new T(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return D(Oe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?D(ke,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):D(Oe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return D(De,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return D(Ae,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new lt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await ut(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return D(N,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return D(Ie,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return D(Re,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return D(He,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getOrCreateDrive(e){return D(Ue,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,region:e.region,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:dt({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await D(Ae,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new w(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:f.fromWeb(t.body)}async killCommand(e){return D(Oe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?wt(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await D(v.any(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new w(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new w(i,{message:`No response body`,sessionId:e.sessionId});let a=bt.parse();Ct(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=Fe.parse(t);if(n.stream===`error`)throw new T(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return D(Ge,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return D(M,await this.request(t,{method:`POST`,body:JSON.stringify(ft(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return D(M,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return D(ze,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return D(Be,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return D(Be,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=P(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),D(Ke,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return D(qe,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:Tt(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return D(Ue,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return D(Je,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,timeout:e.timeout,networkPolicy:e.networkPolicy?ft(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,mounts:e.mounts}),signal:e.signal}))}async deleteSandbox(e){return D(Je,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId,deleteOrphanSnapshots:e.deleteOrphanSnapshots?`true`:void 0},signal:e.signal}))}};async function Ct(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function wt(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function Tt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0){if(t.length>1)throw Error("Filtering by multiple tags is not supported. Pass a single `{ key: value }` tag.");return t.map(([e,t])=>`${e}:${t}`)}}function Et(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var I=t(n(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c}))(),1);const Dt={warn:I.default.yellow,error:I.default.red,success:I.default.green,info:I.default.blue},Ot=I.default.dim(`[vercel/sandbox]`);function L(e,t){t=Array.isArray(t)?t.join(`
8
- `):t;let n=t.replace(/^/gm,`${Ot} `);console.error(Dt[e](n))}function kt(e){return I.default.italic(I.default.dim("`")+e+I.default.dim("`"))}var At=t(a(),1);async function jt(){return await import(`../../_chunks/node/auth-Dztlx9pE.js`)}function Mt(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const Nt=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,Pt(t).catch(t=>{throw e=null,t})]);let n=await e[1];return L(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function Pt(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await jt(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await Ft({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${I.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
9
- `));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&L(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function Ft(e,t){L(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${I.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();L(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${I.default.italic(r.verification_uri)} and type ${I.default.bold(r.user_code)}`,` Press ${I.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${I.default.bold(`help:`)} Link your project with ${kt(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
10
- `);i=Error(e),a.return()},(0,At.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw L(`error`,`${I.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return L(`success`,`${I.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var It=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
11
- `);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Lt=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
12
- `);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function Rt(e){try{return Vt(await(0,xt.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!Mt())throw process.env.VERCEL_URL?new Lt(t):new It(t);return await Nt(e)}}async function R(e){return zt(e??{})||await Rt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function zt(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Bt=v.object({exp:v.number().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:v.number().optional().describe(`Issued at timestamp`),owner_id:v.string(),project_id:v.string()});function Vt(e){try{let t=Bt.parse(Et(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Ht={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Ut(e){if(typeof e==`number`)return e;if(e in Ht)return Ht[e];throw Error(`Unknown signal name: ${String(e)}`)}var Wt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[r](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new Gt({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Ut(e??`SIGTERM`),abortSignal:t?.abortSignal})}},Gt=class e extends Wt{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[r](e){return{...Wt[r](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function z(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Kt(i);let t=e;for(yield t;t.pagination.next!==null;)Kt(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Kt(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Kt(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var qt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get regions(){return this.snapshot.regions??[this.snapshot.region]}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[r](e){return{snapshot:e.snapshot}}static[i](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return z(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function Jt(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?pt(t):void 0}}var Yt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[r](e){return{session:e.session,routes:e.routes}}static[i](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=Jt(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new Wt({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new Gt({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new Wt({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:ut(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=g(t.cwd??``,t.path);return n?.mkdirRecursive&&await x(h(e),{recursive:!0}),await b(i,_(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=Jt(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=Jt((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=Jt((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=Jt(n.json.session),new qt({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:B,S_IFREG:Xt,S_IFDIR:Zt,S_IFLNK:Qt,S_IFBLK:$t,S_IFCHR:en,S_IFIFO:tn,S_IFSOCK:nn}=S;function V(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function rn(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var an=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&B)===Xt}isDirectory(){return(this.mode&B)===Zt}isBlockDevice(){return(this.mode&B)===$t}isCharacterDevice(){return(this.mode&B)===en}isSymbolicLink(){return(this.mode&B)===Qt}isFIFO(){return(this.mode&B)===tn}isSocket(){return(this.mode&B)===nn}},on=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function sn(e){let t=e.trim().split(`|`);return new an(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function cn(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw V(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new on(r,un[i]??1,t)}const ln=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,un={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var dn=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=rn(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw V(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw V(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`scandir`,e):V(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
13
- `).filter(Boolean).map(t=>cn(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`scandir`,e):V(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
14
- `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,ln,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`stat`,e):V(`EACCES`,t.trim(),`stat`,e)}return sn(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,ln,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`lstat`,e):V(`EACCES`,t.trim(),`lstat`,e)}return sn(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`unlink`,e):V(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`rm`,e):V(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?V(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):V(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`rename`,e):V(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`copyfile`,e):V(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw V(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`chmod`,e):V(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`chown`,e):V(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?V(`EEXIST`,`file already exists`,`symlink`,t):V(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`readlink`,e):V(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`realpath`,e):V(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`truncate`,e):V(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw V(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const fn=/^[a-z_][a-z0-9_-]*$/;function H(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!fn.test(e))throw Error(`Invalid ${t} "${e}": must match ${fn} (lowercase letters, digits, hyphens, underscores)`)}var pn=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},mn=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:f.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=g(t.cwd??``,t.path);return n?.mkdirRecursive&&await x(h(i),{recursive:!0}),await b(r,_(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){H(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){H(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function hn(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{drive:`mode`in t?t.drive:t.name,mode:`mode`in t?t.mode:`read-write`}]))}function gn(e){return e instanceof w&&e.response.status===410}function _n(e){return e instanceof w&&e.response.status===404}function vn(e){return e instanceof w&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function yn(e){return e instanceof w&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function bn(e){return e instanceof w&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var xn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region??`iad1`}get failoverRegions(){return this.sandbox.failoverRegions??[]}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get mounts(){return this.sandbox.mounts}get networkPolicy(){return this.sandbox.networkPolicy?pt(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[r](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[i](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new Yt({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";if(e?.runtime!==void 0&&e.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=P(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,mounts:hn(e?.mounts),snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,region:e?.region,failoverRegions:e?.failoverRegions,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new Sn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=P(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,persistent:e.persistent,signal:e.signal,...r});return new Sn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=P(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(t?.runtime!==void 0&&t.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(_n(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(vn(n)){let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=P(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!_n(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new Yt({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new dn(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new Yt({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await C(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new Yt({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(gn(n))return await this.resume(t),e();if(yn(n)||bn(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
15
- `);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){H(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new pn(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new mn({sandbox:this,username:e})}asUser(e){return H(e,`username`),new mn({sandbox:this,username:e})}async createGroup(e,t){H(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){H(e,`username`),H(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){H(e,`username`),H(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,mounts:hn(e.mounts),signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!gn(e)&&!yn(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(gn(e)||yn(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,deleteOrphanSnapshots:e?.deleteOrphanSnapshots,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},Sn=class extends xn{async[Symbol.asyncDispose](){await this.stop()}},Cn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get driveId(){return this.drive.id}get name(){return this.drive.name}get projectId(){return this._projectId}get region(){return this.drive.region??`iad1`}get maxSize(){return this.drive.maxSizeBytes}get currentSessionId(){return this.drive.currentSessionId}get currentSandboxName(){return this.drive.currentSandboxName}get createdAt(){return new Date(this.drive.createdAt)}get updatedAt(){return new Date(this.drive.updatedAt)}snapshot(){return{drive:this.name,mode:`snapshot`}}static[r](e){return{drive:e.drive,projectId:e._projectId}}static[i](t){return new e({drive:t.drive,projectId:t.projectId})}constructor({client:e,drive:t,projectId:n}){this._client=null,this._client=e??null,this.drive=t,this._projectId=n??t.projectId}static async list(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t?.fetch}),i=async i=>{let a=await r.listDrives({...n,...t,...i!==void 0&&{cursor:i}});return{...a.json,drives:a.json.drives.map(t=>new e({client:r,drive:t,projectId:n.projectId}))}};return z(await i(t?.cursor),{itemsKey:`drives`,fetchNext:i,signal:t?.signal})}static async getOrCreate(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getOrCreateDrive({projectId:n.projectId,name:t.name,region:t.region,maxSizeBytes:t.maxSize,signal:t.signal})).json.drive,projectId:n.projectId})}async delete(e){"use step";this.drive=(await(await this.ensureClient()).deleteDrive({projectId:this._projectId,name:this.drive.name,signal:e?.signal})).json.drive}};const wn=new TextEncoder,U=new TextDecoder;function Tn(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function En(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Dn(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function On(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:U.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=U.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Dn(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}const W=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),G=(e,t)=>e.name===t;function kn(e){return parseInt(e.name.slice(4),10)}function An(e,t){if(kn(e.hash)!==t)throw W(`SHA-${t}`,`algorithm.hash`)}function jn(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function Mn(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Nn(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!G(e.algorithm,`HMAC`))throw W(`HMAC`);An(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!G(e.algorithm,`RSASSA-PKCS1-v1_5`))throw W(`RSASSA-PKCS1-v1_5`);An(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!G(e.algorithm,`RSA-PSS`))throw W(`RSA-PSS`);An(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!G(e.algorithm,`Ed25519`))throw W(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!G(e.algorithm,t))throw W(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!G(e.algorithm,`ECDSA`))throw W(`ECDSA`);let n=jn(t);if(e.algorithm.namedCurve!==n)throw W(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}Mn(e,n)}function Pn(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const Fn=(e,...t)=>Pn(`Key must be `,e,...t),In=(e,t,...n)=>Pn(`Key for the ${e} algorithm must be `,t,...n);var K=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},q=class extends K{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Ln=class extends K{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Rn=class extends K{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},J=class extends K{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},Y=class extends K{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},X=class extends K{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},zn=class extends K{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},Bn=class extends K{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Vn=class extends K{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},Hn=class extends K{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Un=class extends K{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};const Wn=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Gn=e=>e?.[Symbol.toStringTag]===`KeyObject`,Kn=e=>Wn(e)||Gn(e);function qn(e,t,n){try{return On(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const Jn=e=>typeof e==`object`&&!!e;function Z(e){if(!Jn(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Yn(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const Xn=e=>Z(e)&&typeof e.kty==`string`,Zn=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Qn=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,$n=e=>e.kty===`oct`&&typeof e.k==`string`;function er(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function tr(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new J(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function nr(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(Fn(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return Nn(t,e,n),t}async function rr(e,t,n,r){let i=await nr(e,t,`verify`);er(e,i);let a=tr(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const ir=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function ar(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new J(ir)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new J(ir)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new J(ir)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new J(ir)}break;default:throw new J(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function or(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=ar(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const sr=`given KeyObject instance cannot be used for this algorithm`;let Q;const cr=async(e,t,n,r=!1)=>{Q||=new WeakMap;let i=Q.get(e);if(i?.[n])return i[n];let a=await or({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:Q.set(e,{[n]:a}),a},lr=(e,t)=>{Q||=new WeakMap;let n=Q.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(sr)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(sr);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(sr);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(sr)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(sr);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(sr);return n?n[t]=a:Q.set(e,{[t]:a}),a};async function ur(e,t){if(e instanceof Uint8Array||Wn(e))return e;if(Gn(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return lr(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:`jwk`});return cr(e,n,t)}if(Xn(e))return e.k?On(e.k):cr(e,e,t,!0);throw Error(`unreachable`)}async function dr(e,t,n){if(!Z(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return On(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new J(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return or({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return or({...e,ext:r});case`EC`:case`OKP`:return or({...e,alg:t,ext:r});default:throw new J(`Unsupported "kty" (Key Type) Parameter value`)}}function fr(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new J(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function pr(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const mr=e=>e?.[Symbol.toStringTag],hr=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},gr=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(Xn(t)){if($n(t)&&hr(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!Kn(t))throw TypeError(In(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${mr(t)} instances for symmetric algorithms must be of type "secret"`)}},_r=(e,t,n)=>{if(Xn(t))switch(n){case`decrypt`:case`sign`:if(Zn(t)&&hr(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Qn(t)&&hr(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!Kn(t))throw TypeError(In(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${mr(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${mr(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${mr(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${mr(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${mr(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function vr(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:gr(e,t,n);break;default:_r(e,t,n)}}async function yr(e,t,n){if(!Z(e))throw new Y(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new Y(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new Y(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new Y(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new Y(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!Z(e.header))throw new Y(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=On(e.protected);r=JSON.parse(U.decode(t))}catch{throw new Y(`JWS Protected Header is invalid`)}if(!Yn(r,e.header))throw new Y(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=fr(Y,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new Y(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new Y(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&pr(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Rn(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new Y(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new Y(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),vr(s,t,`verify`);let u=Tn(e.protected===void 0?new Uint8Array:En(e.protected),En(`.`),typeof e.payload==`string`?o?En(e.payload):wn.encode(e.payload):e.payload),d=qn(e.signature,`signature`,Y),f=await ur(t,s);if(!await rr(s,f,d,u))throw new Un;let p;p=o?qn(e.payload,`payload`,Y):typeof e.payload==`string`?wn.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?{...m,key:f}:m}async function br(e,t,n){if(e instanceof Uint8Array&&(e=U.decode(e)),typeof e!=`string`)throw new Y(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new Y(`Invalid Compact JWS`);let s=await yr({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}const xr=e=>Math.floor(e.getTime()/1e3),Sr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Cr(e){let t=Sr.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600)}return t[1]===`-`||t[4]===`ago`?-i:i}const wr=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,Tr=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function Er(e,t,n={}){let r;try{r=JSON.parse(U.decode(t))}catch{}if(!Z(r))throw new X(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||wr(e.typ)!==wr(i)))throw new q(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new q(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new q(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new q(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!Tr(r.aud,typeof c==`string`?[c]:c))throw new q(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=Cr(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=xr(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new q(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new q(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new q(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new q(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new Ln(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:Cr(l);if(e-d>t)throw new Ln(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new q(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r}async function Dr(e,t,n){let r=await br(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new X(`JWTs MUST NOT use unencoded payload`);let i={payload:Er(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}function Or(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new J(`Unsupported "alg" value for a JSON Web Key Set`)}}function kr(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(Ar)}function Ar(e){return Z(e)}var jr=class{#e;#t=new WeakMap;constructor(e){if(!kr(e))throw new zn(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=Or(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`}return t}),{0:o,length:s}=a;if(s===0)throw new Bn;if(s!==1){let e=new Vn,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await Mr(t,e,n)}catch{}},e}return Mr(this.#t,o,n)}};async function Mr(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await dr({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new zn(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Nr(e){let t=new jr(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Pr(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Fr;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Fr=`jose/v6.2.3`);const Ir=Symbol();async function Lr(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new Hn:e});if(i.status!==200)throw new K(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new K(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Rr=Symbol();function zr(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!Z(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Z))}var Br=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Fr&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Fr),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[Ir],t?.[Rr]!==void 0&&(this.#l=t?.[Rr],zr(t?.[Rr],this.#r)&&(this.#i=this.#l.uat,this.#c=Nr(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#n}fresh(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#r}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof Bn&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Pr()&&(this.#a=void 0),this.#a||=Lr(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Nr(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Vr(e,t){let n=new Br(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}function Hr(e){if(typeof e!=`string`)throw new X(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new X(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new X(`Invalid JWT`);if(!t)throw new X(`JWTs must contain a payload`);let r;try{r=On(t)}catch{throw new X(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(U.decode(r))}catch{throw new X(`Failed to parse the decoded payload as JSON`)}if(!Z(i))throw new X(`Invalid JWT Claims Set`);return i}const Ur=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,Wr=new Set,Gr=typeof process==`object`&&process?process:{},Kr=(e,t,n,r)=>{typeof Gr.emitWarning==`function`?Gr.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let qr=globalThis.AbortController,Jr=globalThis.AbortSignal;if(qr===void 0){Jr=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},qr=class{constructor(){t()}signal=new Jr;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=Gr.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,Kr("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const Yr=e=>!Wr.has(e),$=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Xr=e=>$(e)?e<=256?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?Zr:null:null;var Zr=class extends Array{constructor(e){super(e),this.fill(0)}},Qr=class e{heap;length;static#e=!1;static create(t){let n=Xr(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},$r=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:_,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:x,ignoreFetchAbort:S}=t;if(n!==0&&!$(n))throw TypeError(`max option must be a nonnegative integer`);let C=n?Xr(n):Array;if(!C)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(_!==void 0&&typeof _!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=_,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new C(n),this.#f=new C(n),this.#p=0,this.#m=0,this.#h=Qr.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!S,this.maxEntrySize!==0){if(this.#t!==0&&!$(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!$(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=$(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!$(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;Yr(t)&&(Wr.add(t),Kr(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new Zr(this.#e),t=new Zr(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=Ur.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:Ur.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=Ur.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new Zr(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!$(n)){if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!$(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`)}return n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(Ur.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=Ur.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=Ur.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new qr,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof qr}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#c.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,y,v,m);return t.__returned=t}{let t=this.#u[y];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(y),r&&this.#w(y),g&&this.#T(g,y),t;let a=this.#I(e,y,v,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0){if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}};const ei=`vercel-forwarded-host`,ti=`vercel-forwarded-scheme`,ni=`vercel-forwarded-port`,ri=`vercel-forwarded-path`,ii=`vercel-sandbox-oidc-token`,ai=new $r({max:100});function oi(e,t=si){return async function(n){let r=new Headers(n.headers),i=r.get(ei),a=r.get(ti),o=r.get(ni),s=r.get(ri),c=r.get(ii);if(r.delete(ei),r.delete(ti),r.delete(ni),r.delete(ri),r.delete(ii),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(ci(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=li(new URL(n.url),s),r=await fi(c,t),i=di(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function si(){return new Response(`Forbidden`,{status:403})}function ci(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function li(e,t){let n=ui(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=ui(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=ui(r.pathname.slice(0,-n.length))),r}function ui(e){return e.replace(/\/+$/,``)||`/`}function di(e,t){let n=hi(t,`team_id`),r=hi(t,`project_id`),i=hi(t,`sandbox_id`),a=hi(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function fi(e,t){let n=hi(Hr(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await Dr(e,mi(n),{audience:pi(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function pi(e){let t=ui(e.pathname);return t===`/`?e.origin:e.origin+t}function mi(e){let t=ai.get(e);if(t)return t;let n=Vr(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return ai.set(e,n),n}function hi(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{w as APIError,Wt as Command,Gt as CommandFinished,ee as DEFAULT_SANDBOX_REGION,Cn as Drive,dn as FileSystem,xn as Sandbox,mn as SandboxUser,pn as SandboxUserAlreadyExistsError,Yt as Session,qt as Snapshot,T as StreamError,oi as defineSandboxProxy};
4
+ `);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(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 u(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 d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(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 p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(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 i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})),ht=n(((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=pt(),a=st(),o=ct(),s=mt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!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,null),this._gnuLongLinkPath&&=(this._header.linkname=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,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e))}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(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 e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})),gt=n(((t,n)=>{let r={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{n.exports=e(`fs`).constants||r}catch{n.exports=r}})),_t=n(((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=pt(),a=ct(),o=gt(),s=mt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})),vt=t(n((e=>{e.extract=ht(),e.pack=_t()}))(),1),yt=class{constructor(){let e=m.createGzip();this.pack=vt.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof f?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function bt(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function xt(e){if(!h.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!h.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=h.posix.isAbsolute(e.filePath)?h.posix.normalize(e.filePath):h.posix.join(e.cwd,e.filePath);return h.posix.relative(e.extractDir,t)}function St(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ee.parse(t),t}function Ct(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const A=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var wt=n(((t,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{KNOWN_AGENTS:()=>T,determineAgent:()=>E}),n.exports=l(u);var d=e(`node:fs/promises`),f=e(`node:fs`);let p=`cursor`,m=`cursor-cli`,h=`claude`,g=`cowork`,_=`devin`,v=`replit`,y=`gemini`,b=`codex`,x=`antigravity`,S=`augment-cli`,C=`opencode`,w=`github-copilot`,T={CURSOR:p,CURSOR_CLI:m,CLAUDE:h,COWORK:g,DEVIN:_,REPLIT:v,GEMINI:y,CODEX:b,ANTIGRAVITY:x,AUGMENT_CLI:S,OPENCODE:C,GITHUB_COPILOT:w,V0:`v0`};async function E(){if(process.env.AI_AGENT){let e=process.env.AI_AGENT.trim();if(e)return e===w||e===`github-copilot-cli`?{isAgent:!0,agent:{name:w}}:e===`v0`?{isAgent:!0,agent:{name:`v0`}}:{isAgent:!0,agent:{name:e}}}if(process.env.CURSOR_TRACE_ID)return{isAgent:!0,agent:{name:p}};if(process.env.CURSOR_AGENT||process.env.CURSOR_EXTENSION_HOST_ROLE===`agent-exec`)return{isAgent:!0,agent:{name:m}};if(process.env.GEMINI_CLI)return{isAgent:!0,agent:{name:y}};if(process.env.CODEX_SANDBOX||process.env.CODEX_CI||process.env.CODEX_THREAD_ID)return{isAgent:!0,agent:{name:b}};if(process.env.ANTIGRAVITY_AGENT)return{isAgent:!0,agent:{name:x}};if(process.env.AUGMENT_AGENT)return{isAgent:!0,agent:{name:S}};if(process.env.OPENCODE_CLIENT)return{isAgent:!0,agent:{name:C}};if(process.env.CLAUDECODE||process.env.CLAUDE_CODE)return process.env.CLAUDE_CODE_IS_COWORK?{isAgent:!0,agent:{name:g}}:{isAgent:!0,agent:{name:h}};if(process.env.REPL_ID)return{isAgent:!0,agent:{name:v}};if(process.env.COPILOT_MODEL||process.env.COPILOT_ALLOW_ALL||process.env.COPILOT_GITHUB_TOKEN)return{isAgent:!0,agent:{name:w}};try{return await(0,d.access)(`/opt/.devin`,f.constants.F_OK),{isAgent:!0,agent:{name:_}}}catch{}return{isAgent:!1,agent:void 0}}0&&(n.exports={KNOWN_AGENTS:T,determineAgent:E})}))();let Tt;function Et(){return process.env.VERCEL_TELEMETRY_DISABLED||process.env.VERCEL_SANDBOX_TELEMETRY_DISABLED?Promise.resolve(void 0):(Tt||=(0,wt.determineAgent)().then(e=>e.isAgent?e.agent.name:void 0,()=>void 0),Tt)}var Dt=n(((t,n)=>{var r=e(`stream`).Transform;function i(e){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);e||={},r.call(this,{objectMode:!0}),this._memory=``,this._emitInvalidLines=e.emitInvalidLines||!1}i.prototype=Object.create(r.prototype),i.prototype._handleLines=function(e,t){for(var n=0;n<e.length;n++)if(e[n]!==``){var r=null,i=null;try{i=JSON.parse(e[n])}catch(t){t.source=e[n],r=t}if(r){if(this._emitInvalidLines)this.emit(`invalid-line`,r);else return t(r)}else this.push(i)}t(null)},i.prototype._transform=function(e,t,n){var r=(this._memory+e.toString()).split(`
5
+ `);this._memory=r.pop(),this._handleLines(r,n)},i.prototype._flush=function(e){if(!this._memory)return e(null);var t=this._memory;this._memory=``,this._handleLines([t],e)},n.exports=i})),Ot=n(((t,n)=>{var r=e(`stream`).Transform;function i(){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);r.call(this,{objectMode:!0})}i.prototype=Object.create(r.prototype),i.prototype._transform=function(e,t,n){var r;try{r=JSON.stringify(e)}catch(t){return t.source=e,n(t)}n(null,r+`
6
+ `)},n.exports=i})),kt=n((e=>{var t=Dt();Ot(),e.parse=function(e){return new t(e)}})),At=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{version:()=>u}),t.exports=c(l);let u=`4.0.0`;0&&(t.exports={version:u})})),jt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{exchangeVercelOidcToken:()=>p}),t.exports=c(l);var u=At();let d=new class{constructor(e){this.maxEntries=e,this.entries=new Map}get(e){let t=this.entries.get(e);if(t!==void 0){if(t.expiresAt<=Date.now()){this.entries.delete(e);return}return this.entries.delete(e),this.entries.set(e,t),t.token}}set({key:e,token:t,expiresAt:n}){for(this.entries.delete(e),this.entries.set(e,{token:t,expiresAt:n});this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}}}(1e3);async function f(e){let t=JSON.stringify([e.token,e.audience,e.jti]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function p(e){let t=await f(e);if(!e.skipCache){let e=d.get(t);if(e!==void 0)return e}let n=await fetch(`https://oidc.vercel.com/~token`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`@vercel/oidc@${u.version}`},body:JSON.stringify({token:e.token,aud:e.audience,...e.jti?{jti:e.jti}:void 0})});if(!n.ok)throw Error(`Failed to exchange token: ${await m(n)}`);let r;try{r=await n.json()}catch{throw Error(`Failed to exchange token: response was not valid JSON`)}if(!r||typeof r!=`object`||!(`token`in r)||typeof r.token!=`string`)throw Error(`Failed to exchange token: response did not contain a token`);let{token:i}=r,a=`expiry`in r&&typeof r.expiry==`number`?r.expiry:void 0;if(a!==void 0){let e=a*1e3;e>Date.now()&&d.set({key:t,token:i,expiresAt:e})}return i}async function m(e){try{let t=await e.json();if(t&&typeof t==`object`&&`error`in t&&typeof t.error==`string`)return t.error}catch{}return e.statusText||`HTTP ${e.status}`}0&&(t.exports={exchangeVercelOidcToken:p})})),Mt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}0&&(t.exports={SYMBOL_FOR_REQ_CONTEXT:u,getContext:d})})),Nt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{getVercelOidcTokenSync:()=>d}),t.exports=c(l);var u=Mt();function d(){let e=(0,u.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request.`);return e}0&&(t.exports={getVercelOidcTokenSync:d})})),Pt=n(((n,r)=>{var i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of o(t))!s.call(e,c)&&c!==n&&i(e,c,{get:()=>t[c],enumerable:!(r=a(t,c))||r.enumerable});return e},d=e=>u(i({},`__esModule`,{value:!0}),e),f={};c(f,{getVercelOidcToken:()=>v}),r.exports=d(f);var p=e(`node:fs/promises`),m=jt(),h=Mt(),g=Nt(),_=l();async function v(e){let n=``,r,i=(0,h.getContext)().headers?.[`x-vercel-oidc-token`]?null:await y();try{n=i??(0,g.getVercelOidcTokenSync)()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await import(`../../_chunks/node/token-util-CcvxNv76.js`).then(e=>t(e.default)),await import(`../../_chunks/node/token-DHGH-jVc.js`).then(e=>t(e.default))]);(!n||i(r(n),e?.expirationBufferMs))&&(await a(e),n=(0,g.getVercelOidcTokenSync)())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
7
+ ${e.message}`),t?new _.VercelOidcTokenError(t):e}return e?.audience&&(n=await(0,m.exchangeVercelOidcToken)({token:n,audience:e.audience,jti:e.jti,skipCache:e.skipCache})),n}async function y(){let e=process.env.VERCEL_OIDC_TOKEN_FILE;if(!e)return null;let t=(await(0,p.readFile)(e,`utf8`)).trim();if(!t)throw new _.VercelOidcTokenError(`The Vercel OIDC token file is empty: ${e}`);return t}0&&(r.exports={getVercelOidcToken:v})})),Ft=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`);t.default=(e,t)=>(0,n.createHash)(e).update(t).digest()})),j=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.decoder=e.encoder=void 0,e.concat=r,e.p2s=i,e.uint64be=o,e.uint32be=s,e.lengthAndInput=c,e.concatKdf=l;let t=Ft();e.encoder=new TextEncoder,e.decoder=new TextDecoder;let n=2**32;function r(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function i(t,n){return r(e.encoder.encode(t),new Uint8Array([0]),n)}function a(e,t,r){if(t<0||t>=n)throw RangeError(`value must be >= 0 and <= ${n-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function o(e){let t=Math.floor(e/n),r=e%n,i=new Uint8Array(8);return a(i,t,0),a(i,r,4),i}function s(e){let t=new Uint8Array(4);return a(t,e),t}function c(e){return r(s(e.length),e)}async function l(e,n,r){let i=Math.ceil((n>>3)/32),a=new Uint8Array(i*32);for(let n=0;n<i;n++){let i=new Uint8Array(4+e.length+r.length);i.set(s(n+1)),i.set(e,4),i.set(r,4+e.length),a.set(await(0,t.default)(`sha256`,i),n*32)}return a.slice(0,n>>3)}})),M=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=t.encodeBase64=t.decodeBase64=void 0;let n=e(`node:buffer`),r=j();function i(e){let t=e;return t instanceof Uint8Array&&(t=r.decoder.decode(t)),t}t.encode=e=>n.Buffer.from(e).toString(`base64url`),t.decodeBase64=e=>new Uint8Array(n.Buffer.from(e,`base64`)),t.encodeBase64=e=>n.Buffer.from(e).toString(`base64`),t.decode=e=>new Uint8Array(n.Buffer.from(i(e),`base64url`))})),N=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.JWSSignatureVerificationFailed=e.JWKSTimeout=e.JWKSMultipleMatchingKeys=e.JWKSNoMatchingKey=e.JWKSInvalid=e.JWKInvalid=e.JWTInvalid=e.JWSInvalid=e.JWEInvalid=e.JWEDecryptionFailed=e.JOSENotSupported=e.JOSEAlgNotAllowed=e.JWTExpired=e.JWTClaimValidationFailed=e.JOSEError=void 0;var t=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};e.JOSEError=t,e.JWTClaimValidationFailed=class extends t{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},e.JWTExpired=class extends t{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},e.JOSEAlgNotAllowed=class extends t{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},e.JOSENotSupported=class extends t{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},e.JWEDecryptionFailed=class extends t{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},e.JWEInvalid=class extends t{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},e.JWSInvalid=class extends t{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},e.JWTInvalid=class extends t{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},e.JWKInvalid=class extends t{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},e.JWKSInvalid=class extends t{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},e.JWKSNoMatchingKey=class extends t{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},e.JWKSMultipleMatchingKeys=class extends t{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},e.JWKSTimeout=class extends t{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},e.JWSSignatureVerificationFailed=class extends t{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}}})),It=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=e(`node:crypto`);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.randomFillSync}})})),Lt=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bitLength=r;let t=N(),n=It();function r(e){switch(e){case`A128GCM`:case`A128GCMKW`:case`A192GCM`:case`A192GCMKW`:case`A256GCM`:case`A256GCMKW`:return 96;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return 128;default:throw new t.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}e.default=e=>(0,n.default)(new Uint8Array(r(e)>>3))})),Rt=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=N(),n=Lt();e.default=(e,r)=>{if(r.length<<3!==(0,n.bitLength)(e))throw new t.JWEInvalid(`Invalid Initialization Vector length`)}})),P=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:util`);t.default=e=>n.types.isKeyObject(e)})),zt=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=N(),n=P();e.default=(e,r)=>{let i;switch(e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:i=parseInt(e.slice(-3),10);break;case`A128GCM`:case`A192GCM`:case`A256GCM`:i=parseInt(e.slice(1,4),10);break;default:throw new t.JOSENotSupported(`Content Encryption Algorithm ${e} is not supported either by JOSE or your javascript runtime`)}if(r instanceof Uint8Array){let e=r.byteLength<<3;if(e!==i)throw new t.JWEInvalid(`Invalid Content Encryption Key length. Expected ${i} bits, got ${e} bits`);return}if((0,n.default)(r)&&r.type===`secret`){let e=r.symmetricKeySize<<3;if(e!==i)throw new t.JWEInvalid(`Invalid Content Encryption Key length. Expected ${i} bits, got ${e} bits`);return}throw TypeError(`Invalid Content Encryption Key type`)}})),Bt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=e(`node:crypto`).timingSafeEqual})),Vt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;let n=e(`node:crypto`),r=j();function i(e,t,i,a,o,s){let c=(0,r.concat)(e,t,i,(0,r.uint64be)(e.length<<3)),l=(0,n.createHmac)(`sha${a}`,o);return l.update(c),l.digest().slice(0,s>>3)}})),F=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isCryptoKey=void 0;let n=e(`node:crypto`),r=e(`node:util`);t.default=n.webcrypto,t.isCryptoKey=e=>r.types.isCryptoKey(e)})),I=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkSigCryptoKey=o,e.checkEncCryptoKey=s;function t(e,t=`algorithm.name`){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function n(e,t){return e.name===t}function r(e){return parseInt(e.name.slice(4),10)}function i(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function a(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e=`CryptoKey does not support this operation, its usages must include `;if(t.length>2){let n=t.pop();e+=`one of ${t.join(`, `)}, or ${n}.`}else t.length===2?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw TypeError(e)}}function o(e,o,...s){switch(o){case`HS256`:case`HS384`:case`HS512`:{if(!n(e.algorithm,`HMAC`))throw t(`HMAC`);let i=parseInt(o.slice(2),10);if(r(e.algorithm.hash)!==i)throw t(`SHA-${i}`,`algorithm.hash`);break}case`RS256`:case`RS384`:case`RS512`:{if(!n(e.algorithm,`RSASSA-PKCS1-v1_5`))throw t(`RSASSA-PKCS1-v1_5`);let i=parseInt(o.slice(2),10);if(r(e.algorithm.hash)!==i)throw t(`SHA-${i}`,`algorithm.hash`);break}case`PS256`:case`PS384`:case`PS512`:{if(!n(e.algorithm,`RSA-PSS`))throw t(`RSA-PSS`);let i=parseInt(o.slice(2),10);if(r(e.algorithm.hash)!==i)throw t(`SHA-${i}`,`algorithm.hash`);break}case`EdDSA`:if(e.algorithm.name!==`Ed25519`&&e.algorithm.name!==`Ed448`)throw t(`Ed25519 or Ed448`);break;case`Ed25519`:if(!n(e.algorithm,`Ed25519`))throw t(`Ed25519`);break;case`ES256`:case`ES384`:case`ES512`:{if(!n(e.algorithm,`ECDSA`))throw t(`ECDSA`);let r=i(o);if(e.algorithm.namedCurve!==r)throw t(r,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}a(e,s)}function s(e,i,...o){switch(i){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!n(e.algorithm,`AES-GCM`))throw t(`AES-GCM`);let r=parseInt(i.slice(1,4),10);if(e.algorithm.length!==r)throw t(r,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!n(e.algorithm,`AES-KW`))throw t(`AES-KW`);let r=parseInt(i.slice(1,4),10);if(e.algorithm.length!==r)throw t(r,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:case`X448`:break;default:throw t(`ECDH, X25519, or X448`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!n(e.algorithm,`PBKDF2`))throw t(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:{if(!n(e.algorithm,`RSA-OAEP`))throw t(`RSA-OAEP`);let a=parseInt(i.slice(9),10)||1;if(r(e.algorithm.hash)!==a)throw t(`SHA-${a}`,`algorithm.hash`);break}default:throw TypeError(`CryptoKey does not support this operation`)}a(e,o)}})),L=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.withAlg=n;function t(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}e.default=(e,...n)=>t(`Key must be `,e,...n);function n(e,n,...r){return t(`Key for the ${e} algorithm must be `,n,...r)}})),Ht=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`),r;t.default=e=>(r||=new Set((0,n.getCiphers)()),r.has(e))})),R=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.types=void 0;let t=F(),n=P();e.default=e=>(0,n.default)(e)||(0,t.isCryptoKey)(e);let r=[`KeyObject`];e.types=r,(globalThis.CryptoKey||t.default?.CryptoKey)&&r.push(`CryptoKey`)})),Ut=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`),r=Rt(),i=zt(),a=j(),o=N(),s=Bt(),c=Vt(),l=F(),u=I(),d=P(),f=L(),p=Ht(),m=R();function h(e,t,r,i,l,u){let f=parseInt(e.slice(1,4),10);(0,d.default)(t)&&(t=t.export());let m=t.subarray(f>>3),h=t.subarray(0,f>>3),g=parseInt(e.slice(-3),10),_=`aes-${f}-cbc`;if(!(0,p.default)(_))throw new o.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let v=(0,c.default)(u,i,r,g,h,f),y;try{y=(0,s.default)(l,v)}catch{}if(!y)throw new o.JWEDecryptionFailed;let b;try{let e=(0,n.createDecipheriv)(_,m,i);b=(0,a.concat)(e.update(r),e.final())}catch{}if(!b)throw new o.JWEDecryptionFailed;return b}function g(e,t,r,i,a,s){let c=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,p.default)(c))throw new o.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);try{let e=(0,n.createDecipheriv)(c,t,i,{authTagLength:16});e.setAuthTag(a),s.byteLength&&e.setAAD(s,{plaintextLength:r.length});let o=e.update(r);return e.final(),o}catch{throw new o.JWEDecryptionFailed}}t.default=(e,t,a,s,c,p)=>{let _;if((0,l.isCryptoKey)(t))(0,u.checkEncCryptoKey)(t,e,`decrypt`),_=n.KeyObject.from(t);else if(t instanceof Uint8Array||(0,d.default)(t))_=t;else throw TypeError((0,f.default)(t,...m.types,`Uint8Array`));if(!s)throw new o.JWEInvalid(`JWE Initialization Vector missing`);if(!c)throw new o.JWEInvalid(`JWE Authentication Tag missing`);switch((0,i.default)(e,_),(0,r.default)(e,s),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return h(e,_,a,s,c,p);case`A128GCM`:case`A192GCM`:case`A256GCM`:return g(e,_,a,s,c,p);default:throw new o.JOSENotSupported(`Unsupported JWE Content Encryption Algorithm`)}}})),Wt=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}})),z=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;function t(e){return typeof e==`object`&&!!e}function n(e){if(!t(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let n=e;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}})),Gt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unwrap=t.wrap=void 0;let n=e(`node:buffer`),r=e(`node:crypto`),i=N(),a=j(),o=F(),s=I(),c=P(),l=L(),u=Ht(),d=R();function f(e,t){if(e.symmetricKeySize<<3!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function p(e,t,n){if((0,c.default)(e))return e;if(e instanceof Uint8Array)return(0,r.createSecretKey)(e);if((0,o.isCryptoKey)(e))return(0,s.checkEncCryptoKey)(e,t,n),r.KeyObject.from(e);throw TypeError((0,l.default)(e,...d.types,`Uint8Array`))}t.wrap=(e,t,o)=>{let s=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,u.default)(s))throw new i.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let c=p(t,e,`wrapKey`);f(c,e);let l=(0,r.createCipheriv)(s,c,n.Buffer.alloc(8,166));return(0,a.concat)(l.update(o),l.final())},t.unwrap=(e,t,o)=>{let s=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,u.default)(s))throw new i.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let c=p(t,e,`unwrapKey`);f(c,e);let l=(0,r.createDecipheriv)(s,c,n.Buffer.alloc(8,166));return(0,a.concat)(l.update(o),l.final())}})),Kt=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isJWK=n,e.isPrivateJWK=r,e.isPublicJWK=i,e.isSecretJWK=a;let t=z();function n(e){return(0,t.default)(e)&&typeof e.kty==`string`}function r(e){return e.kty!==`oct`&&typeof e.d==`string`}function i(e){return e.kty!==`oct`&&e.d===void 0}function a(e){return n(e)&&e.kty===`oct`&&typeof e.k==`string`}})),qt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.weakMap=void 0;let n=e(`node:crypto`),r=N(),i=F(),a=P(),o=L(),s=R(),c=Kt();t.weakMap=new WeakMap;let l=e=>{switch(e){case`prime256v1`:return`P-256`;case`secp384r1`:return`P-384`;case`secp521r1`:return`P-521`;case`secp256k1`:return`secp256k1`;default:throw new r.JOSENotSupported(`Unsupported key curve for this operation`)}};t.default=(e,t)=>{let r;if((0,i.isCryptoKey)(e))r=n.KeyObject.from(e);else if((0,a.default)(e))r=e;else if((0,c.isJWK)(e))return e.crv;else throw TypeError((0,o.default)(e,...s.types));if(r.type===`secret`)throw TypeError(`only "private" or "public" type keys can be used for this operation`);switch(r.asymmetricKeyType){case`ed25519`:case`ed448`:return`Ed${r.asymmetricKeyType.slice(2)}`;case`x25519`:case`x448`:return`X${r.asymmetricKeyType.slice(1)}`;case`ec`:{let e=r.asymmetricKeyDetails.namedCurve;return t?e:l(e)}default:throw TypeError(`Invalid asymmetric key type for this operation`)}}})),Jt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ecdhAllowed=void 0,t.deriveKey=p,t.generateEpk=m;let n=e(`node:crypto`),r=e(`node:util`),i=qt(),a=j(),o=N(),s=F(),c=I(),l=P(),u=L(),d=R(),f=(0,r.promisify)(n.generateKeyPair);async function p(e,t,r,i,o=new Uint8Array,f=new Uint8Array){let p;if((0,s.isCryptoKey)(e))(0,c.checkEncCryptoKey)(e,`ECDH`),p=n.KeyObject.from(e);else if((0,l.default)(e))p=e;else throw TypeError((0,u.default)(e,...d.types));let m;if((0,s.isCryptoKey)(t))(0,c.checkEncCryptoKey)(t,`ECDH`,`deriveBits`),m=n.KeyObject.from(t);else if((0,l.default)(t))m=t;else throw TypeError((0,u.default)(t,...d.types));let h=(0,a.concat)((0,a.lengthAndInput)(a.encoder.encode(r)),(0,a.lengthAndInput)(o),(0,a.lengthAndInput)(f),(0,a.uint32be)(i)),g=(0,n.diffieHellman)({privateKey:m,publicKey:p});return(0,a.concatKdf)(g,i,h)}async function m(e){let t;if((0,s.isCryptoKey)(e))t=n.KeyObject.from(e);else if((0,l.default)(e))t=e;else throw TypeError((0,u.default)(e,...d.types));switch(t.asymmetricKeyType){case`x25519`:return f(`x25519`);case`x448`:return f(`x448`);case`ec`:{let e=(0,i.default)(t);return f(`ec`,{namedCurve:e})}default:throw new o.JOSENotSupported(`Invalid or unsupported EPK`)}}t.ecdhAllowed=e=>[`P-256`,`P-384`,`P-521`,`X25519`,`X448`].includes((0,i.default)(e))})),Yt=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;let t=N();function n(e){if(!(e instanceof Uint8Array)||e.length<8)throw new t.JWEInvalid(`PBES2 Salt Input must be 8 or more octets`)}})),Xt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decrypt=t.encrypt=void 0;let n=e(`node:util`),r=e(`node:crypto`),i=It(),a=j(),o=M(),s=Gt(),c=Yt(),l=F(),u=I(),d=P(),f=L(),p=R(),m=(0,n.promisify)(r.pbkdf2);function h(e,t){if((0,d.default)(e))return e.export();if(e instanceof Uint8Array)return e;if((0,l.isCryptoKey)(e))return(0,u.checkEncCryptoKey)(e,t,`deriveBits`,`deriveKey`),r.KeyObject.from(e).export();throw TypeError((0,f.default)(e,...p.types,`Uint8Array`))}t.encrypt=async(e,t,n,r=2048,l=(0,i.default)(new Uint8Array(16)))=>{(0,c.default)(l);let u=(0,a.p2s)(e,l),d=parseInt(e.slice(13,16),10)>>3,f=h(t,e),p=await m(f,u,r,d,`sha${e.slice(8,11)}`);return{encryptedKey:await(0,s.wrap)(e.slice(-6),p,n),p2c:r,p2s:(0,o.encode)(l)}},t.decrypt=async(e,t,n,r,i)=>{(0,c.default)(i);let o=(0,a.p2s)(e,i),l=parseInt(e.slice(13,16),10)>>3,u=h(t,e),d=await m(u,o,r,l,`sha${e.slice(8,11)}`);return(0,s.unwrap)(e.slice(-6),d,n)}})),Zt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`);t.default=(e,t)=>{let r;try{r=e instanceof n.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,`base64url`).byteLength<<3}catch{}if(typeof r!=`number`||r<2048)throw TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}})),Qt=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decrypt=t.encrypt=void 0;let n=e(`node:crypto`),r=e(`node:util`),i=Zt(),a=F(),o=I(),s=P(),c=L(),l=R(),u=(e,t)=>{if(e.asymmetricKeyType!==`rsa`)throw TypeError(`Invalid key for this operation, its asymmetricKeyType must be rsa`);(0,i.default)(e,t)},d=(0,r.deprecate)(()=>n.constants.RSA_PKCS1_PADDING,`The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.`),f=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return n.constants.RSA_PKCS1_OAEP_PADDING;case`RSA1_5`:return d();default:return}},p=e=>{switch(e){case`RSA-OAEP`:return`sha1`;case`RSA-OAEP-256`:return`sha256`;case`RSA-OAEP-384`:return`sha384`;case`RSA-OAEP-512`:return`sha512`;default:return}};function m(e,t,...r){if((0,s.default)(e))return e;if((0,a.isCryptoKey)(e))return(0,o.checkEncCryptoKey)(e,t,...r),n.KeyObject.from(e);throw TypeError((0,c.default)(e,...l.types))}t.encrypt=(e,t,r)=>{let i=f(e),a=p(e),o=m(t,e,`wrapKey`,`encrypt`);return u(o,e),(0,n.publicEncrypt)({key:o,oaepHash:a,padding:i},r)},t.decrypt=(e,t,r)=>{let i=f(e),a=p(e),o=m(t,e,`unwrapKey`,`decrypt`);return u(o,e),(0,n.privateDecrypt)({key:o,oaepHash:a,padding:i},r)}})),$t=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={}})),en=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bitLength=r;let t=N(),n=It();function r(e){switch(e){case`A128GCM`:return 128;case`A192GCM`:return 192;case`A256GCM`:case`A128CBC-HS256`:return 256;case`A192CBC-HS384`:return 384;case`A256CBC-HS512`:return 512;default:throw new t.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}e.default=e=>(0,n.default)(new Uint8Array(r(e)>>3))})),tn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fromX509=t.fromSPKI=t.fromPKCS8=t.toPKCS8=t.toSPKI=void 0;let n=e(`node:crypto`),r=e(`node:buffer`),i=F(),a=P(),o=L(),s=R(),c=(e,t,r)=>{let c;if((0,i.isCryptoKey)(r)){if(!r.extractable)throw TypeError(`CryptoKey is not extractable`);c=n.KeyObject.from(r)}else if((0,a.default)(r))c=r;else throw TypeError((0,o.default)(r,...s.types));if(c.type!==e)throw TypeError(`key is not a ${e} key`);return c.export({format:`pem`,type:t})};t.toSPKI=e=>c(`public`,`spki`,e),t.toPKCS8=e=>c(`private`,`pkcs8`,e),t.fromPKCS8=e=>(0,n.createPrivateKey)({key:r.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,``),`base64`),type:`pkcs8`,format:`der`}),t.fromSPKI=e=>(0,n.createPublicKey)({key:r.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,``),`base64`),type:`spki`,format:`der`}),t.fromX509=e=>(0,n.createPublicKey)({key:e,type:`spki`,format:`pem`})})),nn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`);t.default=e=>e.d?(0,n.createPrivateKey)({format:`jwk`,key:e}):(0,n.createPublicKey)({format:`jwk`,key:e})})),rn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.importSPKI=o,e.importX509=s,e.importPKCS8=c,e.importJWK=l;let t=M(),n=tn(),r=nn(),i=N(),a=z();async function o(e,t,r){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return(0,n.fromSPKI)(e,t,r)}async function s(e,t,r){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return(0,n.fromX509)(e,t,r)}async function c(e,t,r){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return(0,n.fromPKCS8)(e,t,r)}async function l(e,n){if(!(0,a.default)(e))throw TypeError(`JWK must be an object`);switch(n||=e.alg,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return(0,t.decode)(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new i.JOSENotSupported(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);case`EC`:case`OKP`:return(0,r.default)({...e,alg:n});default:throw new i.JOSENotSupported(`Unsupported "kty" (Key Type) Parameter value`)}}})),an=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkKeyTypeWithJwk=void 0;let t=L(),n=R(),r=Kt(),i=e=>e?.[Symbol.toStringTag],a=(e,t,n)=>{if(t.use!==void 0&&t.use!==`sig`)throw TypeError(`Invalid key for this operation, when present its use must be sig`);if(t.key_ops!==void 0&&t.key_ops.includes?.(n)!==!0)throw TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},o=(e,o,s,c)=>{if(!(o instanceof Uint8Array)){if(c&&r.isJWK(o)){if(r.isSecretJWK(o)&&a(e,o,s))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!(0,n.default)(o))throw TypeError((0,t.withAlg)(e,o,...n.types,`Uint8Array`,c?`JSON Web Key`:null));if(o.type!==`secret`)throw TypeError(`${i(o)} instances for symmetric algorithms must be of type "secret"`)}},s=(e,o,s,c)=>{if(c&&r.isJWK(o))switch(s){case`sign`:if(r.isPrivateJWK(o)&&a(e,o,s))return;throw TypeError(`JSON Web Key for this operation be a private JWK`);case`verify`:if(r.isPublicJWK(o)&&a(e,o,s))return;throw TypeError(`JSON Web Key for this operation be a public JWK`)}if(!(0,n.default)(o))throw TypeError((0,t.withAlg)(e,o,...n.types,c?`JSON Web Key`:null));if(o.type===`secret`)throw TypeError(`${i(o)} instances for asymmetric algorithms must not be of type "secret"`);if(s===`sign`&&o.type===`public`)throw TypeError(`${i(o)} instances for asymmetric algorithm signing must be of type "private"`);if(s===`decrypt`&&o.type===`public`)throw TypeError(`${i(o)} instances for asymmetric algorithm decryption must be of type "private"`);if(o.algorithm&&s===`verify`&&o.type===`private`)throw TypeError(`${i(o)} instances for asymmetric algorithm verifying must be of type "public"`);if(o.algorithm&&s===`encrypt`&&o.type===`private`)throw TypeError(`${i(o)} instances for asymmetric algorithm encryption must be of type "public"`)};function c(e,t,n,r){t.startsWith(`HS`)||t===`dir`||t.startsWith(`PBES2`)||/^A\d{3}(?:GCM)?KW$/.test(t)?o(t,n,r,e):s(t,n,r,e)}e.default=c.bind(void 0,!1),e.checkKeyTypeWithJwk=c.bind(void 0,!0)})),on=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`),r=Rt(),i=zt(),a=j(),o=Vt(),s=F(),c=I(),l=P(),u=L(),d=Lt(),f=N(),p=Ht(),m=R();function h(e,t,r,i,s){let c=parseInt(e.slice(1,4),10);(0,l.default)(r)&&(r=r.export());let u=r.subarray(c>>3),d=r.subarray(0,c>>3),m=`aes-${c}-cbc`;if(!(0,p.default)(m))throw new f.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let h=(0,n.createCipheriv)(m,u,i),g=(0,a.concat)(h.update(t),h.final()),_=parseInt(e.slice(-3),10);return{ciphertext:g,tag:(0,o.default)(s,i,g,_,d,c),iv:i}}function g(e,t,r,i,a){let o=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,p.default)(o))throw new f.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let s=(0,n.createCipheriv)(o,r,i,{authTagLength:16});a.byteLength&&s.setAAD(a,{plaintextLength:t.length});let c=s.update(t);return s.final(),{ciphertext:c,tag:s.getAuthTag(),iv:i}}t.default=(e,t,a,o,p)=>{let _;if((0,s.isCryptoKey)(a))(0,c.checkEncCryptoKey)(a,e,`encrypt`),_=n.KeyObject.from(a);else if(a instanceof Uint8Array||(0,l.default)(a))_=a;else throw TypeError((0,u.default)(a,...m.types,`Uint8Array`));switch((0,i.default)(e,_),o?(0,r.default)(e,o):o=(0,d.default)(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return h(e,t,_,o,p);case`A128GCM`:case`A192GCM`:case`A256GCM`:return g(e,t,_,o,p);default:throw new f.JOSENotSupported(`Unsupported JWE Content Encryption Algorithm`)}}})),sn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.wrap=i,e.unwrap=a;let t=on(),n=Ut(),r=M();async function i(e,n,i,a){let o=e.slice(0,7),s=await(0,t.default)(o,i,n,a,new Uint8Array);return{encryptedKey:s.ciphertext,iv:(0,r.encode)(s.iv),tag:(0,r.encode)(s.tag)}}async function a(e,t,r,i,a){let o=e.slice(0,7);return(0,n.default)(o,t,r,i,a,new Uint8Array)}})),cn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Gt(),n=Jt(),r=Xt(),i=Qt(),a=M(),o=$t(),s=N(),c=en(),l=rn(),u=an(),d=z(),f=sn();async function p(e,p,m,h,g){switch((0,u.default)(e,p,`decrypt`),p=await o.default.normalizePrivateKey?.(p,e)||p,e){case`dir`:if(m!==void 0)throw new s.JWEInvalid(`Encountered unexpected JWE Encrypted Key`);return p;case`ECDH-ES`:if(m!==void 0)throw new s.JWEInvalid(`Encountered unexpected JWE Encrypted Key`);case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!(0,d.default)(h.epk))throw new s.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);if(!n.ecdhAllowed(p))throw new s.JOSENotSupported(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let r=await(0,l.importJWK)(h.epk,e),i,o;if(h.apu!==void 0){if(typeof h.apu!=`string`)throw new s.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);try{i=(0,a.decode)(h.apu)}catch{throw new s.JWEInvalid(`Failed to base64url decode the apu`)}}if(h.apv!==void 0){if(typeof h.apv!=`string`)throw new s.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);try{o=(0,a.decode)(h.apv)}catch{throw new s.JWEInvalid(`Failed to base64url decode the apv`)}}let u=await n.deriveKey(r,p,e===`ECDH-ES`?h.enc:e,e===`ECDH-ES`?(0,c.bitLength)(h.enc):parseInt(e.slice(-5,-2),10),i,o);if(e===`ECDH-ES`)return u;if(m===void 0)throw new s.JWEInvalid(`JWE Encrypted Key missing`);return(0,t.unwrap)(e.slice(-6),u,m)}case`RSA1_5`:case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(m===void 0)throw new s.JWEInvalid(`JWE Encrypted Key missing`);return(0,i.decrypt)(e,p,m);case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{if(m===void 0)throw new s.JWEInvalid(`JWE Encrypted Key missing`);if(typeof h.p2c!=`number`)throw new s.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let t=g?.maxPBES2Count||1e4;if(h.p2c>t)throw new s.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof h.p2s!=`string`)throw new s.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let n;try{n=(0,a.decode)(h.p2s)}catch{throw new s.JWEInvalid(`Failed to base64url decode the p2s`)}return(0,r.decrypt)(e,p,m,h.p2c,n)}case`A128KW`:case`A192KW`:case`A256KW`:if(m===void 0)throw new s.JWEInvalid(`JWE Encrypted Key missing`);return(0,t.unwrap)(e,p,m);case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{if(m===void 0)throw new s.JWEInvalid(`JWE Encrypted Key missing`);if(typeof h.iv!=`string`)throw new s.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof h.tag!=`string`)throw new s.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let t;try{t=(0,a.decode)(h.iv)}catch{throw new s.JWEInvalid(`Failed to base64url decode the iv`)}let n;try{n=(0,a.decode)(h.tag)}catch{throw new s.JWEInvalid(`Failed to base64url decode the tag`)}return(0,f.unwrap)(e,p,m,t,n)}default:throw new s.JOSENotSupported(`Invalid or unsupported "alg" (JWE Algorithm) header value`)}}e.default=p})),ln=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=N();function n(e,n,r,i,a){if(a.crit!==void 0&&i?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!i||i.crit===void 0)return new Set;if(!Array.isArray(i.crit)||i.crit.length===0||i.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let o;o=r===void 0?n:new Map([...Object.entries(r),...n.entries()]);for(let n of i.crit){if(!o.has(n))throw new t.JOSENotSupported(`Extension Header Parameter "${n}" is not recognized`);if(a[n]===void 0)throw new e(`Extension Header Parameter "${n}" is missing`);if(o.get(n)&&i[n]===void 0)throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(i.crit)}e.default=n})),un=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}})),dn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.flattenedDecrypt=d;let t=M(),n=Ut(),r=N(),i=Wt(),a=z(),o=cn(),s=j(),c=en(),l=ln(),u=un();async function d(e,d,f){if(!(0,a.default)(e))throw new r.JWEInvalid(`Flattened JWE must be an object`);if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new r.JWEInvalid(`JOSE Header missing`);if(e.iv!==void 0&&typeof e.iv!=`string`)throw new r.JWEInvalid(`JWE Initialization Vector incorrect type`);if(typeof e.ciphertext!=`string`)throw new r.JWEInvalid(`JWE Ciphertext missing or incorrect type`);if(e.tag!==void 0&&typeof e.tag!=`string`)throw new r.JWEInvalid(`JWE Authentication Tag incorrect type`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new r.JWEInvalid(`JWE Protected Header incorrect type`);if(e.encrypted_key!==void 0&&typeof e.encrypted_key!=`string`)throw new r.JWEInvalid(`JWE Encrypted Key incorrect type`);if(e.aad!==void 0&&typeof e.aad!=`string`)throw new r.JWEInvalid(`JWE AAD incorrect type`);if(e.header!==void 0&&!(0,a.default)(e.header))throw new r.JWEInvalid(`JWE Shared Unprotected Header incorrect type`);if(e.unprotected!==void 0&&!(0,a.default)(e.unprotected))throw new r.JWEInvalid(`JWE Per-Recipient Unprotected Header incorrect type`);let p;if(e.protected)try{let n=(0,t.decode)(e.protected);p=JSON.parse(s.decoder.decode(n))}catch{throw new r.JWEInvalid(`JWE Protected Header is invalid`)}if(!(0,i.default)(p,e.header,e.unprotected))throw new r.JWEInvalid(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);let m={...p,...e.header,...e.unprotected};if((0,l.default)(r.JWEInvalid,new Map,f?.crit,p,m),m.zip!==void 0)throw new r.JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);let{alg:h,enc:g}=m;if(typeof h!=`string`||!h)throw new r.JWEInvalid(`missing JWE Algorithm (alg) in JWE Header`);if(typeof g!=`string`||!g)throw new r.JWEInvalid(`missing JWE Encryption Algorithm (enc) in JWE Header`);let _=f&&(0,u.default)(`keyManagementAlgorithms`,f.keyManagementAlgorithms),v=f&&(0,u.default)(`contentEncryptionAlgorithms`,f.contentEncryptionAlgorithms);if(_&&!_.has(h)||!_&&h.startsWith(`PBES2`))throw new r.JOSEAlgNotAllowed(`"alg" (Algorithm) Header Parameter value not allowed`);if(v&&!v.has(g))throw new r.JOSEAlgNotAllowed(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let y;if(e.encrypted_key!==void 0)try{y=(0,t.decode)(e.encrypted_key)}catch{throw new r.JWEInvalid(`Failed to base64url decode the encrypted_key`)}let b=!1;typeof d==`function`&&(d=await d(p,e),b=!0);let x;try{x=await(0,o.default)(h,d,y,m,f)}catch(e){if(e instanceof TypeError||e instanceof r.JWEInvalid||e instanceof r.JOSENotSupported)throw e;x=(0,c.default)(g)}let S,C;if(e.iv!==void 0)try{S=(0,t.decode)(e.iv)}catch{throw new r.JWEInvalid(`Failed to base64url decode the iv`)}if(e.tag!==void 0)try{C=(0,t.decode)(e.tag)}catch{throw new r.JWEInvalid(`Failed to base64url decode the tag`)}let w=s.encoder.encode(e.protected??``),T;T=e.aad===void 0?w:(0,s.concat)(w,s.encoder.encode(`.`),s.encoder.encode(e.aad));let E;try{E=(0,t.decode)(e.ciphertext)}catch{throw new r.JWEInvalid(`Failed to base64url decode the ciphertext`)}let D={plaintext:await(0,n.default)(g,x,E,S,C,T)};if(e.protected!==void 0&&(D.protectedHeader=p),e.aad!==void 0)try{D.additionalAuthenticatedData=(0,t.decode)(e.aad)}catch{throw new r.JWEInvalid(`Failed to base64url decode the aad`)}return e.unprotected!==void 0&&(D.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(D.unprotectedHeader=e.header),b?{...D,key:d}:D}})),fn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.compactDecrypt=i;let t=dn(),n=N(),r=j();async function i(e,i,a){if(e instanceof Uint8Array&&(e=r.decoder.decode(e)),typeof e!=`string`)throw new n.JWEInvalid(`Compact JWE must be a string or Uint8Array`);let{0:o,1:s,2:c,3:l,4:u,length:d}=e.split(`.`);if(d!==5)throw new n.JWEInvalid(`Invalid Compact JWE`);let f=await(0,t.flattenedDecrypt)({ciphertext:l,iv:c||void 0,protected:o,tag:u||void 0,encrypted_key:s||void 0},i,a),p={plaintext:f.plaintext,protectedHeader:f.protectedHeader};return typeof i==`function`?{...p,key:f.key}:p}})),pn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.generalDecrypt=i;let t=dn(),n=N(),r=z();async function i(e,i,a){if(!(0,r.default)(e))throw new n.JWEInvalid(`General JWE must be an object`);if(!Array.isArray(e.recipients)||!e.recipients.every(r.default))throw new n.JWEInvalid(`JWE Recipients missing or incorrect type`);if(!e.recipients.length)throw new n.JWEInvalid(`JWE Recipients has no members`);for(let n of e.recipients)try{return await(0,t.flattenedDecrypt)({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},i,a)}catch{}throw new n.JWEDecryptionFailed}})),mn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.unprotected=void 0,e.unprotected=Symbol()})),hn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`),r=M(),i=N(),a=F(),o=P(),s=L(),c=R();t.default=e=>{let t;if((0,a.isCryptoKey)(e)){if(!e.extractable)throw TypeError(`CryptoKey is not extractable`);t=n.KeyObject.from(e)}else if((0,o.default)(e))t=e;else if(e instanceof Uint8Array)return{kty:`oct`,k:(0,r.encode)(e)};else throw TypeError((0,s.default)(e,...c.types,`Uint8Array`));if(t.type!==`secret`&&![`rsa`,`ec`,`ed25519`,`x25519`,`ed448`,`x448`].includes(t.asymmetricKeyType))throw new i.JOSENotSupported(`Unsupported key asymmetricKeyType`);return t.export({format:`jwk`})}})),gn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.exportSPKI=i,e.exportPKCS8=a,e.exportJWK=o;let t=tn(),n=tn(),r=hn();async function i(e){return(0,t.toSPKI)(e)}async function a(e){return(0,n.toPKCS8)(e)}async function o(e){return(0,r.default)(e)}})),_n=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Gt(),n=Jt(),r=Xt(),i=Qt(),a=M(),o=$t(),s=en(),c=N(),l=gn(),u=an(),d=sn();async function f(e,f,p,m,h={}){let g,_,v;switch((0,u.default)(e,p,`encrypt`),p=await o.default.normalizePublicKey?.(p,e)||p,e){case`dir`:v=p;break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!n.ecdhAllowed(p))throw new c.JOSENotSupported(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let{apu:r,apv:i}=h,{epk:o}=h;o||=(await n.generateEpk(p)).privateKey;let{x:u,y:d,crv:y,kty:b}=await(0,l.exportJWK)(o),x=await n.deriveKey(p,o,e===`ECDH-ES`?f:e,e===`ECDH-ES`?(0,s.bitLength)(f):parseInt(e.slice(-5,-2),10),r,i);if(_={epk:{x:u,crv:y,kty:b}},b===`EC`&&(_.epk.y=d),r&&(_.apu=(0,a.encode)(r)),i&&(_.apv=(0,a.encode)(i)),e===`ECDH-ES`){v=x;break}v=m||(0,s.default)(f);let S=e.slice(-6);g=await(0,t.wrap)(S,x,v);break}case`RSA1_5`:case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:v=m||(0,s.default)(f),g=await(0,i.encrypt)(e,p,v);break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{v=m||(0,s.default)(f);let{p2c:t,p2s:n}=h;({encryptedKey:g,..._}=await(0,r.encrypt)(e,p,v,t,n));break}case`A128KW`:case`A192KW`:case`A256KW`:v=m||(0,s.default)(f),g=await(0,t.wrap)(e,p,v);break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{v=m||(0,s.default)(f);let{iv:t}=h;({encryptedKey:g,..._}=await(0,d.wrap)(e,p,v,t));break}default:throw new c.JOSENotSupported(`Invalid or unsupported "alg" (JWE Algorithm) header value`)}return{cek:v,encryptedKey:g,parameters:_}}e.default=f})),vn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FlattenedEncrypt=void 0;let t=M(),n=mn(),r=on(),i=_n(),a=N(),o=Wt(),s=j(),c=ln();e.FlattenedEncrypt=class{_plaintext;_protectedHeader;_sharedUnprotectedHeader;_unprotectedHeader;_aad;_cek;_iv;_keyManagementParameters;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`plaintext must be an instance of Uint8Array`);this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw TypeError(`setKeyManagementParameters can only be called once`);return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw TypeError(`setProtectedHeader can only be called once`);return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw TypeError(`setSharedUnprotectedHeader can only be called once`);return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError(`setUnprotectedHeader can only be called once`);return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw TypeError(`setContentEncryptionKey can only be called once`);return this._cek=e,this}setInitializationVector(e){if(this._iv)throw TypeError(`setInitializationVector can only be called once`);return this._iv=e,this}async encrypt(e,l){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new a.JWEInvalid(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);if(!(0,o.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new a.JWEInvalid(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let u={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,c.default)(a.JWEInvalid,new Map,l?.crit,this._protectedHeader,u),u.zip!==void 0)throw new a.JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);let{alg:d,enc:f}=u;if(typeof d!=`string`||!d)throw new a.JWEInvalid(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof f!=`string`||!f)throw new a.JWEInvalid(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);let p;if(this._cek&&(d===`dir`||d===`ECDH-ES`))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${d}`);let m;{let t;({cek:m,encryptedKey:p,parameters:t}=await(0,i.default)(d,f,e,this._cek,this._keyManagementParameters)),t&&(l&&n.unprotected in l?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...t}:this.setUnprotectedHeader(t):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...t}:this.setProtectedHeader(t))}let h,g,_;g=this._protectedHeader?s.encoder.encode((0,t.encode)(JSON.stringify(this._protectedHeader))):s.encoder.encode(``),this._aad?(_=(0,t.encode)(this._aad),h=(0,s.concat)(g,s.encoder.encode(`.`),s.encoder.encode(_))):h=g;let{ciphertext:v,tag:y,iv:b}=await(0,r.default)(f,this._plaintext,m,this._iv,h),x={ciphertext:(0,t.encode)(v)};return b&&(x.iv=(0,t.encode)(b)),y&&(x.tag=(0,t.encode)(y)),p&&(x.encrypted_key=(0,t.encode)(p)),_&&(x.aad=_),this._protectedHeader&&(x.protected=s.decoder.decode(g)),this._sharedUnprotectedHeader&&(x.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(x.header=this._unprotectedHeader),x}}})),yn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GeneralEncrypt=void 0;let t=vn(),n=mn(),r=N(),i=en(),a=Wt(),o=_n(),s=M(),c=ln();var l=class{parent;unprotectedHeader;key;options;constructor(e,t,n){this.parent=e,this.key=t,this.options=n}setUnprotectedHeader(e){if(this.unprotectedHeader)throw TypeError(`setUnprotectedHeader can only be called once`);return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}};e.GeneralEncrypt=class{_plaintext;_recipients=[];_protectedHeader;_unprotectedHeader;_aad;constructor(e){this._plaintext=e}addRecipient(e,t){let n=new l(this,e,{crit:t?.crit});return this._recipients.push(n),n}setProtectedHeader(e){if(this._protectedHeader)throw TypeError(`setProtectedHeader can only be called once`);return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError(`setSharedUnprotectedHeader can only be called once`);return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(){if(!this._recipients.length)throw new r.JWEInvalid(`at least one recipient must be added`);if(this._recipients.length===1){let[e]=this._recipients,n=await new t.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(e.unprotectedHeader).encrypt(e.key,{...e.options}),r={ciphertext:n.ciphertext,iv:n.iv,recipients:[{}],tag:n.tag};return n.aad&&(r.aad=n.aad),n.protected&&(r.protected=n.protected),n.unprotected&&(r.unprotected=n.unprotected),n.encrypted_key&&(r.recipients[0].encrypted_key=n.encrypted_key),n.header&&(r.recipients[0].header=n.header),r}let e;for(let t=0;t<this._recipients.length;t++){let n=this._recipients[t];if(!(0,a.default)(this._protectedHeader,this._unprotectedHeader,n.unprotectedHeader))throw new r.JWEInvalid(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let i={...this._protectedHeader,...this._unprotectedHeader,...n.unprotectedHeader},{alg:o}=i;if(typeof o!=`string`||!o)throw new r.JWEInvalid(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(o===`dir`||o===`ECDH-ES`)throw new r.JWEInvalid(`"dir" and "ECDH-ES" alg may only be used with a single recipient`);if(typeof i.enc!=`string`||!i.enc)throw new r.JWEInvalid(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);if(!e)e=i.enc;else if(e!==i.enc)throw new r.JWEInvalid(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`);if((0,c.default)(r.JWEInvalid,new Map,n.options.crit,this._protectedHeader,i),i.zip!==void 0)throw new r.JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`)}let l=(0,i.default)(e),u={ciphertext:``,iv:``,recipients:[],tag:``};for(let r=0;r<this._recipients.length;r++){let i=this._recipients[r],a={};u.recipients.push(a);let c={...this._protectedHeader,...this._unprotectedHeader,...i.unprotectedHeader}.alg.startsWith(`PBES2`)?2048+r:void 0;if(r===0){let e=await new t.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(l).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(i.unprotectedHeader).setKeyManagementParameters({p2c:c}).encrypt(i.key,{...i.options,[n.unprotected]:!0});u.ciphertext=e.ciphertext,u.iv=e.iv,u.tag=e.tag,e.aad&&(u.aad=e.aad),e.protected&&(u.protected=e.protected),e.unprotected&&(u.unprotected=e.unprotected),a.encrypted_key=e.encrypted_key,e.header&&(a.header=e.header);continue}let{encryptedKey:d,parameters:f}=await(0,o.default)(i.unprotectedHeader?.alg||this._protectedHeader?.alg||this._unprotectedHeader?.alg,e,i.key,l,{p2c:c});a.encrypted_key=(0,s.encode)(d),(i.unprotectedHeader||f)&&(a.header={...i.unprotectedHeader,...f})}return u}}})),bn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;let t=N();function n(e){switch(e){case`PS256`:case`RS256`:case`ES256`:case`ES256K`:return`sha256`;case`PS384`:case`RS384`:case`ES384`:return`sha384`;case`PS512`:case`RS512`:case`ES512`:return`sha512`;case`Ed25519`:case`EdDSA`:return;default:throw new t.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}})),xn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=s;let n=e(`node:crypto`),r=qt(),i=N(),a=Zt(),o=new Map([[`ES256`,`P-256`],[`ES256K`,`secp256k1`],[`ES384`,`P-384`],[`ES512`,`P-521`]]);function s(e,t){let s,c,l;if(t instanceof n.KeyObject)s=t.asymmetricKeyType,c=t.asymmetricKeyDetails;else switch(l=!0,t.kty){case`RSA`:s=`rsa`;break;case`EC`:s=`ec`;break;case`OKP`:if(t.crv===`Ed25519`){s=`ed25519`;break}if(t.crv===`Ed448`){s=`ed448`;break}throw TypeError(`Invalid key for this operation, its crv must be Ed25519 or Ed448`);default:throw TypeError(`Invalid key for this operation, its kty must be RSA, OKP, or EC`)}let u;switch(e){case`Ed25519`:if(s!==`ed25519`)throw TypeError(`Invalid key for this operation, its asymmetricKeyType must be ed25519`);break;case`EdDSA`:if(![`ed25519`,`ed448`].includes(s))throw TypeError(`Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448`);break;case`RS256`:case`RS384`:case`RS512`:if(s!==`rsa`)throw TypeError(`Invalid key for this operation, its asymmetricKeyType must be rsa`);(0,a.default)(t,e);break;case`PS256`:case`PS384`:case`PS512`:if(s===`rsa-pss`){let{hashAlgorithm:t,mgf1HashAlgorithm:n,saltLength:r}=c,i=parseInt(e.slice(-3),10);if(t!==void 0&&(t!==`sha${i}`||n!==t))throw TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(r!==void 0&&r>i>>3)throw TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(s!==`rsa`)throw TypeError(`Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss`);(0,a.default)(t,e),u={padding:n.constants.RSA_PKCS1_PSS_PADDING,saltLength:n.constants.RSA_PSS_SALTLEN_DIGEST};break;case`ES256`:case`ES256K`:case`ES384`:case`ES512`:{if(s!==`ec`)throw TypeError(`Invalid key for this operation, its asymmetricKeyType must be ec`);let n=(0,r.default)(t),i=o.get(e);if(n!==i)throw TypeError(`Invalid key curve for the algorithm, its curve must be ${i}, got ${n}`);u={dsaEncoding:`ieee-p1363`};break}default:throw new i.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return l?{format:`jwk`,key:t,...u}:u?{...u,key:t}:t}})),Sn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;let t=N();function n(e){switch(e){case`HS256`:return`sha256`;case`HS384`:return`sha384`;case`HS512`:return`sha512`;default:throw new t.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}})),Cn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;let n=e(`node:crypto`),r=F(),i=I(),a=L(),o=R(),s=Kt();function c(e,t,c){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError((0,a.default)(t,...o.types));return(0,n.createSecretKey)(t)}if(t instanceof n.KeyObject)return t;if((0,r.isCryptoKey)(t))return(0,i.checkSigCryptoKey)(t,e,c),n.KeyObject.from(t);if(s.isJWK(t))return e.startsWith(`HS`)?(0,n.createSecretKey)(Buffer.from(t.k,`base64url`)):t;throw TypeError((0,a.default)(t,...o.types,`Uint8Array`,`JSON Web Key`))}})),wn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`),r=e(`node:util`),i=bn(),a=Sn(),o=xn(),s=Cn(),c=(0,r.promisify)(n.sign);t.default=async(e,t,r)=>{let l=(0,s.default)(e,t,`sign`);if(e.startsWith(`HS`)){let t=n.createHmac((0,a.default)(e),l);return t.update(r),t.digest()}return c((0,i.default)(e),r,(0,o.default)(e,l))}})),Tn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:crypto`),r=e(`node:util`),i=bn(),a=xn(),o=wn(),s=Cn(),c=(0,r.promisify)(n.verify);t.default=async(e,t,r,l)=>{let u=(0,s.default)(e,t,`verify`);if(e.startsWith(`HS`)){let t=await(0,o.default)(e,u,l),i=r;try{return n.timingSafeEqual(i,t)}catch{return!1}}let d=(0,i.default)(e),f=(0,a.default)(e,u);try{return await c(d,l,f,r)}catch{return!1}}})),En=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.flattenedVerify=f;let t=M(),n=Tn(),r=N(),i=j(),a=Wt(),o=z(),s=an(),c=ln(),l=un(),u=Kt(),d=rn();async function f(e,f,p){if(!(0,o.default)(e))throw new r.JWSInvalid(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new r.JWSInvalid(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new r.JWSInvalid(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new r.JWSInvalid(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new r.JWSInvalid(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!(0,o.default)(e.header))throw new r.JWSInvalid(`JWS Unprotected Header incorrect type`);let m={};if(e.protected)try{let n=(0,t.decode)(e.protected);m=JSON.parse(i.decoder.decode(n))}catch{throw new r.JWSInvalid(`JWS Protected Header is invalid`)}if(!(0,a.default)(m,e.header))throw new r.JWSInvalid(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let h={...m,...e.header},g=(0,c.default)(r.JWSInvalid,new Map([[`b64`,!0]]),p?.crit,m,h),_=!0;if(g.has(`b64`)&&(_=m.b64,typeof _!=`boolean`))throw new r.JWSInvalid(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:v}=h;if(typeof v!=`string`||!v)throw new r.JWSInvalid(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let y=p&&(0,l.default)(`algorithms`,p.algorithms);if(y&&!y.has(v))throw new r.JOSEAlgNotAllowed(`"alg" (Algorithm) Header Parameter value not allowed`);if(_){if(typeof e.payload!=`string`)throw new r.JWSInvalid(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new r.JWSInvalid(`JWS Payload must be a string or an Uint8Array instance`);let b=!1;typeof f==`function`?(f=await f(m,e),b=!0,(0,s.checkKeyTypeWithJwk)(v,f,`verify`),(0,u.isJWK)(f)&&(f=await(0,d.importJWK)(f,v))):(0,s.checkKeyTypeWithJwk)(v,f,`verify`);let x=(0,i.concat)(i.encoder.encode(e.protected??``),i.encoder.encode(`.`),typeof e.payload==`string`?i.encoder.encode(e.payload):e.payload),S;try{S=(0,t.decode)(e.signature)}catch{throw new r.JWSInvalid(`Failed to base64url decode the signature`)}if(!await(0,n.default)(v,f,S,x))throw new r.JWSSignatureVerificationFailed;let C;if(_)try{C=(0,t.decode)(e.payload)}catch{throw new r.JWSInvalid(`Failed to base64url decode the payload`)}else C=typeof e.payload==`string`?i.encoder.encode(e.payload):e.payload;let w={payload:C};return e.protected!==void 0&&(w.protectedHeader=m),e.header!==void 0&&(w.unprotectedHeader=e.header),b?{...w,key:f}:w}})),Dn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.compactVerify=i;let t=En(),n=N(),r=j();async function i(e,i,a){if(e instanceof Uint8Array&&(e=r.decoder.decode(e)),typeof e!=`string`)throw new n.JWSInvalid(`Compact JWS must be a string or Uint8Array`);let{0:o,1:s,2:c,length:l}=e.split(`.`);if(l!==3)throw new n.JWSInvalid(`Invalid Compact JWS`);let u=await(0,t.flattenedVerify)({payload:s,protected:o,signature:c},i,a),d={payload:u.payload,protectedHeader:u.protectedHeader};return typeof i==`function`?{...d,key:u.key}:d}})),On=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.generalVerify=i;let t=En(),n=N(),r=z();async function i(e,i,a){if(!(0,r.default)(e))throw new n.JWSInvalid(`General JWS must be an object`);if(!Array.isArray(e.signatures)||!e.signatures.every(r.default))throw new n.JWSInvalid(`JWS Signatures missing or incorrect type`);for(let n of e.signatures)try{return await(0,t.flattenedVerify)({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},i,a)}catch{}throw new n.JWSSignatureVerificationFailed}})),kn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=e=>Math.floor(e.getTime()/1e3)})),An=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;e.default=e=>{let n=t.exec(e);if(!n||n[4]&&n[1])throw TypeError(`Invalid time period format`);let r=parseFloat(n[2]),i=n[3].toLowerCase(),a;switch(i){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:a=Math.round(r);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:a=Math.round(r*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:a=Math.round(r*3600);break;case`day`:case`days`:case`d`:a=Math.round(r*86400);break;case`week`:case`weeks`:case`w`:a=Math.round(r*604800);break;default:a=Math.round(r*31557600)}return n[1]===`-`||n[4]===`ago`?-a:a}})),jn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=N(),n=j(),r=kn(),i=An(),a=z(),o=e=>e.toLowerCase().replace(/^application\//,``),s=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;e.default=(e,c,l={})=>{let u;try{u=JSON.parse(n.decoder.decode(c))}catch{}if(!(0,a.default)(u))throw new t.JWTInvalid(`JWT Claims Set must be a top-level JSON object`);let{typ:d}=l;if(d&&(typeof e.typ!=`string`||o(e.typ)!==o(d)))throw new t.JWTClaimValidationFailed(`unexpected "typ" JWT header value`,u,`typ`,`check_failed`);let{requiredClaims:f=[],issuer:p,subject:m,audience:h,maxTokenAge:g}=l,_=[...f];g!==void 0&&_.push(`iat`),h!==void 0&&_.push(`aud`),m!==void 0&&_.push(`sub`),p!==void 0&&_.push(`iss`);for(let e of new Set(_.reverse()))if(!(e in u))throw new t.JWTClaimValidationFailed(`missing required "${e}" claim`,u,e,`missing`);if(p&&!(Array.isArray(p)?p:[p]).includes(u.iss))throw new t.JWTClaimValidationFailed(`unexpected "iss" claim value`,u,`iss`,`check_failed`);if(m&&u.sub!==m)throw new t.JWTClaimValidationFailed(`unexpected "sub" claim value`,u,`sub`,`check_failed`);if(h&&!s(u.aud,typeof h==`string`?[h]:h))throw new t.JWTClaimValidationFailed(`unexpected "aud" claim value`,u,`aud`,`check_failed`);let v;switch(typeof l.clockTolerance){case`string`:v=(0,i.default)(l.clockTolerance);break;case`number`:v=l.clockTolerance;break;case`undefined`:v=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:y}=l,b=(0,r.default)(y||new Date);if((u.iat!==void 0||g)&&typeof u.iat!=`number`)throw new t.JWTClaimValidationFailed(`"iat" claim must be a number`,u,`iat`,`invalid`);if(u.nbf!==void 0){if(typeof u.nbf!=`number`)throw new t.JWTClaimValidationFailed(`"nbf" claim must be a number`,u,`nbf`,`invalid`);if(u.nbf>b+v)throw new t.JWTClaimValidationFailed(`"nbf" claim timestamp check failed`,u,`nbf`,`check_failed`)}if(u.exp!==void 0){if(typeof u.exp!=`number`)throw new t.JWTClaimValidationFailed(`"exp" claim must be a number`,u,`exp`,`invalid`);if(u.exp<=b-v)throw new t.JWTExpired(`"exp" claim timestamp check failed`,u,`exp`,`check_failed`)}if(g){let e=b-u.iat,n=typeof g==`number`?g:(0,i.default)(g);if(e-v>n)throw new t.JWTExpired(`"iat" claim timestamp check failed (too far in the past)`,u,`iat`,`check_failed`);if(e<0-v)throw new t.JWTClaimValidationFailed(`"iat" claim timestamp check failed (it should be in the past)`,u,`iat`,`check_failed`)}return u}})),Mn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.jwtVerify=i;let t=Dn(),n=jn(),r=N();async function i(e,i,a){let o=await(0,t.compactVerify)(e,i,a);if(o.protectedHeader.crit?.includes(`b64`)&&o.protectedHeader.b64===!1)throw new r.JWTInvalid(`JWTs MUST NOT use unencoded payload`);let s={payload:(0,n.default)(o.protectedHeader,o.payload,a),protectedHeader:o.protectedHeader};return typeof i==`function`?{...s,key:o.key}:s}})),Nn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.jwtDecrypt=i;let t=fn(),n=jn(),r=N();async function i(e,i,a){let o=await(0,t.compactDecrypt)(e,i,a),s=(0,n.default)(o.protectedHeader,o.plaintext,a),{protectedHeader:c}=o;if(c.iss!==void 0&&c.iss!==s.iss)throw new r.JWTClaimValidationFailed(`replicated "iss" claim header parameter mismatch`,s,`iss`,`mismatch`);if(c.sub!==void 0&&c.sub!==s.sub)throw new r.JWTClaimValidationFailed(`replicated "sub" claim header parameter mismatch`,s,`sub`,`mismatch`);if(c.aud!==void 0&&JSON.stringify(c.aud)!==JSON.stringify(s.aud))throw new r.JWTClaimValidationFailed(`replicated "aud" claim header parameter mismatch`,s,`aud`,`mismatch`);let l={payload:s,protectedHeader:c};return typeof i==`function`?{...l,key:o.key}:l}})),Pn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CompactEncrypt=void 0;let t=vn();e.CompactEncrypt=class{_flattened;constructor(e){this._flattened=new t.FlattenedEncrypt(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,t){let n=await this._flattened.encrypt(e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(`.`)}}})),Fn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FlattenedSign=void 0;let t=M(),n=wn(),r=Wt(),i=N(),a=j(),o=an(),s=ln();e.FlattenedSign=class{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw TypeError(`setProtectedHeader can only be called once`);return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError(`setUnprotectedHeader can only be called once`);return this._unprotectedHeader=e,this}async sign(e,c){if(!this._protectedHeader&&!this._unprotectedHeader)throw new i.JWSInvalid(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!(0,r.default)(this._protectedHeader,this._unprotectedHeader))throw new i.JWSInvalid(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...this._protectedHeader,...this._unprotectedHeader},u=(0,s.default)(i.JWSInvalid,new Map([[`b64`,!0]]),c?.crit,this._protectedHeader,l),d=!0;if(u.has(`b64`)&&(d=this._protectedHeader.b64,typeof d!=`boolean`))throw new i.JWSInvalid(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:f}=l;if(typeof f!=`string`||!f)throw new i.JWSInvalid(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);(0,o.checkKeyTypeWithJwk)(f,e,`sign`);let p=this._payload;d&&(p=a.encoder.encode((0,t.encode)(p)));let m;m=this._protectedHeader?a.encoder.encode((0,t.encode)(JSON.stringify(this._protectedHeader))):a.encoder.encode(``);let h=(0,a.concat)(m,a.encoder.encode(`.`),p),g=await(0,n.default)(f,e,h),_={signature:(0,t.encode)(g),payload:``};return d&&(_.payload=a.decoder.decode(p)),this._unprotectedHeader&&(_.header=this._unprotectedHeader),this._protectedHeader&&(_.protected=a.decoder.decode(m)),_}}})),In=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CompactSign=void 0;let t=Fn();e.CompactSign=class{_flattened;constructor(e){this._flattened=new t.FlattenedSign(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let n=await this._flattened.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}}})),Ln=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GeneralSign=void 0;let t=Fn(),n=N();var r=class{parent;protectedHeader;unprotectedHeader;options;key;constructor(e,t,n){this.parent=e,this.key=t,this.options=n}setProtectedHeader(e){if(this.protectedHeader)throw TypeError(`setProtectedHeader can only be called once`);return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw TypeError(`setUnprotectedHeader can only be called once`);return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}};e.GeneralSign=class{_payload;_signatures=[];constructor(e){this._payload=e}addSignature(e,t){let n=new r(this,e,t);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new n.JWSInvalid(`at least one signature must be added`);let e={signatures:[],payload:``};for(let r=0;r<this._signatures.length;r++){let i=this._signatures[r],a=new t.FlattenedSign(this._payload);a.setProtectedHeader(i.protectedHeader),a.setUnprotectedHeader(i.unprotectedHeader);let{payload:o,...s}=await a.sign(i.key,i.options);if(r===0)e.payload=o;else if(e.payload!==o)throw new n.JWSInvalid(`inconsistent use of JWS Unencoded Payload (RFC7797)`);e.signatures.push(s)}return e}}})),Rn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProduceJWT=void 0;let t=kn(),n=z(),r=An();function i(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}e.ProduceJWT=class{_payload;constructor(e={}){if(!(0,n.default)(e))throw TypeError(`JWT Claims Set MUST be an object`);this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return this._payload=typeof e==`number`?{...this._payload,nbf:i(`setNotBefore`,e)}:e instanceof Date?{...this._payload,nbf:i(`setNotBefore`,(0,t.default)(e))}:{...this._payload,nbf:(0,t.default)(new Date)+(0,r.default)(e)},this}setExpirationTime(e){return this._payload=typeof e==`number`?{...this._payload,exp:i(`setExpirationTime`,e)}:e instanceof Date?{...this._payload,exp:i(`setExpirationTime`,(0,t.default)(e))}:{...this._payload,exp:(0,t.default)(new Date)+(0,r.default)(e)},this}setIssuedAt(e){return this._payload=e===void 0?{...this._payload,iat:(0,t.default)(new Date)}:e instanceof Date?{...this._payload,iat:i(`setIssuedAt`,(0,t.default)(e))}:typeof e==`string`?{...this._payload,iat:i(`setIssuedAt`,(0,t.default)(new Date)+(0,r.default)(e))}:{...this._payload,iat:i(`setIssuedAt`,e)},this}}})),zn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SignJWT=void 0;let t=In(),n=N(),r=j(),i=Rn();e.SignJWT=class extends i.ProduceJWT{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,i){let a=new t.CompactSign(r.encoder.encode(JSON.stringify(this._payload)));if(a.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes(`b64`)&&this._protectedHeader.b64===!1)throw new n.JWTInvalid(`JWTs MUST NOT use unencoded payload`);return a.sign(e,i)}}})),Bn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.EncryptJWT=void 0;let t=Pn(),n=j(),r=Rn();e.EncryptJWT=class extends r.ProduceJWT{_cek;_iv;_keyManagementParameters;_protectedHeader;_replicateIssuerAsHeader;_replicateSubjectAsHeader;_replicateAudienceAsHeader;setProtectedHeader(e){if(this._protectedHeader)throw TypeError(`setProtectedHeader can only be called once`);return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw TypeError(`setKeyManagementParameters can only be called once`);return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw TypeError(`setContentEncryptionKey can only be called once`);return this._cek=e,this}setInitializationVector(e){if(this._iv)throw TypeError(`setInitializationVector can only be called once`);return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,r){let i=new t.CompactEncrypt(n.encoder.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),i.setProtectedHeader(this._protectedHeader),this._iv&&i.setInitializationVector(this._iv),this._cek&&i.setContentEncryptionKey(this._cek),this._keyManagementParameters&&i.setKeyManagementParameters(this._keyManagementParameters),i.encrypt(e,r)}}})),Vn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calculateJwkThumbprint=s,e.calculateJwkThumbprintUri=c;let t=Ft(),n=M(),r=N(),i=j(),a=z(),o=(e,t)=>{if(typeof e!=`string`||!e)throw new r.JWKInvalid(`${t} missing or invalid`)};async function s(e,s){if(!(0,a.default)(e))throw TypeError(`JWK must be an object`);if(s??=`sha256`,s!==`sha256`&&s!==`sha384`&&s!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let c;switch(e.kty){case`EC`:o(e.crv,`"crv" (Curve) Parameter`),o(e.x,`"x" (X Coordinate) Parameter`),o(e.y,`"y" (Y Coordinate) Parameter`),c={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case`OKP`:o(e.crv,`"crv" (Subtype of Key Pair) Parameter`),o(e.x,`"x" (Public Key) Parameter`),c={crv:e.crv,kty:e.kty,x:e.x};break;case`RSA`:o(e.e,`"e" (Exponent) Parameter`),o(e.n,`"n" (Modulus) Parameter`),c={e:e.e,kty:e.kty,n:e.n};break;case`oct`:o(e.k,`"k" (Key Value) Parameter`),c={k:e.k,kty:e.kty};break;default:throw new r.JOSENotSupported(`"kty" (Key Type) Parameter missing or unsupported`)}let l=i.encoder.encode(JSON.stringify(c));return(0,n.encode)(await(0,t.default)(s,l))}async function c(e,t){t??=`sha256`;let n=await s(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}})),Hn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.EmbeddedJWK=i;let t=rn(),n=z(),r=N();async function i(e,i){let a={...e,...i?.header};if(!(0,n.default)(a.jwk))throw new r.JWSInvalid(`"jwk" (JSON Web Key) Header Parameter must be a JSON object`);let o=await(0,t.importJWK)({...a.jwk,ext:!0},a.alg);if(o instanceof Uint8Array||o.type!==`public`)throw new r.JWSInvalid(`"jwk" (JSON Web Key) Header Parameter must be a public key`);return o}})),Un=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createLocalJWKSet=u;let t=rn(),n=N(),r=z();function i(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;default:throw new n.JOSENotSupported(`Unsupported "alg" value for a JSON Web Key Set`)}}function a(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(o)}function o(e){return(0,r.default)(e)}function s(e){return typeof structuredClone==`function`?structuredClone(e):JSON.parse(JSON.stringify(e))}var c=class{_jwks;_cached=new WeakMap;constructor(e){if(!a(e))throw new n.JWKSInvalid(`JSON Web Key Set malformed`);this._jwks=s(e)}async getKey(e,t){let{alg:r,kid:a}={...e,...t?.header},o=i(r),s=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&typeof a==`string`&&(t=a===e.kid),t&&typeof e.alg==`string`&&(t=r===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(r){case`ES256`:t=e.crv===`P-256`;break;case`ES256K`:t=e.crv===`secp256k1`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:t=e.crv===`Ed25519`;break;case`EdDSA`:t=e.crv===`Ed25519`||e.crv===`Ed448`}return t}),{0:c,length:u}=s;if(u===0)throw new n.JWKSNoMatchingKey;if(u!==1){let e=new n.JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(let e of s)try{yield await l(t,e,r)}catch{}},e}return l(this._cached,c,r)}};async function l(e,r,i){let a=e.get(r)||e.set(r,{}).get(r);if(a[i]===void 0){let e=await(0,t.importJWK)({...r,ext:!0},i);if(e instanceof Uint8Array||e.type!==`public`)throw new n.JWKSInvalid(`JSON Web Key Set members must be public keys`);a[i]=e}return a[i]}function u(e){let t=new c(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>s(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),n}})),Wn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:http`),r=e(`node:https`),i=e(`node:events`),a=N(),o=j();t.default=async(e,t,s)=>{let c;switch(e.protocol){case`https:`:c=r.get;break;case`http:`:c=n.get;break;default:throw TypeError(`Unsupported URL protocol.`)}let{agent:l,headers:u}=s,d=c(e.href,{agent:l,timeout:t,headers:u}),[f]=await Promise.race([(0,i.once)(d,`response`),(0,i.once)(d,`timeout`)]);if(!f)throw d.destroy(),new a.JWKSTimeout;if(f.statusCode!==200)throw new a.JOSEError(`Expected 200 OK from the JSON Web Key Set HTTP response`);let p=[];for await(let e of f)p.push(e);try{return JSON.parse(o.decoder.decode((0,o.concat)(...p)))}catch{throw new a.JOSEError(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}})),Gn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.experimental_jwksCache=e.jwksCache=void 0,e.createRemoteJWKSet=l;let t=Wn(),n=N(),r=Un(),i=z();function a(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let o;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(o=`jose/v5.10.0`),e.jwksCache=Symbol();function s(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!(0,i.default)(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,i.default))}var c=class{_url;_timeoutDuration;_cooldownDuration;_cacheMaxAge;_jwksTimestamp;_pendingFetch;_options;_local;_cache;constructor(t,n){if(!(t instanceof URL))throw TypeError(`url must be an instance of URL`);this._url=new URL(t.href),this._options={agent:n?.agent,headers:n?.headers},this._timeoutDuration=typeof n?.timeoutDuration==`number`?n?.timeoutDuration:5e3,this._cooldownDuration=typeof n?.cooldownDuration==`number`?n?.cooldownDuration:3e4,this._cacheMaxAge=typeof n?.cacheMaxAge==`number`?n?.cacheMaxAge:6e5,n?.[e.jwksCache]!==void 0&&(this._cache=n?.[e.jwksCache],s(n?.[e.jwksCache],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=(0,r.createLocalJWKSet)(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp==`number`&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return typeof this._jwksTimestamp==`number`&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof n.JWKSNoMatchingKey&&this.coolingDown()===!1)return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&a()&&(this._pendingFetch=void 0);let e=new Headers(this._options.headers);o&&!e.has(`User-Agent`)&&(e.set(`User-Agent`,o),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||=(0,t.default)(this._url,this._timeoutDuration,this._options).then(e=>{this._local=(0,r.createLocalJWKSet)(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e}),await this._pendingFetch}};function l(e,t){let n=new c(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!n._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>n._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}e.experimental_jwksCache=e.jwksCache})),Kn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.UnsecuredJWT=void 0;let t=M(),n=j(),r=N(),i=jn(),a=Rn();e.UnsecuredJWT=class extends a.ProduceJWT{encode(){return`${t.encode(JSON.stringify({alg:`none`}))}.${t.encode(JSON.stringify(this._payload))}.`}static decode(e,a){if(typeof e!=`string`)throw new r.JWTInvalid(`Unsecured JWT must be a string`);let{0:o,1:s,2:c,length:l}=e.split(`.`);if(l!==3||c!==``)throw new r.JWTInvalid(`Invalid Unsecured JWT`);let u;try{if(u=JSON.parse(n.decoder.decode(t.decode(o))),u.alg!==`none`)throw Error()}catch{throw new r.JWTInvalid(`Invalid Unsecured JWT`)}return{payload:(0,i.default)(u,t.decode(s),a),header:u}}}})),qn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.decode=e.encode=void 0;let t=M();e.encode=t.encode,e.decode=t.decode})),Jn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.decodeProtectedHeader=i;let t=qn(),n=j(),r=z();function i(e){let i;if(typeof e==`string`){let t=e.split(`.`);(t.length===3||t.length===5)&&([i]=t)}else if(typeof e==`object`&&e){if(`protected`in e)i=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}try{if(typeof i!=`string`||!i)throw Error();let e=JSON.parse(n.decoder.decode((0,t.decode)(i)));if(!(0,r.default)(e))throw Error();return e}catch{throw TypeError(`Invalid Token or Protected Header formatting`)}}})),Yn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.decodeJwt=a;let t=qn(),n=j(),r=z(),i=N();function a(e){if(typeof e!=`string`)throw new i.JWTInvalid(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:a,length:o}=e.split(`.`);if(o===5)throw new i.JWTInvalid(`Only JWTs using Compact JWS serialization can be decoded`);if(o!==3)throw new i.JWTInvalid(`Invalid JWT`);if(!a)throw new i.JWTInvalid(`JWTs must contain a payload`);let s;try{s=(0,t.decode)(a)}catch{throw new i.JWTInvalid(`Failed to base64url decode the payload`)}let c;try{c=JSON.parse(n.decoder.decode(s))}catch{throw new i.JWTInvalid(`Failed to parse the decoded payload as JSON`)}if(!(0,r.default)(c))throw new i.JWTInvalid(`Invalid JWT Claims Set`);return c}})),Xn=n((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateSecret=s,t.generateKeyPair=c;let n=e(`node:crypto`),r=e(`node:util`),i=It(),a=N(),o=(0,r.promisify)(n.generateKeyPair);async function s(e,t){let r;switch(e){case`HS256`:case`HS384`:case`HS512`:case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:r=parseInt(e.slice(-3),10);break;case`A128KW`:case`A192KW`:case`A256KW`:case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:case`A128GCM`:case`A192GCM`:case`A256GCM`:r=parseInt(e.slice(1,4),10);break;default:throw new a.JOSENotSupported(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return(0,n.createSecretKey)((0,i.default)(new Uint8Array(r>>3)))}async function c(e,t){switch(e){case`RS256`:case`RS384`:case`RS512`:case`PS256`:case`PS384`:case`PS512`:case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:case`RSA1_5`:{let e=t?.modulusLength??2048;if(typeof e!=`number`||e<2048)throw new a.JOSENotSupported(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return await o(`rsa`,{modulusLength:e,publicExponent:65537})}case`ES256`:return o(`ec`,{namedCurve:`P-256`});case`ES256K`:return o(`ec`,{namedCurve:`secp256k1`});case`ES384`:return o(`ec`,{namedCurve:`P-384`});case`ES512`:return o(`ec`,{namedCurve:`P-521`});case`Ed25519`:return o(`ed25519`);case`EdDSA`:switch(t?.crv){case void 0:case`Ed25519`:return o(`ed25519`);case`Ed448`:return o(`ed448`);default:throw new a.JOSENotSupported(`Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448`)}case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{let e=t?.crv??`P-256`;switch(e){case void 0:case`P-256`:case`P-384`:case`P-521`:return o(`ec`,{namedCurve:e});case`X25519`:return o(`x25519`);case`X448`:return o(`x448`);default:throw new a.JOSENotSupported(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448`)}}default:throw new a.JOSENotSupported(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}}})),Zn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.generateKeyPair=n;let t=Xn();async function n(e,n){return(0,t.generateKeyPair)(e,n)}})),Qn=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.generateSecret=n;let t=Xn();async function n(e,n){return(0,t.generateSecret)(e,n)}})),$n=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=`node:crypto`})),er=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=$n().default})),tr=n((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.cryptoRuntime=e.base64url=e.generateSecret=e.generateKeyPair=e.errors=e.decodeJwt=e.decodeProtectedHeader=e.importJWK=e.importX509=e.importPKCS8=e.importSPKI=e.exportJWK=e.exportSPKI=e.exportPKCS8=e.UnsecuredJWT=e.experimental_jwksCache=e.jwksCache=e.createRemoteJWKSet=e.createLocalJWKSet=e.EmbeddedJWK=e.calculateJwkThumbprintUri=e.calculateJwkThumbprint=e.EncryptJWT=e.SignJWT=e.GeneralSign=e.FlattenedSign=e.CompactSign=e.FlattenedEncrypt=e.CompactEncrypt=e.jwtDecrypt=e.jwtVerify=e.generalVerify=e.flattenedVerify=e.compactVerify=e.GeneralEncrypt=e.generalDecrypt=e.flattenedDecrypt=e.compactDecrypt=void 0;var t=fn();Object.defineProperty(e,"compactDecrypt",{enumerable:!0,get:function(){return t.compactDecrypt}});var n=dn();Object.defineProperty(e,"flattenedDecrypt",{enumerable:!0,get:function(){return n.flattenedDecrypt}});var r=pn();Object.defineProperty(e,"generalDecrypt",{enumerable:!0,get:function(){return r.generalDecrypt}});var i=yn();Object.defineProperty(e,"GeneralEncrypt",{enumerable:!0,get:function(){return i.GeneralEncrypt}});var a=Dn();Object.defineProperty(e,"compactVerify",{enumerable:!0,get:function(){return a.compactVerify}});var o=En();Object.defineProperty(e,"flattenedVerify",{enumerable:!0,get:function(){return o.flattenedVerify}});var s=On();Object.defineProperty(e,"generalVerify",{enumerable:!0,get:function(){return s.generalVerify}});var c=Mn();Object.defineProperty(e,"jwtVerify",{enumerable:!0,get:function(){return c.jwtVerify}});var l=Nn();Object.defineProperty(e,"jwtDecrypt",{enumerable:!0,get:function(){return l.jwtDecrypt}});var u=Pn();Object.defineProperty(e,"CompactEncrypt",{enumerable:!0,get:function(){return u.CompactEncrypt}});var d=vn();Object.defineProperty(e,"FlattenedEncrypt",{enumerable:!0,get:function(){return d.FlattenedEncrypt}});var f=In();Object.defineProperty(e,"CompactSign",{enumerable:!0,get:function(){return f.CompactSign}});var p=Fn();Object.defineProperty(e,"FlattenedSign",{enumerable:!0,get:function(){return p.FlattenedSign}});var m=Ln();Object.defineProperty(e,"GeneralSign",{enumerable:!0,get:function(){return m.GeneralSign}});var h=zn();Object.defineProperty(e,"SignJWT",{enumerable:!0,get:function(){return h.SignJWT}});var g=Bn();Object.defineProperty(e,"EncryptJWT",{enumerable:!0,get:function(){return g.EncryptJWT}});var _=Vn();Object.defineProperty(e,"calculateJwkThumbprint",{enumerable:!0,get:function(){return _.calculateJwkThumbprint}}),Object.defineProperty(e,"calculateJwkThumbprintUri",{enumerable:!0,get:function(){return _.calculateJwkThumbprintUri}});var v=Hn();Object.defineProperty(e,"EmbeddedJWK",{enumerable:!0,get:function(){return v.EmbeddedJWK}});var y=Un();Object.defineProperty(e,"createLocalJWKSet",{enumerable:!0,get:function(){return y.createLocalJWKSet}});var b=Gn();Object.defineProperty(e,"createRemoteJWKSet",{enumerable:!0,get:function(){return b.createRemoteJWKSet}}),Object.defineProperty(e,"jwksCache",{enumerable:!0,get:function(){return b.jwksCache}}),Object.defineProperty(e,"experimental_jwksCache",{enumerable:!0,get:function(){return b.experimental_jwksCache}});var x=Kn();Object.defineProperty(e,"UnsecuredJWT",{enumerable:!0,get:function(){return x.UnsecuredJWT}});var S=gn();Object.defineProperty(e,"exportPKCS8",{enumerable:!0,get:function(){return S.exportPKCS8}}),Object.defineProperty(e,"exportSPKI",{enumerable:!0,get:function(){return S.exportSPKI}}),Object.defineProperty(e,"exportJWK",{enumerable:!0,get:function(){return S.exportJWK}});var C=rn();Object.defineProperty(e,"importSPKI",{enumerable:!0,get:function(){return C.importSPKI}}),Object.defineProperty(e,"importPKCS8",{enumerable:!0,get:function(){return C.importPKCS8}}),Object.defineProperty(e,"importX509",{enumerable:!0,get:function(){return C.importX509}}),Object.defineProperty(e,"importJWK",{enumerable:!0,get:function(){return C.importJWK}});var w=Jn();Object.defineProperty(e,"decodeProtectedHeader",{enumerable:!0,get:function(){return w.decodeProtectedHeader}});var T=Yn();Object.defineProperty(e,"decodeJwt",{enumerable:!0,get:function(){return T.decodeJwt}}),e.errors=N();var E=Zn();Object.defineProperty(e,"generateKeyPair",{enumerable:!0,get:function(){return E.generateKeyPair}});var D=Qn();Object.defineProperty(e,"generateSecret",{enumerable:!0,get:function(){return D.generateSecret}}),e.base64url=qn();var ee=er();Object.defineProperty(e,"cryptoRuntime",{enumerable:!0,get:function(){return ee.default}})})),nr=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{verifyVercelOidcToken:()=>h}),t.exports=c(l);var u=tr();let d=`https://oidc.vercel.com`,f=new URL(`https://oidc.vercel.com/.well-known/jwks`),p=[`RS256`],m=(0,u.createRemoteJWKSet)(f);async function h(e,t){let{algorithms:n,projectId:r=process.env.VERCEL_PROJECT_ID,environment:i=process.env.VERCEL_TARGET_ENV||process.env.VERCEL_ENV,ownerId:a,...o}=t??{};if(r===`*`&&a===void 0&&!g(o.audience))throw TypeError(`Expected ownerId or audience to be provided when projectId is '*'.`);let s=await(0,u.jwtVerify)(e,m,{...o,algorithms:n??p});return _(s.payload.iss),v({actual:s.payload.project_id,claim:`project_id`,env:`VERCEL_PROJECT_ID`,expected:r,option:`projectId`}),v({actual:s.payload.environment,claim:`environment`,env:`VERCEL_TARGET_ENV or VERCEL_ENV`,expected:i,option:`environment`}),y({actual:s.payload.owner_id,claim:`owner_id`,expected:a}),s}function g(e){return Array.isArray(e)?e.length>0:e!==void 0}function _(e){if(e!==d&&(typeof e!=`string`||!e.startsWith(`${d}/`)))throw TypeError(`Expected Vercel OIDC token iss claim to be "${d}" or to start with "${d}/".`)}function v({actual:e,claim:t,env:n,expected:r,option:i}){if(r!==`*`){if(r===void 0||r.length===0)throw TypeError(`Expected ${n} to be set or ${i} to be provided. Pass ${i}: '*' to allow any ${t} claim.`);if(!(Array.isArray(r)&&typeof e==`string`&&r.includes(e))&&e!==r)throw TypeError(Array.isArray(r)?`Expected Vercel OIDC token ${t} claim to be one of: ${r.map(e=>`"${e}"`).join(`, `)}.`:`Expected Vercel OIDC token ${t} claim to be "${r}".`)}}function y({actual:e,claim:t,expected:n}){if(n!==void 0&&e!==n)throw TypeError(`Expected Vercel OIDC token ${t} claim to be "${n}".`)}0&&(t.exports={verifyVercelOidcToken:h})})),rr=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>g.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>g.RefreshAccessTokenFailedError,exchangeVercelOidcToken:()=>_.exchangeVercelOidcToken,getContext:()=>m.getContext,getVercelOidcToken:()=>f.getVercelOidcToken,getVercelOidcTokenSync:()=>p.getVercelOidcTokenSync,getVercelToken:()=>v.getVercelToken,verifyVercelOidcToken:()=>h.verifyVercelOidcToken}),t.exports=c(l);var f=Pt(),p=Nt(),m=Mt(),h=nr(),g=u(),_=jt(),v=d();0&&(t.exports={AccessTokenMissingError,RefreshAccessTokenFailedError,exchangeVercelOidcToken,getContext,getVercelOidcToken,getVercelOidcTokenSync,getVercelToken,verifyVercelOidcToken})})),ir=t(kt(),1),ar=rr();function or(e){return 400*2**e}function sr(e,t){return new Promise((n,r)=>{if(t?.aborted)return r(t.reason);let i=()=>{clearTimeout(a),r(t.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}const cr=new WeakSet;function lr(e){return typeof e==`object`&&!!e&&cr.has(e)}async function ur(e,t=!1){try{return{bytesWritten:(await O(Re,e)).json.bytesWritten}}catch(e){throw t&&typeof e==`object`&&e&&cr.add(e),e}}async function dr(e){let t=await e.text(),n;try{let e=JSON.parse(t)?.error?.bytesWritten;Number.isSafeInteger(e)&&e>=0&&(n=e)}catch{}return{bytesWritten:n,response:new Response(t,{status:e.status,statusText:e.statusText,headers:e.headers})}}function fr(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var B=class extends se{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=fr(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,ar.getVercelOidcToken)({expirationBufferMs:3e5,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=fr(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){await this.ensureValidToken();let n=await Et(),r=n?` agent/${n}`:``;return super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${c}${r} (Node.js/${process.version}; ${b.platform()}/${b.arch()})`,...t?.headers}})}async getSession(e){let t=A(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,O(Pe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=A(e),n=e.runtime===void 0?`/v3/sandboxes`:`/v2/sandboxes`;return O(nt,await this.request(n,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?St(e.networkPolicy):void 0,networkId:e.networkId,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async forkSandbox(e){let t=A(e);return O(nt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?St(e.networkPolicy):void 0,networkId:e.networkId,env:e.env,mounts:e.mounts,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,attachStdin:e.attachStdin||void 0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal,retry:{retries:0}});if(t.ok||await O(y.any(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new E(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new E(t,{message:`No response body`,sessionId:e.sessionId});let n=mr(t.body,e.signal),r;try{let t=await n.next();if(t.done)throw new D(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);r=Le.parse(t.value).command}catch(e){throw await n.return(),e}let i={stdout:0,stderr:0},a=(async()=>{try{for(;;){let t=await n.next();if(t.done)throw new pr(`Stream ended before command finished`);if(t.value?.command)return ze.parse(t.value).command;let r=Ge.parse(t.value);if(r.stream===`error`)throw new D(r.data.code,r.data.message,e.sessionId);e.onLog?.(r),i[r.stream]+=r.data.length}}catch(t){if(e.signal?.aborted||!(t instanceof pr))throw t;if(e.logs)for await(let t of this.getLogsStream({sessionId:e.sessionId,cmdId:r.id,signal:e.signal},i))e.onLog?.(t);return(await this.getCommand({sessionId:e.sessionId,cmdId:r.id,wait:!0,signal:e.signal})).json.command}finally{await n.return()}})();return{command:r,finished:a}}return O(Le,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,attachStdin:e.attachStdin||void 0,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,n,r=await ne(async()=>{let r=await this.request(t,{signal:e.signal,query:e.wait?{wait:`true`}:void 0,retry:{retries:0}});return n=r.ok?await r.text():void 0,r})(t,{signal:e.signal,retry:{retries:2}});return e.wait?O(ze,r,n):O(Le,r,n)}async openInteractive(e){return O(Fe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return O(Be,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new yt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await bt(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return O(Ie,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return O(Ke,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return O(Je,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return O(Qe,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getDrive(e){return O($e,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`GET`,query:{projectId:e.projectId},signal:e.signal}))}async getOrCreateDrive(e){return O($e,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,region:e.region,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async forkDrive(e){return O($e,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.forkName}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:xt({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await O(Be,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new E(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:f.fromWeb(t.body)}async killCommand(e){return O(Le,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}async writeCommandStdin(e){let t=t=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/stdin`,{method:`POST`,body:JSON.stringify(t),signal:e.abortSignal,retry:{retries:0}}),n={data:e.data?.length?Buffer.from(e.data).toString(`base64`):void 0,offset:e.offset,close:e.close||void 0},r=e.offset!==void 0||!e.data?.length&&!e.close,i=!1,a=0,o=e.offset??0;for(let s=0;;s++){let c=s<5,l;try{l=await t(n)}catch(t){if(!r||!c||e.abortSignal?.aborted||t?.name===`AbortError`)throw t;i=!0,await sr(or(s),e.abortSignal);continue}let u=l.status;if(u===404&&i&&e.close&&!e.data?.length)return await l.body?.cancel(),{};if(u===429&&c){let t=Number(l.headers.get(`Retry-After`));if(!(t>20)){await l.body?.cancel(),await sr(t>0?t*1e3:or(s),e.abortSignal);continue}}if(r&&c&&(u===502||u===503)){i=!0,await l.body?.cancel(),await sr(or(s),e.abortSignal);continue}if(r&&c&&u===504){i=!0;let e=await dr(l),t=e.bytesWritten;if(t!==void 0&&t>o)o=t,a=0;else if(++a>=2)return ur(e.response,i);continue}return ur(l,i)}}getLogs(e){let t=new AbortController,n=e.signal?gr(e.signal,t.signal):t.signal,r=this.getLogsStream({...e,signal:n});return Object.assign(r,{[Symbol.dispose](){t.abort(`Disposed`)},close:()=>t.abort(`Disposed`)})}async*getLogsStream(e,t={stdout:0,stderr:0}){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`;for(let r=0;;r++){let i=await this.request(n,{signal:e.signal});if(i.ok||await O(y.any(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new E(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new E(i,{message:`No response body`,sessionId:e.sessionId});let a={...t};try{for await(let n of mr(i.body,e.signal)){let r=Ge.parse(n);if(r.stream===`error`)throw new D(r.data.code,r.data.message,e.sessionId);let i=Math.min(a[r.stream],r.data.length);a[r.stream]-=i;let o=r.data.slice(i);(o.length>0||r.data.length===0)&&(t[r.stream]+=o.length,yield{...r,data:o})}return}catch(t){if(e.signal?.aborted||!(t instanceof pr)||r>=2)throw t;await x(200*2**r,void 0,{signal:e.signal})}}}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return O(tt,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return O(Ne,await this.request(t,{method:`POST`,body:JSON.stringify(St(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return O(Ne,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return O(Ye,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return O(Xe,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return O(Xe,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=A(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),O(nt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return O(rt,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:_r(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return O($e,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return O(it,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,timeout:e.timeout,networkPolicy:e.networkPolicy?St(e.networkPolicy):void 0,networkId:e.networkId,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,mounts:e.mounts}),signal:e.signal}))}async deleteSandbox(e){return O(it,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId,deleteOrphanSnapshots:e.deleteOrphanSnapshots?`true`:void 0},signal:e.signal}))}},pr=class extends Error{};async function*mr(e,t){let n=new AbortController,r=!1,i=ir.parse({emitInvalidLines:!0});i.on(`invalid-line`,e=>{i.destroy(r?new pr(`Stream ended with an incomplete JSON record`,{cause:e}):e)});let a=hr(e,i,{signal:t?gr(t,n.signal):n.signal,onEnd:()=>{r=!0}});try{for await(let e of i)yield e}finally{n.abort(),await a}}async function hr(e,t,n){let r=e.getReader(),i=new S(`utf8`),a=!1,o=n?.signal,s=()=>{a=!0;let e=o?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};o&&(o.aborted?s():o.addEventListener(`abort`,s,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(i.write(Buffer.from(e.value))),e.done){a||t.write(i.end());break}}}catch(e){a||(`destroy`in t&&typeof t.destroy==`function`?t.destroy(new pr(`Stream connection was interrupted`,{cause:e})):t.emit(`error`,e))}finally{o?.removeEventListener(`abort`,s),r.releaseLock(),a||(n?.onEnd?.(),t.end())}}function gr(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function _r(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0){if(t.length>1)throw Error("Filtering by multiple tags is not supported. Pass a single `{ key: value }` tag.");return t.map(([e,t])=>`${e}:${t}`)}}function vr(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var V=t(n(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c}))(),1);const yr={warn:V.default.yellow,error:V.default.red,success:V.default.green,info:V.default.blue},br=V.default.dim(`[vercel/sandbox]`);function xr(e,t){t=Array.isArray(t)?t.join(`
8
+ `):t;let n=t.replace(/^/gm,`${br} `);console.error(yr[e](n))}function Sr(e){return V.default.italic(V.default.dim("`")+e+V.default.dim("`"))}var Cr=t(a(),1);async function wr(){return await import(`../../_chunks/node/auth-v5pS3mLo.js`)}function Tr(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const Er=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,Dr(t).catch(t=>{throw e=null,t})]);let n=await e[1];return xr(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function Dr(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await wr(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await Or({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${V.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
9
+ `));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&xr(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function Or(e,t){xr(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${V.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();xr(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${V.default.italic(r.verification_uri)} and type ${V.default.bold(r.user_code)}`,` Press ${V.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${V.default.bold(`help:`)} Link your project with ${Sr(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
10
+ `);i=Error(e),a.return()},(0,Cr.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw xr(`error`,`${V.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return xr(`success`,`${V.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var kr=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
11
+ `);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Ar=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
12
+ `);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function jr(e){try{return Pr(await(0,ar.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!Tr())throw process.env.VERCEL_URL?new Ar(t):new kr(t);return await Er(e)}}async function H(e){return Mr(e??{})||await jr({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Mr(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Nr=y.object({exp:y.number().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:y.number().optional().describe(`Issued at timestamp`),owner_id:y.string(),project_id:y.string()});function Pr(e){try{let t=Nr.parse(vr(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Fr={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Ir(e){if(typeof e==`number`)return e;if(e in Fr)return Fr[e];throw Error(`Unknown signal name: ${String(e)}`)}function Lr(e,t,n){let r=!1,i,a,o=new Promise((e,t)=>{i=e,a=t});o.catch(()=>{});let s=new p({highWaterMark:524288,writev(t,n){e.writeStdin(Buffer.concat(t.map(({chunk:e})=>e))).then(()=>n(),n)},final(t){e.closeStdin().then(()=>t(),t)}}),c=()=>!r&&(r=!0,t.unpipe(s),t.off(`error`,u),t.off(`close`,d),n?.removeEventListener(`abort`,f),t.pause(),s.destroy(),!0),l=e=>{c()&&(e===void 0?i():a(e))},u=t=>{c()&&e.closeStdin().catch(()=>{}).finally(()=>a(t))},d=()=>{t.readableEnded||u(Error(`The stdin stream closed before it ended`))},f=()=>l();return s.on(`finish`,()=>l()),s.on(`error`,e=>l(zr(e)?void 0:e)),n?.aborted?l():(n?.addEventListener(`abort`,f,{once:!0}),t.on(`error`,u),t.on(`close`,d),t.destroyed&&!t.readableEnded?d():t.pipe(s)),{done:o,stop:()=>l()}}async function Rr(e,t,n){return t?(e.then(()=>t.stop(),()=>{n?.signal?.aborted||t.stop()}),Promise.race([e,t.done.then(()=>e,e=>{throw n?.onPipeError?.(),e})])):e}function zr(e){if(!(e instanceof E))return!1;let t=e.json?.error?.code;return e.response.status===404||e.response.status===400&&t===`command_stdin_unavailable`}const Br=524288;var U=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await H();return this._client=new B({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this.stdinQueue=Promise.resolve(),this.stdinError=null,this.stdinOffset=null,this.stdinPipe=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[r](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=this.stdinPipe,r=await Rr(t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal}),n,{signal:e?.signal,onPipeError:()=>{this.stdinPipe===n&&(this.stdinPipe=null)}});return new Ur({client:t,sessionId:this.sessionId,cmd:r.json.command,exitCode:r.json.command.exitCode,durationMs:r.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Ir(e??`SIGTERM`),abortSignal:t?.abortSignal})}async writeStdin(e,t){"use step";let n=typeof e==`string`?new TextEncoder().encode(e):e;n.length!==0&&await this.enqueueStdin(async e=>{if(this.stdinError)throw Error(`Stdin is in an unknown state after an earlier write failed. Close stdin or kill the command.`,{cause:this.stdinError});await this.resolveStdinOffset(e,t?.abortSignal);let r=0;try{for(let i=0;i<n.length;i+=Br){let a=n.subarray(i,i+Br),{bytesWritten:o}=await e.writeCommandStdin({sessionId:this.sessionId,commandId:this.cmd.id,data:a,offset:this.stdinOffset??0,abortSignal:t?.abortSignal});this.stdinOffset=o??(this.stdinOffset??0)+a.length,r++}}catch(e){throw(r>0||!Vr(e))&&(this.stdinError=e,this.stdinOffset=null),e}},t?.abortSignal)}async closeStdin(e){"use step";await this.enqueueStdin(async t=>{await this.resolveStdinOffset(t,e?.abortSignal),await t.writeCommandStdin({sessionId:this.sessionId,commandId:this.cmd.id,offset:this.stdinOffset??0,close:!0,abortSignal:e?.abortSignal})},e?.abortSignal)}async resolveStdinOffset(e,t){if(this.stdinOffset!==null)return;let{bytesWritten:n}=await e.writeCommandStdin({sessionId:this.sessionId,commandId:this.cmd.id,abortSignal:t});if(n===void 0)throw Error(`The API did not report the bytes written to stdin.`);this.stdinOffset=n}enqueueStdin(e,t){let n=this.stdinQueue,r=(async()=>(await Hr(n,t),e(await this.ensureClient())))();return this.stdinQueue=Promise.allSettled([n,r]).then(()=>{}),r}};U.prototype.writeStdin.maxRetries=0,U.prototype.closeStdin.maxRetries=0;function Vr(e){return e instanceof E&&e.response.status>=400&&e.response.status<500&&!lr(e)}function Hr(e,t){return t?(t.throwIfAborted(),new Promise((n,r)=>{let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,i),n()})})):e}var Ur=class e extends U{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[r](e){return{...U[r](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}async writeStdin(e,t){throw Error(`Cannot write to stdin: the command has already finished.`)}async closeStdin(e){throw Error(`Cannot close stdin: the command has already finished.`)}};function Wr(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Gr(i);let t=e;for(yield t;t.pagination.next!==null;)Gr(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Gr(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Gr(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var Kr=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await H();return this._client=new B({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get regions(){return this.snapshot.regions??[this.snapshot.region]}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[r](e){return{snapshot:e.snapshot}}static[i](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await H(e),n=new B({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return Wr(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await H(e),n=new B({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return Wr(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await H(t),r=new B({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function qr(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?Ct(t):void 0}}function Jr(e,t,n){let r=Lr(e,t,n),i=r.done.catch(t=>{throw e.kill().catch(()=>{}),t});return i.catch(()=>{}),{done:i,stop:r.stop}}var Yr=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await H();return this._client=new B({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[r](e){return{session:e.session,routes:e.routes}}static[i](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=qr(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new U({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr),s=typeof i.stdin==`object`&&i.stdin!==null?i.stdin:null,c=!!i.stdin||void 0;if(i.stdin===!0&&a)throw TypeError("`stdin: true` requires `detached: true`, otherwise the command would wait for input that can never be written");if(a){let e=``,t=``,n=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,attachStdin:c,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal}),a=new U({client:r,sessionId:this.session.id,cmd:n.command}),o=Rr(n.finished,s&&Jr(a,s,i.signal));i.onStart&&(o.catch(()=>{}),await i.onStart(a));let l=await o;return new Ur({client:r,sessionId:this.session.id,cmd:l,exitCode:l.exitCode??0,durationMs:l.durationMs,output:{stdout:e,stderr:t}})}let l=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,attachStdin:c,timeout:i.timeoutMs,signal:i.signal}),u=new U({client:r,sessionId:this.session.id,cmd:l.json.command});return s&&(u.stdinPipe=Lr(u,s,i.signal)),o&&(async()=>{try{for await(let e of u.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),u}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:bt(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=_(t.cwd??``,t.path);return n?.mkdirRecursive&&await w(g(e),{recursive:!0}),await C(i,v(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=qr(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=qr((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=qr((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=qr(n.json.session),new Kr({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:Xr,S_IFREG:Zr,S_IFDIR:Qr,S_IFLNK:$r,S_IFBLK:ei,S_IFCHR:ti,S_IFIFO:ni,S_IFSOCK:ri}=T;function W(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function ii(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var ai=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&Xr)===Zr}isDirectory(){return(this.mode&Xr)===Qr}isBlockDevice(){return(this.mode&Xr)===ei}isCharacterDevice(){return(this.mode&Xr)===ti}isSymbolicLink(){return(this.mode&Xr)===$r}isFIFO(){return(this.mode&Xr)===ni}isSocket(){return(this.mode&Xr)===ri}},oi=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function si(e){let t=e.trim().split(`|`);return new ai(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function ci(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw W(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new oi(r,ui[i]??1,t)}const li=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,ui={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var di=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=ii(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw W(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw W(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`scandir`,e):W(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
13
+ `).filter(Boolean).map(t=>ci(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`scandir`,e):W(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
14
+ `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,li,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`stat`,e):W(`EACCES`,t.trim(),`stat`,e)}return si(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,li,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`lstat`,e):W(`EACCES`,t.trim(),`lstat`,e)}return si(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`unlink`,e):W(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`rm`,e):W(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?W(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):W(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`rename`,e):W(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`copyfile`,e):W(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw W(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`chmod`,e):W(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`chown`,e):W(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?W(`EEXIST`,`file already exists`,`symlink`,t):W(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`readlink`,e):W(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`realpath`,e):W(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?W(`ENOENT`,`no such file or directory`,`truncate`,e):W(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw W(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const fi=/^[a-z_][a-z0-9_-]*$/;function G(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!fi.test(e))throw Error(`Invalid ${t} "${e}": must match ${fi} (lowercase letters, digits, hyphens, underscores)`)}var pi=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},mi=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,onStart:r.onStart,stdin:r.stdin,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:f.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=_(t.cwd??``,t.path);return n?.mkdirRecursive&&await w(g(i),{recursive:!0}),await C(r,v(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){G(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){G(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function hi(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{drive:`mode`in t?t.drive:t.name,mode:`mode`in t?t.mode:`read-write`}]))}function gi(e){return e instanceof E&&e.response.status===410}function _i(e){return e instanceof E&&e.response.status===404}function vi(e){return e instanceof E&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function yi(e){return e instanceof E&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function bi(e){return e instanceof E&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var xi=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await H();return this._client=new B({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region??`iad1`}get failoverRegions(){return this.sandbox.failoverRegions??[]}get networkId(){return this.sandbox.networkId}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get mounts(){return this.sandbox.mounts}get networkPolicy(){return this.sandbox.networkPolicy?Ct(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await H(e),n=new B({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return Wr(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[r](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[i](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new Yr({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";if(e?.runtime!==void 0&&e.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");let t=await H(e),n=new B({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=A(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,networkId:e?.networkId,env:e?.env,tags:e?.tags,mounts:hi(e?.mounts),snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,region:e?.region,failoverRegions:e?.failoverRegions,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new Si({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await H(e),n=new B({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=A(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,networkId:e.networkId,env:e.env,mounts:hi(e.mounts),tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,persistent:e.persistent,signal:e.signal,...r});return new Si({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await H(t),r=new B({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=A(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(t?.runtime!==void 0&&t.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(_i(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(vi(n)){let n=await H(t),r=new B({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=A(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!_i(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new Yr({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new di(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new Yr({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(gi(n)||yi(n)||bi(n))return await this.resume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
15
+ `);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){G(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new pi(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new mi({sandbox:this,username:e})}asUser(e){return G(e,`username`),new mi({sandbox:this,username:e})}async createGroup(e,t){G(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){G(e,`username`),G(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){G(e,`username`),G(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;if(e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048}),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!gi(e)&&!yi(e))throw e}}e.networkPolicy!==void 0&&this.session&&this.session.status!==`stopped`&&this.session.status!==`stopping`&&this.session.status!==`aborted`&&this.session.status!==`failed`&&await this.session.update({networkPolicy:e.networkPolicy},t);let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,networkId:e.networkId,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,mounts:hi(e.mounts),signal:t?.signal});this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes)}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,deleteOrphanSnapshots:e?.deleteOrphanSnapshots,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return Wr(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return Wr(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},Si=class extends xi{async[Symbol.asyncDispose](){await this.stop()}},Ci=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await H();return this._client=new B({teamId:e.teamId,token:e.token}),this._client}get driveId(){return this.drive.id}get parentDriveId(){return this.drive.parentDriveId}get rootDriveId(){return this.drive.rootDriveId}get name(){return this.drive.name}get projectId(){return this._projectId}get region(){return this.drive.region??`iad1`}get maxSize(){return this.drive.maxSizeBytes}get currentSessionId(){return this.drive.currentSessionId}get currentSandboxName(){return this.drive.currentSandboxName}get createdAt(){return new Date(this.drive.createdAt)}get updatedAt(){return new Date(this.drive.updatedAt)}snapshot(){return{drive:this.name,mode:`snapshot`}}static[r](e){return{drive:e.drive,projectId:e._projectId}}static[i](t){return new e({drive:t.drive,projectId:t.projectId})}constructor({client:e,drive:t,projectId:n}){this._client=null,this._client=e??null,this.drive=t,this._projectId=n??t.projectId}static async list(t){"use step";let n=await H(t),r=new B({teamId:n.teamId,token:n.token,fetch:t?.fetch}),i=async i=>{let a=await r.listDrives({...n,...t,...i!==void 0&&{cursor:i}});return{...a.json,drives:a.json.drives.map(t=>new e({client:r,drive:t,projectId:n.projectId}))}};return Wr(await i(t?.cursor),{itemsKey:`drives`,fetchNext:i,signal:t?.signal})}static async get(t){"use step";let n=await H(t),r=new B({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getDrive({projectId:n.projectId,name:t.name,signal:t.signal})).json.drive,projectId:n.projectId})}static async getOrCreate(t){"use step";let n=await H(t),r=new B({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getOrCreateDrive({projectId:n.projectId,name:t.name,region:t.region,maxSizeBytes:t.maxSize,signal:t.signal})).json.drive,projectId:n.projectId})}async fork(t){"use step";let n=await this.ensureClient();return new e({client:n,drive:(await n.forkDrive({projectId:this._projectId,name:this.drive.name,forkName:t.name,signal:t.signal})).json.drive,projectId:this._projectId})}async delete(e){"use step";this.drive=(await(await this.ensureClient()).deleteDrive({projectId:this._projectId,name:this.drive.name,signal:e?.signal})).json.drive}};const wi=new TextEncoder,Ti=new TextDecoder;function Ei(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Di(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Oi(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ki(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:Ti.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=Ti.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Oi(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}const K=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),Ai=(e,t)=>e.name===t;function ji(e){return parseInt(e.name.slice(4),10)}function Mi(e,t){if(ji(e.hash)!==t)throw K(`SHA-${t}`,`algorithm.hash`)}function Ni(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function Pi(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Fi(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!Ai(e.algorithm,`HMAC`))throw K(`HMAC`);Mi(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!Ai(e.algorithm,`RSASSA-PKCS1-v1_5`))throw K(`RSASSA-PKCS1-v1_5`);Mi(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!Ai(e.algorithm,`RSA-PSS`))throw K(`RSA-PSS`);Mi(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!Ai(e.algorithm,`Ed25519`))throw K(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!Ai(e.algorithm,t))throw K(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!Ai(e.algorithm,`ECDSA`))throw K(`ECDSA`);let n=Ni(t);if(e.algorithm.namedCurve!==n)throw K(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}Pi(e,n)}function Ii(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const Li=(e,...t)=>Ii(`Key must be `,e,...t),Ri=(e,t,...n)=>Ii(`Key for the ${e} algorithm must be `,t,...n);var q=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},J=class extends q{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},zi=class extends q{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Bi=class extends q{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},Y=class extends q{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},X=class extends q{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Z=class extends q{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Vi=class extends q{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},Hi=class extends q{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Ui=class extends q{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},Wi=class extends q{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Gi=class extends q{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};const Ki=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},qi=e=>e?.[Symbol.toStringTag]===`KeyObject`,Ji=e=>Ki(e)||qi(e);function Yi(e,t,n){try{return ki(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const Xi=e=>typeof e==`object`&&!!e;function Q(e){if(!Xi(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Zi(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const Qi=e=>Q(e)&&typeof e.kty==`string`,$i=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),ea=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,ta=e=>e.kty===`oct`&&typeof e.k==`string`;function na(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function ra(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new Y(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function ia(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(Li(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return Fi(t,e,n),t}async function aa(e,t,n,r){let i=await ia(e,t,`verify`);na(e,i);let a=ra(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const oa=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function sa(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new Y(oa)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new Y(oa)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new Y(oa)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new Y(oa)}break;default:throw new Y(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function ca(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=sa(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const la=`given KeyObject instance cannot be used for this algorithm`;let ua;const da=async(e,t,n,r=!1)=>{ua||=new WeakMap;let i=ua.get(e);if(i?.[n])return i[n];let a=await ca({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:ua.set(e,{[n]:a}),a},fa=(e,t)=>{ua||=new WeakMap;let n=ua.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(la)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(la);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(la);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(la)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(la);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(la);return n?n[t]=a:ua.set(e,{[t]:a}),a};async function pa(e,t){if(e instanceof Uint8Array||Ki(e))return e;if(qi(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return fa(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:`jwk`});return da(e,n,t)}if(Qi(e))return e.k?ki(e.k):da(e,e,t,!0);throw Error(`unreachable`)}async function ma(e,t,n){if(!Q(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return ki(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new Y(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return ca({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return ca({...e,ext:r});case`EC`:case`OKP`:return ca({...e,alg:t,ext:r});default:throw new Y(`Unsupported "kty" (Key Type) Parameter value`)}}function ha(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new Y(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function ga(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const _a=e=>e?.[Symbol.toStringTag],va=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},ya=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(Qi(t)){if(ta(t)&&va(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!Ji(t))throw TypeError(Ri(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${_a(t)} instances for symmetric algorithms must be of type "secret"`)}},ba=(e,t,n)=>{if(Qi(t))switch(n){case`decrypt`:case`sign`:if($i(t)&&va(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(ea(t)&&va(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!Ji(t))throw TypeError(Ri(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${_a(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${_a(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${_a(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${_a(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${_a(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function xa(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:ya(e,t,n);break;default:ba(e,t,n)}}async function Sa(e,t,n){if(!Q(e))throw new X(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new X(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new X(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new X(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new X(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!Q(e.header))throw new X(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=ki(e.protected);r=JSON.parse(Ti.decode(t))}catch{throw new X(`JWS Protected Header is invalid`)}if(!Zi(r,e.header))throw new X(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=ha(X,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new X(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new X(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&ga(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Bi(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new X(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new X(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),xa(s,t,`verify`);let u=Ei(e.protected===void 0?new Uint8Array:Di(e.protected),Di(`.`),typeof e.payload==`string`?o?Di(e.payload):wi.encode(e.payload):e.payload),d=Yi(e.signature,`signature`,X),f=await pa(t,s);if(!await aa(s,f,d,u))throw new Gi;let p;p=o?Yi(e.payload,`payload`,X):typeof e.payload==`string`?wi.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?{...m,key:f}:m}async function Ca(e,t,n){if(e instanceof Uint8Array&&(e=Ti.decode(e)),typeof e!=`string`)throw new X(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new X(`Invalid Compact JWS`);let s=await Sa({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}const wa=e=>Math.floor(e.getTime()/1e3),Ta=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Ea(e){let t=Ta.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600)}return t[1]===`-`||t[4]===`ago`?-i:i}const Da=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,Oa=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function ka(e,t,n={}){let r;try{r=JSON.parse(Ti.decode(t))}catch{}if(!Q(r))throw new Z(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||Da(e.typ)!==Da(i)))throw new J(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new J(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new J(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new J(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!Oa(r.aud,typeof c==`string`?[c]:c))throw new J(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=Ea(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=wa(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new J(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new J(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new J(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new J(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new zi(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:Ea(l);if(e-d>t)throw new zi(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new J(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r}async function Aa(e,t,n){let r=await Ca(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new Z(`JWTs MUST NOT use unencoded payload`);let i={payload:ka(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}function ja(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new Y(`Unsupported "alg" value for a JSON Web Key Set`)}}function Ma(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(Na)}function Na(e){return Q(e)}var Pa=class{#e;#t=new WeakMap;constructor(e){if(!Ma(e))throw new Vi(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=ja(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`}return t}),{0:o,length:s}=a;if(s===0)throw new Hi;if(s!==1){let e=new Ui,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await Fa(t,e,n)}catch{}},e}return Fa(this.#t,o,n)}};async function Fa(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await ma({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new Vi(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Ia(e){let t=new Pa(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function La(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Ra;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Ra=`jose/v6.2.3`);const za=Symbol();async function Ba(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new Wi:e});if(i.status!==200)throw new q(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new q(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Va=Symbol();function Ha(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!Q(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Q))}var Ua=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Ra&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Ra),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[za],t?.[Va]!==void 0&&(this.#l=t?.[Va],Ha(t?.[Va],this.#r)&&(this.#i=this.#l.uat,this.#c=Ia(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#n}fresh(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#r}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof Hi&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&La()&&(this.#a=void 0),this.#a||=Ba(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Ia(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Wa(e,t){let n=new Ua(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}function Ga(e){if(typeof e!=`string`)throw new Z(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Z(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Z(`Invalid JWT`);if(!t)throw new Z(`JWTs must contain a payload`);let r;try{r=ki(t)}catch{throw new Z(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Ti.decode(r))}catch{throw new Z(`Failed to parse the decoded payload as JSON`)}if(!Q(i))throw new Z(`Invalid JWT Claims Set`);return i}const Ka=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,qa=new Set,Ja=typeof process==`object`&&process?process:{},Ya=(e,t,n,r)=>{typeof Ja.emitWarning==`function`?Ja.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let Xa=globalThis.AbortController,Za=globalThis.AbortSignal;if(Xa===void 0){Za=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Xa=class{constructor(){t()}signal=new Za;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=Ja.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,Ya("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const Qa=e=>!qa.has(e),$=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),$a=e=>$(e)?e<=256?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?eo:null:null;var eo=class extends Array{constructor(e){super(e),this.fill(0)}},to=class e{heap;length;static#e=!1;static create(t){let n=$a(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},no=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:_,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:x,ignoreFetchAbort:S}=t;if(n!==0&&!$(n))throw TypeError(`max option must be a nonnegative integer`);let C=n?$a(n):Array;if(!C)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(_!==void 0&&typeof _!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=_,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new C(n),this.#f=new C(n),this.#p=0,this.#m=0,this.#h=to.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!S,this.maxEntrySize!==0){if(this.#t!==0&&!$(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!$(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=$(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!$(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;Qa(t)&&(qa.add(t),Ya(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new eo(this.#e),t=new eo(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=Ka.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:Ka.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=Ka.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new eo(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!$(n)){if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!$(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`)}return n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(Ka.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=Ka.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=Ka.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new Xa,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof Xa}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#c.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,y,v,m);return t.__returned=t}{let t=this.#u[y];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(y),r&&this.#w(y),g&&this.#T(g,y),t;let a=this.#I(e,y,v,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0){if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}};const ro=`vercel-forwarded-host`,io=`vercel-forwarded-scheme`,ao=`vercel-forwarded-port`,oo=`vercel-forwarded-path`,so=`vercel-sandbox-oidc-token`,co=new no({max:100});function lo(e,t=uo){return async function(n){let r=new Headers(n.headers),i=r.get(ro),a=r.get(io),o=r.get(ao),s=r.get(oo),c=r.get(so);if(r.delete(ro),r.delete(io),r.delete(ao),r.delete(oo),r.delete(so),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(fo(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=po(new URL(n.url),s),r=await go(c,t),i=ho(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function uo(){return new Response(`Forbidden`,{status:403})}function fo(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function po(e,t){let n=mo(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=mo(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=mo(r.pathname.slice(0,-n.length))),r}function mo(e){return e.replace(/\/+$/,``)||`/`}function ho(e,t){let n=yo(t,`team_id`),r=yo(t,`project_id`),i=yo(t,`sandbox_id`),a=yo(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function go(e,t){let n=yo(Ga(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await Aa(e,vo(n),{audience:_o(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function _o(e){let t=mo(e.pathname);return t===`/`?e.origin:e.origin+t}function vo(e){let t=co.get(e);if(t)return t;let n=Wa(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return co.set(e,n),n}function yo(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{E as APIError,U as Command,Ur as CommandFinished,ee as DEFAULT_SANDBOX_REGION,Ci as Drive,di as FileSystem,xi as Sandbox,mi as SandboxUser,pi as SandboxUserAlreadyExistsError,Yr as Session,Kr as Snapshot,D as StreamError,lo as defineSandboxProxy};