experimental-ash 0.44.0 → 0.45.0

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.
@@ -102,27 +102,27 @@ ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,
102
102
  \r
103
103
  `),this.maxHeaderSize=t.maxHeaderSize??65536,this.maxBoundaryBuffer=t.maxBoundaryBuffer??8192}async*parseStream(e){let t=e.getReader(),n=new nc,r=this.startProducer(t,n);try{yield*this.consumeMessages(n)}finally{n.cancel(),this.closeCurrentPayload();try{await t.cancel()}catch{}await r}}async startProducer(e,t){try{for(;!t.isTerminal;){let n;try{n=await e.read()}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.constructor.name===`AbortError`||e.name===`TimeoutError`||e.constructor.name===`TimeoutError`))break;throw e}let{done:r,value:i}=n;if(r){if(this.buffer!==null&&this.buffer.length>0){let e=this.write(new Uint8Array);for(let n of e){if(t.isTerminal)break;t.enqueue(n)}}if(this.state!==4)throw this.state===0?new Zs(`Invalid multipart stream: missing initial boundary`):new Zs(`Unexpected end of stream`);break}if(!(i instanceof Uint8Array))throw new Zs(`Invalid chunk type: expected Uint8Array, got ${typeof i}`);let a=this.write(i);for(let e of a){if(t.isTerminal)break;t.enqueue(e)}}t.isTerminal||t.finish()}catch(e){this.closeCurrentPayload(e),t.isTerminal||t.finish(e)}finally{try{e.releaseLock()}catch{}}}async*consumeMessages(e){for(;;){let t=await e.dequeue();if(t===null)break;yield t}}write(e){let t=[];if(this.state===4)throw new Zs(`Unexpected data after end of stream`);let n=0,r=e.length;if(this.buffer!==null){let t=this.buffer.length,n=t+r;if(this.state===2){if(n>this.maxHeaderSize)throw new Zs(`Buffer size limit exceeded: ${n} bytes > ${this.maxHeaderSize} bytes. This may indicate malformed multipart data with oversized headers.`)}else if(t>this.maxBoundaryBuffer)throw new Zs(`Boundary buffer limit exceeded: ${t} bytes > ${this.maxBoundaryBuffer} bytes. This may indicate malformed multipart data with invalid boundaries.`);let i=new Uint8Array(n);i.set(this.buffer,0),i.set(e,t),e=i,r=e.length,this.buffer=null}if(r===0&&this.state===0)throw new Zs(`Invalid multipart stream: missing initial boundary`);for(;;){if(this.state===3){if(r-n<this.boundaryLength){let t=e.subarray(n);if(t.length>this.maxBoundaryBuffer)throw new Zs(`Boundary buffer limit exceeded: ${t.length} > ${this.maxBoundaryBuffer}`);this.buffer=t;break}let t=this.findBoundary(e,n);if(t===-1){let t=this.findPartialTailBoundary(e);if(t===-1)this.writeBody(n===0?e:e.subarray(n));else{this.writeBody(e.subarray(n,t));let r=e.subarray(t);if(r.length>this.maxBoundaryBuffer)throw new Zs(`Partial boundary too large: ${r.length} > ${this.maxBoundaryBuffer}`);this.buffer=r}break}this.writeBody(e.subarray(n,t)),this.finishMessage(),n=t+this.boundaryLength,this.state=1}if(this.state===1){if(r-n<2){let t=e.subarray(n);if(t.length>this.maxBoundaryBuffer)throw new Zs(`After-boundary buffer limit exceeded: ${t.length} > ${this.maxBoundaryBuffer}`);this.buffer=t;break}if(e[n]===45&&e[n+1]===45){this.state=4;break}if(e[n]===13&&e[n+1]===10)n+=2;else if(e[n]===10)n+=1;else throw new Zs(`Invalid character after boundary: expected CRLF or LF, got 0x${e[n].toString(16)}`);this.state=2}if(this.state===2){if(r-n<4){let t=e.subarray(n);if(t.length>this.maxHeaderSize)throw new Zs(`Header buffer limit exceeded: ${t.length} > ${this.maxHeaderSize}`);this.buffer=t;break}let i=this.findDoubleNewline(e,n),a=4;if(i===-1&&(i=Qs(`
104
104
 
105
- `)(e,n),a=2),i===-1){let t=e.subarray(n);if(t.length>this.maxHeaderSize)throw new Zs(`Headers too large: ${t.length} > ${this.maxHeaderSize} bytes`);this.buffer=t;break}let o=e.subarray(n,i);this.currentHeaders=ec(o);let s=this.createStreamingMessage();t.push(s),n=i+a,this.state=3;continue}if(this.state===0){if(r<this.openingBoundaryLength){if(e.length>this.maxBoundaryBuffer)throw new Zs(`Initial chunk too large for boundary detection: ${e.length} > ${this.maxBoundaryBuffer}`);this.buffer=e;break}if(this.findOpeningBoundary(e)!==0)throw new Zs(`Invalid multipart stream: missing initial boundary`);n=this.openingBoundaryLength,this.state=1}}return t}createStreamingMessage(){let e=new Headers(this.currentHeaders),t=new ReadableStream({start:e=>{this.currentPayloadController=e}});return this.currentHeaders=new Headers,{headers:e,payload:t}}writeBody(e){this.currentPayloadController&&this.currentPayloadController.enqueue(e)}finishMessage(){this.currentPayloadController&&=(this.currentPayloadController.close(),null)}closeCurrentPayload(e){if(this.currentPayloadController){try{e?this.currentPayloadController.error(e):this.currentPayloadController.close()}catch{}this.currentPayloadController=null}}};const ac=(e,t,n)=>{let r=e instanceof RegExp?oc(e,n):e,i=t instanceof RegExp?oc(t,n):t,a=r!==null&&i!=null&&sc(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},oc=(e,t)=>{let n=t.match(e);return n?n[0]:null},sc=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},cc=`\0SLASH`+Math.random()+`\0`,lc=`\0OPEN`+Math.random()+`\0`,uc=`\0CLOSE`+Math.random()+`\0`,dc=`\0COMMA`+Math.random()+`\0`,fc=`\0PERIOD`+Math.random()+`\0`,pc=new RegExp(cc,`g`),mc=new RegExp(lc,`g`),hc=new RegExp(uc,`g`),gc=new RegExp(dc,`g`),_c=new RegExp(fc,`g`),vc=/\\\\/g,yc=/\\{/g,bc=/\\}/g,xc=/\\,/g,Sc=/\\\./g;function Cc(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function wc(e){return e.replace(vc,cc).replace(yc,lc).replace(bc,uc).replace(xc,dc).replace(Sc,fc)}function Tc(e){return e.replace(pc,`\\`).replace(mc,`{`).replace(hc,`}`).replace(gc,`,`).replace(_c,`.`)}function Ec(e){if(!e)return[``];let t=[],n=ac(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=Ec(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Dc(e,t={}){if(!e)return[];let{max:n=1e5}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),Mc(wc(e),n,!0).map(Tc)}function Oc(e){return`{`+e+`}`}function kc(e){return/^-?0\d/.test(e)}function Ac(e,t){return e<=t}function jc(e,t){return e>=t}function Mc(e,t,n){let r=[],i=ac(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?Mc(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e<o.length&&e<t;e++){let t=a+`{`+i.body+`}`+o[e];r.push(t)}else{let s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),l=s||c,u=i.body.indexOf(`,`)>=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+uc+i.post,Mc(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=Ec(i.body),d.length===1&&d[0]!==void 0&&(d=Mc(d[0],t,!1).map(Oc),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=Cc(d[0]),n=Cc(d[1]),r=Math.max(d[0].length,d[1].length),i=d.length===3&&d[2]!==void 0?Math.max(Math.abs(Cc(d[2])),1):1,a=Ac;n<e&&(i*=-1,a=jc);let o=d.some(kc);f=[];for(let s=e;a(s,n)&&f.length<t;s+=i){let e;if(c)e=String.fromCharCode(s),e===`\\`&&(e=``);else if(e=String(s),o){let t=r-e.length;if(t>0){let n=Array(t+1).join(`0`);e=s<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e<d.length;e++)f.push.apply(f,Mc(d[e],t,!1))}for(let e=0;e<f.length;e++)for(let i=0;i<o.length&&r.length<t;i++){let t=a+f[e]+o[i];(!n||l||t)&&r.push(t)}}return r}const Nc=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},Pc={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},Fc=e=>e.replace(/[[\]\\-]/g,`\\$&`),Ic=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Lc=e=>e.join(``),Rc=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(Pc))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(Fc(d)+`-`+Fc(t)):t===d&&r.push(Fc(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Fc(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Fc(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l)return[Ic(r[0].length===2?r[0].slice(-1):r[0]),!1,u-n,!1];let f=`[`+(l?`^`:``)+Lc(r)+`]`,p=`[`+(l?``:`^`)+Lc(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},zc=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var Bc;const Vc=new Set([`!`,`?`,`+`,`*`,`@`]),Hc=e=>Vc.has(e),Uc=e=>Hc(e.type),Wc=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Gc=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Kc=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),qc=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Jc=`(?!\\.)`,Yc=new Set([`[`,`.`]),Xc=new Set([`..`,`.`]),Zc=new Set(`().*{}+?[]^$\\!`),Qc=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),$c=`[^/]+?`;let el=0;var tl=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++el;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.type?this.#l=this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#l=this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof Bc&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof Bc&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new Bc(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&Hc(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new Bc(n,t);u=Bc.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new Bc(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&Hc(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new Bc(n,d);d.push(o),u=Bc.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new Bc(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,Gc)}#m(e,t=Wc){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=Kc){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new Bc(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!qc.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=qc.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new Bc(null,void 0,t);return Bc.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!Uc(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?Bc.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Xc.has(this.#r[0]))){let n=Yc,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Jc:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,zc(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,zc(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Jc:``)+$c;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Jc:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,zc(i),this.#t=!!this.#t,this.#n]}#x(){if(Uc(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(Zc.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?$c:`[^/]*?`,t=!0;continue}else o=!1;if(c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=Rc(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=Qc(c)}return[i,zc(e),!!t,a]}};Bc=tl;const nl=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),rl=(e,t,n={})=>(Nc(t),!n.nocomment&&t.charAt(0)===`#`?!1:new jl(t,n).match(e)),il=/^\*+([^+@!?*[(]*)$/,al=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),ol=e=>t=>t.endsWith(e),sl=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),cl=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ll=/^\*+\.\*+$/,ul=e=>!e.startsWith(`.`)&&e.includes(`.`),dl=e=>e!==`.`&&e!==`..`&&e.includes(`.`),fl=/^\.\*+$/,pl=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),ml=/^\*+$/,hl=e=>e.length!==0&&!e.startsWith(`.`),gl=e=>e.length!==0&&e!==`.`&&e!==`..`,_l=/^\?+([^+@!?*[(]*)?$/,vl=([e,t=``])=>{let n=Sl([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},yl=([e,t=``])=>{let n=Cl([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},bl=([e,t=``])=>{let n=Cl([e]);return t?e=>n(e)&&e.endsWith(t):n},xl=([e,t=``])=>{let n=Sl([e]);return t?e=>n(e)&&e.endsWith(t):n},Sl=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},Cl=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},wl=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Tl={win32:{sep:`\\`},posix:{sep:`/`}};rl.sep=wl===`win32`?Tl.win32.sep:Tl.posix.sep;const El=Symbol(`globstar **`);rl.GLOBSTAR=El,rl.filter=(e,t={})=>n=>rl(n,e,t);const Dl=(e,t={})=>Object.assign({},e,t);rl.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return rl;let t=rl;return Object.assign((n,r,i={})=>t(n,r,Dl(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Dl(e,n))}static defaults(n){return t.defaults(Dl(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Dl(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Dl(e,r))}},unescape:(n,r={})=>t.unescape(n,Dl(e,r)),escape:(n,r={})=>t.escape(n,Dl(e,r)),filter:(n,r={})=>t.filter(n,Dl(e,r)),defaults:n=>t.defaults(Dl(e,n)),makeRe:(n,r={})=>t.makeRe(n,Dl(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Dl(e,r)),match:(n,r,i={})=>t.match(n,r,Dl(e,i)),sep:t.sep,GLOBSTAR:El})};const Ol=(e,t={})=>(Nc(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Dc(e,{max:t.braceExpandMax}));rl.braceExpand=Ol,rl.makeRe=(e,t={})=>new jl(e,t).makeRe(),rl.match=(e,t,n={})=>{let r=new jl(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const kl=/[?*]|[+@!]\(.*?\)|\[|\]/,Al=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var jl=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Nc(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||wl,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!kl.test(e[2]))&&!kl.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t of e)for(let e=0;e<t.length;e++)t[e]===`**`&&(t[e]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&!(this.isWindows&&/^[a-z]:$/i.test(r))&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(El)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(El,i),o=t.lastIndexOf(El),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,m=[0];for(let e of c)e===El?(m.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let h=d.length-1,g=e.length-u;for(let e of d)e[1]=g-(m[h--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===El)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return Ol(this.pattern,this.options)}parse(e){Nc(e);let t=this.options;if(e===`**`)return El;if(e===``)return``;let n,r=null;(n=e.match(ml))?r=t.dot?gl:hl:(n=e.match(il))?r=(t.nocase?t.dot?cl:sl:t.dot?ol:al)(n[1]):(n=e.match(_l))?r=(t.nocase?t.dot?yl:vl:t.dot?bl:xl)(n):(n=e.match(ll))?r=t.dot?dl:ul:(n=e.match(fl))&&(r=pl);let i=tl.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?Al(e):e===El?El:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==El||a===El||(a===void 0?i!==void 0&&i!==El?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==El&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=El))});let i=t.filter(e=>e!==El);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return rl.defaults(e).Minimatch}};rl.AST=tl,rl.Minimatch=jl,rl.escape=nl,rl.unescape=zc;var Ml=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})),Nl=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?.()??{}}})),Pl=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,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}})),Fl=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,{getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>m}),n.exports=l(u);var d=Nl(),f=Pl();async function p(t){let n=``,r;try{n=m()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await Promise.resolve().then(()=>e(Bl())),await import(`../../_chunks/workflow/token-DV7rQw_t.js`).then(t=>e(t.default))]);(!n||i(r(n),t?.expirationBufferMs))&&(await a(t),n=m())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
106
- ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,d.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}})),Il=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:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}}})),Ll=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(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 s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{findRootDir:()=>v,getUserDataDir:()=>y}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=d(t(`os`)),_=Pl();function v(){try{let e=process.cwd();for(;e!==m.default.dirname(e);){let t=m.default.join(e,`.vercel`);if(h.default.existsSync(t))return e;e=m.default.dirname(e)}}catch{throw new _.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function y(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(g.default.platform()){case`darwin`:return m.default.join(g.default.homedir(),`Library/Application Support`);case`linux`:return m.default.join(g.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}})),Rl=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(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 s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{isValidAccessToken:()=>b,readAuthConfig:()=>v,writeAuthConfig:()=>y}),n.exports=f(p);var m=d(t(`fs`)),h=d(t(`path`)),g=Bl();function _(){let e=(0,g.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(e,`auth.json`)}function v(){try{let e=_();if(!m.existsSync(e))return null;let t=m.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function y(e){let t=_(),n=h.dirname(t);m.existsSync(n)||m.mkdirSync(n,{mode:504,recursive:!0}),m.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function b(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}})),zl=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),u={};s(u,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),n.exports=l(u);var d=t(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}})),Bl=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(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 s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>T,getTokenPayload:()=>O,getVercelDataDir:()=>x,getVercelOidcToken:()=>C,getVercelToken:()=>S,isExpired:()=>k,loadToken:()=>D,saveToken:()=>E}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=Pl(),_=Ll(),v=Rl(),y=zl(),b=Il();function x(){let e=(0,_.getUserDataDir)();return e?m.join(e,`com.vercel.cli`):null}async function S(e){let t=(0,v.readAuthConfig)();if(!t?.token)throw new b.AccessTokenMissingError;if((0,v.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,v.writeAuthConfig)({}),new b.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,y.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,y.processTokenResponse)(e);if(n||!r)throw(0,v.writeAuthConfig)({}),new b.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,v.writeAuthConfig)(i),i.token}catch(e){throw(0,v.writeAuthConfig)({}),e instanceof b.AccessTokenMissingError||e instanceof b.RefreshAccessTokenFailedError?e:new b.RefreshAccessTokenFailedError(e)}}async function C(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new g.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return w(a),a}function w(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function T(){let e=(0,_.findRootDir)();if(!e)throw new g.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=m.join(e,`.vercel`,`project.json`);if(!h.existsSync(t))throw new g.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(h.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function E(e,t){let n=(0,_.getUserDataDir)();if(!n)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=m.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);h.mkdirSync(m.dirname(r),{mode:504,recursive:!0}),h.writeFileSync(r,i),h.chmodSync(r,432)}function D(e){let t=(0,_.getUserDataDir)();if(!t)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=m.join(t,`com.vercel.token`,`${e}.json`);if(!h.existsSync(n))return null;let r=JSON.parse(h.readFileSync(n,`utf8`));return w(r),r}function O(e){let t=e.split(`.`);if(t.length!==3)throw new g.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function k(e,t=0){return e.exp*1e3<Date.now()+t}})),Vl=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:()=>f.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>f.RefreshAccessTokenFailedError,getContext:()=>d.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>u.getVercelOidcTokenSync,getVercelToken:()=>p.getVercelToken}),t.exports=c(l);var u=Fl(),d=Nl(),f=Il(),p=Bl()})),Hl=e(Ml(),1),Ul=Vl();async function Wl(e){let t=0,n=e.getReader(),r=[];try{for(;;){let{done:e,value:i}=await n.read();if(e)break;r.push(i),t+=i.length}}finally{n.releaseLock()}return Buffer.concat(r,t)}var Gl=class{contentType=`application/json`;replacer;reviver;constructor(e={}){this.replacer=e.replacer,this.reviver=e.reviver}serialize(e){return Buffer.from(JSON.stringify(e,this.replacer),`utf8`)}async deserialize(e){let t=await Wl(e);return JSON.parse(t.toString(`utf8`),this.reviver)}},Kl=class extends Error{constructor(e){super(`Message ${e} not found`),this.name=`MessageNotFoundError`}},ql=class extends Error{constructor(e,t){super(`Message ${e} not available for processing${t?`: ${t}`:``}`),this.name=`MessageNotAvailableError`}},Jl=class extends Error{constructor(e,t){super(`Message ${e} is corrupted: ${t}`),this.name=`MessageCorruptedError`}},Yl=class extends Error{constructor(e=`Missing or invalid authentication token`){super(e),this.name=`UnauthorizedError`}},Xl=class extends Error{constructor(e=`Queue environment doesn't match token environment`){super(e),this.name=`ForbiddenError`}},Zl=class extends Error{constructor(e){super(e),this.name=`BadRequestError`}},Ql=class extends Error{constructor(e=`Unexpected server error`){super(e),this.name=`InternalServerError`}},$l=class extends Error{constructor(e,t=1,n=10){super(`Invalid limit: ${e}. Limit must be between ${t} and ${n}.`),this.name=`InvalidLimitError`}},eu=class extends Error{constructor(e){super(`Message ${e} has already been processed`),this.name=`MessageAlreadyProcessedError`}},tu=class extends Error{idempotencyKey;constructor(e,t){super(e),this.name=`DuplicateMessageError`,this.idempotencyKey=t}},nu=class extends Error{deploymentId;constructor(e,t){super(e),this.name=`ConsumerDiscoveryError`,this.deploymentId=t}},ru=class extends Error{constructor(e=`Consumer registry not configured`){super(e),this.name=`ConsumerRegistryNotConfiguredError`}},iu=300,au=30,ou=60,su=10,cu=3e3;function lu(e){return Math.min(ou,Math.max(su,e/5))}var uu=class{client;topicName;consumerGroupName;visibilityTimeout;constructor(e,t,n,r={}){this.client=e,this.topicName=t,this.consumerGroupName=n,this.visibilityTimeout=Math.max(au,r.visibilityTimeoutSeconds??iu)}isClientError(e){return e instanceof ql||e instanceof Kl||e instanceof Zl||e instanceof Yl||e instanceof Xl}startVisibilityExtension(e,t){let n=!0,r=!1,i,a=null,o=lu(this.visibilityTimeout)*1e3,s=o;if(t?.visibilityDeadline){let e=t.visibilityDeadline.getTime()-Date.now();s=e>0?lu(e/1e3)*1e3:0}let c=new Promise(e=>{i=e}),l=()=>{r||(r=!0,i())},u=async()=>{if(!n){l();return}try{await this.client.changeVisibility({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e,visibilityTimeoutSeconds:this.visibilityTimeout}),n?a=setTimeout(()=>u(),o):l()}catch(t){if(this.isClientError(t)){console.error(`Visibility extension failed with client error for receipt handle ${e} (stopping retries):`,t),l();return}console.error(`Failed to extend visibility for receipt handle ${e} (will retry in ${cu/1e3}s):`,t),n?a=setTimeout(()=>u(),cu):l()}};return a=setTimeout(()=>u(),s),async(e=!1)=>{n=!1,a&&=(clearTimeout(a),null),e?await c:l()}}async finalizePayload(e){let t=this.client.getTransport();if(t.finalize&&e!=null)try{await t.finalize(e)}catch(e){console.warn(`Failed to finalize message payload:`,e)}}async processMessage(e,t,n){let r=this.startVisibilityExtension(e.receiptHandle,n),i={messageId:e.messageId,deliveryCount:e.deliveryCount,createdAt:e.createdAt,expiresAt:e.expiresAt??new Date(e.createdAt.getTime()+864e5),topicName:this.topicName,consumerGroup:this.consumerGroupName,region:this.client.getRegion()};try{await t(e.payload,i),await r(),await this.client.acknowledgeMessage({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e.receiptHandle})}catch(t){if(await r(),n?.retry){let r;try{r=n.retry(t,i)}catch(e){console.warn(`retry handler threw:`,e)}if(r){if(`acknowledge`in r&&r.acknowledge){try{await this.client.acknowledgeMessage({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e.receiptHandle})}catch(e){console.warn(`Failed to acknowledge message:`,e)}await this.finalizePayload(e.payload);return}if(`afterSeconds`in r&&typeof r.afterSeconds==`number`){try{await this.client.changeVisibility({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e.receiptHandle,visibilityTimeoutSeconds:r.afterSeconds})}catch(e){console.warn(`Failed to reschedule message for retry:`,e)}await this.finalizePayload(e.payload);return}}}throw await this.finalizePayload(e.payload),t}}async consumeMessage(e,t,n){await this.processMessage(t,e,n)}async consume(e,t){let n=t?.retry;if(t&&`messageId`in t){let r=await this.client.receiveMessageById({queueName:this.topicName,consumerGroup:this.consumerGroupName,messageId:t.messageId,visibilityTimeoutSeconds:this.visibilityTimeout});return await this.processMessage(r.message,e,{retry:n}),1}else{let r=t&&`limit`in t?t.limit:1,i=0;for await(let t of this.client.receiveMessages({queueName:this.topicName,consumerGroup:this.consumerGroupName,visibilityTimeoutSeconds:this.visibilityTimeout,limit:r}))i++,await this.processMessage(t,e,{retry:n});return i}}get name(){return this.consumerGroupName}get topic(){return this.topicName}},du=class{client;topicName;constructor(e,t){this.client=e,this.topicName=t}async publish(e,t){let n=await this.client.sendMessage({queueName:this.topicName,payload:e,idempotencyKey:t?.idempotencyKey,retentionSeconds:t?.retentionSeconds,delaySeconds:t?.delaySeconds,headers:t?.headers});return n.messageId&&Eu()&&fd(this.topicName,n.messageId,this.client.getRegion(),t?.delaySeconds,t?.retentionSeconds),{messageId:n.messageId}}consumerGroup(e,t){return new uu(this.client,this.topicName,e,t)}get name(){return this.topicName}},fu=`com.vercel.queue.v1beta`,pu=`com.vercel.queue.v2beta`;function mu(e,t){let n=t.slice(0,-1);return e.startsWith(n)}function hu(e){return typeof e==`object`&&!!e}function gu(e,t){if(!t||!t.includes(`application/cloudevents+json`))throw Error(`Invalid content type: expected 'application/cloudevents+json'`);if(!hu(e)||!e.type||!e.source||!e.id||!hu(e.data))throw Error(`Invalid CloudEvent: missing required fields`);if(e.type!==`com.vercel.queue.v1beta`)throw Error(`Invalid CloudEvent type: expected '${fu}', got '${String(e.type)}'`);let{data:n}=e,r=[];if(`queueName`in n||r.push(`queueName`),`consumerGroup`in n||r.push(`consumerGroup`),`messageId`in n||r.push(`messageId`),r.length>0)throw Error(`Missing required CloudEvent data fields: ${r.join(`, `)}`);return{queueName:String(n.queueName),consumerGroup:String(n.consumerGroup),messageId:String(n.messageId)}}function _u(e,t){if(e instanceof Headers)return e.get(t);let n=e[t];return Array.isArray(n)?n[0]??null:n??null}function vu(e){let t=_u(e,`ce-type`);if(t!==`com.vercel.queue.v2beta`)throw Error(`Invalid CloudEvent type: expected '${pu}', got '${t}'`);let n=_u(e,`ce-vqsqueuename`),r=_u(e,`ce-vqsconsumergroup`),i=_u(e,`ce-vqsmessageid`),a=[];if(n||a.push(`ce-vqsqueuename`),r||a.push(`ce-vqsconsumergroup`),i||a.push(`ce-vqsmessageid`),a.length>0)throw Error(`Missing required CloudEvent headers: ${a.join(`, `)}`);let o={queueName:n,consumerGroup:r,messageId:i,region:_u(e,`ce-vqsregion`)??void 0},s=_u(e,`ce-vqsreceipthandle`);if(!s)return o;let c={...o,receiptHandle:s},l=_u(e,`ce-vqsdeliverycount`);l&&(c.deliveryCount=parseInt(l,10));let u=_u(e,`ce-vqscreatedat`);u&&(c.createdAt=u);let d=_u(e,`ce-vqsexpiresat`);d&&(c.expiresAt=d);let f=_u(e,`content-type`);f&&(c.contentType=f);let p=_u(e,`ce-vqsvisibilitydeadline`);return p&&(c.visibilityDeadline=p),c}function yu(e,t){if(_u(t,`ce-type`)===`com.vercel.queue.v2beta`){let n=vu(t);return`receiptHandle`in n&&(n.parsedPayload=e),n}return gu(e,_u(t,`content-type`))}async function bu(e){if(e.headers.get(`ce-type`)===`com.vercel.queue.v2beta`){let t=vu(e.headers);return`receiptHandle`in t&&e.body&&(t.rawBody=e.body),t}let t;try{t=await e.json()}catch{throw Error(`Failed to parse CloudEvent from request body`)}let n={};return e.headers.forEach((e,t)=>{n[t]=e}),yu(t,n)}async function xu(e,t,n){let{queueName:r,consumerGroup:i,messageId:a}=t;if(!n?.client)throw Error(`HandleCallbackOptions.client is required`);let o=Dd(n.client);t.region&&(o=o.withRegion(t.region));let s=new du(o,r).consumerGroup(i,n?.visibilityTimeoutSeconds===void 0?void 0:{visibilityTimeoutSeconds:n.visibilityTimeoutSeconds});if(`receiptHandle`in t){let r=o.getTransport(),i;if(t.rawBody)i=await r.deserialize(t.rawBody);else if(t.parsedPayload!==void 0)i=t.parsedPayload;else throw Error(`Binary mode callback with receipt handle is missing payload`);let c={messageId:a,payload:i,deliveryCount:t.deliveryCount??1,createdAt:t.createdAt?new Date(t.createdAt):new Date,expiresAt:t.expiresAt?new Date(t.expiresAt):void 0,contentType:t.contentType??r.contentType,receiptHandle:t.receiptHandle},l=t.visibilityDeadline?new Date(t.visibilityDeadline):void 0;await s.consumeMessage(e,c,{visibilityDeadline:l,retry:n?.retry})}else await s.consume(e,{messageId:a,retry:n?.retry})}var Su=Hl.default.cyan(`[queue]`),Cu=Hl.default.green(`✓`),wu=Hl.default.red(`✗`),Tu=Hl.default.yellow(`↻`);function Eu(){return process.env.NODE_ENV===`development`}var Du=Symbol.for(`@vercel/queue.devRouteMappings`);function Ou(e){let t=``;for(let n of e)n===`_`?t+=`__`:n===`/`?t+=`_S`:n===`.`?t+=`_D`:/[A-Za-z0-9-]/.test(n)?t+=n:t+=`_`+n.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`);return t}function ku(){let e=globalThis;if(Du in e)return e[Du]??null;try{let t=Vn.join(process.cwd(),`vercel.json`);if(!Hn.existsSync(t))return e[Du]=null,null;let n=JSON.parse(Hn.readFileSync(t,`utf-8`));if(!n.functions)return e[Du]=null,null;let r=[];for(let[e,t]of Object.entries(n.functions))if(t.experimentalTriggers){for(let n of t.experimentalTriggers)if(!(!n.type?.startsWith(`queue/`)||!n.topic)){if(n.type!==`queue/v2beta`){console.warn(`${Su} Unsupported trigger type "${n.type}" for topic "${n.topic}" in ${e}. Use "queue/v2beta" instead.`);continue}r.push({filePath:e,topic:n.topic,consumer:Ou(e),retryAfterSeconds:n.retryAfterSeconds})}}return e[Du]=r.length>0?r:null,e[Du]}catch(t){return console.warn(`${Su} Failed to read vercel.json:`,t),e[Du]=null,null}}function Au(e){let t=ku();return t?t.filter(t=>t.topic.includes(`*`)?mu(e,t.topic):t.topic===e):[]}function ju(e,t){return Au(e).find(e=>e.consumer===t)?.retryAfterSeconds}function Mu(e){return/^src\/(app|pages|server)\//.test(e)?e.slice(4):null}function Nu(e,t){return e===t||rl(e,t)}function Pu(e){let t=ku();if(!t)return[];let n=process.cwd(),r;try{r=Vn.relative(n,e)}catch{return[]}let i=r.replace(/\\/g,`/`),a=Mu(i);return t.filter(e=>Nu(i,e.filePath)||a!==null&&Nu(a,e.filePath))}function Fu(e){let t=e.match(/\((.+?):\d+:\d+\)/);if(t||=e.match(/at\s+(.+?):\d+:\d+/),!t)return null;let n=t[1].trim();if(n===`native`||n.startsWith(`node:`)||n.startsWith(`internal`))return null;if(n.startsWith(`file://`))try{n=new URL(n).pathname}catch{return null}return/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)?null:(n.startsWith(`./`)&&(n=n.slice(2)),n)}var Iu;function Lu(){if(Iu)return Iu;try{let e=typeof __dirname<`u`?__dirname:Vn.dirname(new URL(import.meta.url).pathname);Iu=Vn.resolve(e,`..`)}catch{Iu=``}return Iu}function Ru(){let e=Error().stack;if(!e)return null;let t=e.split(`
107
- `).slice(1),n=Lu();for(let e of t){let t=Fu(e);if(!t)continue;let r=Vn.isAbsolute(t)?t:Vn.resolve(process.cwd(),t),i;try{i=Hn.realpathSync(r)}catch{i=r}if(!(n&&i.startsWith(n)))return i}return null}var zu=Symbol.for(`@vercel/queue.devHandlerRegistry`);function Bu(){let e=globalThis;return e[zu]||(e[zu]=new Map),e[zu]}function Vu(e,t,n,r){let i=Pu(Vn.isAbsolute(e)?e:Vn.resolve(process.cwd(),e));if(i.length===0)return!1;let a=Bu();for(let e of i){let i=e.topic,o=a.get(i)??[],s={consumerGroup:e.consumer,handler:t,client:n,options:r},c=o.findIndex(t=>t.consumerGroup===e.consumer);c>=0?o[c]=s:o.push(s),a.set(i,o)}return!0}function Hu(e,t,n,r){let i=r??Ru();if(!i){console.warn(`${Su} Could not determine caller file path for handler registration.`);return}if(!Vu(i,e,t,n)){let e=ku();if(e&&e.length>0)return;let t=process.cwd(),n;try{n=Vn.relative(t,i).replace(/\\/g,`/`)}catch{n=i}console.warn(`${Su} handleCallback() in ${n} has no matching experimentalTriggers in vercel.json. This handler won't receive messages.
105
+ `)(e,n),a=2),i===-1){let t=e.subarray(n);if(t.length>this.maxHeaderSize)throw new Zs(`Headers too large: ${t.length} > ${this.maxHeaderSize} bytes`);this.buffer=t;break}let o=e.subarray(n,i);this.currentHeaders=ec(o);let s=this.createStreamingMessage();t.push(s),n=i+a,this.state=3;continue}if(this.state===0){if(r<this.openingBoundaryLength){if(e.length>this.maxBoundaryBuffer)throw new Zs(`Initial chunk too large for boundary detection: ${e.length} > ${this.maxBoundaryBuffer}`);this.buffer=e;break}if(this.findOpeningBoundary(e)!==0)throw new Zs(`Invalid multipart stream: missing initial boundary`);n=this.openingBoundaryLength,this.state=1}}return t}createStreamingMessage(){let e=new Headers(this.currentHeaders),t=new ReadableStream({start:e=>{this.currentPayloadController=e}});return this.currentHeaders=new Headers,{headers:e,payload:t}}writeBody(e){this.currentPayloadController&&this.currentPayloadController.enqueue(e)}finishMessage(){this.currentPayloadController&&=(this.currentPayloadController.close(),null)}closeCurrentPayload(e){if(this.currentPayloadController){try{e?this.currentPayloadController.error(e):this.currentPayloadController.close()}catch{}this.currentPayloadController=null}}};const ac=(e,t,n)=>{let r=e instanceof RegExp?oc(e,n):e,i=t instanceof RegExp?oc(t,n):t,a=r!==null&&i!=null&&sc(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},oc=(e,t)=>{let n=t.match(e);return n?n[0]:null},sc=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},cc=`\0SLASH`+Math.random()+`\0`,lc=`\0OPEN`+Math.random()+`\0`,uc=`\0CLOSE`+Math.random()+`\0`,dc=`\0COMMA`+Math.random()+`\0`,fc=`\0PERIOD`+Math.random()+`\0`,pc=new RegExp(cc,`g`),mc=new RegExp(lc,`g`),hc=new RegExp(uc,`g`),gc=new RegExp(dc,`g`),_c=new RegExp(fc,`g`),vc=/\\\\/g,yc=/\\{/g,bc=/\\}/g,xc=/\\,/g,Sc=/\\\./g;function Cc(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function wc(e){return e.replace(vc,cc).replace(yc,lc).replace(bc,uc).replace(xc,dc).replace(Sc,fc)}function Tc(e){return e.replace(pc,`\\`).replace(mc,`{`).replace(hc,`}`).replace(gc,`,`).replace(_c,`.`)}function Ec(e){if(!e)return[``];let t=[],n=ac(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=Ec(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Dc(e,t={}){if(!e)return[];let{max:n=1e5}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),Mc(wc(e),n,!0).map(Tc)}function Oc(e){return`{`+e+`}`}function kc(e){return/^-?0\d/.test(e)}function Ac(e,t){return e<=t}function jc(e,t){return e>=t}function Mc(e,t,n){let r=[],i=ac(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?Mc(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e<o.length&&e<t;e++){let t=a+`{`+i.body+`}`+o[e];r.push(t)}else{let s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),l=s||c,u=i.body.indexOf(`,`)>=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+uc+i.post,Mc(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=Ec(i.body),d.length===1&&d[0]!==void 0&&(d=Mc(d[0],t,!1).map(Oc),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=Cc(d[0]),n=Cc(d[1]),r=Math.max(d[0].length,d[1].length),i=d.length===3&&d[2]!==void 0?Math.max(Math.abs(Cc(d[2])),1):1,a=Ac;n<e&&(i*=-1,a=jc);let o=d.some(kc);f=[];for(let s=e;a(s,n)&&f.length<t;s+=i){let e;if(c)e=String.fromCharCode(s),e===`\\`&&(e=``);else if(e=String(s),o){let t=r-e.length;if(t>0){let n=Array(t+1).join(`0`);e=s<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e<d.length;e++)f.push.apply(f,Mc(d[e],t,!1))}for(let e=0;e<f.length;e++)for(let i=0;i<o.length&&r.length<t;i++){let t=a+f[e]+o[i];(!n||l||t)&&r.push(t)}}return r}const Nc=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},Pc={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},Fc=e=>e.replace(/[[\]\\-]/g,`\\$&`),Ic=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Lc=e=>e.join(``),Rc=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(Pc))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(Fc(d)+`-`+Fc(t)):t===d&&r.push(Fc(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Fc(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Fc(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l)return[Ic(r[0].length===2?r[0].slice(-1):r[0]),!1,u-n,!1];let f=`[`+(l?`^`:``)+Lc(r)+`]`,p=`[`+(l?``:`^`)+Lc(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},zc=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var Bc;const Vc=new Set([`!`,`?`,`+`,`*`,`@`]),Hc=e=>Vc.has(e),Uc=e=>Hc(e.type),Wc=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Gc=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Kc=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),qc=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Jc=`(?!\\.)`,Yc=new Set([`[`,`.`]),Xc=new Set([`..`,`.`]),Zc=new Set(`().*{}+?[]^$\\!`),Qc=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),$c=`[^/]+?`;let el=0;var tl=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++el;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.type?this.#l=this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#l=this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof Bc&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof Bc&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new Bc(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&Hc(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new Bc(n,t);u=Bc.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new Bc(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}else if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&Hc(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new Bc(n,d);d.push(o),u=Bc.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new Bc(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,Gc)}#m(e,t=Wc){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=Kc){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new Bc(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!qc.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=qc.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new Bc(null,void 0,t);return Bc.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!Uc(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?Bc.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Xc.has(this.#r[0]))){let n=Yc,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Jc:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,zc(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,zc(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Jc:``)+$c;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Jc:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,zc(i),this.#t=!!this.#t,this.#n]}#x(){if(Uc(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(Zc.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?$c:`[^/]*?`,t=!0;continue}else o=!1;if(c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=Rc(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=Qc(c)}return[i,zc(e),!!t,a]}};Bc=tl;const nl=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),rl=(e,t,n={})=>(Nc(t),!n.nocomment&&t.charAt(0)===`#`?!1:new jl(t,n).match(e)),il=/^\*+([^+@!?*[(]*)$/,al=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),ol=e=>t=>t.endsWith(e),sl=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),cl=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ll=/^\*+\.\*+$/,ul=e=>!e.startsWith(`.`)&&e.includes(`.`),dl=e=>e!==`.`&&e!==`..`&&e.includes(`.`),fl=/^\.\*+$/,pl=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),ml=/^\*+$/,hl=e=>e.length!==0&&!e.startsWith(`.`),gl=e=>e.length!==0&&e!==`.`&&e!==`..`,_l=/^\?+([^+@!?*[(]*)?$/,vl=([e,t=``])=>{let n=Sl([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},yl=([e,t=``])=>{let n=Cl([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},bl=([e,t=``])=>{let n=Cl([e]);return t?e=>n(e)&&e.endsWith(t):n},xl=([e,t=``])=>{let n=Sl([e]);return t?e=>n(e)&&e.endsWith(t):n},Sl=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},Cl=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},wl=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Tl={win32:{sep:`\\`},posix:{sep:`/`}};rl.sep=wl===`win32`?Tl.win32.sep:Tl.posix.sep;const El=Symbol(`globstar **`);rl.GLOBSTAR=El,rl.filter=(e,t={})=>n=>rl(n,e,t);const Dl=(e,t={})=>Object.assign({},e,t);rl.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return rl;let t=rl;return Object.assign((n,r,i={})=>t(n,r,Dl(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Dl(e,n))}static defaults(n){return t.defaults(Dl(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Dl(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Dl(e,r))}},unescape:(n,r={})=>t.unescape(n,Dl(e,r)),escape:(n,r={})=>t.escape(n,Dl(e,r)),filter:(n,r={})=>t.filter(n,Dl(e,r)),defaults:n=>t.defaults(Dl(e,n)),makeRe:(n,r={})=>t.makeRe(n,Dl(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Dl(e,r)),match:(n,r,i={})=>t.match(n,r,Dl(e,i)),sep:t.sep,GLOBSTAR:El})};const Ol=(e,t={})=>(Nc(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Dc(e,{max:t.braceExpandMax}));rl.braceExpand=Ol,rl.makeRe=(e,t={})=>new jl(e,t).makeRe(),rl.match=(e,t,n={})=>{let r=new jl(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const kl=/[?*]|[+@!]\(.*?\)|\[|\]/,Al=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var jl=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Nc(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||wl,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!kl.test(e[2]))&&!kl.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t of e)for(let e=0;e<t.length;e++)t[e]===`**`&&(t[e]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&!(this.isWindows&&/^[a-z]:$/i.test(r))&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(El)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(El,i),o=t.lastIndexOf(El),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,m=[0];for(let e of c)e===El?(m.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let h=d.length-1,g=e.length-u;for(let e of d)e[1]=g-(m[h--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===El)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return Ol(this.pattern,this.options)}parse(e){Nc(e);let t=this.options;if(e===`**`)return El;if(e===``)return``;let n,r=null;(n=e.match(ml))?r=t.dot?gl:hl:(n=e.match(il))?r=(t.nocase?t.dot?cl:sl:t.dot?ol:al)(n[1]):(n=e.match(_l))?r=(t.nocase?t.dot?yl:vl:t.dot?bl:xl)(n):(n=e.match(ll))?r=t.dot?dl:ul:(n=e.match(fl))&&(r=pl);let i=tl.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?Al(e):e===El?El:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==El||a===El||(a===void 0?i!==void 0&&i!==El?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==El&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=El))});let i=t.filter(e=>e!==El);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return rl.defaults(e).Minimatch}};rl.AST=tl,rl.Minimatch=jl,rl.escape=nl,rl.unescape=zc;var Ml=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})),Nl=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?.()??{}}})),Pl=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=Nl();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}})),Fl=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,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}})),Il=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,{getVercelOidcToken:()=>p}),n.exports=l(u);var d=Pl(),f=Fl();async function p(t){let n=``,r;try{n=(0,d.getVercelOidcTokenSync)()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await Promise.resolve().then(()=>e(Vl())),await import(`../../_chunks/workflow/token-DV7rQw_t.js`).then(t=>e(t.default))]);(!n||i(r(n),t?.expirationBufferMs))&&(await a(t),n=(0,d.getVercelOidcTokenSync)())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
106
+ ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}})),Ll=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:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}}})),Rl=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(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 s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{findRootDir:()=>v,getUserDataDir:()=>y}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=d(t(`os`)),_=Fl();function v(){try{let e=process.cwd();for(;e!==m.default.dirname(e);){let t=m.default.join(e,`.vercel`);if(h.default.existsSync(t))return e;e=m.default.dirname(e)}}catch{throw new _.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function y(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(g.default.platform()){case`darwin`:return m.default.join(g.default.homedir(),`Library/Application Support`);case`linux`:return m.default.join(g.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}})),zl=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(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 s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{isValidAccessToken:()=>b,readAuthConfig:()=>v,writeAuthConfig:()=>y}),n.exports=f(p);var m=d(t(`fs`)),h=d(t(`path`)),g=Vl();function _(){let e=(0,g.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(e,`auth.json`)}function v(){try{let e=_();if(!m.existsSync(e))return null;let t=m.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function y(e){let t=_(),n=h.dirname(t);m.existsSync(n)||m.mkdirSync(n,{mode:504,recursive:!0}),m.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function b(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}})),Bl=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),u={};s(u,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),n.exports=l(u);var d=t(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}})),Vl=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(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 s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>T,getTokenPayload:()=>O,getVercelDataDir:()=>x,getVercelOidcToken:()=>C,getVercelToken:()=>S,isExpired:()=>k,loadToken:()=>D,saveToken:()=>E}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=Fl(),_=Rl(),v=zl(),y=Bl(),b=Ll();function x(){let e=(0,_.getUserDataDir)();return e?m.join(e,`com.vercel.cli`):null}async function S(e){let t=(0,v.readAuthConfig)();if(!t?.token)throw new b.AccessTokenMissingError;if((0,v.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,v.writeAuthConfig)({}),new b.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,y.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,y.processTokenResponse)(e);if(n||!r)throw(0,v.writeAuthConfig)({}),new b.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,v.writeAuthConfig)(i),i.token}catch(e){throw(0,v.writeAuthConfig)({}),e instanceof b.AccessTokenMissingError||e instanceof b.RefreshAccessTokenFailedError?e:new b.RefreshAccessTokenFailedError(e)}}async function C(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new g.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return w(a),a}function w(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function T(){let e=(0,_.findRootDir)();if(!e)throw new g.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=m.join(e,`.vercel`,`project.json`);if(!h.existsSync(t))throw new g.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(h.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function E(e,t){let n=(0,_.getUserDataDir)();if(!n)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=m.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);h.mkdirSync(m.dirname(r),{mode:504,recursive:!0}),h.writeFileSync(r,i),h.chmodSync(r,432)}function D(e){let t=(0,_.getUserDataDir)();if(!t)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=m.join(t,`com.vercel.token`,`${e}.json`);if(!h.existsSync(n))return null;let r=JSON.parse(h.readFileSync(n,`utf8`));return w(r),r}function O(e){let t=e.split(`.`);if(t.length!==3)throw new g.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function k(e,t=0){return e.exp*1e3<Date.now()+t}})),Hl=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:()=>p.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>p.RefreshAccessTokenFailedError,getContext:()=>f.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>d.getVercelOidcTokenSync,getVercelToken:()=>m.getVercelToken}),t.exports=c(l);var u=Il(),d=Pl(),f=Nl(),p=Ll(),m=Vl()})),Ul=e(Ml(),1),Wl=Hl();async function Gl(e){let t=0,n=e.getReader(),r=[];try{for(;;){let{done:e,value:i}=await n.read();if(e)break;r.push(i),t+=i.length}}finally{n.releaseLock()}return Buffer.concat(r,t)}var Kl=class{contentType=`application/json`;replacer;reviver;constructor(e={}){this.replacer=e.replacer,this.reviver=e.reviver}serialize(e){return Buffer.from(JSON.stringify(e,this.replacer),`utf8`)}async deserialize(e){let t=await Gl(e);return JSON.parse(t.toString(`utf8`),this.reviver)}},ql=class extends Error{constructor(e){super(`Message ${e} not found`),this.name=`MessageNotFoundError`}},Jl=class extends Error{constructor(e,t){super(`Message ${e} not available for processing${t?`: ${t}`:``}`),this.name=`MessageNotAvailableError`}},Yl=class extends Error{constructor(e,t){super(`Message ${e} is corrupted: ${t}`),this.name=`MessageCorruptedError`}},Xl=class extends Error{constructor(e=`Missing or invalid authentication token`){super(e),this.name=`UnauthorizedError`}},Zl=class extends Error{constructor(e=`Queue environment doesn't match token environment`){super(e),this.name=`ForbiddenError`}},Ql=class extends Error{constructor(e){super(e),this.name=`BadRequestError`}},$l=class extends Error{constructor(e=`Unexpected server error`){super(e),this.name=`InternalServerError`}},eu=class extends Error{constructor(e,t=1,n=10){super(`Invalid limit: ${e}. Limit must be between ${t} and ${n}.`),this.name=`InvalidLimitError`}},tu=class extends Error{constructor(e){super(`Message ${e} has already been processed`),this.name=`MessageAlreadyProcessedError`}},nu=class extends Error{idempotencyKey;constructor(e,t){super(e),this.name=`DuplicateMessageError`,this.idempotencyKey=t}},ru=class extends Error{deploymentId;constructor(e,t){super(e),this.name=`ConsumerDiscoveryError`,this.deploymentId=t}},iu=class extends Error{constructor(e=`Consumer registry not configured`){super(e),this.name=`ConsumerRegistryNotConfiguredError`}},au=300,ou=30,su=60,cu=10,lu=3e3;function uu(e){return Math.min(su,Math.max(cu,e/5))}var du=class{client;topicName;consumerGroupName;visibilityTimeout;constructor(e,t,n,r={}){this.client=e,this.topicName=t,this.consumerGroupName=n,this.visibilityTimeout=Math.max(ou,r.visibilityTimeoutSeconds??au)}isClientError(e){return e instanceof Jl||e instanceof ql||e instanceof Ql||e instanceof Xl||e instanceof Zl}startVisibilityExtension(e,t){let n=!0,r=!1,i,a=null,o=uu(this.visibilityTimeout)*1e3,s=o;if(t?.visibilityDeadline){let e=t.visibilityDeadline.getTime()-Date.now();s=e>0?uu(e/1e3)*1e3:0}let c=new Promise(e=>{i=e}),l=()=>{r||(r=!0,i())},u=async()=>{if(!n){l();return}try{await this.client.changeVisibility({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e,visibilityTimeoutSeconds:this.visibilityTimeout}),n?a=setTimeout(()=>u(),o):l()}catch(t){if(this.isClientError(t)){console.error(`Visibility extension failed with client error for receipt handle ${e} (stopping retries):`,t),l();return}console.error(`Failed to extend visibility for receipt handle ${e} (will retry in ${lu/1e3}s):`,t),n?a=setTimeout(()=>u(),lu):l()}};return a=setTimeout(()=>u(),s),async(e=!1)=>{n=!1,a&&=(clearTimeout(a),null),e?await c:l()}}async finalizePayload(e){let t=this.client.getTransport();if(t.finalize&&e!=null)try{await t.finalize(e)}catch(e){console.warn(`Failed to finalize message payload:`,e)}}async processMessage(e,t,n){let r=this.startVisibilityExtension(e.receiptHandle,n),i={messageId:e.messageId,deliveryCount:e.deliveryCount,createdAt:e.createdAt,expiresAt:e.expiresAt??new Date(e.createdAt.getTime()+864e5),topicName:this.topicName,consumerGroup:this.consumerGroupName,region:this.client.getRegion()};try{await t(e.payload,i),await r(),await this.client.acknowledgeMessage({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e.receiptHandle})}catch(t){if(await r(),n?.retry){let r;try{r=n.retry(t,i)}catch(e){console.warn(`retry handler threw:`,e)}if(r){if(`acknowledge`in r&&r.acknowledge){try{await this.client.acknowledgeMessage({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e.receiptHandle})}catch(e){console.warn(`Failed to acknowledge message:`,e)}await this.finalizePayload(e.payload);return}if(`afterSeconds`in r&&typeof r.afterSeconds==`number`){try{await this.client.changeVisibility({queueName:this.topicName,consumerGroup:this.consumerGroupName,receiptHandle:e.receiptHandle,visibilityTimeoutSeconds:r.afterSeconds})}catch(e){console.warn(`Failed to reschedule message for retry:`,e)}await this.finalizePayload(e.payload);return}}}throw await this.finalizePayload(e.payload),t}}async consumeMessage(e,t,n){await this.processMessage(t,e,n)}async consume(e,t){let n=t?.retry;if(t&&`messageId`in t){let r=await this.client.receiveMessageById({queueName:this.topicName,consumerGroup:this.consumerGroupName,messageId:t.messageId,visibilityTimeoutSeconds:this.visibilityTimeout});return await this.processMessage(r.message,e,{retry:n}),1}else{let r=t&&`limit`in t?t.limit:1,i=0;for await(let t of this.client.receiveMessages({queueName:this.topicName,consumerGroup:this.consumerGroupName,visibilityTimeoutSeconds:this.visibilityTimeout,limit:r}))i++,await this.processMessage(t,e,{retry:n});return i}}get name(){return this.consumerGroupName}get topic(){return this.topicName}},fu=class{client;topicName;constructor(e,t){this.client=e,this.topicName=t}async publish(e,t){let n=await this.client.sendMessage({queueName:this.topicName,payload:e,idempotencyKey:t?.idempotencyKey,retentionSeconds:t?.retentionSeconds,delaySeconds:t?.delaySeconds,headers:t?.headers});return n.messageId&&Du()&&pd(this.topicName,n.messageId,this.client.getRegion(),t?.delaySeconds,t?.retentionSeconds),{messageId:n.messageId}}consumerGroup(e,t){return new du(this.client,this.topicName,e,t)}get name(){return this.topicName}},pu=`com.vercel.queue.v1beta`,mu=`com.vercel.queue.v2beta`;function hu(e,t){let n=t.slice(0,-1);return e.startsWith(n)}function gu(e){return typeof e==`object`&&!!e}function _u(e,t){if(!t||!t.includes(`application/cloudevents+json`))throw Error(`Invalid content type: expected 'application/cloudevents+json'`);if(!gu(e)||!e.type||!e.source||!e.id||!gu(e.data))throw Error(`Invalid CloudEvent: missing required fields`);if(e.type!==`com.vercel.queue.v1beta`)throw Error(`Invalid CloudEvent type: expected '${pu}', got '${String(e.type)}'`);let{data:n}=e,r=[];if(`queueName`in n||r.push(`queueName`),`consumerGroup`in n||r.push(`consumerGroup`),`messageId`in n||r.push(`messageId`),r.length>0)throw Error(`Missing required CloudEvent data fields: ${r.join(`, `)}`);return{queueName:String(n.queueName),consumerGroup:String(n.consumerGroup),messageId:String(n.messageId)}}function vu(e,t){if(e instanceof Headers)return e.get(t);let n=e[t];return Array.isArray(n)?n[0]??null:n??null}function yu(e){let t=vu(e,`ce-type`);if(t!==`com.vercel.queue.v2beta`)throw Error(`Invalid CloudEvent type: expected '${mu}', got '${t}'`);let n=vu(e,`ce-vqsqueuename`),r=vu(e,`ce-vqsconsumergroup`),i=vu(e,`ce-vqsmessageid`),a=[];if(n||a.push(`ce-vqsqueuename`),r||a.push(`ce-vqsconsumergroup`),i||a.push(`ce-vqsmessageid`),a.length>0)throw Error(`Missing required CloudEvent headers: ${a.join(`, `)}`);let o={queueName:n,consumerGroup:r,messageId:i,region:vu(e,`ce-vqsregion`)??void 0},s=vu(e,`ce-vqsreceipthandle`);if(!s)return o;let c={...o,receiptHandle:s},l=vu(e,`ce-vqsdeliverycount`);l&&(c.deliveryCount=parseInt(l,10));let u=vu(e,`ce-vqscreatedat`);u&&(c.createdAt=u);let d=vu(e,`ce-vqsexpiresat`);d&&(c.expiresAt=d);let f=vu(e,`content-type`);f&&(c.contentType=f);let p=vu(e,`ce-vqsvisibilitydeadline`);return p&&(c.visibilityDeadline=p),c}function bu(e,t){if(vu(t,`ce-type`)===`com.vercel.queue.v2beta`){let n=yu(t);return`receiptHandle`in n&&(n.parsedPayload=e),n}return _u(e,vu(t,`content-type`))}async function xu(e){if(e.headers.get(`ce-type`)===`com.vercel.queue.v2beta`){let t=yu(e.headers);return`receiptHandle`in t&&e.body&&(t.rawBody=e.body),t}let t;try{t=await e.json()}catch{throw Error(`Failed to parse CloudEvent from request body`)}let n={};return e.headers.forEach((e,t)=>{n[t]=e}),bu(t,n)}async function Su(e,t,n){let{queueName:r,consumerGroup:i,messageId:a}=t;if(!n?.client)throw Error(`HandleCallbackOptions.client is required`);let o=Od(n.client);t.region&&(o=o.withRegion(t.region));let s=new fu(o,r).consumerGroup(i,n?.visibilityTimeoutSeconds===void 0?void 0:{visibilityTimeoutSeconds:n.visibilityTimeoutSeconds});if(`receiptHandle`in t){let r=o.getTransport(),i;if(t.rawBody)i=await r.deserialize(t.rawBody);else if(t.parsedPayload!==void 0)i=t.parsedPayload;else throw Error(`Binary mode callback with receipt handle is missing payload`);let c={messageId:a,payload:i,deliveryCount:t.deliveryCount??1,createdAt:t.createdAt?new Date(t.createdAt):new Date,expiresAt:t.expiresAt?new Date(t.expiresAt):void 0,contentType:t.contentType??r.contentType,receiptHandle:t.receiptHandle},l=t.visibilityDeadline?new Date(t.visibilityDeadline):void 0;await s.consumeMessage(e,c,{visibilityDeadline:l,retry:n?.retry})}else await s.consume(e,{messageId:a,retry:n?.retry})}var Cu=Ul.default.cyan(`[queue]`),wu=Ul.default.green(`✓`),Tu=Ul.default.red(`✗`),Eu=Ul.default.yellow(`↻`);function Du(){return process.env.NODE_ENV===`development`}var Ou=Symbol.for(`@vercel/queue.devRouteMappings`);function ku(e){let t=``;for(let n of e)n===`_`?t+=`__`:n===`/`?t+=`_S`:n===`.`?t+=`_D`:/[A-Za-z0-9-]/.test(n)?t+=n:t+=`_`+n.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`);return t}function Au(){let e=globalThis;if(Ou in e)return e[Ou]??null;try{let t=Vn.join(process.cwd(),`vercel.json`);if(!Hn.existsSync(t))return e[Ou]=null,null;let n=JSON.parse(Hn.readFileSync(t,`utf-8`));if(!n.functions)return e[Ou]=null,null;let r=[];for(let[e,t]of Object.entries(n.functions))if(t.experimentalTriggers){for(let n of t.experimentalTriggers)if(!(!n.type?.startsWith(`queue/`)||!n.topic)){if(n.type!==`queue/v2beta`){console.warn(`${Cu} Unsupported trigger type "${n.type}" for topic "${n.topic}" in ${e}. Use "queue/v2beta" instead.`);continue}r.push({filePath:e,topic:n.topic,consumer:ku(e),retryAfterSeconds:n.retryAfterSeconds})}}return e[Ou]=r.length>0?r:null,e[Ou]}catch(t){return console.warn(`${Cu} Failed to read vercel.json:`,t),e[Ou]=null,null}}function ju(e){let t=Au();return t?t.filter(t=>t.topic.includes(`*`)?hu(e,t.topic):t.topic===e):[]}function Mu(e,t){return ju(e).find(e=>e.consumer===t)?.retryAfterSeconds}function Nu(e){return/^src\/(app|pages|server)\//.test(e)?e.slice(4):null}function Pu(e,t){return e===t||rl(e,t)}function Fu(e){let t=Au();if(!t)return[];let n=process.cwd(),r;try{r=Vn.relative(n,e)}catch{return[]}let i=r.replace(/\\/g,`/`),a=Nu(i);return t.filter(e=>Pu(i,e.filePath)||a!==null&&Pu(a,e.filePath))}function Iu(e){let t=e.match(/\((.+?):\d+:\d+\)/);if(t||=e.match(/at\s+(.+?):\d+:\d+/),!t)return null;let n=t[1].trim();if(n===`native`||n.startsWith(`node:`)||n.startsWith(`internal`))return null;if(n.startsWith(`file://`))try{n=new URL(n).pathname}catch{return null}return/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)?null:(n.startsWith(`./`)&&(n=n.slice(2)),n)}var Lu;function Ru(){if(Lu)return Lu;try{let e=typeof __dirname<`u`?__dirname:Vn.dirname(new URL(import.meta.url).pathname);Lu=Vn.resolve(e,`..`)}catch{Lu=``}return Lu}function zu(){let e=Error().stack;if(!e)return null;let t=e.split(`
107
+ `).slice(1),n=Ru();for(let e of t){let t=Iu(e);if(!t)continue;let r=Vn.isAbsolute(t)?t:Vn.resolve(process.cwd(),t),i;try{i=Hn.realpathSync(r)}catch{i=r}if(!(n&&i.startsWith(n)))return i}return null}var Bu=Symbol.for(`@vercel/queue.devHandlerRegistry`);function Vu(){let e=globalThis;return e[Bu]||(e[Bu]=new Map),e[Bu]}function Hu(e,t,n,r){let i=Fu(Vn.isAbsolute(e)?e:Vn.resolve(process.cwd(),e));if(i.length===0)return!1;let a=Vu();for(let e of i){let i=e.topic,o=a.get(i)??[],s={consumerGroup:e.consumer,handler:t,client:n,options:r},c=o.findIndex(t=>t.consumerGroup===e.consumer);c>=0?o[c]=s:o.push(s),a.set(i,o)}return!0}function Uu(e,t,n,r){let i=r??zu();if(!i){console.warn(`${Cu} Could not determine caller file path for handler registration.`);return}if(!Hu(i,e,t,n)){let e=Au();if(e&&e.length>0)return;let t=process.cwd(),n;try{n=Vn.relative(t,i).replace(/\\/g,`/`)}catch{n=i}console.warn(`${Cu} handleCallback() in ${n} has no matching experimentalTriggers in vercel.json. This handler won't receive messages.
108
108
 
109
109
  Add a trigger to vercel.json:
110
110
  "${n}": {
111
111
  "experimentalTriggers": [{ "type": "queue/v2beta", "topic": "your-topic" }]
112
- }`)}}function Uu(e){let t=Bu(),n=[];for(let[r,i]of t)(r.includes(`*`)?mu(e,r):r===e)&&n.push(...i);return n}var Wu=50,Gu=5e3,Ku=2,qu=250,Ju=[`PORT`,`NEXT_PORT`,`NEXTJS_PORT`,`NUXT_PORT`,`NITRO_PORT`,`SVELTEKIT_PORT`,`VITE_PORT`,`DEV_PORT`,`npm_config_port`],Yu=[`__NEXT_PRIVATE_ORIGIN`,`NUXT_PUBLIC_SITE_URL`,`URL`];function Xu(e){return e instanceof Error?e.message:String(e)}function Zu(e){return e instanceof Kl||e instanceof Error&&e.name===`MessageNotFoundError`}function Qu(e){if(!e)return null;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<1||t>65535?null:t}function $u(e){if(!e)return null;try{let t=new URL(e).port;return Qu(t)}catch{return null}}function ed(){let e=[],t=new Set,n=n=>{n&&!t.has(n)&&(t.add(n),e.push(n))};for(let e of Ju)n(Qu(process.env[e]));for(let e of Yu)n($u(process.env[e]));return e}function td(e){return new Promise(t=>{let n=Un.connect({host:`localhost`,port:e}),r=!1,i=e=>{r||(r=!0,n.destroy(),t(e))};n.once(`connect`,()=>i(!0)),n.once(`error`,()=>i(!1)),n.setTimeout(qu,()=>i(!1))})}async function nd(e,t,n){let r=0,i=Wu;for(;;)try{await xu(e,t,n);return}catch(e){if(Zu(e)&&r<Gu){await new Promise(e=>setTimeout(e,i)),r+=i,i=Math.min(i*Ku,Gu-r);continue}throw e}}function rd(e){let t=e.replace(/^src\/app\//,`/`).replace(/^src\/pages\//,`/`).replace(/^src\/server\//,`/`).replace(/^src\/routes\//,`/`).replace(/^app\//,`/`).replace(/^pages\//,`/`).replace(/^server\//,`/`).replace(/\/route\.(ts|mts|js|mjs|tsx|jsx)$/,``).replace(/\/\+server\.(ts|mts|js|mjs|tsx|jsx)$/,``).replace(/\.(ts|mts|js|mjs|tsx|jsx)$/,``);return t.startsWith(`/`)||(t=`/`+t),t}async function id(e,t={}){let n={triedPorts:ed(),listeningPorts:[],unavailablePorts:[],importFailures:[],primeFailures:[]},r=Au(e);if(r.length===0)return n;let i=t.refreshRegistered===!0;for(let e of n.triedPorts)await td(e)?n.listeningPorts.push(e):n.unavailablePorts.push(e);for(let t of r){let r=od(e,t.consumer);if(!(r&&!i)){if(!r){let r=Vn.resolve(process.cwd(),t.filePath);try{await import(r)}catch(e){n.importFailures.push({filePath:t.filePath,reason:Xu(e)})}if(od(e,t.consumer))continue}for(let r of n.listeningPorts){let i=`http://localhost:${r}${rd(t.filePath)}`;try{let r=await fetch(i,{method:`POST`,headers:{"x-vercel-queue-prime":`1`,"x-vercel-queue-prime-file":t.filePath}});try{await r.text()}catch{}if(od(e,t.consumer))break;n.primeFailures.push({filePath:t.filePath,url:i,reason:`HTTP ${r.status}${r.statusText?` ${r.statusText}`:``}`.trim()})}catch(e){n.primeFailures.push({filePath:t.filePath,url:i,reason:Xu(e)})}}}}return n}function ad(e,t,n){let r=t.map(e=>e.filePath),i=n.listeningPorts[0]??n.triedPorts[0],a=i?t.map(e=>`http://localhost:${i}${rd(e.filePath)}`):[],o;if(n.triedPorts.length===0)o=`No local dev port detected from env. Set PORT (or NEXT_PORT/NUXT_PORT/VITE_PORT).`;else if(n.listeningPorts.length===0)o=`Detected env ports: [${n.triedPorts.join(`, `)}], but none are listening.`;else{let e=n.unavailablePorts.length>0?` Not listening: [${n.unavailablePorts.join(`, `)}].`:``;o=`Detected env ports: [${n.triedPorts.join(`, `)}]. Listening: [${n.listeningPorts.join(`, `)}].`+e}let s=n.importFailures.length>0?`
112
+ }`)}}function Wu(e){let t=Vu(),n=[];for(let[r,i]of t)(r.includes(`*`)?hu(e,r):r===e)&&n.push(...i);return n}var Gu=50,Ku=5e3,qu=2,Ju=250,Yu=[`PORT`,`NEXT_PORT`,`NEXTJS_PORT`,`NUXT_PORT`,`NITRO_PORT`,`SVELTEKIT_PORT`,`VITE_PORT`,`DEV_PORT`,`npm_config_port`],Xu=[`__NEXT_PRIVATE_ORIGIN`,`NUXT_PUBLIC_SITE_URL`,`URL`];function Zu(e){return e instanceof Error?e.message:String(e)}function Qu(e){return e instanceof ql||e instanceof Error&&e.name===`MessageNotFoundError`}function $u(e){if(!e)return null;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<1||t>65535?null:t}function ed(e){if(!e)return null;try{let t=new URL(e).port;return $u(t)}catch{return null}}function td(){let e=[],t=new Set,n=n=>{n&&!t.has(n)&&(t.add(n),e.push(n))};for(let e of Yu)n($u(process.env[e]));for(let e of Xu)n(ed(process.env[e]));return e}function nd(e){return new Promise(t=>{let n=Un.connect({host:`localhost`,port:e}),r=!1,i=e=>{r||(r=!0,n.destroy(),t(e))};n.once(`connect`,()=>i(!0)),n.once(`error`,()=>i(!1)),n.setTimeout(Ju,()=>i(!1))})}async function rd(e,t,n){let r=0,i=Gu;for(;;)try{await Su(e,t,n);return}catch(e){if(Qu(e)&&r<Ku){await new Promise(e=>setTimeout(e,i)),r+=i,i=Math.min(i*qu,Ku-r);continue}throw e}}function id(e){let t=e.replace(/^src\/app\//,`/`).replace(/^src\/pages\//,`/`).replace(/^src\/server\//,`/`).replace(/^src\/routes\//,`/`).replace(/^app\//,`/`).replace(/^pages\//,`/`).replace(/^server\//,`/`).replace(/\/route\.(ts|mts|js|mjs|tsx|jsx)$/,``).replace(/\/\+server\.(ts|mts|js|mjs|tsx|jsx)$/,``).replace(/\.(ts|mts|js|mjs|tsx|jsx)$/,``);return t.startsWith(`/`)||(t=`/`+t),t}async function ad(e,t={}){let n={triedPorts:td(),listeningPorts:[],unavailablePorts:[],importFailures:[],primeFailures:[]},r=ju(e);if(r.length===0)return n;let i=t.refreshRegistered===!0;for(let e of n.triedPorts)await nd(e)?n.listeningPorts.push(e):n.unavailablePorts.push(e);for(let t of r){let r=sd(e,t.consumer);if(!(r&&!i)){if(!r){let r=Vn.resolve(process.cwd(),t.filePath);try{await import(r)}catch(e){n.importFailures.push({filePath:t.filePath,reason:Zu(e)})}if(sd(e,t.consumer))continue}for(let r of n.listeningPorts){let i=`http://localhost:${r}${id(t.filePath)}`;try{let r=await fetch(i,{method:`POST`,headers:{"x-vercel-queue-prime":`1`,"x-vercel-queue-prime-file":t.filePath}});try{await r.text()}catch{}if(sd(e,t.consumer))break;n.primeFailures.push({filePath:t.filePath,url:i,reason:`HTTP ${r.status}${r.statusText?` ${r.statusText}`:``}`.trim()})}catch(e){n.primeFailures.push({filePath:t.filePath,url:i,reason:Zu(e)})}}}}return n}function od(e,t,n){let r=t.map(e=>e.filePath),i=n.listeningPorts[0]??n.triedPorts[0],a=i?t.map(e=>`http://localhost:${i}${id(e.filePath)}`):[],o;if(n.triedPorts.length===0)o=`No local dev port detected from env. Set PORT (or NEXT_PORT/NUXT_PORT/VITE_PORT).`;else if(n.listeningPorts.length===0)o=`Detected env ports: [${n.triedPorts.join(`, `)}], but none are listening.`;else{let e=n.unavailablePorts.length>0?` Not listening: [${n.unavailablePorts.join(`, `)}].`:``;o=`Detected env ports: [${n.triedPorts.join(`, `)}]. Listening: [${n.listeningPorts.join(`, `)}].`+e}let s=n.importFailures.length>0?`
113
113
  Import failures: `+n.importFailures.slice(0,2).map(e=>`${e.filePath} (${e.reason})`).join(`; `):``,c=n.primeFailures.length>0?`
114
- Prime failures: `+n.primeFailures.slice(0,3).map(e=>`${e.url} (${e.reason})`).join(`; `):``;return`${Su} No registered handler for topic "${e}". vercel.json maps this topic to [${r.join(`, `)}] but auto-loading failed.
114
+ Prime failures: `+n.primeFailures.slice(0,3).map(e=>`${e.url} (${e.reason})`).join(`; `):``;return`${Cu} No registered handler for topic "${e}". vercel.json maps this topic to [${r.join(`, `)}] but auto-loading failed.
115
115
  ${o}${s}${c}
116
116
  Ensure your dev server is running, set PORT if needed, and confirm mapped route files call handleCallback()/handleNodeCallback() at module scope.
117
- `+(a.length>0?`Try opening: ${a.join(` or `)}`:`Set PORT (or NEXT_PORT/NUXT_PORT/VITE_PORT) and try sending again.`)}function od(e,t){return Uu(e).some(e=>e.consumerGroup===t)}var sd=10,cd=2,ld=10,ud=86400;function dd(e,t){let n=Math.min(Math.max(t,0),sd);console.log(`${Su} ${Tu} Scheduling re-delivery in ${n}s: topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}"`),setTimeout(async()=>{let t=e.deliveryCount+1,n=new Date(e.createdAt.getTime()+e.retentionSeconds*1e3);if(Date.now()>=n.getTime()){console.log(`${Su} Message expired, stopping retries: topic="${e.topicName}" messageId="${e.messageId}"`);return}if(t>ld){console.log(`${Su} Max re-deliveries (${ld}) reached: topic="${e.topicName}" messageId="${e.messageId}"`);return}let r={messageId:e.messageId,deliveryCount:t,createdAt:e.createdAt,expiresAt:n,topicName:e.topicName,consumerGroup:e.consumerGroup,region:e.region};console.log(`${Su} Re-delivering: topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}" deliveryCount=${t}`);let i=!0,a=null,o=!1;try{await e.handler(e.payload,r)}catch(t){if(i=!1,e.retry){let n;try{n=e.retry(t,r)}catch(e){console.warn(`${Su} retry handler threw:`,e)}n&&`afterSeconds`in n?a=n.afterSeconds:n&&`acknowledge`in n&&(o=!0)}o||console.error(`${Su} ${wu} Handler error on re-delivery: topic="${e.topicName}" messageId="${e.messageId}"`,t)}if(i)console.log(`${Su} ${Cu} Message processed on re-delivery: topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}"`);else if(o)console.log(`${Su} ${Cu} Message acknowledged (will not retry): topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}"`);else{let n=a??e.defaultRetryDelayS;dd({...e,deliveryCount:t},n)}},n*1e3)}function fd(e,t,n,r,i){if(r&&r>0){console.log(`${Su} Message sent with delay: topic="${e}" messageId="${t}" delay=${r}s`),setTimeout(()=>{fd(e,t,n,void 0,i)},r*1e3);return}console.log(`${Su} Message sent: topic="${e}" messageId="${t}"`),(async()=>{let r=Uu(e),a=null;if(r.length>0?(await id(e,{refreshRegistered:!0}),r=Uu(e)):(a=await id(e),r=Uu(e)),r.length===0){let t=Au(e);if(t.length>0){let n=a??{triedPorts:ed(),listeningPorts:[],unavailablePorts:[],importFailures:[],primeFailures:[]};console.warn(ad(e,t,n))}else console.warn(`${Su} No registered handler for topic "${e}".
118
- Ensure vercel.json has a matching experimentalTriggers entry and the route file calls handleCallback().`);return}let o=r.map(e=>e.consumerGroup);console.log(`${Su} Invoking handlers for topic="${e}" messageId="${t}" \u2192 consumers: [${o.join(`, `)}]`);let s=i??ud;for(let i of r){let r,a=new Date,o=1,c=!0,l=null,u=!1,d=async(e,t)=>{r=e,a=t.createdAt,o=t.deliveryCount;try{await i.handler(e,t)}catch(e){throw c=!1,e}},f=i.options?.retry?(e,t)=>{let n=i.options.retry(e,t);return n&&`afterSeconds`in n?l=n.afterSeconds:n&&`acknowledge`in n&&(u=!0),n}:void 0,p={queueName:e,consumerGroup:i.consumerGroup,messageId:t,region:n},m={client:i.client,visibilityTimeoutSeconds:i.options?.visibilityTimeoutSeconds,retry:f},h=Math.min(ju(e,i.consumerGroup)??cd,sd),g=()=>({handler:i.handler,retry:i.options?.retry,payload:r,topicName:e,consumerGroup:i.consumerGroup,messageId:t,region:n,createdAt:a,retentionSeconds:s,deliveryCount:o,defaultRetryDelayS:h});try{if(await nd(d,p,m),c)console.log(`${Su} ${Cu} Message processed: topic="${e}" consumer="${i.consumerGroup}" messageId="${t}"`);else if(u)console.log(`${Su} ${Cu} Message acknowledged (will not retry): topic="${e}" consumer="${i.consumerGroup}" messageId="${t}"`);else if(l!==null){let e=Math.min(l,sd);dd(g(),e)}}catch(n){console.error(`${Su} ${wu} Handler failed: topic="${e}" consumer="${i.consumerGroup}" messageId="${t}"`,n),c||dd(g(),h)}}})()}function pd(){let e=globalThis;delete e[Du],delete e[zu]}(process.env.NODE_ENV===`test`||process.env.VITEST)&&(globalThis.__clearDevState=pd,globalThis.__filePathToConsumerGroup=Ou,globalThis.__filePathToUrlPath=rd,globalThis.__matchesFunctionsPattern=Nu,globalThis.__stripSrcPrefix=Mu);function md(){return process.env.VERCEL_QUEUE_DEBUG===`1`||process.env.VERCEL_QUEUE_DEBUG===`true`}async function hd(e){let t=e.getReader();try{for(;;){let{done:e}=await t.read();if(e)break}}finally{t.releaseLock()}}function gd(e,t,n,r,i=`Invalid parameters`){throw e===400?new Zl(n||i):e===401?new Yl(n||void 0):e===403?new Xl(n||void 0):e>=500?new Ql(n||`Server error: ${e} ${t}`):Error(`Failed to ${r}: ${e} ${t}`)}function _d(e){let t=e.get(`Vqs-Message-Id`),n=e.get(`Vqs-Delivery-Count`)||`0`,r=e.get(`Vqs-Timestamp`),i=e.get(`Content-Type`)||`application/octet-stream`,a=e.get(`Vqs-Receipt-Handle`),o=e.get(`Vqs-Expires-At`);if(!t||!r||!a)return null;let s=parseInt(n,10);return Number.isNaN(s)?null:{messageId:t,deliveryCount:s,createdAt:new Date(r),expiresAt:o?new Date(o):void 0,contentType:i,receiptHandle:a}}var vd=e=>new URL(`https://${e}.vercel-queue.com`);function yd(e,t){return(t??vd)(e)}var bd=`/api/v3/topic`,xd=class e{baseUrl;customHeaders;providedToken;resolvedDeploymentId;pinSends;explicitlyUnpinned;transport;region;baseUrlResolver;dispatcher;constructor(e){this.region=e.region,this.baseUrlResolver=e.resolveBaseUrl,this.baseUrl=yd(this.region,this.baseUrlResolver),this.customHeaders=e.headers||{},this.providedToken=e.token,this.transport=e.transport||new Gl,this.dispatcher=e.dispatcher,e.deploymentId===null?(this.pinSends=!1,this.explicitlyUnpinned=!0):(this.resolvedDeploymentId=e.deploymentId||process.env.VERCEL_DEPLOYMENT_ID,this.pinSends=!0,this.explicitlyUnpinned=!1)}withRegion(t){return new e({region:t,resolveBaseUrl:this.baseUrlResolver,token:this.providedToken,headers:{...this.customHeaders},deploymentId:this.explicitlyUnpinned?null:this.resolvedDeploymentId,transport:this.transport,dispatcher:this.dispatcher})}getRegion(){return this.region}getTransport(){return this.transport}requireDeploymentId(){if(!(Eu()||this.explicitlyUnpinned||this.resolvedDeploymentId))throw Error(`No deployment ID available. VERCEL_DEPLOYMENT_ID is not set.
117
+ `+(a.length>0?`Try opening: ${a.join(` or `)}`:`Set PORT (or NEXT_PORT/NUXT_PORT/VITE_PORT) and try sending again.`)}function sd(e,t){return Wu(e).some(e=>e.consumerGroup===t)}var cd=10,ld=2,ud=10,dd=86400;function fd(e,t){let n=Math.min(Math.max(t,0),cd);console.log(`${Cu} ${Eu} Scheduling re-delivery in ${n}s: topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}"`),setTimeout(async()=>{let t=e.deliveryCount+1,n=new Date(e.createdAt.getTime()+e.retentionSeconds*1e3);if(Date.now()>=n.getTime()){console.log(`${Cu} Message expired, stopping retries: topic="${e.topicName}" messageId="${e.messageId}"`);return}if(t>ud){console.log(`${Cu} Max re-deliveries (${ud}) reached: topic="${e.topicName}" messageId="${e.messageId}"`);return}let r={messageId:e.messageId,deliveryCount:t,createdAt:e.createdAt,expiresAt:n,topicName:e.topicName,consumerGroup:e.consumerGroup,region:e.region};console.log(`${Cu} Re-delivering: topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}" deliveryCount=${t}`);let i=!0,a=null,o=!1;try{await e.handler(e.payload,r)}catch(t){if(i=!1,e.retry){let n;try{n=e.retry(t,r)}catch(e){console.warn(`${Cu} retry handler threw:`,e)}n&&`afterSeconds`in n?a=n.afterSeconds:n&&`acknowledge`in n&&(o=!0)}o||console.error(`${Cu} ${Tu} Handler error on re-delivery: topic="${e.topicName}" messageId="${e.messageId}"`,t)}if(i)console.log(`${Cu} ${wu} Message processed on re-delivery: topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}"`);else if(o)console.log(`${Cu} ${wu} Message acknowledged (will not retry): topic="${e.topicName}" consumer="${e.consumerGroup}" messageId="${e.messageId}"`);else{let n=a??e.defaultRetryDelayS;fd({...e,deliveryCount:t},n)}},n*1e3)}function pd(e,t,n,r,i){if(r&&r>0){console.log(`${Cu} Message sent with delay: topic="${e}" messageId="${t}" delay=${r}s`),setTimeout(()=>{pd(e,t,n,void 0,i)},r*1e3);return}console.log(`${Cu} Message sent: topic="${e}" messageId="${t}"`),(async()=>{let r=Wu(e),a=null;if(r.length>0?(await ad(e,{refreshRegistered:!0}),r=Wu(e)):(a=await ad(e),r=Wu(e)),r.length===0){let t=ju(e);if(t.length>0){let n=a??{triedPorts:td(),listeningPorts:[],unavailablePorts:[],importFailures:[],primeFailures:[]};console.warn(od(e,t,n))}else console.warn(`${Cu} No registered handler for topic "${e}".
118
+ Ensure vercel.json has a matching experimentalTriggers entry and the route file calls handleCallback().`);return}let o=r.map(e=>e.consumerGroup);console.log(`${Cu} Invoking handlers for topic="${e}" messageId="${t}" \u2192 consumers: [${o.join(`, `)}]`);let s=i??dd;for(let i of r){let r,a=new Date,o=1,c=!0,l=null,u=!1,d=async(e,t)=>{r=e,a=t.createdAt,o=t.deliveryCount;try{await i.handler(e,t)}catch(e){throw c=!1,e}},f=i.options?.retry?(e,t)=>{let n=i.options.retry(e,t);return n&&`afterSeconds`in n?l=n.afterSeconds:n&&`acknowledge`in n&&(u=!0),n}:void 0,p={queueName:e,consumerGroup:i.consumerGroup,messageId:t,region:n},m={client:i.client,visibilityTimeoutSeconds:i.options?.visibilityTimeoutSeconds,retry:f},h=Math.min(Mu(e,i.consumerGroup)??ld,cd),g=()=>({handler:i.handler,retry:i.options?.retry,payload:r,topicName:e,consumerGroup:i.consumerGroup,messageId:t,region:n,createdAt:a,retentionSeconds:s,deliveryCount:o,defaultRetryDelayS:h});try{if(await rd(d,p,m),c)console.log(`${Cu} ${wu} Message processed: topic="${e}" consumer="${i.consumerGroup}" messageId="${t}"`);else if(u)console.log(`${Cu} ${wu} Message acknowledged (will not retry): topic="${e}" consumer="${i.consumerGroup}" messageId="${t}"`);else if(l!==null){let e=Math.min(l,cd);fd(g(),e)}}catch(n){console.error(`${Cu} ${Tu} Handler failed: topic="${e}" consumer="${i.consumerGroup}" messageId="${t}"`,n),c||fd(g(),h)}}})()}function md(){let e=globalThis;delete e[Ou],delete e[Bu]}(process.env.NODE_ENV===`test`||process.env.VITEST)&&(globalThis.__clearDevState=md,globalThis.__filePathToConsumerGroup=ku,globalThis.__filePathToUrlPath=id,globalThis.__matchesFunctionsPattern=Pu,globalThis.__stripSrcPrefix=Nu);function hd(){return process.env.VERCEL_QUEUE_DEBUG===`1`||process.env.VERCEL_QUEUE_DEBUG===`true`}async function gd(e){let t=e.getReader();try{for(;;){let{done:e}=await t.read();if(e)break}}finally{t.releaseLock()}}function _d(e,t,n,r,i=`Invalid parameters`){throw e===400?new Ql(n||i):e===401?new Xl(n||void 0):e===403?new Zl(n||void 0):e>=500?new $l(n||`Server error: ${e} ${t}`):Error(`Failed to ${r}: ${e} ${t}`)}function vd(e){let t=e.get(`Vqs-Message-Id`),n=e.get(`Vqs-Delivery-Count`)||`0`,r=e.get(`Vqs-Timestamp`),i=e.get(`Content-Type`)||`application/octet-stream`,a=e.get(`Vqs-Receipt-Handle`),o=e.get(`Vqs-Expires-At`);if(!t||!r||!a)return null;let s=parseInt(n,10);return Number.isNaN(s)?null:{messageId:t,deliveryCount:s,createdAt:new Date(r),expiresAt:o?new Date(o):void 0,contentType:i,receiptHandle:a}}var yd=e=>new URL(`https://${e}.vercel-queue.com`);function bd(e,t){return(t??yd)(e)}var xd=`/api/v3/topic`,Sd=class e{baseUrl;customHeaders;providedToken;resolvedDeploymentId;pinSends;explicitlyUnpinned;transport;region;baseUrlResolver;dispatcher;constructor(e){this.region=e.region,this.baseUrlResolver=e.resolveBaseUrl,this.baseUrl=bd(this.region,this.baseUrlResolver),this.customHeaders=e.headers||{},this.providedToken=e.token,this.transport=e.transport||new Kl,this.dispatcher=e.dispatcher,e.deploymentId===null?(this.pinSends=!1,this.explicitlyUnpinned=!0):(this.resolvedDeploymentId=e.deploymentId||process.env.VERCEL_DEPLOYMENT_ID,this.pinSends=!0,this.explicitlyUnpinned=!1)}withRegion(t){return new e({region:t,resolveBaseUrl:this.baseUrlResolver,token:this.providedToken,headers:{...this.customHeaders},deploymentId:this.explicitlyUnpinned?null:this.resolvedDeploymentId,transport:this.transport,dispatcher:this.dispatcher})}getRegion(){return this.region}getTransport(){return this.transport}requireDeploymentId(){if(!(Du()||this.explicitlyUnpinned||this.resolvedDeploymentId))throw Error(`No deployment ID available. VERCEL_DEPLOYMENT_ID is not set.
119
119
 
120
120
  This usually means the code is running outside a Vercel deployment (e.g. during build or in a non-Vercel environment).
121
121
 
122
122
  To fix this, create a client with an explicit deploymentId:
123
123
  new QueueClient({ deploymentId: "dpl_xxx" })
124
124
  Or explicitly opt out of deployment pinning:
125
- new QueueClient({ deploymentId: null })`)}getSendDeploymentId(){if(!Eu())return this.requireDeploymentId(),this.pinSends?this.resolvedDeploymentId:void 0}getConsumeDeploymentId(){if(!Eu())return this.requireDeploymentId(),this.resolvedDeploymentId}async getToken(){if(this.providedToken)return this.providedToken;try{return await(0,Ul.getVercelOidcToken)()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(Eu()?`Failed to get OIDC token for local development.
125
+ new QueueClient({ deploymentId: null })`)}getSendDeploymentId(){if(!Du())return this.requireDeploymentId(),this.pinSends?this.resolvedDeploymentId:void 0}getConsumeDeploymentId(){if(!Du())return this.requireDeploymentId(),this.resolvedDeploymentId}async getToken(){if(this.providedToken)return this.providedToken;try{return await(0,Wl.getVercelOidcToken)()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(Du()?`Failed to get OIDC token for local development.
126
126
 
127
127
  To fix this, pull your environment variables with Vercel CLI:
128
128
  \`vercel env pull\`
@@ -133,9 +133,9 @@ To fix this, either:
133
133
  - Deploy to Vercel (OIDC tokens are provisioned automatically)
134
134
  - Provide a token explicitly: \`new QueueClient({ token: '...' })\`
135
135
 
136
- Cause: ${t}`)}}buildUrl(e,...t){let n=encodeURIComponent(e),r=t.map(e=>encodeURIComponent(e)),i=r.length>0?`/`+r.join(`/`):``,a=this.baseUrl.pathname.replace(/\/+$/,``);return`${this.baseUrl.origin}${a}${bd}/${n}${i}`}async fetch(e,t){let n=t.method||`GET`;if(md()){let r={method:n,url:e,headers:t.headers},i=t.body;i!=null&&(i instanceof ArrayBuffer||i instanceof Uint8Array?r.bodySize=i.byteLength:typeof i==`string`?r.bodySize=i.length:r.bodyType=typeof i),console.debug(`[VQS Debug] Request:`,JSON.stringify(r,null,2))}t.headers.set(`User-Agent`,`@vercel/queue/0.1.7`),t.headers.set(`Vqs-Client-Ts`,new Date().toISOString());let r=this.dispatcher?{...t,dispatcher:this.dispatcher}:t,i=await fetch(e,r);if(md()){let t={method:n,url:e,status:i.status,statusText:i.statusText,headers:i.headers};console.debug(`[VQS Debug] Response:`,JSON.stringify(t,null,2))}return i}async sendMessage(e){let t=this.transport,{queueName:n,payload:r,idempotencyKey:i,retentionSeconds:a,delaySeconds:o,headers:s}=e,c=new Headers;if(this.customHeaders)for(let[e,t]of Object.entries(this.customHeaders))c.append(e,t);if(s){let e=new Set([`authorization`,`content-type`]),t=t=>{let n=t.toLowerCase();return e.has(n)?!0:n.startsWith(`vqs-`)};for(let[e,n]of Object.entries(s))!t(e)&&n!==void 0&&c.append(e,n)}c.set(`Authorization`,`Bearer ${await this.getToken()}`),c.set(`Content-Type`,t.contentType);let l=this.getSendDeploymentId();l&&c.set(`Vqs-Deployment-Id`,l),i&&c.set(`Vqs-Idempotency-Key`,i),a!==void 0&&c.set(`Vqs-Retention-Seconds`,a.toString()),o!==void 0&&c.set(`Vqs-Delay-Seconds`,o.toString());let u=t.serialize(r),d=Buffer.isBuffer(u)?new Uint8Array(u):u,f=await this.fetch(this.buildUrl(n),{method:`POST`,body:d,headers:c});if(!f.ok){let e=await f.text();if(f.status===409)throw new tu(e||`Duplicate idempotency key detected`,i);if(f.status===502)throw new nu(e||`Consumer discovery failed`,l);if(f.status===503)throw new ru(e||`Consumer registry not configured`);gd(f.status,f.statusText,e,`send message`)}return f.status===202?{messageId:null}:await f.json()}async*receiveMessages(e){let t=this.transport,{queueName:n,consumerGroup:r,visibilityTimeoutSeconds:i,limit:a}=e;if(a!==void 0&&(a<1||a>10))throw new $l(a);let o=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:`multipart/mixed`,...this.customHeaders});i!==void 0&&o.set(`Vqs-Visibility-Timeout-Seconds`,i.toString()),a!==void 0&&o.set(`Vqs-Max-Messages`,a.toString());let s=this.getConsumeDeploymentId();s&&o.set(`Vqs-Deployment-Id`,s);let c=await this.fetch(this.buildUrl(n,`consumer`,r),{method:`POST`,headers:o});if(c.status!==204){if(!c.ok){let e=await c.text();gd(c.status,c.statusText,e,`receive messages`)}for await(let e of rc(c))try{let n=_d(e.headers);if(!n){console.warn(`Missing required queue headers in multipart part`),await hd(e.payload);continue}let r=await t.deserialize(e.payload);yield{...n,payload:r}}catch(t){console.warn(`Failed to process multipart message:`,t),await hd(e.payload)}}}async receiveMessageById(e){let t=this.transport,{queueName:n,consumerGroup:r,messageId:i,visibilityTimeoutSeconds:a}=e,o=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:`multipart/mixed`,...this.customHeaders});a!==void 0&&o.set(`Vqs-Visibility-Timeout-Seconds`,a.toString());let s=this.getConsumeDeploymentId();s&&o.set(`Vqs-Deployment-Id`,s);let c=await this.fetch(this.buildUrl(n,`consumer`,r,`id`,i),{method:`POST`,headers:o});if(!c.ok){let e=await c.text();if(c.status===404)throw new Kl(i);if(c.status===409){let t={};try{t=JSON.parse(e)}catch{}throw t.originalMessageId?new ql(i,`This message was a duplicate - use originalMessageId: ${t.originalMessageId}`):new ql(i)}if(c.status===410)throw new eu(i);gd(c.status,c.statusText,e,`receive message by ID`)}for await(let e of rc(c)){let n=_d(e.headers);if(!n)throw await hd(e.payload),new Jl(i,`Missing required queue headers in response`);let r=await t.deserialize(e.payload);return{message:{...n,payload:r}}}throw new Kl(i)}async acknowledgeMessage(e){let{queueName:t,consumerGroup:n,receiptHandle:r}=e,i=new Headers({Authorization:`Bearer ${await this.getToken()}`,...this.customHeaders}),a=this.getConsumeDeploymentId();a&&i.set(`Vqs-Deployment-Id`,a);let o=await this.fetch(this.buildUrl(t,`consumer`,n,`lease`,r),{method:`DELETE`,headers:i});if(!o.ok){let e=await o.text();if(o.status===404)throw new Kl(r);if(o.status===409)throw new ql(r,e||`Invalid receipt handle, message not in correct state, or already processed`);gd(o.status,o.statusText,e,`acknowledge message`,`Missing or invalid receipt handle`)}return{acknowledged:!0}}async changeVisibility(e){let{queueName:t,consumerGroup:n,receiptHandle:r,visibilityTimeoutSeconds:i}=e,a=new Headers({Authorization:`Bearer ${await this.getToken()}`,"Content-Type":`application/json`,...this.customHeaders}),o=this.getConsumeDeploymentId();o&&a.set(`Vqs-Deployment-Id`,o);let s=await this.fetch(this.buildUrl(t,`consumer`,n,`lease`,r),{method:`PATCH`,headers:a,body:JSON.stringify({visibilityTimeoutSeconds:i})});if(!s.ok){let e=await s.text();if(s.status===404)throw new Kl(r);if(s.status===409)throw new ql(r,e||`Invalid receipt handle, message not in correct state, or already processed`);gd(s.status,s.statusText,e,`change visibility`,`Missing receipt handle or invalid visibility timeout`)}return{success:!0}}},Sd=new WeakMap,Cd=Symbol.for(`@vercel/queue.apiClient`);function wd(e,t){Sd.set(e,t),Object.defineProperty(e,Cd,{value:t,writable:!1,enumerable:!1,configurable:!1})}function Td(e){let t=Sd.get(e);if(t)return t;let n=e[Cd];if(typeof n==`object`&&n){let t=n;return Sd.set(e,t),t}throw Error(`QueueClient not initialized. This may happen when multiple bundled copies of @vercel/queue are loaded in local dev.`)}function Ed(e){return`request`in e?e.request:e}function Dd(e){return Td(e)}var Od=`iad1`;function kd(e){return e||process.env.VERCEL_REGION||(Eu()||console.warn(`[QueueClient] Region not detected \u2014 defaulting to "${Od}". On Vercel this is set automatically via VERCEL_REGION. To silence this warning, pass region explicitly: new QueueClient({ region: "iad1" })`),Od)}var Ad=class{constructor(e={}){let t=kd(e.region);wd(this,new xd({...e,region:t}))}send=async(e,t,n)=>{let r=Td(this),i=await r.sendMessage({queueName:e,payload:t,idempotencyKey:n?.idempotencyKey,retentionSeconds:n?.retentionSeconds,delaySeconds:n?.delaySeconds,headers:n?.headers});return i.messageId&&Eu()&&fd(e,i.messageId,r.getRegion(),n?.delaySeconds,n?.retentionSeconds),{messageId:i.messageId}};handleCallback=(e,t)=>(Eu()&&Hu(e,this,t),async n=>{let r=Ed(n);if(Eu()&&r.headers.get(`x-vercel-queue-prime`)===`1`){let n=r.headers.get(`x-vercel-queue-prime-file`);return n&&Hu(e,this,t,n),Response.json({status:`primed`})}try{return await xu(e,await bu(r),{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),Response.json({status:`success`})}catch(e){return console.error(`Queue callback error:`,e),e instanceof Error&&(e.message.includes(`Invalid content type`)||e.message.includes(`Invalid CloudEvent`)||e.message.includes(`Missing required CloudEvent`)||e.message.includes(`Failed to parse CloudEvent`)||e.message.includes(`Binary mode callback`))?Response.json({error:e.message},{status:400}):Response.json({error:`Failed to process queue message`},{status:500})}});handleNodeCallback=(e,t)=>(Eu()&&Hu(e,this,t),async(n,r)=>{if(n.method!==`POST`){r.status(200).end();return}let i=n.headers[`x-vercel-queue-prime`];if(Eu()&&i===`1`){let i=n.headers[`x-vercel-queue-prime-file`],a=Array.isArray(i)?i[0]:i;a&&Hu(e,this,t,a),r.status(200).json({status:`primed`});return}try{await xu(e,yu(n.body,n.headers),{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),r.status(200).json({status:`success`})}catch(e){if(console.error(`Queue callback error:`,e),e instanceof Error&&(e.message.includes(`Invalid content type`)||e.message.includes(`Invalid CloudEvent`)||e.message.includes(`Missing required CloudEvent`)||e.message.includes(`Failed to parse CloudEvent`)||e.message.includes(`Binary mode callback`))){r.status(400).json({error:e.message});return}r.status(500).json({error:`Failed to process queue message`})}})};let jd;try{jd=new TextDecoder}catch{}let J,Md,Y=0;const Nd=[],Pd=57337,Fd={};let Id=11281e4,Ld=1681e4,Rd=Nd,zd=0,X={},Bd,Vd,Hd=0,Ud=0,Wd,Gd,Kd=[],qd=[],Jd,Yd,Xd,Zd={useRecords:!1,mapsAsObjects:!0},Qd=!1,$d=2;try{Function(``)}catch{$d=1/0}var ef=class e{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[t,n]of Object.entries(e.keyMap))this.mapKey.set(n,t)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let t=new Map;for(let[n,r]of Object.entries(e))t.set(this._keyMap.hasOwnProperty(n)?this._keyMap[n]:n,r);return t}decodeKeys(e){if(!this._keyMap||e.constructor.name!=`Map`)return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let t={};return e.forEach((e,n)=>t[af(this._mapKey.has(n)?this._mapKey.get(n):n)]=e),t}mapDecode(e,t){let n=this.decode(e);if(this._keyMap)switch(n.constructor.name){case`Array`:return n.map(e=>this.decodeKeys(e))}return n}decode(t,n){if(J)return kf(()=>(Af(),this?this.decode(t,n):e.prototype.decode.call(Zd,t,n)));Md=n>-1?n:t.length,Y=0,zd=0,Ud=0,Vd=null,Rd=Nd,Wd=null,J=t;try{Yd=t.dataView||=new DataView(t.buffer,t.byteOffset,t.byteLength)}catch(e){throw J=null,t instanceof Uint8Array?e:Error(`Source must be a Uint8Array or Buffer but was a `+(t&&typeof t==`object`?t.constructor.name:typeof t))}if(this instanceof e){if(X=this,Jd=this.sharedValues&&(this.pack?Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return Bd=this.structures,tf();(!Bd||Bd.length>0)&&(Bd=[])}else X=Zd,(!Bd||Bd.length>0)&&(Bd=[]),Jd=null;return tf()}decodeMultiple(e,t){let n,r=0;try{let i=e.length;Qd=!0;let a=this?this.decode(e,i):Mf.decode(e,i);if(t){if(t(a)===!1)return;for(;Y<i;)if(r=Y,t(tf())===!1)return}else{for(n=[a];Y<i;)r=Y,n.push(tf());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{Qd=!1,Af()}}};function tf(){try{let e=Z();if(Wd){if(Y>=Wd.postBundlePosition){let e=Error(`Unexpected bundle position`);throw e.incomplete=!0,e}Y=Wd.postBundlePosition,Wd=null}if(Y==Md)Bd=null,J=null,Gd&&=null;else if(Y>Md){let e=Error(`Unexpected end of CBOR data`);throw e.incomplete=!0,e}else if(!Qd)throw Error(`Data read, but end of buffer not reached`);return e}catch(e){throw Af(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`))&&(e.incomplete=!0),e}}function Z(){let e=J[Y++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=J[Y++];break;case 25:if(t==7)return hf();e=Yd.getUint16(Y),Y+=2;break;case 26:if(t==7){let e=Yd.getFloat32(Y);if(X.useFloat32>2){let t=jf[(J[Y]&127)<<1|J[Y+1]>>7];return Y+=4,(t*e+(e>0?.5:-.5)>>0)/t}return Y+=4,e}e=Yd.getUint32(Y),Y+=4;break;case 27:if(t==7){let e=Yd.getFloat64(Y);return Y+=8,e}if(t>1){if(Yd.getUint32(Y)>0)throw Error(`JavaScript does not support arrays, maps, or strings with length over 4294967295`);e=Yd.getUint32(Y+4)}else X.int64AsNumber?(e=Yd.getUint32(Y)*4294967296,e+=Yd.getUint32(Y+4)):e=Yd.getBigUint64(Y);Y+=8;break;case 31:switch(t){case 2:case 3:throw Error(`Indefinite length not supported for byte or text strings`);case 4:let e=[],n,r=0;for(;(n=Z())!=Fd;){if(r>=Id)throw Error(`Array length exceeds ${Id}`);e[r++]=n}return t==4?e:t==3?e.join(``):Buffer.concat(e);case 5:let i;if(X.mapsAsObjects){let e={},t=0;if(X.keyMap)for(;(i=Z())!=Fd;){if(t++>=Ld)throw Error(`Property count exceeds ${Ld}`);e[af(X.decodeKey(i))]=Z()}else for(;(i=Z())!=Fd;){if(t++>=Ld)throw Error(`Property count exceeds ${Ld}`);e[af(i)]=Z()}return e}else{Xd&&=(X.mapsAsObjects=!0,!1);let e=new Map;if(X.keyMap){let t=0;for(;(i=Z())!=Fd;){if(t++>=Ld)throw Error(`Map size exceeds ${Ld}`);e.set(X.decodeKey(i),Z())}}else{let t=0;for(;(i=Z())!=Fd;){if(t++>=Ld)throw Error(`Map size exceeds ${Ld}`);e.set(i,Z())}}return e}case 7:return Fd;default:throw Error(`Invalid major type for indefinite length `+t)}default:throw Error(`Unknown token `+e)}switch(t){case 0:return e;case 1:return~e;case 2:return ff(e);case 3:if(Ud>=Y)return Vd.slice(Y-Hd,(Y+=e)-Hd);if(Ud==0&&Md<140&&e<32){let t=e<16?df(e):uf(e);if(t!=null)return t}return of(e);case 4:if(e>=Id)throw Error(`Array length exceeds ${Id}`);let t=Array(e);for(let n=0;n<e;n++)t[n]=Z();return t;case 5:if(e>=Ld)throw Error(`Map size exceeds ${Id}`);if(X.mapsAsObjects){let t={};if(X.keyMap)for(let n=0;n<e;n++)t[af(X.decodeKey(Z()))]=Z();else for(let n=0;n<e;n++)t[af(Z())]=Z();return t}else{Xd&&=(X.mapsAsObjects=!0,!1);let t=new Map;if(X.keyMap)for(let n=0;n<e;n++)t.set(X.decodeKey(Z()),Z());else for(let n=0;n<e;n++)t.set(Z(),Z());return t}case 6:if(e>=Pd){let t=Bd[e&8191];if(t)return t.read||=rf(t),t.read();if(e<65536){if(e==57343){let e=Df(),t=Z(),n=Z();_f(t,n);let r={};if(X.keyMap)for(let t=2;t<e;t++){let e=X.decodeKey(n[t-2]);r[af(e)]=Z()}else for(let t=2;t<e;t++){let e=n[t-2];r[af(e)]=Z()}return r}else if(e==57342){let e=Df(),t=Z();for(let n=2;n<e;n++)_f(t++,Z());return Z()}else if(e==Pd)return Ef();if(X.getShared&&(Of(),t=Bd[e&8191],t))return t.read||=rf(t),t.read()}}let n=Kd[e];if(n)return n.handlesRead?n(Z):n(Z());{let t=Z();for(let n=0;n<qd.length;n++){let r=qd[n](e,t);if(r!==void 0)return r}return new gf(t,e)}case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let t=(Jd||xf())[e];if(t!==void 0)return t;throw Error(`Unknown token `+e)}default:if(isNaN(e)){let e=Error(`Unexpected end of CBOR data`);throw e.incomplete=!0,e}throw Error(`Unknown CBOR token `+e)}}const nf=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function rf(e){if(!e)throw Error(`Structure is required in record definition`);function t(){let e=J[Y++];if(e&=31,e>23)switch(e){case 24:e=J[Y++];break;case 25:e=Yd.getUint16(Y),Y+=2;break;case 26:e=Yd.getUint32(Y),Y+=4;break;default:throw Error(`Expected array header, but got `+J[Y-1])}let t=this.compiledReader;for(;t;){if(t.propertyCount===e)return t(Z);t=t.next}if(this.slowReads++>=$d){let n=this.length==e?this:this.slice(0,e);return t=X.keyMap?Function(`r`,`return {`+n.map(e=>X.decodeKey(e)).map(e=>nf.test(e)?af(e)+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`}`):Function(`r`,`return {`+n.map(e=>nf.test(e)?af(e)+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`}`),this.compiledReader&&(t.next=this.compiledReader),t.propertyCount=e,this.compiledReader=t,t(Z)}let n={};if(X.keyMap)for(let t=0;t<e;t++)n[af(X.decodeKey(this[t]))]=Z();else for(let t=0;t<e;t++)n[af(this[t])]=Z();return n}return e.slowReads=0,t}function af(e){if(typeof e==`string`)return e===`__proto__`?`__proto_`:e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(e==null)return e+``;throw Error(`Invalid property name type `+typeof e)}let of=cf;function sf(e){of=t(1);function t(t){return function(t){let n=Rd[zd++];if(n==null){if(Wd)return cf(t);let r=e(Y,Md,t,J);if(typeof r==`string`)n=r,Rd=Nd;else if(Rd=r,zd=1,Ud=1,n=Rd[0],n===void 0)throw Error(`Unexpected end of buffer`)}let r=n.length;return r<=t?(Y+=t,n):(Vd=n,Hd=Y,Ud=Y+r,Y+=t,n.slice(0,t))}}}function cf(e){let t;if(e<16&&(t=df(e)))return t;if(e>64&&jd)return jd.decode(J.subarray(Y,Y+=e));let n=Y+e,r=[];for(t=``;Y<n;){let e=J[Y++];if(!(e&128))r.push(e);else if((e&224)==192){let t=J[Y++]&63;r.push((e&31)<<6|t)}else if((e&240)==224){let t=J[Y++]&63,n=J[Y++]&63;r.push((e&31)<<12|t<<6|n)}else if((e&248)==240){let t=J[Y++]&63,n=J[Y++]&63,i=J[Y++]&63,a=(e&7)<<18|t<<12|n<<6|i;a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a)}else r.push(e);r.length>=4096&&(t+=lf.apply(String,r),r.length=0)}return r.length>0&&(t+=lf.apply(String,r)),t}let lf=String.fromCharCode;function uf(e){let t=Y,n=Array(e);for(let r=0;r<e;r++){let e=J[Y++];if((e&128)>0){Y=t;return}n[r]=e}return lf.apply(String,n)}function df(e){if(e<4)if(e<2){if(e===0)return``;{let e=J[Y++];if((e&128)>1){--Y;return}return lf(e)}}else{let t=J[Y++],n=J[Y++];if((t&128)>0||(n&128)>0){Y-=2;return}if(e<3)return lf(t,n);let r=J[Y++];if((r&128)>0){Y-=3;return}return lf(t,n,r)}else{let t=J[Y++],n=J[Y++],r=J[Y++],i=J[Y++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){Y-=4;return}if(e<6){if(e===4)return lf(t,n,r,i);{let e=J[Y++];if((e&128)>0){Y-=5;return}return lf(t,n,r,i,e)}}else if(e<8){let a=J[Y++],o=J[Y++];if((a&128)>0||(o&128)>0){Y-=6;return}if(e<7)return lf(t,n,r,i,a,o);let s=J[Y++];if((s&128)>0){Y-=7;return}return lf(t,n,r,i,a,o,s)}else{let a=J[Y++],o=J[Y++],s=J[Y++],c=J[Y++];if((a&128)>0||(o&128)>0||(s&128)>0||(c&128)>0){Y-=8;return}if(e<10){if(e===8)return lf(t,n,r,i,a,o,s,c);{let e=J[Y++];if((e&128)>0){Y-=9;return}return lf(t,n,r,i,a,o,s,c,e)}}else if(e<12){let l=J[Y++],u=J[Y++];if((l&128)>0||(u&128)>0){Y-=10;return}if(e<11)return lf(t,n,r,i,a,o,s,c,l,u);let d=J[Y++];if((d&128)>0){Y-=11;return}return lf(t,n,r,i,a,o,s,c,l,u,d)}else{let l=J[Y++],u=J[Y++],d=J[Y++],f=J[Y++];if((l&128)>0||(u&128)>0||(d&128)>0||(f&128)>0){Y-=12;return}if(e<14){if(e===12)return lf(t,n,r,i,a,o,s,c,l,u,d,f);{let e=J[Y++];if((e&128)>0){Y-=13;return}return lf(t,n,r,i,a,o,s,c,l,u,d,f,e)}}else{let p=J[Y++],m=J[Y++];if((p&128)>0||(m&128)>0){Y-=14;return}if(e<15)return lf(t,n,r,i,a,o,s,c,l,u,d,f,p,m);let h=J[Y++];if((h&128)>0){Y-=15;return}return lf(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function ff(e){return X.copyBuffers?Uint8Array.prototype.slice.call(J,Y,Y+=e):J.subarray(Y,Y+=e)}let pf=new Float32Array(1),mf=new Uint8Array(pf.buffer,0,4);function hf(){let e=J[Y++],t=J[Y++],n=(e&127)>>2;if(n===31)return t||e&3?NaN:e&128?-1/0:1/0;if(n===0){let n=((e&3)<<8|t)/(1<<24);return e&128?-n:n}return mf[3]=e&128|(n>>1)+56,mf[2]=(e&7)<<5|t>>3,mf[1]=t<<5,mf[0]=0,pf[0]}Array(4096);var gf=class{constructor(e,t){this.value=e,this.tag=t}};Kd[0]=e=>new Date(e),Kd[1]=e=>new Date(Math.round(e*1e3)),Kd[2]=e=>{let t=BigInt(0);for(let n=0,r=e.byteLength;n<r;n++)t=BigInt(e[n])+(t<<BigInt(8));return t},Kd[3]=e=>BigInt(-1)-Kd[2](e),Kd[4]=e=>+(e[1]+`e`+e[0]),Kd[5]=e=>e[1]*Math.exp(e[0]*Math.log(2));const _f=(e,t)=>{e-=57344;let n=Bd[e];n&&n.isShared&&((Bd.restoreStructures||=[])[e]=n),Bd[e]=t,t.read=rf(t)};Kd[105]=e=>{let t=e.length,n=e[1];_f(e[0],n);let r={};for(let i=2;i<t;i++){let t=n[i-2];r[af(t)]=e[i]}return r},Kd[14]=e=>Wd?Wd[0].slice(Wd.position0,Wd.position0+=e):new gf(e,14),Kd[15]=e=>Wd?Wd[1].slice(Wd.position1,Wd.position1+=e):new gf(e,15);let vf={Error,RegExp};Kd[27]=e=>(vf[e[0]]||Error)(e[1],e[2]);const yf=e=>{if(J[Y++]!=132){let e=Error(`Packed values structure must be followed by a 4 element array`);throw J.length<Y&&(e.incomplete=!0),e}let t=e();if(!t||!t.length){let e=Error(`Packed values structure must be followed by a 4 element array`);throw e.incomplete=!0,e}return Jd=Jd?t.concat(Jd.slice(t.length)):t,Jd.prefixes=e(),Jd.suffixes=e(),e()};yf.handlesRead=!0,Kd[51]=yf,Kd[6]=e=>{if(!Jd)if(X.getShared)Of();else return new gf(e,6);if(typeof e==`number`)return Jd[16+(e>=0?2*e:-2*e-1)];let t=Error(`No support for non-integer packed references yet`);throw e===void 0&&(t.incomplete=!0),t},Kd[28]=e=>{Gd||(Gd=new Map,Gd.id=0);let t=Gd.id++,n=Y,r=J[Y],i;i=r>>5==4?[]:{};let a={target:i};Gd.set(t,a);let o=e();return a.used?(Object.getPrototypeOf(i)!==Object.getPrototypeOf(o)&&(Y=n,i=o,Gd.set(t,{target:i}),o=e()),Object.assign(i,o)):(a.target=o,o)},Kd[28].handlesRead=!0,Kd[29]=e=>{let t=Gd.get(e);return t.used=!0,t.target},Kd[258]=e=>new Set(e),(Kd[259]=e=>(X.mapsAsObjects&&(X.mapsAsObjects=!1,Xd=!0),e())).handlesRead=!0;function bf(e,t){return typeof e==`string`?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function xf(){if(!Jd)if(X.getShared)Of();else throw Error(`No packed values available`);return Jd}qd.push((e,t)=>{if(e>=225&&e<=255)return bf(xf().prefixes[e-224],t);if(e>=28704&&e<=32767)return bf(xf().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return bf(xf().prefixes[e-1879048192],t);if(e>=216&&e<=223)return bf(t,xf().suffixes[e-216]);if(e>=27647&&e<=28671)return bf(t,xf().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return bf(t,xf().suffixes[e-1811939328]);if(e==1399353956)return{packedValues:Jd,structures:Bd.slice(0),version:t};if(e==55799)return t});const Sf=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Cf=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>`u`?{name:`BigUint64Array`}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>`u`?{name:`BigInt64Array`}:BigInt64Array,Float32Array,Float64Array],wf=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e<Cf.length;e++)Tf(Cf[e],wf[e]);function Tf(e,t){let n=`get`+e.name.slice(0,-5),r;typeof e==`function`?r=e.BYTES_PER_ELEMENT:e=null;for(let i=0;i<2;i++){if(!i&&r==1)continue;let a=r==2?1:r==4?2:r==8?3:0;Kd[i?t:t-4]=r==1||i==Sf?n=>{if(!e)throw Error(`Could not find typed array for code `+t);return!X.copyBuffers&&(r===1||r===2&&!(n.byteOffset&1)||r===4&&!(n.byteOffset&3)||r===8&&!(n.byteOffset&7))?new e(n.buffer,n.byteOffset,n.byteLength>>a):new e(Uint8Array.prototype.slice.call(n,0).buffer)}:r=>{if(!e)throw Error(`Could not find typed array for code `+t);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),s=r.length>>a,c=new e(s),l=o[n];for(let e=0;e<s;e++)c[e]=l.call(o,e<<a,i);return c}}}function Ef(){let e=Df(),t=Y+Z();for(let t=2;t<e;t++){let e=Df();Y+=e}let n=Y;return Y=t,Wd=[cf(Df()),cf(Df())],Wd.position0=0,Wd.position1=0,Wd.postBundlePosition=Y,Y=n,Z()}function Df(){let e=J[Y++]&31;if(e>23)switch(e){case 24:e=J[Y++];break;case 25:e=Yd.getUint16(Y),Y+=2;break;case 26:e=Yd.getUint32(Y),Y+=4;break}return e}function Of(){if(X.getShared){let e=kf(()=>(J=null,X.getShared()))||{},t=e.structures||[];X.sharedVersion=e.version,Jd=X.sharedValues=e.packedValues,Bd===!0?X.structures=Bd=t:Bd.splice.apply(Bd,[0,t.length].concat(t))}}function kf(e){let t=Md,n=Y,r=zd,i=Hd,a=Ud,o=Vd,s=Rd,c=Gd,l=Wd,u=new Uint8Array(J.slice(0,Md)),d=Bd,f=X,p=Qd,m=e();return Md=t,Y=n,zd=r,Hd=i,Ud=a,Vd=o,Rd=s,Gd=c,Wd=l,J=u,Qd=p,Bd=d,X=f,Yd=new DataView(J.buffer,J.byteOffset,J.byteLength),m}function Af(){J=null,Gd=null,Bd=null}const jf=Array(147);for(let e=0;e<256;e++)jf[e]=+(`1e`+Math.floor(45.15-e*.30103));let Mf=new ef({useRecords:!1});const Nf=Mf.decode;Mf.decodeMultiple;const Pf={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};let Ff;try{Ff=new TextEncoder}catch{}let If,Lf;const Rf=typeof globalThis==`object`&&globalThis.Buffer,zf=Rf!==void 0,Bf=zf?Rf.allocUnsafeSlow:Uint8Array,Vf=zf?Rf:Uint8Array,Hf=zf?4294967296:2144337920;let Uf,Q,Wf,$=0,Gf,Kf=null;const qf=/[\u0080-\uFFFF]/,Jf=Symbol(`record-id`);var Yf=class extends ef{constructor(e){super(e),this.offset=0;let t,n,r,i,a;e||={};let o=Vf.prototype.utf8Write?function(e,t,n){return Q.utf8Write(e,t,n)}:Ff&&Ff.encodeInto?function(e,t){return Ff.encodeInto(e,Q.subarray(t)).written}:!1,s=this,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(l??=c?128:0,l>8190)throw Error(`Maximum maxSharedStructure is 8190`);let u=e.sequential;u&&(l=0),this.structures||=[],this.saveStructures&&(this.saveShared=this.saveStructures);let d,f,p=e.sharedValues,m;if(p){m=Object.create(null);for(let e=0,t=p.length;e<t;e++)m[p[e]]=e}let h=[],g=0,_=0;this.mapEncode=function(e,t){if(this._keyMap&&!this._mapped)switch(e.constructor.name){case`Array`:e=e.map(e=>this.encodeKeys(e));break}return this.encode(e,t)},this.encode=function(o,c){if(Q||(Q=new Bf(8192),Wf=new DataView(Q.buffer,0,8192),$=0),Gf=Q.length-10,Gf-$<2048?(Q=new Bf(Q.length),Wf=new DataView(Q.buffer,0,Q.length),Gf=Q.length-10,$=0):c===512&&($=$+7&2147483640),t=$,s.useSelfDescribedHeader&&(Wf.setUint32($,3654940416),$+=3),a=s.structuredClone?new Map:null,s.bundleStrings&&typeof o!=`string`?(Kf=[],Kf.size=1/0):Kf=null,n=s.structures,n){if(n.uninitialized){let e=s.getShared()||{};s.structures=n=e.structures||[],s.sharedVersion=e.version;let t=s.sharedValues=e.packedValues;if(t){m={};for(let e=0,n=t.length;e<n;e++)m[t[e]]=e}}let e=n.length;if(e>l&&!u&&(e=l),!n.transitions){n.transitions=Object.create(null);for(let t=0;t<e;t++){let e=n[t];if(!e)continue;let r,i=n.transitions;for(let n=0,a=e.length;n<a;n++){i[Jf]===void 0&&(i[Jf]=t);let a=e[n];r=i[a],r||=i[a]=Object.create(null),i=r}i[Jf]=t|1048576}}u||(n.nextId=e)}if(r&&=!1,i=n||[],f=m,e.pack){let t=new Map;if(t.values=[],t.encoder=s,t.maxValues=e.maxPrivatePackedValues||(m?16:1/0),t.objectMap=m||!1,t.samplingPackedValues=d,tp(o,t),t.values.length>0){Q[$++]=216,Q[$++]=51,Qf(4);let e=t.values;v(e),Qf(0),Qf(0),f=Object.create(m||null);for(let t=0,n=e.length;t<n;t++)f[e[t]]=t}}Uf=c&pp;try{if(Uf)return;if(v(o),Kf&&op(t,v),s.offset=$,a&&a.idsToInsert){$+=a.idsToInsert.length*2,$>Gf&&b($),s.offset=$;let e=ap(Q.subarray(t,$),a.idsToInsert);return a=null,e}return c&512?(Q.start=t,Q.end=$,Q):Q.subarray(t,$)}finally{if(n){if(_<10&&_++,n.length>l&&(n.length=l),g>1e4)n.transitions=null,_=0,g=0,h.length>0&&(h=[]);else if(h.length>0&&!u){for(let e=0,t=h.length;e<t;e++)h[e][Jf]=void 0;h=[]}}if(r&&s.saveShared){s.structures.length>l&&(s.structures=s.structures.slice(0,l));let e=Q.subarray(t,$);return s.updateSharedData()===!1?s.encode(o):e}c&1024&&($=t)}},this.findCommonStringsToPack=()=>(d=new Map,m||=Object.create(null),e=>{let t=e&&e.threshold||4,n=this.pack?e.maxPrivatePackedValues||16:0;p||=this.sharedValues=[];for(let[e,i]of d)i.count>t&&(m[e]=n++,p.push(e),r=!0);for(;this.saveShared&&this.updateSharedData()===!1;);d=null});let v=n=>{$>Gf&&(Q=b($));var r=typeof n,i;if(r===`string`){if(f){let t=f[n];if(t>=0){t<16?Q[$++]=t+224:(Q[$++]=198,t&1?v(15-t>>1):v(t-16>>1));return}else if(d&&!e.pack){let e=d.get(n);e?e.count++:d.set(n,{count:1})}}let r=n.length;if(Kf&&r>=4&&r<1024){if((Kf.size+=r)>61440){let e,n=(Kf[0]?Kf[0].length*3+Kf[1].length:0)+10;$+n>Gf&&(Q=b($+n)),Q[$++]=217,Q[$++]=223,Q[$++]=249,Q[$++]=Kf.position?132:130,Q[$++]=26,e=$-t,$+=4,Kf.position&&op(t,v),Kf=[``,``],Kf.size=0,Kf.position=e}let e=qf.test(n);Kf[+!e]+=n,Q[$++]=e?206:207,v(r);return}let a;a=r<32?1:r<256?2:r<65536?3:5;let s=r*3;if($+s>Gf&&(Q=b($+s)),r<64||!o){let e,t,o,s=$+a;for(e=0;e<r;e++)t=n.charCodeAt(e),t<128?Q[s++]=t:t<2048?(Q[s++]=t>>6|192,Q[s++]=t&63|128):(t&64512)==55296&&((o=n.charCodeAt(e+1))&64512)==56320?(t=65536+((t&1023)<<10)+(o&1023),e++,Q[s++]=t>>18|240,Q[s++]=t>>12&63|128,Q[s++]=t>>6&63|128,Q[s++]=t&63|128):(Q[s++]=t>>12|224,Q[s++]=t>>6&63|128,Q[s++]=t&63|128);i=s-$-a}else i=o(n,$+a,s);i<24?Q[$++]=96|i:i<256?(a<2&&Q.copyWithin($+2,$+1,$+1+i),Q[$++]=120,Q[$++]=i):i<65536?(a<3&&Q.copyWithin($+3,$+2,$+2+i),Q[$++]=121,Q[$++]=i>>8,Q[$++]=i&255):(a<5&&Q.copyWithin($+5,$+3,$+3+i),Q[$++]=122,Wf.setUint32($,i),$+=4),$+=i}else if(r===`number`)if(!this.alwaysUseFloat&&n>>>0===n)n<24?Q[$++]=n:n<256?(Q[$++]=24,Q[$++]=n):n<65536?(Q[$++]=25,Q[$++]=n>>8,Q[$++]=n&255):(Q[$++]=26,Wf.setUint32($,n),$+=4);else if(!this.alwaysUseFloat&&n>>0===n)n>=-24?Q[$++]=31-n:n>=-256?(Q[$++]=56,Q[$++]=~n):n>=-65536?(Q[$++]=57,Wf.setUint16($,~n),$+=2):(Q[$++]=58,Wf.setUint32($,~n),$+=4);else{let e;if((e=this.useFloat32)>0&&n<4294967296&&n>=-2147483648){Q[$++]=250,Wf.setFloat32($,n);let t;if(e<4||(t=n*jf[(Q[$]&127)<<1|Q[$+1]>>7])>>0===t){$+=4;return}else $--}Q[$++]=251,Wf.setFloat64($,n),$+=8}else if(r===`object`)if(!n)Q[$++]=246;else{if(a){let e=a.get(n);if(e){if(Q[$++]=216,Q[$++]=29,Q[$++]=25,!e.references){let t=a.idsToInsert||=[];e.references=[],t.push(e)}e.references.push($-t),$+=2;return}else a.set(n,{offset:$-t})}let e=n.constructor;if(e===Object)y(n);else if(e===Array){i=n.length,i<24?Q[$++]=128|i:Qf(i);for(let e=0;e<i;e++)v(n[e])}else if(e===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(Q[$++]=217,Q[$++]=1,Q[$++]=3),i=n.size,i<24?Q[$++]=160|i:i<256?(Q[$++]=184,Q[$++]=i):i<65536?(Q[$++]=185,Q[$++]=i>>8,Q[$++]=i&255):(Q[$++]=186,Wf.setUint32($,i),$+=4),s.keyMap)for(let[e,t]of n)v(s.encodeKey(e)),v(t);else for(let[e,t]of n)v(e),v(t);else{for(let e=0,t=If.length;e<t;e++){let t=Lf[e];if(n instanceof t){let t=If[e],r=t.tag;r??=t.getTag&&t.getTag.call(this,n),r<24?Q[$++]=192|r:r<256?(Q[$++]=216,Q[$++]=r):r<65536?(Q[$++]=217,Q[$++]=r>>8,Q[$++]=r&255):r>-1&&(Q[$++]=218,Wf.setUint32($,r),$+=4),t.encode.call(this,n,v,b);return}}if(n[Symbol.iterator]){if(Uf){let e=Error(`Iterable should be serialized as iterator`);throw e.iteratorNotHandled=!0,e}Q[$++]=159;for(let e of n)v(e);Q[$++]=255;return}if(n[Symbol.asyncIterator]||ep(n)){let e=Error(`Iterable/blob should be serialized as iterator`);throw e.iteratorNotHandled=!0,e}if(this.useToJSON&&n.toJSON){let e=n.toJSON();if(e!==n)return v(e)}y(n)}}else if(r===`boolean`)Q[$++]=n?245:244;else if(r===`bigint`){if(n<BigInt(1)<<BigInt(64)&&n>=0)Q[$++]=27,Wf.setBigUint64($,n);else if(n>-(BigInt(1)<<BigInt(64))&&n<0)Q[$++]=59,Wf.setBigUint64($,-n-BigInt(1));else if(this.largeBigIntToFloat)Q[$++]=251,Wf.setFloat64($,Number(n));else{n>=BigInt(0)?Q[$++]=194:(Q[$++]=195,n=BigInt(-1)-n);let e=[];for(;n;)e.push(Number(n&BigInt(255))),n>>=BigInt(8);ip(new Uint8Array(e.reverse()),b);return}$+=8}else if(r===`undefined`)Q[$++]=247;else throw Error(`Unknown type: `+r)},y=this.useRecords===!1?this.variableMapSize?e=>{let t=Object.keys(e),n=Object.values(e),r=t.length;if(r<24?Q[$++]=160|r:r<256?(Q[$++]=184,Q[$++]=r):r<65536?(Q[$++]=185,Q[$++]=r>>8,Q[$++]=r&255):(Q[$++]=186,Wf.setUint32($,r),$+=4),s.keyMap)for(let e=0;e<r;e++)v(s.encodeKey(t[e])),v(n[e]);else for(let e=0;e<r;e++)v(t[e]),v(n[e])}:e=>{Q[$++]=185;let n=$-t;$+=2;let r=0;if(s.keyMap)for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(v(s.encodeKey(t)),v(e[t]),r++);else for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(v(t),v(e[t]),r++);Q[n+++t]=r>>8,Q[n+t]=r&255}:(e,t)=>{let n,a=i.transitions||=Object.create(null),o=0,s=0,c,u;if(this.keyMap){u=Object.keys(e).map(e=>this.encodeKey(e)),s=u.length;for(let e=0;e<s;e++){let t=u[e];n=a[t],n||(n=a[t]=Object.create(null),o++),a=n}}else for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(n=a[t],n||(a[Jf]&1048576&&(c=a[Jf]&65535),n=a[t]=Object.create(null),o++),a=n,s++);let d=a[Jf];if(d!==void 0)d&=65535,Q[$++]=217,Q[$++]=d>>8|224,Q[$++]=d&255;else if(u||=a.__keys__||=Object.keys(e),c===void 0?(d=i.nextId++,d||(d=0,i.nextId=1),d>=256&&(i.nextId=(d=l)+1)):d=c,i[d]=u,d<l){Q[$++]=217,Q[$++]=d>>8|224,Q[$++]=d&255,a=i.transitions;for(let e=0;e<s;e++)(a[Jf]===void 0||a[Jf]&1048576)&&(a[Jf]=d),a=a[u[e]];a[Jf]=d|1048576,r=!0}else{if(a[Jf]=d,Wf.setUint32($,3655335680),$+=3,o&&(g+=_*o),h.length>=256-l&&(h.shift()[Jf]=void 0),h.push(a),Qf(s+2),v(57344+d),v(u),t)return;for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&v(e[t]);return}if(s<24?Q[$++]=128|s:Qf(s),!t)for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&v(e[t])},b=e=>{let n;if(e>16777216){if(e-t>Hf)throw Error(`Encoded buffer would be larger than maximum buffer size`);n=Math.min(Hf,Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096)*4096)}else n=(Math.max(e-t<<2,Q.length-1)>>12)+1<<12;let r=new Bf(n);return Wf=new DataView(r.buffer,0,n),Q.copy?Q.copy(r,0,t,e):r.set(Q.slice(t,e)),$-=t,t=0,Gf=r.length-10,Q=r},x=100,S=1e3;this.encodeAsIterable=function(e,t){return E(e,t,C)},this.encodeAsAsyncIterable=function(e,t){return E(e,t,D)};function*C(e,n,r){let i=e.constructor;if(i===Object){let t=s.useRecords!==!1;t?y(e,!0):Xf(Object.keys(e).length,160);for(let r in e){let i=e[r];t||v(r),i&&typeof i==`object`?n[r]?yield*C(i,n[r]):yield*w(i,n,r):v(i)}}else if(i===Array){let r=e.length;Qf(r);for(let i=0;i<r;i++){let r=e[i];r&&(typeof r==`object`||$-t>x)?n.element?yield*C(r,n.element):yield*w(r,n,`element`):v(r)}}else if(e[Symbol.iterator]&&!e.buffer){Q[$++]=159;for(let r of e)r&&(typeof r==`object`||$-t>x)?n.element?yield*C(r,n.element):yield*w(r,n,`element`):v(r);Q[$++]=255}else ep(e)?(Xf(e.size,64),yield Q.subarray(t,$),yield e,T()):e[Symbol.asyncIterator]?(Q[$++]=159,yield Q.subarray(t,$),yield e,T(),Q[$++]=255):v(e);r&&$>t?yield Q.subarray(t,$):$-t>x&&(yield Q.subarray(t,$),T())}function*w(e,n,r){let i=$-t;try{v(e),$-t>x&&(yield Q.subarray(t,$),T())}catch(a){if(a.iteratorNotHandled)n[r]={},$=t+i,yield*C.call(this,e,n[r]);else throw a}}function T(){x=S,s.encode(null,pp)}function E(e,t,n){return x=t&&t.chunkThreshold?S=t.chunkThreshold:100,e&&typeof e==`object`?(s.encode(null,pp),n(e,s.iterateProperties||={},!0)):[s.encode(e)]}async function*D(e,t){for(let n of C(e,t,!0)){let e=n.constructor;if(e===Vf||e===Uint8Array)yield n;else if(ep(n)){let e=n.stream().getReader(),t;for(;!(t=await e.read()).done;)yield t.value}else if(n[Symbol.asyncIterator])for await(let e of n)T(),e?yield*D(e,t.async||={}):yield s.encode(e);else yield n}}}useBuffer(e){Q=e,Wf=new DataView(Q.buffer,Q.byteOffset,Q.byteLength),$=0}clearSharedData(){this.structures&&=[],this.sharedValues&&=void 0}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let t=this.structures.slice(0),n=new Zf(t,this.sharedValues,this.sharedVersion),r=this.saveShared(n,t=>(t&&t.version||0)==e);return r===!1?(n=this.getShared()||{},this.structures=n.structures||[],this.sharedValues=n.packedValues,this.sharedVersion=n.version,this.structures.nextId=this.structures.length):t.forEach((e,t)=>this.structures[t]=e),r}};function Xf(e,t){e<24?Q[$++]=t|e:e<256?(Q[$++]=t|24,Q[$++]=e):e<65536?(Q[$++]=t|25,Q[$++]=e>>8,Q[$++]=e&255):(Q[$++]=t|26,Wf.setUint32($,e),$+=4)}var Zf=class{constructor(e,t,n){this.structures=e,this.packedValues=t,this.version=n}};function Qf(e){e<24?Q[$++]=128|e:e<256?(Q[$++]=152,Q[$++]=e):e<65536?(Q[$++]=153,Q[$++]=e>>8,Q[$++]=e&255):(Q[$++]=154,Wf.setUint32($,e),$+=4)}const $f=typeof Blob>`u`?function(){}:Blob;function ep(e){if(e instanceof $f)return!0;let t=e[Symbol.toStringTag];return t===`Blob`||t===`File`}function tp(e,t){switch(typeof e){case`string`:if(e.length>3){if(t.objectMap[e]>-1||t.values.length>=t.maxValues)return;let n=t.get(e);if(n)++n.count==2&&t.values.push(e);else if(t.set(e,{count:1}),t.samplingPackedValues){let n=t.samplingPackedValues.get(e);n?n.count++:t.samplingPackedValues.set(e,{count:1})}}break;case`object`:if(e)if(e instanceof Array)for(let n=0,r=e.length;n<r;n++)tp(e[n],t);else{let r=!t.encoder.useRecords;for(var n in e)e.hasOwnProperty(n)&&(r&&tp(n,t),tp(e[n],t))}break;case`function`:console.log(e)}}const np=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Lf=[Date,Set,Error,RegExp,gf,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>`u`?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>`u`?function(){}:BigInt64Array,Float32Array,Float64Array,Zf],If=[{tag:1,encode(e,t){let n=e.getTime()/1e3;(this.useTimestamp32||e.getMilliseconds()===0)&&n>=0&&n<4294967296?(Q[$++]=26,Wf.setUint32($,n),$+=4):(Q[$++]=251,Wf.setFloat64($,n),$+=8)}},{tag:258,encode(e,t){t(Array.from(e))}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t([`RegExp`,e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,n){ip(e,n)}},{getTag(e){if(e.constructor===Uint8Array&&(this.tagUint8Array||zf&&this.tagUint8Array!==!1))return 64},encode(e,t,n){ip(e,n)}},rp(68,1),rp(69,2),rp(70,4),rp(71,8),rp(72,1),rp(77,2),rp(78,4),rp(79,8),rp(85,4),rp(86,8),{encode(e,t){let n=e.packedValues||[],r=e.structures||[];if(n.values.length>0){Q[$++]=216,Q[$++]=51,Qf(4);let e=n.values;t(e),Qf(0),Qf(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let t=0,n=e.length;t<n;t++)packedObjectMap[e[t]]=t}if(r){Wf.setUint32($,3655335424),$+=3;let n=r.slice(0);n.unshift(57344),n.push(new gf(e.version,1399353956)),t(n)}else t(new gf(e.version,1399353956))}}];function rp(e,t){return!np&&t>1&&(e-=4),{tag:e,encode:function(e,t){let n=e.byteLength,r=e.byteOffset||0,i=e.buffer||e;t(zf?Rf.from(i,r,n):new Uint8Array(i,r,n))}}}function ip(e,t){let n=e.byteLength;n<24?Q[$++]=64+n:n<256?(Q[$++]=88,Q[$++]=n):n<65536?(Q[$++]=89,Q[$++]=n>>8,Q[$++]=n&255):(Q[$++]=90,Wf.setUint32($,n),$+=4),$+n>=Q.length&&t($+n),Q.set(e.buffer?e:new Uint8Array(e),$),$+=n}function ap(e,t){let n,r=t.length*2,i=e.length-r;t.sort((e,t)=>e.offset>t.offset?1:-1);for(let n=0;n<t.length;n++){let r=t[n];r.id=n;for(let t of r.references)e[t++]=n>>8,e[t]=n&255}for(;n=t.pop();){let t=n.offset;e.copyWithin(t+r,t,i),r-=2;let a=t+r;e[a++]=216,e[a++]=28,i=t}return e}function op(e,t){Wf.setUint32(Kf.position+e,$-Kf.position-e+1);let n=Kf;Kf=null,t(n[0]),t(n[1])}let sp=new Yf({useRecords:!1});const cp=sp.encode;sp.encodeAsIterable,sp.encodeAsAsyncIterable;const{NEVER:lp,ALWAYS:up,DECIMAL_ROUND:dp,DECIMAL_FIT:fp}=Pf,pp=2048;var mp=n(((e,t)=>{let n=()=>process.platform===`linux`,r=null;t.exports={isLinux:n,getReport:()=>{if(!r)if(n()&&process.report){let e=process.report.excludeNetwork;process.report.excludeNetwork=!0,r=process.report.getReport(),process.report.excludeNetwork=e}else r={};return r}}})),hp=n(((e,n)=>{let r=t(`fs`),i=2048;n.exports={LDD_PATH:`/usr/bin/ldd`,SELF_PATH:`/proc/self/exe`,readFileSync:e=>{let t=r.openSync(e,`r`),n=Buffer.alloc(i),a=r.readSync(t,n,0,i,0);return r.close(t,()=>{}),n.subarray(0,a)},readFile:e=>new Promise((t,n)=>{r.open(e,`r`,(e,a)=>{if(e)n(e);else{let e=Buffer.alloc(i);r.read(a,e,0,i,0,(n,i)=>{t(e.subarray(0,i)),r.close(a,()=>{})})}})})}})),gp=n(((e,t)=>{t.exports={interpreterPath:e=>{if(e.length<64||e.readUInt32BE(0)!==2135247942||e.readUInt8(4)!==2||e.readUInt8(5)!==1)return null;let t=e.readUInt32LE(32),n=e.readUInt16LE(54),r=e.readUInt16LE(56);for(let i=0;i<r;i++){let r=t+i*n;if(e.readUInt32LE(r)===3){let t=e.readUInt32LE(r+8),n=e.readUInt32LE(r+32);return e.subarray(t,t+n).toString().replace(/\0.*$/g,``)}}return null}}})),_p=n(((e,n)=>{let r=t(`child_process`),{isLinux:i,getReport:a}=mp(),{LDD_PATH:o,SELF_PATH:s,readFile:c,readFileSync:l}=hp(),{interpreterPath:u}=gp(),d,f,p,m=`getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true`,h=``,g=()=>h||new Promise(e=>{r.exec(m,(t,n)=>{h=t?` `:n,e(h)})}),_=()=>{if(!h)try{h=r.execSync(m,{encoding:`utf8`})}catch{h=` `}return h},v=`glibc`,y=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,b=`musl`,x=e=>e.includes(`libc.musl-`)||e.includes(`ld-musl-`),S=()=>{let e=a();return e.header&&e.header.glibcVersionRuntime?v:Array.isArray(e.sharedObjects)&&e.sharedObjects.some(x)?b:null},C=e=>{let[t,n]=e.split(/[\r\n]+/);return t&&t.includes(v)?v:n&&n.includes(b)?b:null},w=e=>{if(e){if(e.includes(`/ld-musl-`))return b;if(e.includes(`/ld-linux-`))return v}return null},T=e=>(e=e.toString(),e.includes(`musl`)?b:e.includes(`GNU C Library`)?v:null),E=async()=>{if(f!==void 0)return f;f=null;try{f=T(await c(o))}catch{}return f},D=()=>{if(f!==void 0)return f;f=null;try{f=T(l(o))}catch{}return f},O=async()=>{if(d!==void 0)return d;d=null;try{d=w(u(await c(s)))}catch{}return d},k=()=>{if(d!==void 0)return d;d=null;try{d=w(u(l(s)))}catch{}return d},A=async()=>{let e=null;return i()&&(e=await O(),e||(e=await E(),e||=S(),e||=C(await g()))),e},j=()=>{let e=null;return i()&&(e=k(),e||(e=D(),e||=S(),e||=C(_()))),e},M=async()=>i()&&await A()!==v,N=()=>i()&&j()!==v,P=async()=>{if(p!==void 0)return p;p=null;try{let e=(await c(o)).match(y);e&&(p=e[1])}catch{}return p},ee=()=>{if(p!==void 0)return p;p=null;try{let e=l(o).match(y);e&&(p=e[1])}catch{}return p},F=()=>{let e=a();return e.header&&e.header.glibcVersionRuntime?e.header.glibcVersionRuntime:null},te=e=>e.trim().split(/\s+/)[1],I=e=>{let[t,n,r]=e.split(/[\r\n]+/);return t&&t.includes(v)?te(t):n&&r&&n.includes(b)?te(r):null};n.exports={GLIBC:v,MUSL:b,family:A,familySync:j,isNonGlibcLinux:M,isNonGlibcLinuxSync:N,version:async()=>{let e=null;return i()&&(e=await P(),e||=F(),e||=I(await g())),e},versionSync:()=>{let e=null;return i()&&(e=ee(),e||=F(),e||=I(_())),e}}})),vp=n(((e,n)=>{var r=t(`fs`),i=t(`path`),a=t(`url`),o=process.config&&process.config.variables||{},s=!!process.env.PREBUILDS_ONLY,c=process.versions,l=c.modules;(c.deno||process.isBun)&&(l=`unsupported`);var u=D()?`electron`:`node`,d=process.arch,f=process.platform,p=process.env.LIBC||(O(f)?`musl`:`glibc`),m=process.env.ARM_VERSION||(d===`arm64`?`8`:o.arm_version)||``,h=(c.uv||``).split(`.`)[0];n.exports=g;function g(e){return typeof __webpack_require__==`function`?__non_webpack_require__(g.path(e)):t(g.path(e))}g.path=function(e){e=i.resolve(e||`.`);var n=``;try{n=typeof __webpack_require__==`function`?__non_webpack_require__(i.join(e,`package.json`)).name:t(i.join(e,`package.json`)).name;var r=n.toUpperCase().replace(/-/g,`_`)+`_PREBUILD`;process.env[r]&&(e=process.env[r])}catch{}if(!s){var o=v(i.join(e,`build/Release`),y);if(o)return o;var c=v(i.join(e,`build/Debug`),y);if(c)return c}var g=k(e);if(g)return g;var T=k(i.dirname(process.execPath));if(T)return T;var D=(n[0]==`@`?``:`@`+n+`/`)+n+`-`+f+`-`+d;try{return A(i.dirname(t(`module`).createRequire(a.pathToFileURL(i.join(e,`package.json`))).resolve(D)))}catch{}var O=[`platform=`+f,`arch=`+d,`runtime=`+u,`abi=`+l,`uv=`+h,m?`armv=`+m:``,`libc=`+p,`node=`+process.versions.node,process.versions.electron?`electron=`+process.versions.electron:``,typeof __webpack_require__==`function`?`webpack=true`:``].filter(Boolean).join(` `);throw Error(`No native build was found for `+O+`
136
+ Cause: ${t}`)}}buildUrl(e,...t){let n=encodeURIComponent(e),r=t.map(e=>encodeURIComponent(e)),i=r.length>0?`/`+r.join(`/`):``,a=this.baseUrl.pathname.replace(/\/+$/,``);return`${this.baseUrl.origin}${a}${xd}/${n}${i}`}async fetch(e,t){let n=t.method||`GET`;if(hd()){let r={method:n,url:e,headers:t.headers},i=t.body;i!=null&&(i instanceof ArrayBuffer||i instanceof Uint8Array?r.bodySize=i.byteLength:typeof i==`string`?r.bodySize=i.length:r.bodyType=typeof i),console.debug(`[VQS Debug] Request:`,JSON.stringify(r,null,2))}t.headers.set(`User-Agent`,`@vercel/queue/0.1.7`),t.headers.set(`Vqs-Client-Ts`,new Date().toISOString());let r=this.dispatcher?{...t,dispatcher:this.dispatcher}:t,i=await fetch(e,r);if(hd()){let t={method:n,url:e,status:i.status,statusText:i.statusText,headers:i.headers};console.debug(`[VQS Debug] Response:`,JSON.stringify(t,null,2))}return i}async sendMessage(e){let t=this.transport,{queueName:n,payload:r,idempotencyKey:i,retentionSeconds:a,delaySeconds:o,headers:s}=e,c=new Headers;if(this.customHeaders)for(let[e,t]of Object.entries(this.customHeaders))c.append(e,t);if(s){let e=new Set([`authorization`,`content-type`]),t=t=>{let n=t.toLowerCase();return e.has(n)?!0:n.startsWith(`vqs-`)};for(let[e,n]of Object.entries(s))!t(e)&&n!==void 0&&c.append(e,n)}c.set(`Authorization`,`Bearer ${await this.getToken()}`),c.set(`Content-Type`,t.contentType);let l=this.getSendDeploymentId();l&&c.set(`Vqs-Deployment-Id`,l),i&&c.set(`Vqs-Idempotency-Key`,i),a!==void 0&&c.set(`Vqs-Retention-Seconds`,a.toString()),o!==void 0&&c.set(`Vqs-Delay-Seconds`,o.toString());let u=t.serialize(r),d=Buffer.isBuffer(u)?new Uint8Array(u):u,f=await this.fetch(this.buildUrl(n),{method:`POST`,body:d,headers:c});if(!f.ok){let e=await f.text();if(f.status===409)throw new nu(e||`Duplicate idempotency key detected`,i);if(f.status===502)throw new ru(e||`Consumer discovery failed`,l);if(f.status===503)throw new iu(e||`Consumer registry not configured`);_d(f.status,f.statusText,e,`send message`)}return f.status===202?{messageId:null}:await f.json()}async*receiveMessages(e){let t=this.transport,{queueName:n,consumerGroup:r,visibilityTimeoutSeconds:i,limit:a}=e;if(a!==void 0&&(a<1||a>10))throw new eu(a);let o=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:`multipart/mixed`,...this.customHeaders});i!==void 0&&o.set(`Vqs-Visibility-Timeout-Seconds`,i.toString()),a!==void 0&&o.set(`Vqs-Max-Messages`,a.toString());let s=this.getConsumeDeploymentId();s&&o.set(`Vqs-Deployment-Id`,s);let c=await this.fetch(this.buildUrl(n,`consumer`,r),{method:`POST`,headers:o});if(c.status!==204){if(!c.ok){let e=await c.text();_d(c.status,c.statusText,e,`receive messages`)}for await(let e of rc(c))try{let n=vd(e.headers);if(!n){console.warn(`Missing required queue headers in multipart part`),await gd(e.payload);continue}let r=await t.deserialize(e.payload);yield{...n,payload:r}}catch(t){console.warn(`Failed to process multipart message:`,t),await gd(e.payload)}}}async receiveMessageById(e){let t=this.transport,{queueName:n,consumerGroup:r,messageId:i,visibilityTimeoutSeconds:a}=e,o=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:`multipart/mixed`,...this.customHeaders});a!==void 0&&o.set(`Vqs-Visibility-Timeout-Seconds`,a.toString());let s=this.getConsumeDeploymentId();s&&o.set(`Vqs-Deployment-Id`,s);let c=await this.fetch(this.buildUrl(n,`consumer`,r,`id`,i),{method:`POST`,headers:o});if(!c.ok){let e=await c.text();if(c.status===404)throw new ql(i);if(c.status===409){let t={};try{t=JSON.parse(e)}catch{}throw t.originalMessageId?new Jl(i,`This message was a duplicate - use originalMessageId: ${t.originalMessageId}`):new Jl(i)}if(c.status===410)throw new tu(i);_d(c.status,c.statusText,e,`receive message by ID`)}for await(let e of rc(c)){let n=vd(e.headers);if(!n)throw await gd(e.payload),new Yl(i,`Missing required queue headers in response`);let r=await t.deserialize(e.payload);return{message:{...n,payload:r}}}throw new ql(i)}async acknowledgeMessage(e){let{queueName:t,consumerGroup:n,receiptHandle:r}=e,i=new Headers({Authorization:`Bearer ${await this.getToken()}`,...this.customHeaders}),a=this.getConsumeDeploymentId();a&&i.set(`Vqs-Deployment-Id`,a);let o=await this.fetch(this.buildUrl(t,`consumer`,n,`lease`,r),{method:`DELETE`,headers:i});if(!o.ok){let e=await o.text();if(o.status===404)throw new ql(r);if(o.status===409)throw new Jl(r,e||`Invalid receipt handle, message not in correct state, or already processed`);_d(o.status,o.statusText,e,`acknowledge message`,`Missing or invalid receipt handle`)}return{acknowledged:!0}}async changeVisibility(e){let{queueName:t,consumerGroup:n,receiptHandle:r,visibilityTimeoutSeconds:i}=e,a=new Headers({Authorization:`Bearer ${await this.getToken()}`,"Content-Type":`application/json`,...this.customHeaders}),o=this.getConsumeDeploymentId();o&&a.set(`Vqs-Deployment-Id`,o);let s=await this.fetch(this.buildUrl(t,`consumer`,n,`lease`,r),{method:`PATCH`,headers:a,body:JSON.stringify({visibilityTimeoutSeconds:i})});if(!s.ok){let e=await s.text();if(s.status===404)throw new ql(r);if(s.status===409)throw new Jl(r,e||`Invalid receipt handle, message not in correct state, or already processed`);_d(s.status,s.statusText,e,`change visibility`,`Missing receipt handle or invalid visibility timeout`)}return{success:!0}}},Cd=new WeakMap,wd=Symbol.for(`@vercel/queue.apiClient`);function Td(e,t){Cd.set(e,t),Object.defineProperty(e,wd,{value:t,writable:!1,enumerable:!1,configurable:!1})}function Ed(e){let t=Cd.get(e);if(t)return t;let n=e[wd];if(typeof n==`object`&&n){let t=n;return Cd.set(e,t),t}throw Error(`QueueClient not initialized. This may happen when multiple bundled copies of @vercel/queue are loaded in local dev.`)}function Dd(e){return`request`in e?e.request:e}function Od(e){return Ed(e)}var kd=`iad1`;function Ad(e){return e||process.env.VERCEL_REGION||(Du()||console.warn(`[QueueClient] Region not detected \u2014 defaulting to "${kd}". On Vercel this is set automatically via VERCEL_REGION. To silence this warning, pass region explicitly: new QueueClient({ region: "iad1" })`),kd)}var jd=class{constructor(e={}){let t=Ad(e.region);Td(this,new Sd({...e,region:t}))}send=async(e,t,n)=>{let r=Ed(this),i=await r.sendMessage({queueName:e,payload:t,idempotencyKey:n?.idempotencyKey,retentionSeconds:n?.retentionSeconds,delaySeconds:n?.delaySeconds,headers:n?.headers});return i.messageId&&Du()&&pd(e,i.messageId,r.getRegion(),n?.delaySeconds,n?.retentionSeconds),{messageId:i.messageId}};handleCallback=(e,t)=>(Du()&&Uu(e,this,t),async n=>{let r=Dd(n);if(Du()&&r.headers.get(`x-vercel-queue-prime`)===`1`){let n=r.headers.get(`x-vercel-queue-prime-file`);return n&&Uu(e,this,t,n),Response.json({status:`primed`})}try{return await Su(e,await xu(r),{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),Response.json({status:`success`})}catch(e){return console.error(`Queue callback error:`,e),e instanceof Error&&(e.message.includes(`Invalid content type`)||e.message.includes(`Invalid CloudEvent`)||e.message.includes(`Missing required CloudEvent`)||e.message.includes(`Failed to parse CloudEvent`)||e.message.includes(`Binary mode callback`))?Response.json({error:e.message},{status:400}):Response.json({error:`Failed to process queue message`},{status:500})}});handleNodeCallback=(e,t)=>(Du()&&Uu(e,this,t),async(n,r)=>{if(n.method!==`POST`){r.status(200).end();return}let i=n.headers[`x-vercel-queue-prime`];if(Du()&&i===`1`){let i=n.headers[`x-vercel-queue-prime-file`],a=Array.isArray(i)?i[0]:i;a&&Uu(e,this,t,a),r.status(200).json({status:`primed`});return}try{await Su(e,bu(n.body,n.headers),{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),r.status(200).json({status:`success`})}catch(e){if(console.error(`Queue callback error:`,e),e instanceof Error&&(e.message.includes(`Invalid content type`)||e.message.includes(`Invalid CloudEvent`)||e.message.includes(`Missing required CloudEvent`)||e.message.includes(`Failed to parse CloudEvent`)||e.message.includes(`Binary mode callback`))){r.status(400).json({error:e.message});return}r.status(500).json({error:`Failed to process queue message`})}})};let Md;try{Md=new TextDecoder}catch{}let J,Nd,Y=0;const Pd=[],Fd=57337,Id={};let Ld=11281e4,Rd=1681e4,zd=Pd,Bd=0,X={},Vd,Hd,Ud=0,Wd=0,Gd,Kd,qd=[],Jd=[],Yd,Xd,Zd,Qd={useRecords:!1,mapsAsObjects:!0},$d=!1,ef=2;try{Function(``)}catch{ef=1/0}var tf=class e{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[t,n]of Object.entries(e.keyMap))this.mapKey.set(n,t)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let t=new Map;for(let[n,r]of Object.entries(e))t.set(this._keyMap.hasOwnProperty(n)?this._keyMap[n]:n,r);return t}decodeKeys(e){if(!this._keyMap||e.constructor.name!=`Map`)return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let t={};return e.forEach((e,n)=>t[of(this._mapKey.has(n)?this._mapKey.get(n):n)]=e),t}mapDecode(e,t){let n=this.decode(e);if(this._keyMap)switch(n.constructor.name){case`Array`:return n.map(e=>this.decodeKeys(e))}return n}decode(t,n){if(J)return Af(()=>(jf(),this?this.decode(t,n):e.prototype.decode.call(Qd,t,n)));Nd=n>-1?n:t.length,Y=0,Bd=0,Wd=0,Hd=null,zd=Pd,Gd=null,J=t;try{Xd=t.dataView||=new DataView(t.buffer,t.byteOffset,t.byteLength)}catch(e){throw J=null,t instanceof Uint8Array?e:Error(`Source must be a Uint8Array or Buffer but was a `+(t&&typeof t==`object`?t.constructor.name:typeof t))}if(this instanceof e){if(X=this,Yd=this.sharedValues&&(this.pack?Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return Vd=this.structures,nf();(!Vd||Vd.length>0)&&(Vd=[])}else X=Qd,(!Vd||Vd.length>0)&&(Vd=[]),Yd=null;return nf()}decodeMultiple(e,t){let n,r=0;try{let i=e.length;$d=!0;let a=this?this.decode(e,i):Nf.decode(e,i);if(t){if(t(a)===!1)return;for(;Y<i;)if(r=Y,t(nf())===!1)return}else{for(n=[a];Y<i;)r=Y,n.push(nf());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{$d=!1,jf()}}};function nf(){try{let e=Z();if(Gd){if(Y>=Gd.postBundlePosition){let e=Error(`Unexpected bundle position`);throw e.incomplete=!0,e}Y=Gd.postBundlePosition,Gd=null}if(Y==Nd)Vd=null,J=null,Kd&&=null;else if(Y>Nd){let e=Error(`Unexpected end of CBOR data`);throw e.incomplete=!0,e}else if(!$d)throw Error(`Data read, but end of buffer not reached`);return e}catch(e){throw jf(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`))&&(e.incomplete=!0),e}}function Z(){let e=J[Y++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=J[Y++];break;case 25:if(t==7)return gf();e=Xd.getUint16(Y),Y+=2;break;case 26:if(t==7){let e=Xd.getFloat32(Y);if(X.useFloat32>2){let t=Mf[(J[Y]&127)<<1|J[Y+1]>>7];return Y+=4,(t*e+(e>0?.5:-.5)>>0)/t}return Y+=4,e}e=Xd.getUint32(Y),Y+=4;break;case 27:if(t==7){let e=Xd.getFloat64(Y);return Y+=8,e}if(t>1){if(Xd.getUint32(Y)>0)throw Error(`JavaScript does not support arrays, maps, or strings with length over 4294967295`);e=Xd.getUint32(Y+4)}else X.int64AsNumber?(e=Xd.getUint32(Y)*4294967296,e+=Xd.getUint32(Y+4)):e=Xd.getBigUint64(Y);Y+=8;break;case 31:switch(t){case 2:case 3:throw Error(`Indefinite length not supported for byte or text strings`);case 4:let e=[],n,r=0;for(;(n=Z())!=Id;){if(r>=Ld)throw Error(`Array length exceeds ${Ld}`);e[r++]=n}return t==4?e:t==3?e.join(``):Buffer.concat(e);case 5:let i;if(X.mapsAsObjects){let e={},t=0;if(X.keyMap)for(;(i=Z())!=Id;){if(t++>=Rd)throw Error(`Property count exceeds ${Rd}`);e[of(X.decodeKey(i))]=Z()}else for(;(i=Z())!=Id;){if(t++>=Rd)throw Error(`Property count exceeds ${Rd}`);e[of(i)]=Z()}return e}else{Zd&&=(X.mapsAsObjects=!0,!1);let e=new Map;if(X.keyMap){let t=0;for(;(i=Z())!=Id;){if(t++>=Rd)throw Error(`Map size exceeds ${Rd}`);e.set(X.decodeKey(i),Z())}}else{let t=0;for(;(i=Z())!=Id;){if(t++>=Rd)throw Error(`Map size exceeds ${Rd}`);e.set(i,Z())}}return e}case 7:return Id;default:throw Error(`Invalid major type for indefinite length `+t)}default:throw Error(`Unknown token `+e)}switch(t){case 0:return e;case 1:return~e;case 2:return pf(e);case 3:if(Wd>=Y)return Hd.slice(Y-Ud,(Y+=e)-Ud);if(Wd==0&&Nd<140&&e<32){let t=e<16?ff(e):df(e);if(t!=null)return t}return sf(e);case 4:if(e>=Ld)throw Error(`Array length exceeds ${Ld}`);let t=Array(e);for(let n=0;n<e;n++)t[n]=Z();return t;case 5:if(e>=Rd)throw Error(`Map size exceeds ${Ld}`);if(X.mapsAsObjects){let t={};if(X.keyMap)for(let n=0;n<e;n++)t[of(X.decodeKey(Z()))]=Z();else for(let n=0;n<e;n++)t[of(Z())]=Z();return t}else{Zd&&=(X.mapsAsObjects=!0,!1);let t=new Map;if(X.keyMap)for(let n=0;n<e;n++)t.set(X.decodeKey(Z()),Z());else for(let n=0;n<e;n++)t.set(Z(),Z());return t}case 6:if(e>=Fd){let t=Vd[e&8191];if(t)return t.read||=af(t),t.read();if(e<65536){if(e==57343){let e=Of(),t=Z(),n=Z();vf(t,n);let r={};if(X.keyMap)for(let t=2;t<e;t++){let e=X.decodeKey(n[t-2]);r[of(e)]=Z()}else for(let t=2;t<e;t++){let e=n[t-2];r[of(e)]=Z()}return r}else if(e==57342){let e=Of(),t=Z();for(let n=2;n<e;n++)vf(t++,Z());return Z()}else if(e==Fd)return Df();if(X.getShared&&(kf(),t=Vd[e&8191],t))return t.read||=af(t),t.read()}}let n=qd[e];if(n)return n.handlesRead?n(Z):n(Z());{let t=Z();for(let n=0;n<Jd.length;n++){let r=Jd[n](e,t);if(r!==void 0)return r}return new _f(t,e)}case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let t=(Yd||Sf())[e];if(t!==void 0)return t;throw Error(`Unknown token `+e)}default:if(isNaN(e)){let e=Error(`Unexpected end of CBOR data`);throw e.incomplete=!0,e}throw Error(`Unknown CBOR token `+e)}}const rf=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function af(e){if(!e)throw Error(`Structure is required in record definition`);function t(){let e=J[Y++];if(e&=31,e>23)switch(e){case 24:e=J[Y++];break;case 25:e=Xd.getUint16(Y),Y+=2;break;case 26:e=Xd.getUint32(Y),Y+=4;break;default:throw Error(`Expected array header, but got `+J[Y-1])}let t=this.compiledReader;for(;t;){if(t.propertyCount===e)return t(Z);t=t.next}if(this.slowReads++>=ef){let n=this.length==e?this:this.slice(0,e);return t=X.keyMap?Function(`r`,`return {`+n.map(e=>X.decodeKey(e)).map(e=>rf.test(e)?of(e)+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`}`):Function(`r`,`return {`+n.map(e=>rf.test(e)?of(e)+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`}`),this.compiledReader&&(t.next=this.compiledReader),t.propertyCount=e,this.compiledReader=t,t(Z)}let n={};if(X.keyMap)for(let t=0;t<e;t++)n[of(X.decodeKey(this[t]))]=Z();else for(let t=0;t<e;t++)n[of(this[t])]=Z();return n}return e.slowReads=0,t}function of(e){if(typeof e==`string`)return e===`__proto__`?`__proto_`:e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(e==null)return e+``;throw Error(`Invalid property name type `+typeof e)}let sf=lf;function cf(e){sf=t(1);function t(t){return function(t){let n=zd[Bd++];if(n==null){if(Gd)return lf(t);let r=e(Y,Nd,t,J);if(typeof r==`string`)n=r,zd=Pd;else if(zd=r,Bd=1,Wd=1,n=zd[0],n===void 0)throw Error(`Unexpected end of buffer`)}let r=n.length;return r<=t?(Y+=t,n):(Hd=n,Ud=Y,Wd=Y+r,Y+=t,n.slice(0,t))}}}function lf(e){let t;if(e<16&&(t=ff(e)))return t;if(e>64&&Md)return Md.decode(J.subarray(Y,Y+=e));let n=Y+e,r=[];for(t=``;Y<n;){let e=J[Y++];if(!(e&128))r.push(e);else if((e&224)==192){let t=J[Y++]&63;r.push((e&31)<<6|t)}else if((e&240)==224){let t=J[Y++]&63,n=J[Y++]&63;r.push((e&31)<<12|t<<6|n)}else if((e&248)==240){let t=J[Y++]&63,n=J[Y++]&63,i=J[Y++]&63,a=(e&7)<<18|t<<12|n<<6|i;a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a)}else r.push(e);r.length>=4096&&(t+=uf.apply(String,r),r.length=0)}return r.length>0&&(t+=uf.apply(String,r)),t}let uf=String.fromCharCode;function df(e){let t=Y,n=Array(e);for(let r=0;r<e;r++){let e=J[Y++];if((e&128)>0){Y=t;return}n[r]=e}return uf.apply(String,n)}function ff(e){if(e<4)if(e<2){if(e===0)return``;{let e=J[Y++];if((e&128)>1){--Y;return}return uf(e)}}else{let t=J[Y++],n=J[Y++];if((t&128)>0||(n&128)>0){Y-=2;return}if(e<3)return uf(t,n);let r=J[Y++];if((r&128)>0){Y-=3;return}return uf(t,n,r)}else{let t=J[Y++],n=J[Y++],r=J[Y++],i=J[Y++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){Y-=4;return}if(e<6){if(e===4)return uf(t,n,r,i);{let e=J[Y++];if((e&128)>0){Y-=5;return}return uf(t,n,r,i,e)}}else if(e<8){let a=J[Y++],o=J[Y++];if((a&128)>0||(o&128)>0){Y-=6;return}if(e<7)return uf(t,n,r,i,a,o);let s=J[Y++];if((s&128)>0){Y-=7;return}return uf(t,n,r,i,a,o,s)}else{let a=J[Y++],o=J[Y++],s=J[Y++],c=J[Y++];if((a&128)>0||(o&128)>0||(s&128)>0||(c&128)>0){Y-=8;return}if(e<10){if(e===8)return uf(t,n,r,i,a,o,s,c);{let e=J[Y++];if((e&128)>0){Y-=9;return}return uf(t,n,r,i,a,o,s,c,e)}}else if(e<12){let l=J[Y++],u=J[Y++];if((l&128)>0||(u&128)>0){Y-=10;return}if(e<11)return uf(t,n,r,i,a,o,s,c,l,u);let d=J[Y++];if((d&128)>0){Y-=11;return}return uf(t,n,r,i,a,o,s,c,l,u,d)}else{let l=J[Y++],u=J[Y++],d=J[Y++],f=J[Y++];if((l&128)>0||(u&128)>0||(d&128)>0||(f&128)>0){Y-=12;return}if(e<14){if(e===12)return uf(t,n,r,i,a,o,s,c,l,u,d,f);{let e=J[Y++];if((e&128)>0){Y-=13;return}return uf(t,n,r,i,a,o,s,c,l,u,d,f,e)}}else{let p=J[Y++],m=J[Y++];if((p&128)>0||(m&128)>0){Y-=14;return}if(e<15)return uf(t,n,r,i,a,o,s,c,l,u,d,f,p,m);let h=J[Y++];if((h&128)>0){Y-=15;return}return uf(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function pf(e){return X.copyBuffers?Uint8Array.prototype.slice.call(J,Y,Y+=e):J.subarray(Y,Y+=e)}let mf=new Float32Array(1),hf=new Uint8Array(mf.buffer,0,4);function gf(){let e=J[Y++],t=J[Y++],n=(e&127)>>2;if(n===31)return t||e&3?NaN:e&128?-1/0:1/0;if(n===0){let n=((e&3)<<8|t)/(1<<24);return e&128?-n:n}return hf[3]=e&128|(n>>1)+56,hf[2]=(e&7)<<5|t>>3,hf[1]=t<<5,hf[0]=0,mf[0]}Array(4096);var _f=class{constructor(e,t){this.value=e,this.tag=t}};qd[0]=e=>new Date(e),qd[1]=e=>new Date(Math.round(e*1e3)),qd[2]=e=>{let t=BigInt(0);for(let n=0,r=e.byteLength;n<r;n++)t=BigInt(e[n])+(t<<BigInt(8));return t},qd[3]=e=>BigInt(-1)-qd[2](e),qd[4]=e=>+(e[1]+`e`+e[0]),qd[5]=e=>e[1]*Math.exp(e[0]*Math.log(2));const vf=(e,t)=>{e-=57344;let n=Vd[e];n&&n.isShared&&((Vd.restoreStructures||=[])[e]=n),Vd[e]=t,t.read=af(t)};qd[105]=e=>{let t=e.length,n=e[1];vf(e[0],n);let r={};for(let i=2;i<t;i++){let t=n[i-2];r[of(t)]=e[i]}return r},qd[14]=e=>Gd?Gd[0].slice(Gd.position0,Gd.position0+=e):new _f(e,14),qd[15]=e=>Gd?Gd[1].slice(Gd.position1,Gd.position1+=e):new _f(e,15);let yf={Error,RegExp};qd[27]=e=>(yf[e[0]]||Error)(e[1],e[2]);const bf=e=>{if(J[Y++]!=132){let e=Error(`Packed values structure must be followed by a 4 element array`);throw J.length<Y&&(e.incomplete=!0),e}let t=e();if(!t||!t.length){let e=Error(`Packed values structure must be followed by a 4 element array`);throw e.incomplete=!0,e}return Yd=Yd?t.concat(Yd.slice(t.length)):t,Yd.prefixes=e(),Yd.suffixes=e(),e()};bf.handlesRead=!0,qd[51]=bf,qd[6]=e=>{if(!Yd)if(X.getShared)kf();else return new _f(e,6);if(typeof e==`number`)return Yd[16+(e>=0?2*e:-2*e-1)];let t=Error(`No support for non-integer packed references yet`);throw e===void 0&&(t.incomplete=!0),t},qd[28]=e=>{Kd||(Kd=new Map,Kd.id=0);let t=Kd.id++,n=Y,r=J[Y],i;i=r>>5==4?[]:{};let a={target:i};Kd.set(t,a);let o=e();return a.used?(Object.getPrototypeOf(i)!==Object.getPrototypeOf(o)&&(Y=n,i=o,Kd.set(t,{target:i}),o=e()),Object.assign(i,o)):(a.target=o,o)},qd[28].handlesRead=!0,qd[29]=e=>{let t=Kd.get(e);return t.used=!0,t.target},qd[258]=e=>new Set(e),(qd[259]=e=>(X.mapsAsObjects&&(X.mapsAsObjects=!1,Zd=!0),e())).handlesRead=!0;function xf(e,t){return typeof e==`string`?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function Sf(){if(!Yd)if(X.getShared)kf();else throw Error(`No packed values available`);return Yd}Jd.push((e,t)=>{if(e>=225&&e<=255)return xf(Sf().prefixes[e-224],t);if(e>=28704&&e<=32767)return xf(Sf().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return xf(Sf().prefixes[e-1879048192],t);if(e>=216&&e<=223)return xf(t,Sf().suffixes[e-216]);if(e>=27647&&e<=28671)return xf(t,Sf().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return xf(t,Sf().suffixes[e-1811939328]);if(e==1399353956)return{packedValues:Yd,structures:Vd.slice(0),version:t};if(e==55799)return t});const Cf=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,wf=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>`u`?{name:`BigUint64Array`}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>`u`?{name:`BigInt64Array`}:BigInt64Array,Float32Array,Float64Array],Tf=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e<wf.length;e++)Ef(wf[e],Tf[e]);function Ef(e,t){let n=`get`+e.name.slice(0,-5),r;typeof e==`function`?r=e.BYTES_PER_ELEMENT:e=null;for(let i=0;i<2;i++){if(!i&&r==1)continue;let a=r==2?1:r==4?2:r==8?3:0;qd[i?t:t-4]=r==1||i==Cf?n=>{if(!e)throw Error(`Could not find typed array for code `+t);return!X.copyBuffers&&(r===1||r===2&&!(n.byteOffset&1)||r===4&&!(n.byteOffset&3)||r===8&&!(n.byteOffset&7))?new e(n.buffer,n.byteOffset,n.byteLength>>a):new e(Uint8Array.prototype.slice.call(n,0).buffer)}:r=>{if(!e)throw Error(`Could not find typed array for code `+t);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),s=r.length>>a,c=new e(s),l=o[n];for(let e=0;e<s;e++)c[e]=l.call(o,e<<a,i);return c}}}function Df(){let e=Of(),t=Y+Z();for(let t=2;t<e;t++){let e=Of();Y+=e}let n=Y;return Y=t,Gd=[lf(Of()),lf(Of())],Gd.position0=0,Gd.position1=0,Gd.postBundlePosition=Y,Y=n,Z()}function Of(){let e=J[Y++]&31;if(e>23)switch(e){case 24:e=J[Y++];break;case 25:e=Xd.getUint16(Y),Y+=2;break;case 26:e=Xd.getUint32(Y),Y+=4;break}return e}function kf(){if(X.getShared){let e=Af(()=>(J=null,X.getShared()))||{},t=e.structures||[];X.sharedVersion=e.version,Yd=X.sharedValues=e.packedValues,Vd===!0?X.structures=Vd=t:Vd.splice.apply(Vd,[0,t.length].concat(t))}}function Af(e){let t=Nd,n=Y,r=Bd,i=Ud,a=Wd,o=Hd,s=zd,c=Kd,l=Gd,u=new Uint8Array(J.slice(0,Nd)),d=Vd,f=X,p=$d,m=e();return Nd=t,Y=n,Bd=r,Ud=i,Wd=a,Hd=o,zd=s,Kd=c,Gd=l,J=u,$d=p,Vd=d,X=f,Xd=new DataView(J.buffer,J.byteOffset,J.byteLength),m}function jf(){J=null,Kd=null,Vd=null}const Mf=Array(147);for(let e=0;e<256;e++)Mf[e]=+(`1e`+Math.floor(45.15-e*.30103));let Nf=new tf({useRecords:!1});const Pf=Nf.decode;Nf.decodeMultiple;const Ff={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};let If;try{If=new TextEncoder}catch{}let Lf,Rf;const zf=typeof globalThis==`object`&&globalThis.Buffer,Bf=zf!==void 0,Vf=Bf?zf.allocUnsafeSlow:Uint8Array,Hf=Bf?zf:Uint8Array,Uf=Bf?4294967296:2144337920;let Wf,Q,Gf,$=0,Kf,qf=null;const Jf=/[\u0080-\uFFFF]/,Yf=Symbol(`record-id`);var Xf=class extends tf{constructor(e){super(e),this.offset=0;let t,n,r,i,a;e||={};let o=Hf.prototype.utf8Write?function(e,t,n){return Q.utf8Write(e,t,n)}:If&&If.encodeInto?function(e,t){return If.encodeInto(e,Q.subarray(t)).written}:!1,s=this,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(l??=c?128:0,l>8190)throw Error(`Maximum maxSharedStructure is 8190`);let u=e.sequential;u&&(l=0),this.structures||=[],this.saveStructures&&(this.saveShared=this.saveStructures);let d,f,p=e.sharedValues,m;if(p){m=Object.create(null);for(let e=0,t=p.length;e<t;e++)m[p[e]]=e}let h=[],g=0,_=0;this.mapEncode=function(e,t){if(this._keyMap&&!this._mapped)switch(e.constructor.name){case`Array`:e=e.map(e=>this.encodeKeys(e));break}return this.encode(e,t)},this.encode=function(o,c){if(Q||(Q=new Vf(8192),Gf=new DataView(Q.buffer,0,8192),$=0),Kf=Q.length-10,Kf-$<2048?(Q=new Vf(Q.length),Gf=new DataView(Q.buffer,0,Q.length),Kf=Q.length-10,$=0):c===512&&($=$+7&2147483640),t=$,s.useSelfDescribedHeader&&(Gf.setUint32($,3654940416),$+=3),a=s.structuredClone?new Map:null,s.bundleStrings&&typeof o!=`string`?(qf=[],qf.size=1/0):qf=null,n=s.structures,n){if(n.uninitialized){let e=s.getShared()||{};s.structures=n=e.structures||[],s.sharedVersion=e.version;let t=s.sharedValues=e.packedValues;if(t){m={};for(let e=0,n=t.length;e<n;e++)m[t[e]]=e}}let e=n.length;if(e>l&&!u&&(e=l),!n.transitions){n.transitions=Object.create(null);for(let t=0;t<e;t++){let e=n[t];if(!e)continue;let r,i=n.transitions;for(let n=0,a=e.length;n<a;n++){i[Yf]===void 0&&(i[Yf]=t);let a=e[n];r=i[a],r||=i[a]=Object.create(null),i=r}i[Yf]=t|1048576}}u||(n.nextId=e)}if(r&&=!1,i=n||[],f=m,e.pack){let t=new Map;if(t.values=[],t.encoder=s,t.maxValues=e.maxPrivatePackedValues||(m?16:1/0),t.objectMap=m||!1,t.samplingPackedValues=d,np(o,t),t.values.length>0){Q[$++]=216,Q[$++]=51,$f(4);let e=t.values;v(e),$f(0),$f(0),f=Object.create(m||null);for(let t=0,n=e.length;t<n;t++)f[e[t]]=t}}Wf=c&mp;try{if(Wf)return;if(v(o),qf&&sp(t,v),s.offset=$,a&&a.idsToInsert){$+=a.idsToInsert.length*2,$>Kf&&b($),s.offset=$;let e=op(Q.subarray(t,$),a.idsToInsert);return a=null,e}return c&512?(Q.start=t,Q.end=$,Q):Q.subarray(t,$)}finally{if(n){if(_<10&&_++,n.length>l&&(n.length=l),g>1e4)n.transitions=null,_=0,g=0,h.length>0&&(h=[]);else if(h.length>0&&!u){for(let e=0,t=h.length;e<t;e++)h[e][Yf]=void 0;h=[]}}if(r&&s.saveShared){s.structures.length>l&&(s.structures=s.structures.slice(0,l));let e=Q.subarray(t,$);return s.updateSharedData()===!1?s.encode(o):e}c&1024&&($=t)}},this.findCommonStringsToPack=()=>(d=new Map,m||=Object.create(null),e=>{let t=e&&e.threshold||4,n=this.pack?e.maxPrivatePackedValues||16:0;p||=this.sharedValues=[];for(let[e,i]of d)i.count>t&&(m[e]=n++,p.push(e),r=!0);for(;this.saveShared&&this.updateSharedData()===!1;);d=null});let v=n=>{$>Kf&&(Q=b($));var r=typeof n,i;if(r===`string`){if(f){let t=f[n];if(t>=0){t<16?Q[$++]=t+224:(Q[$++]=198,t&1?v(15-t>>1):v(t-16>>1));return}else if(d&&!e.pack){let e=d.get(n);e?e.count++:d.set(n,{count:1})}}let r=n.length;if(qf&&r>=4&&r<1024){if((qf.size+=r)>61440){let e,n=(qf[0]?qf[0].length*3+qf[1].length:0)+10;$+n>Kf&&(Q=b($+n)),Q[$++]=217,Q[$++]=223,Q[$++]=249,Q[$++]=qf.position?132:130,Q[$++]=26,e=$-t,$+=4,qf.position&&sp(t,v),qf=[``,``],qf.size=0,qf.position=e}let e=Jf.test(n);qf[+!e]+=n,Q[$++]=e?206:207,v(r);return}let a;a=r<32?1:r<256?2:r<65536?3:5;let s=r*3;if($+s>Kf&&(Q=b($+s)),r<64||!o){let e,t,o,s=$+a;for(e=0;e<r;e++)t=n.charCodeAt(e),t<128?Q[s++]=t:t<2048?(Q[s++]=t>>6|192,Q[s++]=t&63|128):(t&64512)==55296&&((o=n.charCodeAt(e+1))&64512)==56320?(t=65536+((t&1023)<<10)+(o&1023),e++,Q[s++]=t>>18|240,Q[s++]=t>>12&63|128,Q[s++]=t>>6&63|128,Q[s++]=t&63|128):(Q[s++]=t>>12|224,Q[s++]=t>>6&63|128,Q[s++]=t&63|128);i=s-$-a}else i=o(n,$+a,s);i<24?Q[$++]=96|i:i<256?(a<2&&Q.copyWithin($+2,$+1,$+1+i),Q[$++]=120,Q[$++]=i):i<65536?(a<3&&Q.copyWithin($+3,$+2,$+2+i),Q[$++]=121,Q[$++]=i>>8,Q[$++]=i&255):(a<5&&Q.copyWithin($+5,$+3,$+3+i),Q[$++]=122,Gf.setUint32($,i),$+=4),$+=i}else if(r===`number`)if(!this.alwaysUseFloat&&n>>>0===n)n<24?Q[$++]=n:n<256?(Q[$++]=24,Q[$++]=n):n<65536?(Q[$++]=25,Q[$++]=n>>8,Q[$++]=n&255):(Q[$++]=26,Gf.setUint32($,n),$+=4);else if(!this.alwaysUseFloat&&n>>0===n)n>=-24?Q[$++]=31-n:n>=-256?(Q[$++]=56,Q[$++]=~n):n>=-65536?(Q[$++]=57,Gf.setUint16($,~n),$+=2):(Q[$++]=58,Gf.setUint32($,~n),$+=4);else{let e;if((e=this.useFloat32)>0&&n<4294967296&&n>=-2147483648){Q[$++]=250,Gf.setFloat32($,n);let t;if(e<4||(t=n*Mf[(Q[$]&127)<<1|Q[$+1]>>7])>>0===t){$+=4;return}else $--}Q[$++]=251,Gf.setFloat64($,n),$+=8}else if(r===`object`)if(!n)Q[$++]=246;else{if(a){let e=a.get(n);if(e){if(Q[$++]=216,Q[$++]=29,Q[$++]=25,!e.references){let t=a.idsToInsert||=[];e.references=[],t.push(e)}e.references.push($-t),$+=2;return}else a.set(n,{offset:$-t})}let e=n.constructor;if(e===Object)y(n);else if(e===Array){i=n.length,i<24?Q[$++]=128|i:$f(i);for(let e=0;e<i;e++)v(n[e])}else if(e===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(Q[$++]=217,Q[$++]=1,Q[$++]=3),i=n.size,i<24?Q[$++]=160|i:i<256?(Q[$++]=184,Q[$++]=i):i<65536?(Q[$++]=185,Q[$++]=i>>8,Q[$++]=i&255):(Q[$++]=186,Gf.setUint32($,i),$+=4),s.keyMap)for(let[e,t]of n)v(s.encodeKey(e)),v(t);else for(let[e,t]of n)v(e),v(t);else{for(let e=0,t=Lf.length;e<t;e++){let t=Rf[e];if(n instanceof t){let t=Lf[e],r=t.tag;r??=t.getTag&&t.getTag.call(this,n),r<24?Q[$++]=192|r:r<256?(Q[$++]=216,Q[$++]=r):r<65536?(Q[$++]=217,Q[$++]=r>>8,Q[$++]=r&255):r>-1&&(Q[$++]=218,Gf.setUint32($,r),$+=4),t.encode.call(this,n,v,b);return}}if(n[Symbol.iterator]){if(Wf){let e=Error(`Iterable should be serialized as iterator`);throw e.iteratorNotHandled=!0,e}Q[$++]=159;for(let e of n)v(e);Q[$++]=255;return}if(n[Symbol.asyncIterator]||tp(n)){let e=Error(`Iterable/blob should be serialized as iterator`);throw e.iteratorNotHandled=!0,e}if(this.useToJSON&&n.toJSON){let e=n.toJSON();if(e!==n)return v(e)}y(n)}}else if(r===`boolean`)Q[$++]=n?245:244;else if(r===`bigint`){if(n<BigInt(1)<<BigInt(64)&&n>=0)Q[$++]=27,Gf.setBigUint64($,n);else if(n>-(BigInt(1)<<BigInt(64))&&n<0)Q[$++]=59,Gf.setBigUint64($,-n-BigInt(1));else if(this.largeBigIntToFloat)Q[$++]=251,Gf.setFloat64($,Number(n));else{n>=BigInt(0)?Q[$++]=194:(Q[$++]=195,n=BigInt(-1)-n);let e=[];for(;n;)e.push(Number(n&BigInt(255))),n>>=BigInt(8);ap(new Uint8Array(e.reverse()),b);return}$+=8}else if(r===`undefined`)Q[$++]=247;else throw Error(`Unknown type: `+r)},y=this.useRecords===!1?this.variableMapSize?e=>{let t=Object.keys(e),n=Object.values(e),r=t.length;if(r<24?Q[$++]=160|r:r<256?(Q[$++]=184,Q[$++]=r):r<65536?(Q[$++]=185,Q[$++]=r>>8,Q[$++]=r&255):(Q[$++]=186,Gf.setUint32($,r),$+=4),s.keyMap)for(let e=0;e<r;e++)v(s.encodeKey(t[e])),v(n[e]);else for(let e=0;e<r;e++)v(t[e]),v(n[e])}:e=>{Q[$++]=185;let n=$-t;$+=2;let r=0;if(s.keyMap)for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(v(s.encodeKey(t)),v(e[t]),r++);else for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(v(t),v(e[t]),r++);Q[n+++t]=r>>8,Q[n+t]=r&255}:(e,t)=>{let n,a=i.transitions||=Object.create(null),o=0,s=0,c,u;if(this.keyMap){u=Object.keys(e).map(e=>this.encodeKey(e)),s=u.length;for(let e=0;e<s;e++){let t=u[e];n=a[t],n||(n=a[t]=Object.create(null),o++),a=n}}else for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(n=a[t],n||(a[Yf]&1048576&&(c=a[Yf]&65535),n=a[t]=Object.create(null),o++),a=n,s++);let d=a[Yf];if(d!==void 0)d&=65535,Q[$++]=217,Q[$++]=d>>8|224,Q[$++]=d&255;else if(u||=a.__keys__||=Object.keys(e),c===void 0?(d=i.nextId++,d||(d=0,i.nextId=1),d>=256&&(i.nextId=(d=l)+1)):d=c,i[d]=u,d<l){Q[$++]=217,Q[$++]=d>>8|224,Q[$++]=d&255,a=i.transitions;for(let e=0;e<s;e++)(a[Yf]===void 0||a[Yf]&1048576)&&(a[Yf]=d),a=a[u[e]];a[Yf]=d|1048576,r=!0}else{if(a[Yf]=d,Gf.setUint32($,3655335680),$+=3,o&&(g+=_*o),h.length>=256-l&&(h.shift()[Yf]=void 0),h.push(a),$f(s+2),v(57344+d),v(u),t)return;for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&v(e[t]);return}if(s<24?Q[$++]=128|s:$f(s),!t)for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&v(e[t])},b=e=>{let n;if(e>16777216){if(e-t>Uf)throw Error(`Encoded buffer would be larger than maximum buffer size`);n=Math.min(Uf,Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096)*4096)}else n=(Math.max(e-t<<2,Q.length-1)>>12)+1<<12;let r=new Vf(n);return Gf=new DataView(r.buffer,0,n),Q.copy?Q.copy(r,0,t,e):r.set(Q.slice(t,e)),$-=t,t=0,Kf=r.length-10,Q=r},x=100,S=1e3;this.encodeAsIterable=function(e,t){return E(e,t,C)},this.encodeAsAsyncIterable=function(e,t){return E(e,t,D)};function*C(e,n,r){let i=e.constructor;if(i===Object){let t=s.useRecords!==!1;t?y(e,!0):Zf(Object.keys(e).length,160);for(let r in e){let i=e[r];t||v(r),i&&typeof i==`object`?n[r]?yield*C(i,n[r]):yield*w(i,n,r):v(i)}}else if(i===Array){let r=e.length;$f(r);for(let i=0;i<r;i++){let r=e[i];r&&(typeof r==`object`||$-t>x)?n.element?yield*C(r,n.element):yield*w(r,n,`element`):v(r)}}else if(e[Symbol.iterator]&&!e.buffer){Q[$++]=159;for(let r of e)r&&(typeof r==`object`||$-t>x)?n.element?yield*C(r,n.element):yield*w(r,n,`element`):v(r);Q[$++]=255}else tp(e)?(Zf(e.size,64),yield Q.subarray(t,$),yield e,T()):e[Symbol.asyncIterator]?(Q[$++]=159,yield Q.subarray(t,$),yield e,T(),Q[$++]=255):v(e);r&&$>t?yield Q.subarray(t,$):$-t>x&&(yield Q.subarray(t,$),T())}function*w(e,n,r){let i=$-t;try{v(e),$-t>x&&(yield Q.subarray(t,$),T())}catch(a){if(a.iteratorNotHandled)n[r]={},$=t+i,yield*C.call(this,e,n[r]);else throw a}}function T(){x=S,s.encode(null,mp)}function E(e,t,n){return x=t&&t.chunkThreshold?S=t.chunkThreshold:100,e&&typeof e==`object`?(s.encode(null,mp),n(e,s.iterateProperties||={},!0)):[s.encode(e)]}async function*D(e,t){for(let n of C(e,t,!0)){let e=n.constructor;if(e===Hf||e===Uint8Array)yield n;else if(tp(n)){let e=n.stream().getReader(),t;for(;!(t=await e.read()).done;)yield t.value}else if(n[Symbol.asyncIterator])for await(let e of n)T(),e?yield*D(e,t.async||={}):yield s.encode(e);else yield n}}}useBuffer(e){Q=e,Gf=new DataView(Q.buffer,Q.byteOffset,Q.byteLength),$=0}clearSharedData(){this.structures&&=[],this.sharedValues&&=void 0}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let t=this.structures.slice(0),n=new Qf(t,this.sharedValues,this.sharedVersion),r=this.saveShared(n,t=>(t&&t.version||0)==e);return r===!1?(n=this.getShared()||{},this.structures=n.structures||[],this.sharedValues=n.packedValues,this.sharedVersion=n.version,this.structures.nextId=this.structures.length):t.forEach((e,t)=>this.structures[t]=e),r}};function Zf(e,t){e<24?Q[$++]=t|e:e<256?(Q[$++]=t|24,Q[$++]=e):e<65536?(Q[$++]=t|25,Q[$++]=e>>8,Q[$++]=e&255):(Q[$++]=t|26,Gf.setUint32($,e),$+=4)}var Qf=class{constructor(e,t,n){this.structures=e,this.packedValues=t,this.version=n}};function $f(e){e<24?Q[$++]=128|e:e<256?(Q[$++]=152,Q[$++]=e):e<65536?(Q[$++]=153,Q[$++]=e>>8,Q[$++]=e&255):(Q[$++]=154,Gf.setUint32($,e),$+=4)}const ep=typeof Blob>`u`?function(){}:Blob;function tp(e){if(e instanceof ep)return!0;let t=e[Symbol.toStringTag];return t===`Blob`||t===`File`}function np(e,t){switch(typeof e){case`string`:if(e.length>3){if(t.objectMap[e]>-1||t.values.length>=t.maxValues)return;let n=t.get(e);if(n)++n.count==2&&t.values.push(e);else if(t.set(e,{count:1}),t.samplingPackedValues){let n=t.samplingPackedValues.get(e);n?n.count++:t.samplingPackedValues.set(e,{count:1})}}break;case`object`:if(e)if(e instanceof Array)for(let n=0,r=e.length;n<r;n++)np(e[n],t);else{let r=!t.encoder.useRecords;for(var n in e)e.hasOwnProperty(n)&&(r&&np(n,t),np(e[n],t))}break;case`function`:console.log(e)}}const rp=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Rf=[Date,Set,Error,RegExp,_f,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>`u`?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>`u`?function(){}:BigInt64Array,Float32Array,Float64Array,Qf],Lf=[{tag:1,encode(e,t){let n=e.getTime()/1e3;(this.useTimestamp32||e.getMilliseconds()===0)&&n>=0&&n<4294967296?(Q[$++]=26,Gf.setUint32($,n),$+=4):(Q[$++]=251,Gf.setFloat64($,n),$+=8)}},{tag:258,encode(e,t){t(Array.from(e))}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t([`RegExp`,e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,n){ap(e,n)}},{getTag(e){if(e.constructor===Uint8Array&&(this.tagUint8Array||Bf&&this.tagUint8Array!==!1))return 64},encode(e,t,n){ap(e,n)}},ip(68,1),ip(69,2),ip(70,4),ip(71,8),ip(72,1),ip(77,2),ip(78,4),ip(79,8),ip(85,4),ip(86,8),{encode(e,t){let n=e.packedValues||[],r=e.structures||[];if(n.values.length>0){Q[$++]=216,Q[$++]=51,$f(4);let e=n.values;t(e),$f(0),$f(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let t=0,n=e.length;t<n;t++)packedObjectMap[e[t]]=t}if(r){Gf.setUint32($,3655335424),$+=3;let n=r.slice(0);n.unshift(57344),n.push(new _f(e.version,1399353956)),t(n)}else t(new _f(e.version,1399353956))}}];function ip(e,t){return!rp&&t>1&&(e-=4),{tag:e,encode:function(e,t){let n=e.byteLength,r=e.byteOffset||0,i=e.buffer||e;t(Bf?zf.from(i,r,n):new Uint8Array(i,r,n))}}}function ap(e,t){let n=e.byteLength;n<24?Q[$++]=64+n:n<256?(Q[$++]=88,Q[$++]=n):n<65536?(Q[$++]=89,Q[$++]=n>>8,Q[$++]=n&255):(Q[$++]=90,Gf.setUint32($,n),$+=4),$+n>=Q.length&&t($+n),Q.set(e.buffer?e:new Uint8Array(e),$),$+=n}function op(e,t){let n,r=t.length*2,i=e.length-r;t.sort((e,t)=>e.offset>t.offset?1:-1);for(let n=0;n<t.length;n++){let r=t[n];r.id=n;for(let t of r.references)e[t++]=n>>8,e[t]=n&255}for(;n=t.pop();){let t=n.offset;e.copyWithin(t+r,t,i),r-=2;let a=t+r;e[a++]=216,e[a++]=28,i=t}return e}function sp(e,t){Gf.setUint32(qf.position+e,$-qf.position-e+1);let n=qf;qf=null,t(n[0]),t(n[1])}let cp=new Xf({useRecords:!1});const lp=cp.encode;cp.encodeAsIterable,cp.encodeAsAsyncIterable;const{NEVER:up,ALWAYS:dp,DECIMAL_ROUND:fp,DECIMAL_FIT:pp}=Ff,mp=2048;var hp=n(((e,t)=>{let n=()=>process.platform===`linux`,r=null;t.exports={isLinux:n,getReport:()=>{if(!r)if(n()&&process.report){let e=process.report.excludeNetwork;process.report.excludeNetwork=!0,r=process.report.getReport(),process.report.excludeNetwork=e}else r={};return r}}})),gp=n(((e,n)=>{let r=t(`fs`),i=2048;n.exports={LDD_PATH:`/usr/bin/ldd`,SELF_PATH:`/proc/self/exe`,readFileSync:e=>{let t=r.openSync(e,`r`),n=Buffer.alloc(i),a=r.readSync(t,n,0,i,0);return r.close(t,()=>{}),n.subarray(0,a)},readFile:e=>new Promise((t,n)=>{r.open(e,`r`,(e,a)=>{if(e)n(e);else{let e=Buffer.alloc(i);r.read(a,e,0,i,0,(n,i)=>{t(e.subarray(0,i)),r.close(a,()=>{})})}})})}})),_p=n(((e,t)=>{t.exports={interpreterPath:e=>{if(e.length<64||e.readUInt32BE(0)!==2135247942||e.readUInt8(4)!==2||e.readUInt8(5)!==1)return null;let t=e.readUInt32LE(32),n=e.readUInt16LE(54),r=e.readUInt16LE(56);for(let i=0;i<r;i++){let r=t+i*n;if(e.readUInt32LE(r)===3){let t=e.readUInt32LE(r+8),n=e.readUInt32LE(r+32);return e.subarray(t,t+n).toString().replace(/\0.*$/g,``)}}return null}}})),vp=n(((e,n)=>{let r=t(`child_process`),{isLinux:i,getReport:a}=hp(),{LDD_PATH:o,SELF_PATH:s,readFile:c,readFileSync:l}=gp(),{interpreterPath:u}=_p(),d,f,p,m=`getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true`,h=``,g=()=>h||new Promise(e=>{r.exec(m,(t,n)=>{h=t?` `:n,e(h)})}),_=()=>{if(!h)try{h=r.execSync(m,{encoding:`utf8`})}catch{h=` `}return h},v=`glibc`,y=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,b=`musl`,x=e=>e.includes(`libc.musl-`)||e.includes(`ld-musl-`),S=()=>{let e=a();return e.header&&e.header.glibcVersionRuntime?v:Array.isArray(e.sharedObjects)&&e.sharedObjects.some(x)?b:null},C=e=>{let[t,n]=e.split(/[\r\n]+/);return t&&t.includes(v)?v:n&&n.includes(b)?b:null},w=e=>{if(e){if(e.includes(`/ld-musl-`))return b;if(e.includes(`/ld-linux-`))return v}return null},T=e=>(e=e.toString(),e.includes(`musl`)?b:e.includes(`GNU C Library`)?v:null),E=async()=>{if(f!==void 0)return f;f=null;try{f=T(await c(o))}catch{}return f},D=()=>{if(f!==void 0)return f;f=null;try{f=T(l(o))}catch{}return f},O=async()=>{if(d!==void 0)return d;d=null;try{d=w(u(await c(s)))}catch{}return d},k=()=>{if(d!==void 0)return d;d=null;try{d=w(u(l(s)))}catch{}return d},A=async()=>{let e=null;return i()&&(e=await O(),e||(e=await E(),e||=S(),e||=C(await g()))),e},j=()=>{let e=null;return i()&&(e=k(),e||(e=D(),e||=S(),e||=C(_()))),e},M=async()=>i()&&await A()!==v,N=()=>i()&&j()!==v,P=async()=>{if(p!==void 0)return p;p=null;try{let e=(await c(o)).match(y);e&&(p=e[1])}catch{}return p},ee=()=>{if(p!==void 0)return p;p=null;try{let e=l(o).match(y);e&&(p=e[1])}catch{}return p},F=()=>{let e=a();return e.header&&e.header.glibcVersionRuntime?e.header.glibcVersionRuntime:null},te=e=>e.trim().split(/\s+/)[1],I=e=>{let[t,n,r]=e.split(/[\r\n]+/);return t&&t.includes(v)?te(t):n&&r&&n.includes(b)?te(r):null};n.exports={GLIBC:v,MUSL:b,family:A,familySync:j,isNonGlibcLinux:M,isNonGlibcLinuxSync:N,version:async()=>{let e=null;return i()&&(e=await P(),e||=F(),e||=I(await g())),e},versionSync:()=>{let e=null;return i()&&(e=ee(),e||=F(),e||=I(_())),e}}})),yp=n(((e,n)=>{var r=t(`fs`),i=t(`path`),a=t(`url`),o=process.config&&process.config.variables||{},s=!!process.env.PREBUILDS_ONLY,c=process.versions,l=c.modules;(c.deno||process.isBun)&&(l=`unsupported`);var u=D()?`electron`:`node`,d=process.arch,f=process.platform,p=process.env.LIBC||(O(f)?`musl`:`glibc`),m=process.env.ARM_VERSION||(d===`arm64`?`8`:o.arm_version)||``,h=(c.uv||``).split(`.`)[0];n.exports=g;function g(e){return typeof __webpack_require__==`function`?__non_webpack_require__(g.path(e)):t(g.path(e))}g.path=function(e){e=i.resolve(e||`.`);var n=``;try{n=typeof __webpack_require__==`function`?__non_webpack_require__(i.join(e,`package.json`)).name:t(i.join(e,`package.json`)).name;var r=n.toUpperCase().replace(/-/g,`_`)+`_PREBUILD`;process.env[r]&&(e=process.env[r])}catch{}if(!s){var o=v(i.join(e,`build/Release`),y);if(o)return o;var c=v(i.join(e,`build/Debug`),y);if(c)return c}var g=k(e);if(g)return g;var T=k(i.dirname(process.execPath));if(T)return T;var D=(n[0]==`@`?``:`@`+n+`/`)+n+`-`+f+`-`+d;try{return A(i.dirname(t(`module`).createRequire(a.pathToFileURL(i.join(e,`package.json`))).resolve(D)))}catch{}var O=[`platform=`+f,`arch=`+d,`runtime=`+u,`abi=`+l,`uv=`+h,m?`armv=`+m:``,`libc=`+p,`node=`+process.versions.node,process.versions.electron?`electron=`+process.versions.electron:``,typeof __webpack_require__==`function`?`webpack=true`:``].filter(Boolean).join(` `);throw Error(`No native build was found for `+O+`
137
137
  attempted loading from: `+e+` and package: `+D+`
138
- `);function k(e){var t=_(i.join(e,`prebuilds`)).map(b).filter(x(f,d)).sort(S)[0];if(t)return A(i.join(e,`prebuilds`,t.name))}function A(e){var t=_(e).map(C).filter(w(u,l)).sort(E(u))[0];if(t)return i.join(e,t.file)}};function _(e){try{return r.readdirSync(e)}catch{return[]}}function v(e,t){var n=_(e).filter(t);return n[0]&&i.join(e,n[0])}function y(e){return/\.node$/.test(e)}function b(e){var t=e.split(`-`);if(t.length===2){var n=t[0],r=t[1].split(`+`);if(n&&r.length&&r.every(Boolean))return{name:e,platform:n,architectures:r}}}function x(e,t){return function(n){return n==null||n.platform!==e?!1:n.architectures.includes(t)}}function S(e,t){return e.architectures.length-t.architectures.length}function C(e){var t=e.split(`.`),n=t.pop(),r={file:e,specificity:0};if(n===`node`){for(var i=0;i<t.length;i++){var a=t[i];if(a===`node`||a===`electron`||a===`node-webkit`)r.runtime=a;else if(a===`napi`)r.napi=!0;else if(a.slice(0,3)===`abi`)r.abi=a.slice(3);else if(a.slice(0,2)===`uv`)r.uv=a.slice(2);else if(a.slice(0,4)===`armv`)r.armv=a.slice(4);else if(a===`glibc`||a===`musl`)r.libc=a;else continue;r.specificity++}return r}}function w(e,t){return function(n){return!(n==null||n.runtime!==e&&!T(n)||n.abi!==t&&!n.napi||n.uv&&n.uv!==h||n.armv&&n.armv!==m||n.libc&&n.libc!==p)}}function T(e){return e.runtime===`node`&&e.napi}function E(e){return function(t,n){return t.runtime===n.runtime?t.abi===n.abi?t.specificity===n.specificity?0:t.specificity>n.specificity?-1:1:t.abi?-1:1:t.runtime===e?-1:1}}function D(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<`u`&&window.process&&window.process.type===`renderer`}function O(e){if(e!==`linux`)return!1;let{familySync:t,MUSL:n}=_p();return t()===n}g.parseTags=C,g.matchTags=w,g.compareTags=E,g.parseTuple=b,g.matchTuple=x,g.compareTuples=S})),yp=n(((e,t)=>{t.exports=vp()(__dirname)}));if(!(process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()===`true`)){let e;try{e=typeof t==`function`?yp():Wn(import.meta.url)(`cbor-extract`),e&&sf(e.extractStrings)}catch{}}const bp=`5.0.0-beta.9`,xp=typeof process<`u`&&typeof process.env.DEBUG==`string`&&(process.env.DEBUG.includes(`workflow:`)||process.env.DEBUG===`*`);function Sp(e,t,n,r){xp&&console.debug(`[workflow:world-vercel:http] ${e} ${t} -> ${n} (${r}ms)`)}const Cp=()=>process.env.VERCEL_WORKFLOW_SERVER_URL||``;function wp(e){return e}const Tp=()=>{let e=process.env.VERCEL_DEPLOYMENT_ID;return e?`@workflow/world-vercel/${bp} node-${process.version} ${Gn.platform()} (${Gn.arch()}) ${e}`:`@workflow/world-vercel/${bp} node-${process.version} ${Gn.platform()} (${Gn.arch()})`},Ep=e=>{let t=e?.projectConfig,n=Cp()||`https://vercel-workflow.com`,r=process.env.WORKFLOW_VERCEL_BACKEND_URL,i=!!(t?.projectId&&t?.teamId);return{baseUrl:i?r||`https://api.vercel.com/v1/workflow`:`${n}/api`,usingProxy:i}},Dp=(e,t)=>{let n=e?.projectConfig,r=new Headers(e?.headers);r.set(`User-Agent`,Tp()),n&&(r.set(`x-vercel-environment`,n.environment||`production`),n.projectId&&r.set(`x-vercel-project-id`,n.projectId),n.teamId&&r.set(`x-vercel-team-id`,n.teamId));let i=Cp();return i&&t.usingProxy&&r.set(`x-vercel-workflow-api-url`,i),r};async function Op(e){let{baseUrl:t,usingProxy:n}=Ep(e),r=Dp(e,{usingProxy:n});if(n){if(!e?.token)throw Error(`world-vercel: api-workflow proxy requested (${t}) but no Vercel auth token was provided. Pass one as \`config.token\` (the SDK reads it from \`WORKFLOW_VERCEL_AUTH_TOKEN\`).`);r.set(`Authorization`,`Bearer ${e.token}`)}else{let t;try{t=await(0,ws.getVercelOidcToken)()}catch{}let n=e?.token??t;n&&r.set(`Authorization`,`Bearer ${n}`),t&&r.set(`x-vercel-trusted-oidc-idp-token`,t)}return{baseUrl:t,headers:r,usingProxy:n}}async function kp({endpoint:e,options:t={},config:n={},schema:r,data:i,onResponse:a}){let o=t.method||`GET`,{baseUrl:s,headers:c}=await Op(n),l=`${s}${e}`,u,d;try{let e=new URL(l);u=e.hostname,d=e.port?parseInt(e.port,10):e.protocol===`https:`?443:80}catch{}return Ps(`http ${o}`,{kind:await Fs(`CLIENT`)},async n=>{n?.setAttributes({...Ls(o),...Rs(l),...u&&zs(u),...d&&Bs(d),...Ws(`workflow-server`),...Gs(`http`),...Ks(`workflow-server`)}),c.set(`Accept`,`application/cbor`),c.set(`X-Request-Time`,Date.now().toString());let s;i!==void 0&&(c.set(`Content-Type`,`application/cbor`),s=cp(i));let f=AbortSignal.timeout(6e4),p=t.signal?AbortSignal.any([t.signal,f]):f,h=new Request(l,{...t,body:s,headers:c,signal:p}),g=Date.now(),_;try{_=await fetch(h,{dispatcher:Es()})}catch(t){let r=Date.now()-g;if(t instanceof Error&&(t.name===`TimeoutError`||t.name===`AbortError`)){let i=new O(`${o} ${e} timed out after ${r}ms`,{url:l,cause:t});throw n?.setAttributes({...Hs(`TIMEOUT`)}),n?.recordException?.(i),i}throw t}let v=Date.now()-g;if(Sp(o,e,_.status,v),n?.setAttributes({...Vs(_.status)}),!_.ok){let t=await jp(_).then(e=>e.data).catch(()=>({}));if(process.env.DEBUG){let e=Array.from(c.entries()).filter(([e])=>e.toLowerCase()!==`authorization`).map(([e,t])=>`-H "${e}: ${t}"`).join(` `);console.error(`Failed to fetch, reproduce with:\ncurl -X ${h.method} ${e} "${l}"`)}let r,i=_.headers.get(`Retry-After`);if(i){let e=parseInt(i,10);Number.isNaN(e)||(r=e)}let a=t.message||`${h.method} ${e} -> HTTP ${_.status}: ${_.statusText}`,o=e=>{throw n?.setAttributes({...Hs(t.code||`HTTP ${_.status}`)}),n?.recordException?.(e),e};_.status===409&&o(new C(a)),_.status===410&&o(new m(a)),_.status===425&&o(new y(a,{retryAfter:r})),_.status===429&&o(new S(a,{retryAfter:r})),o(new O(a,{url:l,status:_.status,code:t.code,retryAfter:r}))}a?.(_);let b;try{b=await Ps(`world.parse`,async e=>{let t=await jp(_),n=(_.headers.get(`Content-Type`)||``).includes(`application/cbor`);return e?.setAttributes({...Us(n?`cbor`:`json`)}),t})}catch(t){let n=_.headers.get(`Content-Type`)||`unknown`;throw new O(`Failed to parse response body for ${h.method} ${e} (Content-Type: ${n}):\n\n${t}`,{url:l,code:`PARSE_ERROR`,cause:t})}return await Ps(`world.validate`,async()=>{let t=r.safeParse(b.data);if(!t.success)throw new O(`Schema validation failed for ${o} ${e}:\n${t.error.issues.map(e=>` ${e.path.length>0?e.path.join(`.`):`<root>`}: ${e.message}`).join(`
139
- `)}${process.env.DEBUG?`\n\nResponse context: ${b.getDebugContext()}`:``}`,{url:l,code:`SCHEMA_VALIDATION`,cause:t.error});return t.data})})}function Ap(e){let t=xn(e,{depth:3,maxArrayLength:10,breakLength:120});return t.length>500?`${t.slice(0,500)}...`:t}async function jp(e){let t=e.headers.get(`Content-Type`)||``;if(t.includes(`application/cbor`)){let n=await e.arrayBuffer(),r=Nf(new Uint8Array(n));return{data:r,getDebugContext:()=>`Content-Type: ${t}, ${n.byteLength} bytes (CBOR), preview: ${Ap(r)}`}}let n=await e.text(),r=JSON.parse(n);return{data:r,getDebugContext:()=>`Content-Type: ${t}, ${n.length} bytes, preview: ${Ap(r)}`}}var Mp=class{contentType=`application/cbor`;serialize(e){return Buffer.from(cp(e))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}return Nf(Buffer.concat(t))}},Np=class{contentType=`application/json`;serialize(e){return Buffer.from(JSON.stringify(e))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}return JSON.parse(Buffer.concat(t).toString())}},Pp=class{contentType=`application/cbor`;serialize(e){return Buffer.from(cp(e))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}let r=Buffer.concat(t);try{return Nf(r)}catch{return JSON.parse(r.toString())}}};const Fp=new wn,Ip=R({payload:M,queueName:be,deploymentId:de().optional()}),Lp=Number(process.env.VERCEL_QUEUE_MAX_DELAY_SECONDS||82800);function Rp(e){let t=Math.min(Math.max(1,2**(e-1)),60),n=Math.floor(Math.random()*(Math.ceil(t*.25)+1));return Math.max(1,t-n)}function zp(e){let t={};return`runId`in e&&typeof e.runId==`string`&&(t[`x-vercel-workflow-run-id`]=e.runId),`workflowRunId`in e&&typeof e.workflowRunId==`string`&&(t[`x-vercel-workflow-run-id`]=e.workflowRunId),`stepId`in e&&typeof e.stepId==`string`&&(t[`x-vercel-workflow-step-id`]=e.stepId),Object.keys(t).length>0?t:void 0}function Bp(e){let{baseUrl:t,usingProxy:n}=Ep(e),r=Dp(e,{usingProxy:n}),i=new Mp,a=new Np,o=new Pp,s={region:`iad1`,dispatcher:Es(),transport:o,...n&&{resolveBaseUrl:()=>new URL(`${t}/queues-proxy`),token:e?.token},headers:Object.fromEntries(r.entries())},c=async(e,t,n)=>{let r=n?.deploymentId??process.env.VERCEL_DEPLOYMENT_ID;if(!r)throw Error(`No deploymentId provided and VERCEL_DEPLOYMENT_ID environment variable is not set. Queue messages require a deployment ID to route correctly. Either set VERCEL_DEPLOYMENT_ID or provide deploymentId in options.`);let o=(n?.specVersion??3)>=3?i:a,c=new Ad({...s,deploymentId:r,transport:o}),l={payload:t,queueName:e,deploymentId:n?.deploymentId},u=e.replace(/[^A-Za-z0-9-_]/g,`-`);try{let{messageId:e}=await c.send(u,l,{idempotencyKey:n?.idempotencyKey,delaySeconds:n?.delaySeconds,headers:{...zp(t),...n?.headers}});return{messageId:e?xe.parse(e):null}}catch(e){if(e instanceof tu)return{messageId:xe.parse(`msg_duplicate_${e.idempotencyKey??n?.idempotencyKey??`unknown`}`)};throw e}};return{queue:c,createQueueHandler:(e,t)=>{let n=new Ad(s).handleCallback(async(e,n)=>{if(!e||!n)return;let r=Fp.getStore(),{payload:i,queueName:a,deploymentId:o}=Ip.parse(e),s=await t(i,{queueName:a,messageId:xe.parse(n.messageId),attempt:n.deliveryCount,requestId:r});typeof s?.timeoutSeconds==`number`&&await c(a,i,{deploymentId:o,delaySeconds:s.timeoutSeconds>0?Math.min(s.timeoutSeconds,Lp):void 0})},{retry:(e,{deliveryCount:t})=>({afterSeconds:Rp(t)})});return async e=>{let t=e.headers.get(`x-vercel-id`)?.trim()||void 0;return Fp.run(t,()=>n(e))}},getDeploymentId:async()=>{let e=process.env.VERCEL_DEPLOYMENT_ID;if(!e)throw Error(`VERCEL_DEPLOYMENT_ID environment variable is not set`);return e}}}const Vp=R({id:de()});function Hp(e){return async function(){let t=process.env.VERCEL_DEPLOYMENT_ID;if(!t)throw Error(`Cannot resolve latest deployment: VERCEL_DEPLOYMENT_ID environment variable is not set`);let n=e?.token??process.env.VERCEL_TOKEN??await(0,ws.getVercelOidcToken)().catch(()=>null);if(!n)throw Error(`Cannot resolve latest deployment: no OIDC token or VERCEL_TOKEN available`);let r=`https://api.vercel.com/v1/workflow/resolve-latest-deployment/${encodeURIComponent(t)}`,i=await fetch(r,{method:`GET`,headers:{Authorization:`Bearer ${n}`},dispatcher:Es()});if(!i.ok){let e;try{e=await i.text()}catch{e=`<unable to read response body>`}throw Error(`Failed to resolve latest deployment for ${t}: HTTP ${i.status} ${i.statusText}${e?` — ${e}`:``}`)}let a=await i.json(),o=Vp.safeParse(a);if(!o.success)throw Error(`Invalid response from Vercel API: expected { id: string }. Zod error: ${o.error.message}`);return o.data.id}}function Up(e){return typeof e==`object`&&!!e&&`_type`in e&&`_ref`in e&&typeof e._ref==`string`&&e._type===`RemoteRef`}async function Wp(e,t,n){let r=e._ref;if(r.startsWith(`dbrf:`)){if(!e._data)throw Error(`Inline ref descriptor missing _data field: ${r}`);let t=e._ct??`application/cbor`,n=Buffer.from(e._data,`base64`);return t===`application/octet-stream`?n:Nf(n)}let{baseUrl:i,headers:a}=await Op(n),o=`${i}${`/v2/runs/${encodeURIComponent(t)}/refs?ref=${encodeURIComponent(r)}`}`;return a.set(`Accept`,`application/cbor, application/octet-stream`),a.set(`X-Request-Time`,Date.now().toString()),Ps(`http GET`,{kind:await Fs(`CLIENT`)},async e=>{e?.setAttributes({...Ls(`GET`),...Rs(o),...Ws(`workflow-server`)});let t=await fetch(o,{method:`GET`,headers:a,dispatcher:Es()});if(e?.setAttributes({...Vs(t.status)}),!t.ok){let n=new O(`Failed to resolve ref: HTTP ${t.status}`,{url:o,status:t.status});throw e?.setAttributes({...Hs(`HTTP ${t.status}`)}),e?.recordException?.(n),n}let n=t.headers.get(`content-type`)||``,r=await t.arrayBuffer();return n.includes(`application/octet-stream`)?new Uint8Array(r):Nf(new Uint8Array(r))})}async function Gp(e,t,n){if(e.length===0)return[];let r=n??10;return Ps(`world.refs.resolve`,async n=>{let i=e.filter(e=>e.descriptor._ref.startsWith(`dbrf:`)).length,a=e.length-i;if(n?.setAttributes({"workflow.refs.total_count":e.length,"workflow.refs.inline_count":i,"workflow.refs.remote_count":a,"workflow.refs.concurrency_limit":r}),e.length<=r)return Promise.all(e.map(e=>Wp(e.descriptor,e.runId,t)));let o=Array(e.length);for(let n=0;n<e.length;n+=r){let i=e.slice(n,n+r),a=await Promise.all(i.map(e=>Wp(e.descriptor,e.runId,t)));for(let e=0;e<a.length;e++)o[n+e]=a[e]}return o})}const Kp=V.omit({error:!0,errorCode:!0}).extend({error:U([z,ue()]).optional(),errorCode:de().optional(),blobStorageBytes:Ee().optional(),streamStorageBytes:Ee().optional()}),qp=Kp,Jp=Kp.omit({input:!0,output:!0}).extend({inputRef:ue().optional(),outputRef:ue().optional(),input:U([le(Uint8Array),ue()]).optional(),output:U([le(Uint8Array),ue()]).optional()});function Yp(e,t){if(t===`none`){let{inputRef:t,outputRef:n,...r}=e;return{...wp(r),input:void 0,output:void 0}}return wp(e)}async function Xp(e={},t){let{workflowName:n,status:r,pagination:i,resolveData:a=`all`}=e,o=new URLSearchParams;n&&o.set(`workflowName`,n),r&&o.set(`status`,r),i?.limit&&o.set(`limit`,i.limit.toString()),i?.cursor&&o.set(`cursor`,i.cursor),i?.sortOrder&&o.set(`sortOrder`,i.sortOrder);let s=a===`none`?`lazy`:`resolve`;o.set(`remoteRefBehavior`,s);let c=o.toString(),l=await kp({endpoint:`/v2/runs${c?`?${c}`:``}`,options:{method:`GET`},config:t,schema:ke(s===`lazy`?Jp:qp)});return{...l,data:l.data.map(e=>Yp(e,a))}}async function Zp(e,t){return wp(await kp({endpoint:`/v1/runs/create`,options:{method:`POST`},data:e,config:t,schema:qp}))}async function Qp(e,t,n){let r=t?.resolveData??`all`,i=r===`none`?`lazy`:`resolve`,a=new URLSearchParams;a.set(`remoteRefBehavior`,i);let o=a.toString(),s=`/v2/runs/${encodeURIComponent(e)}${o?`?${o}`:``}`;try{return Yp(await kp({endpoint:s,options:{method:`GET`},config:n,schema:i===`lazy`?Jp:qp}),r)}catch(t){throw t instanceof O&&t.status===404?new u(e):t}}async function $p(e,t,n){let r=t?.resolveData??`all`,i=r===`none`?`lazy`:`resolve`,a=new URLSearchParams;a.set(`remoteRefBehavior`,i);let o=a.toString(),s=`/v1/runs/${encodeURIComponent(e)}/cancel${o?`?${o}`:``}`;try{return Yp(await kp({endpoint:s,options:{method:`PUT`},config:n,schema:i===`lazy`?Jp:qp}),r)}catch(t){throw t instanceof O&&t.status===404?new u(e):t}}const em=R({attributes:fe(de(),de())});async function tm(e,t,n,r){try{return{attributes:(await kp({endpoint:`/v2/runs/${encodeURIComponent(e)}/attributes`,options:{method:`POST`},data:n?.allowReservedAttributes?{changes:t,allowReservedAttributes:!0}:{changes:t},config:r,schema:em})).attributes}}catch(t){throw t instanceof O&&t.status===404?new u(e):t}}const nm=Ae.omit({error:!0}).extend({error:U([z,ue()]).optional(),errorRef:ue().optional()}),rm=nm.omit({input:!0,output:!0}).extend({inputRef:ue().optional(),outputRef:ue().optional(),input:le(Uint8Array).optional(),output:le(Uint8Array).optional()});function im(e){let{error:t,errorRef:n,...r}=e,i={...r},a=t??n;return a!=null&&(i.error=a),i}function am(e,t){if(t===`none`){let{inputRef:t,outputRef:n,...r}=e;return{...im(r),input:void 0,output:void 0}}return im(e)}async function om(e,t){let{runId:n,pagination:r,resolveData:i=`all`}=e,a=new URLSearchParams;r?.cursor&&a.set(`cursor`,r.cursor),r?.limit&&a.set(`limit`,r.limit.toString()),r?.sortOrder&&a.set(`sortOrder`,r.sortOrder);let o=i===`none`?`lazy`:`resolve`;a.set(`remoteRefBehavior`,o);let s=a.toString(),c=await kp({endpoint:`/v2/runs/${encodeURIComponent(n)}/steps${s?`?${s}`:``}`,options:{method:`GET`},config:t,schema:ke(o===`lazy`?rm:nm)});return{...c,data:c.data.map(e=>am(e,i))}}async function sm(e,t,n,r){let i=n?.resolveData??`all`,a=i===`none`?`lazy`:`resolve`,o=new URLSearchParams;o.set(`remoteRefBehavior`,a);let s=o.toString();return am(await kp({endpoint:`/v2/runs/${encodeURIComponent(e)}/steps/${encodeURIComponent(t)}${s?`?${s}`:``}`,options:{method:`GET`},config:r,schema:a===`lazy`?rm:nm}),i)}function cm(e,t){if(t!==`none`)return e;let{eventDataRef:n,...r}=e;return L(r,t)}const lm=H.object({event:B.optional(),run:F.optional(),step:nm.optional(),hook:ae.optional(),events:H.array(B).optional(),cursor:H.string().nullable().optional(),hasMore:H.boolean().optional()}),um=H.object({event:B.optional(),run:Kp.optional(),step:nm.optional(),hook:ae.optional(),events:H.array(B).optional(),cursor:H.string().nullable().optional(),hasMore:H.boolean().optional()}),dm=H.object({eventId:H.string(),runId:H.string(),eventType:te,correlationId:H.string().optional(),eventDataRef:H.any().optional(),eventData:H.any().optional(),createdAt:H.coerce.date(),specVersion:H.number().default(1)}),fm={run_created:`input`,run_completed:`output`,run_failed:`error`,step_created:`input`,step_completed:`result`,step_failed:`error`,step_retrying:`error`,hook_created:`metadata`,hook_received:`payload`},pm=new Set([`run_created`,`run_started`,`step_started`]);function mm(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.eventDataRef&&Up(r.eventDataRef)&&t.push({eventIndex:n,refType:`entity`,descriptor:r.eventDataRef}),r.eventData&&typeof r.eventData==`object`){let e=fm[r.eventType];if(e){let i=r.eventData[e];Up(i)&&t.push({eventIndex:n,refType:`nested`,fieldName:e,descriptor:i})}}}return t}async function hm(e,t,n){let r=mm(e);return r.length===0?e:Ps(`world.refs.hydrate`,async i=>{i?.setAttribute(`workflow.refs.hydrated_count`,r.length);let a=new Map;for(let t of r)if(!a.has(t.descriptor._ref)){let n=e[t.eventIndex].runId;a.set(t.descriptor._ref,{descriptor:t.descriptor,runId:n})}let o=await Gp(Array.from(a.values()),t,n).catch(t=>{let n=t instanceof Error?t.message:String(t);throw Error(`Failed to hydrate ${r.length} ref(s) across ${e.length} event(s): ${n}`)}),s=new Map,c=Array.from(a.keys());for(let e=0;e<c.length;e++)s.set(c[e],o[e]);let l=[...e];for(let t=0;t<r.length;t++){let{eventIndex:n,refType:i,fieldName:a,descriptor:o}=r[t],c=s.get(o._ref);l[n]===e[n]&&(l[n]={...e[n]});let u=l[n];i===`entity`?(u.eventData=c,delete u.eventDataRef):i===`nested`&&a&&(u.eventData===e[n].eventData&&(u.eventData={...u.eventData}),u.eventData[a]=c)}return l})}async function gm(e,t,n,r){let i=n?.resolveData??`all`,a=i===`none`?`lazy`:`resolve`,o=new URLSearchParams;o.set(`remoteRefBehavior`,a);let s=o.toString();return cm(await kp({endpoint:`/v3/runs/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}${s?`?${s}`:``}`,options:{method:`GET`},config:r,schema:i===`none`?dm:B}),i)}async function _m(e,t){let n=new URLSearchParams,{pagination:r,resolveData:i=`all`}=e,a,o;if(`runId`in e?a=e.runId:o=e.correlationId,!a&&!o)throw Error(`Either runId or correlationId must be provided`);r?.limit&&n.set(`limit`,r.limit.toString()),r?.cursor&&n.set(`cursor`,r.cursor),r?.sortOrder&&n.set(`sortOrder`,r.sortOrder),o&&n.set(`correlationId`,o),n.set(`remoteRefBehavior`,`lazy`);let s=n.toString(),c=s?`?${s}`:``,l=o?`/v2/events${c}`:`/v3/runs/${encodeURIComponent(a)}/events${c}`,u,d=await kp({endpoint:l,options:{method:`GET`},config:t,schema:ke(dm),onResponse:e=>{let t=e.headers.get(`x-ref-resolve-concurrency`);if(t){let e=parseInt(t,10);!Number.isNaN(e)&&e>0&&(u=e)}}});if(i===`all`){let e=await hm(d.data,t,u),n=0,r=e.map(e=>{let t=B.safeParse(e);return t.success||n++,t.success?t.data:e});return n>0&&console.warn(`[world-vercel] EventSchema coercion failed for ${n}/${e.length} events`),{...d,data:r}}return{...d,data:d.data.map(e=>cm(e,i))}}const vm=new Set([`hook_disposed`,`hook_received`]);async function ym(e,t,n,r){try{return await bm(e,t,n,r)}catch(e){throw vm.has(t.eventType)&&O.is(e)&&e.status===404&&t.correlationId?new x(t.correlationId):e}}async function bm(e,t,n,r){let i=n?.resolveData??`all`;if(n?.v1Compat??!1)return t.eventType===`run_cancelled`&&e?{run:await $p(e,n,r)}:t.eventType===`run_created`?{run:await Zp(t.eventData,r)}:{event:await kp({endpoint:`/v1/runs/${encodeURIComponent(e)}/events`,options:{method:`POST`},data:t,config:r,schema:B})};if(t.eventType===`run_created`&&e){let t=je(e,`wrun_`);if(t)throw new O(t,{status:400})}let a=e===null?`null`:encodeURIComponent(e),o=pm.has(t.eventType)?`resolve`:`lazy`;if(o===`resolve`){let e=await kp({endpoint:`/v3/runs/${a}/events`,options:{method:`POST`},data:{...t,remoteRefBehavior:o,...n?.requestId?{vercelId:n.requestId}:{}},config:r,schema:lm});return{event:e.event?cm(e.event,i):void 0,run:e.run,step:e.step?im(e.step):void 0,hook:e.hook,events:e.events,cursor:e.cursor,hasMore:e.hasMore}}let s=await kp({endpoint:`/v3/runs/${a}/events`,options:{method:`POST`},data:{...t,remoteRefBehavior:o,...n?.requestId?{vercelId:n.requestId}:{}},config:r,schema:um});return{event:s.event?cm(s.event,i):void 0,run:s.run?wp(s.run):void 0,step:s.step?im(s.step):void 0,hook:s.hook,events:s.events,cursor:s.cursor,hasMore:s.hasMore}}function xm(e,t){if(t===`none`){let{metadataRef:t,...n}=e;return n}return e}const Sm=ae.omit({metadata:!0}).extend({metadataRef:H.any().optional()});async function Cm(e,t){let{runId:n,pagination:r,resolveData:i=`all`}=e,a=new URLSearchParams;r?.limit&&a.set(`limit`,r.limit.toString()),r?.cursor&&a.set(`cursor`,r.cursor),r?.sortOrder&&a.set(`sortOrder`,r.sortOrder);let o=i===`none`?`lazy`:`resolve`;a.set(`remoteRefBehavior`,o),n&&a.set(`runId`,n);let s=a.toString(),c=await kp({endpoint:`/v2/hooks${s?`?${s}`:``}`,options:{method:`GET`},config:t,schema:ke(o===`lazy`?Sm:ae)});return{...c,data:c.data.map(e=>xm(e,i))}}async function wm(e,t,n){let r=t?.resolveData||`all`;return xm(await kp({endpoint:`/v2/hooks/${encodeURIComponent(e)}`,options:{method:`GET`},config:n,schema:ae}),r)}async function Tm(e,t){try{return await kp({endpoint:`/v2/hooks/by-token?token=${encodeURIComponent(e)}`,options:{method:`GET`},config:t,schema:ae})}catch(t){throw O.is(t)&&t.status===404?new x(e):t}}function Em(e){let t={runs:{get:((t,n)=>Qp(t,n,e)),list:(t=>Xp(t,e)),experimentalSetAttributes:(t,n,r)=>tm(t,n,r,e)},steps:{get:((t,n,r)=>sm(t,n,r,e)),list:(t=>om(t,e))},events:{create:(t,n,r)=>ym(t,n,r,e),get:(t,n,r)=>gm(t,n,r,e),list:t=>_m(t,e),listByCorrelationId:t=>_m(t,e)},hooks:{get:(t,n)=>wm(t,n,e),getByToken:t=>Tm(t,e),list:t=>Cm(t,e)}};return{runs:Xs(`world.runs`,t.runs),steps:Xs(`world.steps`,t.steps),events:Xs(`world.events`,t.events),hooks:Xs(`world.hooks`,t.hooks)}}const Dm=1e3;function Om(e,t,n){return new URL(`${n.baseUrl}/v2/runs/${encodeURIComponent(t)}/stream/${encodeURIComponent(e)}`)}function km(e,t,n,r){let i=[`PUT ${t.origin}${t.pathname}`];for(let e of[`x-vercel-id`,`x-vercel-error`]){let t=n.headers.get(e);t&&i.push(`${e}=${t}`)}return Error(`Stream ${e} failed: HTTP ${n.status} (${i.join(`; `)}): ${r}`)}function Am(e){let t=new TextEncoder,n=[],r=0;for(let i of e){let e=typeof i==`string`?t.encode(i):i;n.push(e),r+=4+e.length}let i=new Uint8Array(r),a=new DataView(i.buffer),o=0;for(let e of n)a.setUint32(o,e.length,!1),o+=4,i.set(e,o),o+=e.length;return i}const jm=R({tailIndex:Ee(),done:re()}),Mm=R({data:I(R({index:Ee(),data:le(Uint8Array)})),cursor:de().nullable(),hasMore:re(),done:re()});function Nm(e){return{streams:{async write(t,n,r){let i=await t,a=await Op(e),o=Om(n,i,a),s=await fetch(o,{method:`PUT`,body:r,headers:a.headers}),c=await s.text();if(!s.ok)throw km(`write`,o,s,c)},async writeMulti(t,n,r){if(r.length===0)return;let i=await t,a=await Op(e);a.headers.set(`X-Stream-Multi`,`true`);for(let e=0;e<r.length;e+=Dm){let t=Am(r.slice(e,e+Dm)),o=Om(n,i,a),s=await fetch(o,{method:`PUT`,body:t,headers:a.headers}),c=await s.text();if(!s.ok)throw km(`write`,o,s,c)}},async close(t,n){let r=await t,i=await Op(e);i.headers.set(`X-Stream-Done`,`true`);let a=Om(n,r,i),o=await fetch(a,{method:`PUT`,headers:i.headers}),s=await o.text();if(!o.ok)throw km(`close`,a,o,s)},async get(t,n,r){let i=await Op(e),a=Om(n,t,i);typeof r==`number`&&a.searchParams.set(`startIndex`,String(r));let o=await fetch(a,{headers:i.headers});if(!o.ok)throw Error(`Failed to fetch stream: ${o.status}`);if(!o.body)throw Error(`No response body for stream`);return o.body},async getChunks(t,n,r){let i=new URLSearchParams;r?.limit!=null&&i.set(`limit`,String(r.limit)),r?.cursor&&i.set(`cursor`,r.cursor);let a=i.toString();return kp({endpoint:`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(n)}/chunks${a?`?${a}`:``}`,config:e,schema:Mm})},async getInfo(t,n){return kp({endpoint:`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(n)}/info`,config:e,schema:jm})},async list(t){let n=await Op(e),r=new URL(`${n.baseUrl}/v2/runs/${encodeURIComponent(t)}/streams`),i=await fetch(r,{headers:n.headers});if(!i.ok)throw Error(`Failed to list streams: ${i.status}`);return await i.json()}}}}function Pm(e){let t=e?.projectConfig?.projectId||process.env.VERCEL_PROJECT_ID;return{specVersion:3,processExitTriggersQueueRedelivery:!0,...Bp(e),...Em(e),...Xs(`world.streams`,Nm(e)),getEncryptionKeyForRun:ks(t,e?.projectConfig?.teamId,e?.token),resolveLatestDeploymentId:Hp(e)}}function Fm(){try{return vn(En(process.cwd()+`/package.json`).href)}catch{return vn(import.meta.url)}}const Im=Symbol.for(`@workflow/world//cache`),Lm=Symbol.for(`@workflow/world//stubbedCache`),Rm=Symbol.for(`@workflow/world//cachePromise`),zm=Symbol.for(`@workflow/world//stubbedCachePromise`),Bm=globalThis;function Vm(e){if(e.startsWith(`file://`))return e;if(e.startsWith(`/`))return En(e).href;if(e.startsWith(`./`)||e.startsWith(`../`))return En(process.cwd()+`/`+e).href;try{return En(Fm().resolve(e)).href}catch{return e}}const Hm=async()=>{let e=a();if(o(e)){let e=[`WORKFLOW_VERCEL_PROJECT`,`WORKFLOW_VERCEL_TEAM`,`WORKFLOW_VERCEL_AUTH_TOKEN`,`WORKFLOW_VERCEL_ENV`].filter(e=>process.env[e]);return e.length>0&&process.env.VERCEL===`1`&&console.warn(`[workflow] Warning: ${e.join(`, `)} env var(s) are set but have no effect at runtime. These are only used by the Workflow CLI. Remove them from your Vercel project environment variables.`),Pm()}if(e===`local`)return hs({dataDir:process.env.WORKFLOW_LOCAL_DATA_DIR});let t;try{t=Fm()(e)}catch{t=await import(Vm(e))}if(typeof t==`function`)return t();if(typeof t.default==`function`)return t.default();if(typeof t.createWorld==`function`)return t.createWorld();throw Error(`Invalid target world module: ${e}, must export a default function or createWorld function that returns a World instance.`)},Um=async()=>{if(Bm[Lm])return Bm[Lm];Bm[zm]||(Bm[zm]=Hm().catch(e=>{throw Bm[zm]=void 0,e}));let e=await Bm[zm];return Bm[Lm]=e,{createQueueHandler:e.createQueueHandler,specVersion:e.specVersion}},Wm=async()=>Bm[Im]?Bm[Im]:(Bm[Rm]||(Bm[Rm]=Hm().catch(e=>{throw Bm[Rm]=void 0,e})),Bm[Im]=await Bm[Rm],Bm[Im]),Gm=e=>{Bm[Im]=e,Bm[Lm]=e,Bm[Rm]=void 0,Bm[zm]=void 0},Km=Symbol.for(`@workflow/world//getWorldFn`);globalThis[Km]??=Wm;var qm=class{limitMs;elapsedMs=0;intervalStart;constructor(e=or()){this.limitMs=e,this.intervalStart=Date.now()}get configuredLimitMs(){return this.limitMs}elapsed(){let e=this.intervalStart===null?0:Date.now()-this.intervalStart;return this.elapsedMs+e}pause(){this.intervalStart!==null&&(this.elapsedMs+=Date.now()-this.intervalStart,this.intervalStart=null)}resume(){this.intervalStart=Date.now()}isExhausted(){return this.elapsed()>=this.limitMs}};async function Jm(e){let{runId:t,workflowName:n,requestId:r,attempt:i,limitMs:a}=e,o=W.forRun(t,n),s=await Wm();if(s.processExitTriggersQueueRedelivery!==!0){o.warn(`Workflow replay exceeded timeout; current World does not support process exit for redelivery — failing the run and returning`,{timeoutMs:a,attempt:i});try{let e=Wt(s,t),n=new _(`Workflow replay exceeded maximum duration (${a/1e3}s)`);await s.events.create(t,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(n,t,await e()),errorCode:d.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e)})}return}i<=3&&(o.warn(`Workflow replay exceeded timeout but will be re-attempted (attempt < maxRetries)`,{timeoutMs:a,attempt:i,maxRetries:3}),process.exit(1));let c=er(void 0,d.REPLAY_TIMEOUT);o.error(`Workflow replay exceeded timeout and max retries exceeded. Failing the run`,{timeoutMs:a,attempt:i,maxRetries:3,errorCode:c.errorCode,errorAttribution:c.attribution});try{let e=Wt(s,t),n=new _(`Workflow replay exceeded maximum duration (${a/1e3}s) after ${i} attempts`);await s.events.create(t,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(n,t,await e()),errorCode:d.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed. The queue will continue to retry`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}process.exit(1)}var Ym=ht();function Xm(e){return Cn.isNativeError(e)?e.name:`Error`}function Zm(e){return Cn.isNativeError(e)?e.stack??``:``}function Qm(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`&&`message`in e&&typeof e.message==`string`&&(!(`stack`in e)||e.stack===void 0||typeof e.stack==`string`)}function $m(e){if(!Qm(e)||_.is(e))return e;let t=new _(`Aborted: ${e.message}`);return e.stack&&(t.stack=e.stack),t}function eh(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function th(e){if(Cn.isNativeError(e))return{name:e.name,message:e.message,stack:e.stack??``};if(typeof e==`string`)return{name:`Error`,message:e,stack:``};try{return{name:`Error`,message:JSON.stringify(e),stack:``}}catch{return{name:`Error`,message:String(e),stack:``}}}async function nh(e){if(eh(e))try{let t=await nh(await e);return{...t,message:`Promise rejection: ${t.message}`}}catch(e){let t=await nh(e);return{...t,message:`Promise rejection: ${t.message}`}}return th(e)}let rh;async function ih(){if(!rh)try{let e=[`@workflow/utils`,`get-port`].join(`/`);rh=vn(En(process.cwd()+`/package.json`).href)(e).getPort}catch{rh=async()=>void 0}return rh()}async function ah(e){let{world:t,workflowRunId:n,workflowName:r,workflowStartedAt:a,stepId:o,stepName:c}=e,l=process.env.VERCEL_URL!==void 0;return _t(`STEP ${c}`,{},async u=>{u?.setAttributes({...At(c),...pt(r),...it(n),...Gt(o)});let d=Wt(t,n),f=gn(c);if(!f||typeof f!=`function`){let e=`Step "${c}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`;W.error(`Step function not registered, failing step`,{workflowRunId:n,stepName:c,stepId:o});try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(new _(e),n,await d())}})}catch(e){if(C.is(e))return{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Ot(!0)}),{type:`failed`}}let p=f.maxRetries??3;u?.setAttributes({...cn(p)});let h;try{let e=await t.events.create(n,{eventType:`step_started`,specVersion:3,correlationId:o,eventData:{stepName:c}});if(!e.step)throw new i(`step_started event for "${o}" did not return step entity`);h=e.step}catch(e){if(S.is(e)){let t=Math.max(1,typeof e.retryAfter==`number`?e.retryAfter:1);return W.info(`Throttled on step_started, deferring`,{retryAfterSeconds:t}),{type:`throttled`,timeoutSeconds:t}}if(m.is(e))return W.info(`Workflow run "${n}" has already completed, skipping step "${o}": ${e.message}`),{type:`gone`};if(C.is(e))return W.debug(`Step in terminal state, skipping`,{stepName:c,stepId:o,workflowRunId:n,error:e.message}),u?.setAttributes({...St(!0),...Ft(`completed`)}),{type:`skipped`};if(y.is(e)){let t=Math.max(1,e.retryAfter??1);return W.debug(`Step retryAfter timestamp not yet reached`,{stepName:c,stepId:o,timeoutSeconds:t}),{type:`retry`,timeoutSeconds:t}}throw e}W.debug(`Step execution details`,{stepName:c,stepId:h.stepId,status:h.status,attempt:h.attempt}),u?.setAttributes({...un(h.status)});let g;if(h.attempt>p+1&&h.error){let e=h.attempt-1,r=`Step "${c}" exceeded max retries (${e} ${s(`retry`,`retries`,e)})`;Ie.error(`Step exceeded max retries`,{workflowRunId:n,stepName:c,retryCount:e});let i=new _(r);if(h.error!=null)try{i.cause=await Be(h.error,n,await d())}catch{}try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(i,n,await d())}})}catch(e){if(C.is(e))return W.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Qt(!0)}),{type:`failed`}}try{let s=h.attempt;if(!h.startedAt)throw new i(`Step "${o}" has no "startedAt" timestamp`);let p=h.startedAt,m=[],_=e.encryptionKey??await d(),v=await _t(`step.hydrate`,{},async e=>{let t=Date.now(),r=await ft(h.input,n,_,m),i=Date.now()-t;return e?.setAttributes({...zt(r.args.length),...on(i)}),r}),y=v.args,b=v.thisVal??null,x=l?void 0:await ih(),S=Date.now();g=await _t(`step.execute`,{},async()=>await ct.run({stepMetadata:{stepName:c,stepId:o,stepStartedAt:new Date(+p),attempt:s},workflowMetadata:{workflowName:r,workflowRunId:n,workflowStartedAt:new Date(+a),url:l?`https://${process.env.VERCEL_URL}`:`http://localhost:${x??3e3}`,features:{encryption:!!_}},ops:m,closureVars:v.closureVars,encryptionKey:_},()=>f.apply(b,y)));let w=Date.now()-S;u?.setAttributes({...Jt(w)}),g=await _t(`step.dehydrate`,{},async e=>{let t=Date.now(),r=await ln(g,n,_,m),i=Date.now()-t;return e?.setAttributes({...tn(i),...Nt(typeof r)}),r});let T=!0;if(m.length>0){let e=Promise.all(m).catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))throw e});(0,Ym.waitUntil)(e),T=await Promise.race([e.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),500))])}let E=!1;return await t.events.create(n,{eventType:`step_completed`,specVersion:3,correlationId:o,eventData:{stepName:c,result:g}}).catch(e=>{if(C.is(e)){W.info(`Tried completing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),E=!0;return}throw e}),E?{type:`skipped`}:(u?.setAttributes({...un(`completed`),...Nt(typeof g)}),m.length>0&&Ie.debug(`Step has pending ops`,{workflowRunId:n,stepName:c,opsCount:m.length}),{type:`completed`,hasPendingOps:!T})}catch(e){let r=$m(e),i=await nh(r),a=i.stack||Zm(r)||``;r instanceof Error&&u?.recordException?.(r);let l=_.is(r);if(u?.setAttributes({...rn(Xm(r)),...Xt(i.message),...vt(Xm(r)),...Ye(l?`fatal`:w.is(r)?`retryable`:`transient`),...yt(!l)}),m.is(e))return Ie.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};if(l){Ie.error(`Encountered FatalError while executing step, bubbling up to parent workflow`,{workflowRunId:n,stepName:c,errorStack:a}),Cn.isNativeError(r)&&a&&(r.stack=a);try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(r,n,await d())}})}catch(e){if(C.is(e))return W.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Ot(!0)}),{type:`failed`}}let f=h.attempt;if(u?.setAttributes({...wt(f),...cn(p)}),f>=p+1){let r=h.attempt-1;Ie.error(`Max retries reached, bubbling error to parent workflow`,{workflowRunId:n,stepName:c,attempt:h.attempt,retryCount:r,errorStack:a});let l=new _(`Step "${c}" failed after ${p} ${s(`retry`,`retries`,p)}: ${i.message}`);l.cause=e,a&&(l.stack=a);try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(l,n,await d())}})}catch(e){if(C.is(e))return W.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Qt(!0)}),{type:`failed`}}w.is(e)?Ie.info(`Encountered RetryableError, step will be retried`,{workflowRunId:n,stepName:c,attempt:f,message:e.message}):Ie.info(`Encountered Error, step will be retried`,{workflowRunId:n,stepName:c,attempt:f,errorStack:a}),Cn.isNativeError(e)&&a&&(e.stack=a);try{await t.events.create(n,{eventType:`step_retrying`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(e,n,await d()),...w.is(e)&&{retryAfter:e.retryAfter}}})}catch(e){if(C.is(e))return W.info(`Tried retrying step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}let g=Math.max(1,w.is(e)?Math.ceil((+e.retryAfter.getTime()-Date.now())/1e3):1);return u?.setAttributes({...Kt(g),...Lt(!0)}),{type:`retry`,timeoutSeconds:g}}})}async function oh({suspension:e,world:t,run:n,span:r,requestId:i}){let a=n.runId,o=e.steps.filter(e=>e.type===`step`),s=e.steps.filter(e=>e.type===`hook`),c=e.steps.filter(e=>e.type===`wait`),l=s.filter(e=>!e.hasCreatedEvent),u=s.filter(e=>e.disposed),d=await t.getEncryptionKeyForRun?.(n),f=d?await Ke(d):void 0,p=await Promise.all(l.map(async t=>{let n=t.metadata===void 0?void 0:await Pt(t.metadata,a,f,e.globalThis);return{eventType:`hook_created`,specVersion:3,correlationId:t.correlationId,eventData:{token:t.token,metadata:n,isWebhook:t.isWebhook??!1,...t.isSystem&&{isSystem:!0}}}})),h=!1;p.length>0&&await Promise.all(p.map(async e=>{try{(await t.events.create(a,e,{requestId:i})).event.eventType===`hook_conflict`&&(h=!0)}catch(e){if(C.is(e)||m.is(e))W.info(`Workflow run already completed, skipping hook`,{workflowRunId:a,message:e.message});else throw e}})),u.length>0&&await Promise.all(u.map(async e=>{let n={eventType:`hook_disposed`,specVersion:3,correlationId:e.correlationId,eventData:{token:e.token}};try{await t.events.create(a,n,{requestId:i})}catch(t){if(C.is(t))W.info(`Hook already disposed, skipping duplicate disposal`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else if(m.is(t))W.info(`Workflow run already completed, skipping hook disposal`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else if(x.is(t))W.info(`Hook not found for disposal, continuing`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else throw t}}));let g=s.filter(e=>e.abortRequested&&!e.disposed);g.length>0&&await Promise.all(g.map(async n=>{try{let r=await Pt({aborted:!0,reason:n.abortReason},a,f,e.globalThis);await t.events.create(a,{eventType:`hook_received`,specVersion:3,correlationId:n.correlationId,eventData:{token:n.token,payload:r}});try{let e=He(n.token);await t.streams.write(a,e,r),await t.streams.close(a,e)}catch{W.debug(`Failed to write abort stream packet, hook event will provide fallback`,{workflowRunId:a,correlationId:n.correlationId})}}catch(e){if(C.is(e)||m.is(e))W.info(`Workflow run already completed, skipping abort`,{workflowRunId:a,correlationId:n.correlationId,message:e.message});else throw e}}));let _=new Set(o.filter(e=>!e.hasCreatedEvent).map(e=>e.correlationId)),v=new Set,y=[];for(let n of o)_.has(n.correlationId)&&y.push((async()=>{let r=await Pt({args:n.args,closureVars:n.closureVars,thisVal:n.thisVal},a,f,e.globalThis),o={eventType:`step_created`,specVersion:3,correlationId:n.correlationId,eventData:{stepName:n.stepName,input:r}};try{await t.events.create(a,o,{requestId:i}),v.add(n.correlationId)}catch(e){if(C.is(e))W.info(`Step already exists, continuing`,{workflowRunId:a,correlationId:n.correlationId,message:e.message});else throw e}})());for(let e of c)e.hasCreatedEvent||y.push((async()=>{let n={eventType:`wait_created`,specVersion:3,correlationId:e.correlationId,eventData:{resumeAt:e.resumeAt}};try{await t.events.create(a,n,{requestId:i})}catch(t){if(C.is(t))W.info(`Wait already exists, continuing`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else throw t}})());(0,Ym.waitUntil)(Promise.all(y).catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))throw e})),await Promise.all(y);let b=Date.now(),S=c.reduce((e,t)=>{let n=t.resumeAt.getTime(),r=Math.max(1e3,n-b),i=Math.ceil(r/1e3);return e===null?i:Math.min(e,i)},null);return r?.setAttributes({...Ut(`workflow_suspended`),...Vt(o.length),...fn(l.length),...nt(c.length)}),{pendingSteps:o,createdStepCorrelationIds:v,timeoutSeconds:h?0:S??void 0,hasHookConflict:h}}var sh=44,ch=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,lh=new Uint8Array(64),uh=new Uint8Array(128);for(let e=0;e<ch.length;e++){let t=ch.charCodeAt(e);lh[e]=t,uh[t]=e}function dh(e,t){let n=0,r=0,i=0;do i=uh[e.next()],n|=(i&31)<<r,r+=5;while(i&32);let a=n&1;return n>>>=1,a&&(n=-2147483648|-n),t+n}function fh(e,t){return e.pos>=t?!1:e.peek()!==sh}var ph=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}};function mh(e){let{length:t}=e,n=new ph(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i=dh(n,i),i<u&&(l=!1),u=i,fh(n,e)?(a=dh(n,a),o=dh(n,o),s=dh(n,s),fh(n,e)?(c=dh(n,c),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||hh(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function hh(e){e.sort(gh)}function gh(e,t){return e[0]-t[0]}const _h=/^[\w+.-]+:\/\//,vh=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,yh=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function bh(e){return _h.test(e)}function xh(e){return e.startsWith(`//`)}function Sh(e){return e.startsWith(`/`)}function Ch(e){return e.startsWith(`file:`)}function wh(e){return/^[.?#]/.test(e)}function Th(e){let t=vh.exec(e);return Dh(t[1],t[2]||``,t[3],t[4]||``,t[5]||`/`,t[6]||``,t[7]||``)}function Eh(e){let t=yh.exec(e),n=t[2];return Dh(`file:`,``,t[1]||``,``,Sh(n)?n:`/`+n,t[3]||``,t[4]||``)}function Dh(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function Oh(e){if(xh(e)){let t=Th(`http:`+e);return t.scheme=``,t.type=6,t}if(Sh(e)){let t=Th(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(Ch(e))return Eh(e);if(bh(e))return Th(e);let t=Th(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function kh(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Ah(e,t){jh(t,t.type),e.path===`/`?e.path=t.path:e.path=kh(t.path)+e.path}function jh(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];if(!t){o=!0;continue}if(o=!1,t!==`.`){if(t===`..`){a?(o=!0,a--,i--):n&&(r[i++]=t);continue}r[i++]=t,a++}}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function Mh(e,t){if(!e&&!t)return``;let n=Oh(e),r=n.type;if(t&&r!==7){let e=Oh(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:Ah(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}jh(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?wh(t||e)&&!wh(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}function Nh(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Ph(e,t){let n=Nh(e),r=t?t+`/`:``;return e=>Mh(r+(e||``),n)}var Fh=0,Ih=1,Lh=2,Rh=3,zh=4;function Bh(e,t){let n=Vh(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=Vh(e,r+1))e[r]=Uh(e[r],t);return e}function Vh(e,t){for(let n=t;n<e.length;n++)if(!Hh(e[n]))return n;return e.length}function Hh(e){for(let t=1;t<e.length;t++)if(e[t][Fh]<e[t-1][Fh])return!1;return!0}function Uh(e,t){return t||(e=e.slice()),e.sort(Wh)}function Wh(e,t){return e[Fh]-t[Fh]}var Gh=!1;function Kh(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][Fh]-t;if(a===0)return Gh=!0,i;a<0?n=i+1:r=i-1}return Gh=!1,n-1}function qh(e,t,n){for(let r=n+1;r<e.length&&e[r][Fh]===t;n=r++);return n}function Jh(e,t,n){for(let r=n-1;r>=0&&e[r][Fh]===t;n=r--);return n}function Yh(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function Xh(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return Gh=o!==-1&&e[o][Fh]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=Kh(e,t,s,c)}function Zh(e){return typeof e==`string`?JSON.parse(e):e}var Qh="`line` must be greater than 0 (lines start at line 1)",$h="`column` must be greater than or equal to 0 (columns start at column 0)",eg=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=Zh(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=Ph(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=Bh(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=Yh(),this._bySources=void 0,this._bySourceMemos=void 0}};function tg(e){return e}function ng(e){var t;return(t=tg(e))._decoded||(t._decoded=mh(tg(e)._encoded))}function rg(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error(Qh);if(r<0)throw Error($h);let a=ng(e);if(n>=a.length)return ig(null,null,null,null);let o=a[n],s=ag(o,tg(e)._decodedMemo,n,r,i||1);if(s===-1)return ig(null,null,null,null);let c=o[s];if(c.length===1)return ig(null,null,null,null);let{names:l,resolvedSources:u}=e;return ig(u[c[Ih]],c[Lh]+1,c[Rh],c.length===5?l[c[zh]]:null)}function ig(e,t,n,r){return{source:e,line:t,column:n,name:r}}function ag(e,t,n,r,i){let a=Xh(e,r,t,n);return Gh?a=(i===-1?qh:Jh)(e,r,a):i===-1&&a++,a===-1||a===e.length?-1:a}function og(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===61}function sg(e){let t=0;for(;t<e.length;){let n=e.indexOf(`//# sourceMappingURL=data:application/json`,t);if(n===-1)return;let r=e.indexOf(`;base64,`,n+42);if(r===-1){t=n+42;continue}let i=e.indexOf(`,`,n);if(i!==-1&&i<r){t=r+8;continue}let a=r+8,o=a;for(;o<e.length&&og(e.charCodeAt(o));)o++;if(o>a)return e.slice(a,o);t=o}}function cg(e,t,n){let r=sg(n);if(!r)return e;try{let n=Buffer.from(r,`base64`).toString(`utf-8`),i=new eg(JSON.parse(n));return e.split(`
140
- `).map(e=>{let n=e.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);if(!n)return e;let[,r,a,o,s]=n;if(!a.includes(t))return e;let c=parseInt(o,10),l=parseInt(s,10),u=rg(i,{line:c,column:l});if(u.source&&u.line!==null){let e=r||u.name||`anonymous`,t=u.column===null?l:u.column;return` at ${e} (${u.source}:${u.line}:${t})`}return e}).join(`
141
- `)}catch{return e}}function lg(e,t,n){let r=(2<<31-Math.clz32(e.length-1|1))-1,i=Math.ceil(1.6*r*t/e.length);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(o+=e[t[s]&r]||``,o.length>=a)return o}}}function ug(e){return function(t,n){let i=function(...i){let{promise:a,resolve:o,reject:s}=r(),c=`step_${e.generateUlid()}`,l={type:`step`,correlationId:c,stepName:t,args:i};this!==void 0&&this!==null&&this!==globalThis&&(l.thisVal=this);let u=n?.();return u&&(l.closureVars=u),e.invocationsQueue.set(c,l),Ie.debug(`Step consumer setup`,{correlationId:c,stepName:t,args:i}),e.eventsConsumer.subscribe(n=>{if(!n)return _n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),$e.NotConsumed;if(Ie.debug(`Step consumer event processing`,{correlationId:c,stepName:t,args:i.join(`, `),incomingCorrelationId:n.correlationId,isMatch:c===n.correlationId,eventType:n.eventType}),n.correlationId!==c)return $e.NotConsumed;let r=`eventData`in n&&n.eventData&&`stepName`in n.eventData?n.eventData.stepName:void 0;if(typeof r==`string`&&r!==t)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Corrupted event log: step event ${n.eventType} for ${c} belongs to "${r}", but the current step consumer is "${t}"`))}),$e.Finished;if(n.eventType===`step_created`){let n=e.invocationsQueue.get(c);return!n||n.type!==`step`?(e.promiseQueue=e.promiseQueue.then(()=>{s(new T(`Corrupted event log: step ${c} (${t}) created but not found in invocation queue`))}),$e.Finished):(n.hasCreatedEvent=!0,$e.Consumed)}return n.eventType===`step_started`||n.eventType===`step_retrying`?$e.Consumed:n.eventType===`step_failed`?(e.invocationsQueue.delete(n.correlationId),e.promiseQueue=e.promiseQueue.then(async()=>{try{s(await Be(n.eventData.error,e.runId,e.encryptionKey,e.globalThis))}catch(e){Ie.error(`Failed to hydrate step_failed error`,{correlationId:n.correlationId,error:e instanceof Error?e.message:String(e)}),s(new _(`Failed to hydrate step error: ${e instanceof Error?e.message:String(e)}`))}}),$e.Finished):n.eventType===`step_completed`?(e.invocationsQueue.delete(n.correlationId),e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{o(await Re(n.eventData.result,e.runId,e.encryptionKey,e.globalThis))}catch(e){s(e)}finally{e.pendingDeliveries--}}),$e.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Unexpected event type for step ${c} (name: ${t}) "${n.eventType}"`))}),$e.Finished)}),a},a=t.split(`//`).pop();return Object.defineProperty(i,"name",{value:a}),Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"bind",{value:function(e,...r){let i=Function.prototype.bind.call(this,e,...r);return Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"__boundThis",{value:e,writable:!1,enumerable:!1,configurable:!1}),r.length>0&&Object.defineProperty(i,"__boundArgs",{value:r,writable:!1,enumerable:!1,configurable:!1}),i},writable:!1,enumerable:!1,configurable:!1}),i}}var dg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*23283064365386963e-26;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=e|0)},t.c=1,t.s0=n(` `),t.s1=n(` `),t.s2=n(` `),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return n.next()*4294967296|0},o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}function o(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=r*4294967296}return(e>>>0)*23283064365386963e-26}}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),fg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),pg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),mg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r=e[n],i;return r^=r>>>7,i=r^r<<24,r=e[n+1&7],i^=r^r>>>10,r=e[n+3&7],i^=r^r>>>3,r=e[n+4&7],i^=r^r<<7,r=e[n+7&7],r^=r<<13,i^=r^r<<9,e[n]=i,t.i=n+1&7,i};function n(e,t){var n,r=[];if(t===(t|0))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}n(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),hg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,i,a;return t.w=e=e+1640531527|0,a=n[r+34&127],i=n[r=r+1&127],a^=a<<13,i^=i<<17,a^=a>>>15,i^=i>>>12,a=n[r]=a^i,t.i=r,a+(e^e>>>16)|0};function n(e,t){var n,r,i,a,o,s=[],c=128;for(t===(t|0)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,n=s[a&127]^=r+o,i=n==0?i+1:0);for(i>=128&&(s[(t&&t.length||0)&127]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}n(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),gg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=e|0):n+=e;for(var r=0;r<n.length+20;r++)t.b^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),_g=n(((e,n)=>{(function(e,r,i){var a=256,o=6,s=52,c=`random`,l=i.pow(a,o),u=i.pow(2,s),d=u*2,f=a-1,p;function m(e,t,n){var s=[];t=t==1?{entropy:!0}:t||{};var f=v(_(t.entropy?[e,b(r)]:e??y(),3),s),p=new h(s),m=function(){for(var e=p.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=p.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return m.int32=function(){return p.g(4)|0},m.quick=function(){return p.g(4)/4294967296},m.double=m,v(b(p.S),r),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,p),e.state=function(){return g(p,{})}),n?(i[c]=e,t):e})(m,f,`global`in t?t.global:this==i,t.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function _(e,t){var n=[],r=typeof e,i;if(t&&r==`object`)for(i in e)try{n.push(_(e[i],t-1))}catch{}return n.length?n:r==`string`?e:e+`\0`}function v(e,t){for(var n=e+``,r,i=0;i<n.length;)t[f&i]=f&(r^=t[f&i]*19)+n.charCodeAt(i++);return b(t)}function y(){try{var t;return p&&(t=p.randomBytes)?t=t(a):(t=new Uint8Array(a),(e.crypto||e.msCrypto).getRandomValues(t)),b(t)}catch{var n=e.navigator,i=n&&n.plugins;return[+new Date,e,i,e.screen,b(r)]}}function b(e){return String.fromCharCode.apply(0,e)}if(v(i.random(),r),typeof n==`object`&&n.exports){n.exports=m;try{p=t(`crypto`)}catch{}}else typeof define==`function`&&define.amd?define(function(){return m}):i[`seed`+c]=m})(typeof self<`u`?self:e,[],Math)})),vg=e(n(((e,t)=>{var n=dg(),r=fg(),i=pg(),a=mg(),o=hg(),s=gg(),c=_g();c.alea=n,c.xor128=r,c.xorwow=i,c.xorshift7=a,c.xor4096=o,c.tychei=s,t.exports=c}))(),1);const yg=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,bg=new Uint8Array(128).fill(255);for(let e=0;e<64;e++)bg[yg.charCodeAt(e)]=e;function xg(e){return e===9||e===10||e===12||e===13||e===32}function Sg(e,t){for(;t<e.length&&xg(e.charCodeAt(t));)t++;return t}function Cg(e,t){let n=e.length,r=e;n===2?r=e+`AA`:n===3&&(r=e+`A`);let i=bg[r.charCodeAt(0)],a=bg[r.charCodeAt(1)],o=bg[r.charCodeAt(2)],s=bg[r.charCodeAt(3)],c=i<<2|a>>4,l=(a&15)<<4|o>>2,u=(o&3)<<6|s;if(n===2){if(t&&l!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c]}if(n===3){if(t&&u!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c,l]}return[c,l,u]}function wg(e,t,n,r){if(r===void 0&&(r=2**53-1),r===0)return{read:0,bytes:[],error:null};let i=0,a=[],o=``,s=0,c=0,l=e.length;for(;;){if(c=Sg(e,c),c===l){if(s>0){if(n===`stop-before-partial`)return{read:i,bytes:a,error:null};if(n===`loose`){if(s===1)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: lone character in final chunk`)};a.push(...Cg(o,!1))}else return{read:i,bytes:a,error:SyntaxError(`Invalid base64: incomplete chunk in strict mode`)}}return{read:l,bytes:a,error:null}}let u=e[c];if(c++,u===`=`){if(s<2)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: padding in unexpected place`)};if(c=Sg(e,c),s===2){if(c===l)return n===`stop-before-partial`?{read:i,bytes:a,error:null}:{read:i,bytes:a,error:SyntaxError(`Invalid base64: missing second padding character`)};u=e[c],u===`=`&&(c=Sg(e,c+1))}if(c<l)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected characters after padding`)};let t=n===`strict`;try{a.push(...Cg(o,t))}catch(e){return{read:i,bytes:a,error:e}}return{read:l,bytes:a,error:null}}if(t===`base64url`){if(u===`+`||u===`/`)return{read:i,bytes:a,error:SyntaxError(`Invalid base64url: unexpected character '${u}'`)};u===`-`?u=`+`:u===`_`&&(u=`/`)}let d=u.charCodeAt(0);if(d>=128||bg[d]===255)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected character '${e[c-1]}'`)};let f=r-a.length;if(f===1&&s===2||f===2&&s===3||(o+=u,s=o.length,s===4&&(a.push(...Cg(o)),o=``,s=0,i=c,a.length===r)))return{read:i,bytes:a,error:null}}}function Tg(e,t){t===void 0&&(t=2**53-1);let n=e.length,r=[],i=0;if(n%2!=0)return{read:0,bytes:[],error:SyntaxError(`Invalid hex: string length must be even`)};for(;i<n&&r.length<t;){let t=e.substring(i,i+2);if(!/^[0-9a-fA-F]{2}$/.test(t))return{read:i,bytes:r,error:SyntaxError(`Invalid hex: unexpected character at position ${i}`)};i+=2,r.push(Number.parseInt(t,16))}return{read:i,bytes:r,error:null}}function Eg(e,t){let n=t?.alphabet??`base64`;if(n!==`base64`&&n!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${n}"`);let r=!!t?.omitPadding,i=``,a=e.length;for(let t=0;t<a;t+=3){let n=e[t],o=t+1<a?e[t+1]:0,s=t+2<a?e[t+2]:0;i+=yg[n>>2&63],i+=yg[(n&3)<<4|o>>4&15],t+1<a?i+=yg[(o&15)<<2|s>>6&3]:r||(i+=`=`),t+2<a?i+=yg[s&63]:r||(i+=`=`)}return n===`base64url`&&(i=i.replace(/\+/g,`-`).replace(/\//g,`_`)),i}function Dg(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function Og(e){let t=e.prototype,n=e;t.toBase64||Object.defineProperty(t,"toBase64",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Eg(this,t)},writable:!0,enumerable:!1,configurable:!0}),t.toHex||Object.defineProperty(t,"toHex",{value:function(){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Dg(this)},writable:!0,enumerable:!1,configurable:!0}),t.setFromBase64||Object.defineProperty(t,"setFromBase64",{value:function(t,n){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=wg(t,r,i,this.length),o=a.bytes,s=o.length;for(let e=0;e<s;e++)this[e]=o[e];if(a.error)throw a.error;return{read:a.read,written:s}},writable:!0,enumerable:!1,configurable:!0}),t.setFromHex||Object.defineProperty(t,"setFromHex",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Tg(t,this.length),r=n.bytes,i=r.length;for(let e=0;e<i;e++)this[e]=r[e];if(n.error)throw n.error;return{read:n.read,written:i}},writable:!0,enumerable:!1,configurable:!0}),n.fromBase64||Object.defineProperty(e,"fromBase64",{value:function(t,n){if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=wg(t,r,i);if(a.error)throw a.error;return new e(a.bytes)},writable:!0,enumerable:!1,configurable:!0}),n.fromHex||Object.defineProperty(e,"fromHex",{value:function(t){if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Tg(t);if(n.error)throw n.error;return new e(n.bytes)},writable:!0,enumerable:!1,configurable:!0})}function kg(e){return function(){let t=`0123456789abcdef`,n=``;for(let r=0;r<36;r++)r===8||r===13||r===18||r===23?n+=`-`:r===14?n+=`4`:r===19?n+=t[Math.floor(e()*4)+8]:n+=t[Math.floor(e()*16)];return n}}function Ag(e){let{fixedTimestamp:t}=e,{seed:n}=e,r=(0,vg.default)(n),a=Kn(),o=qn(`globalThis`,a);o.Math.random=r;let s=o.Date;o.Date=function(...e){return e.length===0?new s(t):new s(...e)},o.Date.prototype=s.prototype,Object.setPrototypeOf(o.Date,s),o.Date.now=()=>t;let c=globalThis.crypto,l=c.subtle;function u(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(r()*256);return e}let d=kg(r),f=l.digest.bind(l);return o.crypto=new Proxy(c,{get(e,t){return t===`getRandomValues`?u:t===`randomUUID`?d:t===`subtle`?new Proxy(l,{get(e,t){return t===`generateKey`?()=>{throw new i("`crypto.subtle.generateKey()` is not available inside a workflow function. Move key generation to a step function where full Node.js crypto is available.")}:t===`digest`?f:e[t]}}):e[t]}}),o.process={env:Object.freeze({...process.env})},o.DOMException=globalThis.DOMException,o.Headers=globalThis.Headers,o.TextEncoder=globalThis.TextEncoder,o.TextDecoder=globalThis.TextDecoder,o.console=globalThis.console,o.URL=globalThis.URL,o.URLSearchParams=globalThis.URLSearchParams,o.structuredClone=globalThis.structuredClone,o.atob=globalThis.atob,o.btoa=globalThis.btoa,Og(o.Uint8Array),o.Symbol.dispose??=Symbol.for(`Symbol.dispose`),o.Symbol.asyncDispose??=Symbol.for(`Symbol.asyncDispose`),o.exports={},o.module={exports:o.exports},{context:a,globalThis:o,updateTimestamp:e=>{t=e}}}function jg(e){return function(t={}){let n=`hook_${e.generateUlid()}`,i=t.token??e.generateNanoid(),a=t.isWebhook??!1;e.invocationsQueue.set(n,{type:`hook`,correlationId:n,token:i,metadata:t.metadata,isWebhook:a});let o=[],s=[],c=!1,l=!1,u=!1,d=null;gt.debug(`Hook consumer setup`,{correlationId:n,token:i}),e.eventsConsumer.subscribe(t=>{if(!t)return c=!0,s.length>0&&o.length===0&&_n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),$e.NotConsumed;if(t.correlationId!==n)return $e.NotConsumed;let r=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof r==`string`&&r!==i)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Corrupted event log: hook event ${t.eventType} for ${n} belongs to token "${r}", but the current hook consumer expects "${i}"`))}),$e.Finished;if(t.eventType===`hook_created`){let t=e.invocationsQueue.get(n);return t&&t.type===`hook`&&(t.hasCreatedEvent=!0),$e.Consumed}if(t.eventType===`hook_conflict`){e.invocationsQueue.delete(n);let r=t,i=new f(r.eventData.token,r.eventData.conflictingRunId);u=!0,d=i;let a=s.slice();return s.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of a)e.reject(i)}),$e.Consumed}if(t.eventType===`hook_received`){if(s.length>0){let n=s.shift();n&&(e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await Re(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis);n.resolve(r)}catch(e){n.reject(e)}finally{e.pendingDeliveries--}}))}else o.push(t);return $e.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(n),l=!0,$e.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Unexpected event type for hook ${n} (token: ${i}) "${t.eventType}"`))}),$e.Finished)});let p=!1;function m(){let t=r();if(u&&d)return e.promiseQueue=e.promiseQueue.then(()=>{t.reject(d)}),t.promise;if(o.length>0){let n=o.shift();if(n)return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await Re(n.eventData.payload,e.runId,e.encryptionKey,e.globalThis);t.resolve(r)}catch(e){t.reject(e)}finally{e.pendingDeliveries--}}),t.promise}return c&&_n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),s.push(t),t.promise}function h(){if(p||(p=!0,l))return;let t=e.invocationsQueue.get(n);t&&t.type===`hook`&&(t.disposed=!0),s.length>0&&(s.length=0,_n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))})),gt.debug(`Hook disposed`,{correlationId:n,token:i})}let g={token:i,then(e,t){return m().then(e,t)},async*[Symbol.asyncIterator](){for(;!p;)yield await this},dispose:h,[Symbol.dispose]:h},_=e.globalThis.Symbol.dispose;return _&&_!==Symbol.dispose&&(g[_]=h),g}}function Mg(e){return async function(t){let{promise:n,resolve:i}=r(),a=`wait_${e.generateUlid()}`,o=c(t),s={type:`wait`,correlationId:a,resumeAt:o};return e.invocationsQueue.set(a,s),e.eventsConsumer.subscribe(t=>{if(!t)return _n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),$e.NotConsumed;if(t.correlationId!==a)return $e.NotConsumed;if(t.eventType===`wait_created`){let n=e.invocationsQueue.get(a);return n&&n.type===`wait`&&(n.hasCreatedEvent=!0,n.resumeAt=t.eventData.resumeAt),$e.Consumed}if(t.eventType===`wait_completed`){let n=t.eventData?.resumeAt;if(n!==void 0){let t=e.invocationsQueue.get(a),r=t&&t.type===`wait`?t.resumeAt:o,i=new Date(n),s=i.getTime(),c=r.getTime(),l=Number.isFinite(s)?i.toISOString():String(n);if(s!==c)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Corrupted event log: wait_completed event for ${a} has resumeAt "${l}", but the current wait consumer expects "${r.toISOString()}"`))}),$e.Finished}return e.invocationsQueue.delete(a),e.promiseQueue=e.promiseQueue.then(()=>{i()}),$e.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Unexpected event type for wait ${a} "${t.eventType}"`))}),$e.Finished}),n}}async function Ng(e,t,n,r,i){if(t.size!==0){for(let e of t.values())e.type===`hook`&&e.isSystem&&!e.disposed&&!e.abortRequested&&(e.disposed=!0);try{let e=await Wm();await oh({suspension:new Ue(t,n),world:e,run:r})}catch(t){W.warn(`Failed to drain pending queue items for ${i} workflow run`,{workflowRunId:e,message:t instanceof Error?t.message:String(t)})}}}async function Pg(e,t,n,a){return _t(`workflow.run ${t.workflowName}`,async o=>{o?.setAttributes({...pt(t.workflowName),...it(t.runId),...Ut(t.status),...Le(n.length)});let s=t.startedAt;if(!s)throw new i(`Workflow run "${t.runId}" has no "startedAt" timestamp (should not happen)`);let c=process.env.VERCEL_URL!==void 0,u=c?void 0:await ih(),{context:d,globalThis:f,updateTimestamp:p}=Ag({seed:`${t.runId}:${t.workflowName}:${+s}`,fixedTimestamp:+s}),m=r(),h=he(()=>f.Math.random()),g=lg(`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,21,e=>new Uint8Array(e).map(()=>256*f.Math.random())),_={current:Promise.resolve()},v=new tt(n,{onUnconsumedEvent:e=>{m.reject(new T(`Unconsumed event in event log: eventType=${e.eventType}, correlationId=${e.correlationId}, eventId=${e.eventId}. This indicates a corrupted or invalid event log.`))},getPromiseQueue:()=>_.current}),y={runId:t.runId,encryptionKey:a,globalThis:f,onWorkflowError:m.reject,eventsConsumer:v,generateUlid:()=>h(+s),generateNanoid:g,invocationsQueue:new Map,get promiseQueue(){return _.current},set promiseQueue(e){_.current=e},pendingDeliveries:0};y.eventsConsumer.subscribe(e=>{let t=e?.createdAt;return t&&p(+t),$e.NotConsumed}),y.eventsConsumer.subscribe(e=>e&&(e.eventType===`run_created`||e.eventType===`run_started`)?$e.Consumed:$e.NotConsumed);let x=ug(y),S=jg(y),C=Mg(y);f[ve]=x,f[_e]=S,f[Se]=C,f[Te]=e=>qe(t.runId,e);let w=c?`https://${process.env.VERCEL_URL}`:`http://localhost:${u??3e3}`;f[ye]={workflowName:t.workflowName,workflowRunId:t.runId,workflowStartedAt:new f.Date(+s),url:w,features:{encryption:!!a}},f[Ce]=h,f.fetch=()=>{throw new f.Error(`Global "fetch" is unavailable in workflow functions. Use the "fetch" step function from "workflow" to make HTTP requests.\n\nLearn more: https://workflow-sdk.dev/err/${b.FETCH_IN_WORKFLOW_FUNCTION}`)};let E=`Timeout functions like "setTimeout" and "setInterval" are not supported in workflow functions. Use the "sleep" function from "workflow" for time-based delays.`;f.setTimeout=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.setInterval=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.clearTimeout=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.clearInterval=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.setImmediate=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.clearImmediate=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.AbortController=Bt(y);let O=Pe();f.AbortSignal={abort:O.abort,any:O.any,timeout:O.timeout};class k{cache;credentials;destination;headers;integrity;method;mode;redirect;referrer;referrerPolicy;url;keepalive;signal;duplex;body;constructor(e,t){if(typeof e==`string`||e instanceof f.URL){let t=String(e);try{new f.URL(t),this.url=t}catch(e){throw TypeError(`Failed to parse URL from ${t}`,{cause:e})}}else{if(this.url=e.url,!t){this.method=e.method,this.headers=new f.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination;return}this.method=e.method,this.headers=new f.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination}t?.method?this.method=t.method.toUpperCase():typeof this.method!=`string`&&(this.method=`GET`),t?.headers?this.headers=new f.Headers(t.headers):(typeof e==`string`||e instanceof f.URL)&&(this.headers=new f.Headers),t?.mode===void 0?typeof this.mode!=`string`&&(this.mode=`cors`):this.mode=t.mode,t?.credentials===void 0?typeof this.credentials!=`string`&&(this.credentials=`same-origin`):this.credentials=t.credentials,t?.cache===void 0?typeof this.cache!=`string`&&(this.cache=`default`):this.cache=t.cache,t?.redirect===void 0?typeof this.redirect!=`string`&&(this.redirect=`follow`):this.redirect=t.redirect,t?.referrer===void 0?typeof this.referrer!=`string`&&(this.referrer=`about:client`):this.referrer=t.referrer,t?.referrerPolicy===void 0?typeof this.referrerPolicy!=`string`&&(this.referrerPolicy=``):this.referrerPolicy=t.referrerPolicy,t?.integrity===void 0?typeof this.integrity!=`string`&&(this.integrity=``):this.integrity=t.integrity,t?.keepalive===void 0?typeof this.keepalive!=`boolean`&&(this.keepalive=!1):this.keepalive=t.keepalive,t?.signal===void 0?this.signal||={aborted:!1}:this.signal=t.signal,this.duplex||=`half`,this.destination||=`document`;let n=t?.body;if(n!=null&&(this.method===`GET`||this.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);n==null?this.body=null:this.body=Object.create(f.ReadableStream.prototype,{[me]:{value:n,writable:!1}})}clone(){ot()}get bodyUsed(){return!1}blob;formData;arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}}f.Request=k,Object.defineProperties(k.prototype,{arrayBuffer:{value:x(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:x(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:x(`__builtin_response_text`),writable:!0,configurable:!0}});class A{type;url;status;statusText;body;headers;redirected;constructor(e,t){if(this.status=t?.status??200,this.statusText=t?.statusText??``,this.headers=new f.Headers(t?.headers),this.type=`default`,this.url=``,this.redirected=!1,e!=null&&(this.status===204||this.status===205||this.status===304))throw TypeError(`Response constructor: Invalid response status code ${this.status}`);e==null?this.body=null:this.body=Object.create(f.ReadableStream.prototype,{[me]:{value:e,writable:!1}})}clone;blob;formData;get ok(){return this.status>=200&&this.status<300}get bodyUsed(){return!1}arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}static json(e,t){let n=JSON.stringify(e),r=new f.Headers(t?.headers);return r.has(`content-type`)||r.set(`content-type`,`application/json`),new A(n,{...t,headers:r})}static error(){ot()}static redirect(e,t=302){if(![301,302,303,307,308].includes(t))throw RangeError(`Invalid redirect status code: ${t}. Must be one of: 301, 302, 303, 307, 308`);let n=new f.Headers;n.set(`Location`,String(e));let r=Object.create(A.prototype);return r.status=t,r.statusText=``,r.headers=n,r.body=null,r.type=`default`,r.url=``,r.redirected=!1,r}}f.Response=A,Object.defineProperties(A.prototype,{arrayBuffer:{value:x(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:x(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:x(`__builtin_response_text`),writable:!0,configurable:!0}});class j{constructor(){ot()}get locked(){return!1}cancel(){ot()}getReader(){ot()}pipeThrough(){ot()}pipeTo(){ot()}tee(){ot()}values(){ot()}static from(){ot()}[Symbol.asyncIterator](){ot()}}f.ReadableStream=j;class M{constructor(){ot()}get locked(){return!1}abort(){ot()}close(){ot()}getWriter(){ot()}}f.WritableStream=M;class N{readable;writable;constructor(){ot()}}f.TransformStream=N,f.console=globalThis.console;let P=Symbol.for(`@vercel/request-context`);f[P]=globalThis[P];let ee=l(t.workflowName)?.moduleSpecifier||t.workflowName,F=qn(`${e}; globalThis.__private_workflows?.get(${JSON.stringify(t.workflowName)})`,d,{filename:ee});if(typeof F!=`function`)throw new D(t.workflowName);let te=[];y.promiseQueue=y.promiseQueue.then(async()=>{te=await rt(t.input,t.runId,a,f)}),await y.promiseQueue,o?.setAttributes({...hn(te.length)});try{let e=await Promise.race([F(...te),m.promise]),n=await Tt(e,t.runId,a,f);return o?.setAttributes({...ze(typeof e)}),await Ng(t.runId,y.invocationsQueue,f,t,`completed`),n}catch(e){throw Ue.is(e)||await Ng(t.runId,y.invocationsQueue,f,t,`failed`),e}})}const Fg=he();async function Ig(e,t,n){"use step";return await Ze(()=>{let r=e?.workflowId;if(!r)throw new i(`'start' received an invalid workflow function. Ensure the Workflow SDK is configured correctly and the function includes a 'use workflow' directive.`,{slug:`start-invalid-workflow-function`});return _t(`workflow.start ${r}`,async e=>{e?.setAttributes({...pt(r),...Ve(`start`)});let a=[],o=n??{};Array.isArray(t)?a=t:typeof t==`object`&&(o=t),e?.setAttributes({...hn(a.length)});let s=o?.world??await lt(),c=o.deploymentId??await s.getDeploymentId();if(c===`latest`){if(!s.resolveLatestDeploymentId)throw new i(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`);c=await s.resolveLatestDeploymentId()}let l=[],u=`wrun_${Fg()}`,d=await mt(),f=o.specVersion??s.specVersion??2,p=ce(f),m=await s.getEncryptionKeyForRun?.(u,{...o,deploymentId:c}),h=m?await Ke(m):void 0,g=await mn(a,u,h,l,globalThis,p),_={traceCarrier:d,workflowCoreVersion:Zt,features:{encryption:!!h}},[v,y]=await Promise.allSettled([s.events.create(u,{eventType:`run_created`,specVersion:f,eventData:{deploymentId:c,workflowName:r,input:g,executionContext:_}},{v1Compat:p}),s.queue(Ct(r),{runId:u,traceCarrier:d,...f>=3?{runInput:{input:g,deploymentId:c,workflowName:r,specVersion:f,executionContext:_}}:{}},{deploymentId:c,specVersion:f})]);if(y.status===`rejected`)throw y.reason;let b=!1;if(v.status===`rejected`){let e=v.reason;if(!C.is(e))if(Lg(e))b=!0,W.warn(`Run creation event failed, but the run was accepted via the queue. The run_created event will be re-tried async by the runtime.`,{workflowRunId:u,error:e.message});else throw e}else{let e=v.value;if(!e.run)throw new i(`Missing 'run' in server response for 'run_created' event`);if(!p&&e.run.runId!==u)throw new i(`Server returned different runId than requested: expected ${u}, got ${e.run.runId}`)}return(0,Ym.waitUntil)(Promise.all(l).catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))throw e})),e?.setAttributes({...it(u),...$t(c),...v.status===`fulfilled`&&v.value.run?Ut(v.value.run.status):{}}),new Gg(u,{resilientStart:b})})})}function Lg(e){return!!(S.is(e)||O.is(e)&&e.status&&e.status>=500)}const Rg=e=>Array.isArray(e)?e:[e];async function zg(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),a=i?await Ke(i):void 0,o=Rg(await rt(r.input,t,a,globalThis)),s=n.specVersion??r.specVersion??1,c=n.deploymentId??r.deploymentId;return(await Ig({workflowId:r.workflowName},o,{deploymentId:c,world:e,specVersion:s})).runId}catch(e){throw Error(`Failed to recreate run from ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Bg(e,t){try{let n=(await e.runs.get(t,{resolveData:`none`})).specVersion??1,r=ce(n),i={eventType:`run_cancelled`,specVersion:n};await e.events.create(t,i,{v1Compat:r})}catch(e){throw Error(`Failed to cancel run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Vg(e,t){try{let n=await e.runs.get(t,{resolveData:`none`});await e.queue(Ct(n.workflowName),{runId:t},{deploymentId:n.deploymentId,specVersion:n.specVersion??1})}catch(e){throw Error(`Failed to re-enqueue run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Hg(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`}),i=ce(r.specVersion),a=[],o=null;do{let n=await e.events.list({runId:t,pagination:{limit:1e3,...o?{cursor:o}:{}},resolveData:`none`});a.push(...n.data),o=n.hasMore?n.cursor:null}while(o);let s=a.filter(e=>e.eventType===`wait_created`),c=new Set(a.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),l=s.filter(e=>!c.has(e.correlationId));if(n?.correlationIds&&n.correlationIds.length>0){let e=new Set(n.correlationIds);l=l.filter(t=>t.correlationId&&e.has(t.correlationId))}let u=[],d=0;for(let n of l){if(!n.correlationId)continue;let a=i?{eventType:`wait_completed`,correlationId:n.correlationId}:{eventType:`wait_completed`,correlationId:n.correlationId,specVersion:r.specVersion,eventData:{resumeAt:n.eventData.resumeAt}};try{await e.events.create(t,a,{v1Compat:i}),d++}catch(e){C.is(e)?d++:u.push(e instanceof Error?e:Error(String(e)))}}if(d>0&&await e.queue(Ct(r.workflowName),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1}),u.length>0)throw AggregateError(u,`Failed to complete ${u.length}/${l.length} pending wait(s) for run ${t}`);return{stoppedCount:d}}catch(e){throw e instanceof AggregateError?e:Error(`Failed to wake up run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Ug(e,t,n,r){try{return await e.streams.get(t,n,r?.startIndex)}catch(e){throw Error(`Failed to read stream ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Wg(e,t){try{return await e.streams.list(t)}catch(e){throw Error(`Failed to list streams for run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}var Gg=class e{static[Qe](e){return{runId:e.runId,resilientStart:e.#r}}static[Je](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=lt(),this.#e}#n=null;#r=!1;constructor(e,t){this.runId=e,this.#r=t?.resilientStart??!1}#i(){return this.#n||=(async()=>{let e=await this.#t,t=await e.runs.get(this.runId),n=await e.getEncryptionKeyForRun?.(t);return n?await Ke(n):void 0})(),this.#n}async wakeUp(e){"use step";return Hg(await this.#t,this.runId,e)}async cancel(){"use step";await(await this.#t).events.create(this.runId,{eventType:`run_cancelled`,specVersion:3})}get exists(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(()=>!0).catch(e=>{if(u.is(e))return!1;throw e}))}get status(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.status))}get returnValue(){"use step";return this.#a()}get workflowName(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.workflowName))}get createdAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.createdAt))}get startedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.startedAt))}get completedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.completedAt))}get readable(){return this.getReadable()}getReadable(e={}){"use step";let{ops:t=[],global:n=globalThis,startIndex:r,namespace:i}=e,a=qe(this.runId,i),o=this.#i(),s=ut(n,t,this.runId,o).ReadableStream({name:a,startIndex:r}),c=this.#t,l=this.runId;return Object.assign(s,{getTailIndex:async()=>(await(await c).streams.getInfo(l,a)).tailIndex})}async#a(){let e=await this.#t,t=0,n=this.#r?3:0,r=[1e3,3e3,6e3];for(;;)try{let t=await e.runs.get(this.runId);if(t.status===`completed`){let e=await this.#i();return await Ht(t.output,this.runId,e)}if(t.status===`cancelled`)throw new A(this.runId);if(t.status===`failed`){let e=await this.#i(),n;try{n=await dn(t.error,this.runId,e)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new p(this.runId,n,{errorCode:t.errorCode})}throw new k(this.runId,t.status)}catch(e){if(k.is(e)){await new Promise(e=>setTimeout(e,1e3));continue}if(u.is(e)&&t<n){let e=r[t];t++,await new Promise(t=>setTimeout(t,e));continue}throw e}}};function Kg(e){return new Gg(e)}function qg(e){return i.is(e)?d.RUNTIME_ERROR:Xn(e)?d.WORLD_CONTRACT_ERROR:null}async function Jg({world:e,workflowRun:t,runId:n,requestId:r,err:i,errorCode:a,logMessage:o}){W.error(o,{workflowRunId:n,errorCode:a,error:i instanceof Error?i.message:String(i)});try{let o=Wt(e,t??n);await e.events.create(n,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(i,n,await o()),errorCode:a}},{requestId:r})}catch(e){if(C.is(e)||m.is(e))return;if(Xn(e)){W.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:n,errorCode:d.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}}function Yg(e){let t=Number(process.env.WORKFLOW_V2_TIMEOUT_MS)||12e4,n=n=>n.createQueueHandler(`__wkf_workflow_`,async(r,a)=>{let o=sn(r);if(o){await Yt(o,`workflow`,n.specVersion);return}let{runId:s,traceCarrier:c,requestedAt:u,stepId:f,stepName:p,runInput:h}=ie.parse(r),{requestId:g}=a,v=a.queueName.slice(15),y=W.forRun(s,v);if(a.attempt>48){let e=er(void 0,d.MAX_DELIVERIES_EXCEEDED);y.error(`Workflow handler exceeded max deliveries (${a.attempt}/48)`,{attempt:a.attempt,errorCode:e.errorCode,errorAttribution:e.attribution});try{let e=await Wm(),t=Wt(e,s),n=new _(`Workflow exceeded maximum queue deliveries (${a.attempt}/48)`);await e.events.create(s,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(n,s,await t()),errorCode:d.MAX_DELIVERIES_EXCEEDED}},{requestId:g})}catch(e){if(C.is(e)||m.is(e))return;y.error(`Failed to mark run as failed after ${a.attempt} delivery attempts. A persistent error is preventing the run from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`,{attempt:a.attempt,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}return}let b=await Ge(),x=new qm;return await We(c,async()=>await Xe({workflowRunId:s,workflowName:v},async()=>{let n=await Wm();return _t(`WORKFLOW_V2 ${v}`,{links:b},async r=>{r?.setAttributes({...pt(v),...Ve(`execute_v2`),...jt(`vercel-queue`),...bt(a.queueName),...st(a.messageId),...Ne(`process`),...Rt({requestedAt:u}),...it(s),...et(!!c)});let o=Date.now(),_=0,y=null,b=null,S,w=-1,T,E;if(f&&p)try{let e=await n.runs.get(s);if(e.status!==`running`){W.debug(`Run already finished, skipping background step`,{workflowRunId:s,status:e.status});return}let t=e.startedAt?+e.startedAt:Date.now();x.pause();let r;try{r=await ah({world:n,workflowRunId:s,workflowName:v,workflowStartedAt:t,stepId:f,stepName:p})}finally{x.resume()}if(r.type===`retry`||r.type===`throttled`)return{timeoutSeconds:r.timeoutSeconds};if(r.type===`completed`&&r.hasPendingOps){await kt(n,Ct(v),{runId:s,traceCarrier:await mt(),requestedAt:new Date});return}if(r.type===`completed`||r.type===`failed`||r.type===`skipped`){let n=await Dt(s);y=n.events,b=n.cursor;let r=new Set,i=new Set;for(let e of y)e.eventType===`step_created`?r.add(e.correlationId):(e.eventType===`step_completed`||e.eventType===`step_failed`)&&i.add(e.correlationId);let a=!1;for(let e of r)if(!i.has(e)){a=!0;break}if(a){W.debug(`Background step done but other steps pending, returning`,{workflowRunId:s});return}W.debug(`All parallel steps done, replaying inline after background step`,{workflowRunId:s}),S=e,w=t}else return}catch(e){let t=qg(e);if(!t)throw e;await Jg({world:n,workflowRun:S,runId:s,requestId:g,err:e,errorCode:t,logMessage:`Fatal error while preparing background workflow step`});return}if(!S){try{let e=await n.events.create(s,{eventType:`run_started`,specVersion:h?.specVersion??3,...h?{eventData:{input:h.input,deploymentId:h.deploymentId,workflowName:h.workflowName,executionContext:h.executionContext}}:{}},{requestId:g});if(!e.run)throw new i(`Event creation for 'run_started' did not return the run entity for run "${s}"`);if(S=e.run,e.events&&e.events.length>0&&e.hasMore!==!0&&(T=e.events,E=e.cursor),!S.startedAt)throw new i(`Workflow run "${s}" has no "startedAt" timestamp`)}catch(e){if(C.is(e)||m.is(e)){W.info(`Run already finished during setup, skipping`,{workflowRunId:s,message:e.message});return}else{let t=qg(e);if(!t)throw e;await Jg({world:n,workflowRun:S,runId:s,requestId:g,err:e,errorCode:t,logMessage:`Fatal runtime error during workflow setup`});return}}if(w=+S.startedAt,r?.setAttributes({...Ut(S.status),...Fe(w)}),S.status!==`running`){W.info(`Workflow already completed or failed, skipping`,{workflowRunId:s,status:S.status});return}}let D=await Wt(n,S)();for(;;){if(_++,x.isExhausted()){await Jm({runId:s,workflowName:v,requestId:g,attempt:a.attempt,limitMs:x.configuredLimitMs});return}if(Date.now()-o>=t){W.info(`V2 timeout reached, re-scheduling workflow`,{workflowRunId:s,loopIteration:_,elapsedMs:Date.now()-o}),await kt(n,Ct(v),{runId:s,traceCarrier:await mt(),requestedAt:new Date});return}let i=0;try{let t;if(y===null)if(T)t=T,b=E??null;else{let e=await Dt(s);t=e.events,b=e.cursor}else if(b){let e=await Dt(s,b);if(e.events.length>0){let t=new Set(y.map(e=>e.eventId));for(let n of e.events)t.has(n.eventId)||y.push(n)}b=e.cursor??b,t=y}else if(T){W.debug(`No cursor after preloaded-events first iteration; doing full reload to pick up cursor.`,{workflowRunId:s});let e=await Dt(s);y=e.events,b=e.cursor,t=y}else{W.warn(`Event cursor missing after initial load — falling back to full reload. This indicates a bug in the World implementation.`,{workflowRunId:s});let e=await Dt(s);y=e.events,b=e.cursor,t=y}let a=t.find(e=>e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`);if(a){W.debug(`Run completed by concurrent handler, exiting`,{workflowRunId:s,eventType:a.eventType});return}let o=Date.now(),c=new Set(t.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),l=t.filter(e=>e.eventType===`wait_created`&&e.correlationId!==void 0&&!c.has(e.correlationId)&&o>=e.eventData.resumeAt.getTime()).map(e=>({eventType:`wait_completed`,specVersion:3,correlationId:e.correlationId,eventData:{resumeAt:e.eventData.resumeAt}}));for(let e of l)try{await n.events.create(s,e,{requestId:g})}catch(t){if(C.is(t)){W.info(`Wait already completed, skipping`,{workflowRunId:s,correlationId:e.correlationId});continue}throw t}if(l.length>0)if(b){let e=await Dt(s,b),n=new Set(e.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId));if(l.every(e=>n.has(e.correlationId))){let n=new Set(t.map(e=>e.eventId));for(let r of e.events)n.has(r.eventId)||t.push(r);b=e.cursor??b}else{let e=await Dt(s);t=e.events,b=e.cursor}}else{let e=await Dt(s);t=e.events,b=e.cursor}y=t,W.debug(`Starting workflow replay`,{workflowRunId:s,loopIteration:_,eventCount:t.length}),i=Date.now();let u=await Pg(e,S,t,D);W.debug(`Workflow replay completed`,{workflowRunId:s,loopIteration:_,replayMs:Date.now()-i});try{await n.events.create(s,{eventType:`run_completed`,specVersion:3,eventData:{output:u}},{requestId:g})}catch(e){if(C.is(e)||m.is(e)){W.info(`Tried completing workflow run, but run has already finished.`,{workflowRunId:s,message:e.message});return}throw e}r?.setAttributes({...Ut(`completed`)});return}catch(t){if(Ue.is(t)){W.debug(`Workflow suspended`,{workflowRunId:s,loopIteration:_,replayMs:Date.now()-i,steps:t.stepCount,hooks:t.hookCount,waits:t.waitCount});let e=at(t.stepCount,t.hookCount,t.waitCount);e&&W.debug(e);let a=Date.now(),o=await oh({suspension:t,world:n,run:S,span:r,requestId:g});if(W.debug(`Suspension handled`,{workflowRunId:s,suspensionMs:Date.now()-a,pendingSteps:o.pendingSteps.length,timeoutSeconds:o.timeoutSeconds,hasHookConflict:o.hasHookConflict}),o.hasHookConflict)return{timeoutSeconds:0};let c=o.pendingSteps;if(c.length===0)return o.timeoutSeconds===void 0?void 0:{timeoutSeconds:o.timeoutSeconds};let l=c.filter(e=>o.createdStepCorrelationIds.has(e.correlationId)),u=o.timeoutSeconds===void 0?l[0]:void 0;for(let e of c){if(u&&e.correlationId===u.correlationId)continue;let t=await mt();await kt(n,Ct(v),{runId:s,stepId:e.correlationId,stepName:e.stepName,traceCarrier:t,requestedAt:new Date},{idempotencyKey:e.correlationId})}if(!u)return o.timeoutSeconds===void 0?void 0:{timeoutSeconds:o.timeoutSeconds};x.pause();let d;try{d=await ah({world:n,workflowRunId:s,workflowName:v,workflowStartedAt:w,stepId:u.correlationId,stepName:u.stepName})}finally{x.resume()}if(d.type===`retry`){let e=await mt();return await kt(n,Ct(v),{runId:s,stepId:u.correlationId,stepName:u.stepName,traceCarrier:e,requestedAt:new Date},{delaySeconds:d.timeoutSeconds}),o.timeoutSeconds===void 0?void 0:{timeoutSeconds:o.timeoutSeconds}}if(d.type===`throttled`)return{timeoutSeconds:d.timeoutSeconds};if(d.type===`completed`&&d.hasPendingOps){W.debug(`Breaking loop: step has pending ops`,{workflowRunId:s,loopIteration:_,stepName:u.stepName}),await kt(n,Ct(v),{runId:s,traceCarrier:await mt(),requestedAt:new Date});return}o.timeoutSeconds!==void 0&&c.length}else{t instanceof Error&&r?.recordException?.(t);let i=await nh(t),a=i.name||Xm(t),o=i.message,c=i.stack||Zm(t);if(c){let t=l(v)?.moduleSpecifier||v;c=cg(c,t,e)}let u=Zn(t);W.error(`Error while running workflow`,{workflowRunId:s,errorCode:u,errorName:a,errorStack:c}),Cn.isNativeError(t)&&c&&(t.stack=c);try{await n.events.create(s,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(t,s,D),errorCode:u}},{requestId:g})}catch(e){if(C.is(e)||m.is(e)){W.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:s,message:e.message});return}if(Xn(e)){W.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:s,errorCode:d.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}r?.setAttributes({...Ut(`failed`),...Et(u),...dt(a),...pn(o),...vt(a)});return}}}})}))}),r;return Mt(async e=>(r||=n(await Um()),r(e)))}export{Gg as Run,Ue as WorkflowSuspension,Bg as cancelRun,Hm as createWorld,an as getHookByToken,Kg as getRun,Wm as getWorld,Um as getWorldHandlers,nn as healthCheck,_s as i,Wg as listStreams,Pl as n,Cs as r,Ug as readStream,zg as recreateRunFromExisting,Vg as reenqueueRun,qt as resumeHook,en as resumeWebhook,Gm as setWorld,Ig as start,Bl as t,Hg as wakeUpRun,Yg as workflowEntrypoint};
138
+ `);function k(e){var t=_(i.join(e,`prebuilds`)).map(b).filter(x(f,d)).sort(S)[0];if(t)return A(i.join(e,`prebuilds`,t.name))}function A(e){var t=_(e).map(C).filter(w(u,l)).sort(E(u))[0];if(t)return i.join(e,t.file)}};function _(e){try{return r.readdirSync(e)}catch{return[]}}function v(e,t){var n=_(e).filter(t);return n[0]&&i.join(e,n[0])}function y(e){return/\.node$/.test(e)}function b(e){var t=e.split(`-`);if(t.length===2){var n=t[0],r=t[1].split(`+`);if(n&&r.length&&r.every(Boolean))return{name:e,platform:n,architectures:r}}}function x(e,t){return function(n){return n==null||n.platform!==e?!1:n.architectures.includes(t)}}function S(e,t){return e.architectures.length-t.architectures.length}function C(e){var t=e.split(`.`),n=t.pop(),r={file:e,specificity:0};if(n===`node`){for(var i=0;i<t.length;i++){var a=t[i];if(a===`node`||a===`electron`||a===`node-webkit`)r.runtime=a;else if(a===`napi`)r.napi=!0;else if(a.slice(0,3)===`abi`)r.abi=a.slice(3);else if(a.slice(0,2)===`uv`)r.uv=a.slice(2);else if(a.slice(0,4)===`armv`)r.armv=a.slice(4);else if(a===`glibc`||a===`musl`)r.libc=a;else continue;r.specificity++}return r}}function w(e,t){return function(n){return!(n==null||n.runtime!==e&&!T(n)||n.abi!==t&&!n.napi||n.uv&&n.uv!==h||n.armv&&n.armv!==m||n.libc&&n.libc!==p)}}function T(e){return e.runtime===`node`&&e.napi}function E(e){return function(t,n){return t.runtime===n.runtime?t.abi===n.abi?t.specificity===n.specificity?0:t.specificity>n.specificity?-1:1:t.abi?-1:1:t.runtime===e?-1:1}}function D(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<`u`&&window.process&&window.process.type===`renderer`}function O(e){if(e!==`linux`)return!1;let{familySync:t,MUSL:n}=vp();return t()===n}g.parseTags=C,g.matchTags=w,g.compareTags=E,g.parseTuple=b,g.matchTuple=x,g.compareTuples=S})),bp=n(((e,t)=>{t.exports=yp()(__dirname)}));if(!(process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()===`true`)){let e;try{e=typeof t==`function`?bp():Wn(import.meta.url)(`cbor-extract`),e&&cf(e.extractStrings)}catch{}}const xp=`5.0.0-beta.9`,Sp=typeof process<`u`&&typeof process.env.DEBUG==`string`&&(process.env.DEBUG.includes(`workflow:`)||process.env.DEBUG===`*`);function Cp(e,t,n,r){Sp&&console.debug(`[workflow:world-vercel:http] ${e} ${t} -> ${n} (${r}ms)`)}const wp=()=>process.env.VERCEL_WORKFLOW_SERVER_URL||``;function Tp(e){return e}const Ep=()=>{let e=process.env.VERCEL_DEPLOYMENT_ID;return e?`@workflow/world-vercel/${xp} node-${process.version} ${Gn.platform()} (${Gn.arch()}) ${e}`:`@workflow/world-vercel/${xp} node-${process.version} ${Gn.platform()} (${Gn.arch()})`},Dp=e=>{let t=e?.projectConfig,n=wp()||`https://vercel-workflow.com`,r=process.env.WORKFLOW_VERCEL_BACKEND_URL,i=!!(t?.projectId&&t?.teamId);return{baseUrl:i?r||`https://api.vercel.com/v1/workflow`:`${n}/api`,usingProxy:i}},Op=(e,t)=>{let n=e?.projectConfig,r=new Headers(e?.headers);r.set(`User-Agent`,Ep()),n&&(r.set(`x-vercel-environment`,n.environment||`production`),n.projectId&&r.set(`x-vercel-project-id`,n.projectId),n.teamId&&r.set(`x-vercel-team-id`,n.teamId));let i=wp();return i&&t.usingProxy&&r.set(`x-vercel-workflow-api-url`,i),r};async function kp(e){let{baseUrl:t,usingProxy:n}=Dp(e),r=Op(e,{usingProxy:n});if(n){if(!e?.token)throw Error(`world-vercel: api-workflow proxy requested (${t}) but no Vercel auth token was provided. Pass one as \`config.token\` (the SDK reads it from \`WORKFLOW_VERCEL_AUTH_TOKEN\`).`);r.set(`Authorization`,`Bearer ${e.token}`)}else{let t;try{t=await(0,ws.getVercelOidcToken)()}catch{}let n=e?.token??t;n&&r.set(`Authorization`,`Bearer ${n}`),t&&r.set(`x-vercel-trusted-oidc-idp-token`,t)}return{baseUrl:t,headers:r,usingProxy:n}}async function Ap({endpoint:e,options:t={},config:n={},schema:r,data:i,onResponse:a}){let o=t.method||`GET`,{baseUrl:s,headers:c}=await kp(n),l=`${s}${e}`,u,d;try{let e=new URL(l);u=e.hostname,d=e.port?parseInt(e.port,10):e.protocol===`https:`?443:80}catch{}return Ps(`http ${o}`,{kind:await Fs(`CLIENT`)},async n=>{n?.setAttributes({...Ls(o),...Rs(l),...u&&zs(u),...d&&Bs(d),...Ws(`workflow-server`),...Gs(`http`),...Ks(`workflow-server`)}),c.set(`Accept`,`application/cbor`),c.set(`X-Request-Time`,Date.now().toString());let s;i!==void 0&&(c.set(`Content-Type`,`application/cbor`),s=lp(i));let f=AbortSignal.timeout(6e4),p=t.signal?AbortSignal.any([t.signal,f]):f,h=new Request(l,{...t,body:s,headers:c,signal:p}),g=Date.now(),_;try{_=await fetch(h,{dispatcher:Es()})}catch(t){let r=Date.now()-g;if(t instanceof Error&&(t.name===`TimeoutError`||t.name===`AbortError`)){let i=new O(`${o} ${e} timed out after ${r}ms`,{url:l,cause:t});throw n?.setAttributes({...Hs(`TIMEOUT`)}),n?.recordException?.(i),i}throw t}let v=Date.now()-g;if(Cp(o,e,_.status,v),n?.setAttributes({...Vs(_.status)}),!_.ok){let t=await Mp(_).then(e=>e.data).catch(()=>({}));if(process.env.DEBUG){let e=Array.from(c.entries()).filter(([e])=>e.toLowerCase()!==`authorization`).map(([e,t])=>`-H "${e}: ${t}"`).join(` `);console.error(`Failed to fetch, reproduce with:\ncurl -X ${h.method} ${e} "${l}"`)}let r,i=_.headers.get(`Retry-After`);if(i){let e=parseInt(i,10);Number.isNaN(e)||(r=e)}let a=t.message||`${h.method} ${e} -> HTTP ${_.status}: ${_.statusText}`,o=e=>{throw n?.setAttributes({...Hs(t.code||`HTTP ${_.status}`)}),n?.recordException?.(e),e};_.status===409&&o(new C(a)),_.status===410&&o(new m(a)),_.status===425&&o(new y(a,{retryAfter:r})),_.status===429&&o(new S(a,{retryAfter:r})),o(new O(a,{url:l,status:_.status,code:t.code,retryAfter:r}))}a?.(_);let b;try{b=await Ps(`world.parse`,async e=>{let t=await Mp(_),n=(_.headers.get(`Content-Type`)||``).includes(`application/cbor`);return e?.setAttributes({...Us(n?`cbor`:`json`)}),t})}catch(t){let n=_.headers.get(`Content-Type`)||`unknown`;throw new O(`Failed to parse response body for ${h.method} ${e} (Content-Type: ${n}):\n\n${t}`,{url:l,code:`PARSE_ERROR`,cause:t})}return await Ps(`world.validate`,async()=>{let t=r.safeParse(b.data);if(!t.success)throw new O(`Schema validation failed for ${o} ${e}:\n${t.error.issues.map(e=>` ${e.path.length>0?e.path.join(`.`):`<root>`}: ${e.message}`).join(`
139
+ `)}${process.env.DEBUG?`\n\nResponse context: ${b.getDebugContext()}`:``}`,{url:l,code:`SCHEMA_VALIDATION`,cause:t.error});return t.data})})}function jp(e){let t=xn(e,{depth:3,maxArrayLength:10,breakLength:120});return t.length>500?`${t.slice(0,500)}...`:t}async function Mp(e){let t=e.headers.get(`Content-Type`)||``;if(t.includes(`application/cbor`)){let n=await e.arrayBuffer(),r=Pf(new Uint8Array(n));return{data:r,getDebugContext:()=>`Content-Type: ${t}, ${n.byteLength} bytes (CBOR), preview: ${jp(r)}`}}let n=await e.text(),r=JSON.parse(n);return{data:r,getDebugContext:()=>`Content-Type: ${t}, ${n.length} bytes, preview: ${jp(r)}`}}var Np=class{contentType=`application/cbor`;serialize(e){return Buffer.from(lp(e))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}return Pf(Buffer.concat(t))}},Pp=class{contentType=`application/json`;serialize(e){return Buffer.from(JSON.stringify(e))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}return JSON.parse(Buffer.concat(t).toString())}},Fp=class{contentType=`application/cbor`;serialize(e){return Buffer.from(lp(e))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}let r=Buffer.concat(t);try{return Pf(r)}catch{return JSON.parse(r.toString())}}};const Ip=new wn,Lp=R({payload:M,queueName:be,deploymentId:de().optional()}),Rp=Number(process.env.VERCEL_QUEUE_MAX_DELAY_SECONDS||82800);function zp(e){let t=Math.min(Math.max(1,2**(e-1)),60),n=Math.floor(Math.random()*(Math.ceil(t*.25)+1));return Math.max(1,t-n)}function Bp(e){let t={};return`runId`in e&&typeof e.runId==`string`&&(t[`x-vercel-workflow-run-id`]=e.runId),`workflowRunId`in e&&typeof e.workflowRunId==`string`&&(t[`x-vercel-workflow-run-id`]=e.workflowRunId),`stepId`in e&&typeof e.stepId==`string`&&(t[`x-vercel-workflow-step-id`]=e.stepId),Object.keys(t).length>0?t:void 0}function Vp(e){let{baseUrl:t,usingProxy:n}=Dp(e),r=Op(e,{usingProxy:n}),i=new Np,a=new Pp,o=new Fp,s={region:`iad1`,dispatcher:Es(),transport:o,...n&&{resolveBaseUrl:()=>new URL(`${t}/queues-proxy`),token:e?.token},headers:Object.fromEntries(r.entries())},c=async(e,t,n)=>{let r=n?.deploymentId??process.env.VERCEL_DEPLOYMENT_ID;if(!r)throw Error(`No deploymentId provided and VERCEL_DEPLOYMENT_ID environment variable is not set. Queue messages require a deployment ID to route correctly. Either set VERCEL_DEPLOYMENT_ID or provide deploymentId in options.`);let o=(n?.specVersion??3)>=3?i:a,c=new jd({...s,deploymentId:r,transport:o}),l={payload:t,queueName:e,deploymentId:n?.deploymentId},u=e.replace(/[^A-Za-z0-9-_]/g,`-`);try{let{messageId:e}=await c.send(u,l,{idempotencyKey:n?.idempotencyKey,delaySeconds:n?.delaySeconds,headers:{...Bp(t),...n?.headers}});return{messageId:e?xe.parse(e):null}}catch(e){if(e instanceof nu)return{messageId:xe.parse(`msg_duplicate_${e.idempotencyKey??n?.idempotencyKey??`unknown`}`)};throw e}};return{queue:c,createQueueHandler:(e,t)=>{let n=new jd(s).handleCallback(async(e,n)=>{if(!e||!n)return;let r=Ip.getStore(),{payload:i,queueName:a,deploymentId:o}=Lp.parse(e),s=await t(i,{queueName:a,messageId:xe.parse(n.messageId),attempt:n.deliveryCount,requestId:r});typeof s?.timeoutSeconds==`number`&&await c(a,i,{deploymentId:o,delaySeconds:s.timeoutSeconds>0?Math.min(s.timeoutSeconds,Rp):void 0})},{retry:(e,{deliveryCount:t})=>({afterSeconds:zp(t)})});return async e=>{let t=e.headers.get(`x-vercel-id`)?.trim()||void 0;return Ip.run(t,()=>n(e))}},getDeploymentId:async()=>{let e=process.env.VERCEL_DEPLOYMENT_ID;if(!e)throw Error(`VERCEL_DEPLOYMENT_ID environment variable is not set`);return e}}}const Hp=R({id:de()});function Up(e){return async function(){let t=process.env.VERCEL_DEPLOYMENT_ID;if(!t)throw Error(`Cannot resolve latest deployment: VERCEL_DEPLOYMENT_ID environment variable is not set`);let n=e?.token??process.env.VERCEL_TOKEN??await(0,ws.getVercelOidcToken)().catch(()=>null);if(!n)throw Error(`Cannot resolve latest deployment: no OIDC token or VERCEL_TOKEN available`);let r=`https://api.vercel.com/v1/workflow/resolve-latest-deployment/${encodeURIComponent(t)}`,i=await fetch(r,{method:`GET`,headers:{Authorization:`Bearer ${n}`},dispatcher:Es()});if(!i.ok){let e;try{e=await i.text()}catch{e=`<unable to read response body>`}throw Error(`Failed to resolve latest deployment for ${t}: HTTP ${i.status} ${i.statusText}${e?` — ${e}`:``}`)}let a=await i.json(),o=Hp.safeParse(a);if(!o.success)throw Error(`Invalid response from Vercel API: expected { id: string }. Zod error: ${o.error.message}`);return o.data.id}}function Wp(e){return typeof e==`object`&&!!e&&`_type`in e&&`_ref`in e&&typeof e._ref==`string`&&e._type===`RemoteRef`}async function Gp(e,t,n){let r=e._ref;if(r.startsWith(`dbrf:`)){if(!e._data)throw Error(`Inline ref descriptor missing _data field: ${r}`);let t=e._ct??`application/cbor`,n=Buffer.from(e._data,`base64`);return t===`application/octet-stream`?n:Pf(n)}let{baseUrl:i,headers:a}=await kp(n),o=`${i}${`/v2/runs/${encodeURIComponent(t)}/refs?ref=${encodeURIComponent(r)}`}`;return a.set(`Accept`,`application/cbor, application/octet-stream`),a.set(`X-Request-Time`,Date.now().toString()),Ps(`http GET`,{kind:await Fs(`CLIENT`)},async e=>{e?.setAttributes({...Ls(`GET`),...Rs(o),...Ws(`workflow-server`)});let t=await fetch(o,{method:`GET`,headers:a,dispatcher:Es()});if(e?.setAttributes({...Vs(t.status)}),!t.ok){let n=new O(`Failed to resolve ref: HTTP ${t.status}`,{url:o,status:t.status});throw e?.setAttributes({...Hs(`HTTP ${t.status}`)}),e?.recordException?.(n),n}let n=t.headers.get(`content-type`)||``,r=await t.arrayBuffer();return n.includes(`application/octet-stream`)?new Uint8Array(r):Pf(new Uint8Array(r))})}async function Kp(e,t,n){if(e.length===0)return[];let r=n??10;return Ps(`world.refs.resolve`,async n=>{let i=e.filter(e=>e.descriptor._ref.startsWith(`dbrf:`)).length,a=e.length-i;if(n?.setAttributes({"workflow.refs.total_count":e.length,"workflow.refs.inline_count":i,"workflow.refs.remote_count":a,"workflow.refs.concurrency_limit":r}),e.length<=r)return Promise.all(e.map(e=>Gp(e.descriptor,e.runId,t)));let o=Array(e.length);for(let n=0;n<e.length;n+=r){let i=e.slice(n,n+r),a=await Promise.all(i.map(e=>Gp(e.descriptor,e.runId,t)));for(let e=0;e<a.length;e++)o[n+e]=a[e]}return o})}const qp=V.omit({error:!0,errorCode:!0}).extend({error:U([z,ue()]).optional(),errorCode:de().optional(),blobStorageBytes:Ee().optional(),streamStorageBytes:Ee().optional()}),Jp=qp,Yp=qp.omit({input:!0,output:!0}).extend({inputRef:ue().optional(),outputRef:ue().optional(),input:U([le(Uint8Array),ue()]).optional(),output:U([le(Uint8Array),ue()]).optional()});function Xp(e,t){if(t===`none`){let{inputRef:t,outputRef:n,...r}=e;return{...Tp(r),input:void 0,output:void 0}}return Tp(e)}async function Zp(e={},t){let{workflowName:n,status:r,pagination:i,resolveData:a=`all`}=e,o=new URLSearchParams;n&&o.set(`workflowName`,n),r&&o.set(`status`,r),i?.limit&&o.set(`limit`,i.limit.toString()),i?.cursor&&o.set(`cursor`,i.cursor),i?.sortOrder&&o.set(`sortOrder`,i.sortOrder);let s=a===`none`?`lazy`:`resolve`;o.set(`remoteRefBehavior`,s);let c=o.toString(),l=await Ap({endpoint:`/v2/runs${c?`?${c}`:``}`,options:{method:`GET`},config:t,schema:ke(s===`lazy`?Yp:Jp)});return{...l,data:l.data.map(e=>Xp(e,a))}}async function Qp(e,t){return Tp(await Ap({endpoint:`/v1/runs/create`,options:{method:`POST`},data:e,config:t,schema:Jp}))}async function $p(e,t,n){let r=t?.resolveData??`all`,i=r===`none`?`lazy`:`resolve`,a=new URLSearchParams;a.set(`remoteRefBehavior`,i);let o=a.toString(),s=`/v2/runs/${encodeURIComponent(e)}${o?`?${o}`:``}`;try{return Xp(await Ap({endpoint:s,options:{method:`GET`},config:n,schema:i===`lazy`?Yp:Jp}),r)}catch(t){throw t instanceof O&&t.status===404?new u(e):t}}async function em(e,t,n){let r=t?.resolveData??`all`,i=r===`none`?`lazy`:`resolve`,a=new URLSearchParams;a.set(`remoteRefBehavior`,i);let o=a.toString(),s=`/v1/runs/${encodeURIComponent(e)}/cancel${o?`?${o}`:``}`;try{return Xp(await Ap({endpoint:s,options:{method:`PUT`},config:n,schema:i===`lazy`?Yp:Jp}),r)}catch(t){throw t instanceof O&&t.status===404?new u(e):t}}const tm=R({attributes:fe(de(),de())});async function nm(e,t,n,r){try{return{attributes:(await Ap({endpoint:`/v2/runs/${encodeURIComponent(e)}/attributes`,options:{method:`POST`},data:n?.allowReservedAttributes?{changes:t,allowReservedAttributes:!0}:{changes:t},config:r,schema:tm})).attributes}}catch(t){throw t instanceof O&&t.status===404?new u(e):t}}const rm=Ae.omit({error:!0}).extend({error:U([z,ue()]).optional(),errorRef:ue().optional()}),im=rm.omit({input:!0,output:!0}).extend({inputRef:ue().optional(),outputRef:ue().optional(),input:le(Uint8Array).optional(),output:le(Uint8Array).optional()});function am(e){let{error:t,errorRef:n,...r}=e,i={...r},a=t??n;return a!=null&&(i.error=a),i}function om(e,t){if(t===`none`){let{inputRef:t,outputRef:n,...r}=e;return{...am(r),input:void 0,output:void 0}}return am(e)}async function sm(e,t){let{runId:n,pagination:r,resolveData:i=`all`}=e,a=new URLSearchParams;r?.cursor&&a.set(`cursor`,r.cursor),r?.limit&&a.set(`limit`,r.limit.toString()),r?.sortOrder&&a.set(`sortOrder`,r.sortOrder);let o=i===`none`?`lazy`:`resolve`;a.set(`remoteRefBehavior`,o);let s=a.toString(),c=await Ap({endpoint:`/v2/runs/${encodeURIComponent(n)}/steps${s?`?${s}`:``}`,options:{method:`GET`},config:t,schema:ke(o===`lazy`?im:rm)});return{...c,data:c.data.map(e=>om(e,i))}}async function cm(e,t,n,r){let i=n?.resolveData??`all`,a=i===`none`?`lazy`:`resolve`,o=new URLSearchParams;o.set(`remoteRefBehavior`,a);let s=o.toString();return om(await Ap({endpoint:`/v2/runs/${encodeURIComponent(e)}/steps/${encodeURIComponent(t)}${s?`?${s}`:``}`,options:{method:`GET`},config:r,schema:a===`lazy`?im:rm}),i)}function lm(e,t){if(t!==`none`)return e;let{eventDataRef:n,...r}=e;return L(r,t)}const um=H.object({event:B.optional(),run:F.optional(),step:rm.optional(),hook:ae.optional(),events:H.array(B).optional(),cursor:H.string().nullable().optional(),hasMore:H.boolean().optional()}),dm=H.object({event:B.optional(),run:qp.optional(),step:rm.optional(),hook:ae.optional(),events:H.array(B).optional(),cursor:H.string().nullable().optional(),hasMore:H.boolean().optional()}),fm=H.object({eventId:H.string(),runId:H.string(),eventType:te,correlationId:H.string().optional(),eventDataRef:H.any().optional(),eventData:H.any().optional(),createdAt:H.coerce.date(),specVersion:H.number().default(1)}),pm={run_created:`input`,run_completed:`output`,run_failed:`error`,step_created:`input`,step_completed:`result`,step_failed:`error`,step_retrying:`error`,hook_created:`metadata`,hook_received:`payload`},mm=new Set([`run_created`,`run_started`,`step_started`]);function hm(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.eventDataRef&&Wp(r.eventDataRef)&&t.push({eventIndex:n,refType:`entity`,descriptor:r.eventDataRef}),r.eventData&&typeof r.eventData==`object`){let e=pm[r.eventType];if(e){let i=r.eventData[e];Wp(i)&&t.push({eventIndex:n,refType:`nested`,fieldName:e,descriptor:i})}}}return t}async function gm(e,t,n){let r=hm(e);return r.length===0?e:Ps(`world.refs.hydrate`,async i=>{i?.setAttribute(`workflow.refs.hydrated_count`,r.length);let a=new Map;for(let t of r)if(!a.has(t.descriptor._ref)){let n=e[t.eventIndex].runId;a.set(t.descriptor._ref,{descriptor:t.descriptor,runId:n})}let o=await Kp(Array.from(a.values()),t,n).catch(t=>{let n=t instanceof Error?t.message:String(t);throw Error(`Failed to hydrate ${r.length} ref(s) across ${e.length} event(s): ${n}`)}),s=new Map,c=Array.from(a.keys());for(let e=0;e<c.length;e++)s.set(c[e],o[e]);let l=[...e];for(let t=0;t<r.length;t++){let{eventIndex:n,refType:i,fieldName:a,descriptor:o}=r[t],c=s.get(o._ref);l[n]===e[n]&&(l[n]={...e[n]});let u=l[n];i===`entity`?(u.eventData=c,delete u.eventDataRef):i===`nested`&&a&&(u.eventData===e[n].eventData&&(u.eventData={...u.eventData}),u.eventData[a]=c)}return l})}async function _m(e,t,n,r){let i=n?.resolveData??`all`,a=i===`none`?`lazy`:`resolve`,o=new URLSearchParams;o.set(`remoteRefBehavior`,a);let s=o.toString();return lm(await Ap({endpoint:`/v3/runs/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}${s?`?${s}`:``}`,options:{method:`GET`},config:r,schema:i===`none`?fm:B}),i)}async function vm(e,t){let n=new URLSearchParams,{pagination:r,resolveData:i=`all`}=e,a,o;if(`runId`in e?a=e.runId:o=e.correlationId,!a&&!o)throw Error(`Either runId or correlationId must be provided`);r?.limit&&n.set(`limit`,r.limit.toString()),r?.cursor&&n.set(`cursor`,r.cursor),r?.sortOrder&&n.set(`sortOrder`,r.sortOrder),o&&n.set(`correlationId`,o),n.set(`remoteRefBehavior`,`lazy`);let s=n.toString(),c=s?`?${s}`:``,l=o?`/v2/events${c}`:`/v3/runs/${encodeURIComponent(a)}/events${c}`,u,d=await Ap({endpoint:l,options:{method:`GET`},config:t,schema:ke(fm),onResponse:e=>{let t=e.headers.get(`x-ref-resolve-concurrency`);if(t){let e=parseInt(t,10);!Number.isNaN(e)&&e>0&&(u=e)}}});if(i===`all`){let e=await gm(d.data,t,u),n=0,r=e.map(e=>{let t=B.safeParse(e);return t.success||n++,t.success?t.data:e});return n>0&&console.warn(`[world-vercel] EventSchema coercion failed for ${n}/${e.length} events`),{...d,data:r}}return{...d,data:d.data.map(e=>lm(e,i))}}const ym=new Set([`hook_disposed`,`hook_received`]);async function bm(e,t,n,r){try{return await xm(e,t,n,r)}catch(e){throw ym.has(t.eventType)&&O.is(e)&&e.status===404&&t.correlationId?new x(t.correlationId):e}}async function xm(e,t,n,r){let i=n?.resolveData??`all`;if(n?.v1Compat??!1)return t.eventType===`run_cancelled`&&e?{run:await em(e,n,r)}:t.eventType===`run_created`?{run:await Qp(t.eventData,r)}:{event:await Ap({endpoint:`/v1/runs/${encodeURIComponent(e)}/events`,options:{method:`POST`},data:t,config:r,schema:B})};if(t.eventType===`run_created`&&e){let t=je(e,`wrun_`);if(t)throw new O(t,{status:400})}let a=e===null?`null`:encodeURIComponent(e),o=mm.has(t.eventType)?`resolve`:`lazy`;if(o===`resolve`){let e=await Ap({endpoint:`/v3/runs/${a}/events`,options:{method:`POST`},data:{...t,remoteRefBehavior:o,...n?.requestId?{vercelId:n.requestId}:{}},config:r,schema:um});return{event:e.event?lm(e.event,i):void 0,run:e.run,step:e.step?am(e.step):void 0,hook:e.hook,events:e.events,cursor:e.cursor,hasMore:e.hasMore}}let s=await Ap({endpoint:`/v3/runs/${a}/events`,options:{method:`POST`},data:{...t,remoteRefBehavior:o,...n?.requestId?{vercelId:n.requestId}:{}},config:r,schema:dm});return{event:s.event?lm(s.event,i):void 0,run:s.run?Tp(s.run):void 0,step:s.step?am(s.step):void 0,hook:s.hook,events:s.events,cursor:s.cursor,hasMore:s.hasMore}}function Sm(e,t){if(t===`none`){let{metadataRef:t,...n}=e;return n}return e}const Cm=ae.omit({metadata:!0}).extend({metadataRef:H.any().optional()});async function wm(e,t){let{runId:n,pagination:r,resolveData:i=`all`}=e,a=new URLSearchParams;r?.limit&&a.set(`limit`,r.limit.toString()),r?.cursor&&a.set(`cursor`,r.cursor),r?.sortOrder&&a.set(`sortOrder`,r.sortOrder);let o=i===`none`?`lazy`:`resolve`;a.set(`remoteRefBehavior`,o),n&&a.set(`runId`,n);let s=a.toString(),c=await Ap({endpoint:`/v2/hooks${s?`?${s}`:``}`,options:{method:`GET`},config:t,schema:ke(o===`lazy`?Cm:ae)});return{...c,data:c.data.map(e=>Sm(e,i))}}async function Tm(e,t,n){let r=t?.resolveData||`all`;return Sm(await Ap({endpoint:`/v2/hooks/${encodeURIComponent(e)}`,options:{method:`GET`},config:n,schema:ae}),r)}async function Em(e,t){try{return await Ap({endpoint:`/v2/hooks/by-token?token=${encodeURIComponent(e)}`,options:{method:`GET`},config:t,schema:ae})}catch(t){throw O.is(t)&&t.status===404?new x(e):t}}function Dm(e){let t={runs:{get:((t,n)=>$p(t,n,e)),list:(t=>Zp(t,e)),experimentalSetAttributes:(t,n,r)=>nm(t,n,r,e)},steps:{get:((t,n,r)=>cm(t,n,r,e)),list:(t=>sm(t,e))},events:{create:(t,n,r)=>bm(t,n,r,e),get:(t,n,r)=>_m(t,n,r,e),list:t=>vm(t,e),listByCorrelationId:t=>vm(t,e)},hooks:{get:(t,n)=>Tm(t,n,e),getByToken:t=>Em(t,e),list:t=>wm(t,e)}};return{runs:Xs(`world.runs`,t.runs),steps:Xs(`world.steps`,t.steps),events:Xs(`world.events`,t.events),hooks:Xs(`world.hooks`,t.hooks)}}const Om=1e3;function km(e,t,n){return new URL(`${n.baseUrl}/v2/runs/${encodeURIComponent(t)}/stream/${encodeURIComponent(e)}`)}function Am(e,t,n,r){let i=[`PUT ${t.origin}${t.pathname}`];for(let e of[`x-vercel-id`,`x-vercel-error`]){let t=n.headers.get(e);t&&i.push(`${e}=${t}`)}return Error(`Stream ${e} failed: HTTP ${n.status} (${i.join(`; `)}): ${r}`)}function jm(e){let t=new TextEncoder,n=[],r=0;for(let i of e){let e=typeof i==`string`?t.encode(i):i;n.push(e),r+=4+e.length}let i=new Uint8Array(r),a=new DataView(i.buffer),o=0;for(let e of n)a.setUint32(o,e.length,!1),o+=4,i.set(e,o),o+=e.length;return i}const Mm=R({tailIndex:Ee(),done:re()}),Nm=R({data:I(R({index:Ee(),data:le(Uint8Array)})),cursor:de().nullable(),hasMore:re(),done:re()});function Pm(e){return{streams:{async write(t,n,r){let i=await t,a=await kp(e),o=km(n,i,a),s=await fetch(o,{method:`PUT`,body:r,headers:a.headers}),c=await s.text();if(!s.ok)throw Am(`write`,o,s,c)},async writeMulti(t,n,r){if(r.length===0)return;let i=await t,a=await kp(e);a.headers.set(`X-Stream-Multi`,`true`);for(let e=0;e<r.length;e+=Om){let t=jm(r.slice(e,e+Om)),o=km(n,i,a),s=await fetch(o,{method:`PUT`,body:t,headers:a.headers}),c=await s.text();if(!s.ok)throw Am(`write`,o,s,c)}},async close(t,n){let r=await t,i=await kp(e);i.headers.set(`X-Stream-Done`,`true`);let a=km(n,r,i),o=await fetch(a,{method:`PUT`,headers:i.headers}),s=await o.text();if(!o.ok)throw Am(`close`,a,o,s)},async get(t,n,r){let i=await kp(e),a=km(n,t,i);typeof r==`number`&&a.searchParams.set(`startIndex`,String(r));let o=await fetch(a,{headers:i.headers});if(!o.ok)throw Error(`Failed to fetch stream: ${o.status}`);if(!o.body)throw Error(`No response body for stream`);return o.body},async getChunks(t,n,r){let i=new URLSearchParams;r?.limit!=null&&i.set(`limit`,String(r.limit)),r?.cursor&&i.set(`cursor`,r.cursor);let a=i.toString();return Ap({endpoint:`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(n)}/chunks${a?`?${a}`:``}`,config:e,schema:Nm})},async getInfo(t,n){return Ap({endpoint:`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(n)}/info`,config:e,schema:Mm})},async list(t){let n=await kp(e),r=new URL(`${n.baseUrl}/v2/runs/${encodeURIComponent(t)}/streams`),i=await fetch(r,{headers:n.headers});if(!i.ok)throw Error(`Failed to list streams: ${i.status}`);return await i.json()}}}}function Fm(e){let t=e?.projectConfig?.projectId||process.env.VERCEL_PROJECT_ID;return{specVersion:3,processExitTriggersQueueRedelivery:!0,...Vp(e),...Dm(e),...Xs(`world.streams`,Pm(e)),getEncryptionKeyForRun:ks(t,e?.projectConfig?.teamId,e?.token),resolveLatestDeploymentId:Up(e)}}function Im(){try{return vn(En(process.cwd()+`/package.json`).href)}catch{return vn(import.meta.url)}}const Lm=Symbol.for(`@workflow/world//cache`),Rm=Symbol.for(`@workflow/world//stubbedCache`),zm=Symbol.for(`@workflow/world//cachePromise`),Bm=Symbol.for(`@workflow/world//stubbedCachePromise`),Vm=globalThis;function Hm(e){if(e.startsWith(`file://`))return e;if(e.startsWith(`/`))return En(e).href;if(e.startsWith(`./`)||e.startsWith(`../`))return En(process.cwd()+`/`+e).href;try{return En(Im().resolve(e)).href}catch{return e}}const Um=async()=>{let e=a();if(o(e)){let e=[`WORKFLOW_VERCEL_PROJECT`,`WORKFLOW_VERCEL_TEAM`,`WORKFLOW_VERCEL_AUTH_TOKEN`,`WORKFLOW_VERCEL_ENV`].filter(e=>process.env[e]);return e.length>0&&process.env.VERCEL===`1`&&console.warn(`[workflow] Warning: ${e.join(`, `)} env var(s) are set but have no effect at runtime. These are only used by the Workflow CLI. Remove them from your Vercel project environment variables.`),Fm()}if(e===`local`)return hs({dataDir:process.env.WORKFLOW_LOCAL_DATA_DIR});let t;try{t=Im()(e)}catch{t=await import(Hm(e))}if(typeof t==`function`)return t();if(typeof t.default==`function`)return t.default();if(typeof t.createWorld==`function`)return t.createWorld();throw Error(`Invalid target world module: ${e}, must export a default function or createWorld function that returns a World instance.`)},Wm=async()=>{if(Vm[Rm])return Vm[Rm];Vm[Bm]||(Vm[Bm]=Um().catch(e=>{throw Vm[Bm]=void 0,e}));let e=await Vm[Bm];return Vm[Rm]=e,{createQueueHandler:e.createQueueHandler,specVersion:e.specVersion}},Gm=async()=>Vm[Lm]?Vm[Lm]:(Vm[zm]||(Vm[zm]=Um().catch(e=>{throw Vm[zm]=void 0,e})),Vm[Lm]=await Vm[zm],Vm[Lm]),Km=e=>{Vm[Lm]=e,Vm[Rm]=e,Vm[zm]=void 0,Vm[Bm]=void 0},qm=Symbol.for(`@workflow/world//getWorldFn`);globalThis[qm]??=Gm;var Jm=class{limitMs;elapsedMs=0;intervalStart;constructor(e=or()){this.limitMs=e,this.intervalStart=Date.now()}get configuredLimitMs(){return this.limitMs}elapsed(){let e=this.intervalStart===null?0:Date.now()-this.intervalStart;return this.elapsedMs+e}pause(){this.intervalStart!==null&&(this.elapsedMs+=Date.now()-this.intervalStart,this.intervalStart=null)}resume(){this.intervalStart=Date.now()}isExhausted(){return this.elapsed()>=this.limitMs}};async function Ym(e){let{runId:t,workflowName:n,requestId:r,attempt:i,limitMs:a}=e,o=W.forRun(t,n),s=await Gm();if(s.processExitTriggersQueueRedelivery!==!0){o.warn(`Workflow replay exceeded timeout; current World does not support process exit for redelivery — failing the run and returning`,{timeoutMs:a,attempt:i});try{let e=Wt(s,t),n=new _(`Workflow replay exceeded maximum duration (${a/1e3}s)`);await s.events.create(t,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(n,t,await e()),errorCode:d.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e)})}return}i<=3&&(o.warn(`Workflow replay exceeded timeout but will be re-attempted (attempt < maxRetries)`,{timeoutMs:a,attempt:i,maxRetries:3}),process.exit(1));let c=er(void 0,d.REPLAY_TIMEOUT);o.error(`Workflow replay exceeded timeout and max retries exceeded. Failing the run`,{timeoutMs:a,attempt:i,maxRetries:3,errorCode:c.errorCode,errorAttribution:c.attribution});try{let e=Wt(s,t),n=new _(`Workflow replay exceeded maximum duration (${a/1e3}s) after ${i} attempts`);await s.events.create(t,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(n,t,await e()),errorCode:d.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed. The queue will continue to retry`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}process.exit(1)}var Xm=ht();function Zm(e){return Cn.isNativeError(e)?e.name:`Error`}function Qm(e){return Cn.isNativeError(e)?e.stack??``:``}function $m(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`&&`message`in e&&typeof e.message==`string`&&(!(`stack`in e)||e.stack===void 0||typeof e.stack==`string`)}function eh(e){if(!$m(e)||_.is(e))return e;let t=new _(`Aborted: ${e.message}`);return e.stack&&(t.stack=e.stack),t}function th(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function nh(e){if(Cn.isNativeError(e))return{name:e.name,message:e.message,stack:e.stack??``};if(typeof e==`string`)return{name:`Error`,message:e,stack:``};try{return{name:`Error`,message:JSON.stringify(e),stack:``}}catch{return{name:`Error`,message:String(e),stack:``}}}async function rh(e){if(th(e))try{let t=await rh(await e);return{...t,message:`Promise rejection: ${t.message}`}}catch(e){let t=await rh(e);return{...t,message:`Promise rejection: ${t.message}`}}return nh(e)}let ih;async function ah(){if(!ih)try{let e=[`@workflow/utils`,`get-port`].join(`/`);ih=vn(En(process.cwd()+`/package.json`).href)(e).getPort}catch{ih=async()=>void 0}return ih()}async function oh(e){let{world:t,workflowRunId:n,workflowName:r,workflowStartedAt:a,stepId:o,stepName:c}=e,l=process.env.VERCEL_URL!==void 0;return _t(`STEP ${c}`,{},async u=>{u?.setAttributes({...At(c),...pt(r),...it(n),...Gt(o)});let d=Wt(t,n),f=gn(c);if(!f||typeof f!=`function`){let e=`Step "${c}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`;W.error(`Step function not registered, failing step`,{workflowRunId:n,stepName:c,stepId:o});try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(new _(e),n,await d())}})}catch(e){if(C.is(e))return{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Ot(!0)}),{type:`failed`}}let p=f.maxRetries??3;u?.setAttributes({...cn(p)});let h;try{let e=await t.events.create(n,{eventType:`step_started`,specVersion:3,correlationId:o,eventData:{stepName:c}});if(!e.step)throw new i(`step_started event for "${o}" did not return step entity`);h=e.step}catch(e){if(S.is(e)){let t=Math.max(1,typeof e.retryAfter==`number`?e.retryAfter:1);return W.info(`Throttled on step_started, deferring`,{retryAfterSeconds:t}),{type:`throttled`,timeoutSeconds:t}}if(m.is(e))return W.info(`Workflow run "${n}" has already completed, skipping step "${o}": ${e.message}`),{type:`gone`};if(C.is(e))return W.debug(`Step in terminal state, skipping`,{stepName:c,stepId:o,workflowRunId:n,error:e.message}),u?.setAttributes({...St(!0),...Ft(`completed`)}),{type:`skipped`};if(y.is(e)){let t=Math.max(1,e.retryAfter??1);return W.debug(`Step retryAfter timestamp not yet reached`,{stepName:c,stepId:o,timeoutSeconds:t}),{type:`retry`,timeoutSeconds:t}}throw e}W.debug(`Step execution details`,{stepName:c,stepId:h.stepId,status:h.status,attempt:h.attempt}),u?.setAttributes({...un(h.status)});let g;if(h.attempt>p+1&&h.error){let e=h.attempt-1,r=`Step "${c}" exceeded max retries (${e} ${s(`retry`,`retries`,e)})`;Ie.error(`Step exceeded max retries`,{workflowRunId:n,stepName:c,retryCount:e});let i=new _(r);if(h.error!=null)try{i.cause=await Be(h.error,n,await d())}catch{}try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(i,n,await d())}})}catch(e){if(C.is(e))return W.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Qt(!0)}),{type:`failed`}}try{let s=h.attempt;if(!h.startedAt)throw new i(`Step "${o}" has no "startedAt" timestamp`);let p=h.startedAt,m=[],_=e.encryptionKey??await d(),v=await _t(`step.hydrate`,{},async e=>{let t=Date.now(),r=await ft(h.input,n,_,m),i=Date.now()-t;return e?.setAttributes({...zt(r.args.length),...on(i)}),r}),y=v.args,b=v.thisVal??null,x=l?void 0:await ah(),S=Date.now();g=await _t(`step.execute`,{},async()=>await ct.run({stepMetadata:{stepName:c,stepId:o,stepStartedAt:new Date(+p),attempt:s},workflowMetadata:{workflowName:r,workflowRunId:n,workflowStartedAt:new Date(+a),url:l?`https://${process.env.VERCEL_URL}`:`http://localhost:${x??3e3}`,features:{encryption:!!_}},ops:m,closureVars:v.closureVars,encryptionKey:_},()=>f.apply(b,y)));let w=Date.now()-S;u?.setAttributes({...Jt(w)}),g=await _t(`step.dehydrate`,{},async e=>{let t=Date.now(),r=await ln(g,n,_,m),i=Date.now()-t;return e?.setAttributes({...tn(i),...Nt(typeof r)}),r});let T=!0;if(m.length>0){let e=Promise.all(m).catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))throw e});(0,Xm.waitUntil)(e),T=await Promise.race([e.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),500))])}let E=!1;return await t.events.create(n,{eventType:`step_completed`,specVersion:3,correlationId:o,eventData:{stepName:c,result:g}}).catch(e=>{if(C.is(e)){W.info(`Tried completing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),E=!0;return}throw e}),E?{type:`skipped`}:(u?.setAttributes({...un(`completed`),...Nt(typeof g)}),m.length>0&&Ie.debug(`Step has pending ops`,{workflowRunId:n,stepName:c,opsCount:m.length}),{type:`completed`,hasPendingOps:!T})}catch(e){let r=eh(e),i=await rh(r),a=i.stack||Qm(r)||``;r instanceof Error&&u?.recordException?.(r);let l=_.is(r);if(u?.setAttributes({...rn(Zm(r)),...Xt(i.message),...vt(Zm(r)),...Ye(l?`fatal`:w.is(r)?`retryable`:`transient`),...yt(!l)}),m.is(e))return Ie.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};if(l){Ie.error(`Encountered FatalError while executing step, bubbling up to parent workflow`,{workflowRunId:n,stepName:c,errorStack:a}),Cn.isNativeError(r)&&a&&(r.stack=a);try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(r,n,await d())}})}catch(e){if(C.is(e))return W.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Ot(!0)}),{type:`failed`}}let f=h.attempt;if(u?.setAttributes({...wt(f),...cn(p)}),f>=p+1){let r=h.attempt-1;Ie.error(`Max retries reached, bubbling error to parent workflow`,{workflowRunId:n,stepName:c,attempt:h.attempt,retryCount:r,errorStack:a});let l=new _(`Step "${c}" failed after ${p} ${s(`retry`,`retries`,p)}: ${i.message}`);l.cause=e,a&&(l.stack=a);try{await t.events.create(n,{eventType:`step_failed`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(l,n,await d())}})}catch(e){if(C.is(e))return W.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}return u?.setAttributes({...un(`failed`),...Qt(!0)}),{type:`failed`}}w.is(e)?Ie.info(`Encountered RetryableError, step will be retried`,{workflowRunId:n,stepName:c,attempt:f,message:e.message}):Ie.info(`Encountered Error, step will be retried`,{workflowRunId:n,stepName:c,attempt:f,errorStack:a}),Cn.isNativeError(e)&&a&&(e.stack=a);try{await t.events.create(n,{eventType:`step_retrying`,specVersion:3,correlationId:o,eventData:{stepName:c,error:await xt(e,n,await d()),...w.is(e)&&{retryAfter:e.retryAfter}}})}catch(e){if(C.is(e))return W.info(`Tried retrying step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:c,message:e.message}),{type:`skipped`};throw e}let g=Math.max(1,w.is(e)?Math.ceil((+e.retryAfter.getTime()-Date.now())/1e3):1);return u?.setAttributes({...Kt(g),...Lt(!0)}),{type:`retry`,timeoutSeconds:g}}})}async function sh({suspension:e,world:t,run:n,span:r,requestId:i}){let a=n.runId,o=e.steps.filter(e=>e.type===`step`),s=e.steps.filter(e=>e.type===`hook`),c=e.steps.filter(e=>e.type===`wait`),l=s.filter(e=>!e.hasCreatedEvent),u=s.filter(e=>e.disposed),d=await t.getEncryptionKeyForRun?.(n),f=d?await Ke(d):void 0,p=await Promise.all(l.map(async t=>{let n=t.metadata===void 0?void 0:await Pt(t.metadata,a,f,e.globalThis);return{eventType:`hook_created`,specVersion:3,correlationId:t.correlationId,eventData:{token:t.token,metadata:n,isWebhook:t.isWebhook??!1,...t.isSystem&&{isSystem:!0}}}})),h=!1;p.length>0&&await Promise.all(p.map(async e=>{try{(await t.events.create(a,e,{requestId:i})).event.eventType===`hook_conflict`&&(h=!0)}catch(e){if(C.is(e)||m.is(e))W.info(`Workflow run already completed, skipping hook`,{workflowRunId:a,message:e.message});else throw e}})),u.length>0&&await Promise.all(u.map(async e=>{let n={eventType:`hook_disposed`,specVersion:3,correlationId:e.correlationId,eventData:{token:e.token}};try{await t.events.create(a,n,{requestId:i})}catch(t){if(C.is(t))W.info(`Hook already disposed, skipping duplicate disposal`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else if(m.is(t))W.info(`Workflow run already completed, skipping hook disposal`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else if(x.is(t))W.info(`Hook not found for disposal, continuing`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else throw t}}));let g=s.filter(e=>e.abortRequested&&!e.disposed);g.length>0&&await Promise.all(g.map(async n=>{try{let r=await Pt({aborted:!0,reason:n.abortReason},a,f,e.globalThis);await t.events.create(a,{eventType:`hook_received`,specVersion:3,correlationId:n.correlationId,eventData:{token:n.token,payload:r}});try{let e=He(n.token);await t.streams.write(a,e,r),await t.streams.close(a,e)}catch{W.debug(`Failed to write abort stream packet, hook event will provide fallback`,{workflowRunId:a,correlationId:n.correlationId})}}catch(e){if(C.is(e)||m.is(e))W.info(`Workflow run already completed, skipping abort`,{workflowRunId:a,correlationId:n.correlationId,message:e.message});else throw e}}));let _=new Set(o.filter(e=>!e.hasCreatedEvent).map(e=>e.correlationId)),v=new Set,y=[];for(let n of o)_.has(n.correlationId)&&y.push((async()=>{let r=await Pt({args:n.args,closureVars:n.closureVars,thisVal:n.thisVal},a,f,e.globalThis),o={eventType:`step_created`,specVersion:3,correlationId:n.correlationId,eventData:{stepName:n.stepName,input:r}};try{await t.events.create(a,o,{requestId:i}),v.add(n.correlationId)}catch(e){if(C.is(e))W.info(`Step already exists, continuing`,{workflowRunId:a,correlationId:n.correlationId,message:e.message});else throw e}})());for(let e of c)e.hasCreatedEvent||y.push((async()=>{let n={eventType:`wait_created`,specVersion:3,correlationId:e.correlationId,eventData:{resumeAt:e.resumeAt}};try{await t.events.create(a,n,{requestId:i})}catch(t){if(C.is(t))W.info(`Wait already exists, continuing`,{workflowRunId:a,correlationId:e.correlationId,message:t.message});else throw t}})());(0,Xm.waitUntil)(Promise.all(y).catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))throw e})),await Promise.all(y);let b=Date.now(),S=c.reduce((e,t)=>{let n=t.resumeAt.getTime(),r=Math.max(1e3,n-b),i=Math.ceil(r/1e3);return e===null?i:Math.min(e,i)},null);return r?.setAttributes({...Ut(`workflow_suspended`),...Vt(o.length),...fn(l.length),...nt(c.length)}),{pendingSteps:o,createdStepCorrelationIds:v,timeoutSeconds:h?0:S??void 0,hasHookConflict:h}}var ch=44,lh=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,uh=new Uint8Array(64),dh=new Uint8Array(128);for(let e=0;e<lh.length;e++){let t=lh.charCodeAt(e);uh[e]=t,dh[t]=e}function fh(e,t){let n=0,r=0,i=0;do i=dh[e.next()],n|=(i&31)<<r,r+=5;while(i&32);let a=n&1;return n>>>=1,a&&(n=-2147483648|-n),t+n}function ph(e,t){return e.pos>=t?!1:e.peek()!==ch}var mh=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}};function hh(e){let{length:t}=e,n=new mh(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i=fh(n,i),i<u&&(l=!1),u=i,ph(n,e)?(a=fh(n,a),o=fh(n,o),s=fh(n,s),ph(n,e)?(c=fh(n,c),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||gh(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function gh(e){e.sort(_h)}function _h(e,t){return e[0]-t[0]}const vh=/^[\w+.-]+:\/\//,yh=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,bh=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function xh(e){return vh.test(e)}function Sh(e){return e.startsWith(`//`)}function Ch(e){return e.startsWith(`/`)}function wh(e){return e.startsWith(`file:`)}function Th(e){return/^[.?#]/.test(e)}function Eh(e){let t=yh.exec(e);return Oh(t[1],t[2]||``,t[3],t[4]||``,t[5]||`/`,t[6]||``,t[7]||``)}function Dh(e){let t=bh.exec(e),n=t[2];return Oh(`file:`,``,t[1]||``,``,Ch(n)?n:`/`+n,t[3]||``,t[4]||``)}function Oh(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function kh(e){if(Sh(e)){let t=Eh(`http:`+e);return t.scheme=``,t.type=6,t}if(Ch(e)){let t=Eh(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(wh(e))return Dh(e);if(xh(e))return Eh(e);let t=Eh(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function Ah(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function jh(e,t){Mh(t,t.type),e.path===`/`?e.path=t.path:e.path=Ah(t.path)+e.path}function Mh(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];if(!t){o=!0;continue}if(o=!1,t!==`.`){if(t===`..`){a?(o=!0,a--,i--):n&&(r[i++]=t);continue}r[i++]=t,a++}}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function Nh(e,t){if(!e&&!t)return``;let n=kh(e),r=n.type;if(t&&r!==7){let e=kh(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:jh(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}Mh(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?Th(t||e)&&!Th(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}function Ph(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Fh(e,t){let n=Ph(e),r=t?t+`/`:``;return e=>Nh(r+(e||``),n)}var Ih=0,Lh=1,Rh=2,zh=3,Bh=4;function Vh(e,t){let n=Hh(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=Hh(e,r+1))e[r]=Wh(e[r],t);return e}function Hh(e,t){for(let n=t;n<e.length;n++)if(!Uh(e[n]))return n;return e.length}function Uh(e){for(let t=1;t<e.length;t++)if(e[t][Ih]<e[t-1][Ih])return!1;return!0}function Wh(e,t){return t||(e=e.slice()),e.sort(Gh)}function Gh(e,t){return e[Ih]-t[Ih]}var Kh=!1;function qh(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][Ih]-t;if(a===0)return Kh=!0,i;a<0?n=i+1:r=i-1}return Kh=!1,n-1}function Jh(e,t,n){for(let r=n+1;r<e.length&&e[r][Ih]===t;n=r++);return n}function Yh(e,t,n){for(let r=n-1;r>=0&&e[r][Ih]===t;n=r--);return n}function Xh(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function Zh(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return Kh=o!==-1&&e[o][Ih]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=qh(e,t,s,c)}function Qh(e){return typeof e==`string`?JSON.parse(e):e}var $h="`line` must be greater than 0 (lines start at line 1)",eg="`column` must be greater than or equal to 0 (columns start at column 0)",tg=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=Qh(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=Fh(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=Vh(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=Xh(),this._bySources=void 0,this._bySourceMemos=void 0}};function ng(e){return e}function rg(e){var t;return(t=ng(e))._decoded||(t._decoded=hh(ng(e)._encoded))}function ig(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error($h);if(r<0)throw Error(eg);let a=rg(e);if(n>=a.length)return ag(null,null,null,null);let o=a[n],s=og(o,ng(e)._decodedMemo,n,r,i||1);if(s===-1)return ag(null,null,null,null);let c=o[s];if(c.length===1)return ag(null,null,null,null);let{names:l,resolvedSources:u}=e;return ag(u[c[Lh]],c[Rh]+1,c[zh],c.length===5?l[c[Bh]]:null)}function ag(e,t,n,r){return{source:e,line:t,column:n,name:r}}function og(e,t,n,r,i){let a=Zh(e,r,t,n);return Kh?a=(i===-1?Jh:Yh)(e,r,a):i===-1&&a++,a===-1||a===e.length?-1:a}function sg(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===61}function cg(e){let t=0;for(;t<e.length;){let n=e.indexOf(`//# sourceMappingURL=data:application/json`,t);if(n===-1)return;let r=e.indexOf(`;base64,`,n+42);if(r===-1){t=n+42;continue}let i=e.indexOf(`,`,n);if(i!==-1&&i<r){t=r+8;continue}let a=r+8,o=a;for(;o<e.length&&sg(e.charCodeAt(o));)o++;if(o>a)return e.slice(a,o);t=o}}function lg(e,t,n){let r=cg(n);if(!r)return e;try{let n=Buffer.from(r,`base64`).toString(`utf-8`),i=new tg(JSON.parse(n));return e.split(`
140
+ `).map(e=>{let n=e.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);if(!n)return e;let[,r,a,o,s]=n;if(!a.includes(t))return e;let c=parseInt(o,10),l=parseInt(s,10),u=ig(i,{line:c,column:l});if(u.source&&u.line!==null){let e=r||u.name||`anonymous`,t=u.column===null?l:u.column;return` at ${e} (${u.source}:${u.line}:${t})`}return e}).join(`
141
+ `)}catch{return e}}function ug(e,t,n){let r=(2<<31-Math.clz32(e.length-1|1))-1,i=Math.ceil(1.6*r*t/e.length);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(o+=e[t[s]&r]||``,o.length>=a)return o}}}function dg(e){return function(t,n){let i=function(...i){let{promise:a,resolve:o,reject:s}=r(),c=`step_${e.generateUlid()}`,l={type:`step`,correlationId:c,stepName:t,args:i};this!==void 0&&this!==null&&this!==globalThis&&(l.thisVal=this);let u=n?.();return u&&(l.closureVars=u),e.invocationsQueue.set(c,l),Ie.debug(`Step consumer setup`,{correlationId:c,stepName:t,args:i}),e.eventsConsumer.subscribe(n=>{if(!n)return _n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),$e.NotConsumed;if(Ie.debug(`Step consumer event processing`,{correlationId:c,stepName:t,args:i.join(`, `),incomingCorrelationId:n.correlationId,isMatch:c===n.correlationId,eventType:n.eventType}),n.correlationId!==c)return $e.NotConsumed;let r=`eventData`in n&&n.eventData&&`stepName`in n.eventData?n.eventData.stepName:void 0;if(typeof r==`string`&&r!==t)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Corrupted event log: step event ${n.eventType} for ${c} belongs to "${r}", but the current step consumer is "${t}"`))}),$e.Finished;if(n.eventType===`step_created`){let n=e.invocationsQueue.get(c);return!n||n.type!==`step`?(e.promiseQueue=e.promiseQueue.then(()=>{s(new T(`Corrupted event log: step ${c} (${t}) created but not found in invocation queue`))}),$e.Finished):(n.hasCreatedEvent=!0,$e.Consumed)}return n.eventType===`step_started`||n.eventType===`step_retrying`?$e.Consumed:n.eventType===`step_failed`?(e.invocationsQueue.delete(n.correlationId),e.promiseQueue=e.promiseQueue.then(async()=>{try{s(await Be(n.eventData.error,e.runId,e.encryptionKey,e.globalThis))}catch(e){Ie.error(`Failed to hydrate step_failed error`,{correlationId:n.correlationId,error:e instanceof Error?e.message:String(e)}),s(new _(`Failed to hydrate step error: ${e instanceof Error?e.message:String(e)}`))}}),$e.Finished):n.eventType===`step_completed`?(e.invocationsQueue.delete(n.correlationId),e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{o(await Re(n.eventData.result,e.runId,e.encryptionKey,e.globalThis))}catch(e){s(e)}finally{e.pendingDeliveries--}}),$e.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Unexpected event type for step ${c} (name: ${t}) "${n.eventType}"`))}),$e.Finished)}),a},a=t.split(`//`).pop();return Object.defineProperty(i,"name",{value:a}),Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"bind",{value:function(e,...r){let i=Function.prototype.bind.call(this,e,...r);return Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"__boundThis",{value:e,writable:!1,enumerable:!1,configurable:!1}),r.length>0&&Object.defineProperty(i,"__boundArgs",{value:r,writable:!1,enumerable:!1,configurable:!1}),i},writable:!1,enumerable:!1,configurable:!1}),i}}var fg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*23283064365386963e-26;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=e|0)},t.c=1,t.s0=n(` `),t.s1=n(` `),t.s2=n(` `),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return n.next()*4294967296|0},o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}function o(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=r*4294967296}return(e>>>0)*23283064365386963e-26}}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),pg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),mg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),hg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r=e[n],i;return r^=r>>>7,i=r^r<<24,r=e[n+1&7],i^=r^r>>>10,r=e[n+3&7],i^=r^r>>>3,r=e[n+4&7],i^=r^r<<7,r=e[n+7&7],r^=r<<13,i^=r^r<<9,e[n]=i,t.i=n+1&7,i};function n(e,t){var n,r=[];if(t===(t|0))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}n(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),gg=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,i,a;return t.w=e=e+1640531527|0,a=n[r+34&127],i=n[r=r+1&127],a^=a<<13,i^=i<<17,a^=a>>>15,i^=i>>>12,a=n[r]=a^i,t.i=r,a+(e^e>>>16)|0};function n(e,t){var n,r,i,a,o,s=[],c=128;for(t===(t|0)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,n=s[a&127]^=r+o,i=n==0?i+1:0);for(i>=128&&(s[(t&&t.length||0)&127]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}n(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),_g=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=e|0):n+=e;for(var r=0;r<n.length+20;r++)t.b^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),vg=n(((e,n)=>{(function(e,r,i){var a=256,o=6,s=52,c=`random`,l=i.pow(a,o),u=i.pow(2,s),d=u*2,f=a-1,p;function m(e,t,n){var s=[];t=t==1?{entropy:!0}:t||{};var f=v(_(t.entropy?[e,b(r)]:e??y(),3),s),p=new h(s),m=function(){for(var e=p.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=p.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return m.int32=function(){return p.g(4)|0},m.quick=function(){return p.g(4)/4294967296},m.double=m,v(b(p.S),r),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,p),e.state=function(){return g(p,{})}),n?(i[c]=e,t):e})(m,f,`global`in t?t.global:this==i,t.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function _(e,t){var n=[],r=typeof e,i;if(t&&r==`object`)for(i in e)try{n.push(_(e[i],t-1))}catch{}return n.length?n:r==`string`?e:e+`\0`}function v(e,t){for(var n=e+``,r,i=0;i<n.length;)t[f&i]=f&(r^=t[f&i]*19)+n.charCodeAt(i++);return b(t)}function y(){try{var t;return p&&(t=p.randomBytes)?t=t(a):(t=new Uint8Array(a),(e.crypto||e.msCrypto).getRandomValues(t)),b(t)}catch{var n=e.navigator,i=n&&n.plugins;return[+new Date,e,i,e.screen,b(r)]}}function b(e){return String.fromCharCode.apply(0,e)}if(v(i.random(),r),typeof n==`object`&&n.exports){n.exports=m;try{p=t(`crypto`)}catch{}}else typeof define==`function`&&define.amd?define(function(){return m}):i[`seed`+c]=m})(typeof self<`u`?self:e,[],Math)})),yg=e(n(((e,t)=>{var n=fg(),r=pg(),i=mg(),a=hg(),o=gg(),s=_g(),c=vg();c.alea=n,c.xor128=r,c.xorwow=i,c.xorshift7=a,c.xor4096=o,c.tychei=s,t.exports=c}))(),1);const bg=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,xg=new Uint8Array(128).fill(255);for(let e=0;e<64;e++)xg[bg.charCodeAt(e)]=e;function Sg(e){return e===9||e===10||e===12||e===13||e===32}function Cg(e,t){for(;t<e.length&&Sg(e.charCodeAt(t));)t++;return t}function wg(e,t){let n=e.length,r=e;n===2?r=e+`AA`:n===3&&(r=e+`A`);let i=xg[r.charCodeAt(0)],a=xg[r.charCodeAt(1)],o=xg[r.charCodeAt(2)],s=xg[r.charCodeAt(3)],c=i<<2|a>>4,l=(a&15)<<4|o>>2,u=(o&3)<<6|s;if(n===2){if(t&&l!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c]}if(n===3){if(t&&u!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c,l]}return[c,l,u]}function Tg(e,t,n,r){if(r===void 0&&(r=2**53-1),r===0)return{read:0,bytes:[],error:null};let i=0,a=[],o=``,s=0,c=0,l=e.length;for(;;){if(c=Cg(e,c),c===l){if(s>0){if(n===`stop-before-partial`)return{read:i,bytes:a,error:null};if(n===`loose`){if(s===1)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: lone character in final chunk`)};a.push(...wg(o,!1))}else return{read:i,bytes:a,error:SyntaxError(`Invalid base64: incomplete chunk in strict mode`)}}return{read:l,bytes:a,error:null}}let u=e[c];if(c++,u===`=`){if(s<2)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: padding in unexpected place`)};if(c=Cg(e,c),s===2){if(c===l)return n===`stop-before-partial`?{read:i,bytes:a,error:null}:{read:i,bytes:a,error:SyntaxError(`Invalid base64: missing second padding character`)};u=e[c],u===`=`&&(c=Cg(e,c+1))}if(c<l)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected characters after padding`)};let t=n===`strict`;try{a.push(...wg(o,t))}catch(e){return{read:i,bytes:a,error:e}}return{read:l,bytes:a,error:null}}if(t===`base64url`){if(u===`+`||u===`/`)return{read:i,bytes:a,error:SyntaxError(`Invalid base64url: unexpected character '${u}'`)};u===`-`?u=`+`:u===`_`&&(u=`/`)}let d=u.charCodeAt(0);if(d>=128||xg[d]===255)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected character '${e[c-1]}'`)};let f=r-a.length;if(f===1&&s===2||f===2&&s===3||(o+=u,s=o.length,s===4&&(a.push(...wg(o)),o=``,s=0,i=c,a.length===r)))return{read:i,bytes:a,error:null}}}function Eg(e,t){t===void 0&&(t=2**53-1);let n=e.length,r=[],i=0;if(n%2!=0)return{read:0,bytes:[],error:SyntaxError(`Invalid hex: string length must be even`)};for(;i<n&&r.length<t;){let t=e.substring(i,i+2);if(!/^[0-9a-fA-F]{2}$/.test(t))return{read:i,bytes:r,error:SyntaxError(`Invalid hex: unexpected character at position ${i}`)};i+=2,r.push(Number.parseInt(t,16))}return{read:i,bytes:r,error:null}}function Dg(e,t){let n=t?.alphabet??`base64`;if(n!==`base64`&&n!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${n}"`);let r=!!t?.omitPadding,i=``,a=e.length;for(let t=0;t<a;t+=3){let n=e[t],o=t+1<a?e[t+1]:0,s=t+2<a?e[t+2]:0;i+=bg[n>>2&63],i+=bg[(n&3)<<4|o>>4&15],t+1<a?i+=bg[(o&15)<<2|s>>6&3]:r||(i+=`=`),t+2<a?i+=bg[s&63]:r||(i+=`=`)}return n===`base64url`&&(i=i.replace(/\+/g,`-`).replace(/\//g,`_`)),i}function Og(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function kg(e){let t=e.prototype,n=e;t.toBase64||Object.defineProperty(t,"toBase64",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Dg(this,t)},writable:!0,enumerable:!1,configurable:!0}),t.toHex||Object.defineProperty(t,"toHex",{value:function(){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Og(this)},writable:!0,enumerable:!1,configurable:!0}),t.setFromBase64||Object.defineProperty(t,"setFromBase64",{value:function(t,n){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=Tg(t,r,i,this.length),o=a.bytes,s=o.length;for(let e=0;e<s;e++)this[e]=o[e];if(a.error)throw a.error;return{read:a.read,written:s}},writable:!0,enumerable:!1,configurable:!0}),t.setFromHex||Object.defineProperty(t,"setFromHex",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Eg(t,this.length),r=n.bytes,i=r.length;for(let e=0;e<i;e++)this[e]=r[e];if(n.error)throw n.error;return{read:n.read,written:i}},writable:!0,enumerable:!1,configurable:!0}),n.fromBase64||Object.defineProperty(e,"fromBase64",{value:function(t,n){if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=Tg(t,r,i);if(a.error)throw a.error;return new e(a.bytes)},writable:!0,enumerable:!1,configurable:!0}),n.fromHex||Object.defineProperty(e,"fromHex",{value:function(t){if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Eg(t);if(n.error)throw n.error;return new e(n.bytes)},writable:!0,enumerable:!1,configurable:!0})}function Ag(e){return function(){let t=`0123456789abcdef`,n=``;for(let r=0;r<36;r++)r===8||r===13||r===18||r===23?n+=`-`:r===14?n+=`4`:r===19?n+=t[Math.floor(e()*4)+8]:n+=t[Math.floor(e()*16)];return n}}function jg(e){let{fixedTimestamp:t}=e,{seed:n}=e,r=(0,yg.default)(n),a=Kn(),o=qn(`globalThis`,a);o.Math.random=r;let s=o.Date;o.Date=function(...e){return e.length===0?new s(t):new s(...e)},o.Date.prototype=s.prototype,Object.setPrototypeOf(o.Date,s),o.Date.now=()=>t;let c=globalThis.crypto,l=c.subtle;function u(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(r()*256);return e}let d=Ag(r),f=l.digest.bind(l);return o.crypto=new Proxy(c,{get(e,t){return t===`getRandomValues`?u:t===`randomUUID`?d:t===`subtle`?new Proxy(l,{get(e,t){return t===`generateKey`?()=>{throw new i("`crypto.subtle.generateKey()` is not available inside a workflow function. Move key generation to a step function where full Node.js crypto is available.")}:t===`digest`?f:e[t]}}):e[t]}}),o.process={env:Object.freeze({...process.env})},o.DOMException=globalThis.DOMException,o.Headers=globalThis.Headers,o.TextEncoder=globalThis.TextEncoder,o.TextDecoder=globalThis.TextDecoder,o.console=globalThis.console,o.URL=globalThis.URL,o.URLSearchParams=globalThis.URLSearchParams,o.structuredClone=globalThis.structuredClone,o.atob=globalThis.atob,o.btoa=globalThis.btoa,kg(o.Uint8Array),o.Symbol.dispose??=Symbol.for(`Symbol.dispose`),o.Symbol.asyncDispose??=Symbol.for(`Symbol.asyncDispose`),o.exports={},o.module={exports:o.exports},{context:a,globalThis:o,updateTimestamp:e=>{t=e}}}function Mg(e){return function(t={}){let n=`hook_${e.generateUlid()}`,i=t.token??e.generateNanoid(),a=t.isWebhook??!1;e.invocationsQueue.set(n,{type:`hook`,correlationId:n,token:i,metadata:t.metadata,isWebhook:a});let o=[],s=[],c=!1,l=!1,u=!1,d=null;gt.debug(`Hook consumer setup`,{correlationId:n,token:i}),e.eventsConsumer.subscribe(t=>{if(!t)return c=!0,s.length>0&&o.length===0&&_n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),$e.NotConsumed;if(t.correlationId!==n)return $e.NotConsumed;let r=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof r==`string`&&r!==i)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Corrupted event log: hook event ${t.eventType} for ${n} belongs to token "${r}", but the current hook consumer expects "${i}"`))}),$e.Finished;if(t.eventType===`hook_created`){let t=e.invocationsQueue.get(n);return t&&t.type===`hook`&&(t.hasCreatedEvent=!0),$e.Consumed}if(t.eventType===`hook_conflict`){e.invocationsQueue.delete(n);let r=t,i=new f(r.eventData.token,r.eventData.conflictingRunId);u=!0,d=i;let a=s.slice();return s.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of a)e.reject(i)}),$e.Consumed}if(t.eventType===`hook_received`){if(s.length>0){let n=s.shift();n&&(e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await Re(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis);n.resolve(r)}catch(e){n.reject(e)}finally{e.pendingDeliveries--}}))}else o.push(t);return $e.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(n),l=!0,$e.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Unexpected event type for hook ${n} (token: ${i}) "${t.eventType}"`))}),$e.Finished)});let p=!1;function m(){let t=r();if(u&&d)return e.promiseQueue=e.promiseQueue.then(()=>{t.reject(d)}),t.promise;if(o.length>0){let n=o.shift();if(n)return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await Re(n.eventData.payload,e.runId,e.encryptionKey,e.globalThis);t.resolve(r)}catch(e){t.reject(e)}finally{e.pendingDeliveries--}}),t.promise}return c&&_n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),s.push(t),t.promise}function h(){if(p||(p=!0,l))return;let t=e.invocationsQueue.get(n);t&&t.type===`hook`&&(t.disposed=!0),s.length>0&&(s.length=0,_n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))})),gt.debug(`Hook disposed`,{correlationId:n,token:i})}let g={token:i,then(e,t){return m().then(e,t)},async*[Symbol.asyncIterator](){for(;!p;)yield await this},dispose:h,[Symbol.dispose]:h},_=e.globalThis.Symbol.dispose;return _&&_!==Symbol.dispose&&(g[_]=h),g}}function Ng(e){return async function(t){let{promise:n,resolve:i}=r(),a=`wait_${e.generateUlid()}`,o=c(t),s={type:`wait`,correlationId:a,resumeAt:o};return e.invocationsQueue.set(a,s),e.eventsConsumer.subscribe(t=>{if(!t)return _n(e,()=>{e.onWorkflowError(new Ue(e.invocationsQueue,e.globalThis))}),$e.NotConsumed;if(t.correlationId!==a)return $e.NotConsumed;if(t.eventType===`wait_created`){let n=e.invocationsQueue.get(a);return n&&n.type===`wait`&&(n.hasCreatedEvent=!0,n.resumeAt=t.eventData.resumeAt),$e.Consumed}if(t.eventType===`wait_completed`){let n=t.eventData?.resumeAt;if(n!==void 0){let t=e.invocationsQueue.get(a),r=t&&t.type===`wait`?t.resumeAt:o,i=new Date(n),s=i.getTime(),c=r.getTime(),l=Number.isFinite(s)?i.toISOString():String(n);if(s!==c)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Corrupted event log: wait_completed event for ${a} has resumeAt "${l}", but the current wait consumer expects "${r.toISOString()}"`))}),$e.Finished}return e.invocationsQueue.delete(a),e.promiseQueue=e.promiseQueue.then(()=>{i()}),$e.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new T(`Unexpected event type for wait ${a} "${t.eventType}"`))}),$e.Finished}),n}}async function Pg(e,t,n,r,i){if(t.size!==0){for(let e of t.values())e.type===`hook`&&e.isSystem&&!e.disposed&&!e.abortRequested&&(e.disposed=!0);try{let e=await Gm();await sh({suspension:new Ue(t,n),world:e,run:r})}catch(t){W.warn(`Failed to drain pending queue items for ${i} workflow run`,{workflowRunId:e,message:t instanceof Error?t.message:String(t)})}}}async function Fg(e,t,n,a){return _t(`workflow.run ${t.workflowName}`,async o=>{o?.setAttributes({...pt(t.workflowName),...it(t.runId),...Ut(t.status),...Le(n.length)});let s=t.startedAt;if(!s)throw new i(`Workflow run "${t.runId}" has no "startedAt" timestamp (should not happen)`);let c=process.env.VERCEL_URL!==void 0,u=c?void 0:await ah(),{context:d,globalThis:f,updateTimestamp:p}=jg({seed:`${t.runId}:${t.workflowName}:${+s}`,fixedTimestamp:+s}),m=r(),h=he(()=>f.Math.random()),g=ug(`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,21,e=>new Uint8Array(e).map(()=>256*f.Math.random())),_={current:Promise.resolve()},v=new tt(n,{onUnconsumedEvent:e=>{m.reject(new T(`Unconsumed event in event log: eventType=${e.eventType}, correlationId=${e.correlationId}, eventId=${e.eventId}. This indicates a corrupted or invalid event log.`))},getPromiseQueue:()=>_.current}),y={runId:t.runId,encryptionKey:a,globalThis:f,onWorkflowError:m.reject,eventsConsumer:v,generateUlid:()=>h(+s),generateNanoid:g,invocationsQueue:new Map,get promiseQueue(){return _.current},set promiseQueue(e){_.current=e},pendingDeliveries:0};y.eventsConsumer.subscribe(e=>{let t=e?.createdAt;return t&&p(+t),$e.NotConsumed}),y.eventsConsumer.subscribe(e=>e&&(e.eventType===`run_created`||e.eventType===`run_started`)?$e.Consumed:$e.NotConsumed);let x=dg(y),S=Mg(y),C=Ng(y);f[ve]=x,f[_e]=S,f[Se]=C,f[Te]=e=>qe(t.runId,e);let w=c?`https://${process.env.VERCEL_URL}`:`http://localhost:${u??3e3}`;f[ye]={workflowName:t.workflowName,workflowRunId:t.runId,workflowStartedAt:new f.Date(+s),url:w,features:{encryption:!!a}},f[Ce]=h,f.fetch=()=>{throw new f.Error(`Global "fetch" is unavailable in workflow functions. Use the "fetch" step function from "workflow" to make HTTP requests.\n\nLearn more: https://workflow-sdk.dev/err/${b.FETCH_IN_WORKFLOW_FUNCTION}`)};let E=`Timeout functions like "setTimeout" and "setInterval" are not supported in workflow functions. Use the "sleep" function from "workflow" for time-based delays.`;f.setTimeout=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.setInterval=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.clearTimeout=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.clearInterval=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.setImmediate=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.clearImmediate=()=>{throw new i(E,{slug:b.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},f.AbortController=Bt(y);let O=Pe();f.AbortSignal={abort:O.abort,any:O.any,timeout:O.timeout};class k{cache;credentials;destination;headers;integrity;method;mode;redirect;referrer;referrerPolicy;url;keepalive;signal;duplex;body;constructor(e,t){if(typeof e==`string`||e instanceof f.URL){let t=String(e);try{new f.URL(t),this.url=t}catch(e){throw TypeError(`Failed to parse URL from ${t}`,{cause:e})}}else{if(this.url=e.url,!t){this.method=e.method,this.headers=new f.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination;return}this.method=e.method,this.headers=new f.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination}t?.method?this.method=t.method.toUpperCase():typeof this.method!=`string`&&(this.method=`GET`),t?.headers?this.headers=new f.Headers(t.headers):(typeof e==`string`||e instanceof f.URL)&&(this.headers=new f.Headers),t?.mode===void 0?typeof this.mode!=`string`&&(this.mode=`cors`):this.mode=t.mode,t?.credentials===void 0?typeof this.credentials!=`string`&&(this.credentials=`same-origin`):this.credentials=t.credentials,t?.cache===void 0?typeof this.cache!=`string`&&(this.cache=`default`):this.cache=t.cache,t?.redirect===void 0?typeof this.redirect!=`string`&&(this.redirect=`follow`):this.redirect=t.redirect,t?.referrer===void 0?typeof this.referrer!=`string`&&(this.referrer=`about:client`):this.referrer=t.referrer,t?.referrerPolicy===void 0?typeof this.referrerPolicy!=`string`&&(this.referrerPolicy=``):this.referrerPolicy=t.referrerPolicy,t?.integrity===void 0?typeof this.integrity!=`string`&&(this.integrity=``):this.integrity=t.integrity,t?.keepalive===void 0?typeof this.keepalive!=`boolean`&&(this.keepalive=!1):this.keepalive=t.keepalive,t?.signal===void 0?this.signal||={aborted:!1}:this.signal=t.signal,this.duplex||=`half`,this.destination||=`document`;let n=t?.body;if(n!=null&&(this.method===`GET`||this.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);n==null?this.body=null:this.body=Object.create(f.ReadableStream.prototype,{[me]:{value:n,writable:!1}})}clone(){ot()}get bodyUsed(){return!1}blob;formData;arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}}f.Request=k,Object.defineProperties(k.prototype,{arrayBuffer:{value:x(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:x(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:x(`__builtin_response_text`),writable:!0,configurable:!0}});class A{type;url;status;statusText;body;headers;redirected;constructor(e,t){if(this.status=t?.status??200,this.statusText=t?.statusText??``,this.headers=new f.Headers(t?.headers),this.type=`default`,this.url=``,this.redirected=!1,e!=null&&(this.status===204||this.status===205||this.status===304))throw TypeError(`Response constructor: Invalid response status code ${this.status}`);e==null?this.body=null:this.body=Object.create(f.ReadableStream.prototype,{[me]:{value:e,writable:!1}})}clone;blob;formData;get ok(){return this.status>=200&&this.status<300}get bodyUsed(){return!1}arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}static json(e,t){let n=JSON.stringify(e),r=new f.Headers(t?.headers);return r.has(`content-type`)||r.set(`content-type`,`application/json`),new A(n,{...t,headers:r})}static error(){ot()}static redirect(e,t=302){if(![301,302,303,307,308].includes(t))throw RangeError(`Invalid redirect status code: ${t}. Must be one of: 301, 302, 303, 307, 308`);let n=new f.Headers;n.set(`Location`,String(e));let r=Object.create(A.prototype);return r.status=t,r.statusText=``,r.headers=n,r.body=null,r.type=`default`,r.url=``,r.redirected=!1,r}}f.Response=A,Object.defineProperties(A.prototype,{arrayBuffer:{value:x(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:x(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:x(`__builtin_response_text`),writable:!0,configurable:!0}});class j{constructor(){ot()}get locked(){return!1}cancel(){ot()}getReader(){ot()}pipeThrough(){ot()}pipeTo(){ot()}tee(){ot()}values(){ot()}static from(){ot()}[Symbol.asyncIterator](){ot()}}f.ReadableStream=j;class M{constructor(){ot()}get locked(){return!1}abort(){ot()}close(){ot()}getWriter(){ot()}}f.WritableStream=M;class N{readable;writable;constructor(){ot()}}f.TransformStream=N,f.console=globalThis.console;let P=Symbol.for(`@vercel/request-context`);f[P]=globalThis[P];let ee=l(t.workflowName)?.moduleSpecifier||t.workflowName,F=qn(`${e}; globalThis.__private_workflows?.get(${JSON.stringify(t.workflowName)})`,d,{filename:ee});if(typeof F!=`function`)throw new D(t.workflowName);let te=[];y.promiseQueue=y.promiseQueue.then(async()=>{te=await rt(t.input,t.runId,a,f)}),await y.promiseQueue,o?.setAttributes({...hn(te.length)});try{let e=await Promise.race([F(...te),m.promise]),n=await Tt(e,t.runId,a,f);return o?.setAttributes({...ze(typeof e)}),await Pg(t.runId,y.invocationsQueue,f,t,`completed`),n}catch(e){throw Ue.is(e)||await Pg(t.runId,y.invocationsQueue,f,t,`failed`),e}})}const Ig=he();async function Lg(e,t,n){"use step";return await Ze(()=>{let r=e?.workflowId;if(!r)throw new i(`'start' received an invalid workflow function. Ensure the Workflow SDK is configured correctly and the function includes a 'use workflow' directive.`,{slug:`start-invalid-workflow-function`});return _t(`workflow.start ${r}`,async e=>{e?.setAttributes({...pt(r),...Ve(`start`)});let a=[],o=n??{};Array.isArray(t)?a=t:typeof t==`object`&&(o=t),e?.setAttributes({...hn(a.length)});let s=o?.world??await lt(),c=o.deploymentId??await s.getDeploymentId();if(c===`latest`){if(!s.resolveLatestDeploymentId)throw new i(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`);c=await s.resolveLatestDeploymentId()}let l=[],u=`wrun_${Ig()}`,d=await mt(),f=o.specVersion??s.specVersion??2,p=ce(f),m=await s.getEncryptionKeyForRun?.(u,{...o,deploymentId:c}),h=m?await Ke(m):void 0,g=await mn(a,u,h,l,globalThis,p),_={traceCarrier:d,workflowCoreVersion:Zt,features:{encryption:!!h}},[v,y]=await Promise.allSettled([s.events.create(u,{eventType:`run_created`,specVersion:f,eventData:{deploymentId:c,workflowName:r,input:g,executionContext:_}},{v1Compat:p}),s.queue(Ct(r),{runId:u,traceCarrier:d,...f>=3?{runInput:{input:g,deploymentId:c,workflowName:r,specVersion:f,executionContext:_}}:{}},{deploymentId:c,specVersion:f})]);if(y.status===`rejected`)throw y.reason;let b=!1;if(v.status===`rejected`){let e=v.reason;if(!C.is(e))if(Rg(e))b=!0,W.warn(`Run creation event failed, but the run was accepted via the queue. The run_created event will be re-tried async by the runtime.`,{workflowRunId:u,error:e.message});else throw e}else{let e=v.value;if(!e.run)throw new i(`Missing 'run' in server response for 'run_created' event`);if(!p&&e.run.runId!==u)throw new i(`Server returned different runId than requested: expected ${u}, got ${e.run.runId}`)}return(0,Xm.waitUntil)(Promise.all(l).catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))throw e})),e?.setAttributes({...it(u),...$t(c),...v.status===`fulfilled`&&v.value.run?Ut(v.value.run.status):{}}),new Kg(u,{resilientStart:b})})})}function Rg(e){return!!(S.is(e)||O.is(e)&&e.status&&e.status>=500)}const zg=e=>Array.isArray(e)?e:[e];async function Bg(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),a=i?await Ke(i):void 0,o=zg(await rt(r.input,t,a,globalThis)),s=n.specVersion??r.specVersion??1,c=n.deploymentId??r.deploymentId;return(await Lg({workflowId:r.workflowName},o,{deploymentId:c,world:e,specVersion:s})).runId}catch(e){throw Error(`Failed to recreate run from ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Vg(e,t){try{let n=(await e.runs.get(t,{resolveData:`none`})).specVersion??1,r=ce(n),i={eventType:`run_cancelled`,specVersion:n};await e.events.create(t,i,{v1Compat:r})}catch(e){throw Error(`Failed to cancel run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Hg(e,t){try{let n=await e.runs.get(t,{resolveData:`none`});await e.queue(Ct(n.workflowName),{runId:t},{deploymentId:n.deploymentId,specVersion:n.specVersion??1})}catch(e){throw Error(`Failed to re-enqueue run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Ug(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`}),i=ce(r.specVersion),a=[],o=null;do{let n=await e.events.list({runId:t,pagination:{limit:1e3,...o?{cursor:o}:{}},resolveData:`none`});a.push(...n.data),o=n.hasMore?n.cursor:null}while(o);let s=a.filter(e=>e.eventType===`wait_created`),c=new Set(a.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),l=s.filter(e=>!c.has(e.correlationId));if(n?.correlationIds&&n.correlationIds.length>0){let e=new Set(n.correlationIds);l=l.filter(t=>t.correlationId&&e.has(t.correlationId))}let u=[],d=0;for(let n of l){if(!n.correlationId)continue;let a=i?{eventType:`wait_completed`,correlationId:n.correlationId}:{eventType:`wait_completed`,correlationId:n.correlationId,specVersion:r.specVersion,eventData:{resumeAt:n.eventData.resumeAt}};try{await e.events.create(t,a,{v1Compat:i}),d++}catch(e){C.is(e)?d++:u.push(e instanceof Error?e:Error(String(e)))}}if(d>0&&await e.queue(Ct(r.workflowName),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1}),u.length>0)throw AggregateError(u,`Failed to complete ${u.length}/${l.length} pending wait(s) for run ${t}`);return{stoppedCount:d}}catch(e){throw e instanceof AggregateError?e:Error(`Failed to wake up run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Wg(e,t,n,r){try{return await e.streams.get(t,n,r?.startIndex)}catch(e){throw Error(`Failed to read stream ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Gg(e,t){try{return await e.streams.list(t)}catch(e){throw Error(`Failed to list streams for run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}var Kg=class e{static[Qe](e){return{runId:e.runId,resilientStart:e.#r}}static[Je](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=lt(),this.#e}#n=null;#r=!1;constructor(e,t){this.runId=e,this.#r=t?.resilientStart??!1}#i(){return this.#n||=(async()=>{let e=await this.#t,t=await e.runs.get(this.runId),n=await e.getEncryptionKeyForRun?.(t);return n?await Ke(n):void 0})(),this.#n}async wakeUp(e){"use step";return Ug(await this.#t,this.runId,e)}async cancel(){"use step";await(await this.#t).events.create(this.runId,{eventType:`run_cancelled`,specVersion:3})}get exists(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(()=>!0).catch(e=>{if(u.is(e))return!1;throw e}))}get status(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.status))}get returnValue(){"use step";return this.#a()}get workflowName(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.workflowName))}get createdAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.createdAt))}get startedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.startedAt))}get completedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.completedAt))}get readable(){return this.getReadable()}getReadable(e={}){"use step";let{ops:t=[],global:n=globalThis,startIndex:r,namespace:i}=e,a=qe(this.runId,i),o=this.#i(),s=ut(n,t,this.runId,o).ReadableStream({name:a,startIndex:r}),c=this.#t,l=this.runId;return Object.assign(s,{getTailIndex:async()=>(await(await c).streams.getInfo(l,a)).tailIndex})}async#a(){let e=await this.#t,t=0,n=this.#r?3:0,r=[1e3,3e3,6e3];for(;;)try{let t=await e.runs.get(this.runId);if(t.status===`completed`){let e=await this.#i();return await Ht(t.output,this.runId,e)}if(t.status===`cancelled`)throw new A(this.runId);if(t.status===`failed`){let e=await this.#i(),n;try{n=await dn(t.error,this.runId,e)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new p(this.runId,n,{errorCode:t.errorCode})}throw new k(this.runId,t.status)}catch(e){if(k.is(e)){await new Promise(e=>setTimeout(e,1e3));continue}if(u.is(e)&&t<n){let e=r[t];t++,await new Promise(t=>setTimeout(t,e));continue}throw e}}};function qg(e){return new Kg(e)}function Jg(e){return i.is(e)?d.RUNTIME_ERROR:Xn(e)?d.WORLD_CONTRACT_ERROR:null}async function Yg({world:e,workflowRun:t,runId:n,requestId:r,err:i,errorCode:a,logMessage:o}){W.error(o,{workflowRunId:n,errorCode:a,error:i instanceof Error?i.message:String(i)});try{let o=Wt(e,t??n);await e.events.create(n,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(i,n,await o()),errorCode:a}},{requestId:r})}catch(e){if(C.is(e)||m.is(e))return;if(Xn(e)){W.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:n,errorCode:d.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}}function Xg(e){let t=Number(process.env.WORKFLOW_V2_TIMEOUT_MS)||12e4,n=n=>n.createQueueHandler(`__wkf_workflow_`,async(r,a)=>{let o=sn(r);if(o){await Yt(o,`workflow`,n.specVersion);return}let{runId:s,traceCarrier:c,requestedAt:u,stepId:f,stepName:p,runInput:h}=ie.parse(r),{requestId:g}=a,v=a.queueName.slice(15),y=W.forRun(s,v);if(a.attempt>48){let e=er(void 0,d.MAX_DELIVERIES_EXCEEDED);y.error(`Workflow handler exceeded max deliveries (${a.attempt}/48)`,{attempt:a.attempt,errorCode:e.errorCode,errorAttribution:e.attribution});try{let e=await Gm(),t=Wt(e,s),n=new _(`Workflow exceeded maximum queue deliveries (${a.attempt}/48)`);await e.events.create(s,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(n,s,await t()),errorCode:d.MAX_DELIVERIES_EXCEEDED}},{requestId:g})}catch(e){if(C.is(e)||m.is(e))return;y.error(`Failed to mark run as failed after ${a.attempt} delivery attempts. A persistent error is preventing the run from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`,{attempt:a.attempt,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}return}let b=await Ge(),x=new Jm;return await We(c,async()=>await Xe({workflowRunId:s,workflowName:v},async()=>{let n=await Gm();return _t(`WORKFLOW_V2 ${v}`,{links:b},async r=>{r?.setAttributes({...pt(v),...Ve(`execute_v2`),...jt(`vercel-queue`),...bt(a.queueName),...st(a.messageId),...Ne(`process`),...Rt({requestedAt:u}),...it(s),...et(!!c)});let o=Date.now(),_=0,y=null,b=null,S,w=-1,T,E;if(f&&p)try{let e=await n.runs.get(s);if(e.status!==`running`){W.debug(`Run already finished, skipping background step`,{workflowRunId:s,status:e.status});return}let t=e.startedAt?+e.startedAt:Date.now();x.pause();let r;try{r=await oh({world:n,workflowRunId:s,workflowName:v,workflowStartedAt:t,stepId:f,stepName:p})}finally{x.resume()}if(r.type===`retry`||r.type===`throttled`)return{timeoutSeconds:r.timeoutSeconds};if(r.type===`completed`&&r.hasPendingOps){await kt(n,Ct(v),{runId:s,traceCarrier:await mt(),requestedAt:new Date});return}if(r.type===`completed`||r.type===`failed`||r.type===`skipped`){let n=await Dt(s);y=n.events,b=n.cursor;let r=new Set,i=new Set;for(let e of y)e.eventType===`step_created`?r.add(e.correlationId):(e.eventType===`step_completed`||e.eventType===`step_failed`)&&i.add(e.correlationId);let a=!1;for(let e of r)if(!i.has(e)){a=!0;break}if(a){W.debug(`Background step done but other steps pending, returning`,{workflowRunId:s});return}W.debug(`All parallel steps done, replaying inline after background step`,{workflowRunId:s}),S=e,w=t}else return}catch(e){let t=Jg(e);if(!t)throw e;await Yg({world:n,workflowRun:S,runId:s,requestId:g,err:e,errorCode:t,logMessage:`Fatal error while preparing background workflow step`});return}if(!S){try{let e=await n.events.create(s,{eventType:`run_started`,specVersion:h?.specVersion??3,...h?{eventData:{input:h.input,deploymentId:h.deploymentId,workflowName:h.workflowName,executionContext:h.executionContext}}:{}},{requestId:g});if(!e.run)throw new i(`Event creation for 'run_started' did not return the run entity for run "${s}"`);if(S=e.run,e.events&&e.events.length>0&&e.hasMore!==!0&&(T=e.events,E=e.cursor),!S.startedAt)throw new i(`Workflow run "${s}" has no "startedAt" timestamp`)}catch(e){if(C.is(e)||m.is(e)){W.info(`Run already finished during setup, skipping`,{workflowRunId:s,message:e.message});return}else{let t=Jg(e);if(!t)throw e;await Yg({world:n,workflowRun:S,runId:s,requestId:g,err:e,errorCode:t,logMessage:`Fatal runtime error during workflow setup`});return}}if(w=+S.startedAt,r?.setAttributes({...Ut(S.status),...Fe(w)}),S.status!==`running`){W.info(`Workflow already completed or failed, skipping`,{workflowRunId:s,status:S.status});return}}let D=await Wt(n,S)();for(;;){if(_++,x.isExhausted()){await Ym({runId:s,workflowName:v,requestId:g,attempt:a.attempt,limitMs:x.configuredLimitMs});return}if(Date.now()-o>=t){W.info(`V2 timeout reached, re-scheduling workflow`,{workflowRunId:s,loopIteration:_,elapsedMs:Date.now()-o}),await kt(n,Ct(v),{runId:s,traceCarrier:await mt(),requestedAt:new Date});return}let i=0;try{let t;if(y===null)if(T)t=T,b=E??null;else{let e=await Dt(s);t=e.events,b=e.cursor}else if(b){let e=await Dt(s,b);if(e.events.length>0){let t=new Set(y.map(e=>e.eventId));for(let n of e.events)t.has(n.eventId)||y.push(n)}b=e.cursor??b,t=y}else if(T){W.debug(`No cursor after preloaded-events first iteration; doing full reload to pick up cursor.`,{workflowRunId:s});let e=await Dt(s);y=e.events,b=e.cursor,t=y}else{W.warn(`Event cursor missing after initial load — falling back to full reload. This indicates a bug in the World implementation.`,{workflowRunId:s});let e=await Dt(s);y=e.events,b=e.cursor,t=y}let a=t.find(e=>e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`);if(a){W.debug(`Run completed by concurrent handler, exiting`,{workflowRunId:s,eventType:a.eventType});return}let o=Date.now(),c=new Set(t.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),l=t.filter(e=>e.eventType===`wait_created`&&e.correlationId!==void 0&&!c.has(e.correlationId)&&o>=e.eventData.resumeAt.getTime()).map(e=>({eventType:`wait_completed`,specVersion:3,correlationId:e.correlationId,eventData:{resumeAt:e.eventData.resumeAt}}));for(let e of l)try{await n.events.create(s,e,{requestId:g})}catch(t){if(C.is(t)){W.info(`Wait already completed, skipping`,{workflowRunId:s,correlationId:e.correlationId});continue}throw t}if(l.length>0)if(b){let e=await Dt(s,b),n=new Set(e.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId));if(l.every(e=>n.has(e.correlationId))){let n=new Set(t.map(e=>e.eventId));for(let r of e.events)n.has(r.eventId)||t.push(r);b=e.cursor??b}else{let e=await Dt(s);t=e.events,b=e.cursor}}else{let e=await Dt(s);t=e.events,b=e.cursor}y=t,W.debug(`Starting workflow replay`,{workflowRunId:s,loopIteration:_,eventCount:t.length}),i=Date.now();let u=await Fg(e,S,t,D);W.debug(`Workflow replay completed`,{workflowRunId:s,loopIteration:_,replayMs:Date.now()-i});try{await n.events.create(s,{eventType:`run_completed`,specVersion:3,eventData:{output:u}},{requestId:g})}catch(e){if(C.is(e)||m.is(e)){W.info(`Tried completing workflow run, but run has already finished.`,{workflowRunId:s,message:e.message});return}throw e}r?.setAttributes({...Ut(`completed`)});return}catch(t){if(Ue.is(t)){W.debug(`Workflow suspended`,{workflowRunId:s,loopIteration:_,replayMs:Date.now()-i,steps:t.stepCount,hooks:t.hookCount,waits:t.waitCount});let e=at(t.stepCount,t.hookCount,t.waitCount);e&&W.debug(e);let a=Date.now(),o=await sh({suspension:t,world:n,run:S,span:r,requestId:g});if(W.debug(`Suspension handled`,{workflowRunId:s,suspensionMs:Date.now()-a,pendingSteps:o.pendingSteps.length,timeoutSeconds:o.timeoutSeconds,hasHookConflict:o.hasHookConflict}),o.hasHookConflict)return{timeoutSeconds:0};let c=o.pendingSteps;if(c.length===0)return o.timeoutSeconds===void 0?void 0:{timeoutSeconds:o.timeoutSeconds};let l=c.filter(e=>o.createdStepCorrelationIds.has(e.correlationId)),u=o.timeoutSeconds===void 0?l[0]:void 0;for(let e of c){if(u&&e.correlationId===u.correlationId)continue;let t=await mt();await kt(n,Ct(v),{runId:s,stepId:e.correlationId,stepName:e.stepName,traceCarrier:t,requestedAt:new Date},{idempotencyKey:e.correlationId})}if(!u)return o.timeoutSeconds===void 0?void 0:{timeoutSeconds:o.timeoutSeconds};x.pause();let d;try{d=await oh({world:n,workflowRunId:s,workflowName:v,workflowStartedAt:w,stepId:u.correlationId,stepName:u.stepName})}finally{x.resume()}if(d.type===`retry`){let e=await mt();return await kt(n,Ct(v),{runId:s,stepId:u.correlationId,stepName:u.stepName,traceCarrier:e,requestedAt:new Date},{delaySeconds:d.timeoutSeconds}),o.timeoutSeconds===void 0?void 0:{timeoutSeconds:o.timeoutSeconds}}if(d.type===`throttled`)return{timeoutSeconds:d.timeoutSeconds};if(d.type===`completed`&&d.hasPendingOps){W.debug(`Breaking loop: step has pending ops`,{workflowRunId:s,loopIteration:_,stepName:u.stepName}),await kt(n,Ct(v),{runId:s,traceCarrier:await mt(),requestedAt:new Date});return}o.timeoutSeconds!==void 0&&c.length}else{t instanceof Error&&r?.recordException?.(t);let i=await rh(t),a=i.name||Zm(t),o=i.message,c=i.stack||Qm(t);if(c){let t=l(v)?.moduleSpecifier||v;c=lg(c,t,e)}let u=Zn(t);W.error(`Error while running workflow`,{workflowRunId:s,errorCode:u,errorName:a,errorStack:c}),Cn.isNativeError(t)&&c&&(t.stack=c);try{await n.events.create(s,{eventType:`run_failed`,specVersion:3,eventData:{error:await It(t,s,D),errorCode:u}},{requestId:g})}catch(e){if(C.is(e)||m.is(e)){W.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:s,message:e.message});return}if(Xn(e)){W.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:s,errorCode:d.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}r?.setAttributes({...Ut(`failed`),...Et(u),...dt(a),...pn(o),...vt(a)});return}}}})}))}),r;return Mt(async e=>(r||=n(await Wm()),r(e)))}export{Kg as Run,Ue as WorkflowSuspension,Vg as cancelRun,Um as createWorld,an as getHookByToken,qg as getRun,Gm as getWorld,Wm as getWorldHandlers,nn as healthCheck,_s as i,Gg as listStreams,Fl as n,Cs as r,Wg as readStream,Bg as recreateRunFromExisting,Hg as reenqueueRun,qt as resumeHook,en as resumeWebhook,Km as setWorld,Lg as start,Vl as t,Ug as wakeUpRun,Xg as workflowEntrypoint};