billion-context 0.1.207 → 0.1.208
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.
- package/dist/agent/dsh-native.js +1 -1
- package/dist/agent/omp-native.js +1 -1
- package/dist/agent/omp.js +1 -1
- package/dist/agent/opencode-native.js +1 -1
- package/dist/agent/opencode.js +1 -1
- package/dist/agent/pi-native.js +2 -2
- package/dist/agent/pi.js +1 -1
- package/dist/build-info.json +1 -1
- package/dist/claude-mcp-entry.js +1 -1
- package/dist/claude-native-bootstrap.js +1 -1
- package/dist/index.js +2 -2
- package/dist/kimi/bootstrap-hook.js +1 -1
- package/dist/kimi/native-mcp.js +1 -1
- package/dist/zcode/bootstrap-hook.js +1 -1
- package/dist/zcode/mcp-entry.js +1 -1
- package/package.json +1 -1
package/dist/agent/dsh-native.js
CHANGED
|
@@ -122,7 +122,7 @@ ${pendingInterceptorsFormatter.format(pending)}`.trim())}};module.exports=MockAg
|
|
|
122
122
|
)
|
|
123
123
|
`)}close(){this.#db.close()}get(key){assertCacheKey(key);const value=this.#findValue(key);return value?{body:value.body?Buffer.from(value.body.buffer,value.body.byteOffset,value.body.byteLength):void 0,statusCode:value.statusCode,statusMessage:value.statusMessage,headers:value.headers?JSON.parse(value.headers):void 0,etag:value.etag?value.etag:void 0,vary:value.vary?JSON.parse(value.vary):void 0,cacheControlDirectives:value.cacheControlDirectives?JSON.parse(value.cacheControlDirectives):void 0,cachedAt:value.cachedAt,staleAt:value.staleAt,deleteAt:value.deleteAt}:void 0}set(key,value){assertCacheKey(key);const url=this.#makeValueUrl(key);const body=Array.isArray(value.body)?Buffer.concat(value.body):value.body;const size=body?.byteLength;if(size&&size>this.#maxEntrySize){return}const existingValue=this.#findValue(key,true);if(existingValue){this.#updateValueQuery.run(body,value.deleteAt,value.statusCode,value.statusMessage,value.headers?JSON.stringify(value.headers):null,value.etag?value.etag:null,value.cacheControlDirectives?JSON.stringify(value.cacheControlDirectives):null,value.cachedAt,value.staleAt,existingValue.id)}else{this.#insertValueQuery.run(url,key.method,body,value.deleteAt,value.statusCode,value.statusMessage,value.headers?JSON.stringify(value.headers):null,value.etag?value.etag:null,value.cacheControlDirectives?JSON.stringify(value.cacheControlDirectives):null,value.vary?JSON.stringify(value.vary):null,value.cachedAt,value.staleAt);this.#prune()}}createWriteStream(key,value){assertCacheKey(key);assertCacheValue(value);let size=0;const body=[];const store=this;return new Writable({decodeStrings:true,write(chunk,encoding,callback){size+=chunk.byteLength;if(size<store.#maxEntrySize){body.push(chunk)}else{this.destroy()}callback()},final(callback){store.set(key,{...value,body});callback()}})}delete(key){if(typeof key!=="object"){throw new TypeError(`expected key to be object, got ${typeof key}`)}this.#deleteByUrlQuery.run(this.#makeValueUrl(key))}#prune(){if(Number.isFinite(this.#maxCount)&&this.size<=this.#maxCount){return 0}{const removed=this.#deleteExpiredValuesQuery.run(Date.now()).changes;if(removed){return removed}}{const removed=this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount*.1),1)).changes;if(removed){return removed}}return 0}get size(){const{total}=this.#countEntriesQuery.get();return total}#makeValueUrl(key){return`${key.origin}/${key.path}`}#findValue(key,canBeExpired=false){const url=this.#makeValueUrl(key);const{headers,method}=key;const values=this.#getValuesQuery.all(url,method);if(values.length===0){return void 0}const now=Date.now();for(const value of values){if(now>=value.deleteAt&&!canBeExpired){continue}let matches=true;if(value.vary){const vary=JSON.parse(value.vary);for(const header in vary){if(!headerValueEquals(headers[header],vary[header])){matches=false;break}}}if(matches){return value}}return void 0}};function headerValueEquals(lhs,rhs){if(lhs==null&&rhs==null){return true}if(lhs==null&&rhs!=null||lhs!=null&&rhs==null){return false}if(Array.isArray(lhs)&&Array.isArray(rhs)){if(lhs.length!==rhs.length){return false}for(let i=0;i<lhs.length;i++){if(lhs[i]!==rhs[i]){return false}}return true}return lhs===rhs}}});var require_headers=__commonJS({"node_modules/undici/lib/web/fetch/headers.js"(exports,module){"use strict";var{kConstruct}=require_symbols();var{kEnumerableProperty}=require_util2();var{iteratorMixin,isValidHeaderName,isValidHeaderValue}=require_util3();var{webidl}=require_webidl();var assert=__require("assert");var util=__require("util");function isHTTPWhiteSpaceCharCode(code){return code===10||code===13||code===9||code===32}function headerValueNormalize(potentialValue){let i=0;let j2=potentialValue.length;while(j2>i&&isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j2-1)))--j2;while(j2>i&&isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i)))++i;return i===0&&j2===potentialValue.length?potentialValue:potentialValue.substring(i,j2)}function fill(headers,object){if(Array.isArray(object)){for(let i=0;i<object.length;++i){const header=object[i];if(header.length!==2){throw webidl.errors.exception({header:"Headers constructor",message:`expected name/value pair to be length 2, found ${header.length}.`})}appendHeader(headers,header[0],header[1])}}else if(typeof object==="object"&&object!==null){const keys=Object.keys(object);for(let i=0;i<keys.length;++i){appendHeader(headers,keys[i],object[keys[i]])}}else{throw webidl.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})}}function appendHeader(headers,name2,value){value=headerValueNormalize(value);if(!isValidHeaderName(name2)){throw webidl.errors.invalidArgument({prefix:"Headers.append",value:name2,type:"header name"})}else if(!isValidHeaderValue(value)){throw webidl.errors.invalidArgument({prefix:"Headers.append",value,type:"header value"})}if(getHeadersGuard(headers)==="immutable"){throw new TypeError("immutable")}return getHeadersList(headers).append(name2,value,false)}function headersListSortAndCombine(target){const headersList=getHeadersList(target);if(!headersList){return[]}if(headersList.sortedMap){return headersList.sortedMap}const headers=[];const names=headersList.toSortedArray();const cookies=headersList.cookies;if(cookies===null||cookies.length===1){return headersList.sortedMap=names}for(let i=0;i<names.length;++i){const{0:name2,1:value}=names[i];if(name2==="set-cookie"){for(let j2=0;j2<cookies.length;++j2){headers.push([name2,cookies[j2]])}}else{headers.push([name2,value])}}return headersList.sortedMap=headers}function compareHeaderName(a,b2){return a[0]<b2[0]?-1:1}var HeadersList=class _HeadersList{cookies=null;sortedMap;headersMap;constructor(init){if(init instanceof _HeadersList){this.headersMap=new Map(init.headersMap);this.sortedMap=init.sortedMap;this.cookies=init.cookies===null?null:[...init.cookies]}else{this.headersMap=new Map(init);this.sortedMap=null}}contains(name2,isLowerCase){return this.headersMap.has(isLowerCase?name2:name2.toLowerCase())}clear(){this.headersMap.clear();this.sortedMap=null;this.cookies=null}append(name2,value,isLowerCase){this.sortedMap=null;const lowercaseName=isLowerCase?name2:name2.toLowerCase();const exists=this.headersMap.get(lowercaseName);if(exists){const delimiter=lowercaseName==="cookie"?"; ":", ";this.headersMap.set(lowercaseName,{name:exists.name,value:`${exists.value}${delimiter}${value}`})}else{this.headersMap.set(lowercaseName,{name:name2,value})}if(lowercaseName==="set-cookie"){(this.cookies??=[]).push(value)}}set(name2,value,isLowerCase){this.sortedMap=null;const lowercaseName=isLowerCase?name2:name2.toLowerCase();if(lowercaseName==="set-cookie"){this.cookies=[value]}this.headersMap.set(lowercaseName,{name:name2,value})}delete(name2,isLowerCase){this.sortedMap=null;if(!isLowerCase)name2=name2.toLowerCase();if(name2==="set-cookie"){this.cookies=null}this.headersMap.delete(name2)}get(name2,isLowerCase){return this.headersMap.get(isLowerCase?name2:name2.toLowerCase())?.value??null}*[Symbol.iterator](){for(const{0:name2,1:{value}}of this.headersMap){yield[name2,value]}}get entries(){const headers={};if(this.headersMap.size!==0){for(const{name:name2,value}of this.headersMap.values()){headers[name2]=value}}return headers}rawValues(){return this.headersMap.values()}get entriesList(){const headers=[];if(this.headersMap.size!==0){for(const{0:lowerName,1:{name:name2,value}}of this.headersMap){if(lowerName==="set-cookie"){for(const cookie of this.cookies){headers.push([name2,cookie])}}else{headers.push([name2,value])}}}return headers}toSortedArray(){const size=this.headersMap.size;const array=new Array(size);if(size<=32){if(size===0){return array}const iterator=this.headersMap[Symbol.iterator]();const firstValue=iterator.next().value;array[0]=[firstValue[0],firstValue[1].value];assert(firstValue[1].value!==null);for(let i=1,j2=0,right=0,left=0,pivot=0,x,value;i<size;++i){value=iterator.next().value;x=array[i]=[value[0],value[1].value];assert(x[1]!==null);left=0;right=i;while(left<right){pivot=left+(right-left>>1);if(array[pivot][0]<=x[0]){left=pivot+1}else{right=pivot}}if(i!==pivot){j2=i;while(j2>left){array[j2]=array[--j2]}array[left]=x}}if(!iterator.next().done){throw new TypeError("Unreachable")}return array}else{let i=0;for(const{0:name2,1:{value}}of this.headersMap){array[i++]=[name2,value];assert(value!==null)}return array.sort(compareHeaderName)}}};var Headers2=class _Headers{#guard;#headersList;constructor(init=void 0){webidl.util.markAsUncloneable(this);if(init===kConstruct){return}this.#headersList=new HeadersList;this.#guard="none";if(init!==void 0){init=webidl.converters.HeadersInit(init,"Headers constructor","init");fill(this,init)}}append(name2,value){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,2,"Headers.append");const prefix="Headers.append";name2=webidl.converters.ByteString(name2,prefix,"name");value=webidl.converters.ByteString(value,prefix,"value");return appendHeader(this,name2,value)}delete(name2){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,1,"Headers.delete");const prefix="Headers.delete";name2=webidl.converters.ByteString(name2,prefix,"name");if(!isValidHeaderName(name2)){throw webidl.errors.invalidArgument({prefix:"Headers.delete",value:name2,type:"header name"})}if(this.#guard==="immutable"){throw new TypeError("immutable")}if(!this.#headersList.contains(name2,false)){return}this.#headersList.delete(name2,false)}get(name2){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,1,"Headers.get");const prefix="Headers.get";name2=webidl.converters.ByteString(name2,prefix,"name");if(!isValidHeaderName(name2)){throw webidl.errors.invalidArgument({prefix,value:name2,type:"header name"})}return this.#headersList.get(name2,false)}has(name2){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,1,"Headers.has");const prefix="Headers.has";name2=webidl.converters.ByteString(name2,prefix,"name");if(!isValidHeaderName(name2)){throw webidl.errors.invalidArgument({prefix,value:name2,type:"header name"})}return this.#headersList.contains(name2,false)}set(name2,value){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,2,"Headers.set");const prefix="Headers.set";name2=webidl.converters.ByteString(name2,prefix,"name");value=webidl.converters.ByteString(value,prefix,"value");value=headerValueNormalize(value);if(!isValidHeaderName(name2)){throw webidl.errors.invalidArgument({prefix,value:name2,type:"header name"})}else if(!isValidHeaderValue(value)){throw webidl.errors.invalidArgument({prefix,value,type:"header value"})}if(this.#guard==="immutable"){throw new TypeError("immutable")}this.#headersList.set(name2,value,false)}getSetCookie(){webidl.brandCheck(this,_Headers);const list=this.#headersList.cookies;if(list){return[...list]}return[]}[util.inspect.custom](depth,options){options.depth??=depth;return`Headers ${util.formatWithOptions(options,this.#headersList.entries)}`}static getHeadersGuard(o){return o.#guard}static setHeadersGuard(o,guard){o.#guard=guard}static getHeadersList(o){return o.#headersList}static setHeadersList(target,list){target.#headersList=list}};var{getHeadersGuard,setHeadersGuard,getHeadersList,setHeadersList}=Headers2;Reflect.deleteProperty(Headers2,"getHeadersGuard");Reflect.deleteProperty(Headers2,"setHeadersGuard");Reflect.deleteProperty(Headers2,"getHeadersList");Reflect.deleteProperty(Headers2,"setHeadersList");iteratorMixin("Headers",Headers2,headersListSortAndCombine,0,1);Object.defineProperties(Headers2.prototype,{append:kEnumerableProperty,delete:kEnumerableProperty,get:kEnumerableProperty,has:kEnumerableProperty,set:kEnumerableProperty,getSetCookie:kEnumerableProperty,[Symbol.toStringTag]:{value:"Headers",configurable:true},[util.inspect.custom]:{enumerable:false}});webidl.converters.HeadersInit=function(V2,prefix,argument){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT){const iterator=Reflect.get(V2,Symbol.iterator);if(!util.types.isProxy(V2)&&iterator===Headers2.prototype.entries){try{return getHeadersList(V2).entriesList}catch{}}if(typeof iterator==="function"){return webidl.converters["sequence<sequence<ByteString>>"](V2,prefix,argument,iterator.bind(V2))}return webidl.converters["record<ByteString, ByteString>"](V2,prefix,argument)}throw webidl.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})};module.exports={fill,compareHeaderName,Headers:Headers2,HeadersList,getHeadersGuard,setHeadersGuard,setHeadersList,getHeadersList}}});var require_response=__commonJS({"node_modules/undici/lib/web/fetch/response.js"(exports,module){"use strict";var{Headers:Headers2,HeadersList,fill,getHeadersGuard,setHeadersGuard,setHeadersList}=require_headers();var{extractBody,cloneBody,mixinBody,streamRegistry,bodyUnusable}=require_body();var util=require_util2();var nodeUtil=__require("util");var{kEnumerableProperty}=util;var{isValidReasonPhrase,isCancelled,isAborted,isErrorLike,environmentSettingsObject:relevantRealm}=require_util3();var{redirectStatusSet,nullBodyStatus}=require_constants3();var{webidl}=require_webidl();var{URLSerializer}=require_data_url();var{kConstruct}=require_symbols();var assert=__require("assert");var{isomorphicEncode,serializeJavascriptValueToJSONString}=require_infra();var textEncoder=new TextEncoder("utf-8");var Response2=class _Response{#headers;#state;static error(){const responseObject=fromInnerResponse(makeNetworkError(),"immutable");return responseObject}static json(data,init=void 0){webidl.argumentLengthCheck(arguments,1,"Response.json");if(init!==null){init=webidl.converters.ResponseInit(init)}const bytes=textEncoder.encode(serializeJavascriptValueToJSONString(data));const body=extractBody(bytes);const responseObject=fromInnerResponse(makeResponse({}),"response");initializeResponse(responseObject,init,{body:body[0],type:"application/json"});return responseObject}static redirect(url,status=302){webidl.argumentLengthCheck(arguments,1,"Response.redirect");url=webidl.converters.USVString(url);status=webidl.converters["unsigned short"](status);let parsedURL;try{parsedURL=new URL(url,relevantRealm.settingsObject.baseUrl)}catch(err){throw new TypeError(`Failed to parse URL from ${url}`,{cause:err})}if(!redirectStatusSet.has(status)){throw new RangeError(`Invalid status code ${status}`)}const responseObject=fromInnerResponse(makeResponse({}),"immutable");responseObject.#state.status=status;const value=isomorphicEncode(URLSerializer(parsedURL));responseObject.#state.headersList.append("location",value,true);return responseObject}constructor(body=null,init=void 0){webidl.util.markAsUncloneable(this);if(body===kConstruct){return}if(body!==null){body=webidl.converters.BodyInit(body,"Response","body")}init=webidl.converters.ResponseInit(init);this.#state=makeResponse({});this.#headers=new Headers2(kConstruct);setHeadersGuard(this.#headers,"response");setHeadersList(this.#headers,this.#state.headersList);let bodyWithType=null;if(body!=null){const[extractedBody,type]=extractBody(body);bodyWithType={body:extractedBody,type}}initializeResponse(this,init,bodyWithType)}get type(){webidl.brandCheck(this,_Response);return this.#state.type}get url(){webidl.brandCheck(this,_Response);const urlList=this.#state.urlList;const url=urlList[urlList.length-1]??null;if(url===null){return""}return URLSerializer(url,true)}get redirected(){webidl.brandCheck(this,_Response);return this.#state.urlList.length>1}get status(){webidl.brandCheck(this,_Response);return this.#state.status}get ok(){webidl.brandCheck(this,_Response);return this.#state.status>=200&&this.#state.status<=299}get statusText(){webidl.brandCheck(this,_Response);return this.#state.statusText}get headers(){webidl.brandCheck(this,_Response);return this.#headers}get body(){webidl.brandCheck(this,_Response);return this.#state.body?this.#state.body.stream:null}get bodyUsed(){webidl.brandCheck(this,_Response);return!!this.#state.body&&util.isDisturbed(this.#state.body.stream)}clone(){webidl.brandCheck(this,_Response);if(bodyUnusable(this.#state)){throw webidl.errors.exception({header:"Response.clone",message:"Body has already been consumed."})}const clonedResponse=cloneResponse(this.#state);if(this.#state.urlList.length!==0&&this.#state.body?.stream){streamRegistry.register(this,new WeakRef(this.#state.body.stream))}return fromInnerResponse(clonedResponse,getHeadersGuard(this.#headers))}[nodeUtil.inspect.custom](depth,options){if(options.depth===null){options.depth=2}options.colors??=true;const properties={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${nodeUtil.formatWithOptions(options,properties)}`}static getResponseHeaders(response){return response.#headers}static setResponseHeaders(response,newHeaders){response.#headers=newHeaders}static getResponseState(response){return response.#state}static setResponseState(response,newState){response.#state=newState}};var{getResponseHeaders,setResponseHeaders,getResponseState,setResponseState}=Response2;Reflect.deleteProperty(Response2,"getResponseHeaders");Reflect.deleteProperty(Response2,"setResponseHeaders");Reflect.deleteProperty(Response2,"getResponseState");Reflect.deleteProperty(Response2,"setResponseState");mixinBody(Response2,getResponseState);Object.defineProperties(Response2.prototype,{type:kEnumerableProperty,url:kEnumerableProperty,status:kEnumerableProperty,ok:kEnumerableProperty,redirected:kEnumerableProperty,statusText:kEnumerableProperty,headers:kEnumerableProperty,clone:kEnumerableProperty,body:kEnumerableProperty,bodyUsed:kEnumerableProperty,[Symbol.toStringTag]:{value:"Response",configurable:true}});Object.defineProperties(Response2,{json:kEnumerableProperty,redirect:kEnumerableProperty,error:kEnumerableProperty});function cloneResponse(response){if(response.internalResponse){return filterResponse(cloneResponse(response.internalResponse),response.type)}const newResponse=makeResponse({...response,body:null});if(response.body!=null){newResponse.body=cloneBody(response.body)}return newResponse}function makeResponse(init){return{aborted:false,rangeRequested:false,timingAllowPassed:false,requestIncludesCredentials:false,type:"default",status:200,timingInfo:null,cacheState:"",statusText:"",...init,headersList:init?.headersList?new HeadersList(init?.headersList):new HeadersList,urlList:init?.urlList?[...init.urlList]:[]}}function makeNetworkError(reason){const isError=isErrorLike(reason);return makeResponse({type:"error",status:0,error:isError?reason:new Error(reason?String(reason):reason),aborted:reason&&reason.name==="AbortError"})}function isNetworkError(response){return response.type==="error"&&response.status===0}function makeFilteredResponse(response,state3){state3={internalResponse:response,...state3};return new Proxy(response,{get(target,p2){return p2 in state3?state3[p2]:target[p2]},set(target,p2,value){assert(!(p2 in state3));target[p2]=value;return true}})}function filterResponse(response,type){if(type==="basic"){return makeFilteredResponse(response,{type:"basic",headersList:response.headersList})}else if(type==="cors"){return makeFilteredResponse(response,{type:"cors",headersList:response.headersList})}else if(type==="opaque"){return makeFilteredResponse(response,{type:"opaque",urlList:[],status:0,statusText:"",body:null})}else if(type==="opaqueredirect"){return makeFilteredResponse(response,{type:"opaqueredirect",status:0,statusText:"",headersList:[],body:null})}else{assert(false)}}function makeAppropriateNetworkError(fetchParams,err=null){assert(isCancelled(fetchParams));return isAborted(fetchParams)?makeNetworkError(Object.assign(new DOMException("The operation was aborted.","AbortError"),{cause:err})):makeNetworkError(Object.assign(new DOMException("Request was cancelled."),{cause:err}))}function initializeResponse(response,init,body){if(init.status!==null&&(init.status<200||init.status>599)){throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')}if("statusText"in init&&init.statusText!=null){if(!isValidReasonPhrase(String(init.statusText))){throw new TypeError("Invalid statusText")}}if("status"in init&&init.status!=null){getResponseState(response).status=init.status}if("statusText"in init&&init.statusText!=null){getResponseState(response).statusText=init.statusText}if("headers"in init&&init.headers!=null){fill(getResponseHeaders(response),init.headers)}if(body){if(nullBodyStatus.includes(response.status)){throw webidl.errors.exception({header:"Response constructor",message:`Invalid response status code ${response.status}`})}getResponseState(response).body=body.body;if(body.type!=null&&!getResponseState(response).headersList.contains("content-type",true)){getResponseState(response).headersList.append("content-type",body.type,true)}}}function fromInnerResponse(innerResponse,guard){const response=new Response2(kConstruct);setResponseState(response,innerResponse);const headers=new Headers2(kConstruct);setResponseHeaders(response,headers);setHeadersList(headers,innerResponse.headersList);setHeadersGuard(headers,guard);if(innerResponse.urlList.length!==0&&innerResponse.body?.stream){streamRegistry.register(response,new WeakRef(innerResponse.body.stream))}return response}webidl.converters.XMLHttpRequestBodyInit=function(V2,prefix,name2){if(typeof V2==="string"){return webidl.converters.USVString(V2,prefix,name2)}if(webidl.is.Blob(V2)){return V2}if(webidl.is.BufferSource(V2)){return V2}if(webidl.is.FormData(V2)){return V2}if(webidl.is.URLSearchParams(V2)){return V2}return webidl.converters.DOMString(V2,prefix,name2)};webidl.converters.BodyInit=function(V2,prefix,argument){if(webidl.is.ReadableStream(V2)){return V2}if(V2?.[Symbol.asyncIterator]){return V2}return webidl.converters.XMLHttpRequestBodyInit(V2,prefix,argument)};webidl.converters.ResponseInit=webidl.dictionaryConverter([{key:"status",converter:webidl.converters["unsigned short"],defaultValue:()=>200},{key:"statusText",converter:webidl.converters.ByteString,defaultValue:()=>""},{key:"headers",converter:webidl.converters.HeadersInit}]);webidl.is.Response=webidl.util.MakeTypeAssertion(Response2);module.exports={isNetworkError,makeNetworkError,makeResponse,makeAppropriateNetworkError,filterResponse,Response:Response2,cloneResponse,fromInnerResponse,getResponseState}}});var require_request2=__commonJS({"node_modules/undici/lib/web/fetch/request.js"(exports,module){"use strict";var{extractBody,mixinBody,cloneBody,bodyUnusable}=require_body();var{Headers:Headers2,fill:fillHeaders,HeadersList,setHeadersGuard,getHeadersGuard,setHeadersList,getHeadersList}=require_headers();var util=require_util2();var nodeUtil=__require("util");var{isValidHTTPToken,sameOrigin,environmentSettingsObject}=require_util3();var{forbiddenMethodsSet,corsSafeListedMethodsSet,referrerPolicy,requestRedirect,requestMode,requestCredentials,requestCache,requestDuplex}=require_constants3();var{kEnumerableProperty,normalizedMethodRecordsBase,normalizedMethodRecords}=util;var{webidl}=require_webidl();var{URLSerializer}=require_data_url();var{kConstruct}=require_symbols();var assert=__require("assert");var{getMaxListeners,setMaxListeners,defaultMaxListeners}=__require("events");var kAbortController=Symbol("abortController");var requestFinalizer=new FinalizationRegistry(({signal,abort})=>{signal.removeEventListener("abort",abort)});var dependentControllerMap=new WeakMap;var abortSignalHasEventHandlerLeakWarning;try{abortSignalHasEventHandlerLeakWarning=getMaxListeners(new AbortController().signal)>0}catch{abortSignalHasEventHandlerLeakWarning=false}function buildAbort(acRef){return abort;function abort(){const ac=acRef.deref();if(ac!==void 0){requestFinalizer.unregister(abort);this.removeEventListener("abort",abort);ac.abort(this.reason);const controllerList=dependentControllerMap.get(ac.signal);if(controllerList!==void 0){if(controllerList.size!==0){for(const ref of controllerList){const ctrl=ref.deref();if(ctrl!==void 0){ctrl.abort(this.reason)}}controllerList.clear()}dependentControllerMap.delete(ac.signal)}}}}var patchMethodWarning=false;var Request2=class _Request{#signal;#dispatcher;#headers;#state;constructor(input,init=void 0){webidl.util.markAsUncloneable(this);if(input===kConstruct){return}const prefix="Request constructor";webidl.argumentLengthCheck(arguments,1,prefix);input=webidl.converters.RequestInfo(input);init=webidl.converters.RequestInit(init);let request=null;let fallbackMode=null;const baseUrl=environmentSettingsObject.settingsObject.baseUrl;let signal=null;if(typeof input==="string"){this.#dispatcher=init.dispatcher;let parsedURL;try{parsedURL=new URL(input,baseUrl)}catch(err){throw new TypeError("Failed to parse URL from "+input,{cause:err})}if(parsedURL.username||parsedURL.password){throw new TypeError("Request cannot be constructed from a URL that includes credentials: "+input)}request=makeRequest({urlList:[parsedURL]});fallbackMode="cors"}else{assert(webidl.is.Request(input));request=input.#state;signal=input.#signal;this.#dispatcher=init.dispatcher||input.#dispatcher}const origin=environmentSettingsObject.settingsObject.origin;let window2="client";if(request.window?.constructor?.name==="EnvironmentSettingsObject"&&sameOrigin(request.window,origin)){window2=request.window}if(init.window!=null){throw new TypeError(`'window' option '${window2}' must be null`)}if("window"in init){window2="no-window"}request=makeRequest({method:request.method,headersList:request.headersList,unsafeRequest:request.unsafeRequest,client:environmentSettingsObject.settingsObject,window:window2,priority:request.priority,origin:request.origin,referrer:request.referrer,referrerPolicy:request.referrerPolicy,mode:request.mode,credentials:request.credentials,cache:request.cache,redirect:request.redirect,integrity:request.integrity,keepalive:request.keepalive,reloadNavigation:request.reloadNavigation,historyNavigation:request.historyNavigation,urlList:[...request.urlList]});const initHasKey=Object.keys(init).length!==0;if(initHasKey){if(request.mode==="navigate"){request.mode="same-origin"}request.reloadNavigation=false;request.historyNavigation=false;request.origin="client";request.referrer="client";request.referrerPolicy="";request.url=request.urlList[request.urlList.length-1];request.urlList=[request.url]}if(init.referrer!==void 0){const referrer=init.referrer;if(referrer===""){request.referrer="no-referrer"}else{let parsedReferrer;try{parsedReferrer=new URL(referrer,baseUrl)}catch(err){throw new TypeError(`Referrer "${referrer}" is not a valid URL.`,{cause:err})}if(parsedReferrer.protocol==="about:"&&parsedReferrer.hostname==="client"||origin&&!sameOrigin(parsedReferrer,environmentSettingsObject.settingsObject.baseUrl)){request.referrer="client"}else{request.referrer=parsedReferrer}}}if(init.referrerPolicy!==void 0){request.referrerPolicy=init.referrerPolicy}let mode;if(init.mode!==void 0){mode=init.mode}else{mode=fallbackMode}if(mode==="navigate"){throw webidl.errors.exception({header:"Request constructor",message:"invalid request mode navigate."})}if(mode!=null){request.mode=mode}if(init.credentials!==void 0){request.credentials=init.credentials}if(init.cache!==void 0){request.cache=init.cache}if(request.cache==="only-if-cached"&&request.mode!=="same-origin"){throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode")}if(init.redirect!==void 0){request.redirect=init.redirect}if(init.integrity!=null){request.integrity=String(init.integrity)}if(init.keepalive!==void 0){request.keepalive=Boolean(init.keepalive)}if(init.method!==void 0){let method=init.method;const mayBeNormalized=normalizedMethodRecords[method];if(mayBeNormalized!==void 0){request.method=mayBeNormalized}else{if(!isValidHTTPToken(method)){throw new TypeError(`'${method}' is not a valid HTTP method.`)}const upperCase=method.toUpperCase();if(forbiddenMethodsSet.has(upperCase)){throw new TypeError(`'${method}' HTTP method is unsupported.`)}method=normalizedMethodRecordsBase[upperCase]??method;request.method=method}if(!patchMethodWarning&&request.method==="patch"){process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"});patchMethodWarning=true}}if(init.signal!==void 0){signal=init.signal}this.#state=request;const ac=new AbortController;this.#signal=ac.signal;if(signal!=null){if(signal.aborted){ac.abort(signal.reason)}else{this[kAbortController]=ac;const acRef=new WeakRef(ac);const abort=buildAbort(acRef);if(abortSignalHasEventHandlerLeakWarning&&getMaxListeners(signal)===defaultMaxListeners){setMaxListeners(1500,signal)}util.addAbortListener(signal,abort);requestFinalizer.register(ac,{signal,abort},abort)}}this.#headers=new Headers2(kConstruct);setHeadersList(this.#headers,request.headersList);setHeadersGuard(this.#headers,"request");if(mode==="no-cors"){if(!corsSafeListedMethodsSet.has(request.method)){throw new TypeError(`'${request.method} is unsupported in no-cors mode.`)}setHeadersGuard(this.#headers,"request-no-cors")}if(initHasKey){const headersList=getHeadersList(this.#headers);const headers=init.headers!==void 0?init.headers:new HeadersList(headersList);headersList.clear();if(headers instanceof HeadersList){for(const{name:name2,value}of headers.rawValues()){headersList.append(name2,value,false)}headersList.cookies=headers.cookies}else{fillHeaders(this.#headers,headers)}}const inputBody=webidl.is.Request(input)?input.#state.body:null;if((init.body!=null||inputBody!=null)&&(request.method==="GET"||request.method==="HEAD")){throw new TypeError("Request with GET/HEAD method cannot have body.")}let initBody=null;if(init.body!=null){const[extractedBody,contentType]=extractBody(init.body,request.keepalive);initBody=extractedBody;if(contentType&&!getHeadersList(this.#headers).contains("content-type",true)){this.#headers.append("content-type",contentType,true)}}const inputOrInitBody=initBody??inputBody;if(inputOrInitBody!=null&&inputOrInitBody.source==null){if(initBody!=null&&init.duplex==null){throw new TypeError("RequestInit: duplex option is required when sending a body.")}if(request.mode!=="same-origin"&&request.mode!=="cors"){throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"')}request.useCORSPreflightFlag=true}let finalBody=inputOrInitBody;if(initBody==null&&inputBody!=null){if(bodyUnusable(input.#state)){throw new TypeError("Cannot construct a Request with a Request object that has already been used.")}const identityTransform=new TransformStream;inputBody.stream.pipeThrough(identityTransform);finalBody={source:inputBody.source,length:inputBody.length,stream:identityTransform.readable}}this.#state.body=finalBody}get method(){webidl.brandCheck(this,_Request);return this.#state.method}get url(){webidl.brandCheck(this,_Request);return URLSerializer(this.#state.url)}get headers(){webidl.brandCheck(this,_Request);return this.#headers}get destination(){webidl.brandCheck(this,_Request);return this.#state.destination}get referrer(){webidl.brandCheck(this,_Request);if(this.#state.referrer==="no-referrer"){return""}if(this.#state.referrer==="client"){return"about:client"}return this.#state.referrer.toString()}get referrerPolicy(){webidl.brandCheck(this,_Request);return this.#state.referrerPolicy}get mode(){webidl.brandCheck(this,_Request);return this.#state.mode}get credentials(){webidl.brandCheck(this,_Request);return this.#state.credentials}get cache(){webidl.brandCheck(this,_Request);return this.#state.cache}get redirect(){webidl.brandCheck(this,_Request);return this.#state.redirect}get integrity(){webidl.brandCheck(this,_Request);return this.#state.integrity}get keepalive(){webidl.brandCheck(this,_Request);return this.#state.keepalive}get isReloadNavigation(){webidl.brandCheck(this,_Request);return this.#state.reloadNavigation}get isHistoryNavigation(){webidl.brandCheck(this,_Request);return this.#state.historyNavigation}get signal(){webidl.brandCheck(this,_Request);return this.#signal}get body(){webidl.brandCheck(this,_Request);return this.#state.body?this.#state.body.stream:null}get bodyUsed(){webidl.brandCheck(this,_Request);return!!this.#state.body&&util.isDisturbed(this.#state.body.stream)}get duplex(){webidl.brandCheck(this,_Request);return"half"}clone(){webidl.brandCheck(this,_Request);if(bodyUnusable(this.#state)){throw new TypeError("unusable")}const clonedRequest=cloneRequest(this.#state);const ac=new AbortController;if(this.signal.aborted){ac.abort(this.signal.reason)}else{let list=dependentControllerMap.get(this.signal);if(list===void 0){list=new Set;dependentControllerMap.set(this.signal,list)}const acRef=new WeakRef(ac);list.add(acRef);util.addAbortListener(ac.signal,buildAbort(acRef))}return fromInnerRequest(clonedRequest,this.#dispatcher,ac.signal,getHeadersGuard(this.#headers))}[nodeUtil.inspect.custom](depth,options){if(options.depth===null){options.depth=2}options.colors??=true;const properties={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${nodeUtil.formatWithOptions(options,properties)}`}static setRequestSignal(request,newSignal){request.#signal=newSignal;return request}static getRequestDispatcher(request){return request.#dispatcher}static setRequestDispatcher(request,newDispatcher){request.#dispatcher=newDispatcher}static setRequestHeaders(request,newHeaders){request.#headers=newHeaders}static getRequestState(request){return request.#state}static setRequestState(request,newState){request.#state=newState}};var{setRequestSignal,getRequestDispatcher,setRequestDispatcher,setRequestHeaders,getRequestState,setRequestState}=Request2;Reflect.deleteProperty(Request2,"setRequestSignal");Reflect.deleteProperty(Request2,"getRequestDispatcher");Reflect.deleteProperty(Request2,"setRequestDispatcher");Reflect.deleteProperty(Request2,"setRequestHeaders");Reflect.deleteProperty(Request2,"getRequestState");Reflect.deleteProperty(Request2,"setRequestState");mixinBody(Request2,getRequestState);function makeRequest(init){return{method:init.method??"GET",localURLsOnly:init.localURLsOnly??false,unsafeRequest:init.unsafeRequest??false,body:init.body??null,client:init.client??null,reservedClient:init.reservedClient??null,replacesClientId:init.replacesClientId??"",window:init.window??"client",keepalive:init.keepalive??false,serviceWorkers:init.serviceWorkers??"all",initiator:init.initiator??"",destination:init.destination??"",priority:init.priority??null,origin:init.origin??"client",policyContainer:init.policyContainer??"client",referrer:init.referrer??"client",referrerPolicy:init.referrerPolicy??"",mode:init.mode??"no-cors",useCORSPreflightFlag:init.useCORSPreflightFlag??false,credentials:init.credentials??"same-origin",useCredentials:init.useCredentials??false,cache:init.cache??"default",redirect:init.redirect??"follow",integrity:init.integrity??"",cryptoGraphicsNonceMetadata:init.cryptoGraphicsNonceMetadata??"",parserMetadata:init.parserMetadata??"",reloadNavigation:init.reloadNavigation??false,historyNavigation:init.historyNavigation??false,userActivation:init.userActivation??false,taintedOrigin:init.taintedOrigin??false,redirectCount:init.redirectCount??0,responseTainting:init.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:init.preventNoCacheCacheControlHeaderModification??false,done:init.done??false,timingAllowFailed:init.timingAllowFailed??false,useURLCredentials:init.useURLCredentials??void 0,traversableForUserPrompts:init.traversableForUserPrompts??"client",urlList:init.urlList,url:init.urlList[0],headersList:init.headersList?new HeadersList(init.headersList):new HeadersList}}function cloneRequest(request){const newRequest=makeRequest({...request,body:null});if(request.body!=null){newRequest.body=cloneBody(request.body)}return newRequest}function fromInnerRequest(innerRequest,dispatcher,signal,guard){const request=new Request2(kConstruct);setRequestState(request,innerRequest);setRequestDispatcher(request,dispatcher);setRequestSignal(request,signal);const headers=new Headers2(kConstruct);setRequestHeaders(request,headers);setHeadersList(headers,innerRequest.headersList);setHeadersGuard(headers,guard);return request}Object.defineProperties(Request2.prototype,{method:kEnumerableProperty,url:kEnumerableProperty,headers:kEnumerableProperty,redirect:kEnumerableProperty,clone:kEnumerableProperty,signal:kEnumerableProperty,duplex:kEnumerableProperty,destination:kEnumerableProperty,body:kEnumerableProperty,bodyUsed:kEnumerableProperty,isHistoryNavigation:kEnumerableProperty,isReloadNavigation:kEnumerableProperty,keepalive:kEnumerableProperty,integrity:kEnumerableProperty,cache:kEnumerableProperty,credentials:kEnumerableProperty,attribute:kEnumerableProperty,referrerPolicy:kEnumerableProperty,referrer:kEnumerableProperty,mode:kEnumerableProperty,[Symbol.toStringTag]:{value:"Request",configurable:true}});webidl.is.Request=webidl.util.MakeTypeAssertion(Request2);webidl.converters.RequestInfo=function(V2){if(typeof V2==="string"){return webidl.converters.USVString(V2)}if(webidl.is.Request(V2)){return V2}return webidl.converters.USVString(V2)};webidl.converters.RequestInit=webidl.dictionaryConverter([{key:"method",converter:webidl.converters.ByteString},{key:"headers",converter:webidl.converters.HeadersInit},{key:"body",converter:webidl.nullableConverter(webidl.converters.BodyInit)},{key:"referrer",converter:webidl.converters.USVString},{key:"referrerPolicy",converter:webidl.converters.DOMString,allowedValues:referrerPolicy},{key:"mode",converter:webidl.converters.DOMString,allowedValues:requestMode},{key:"credentials",converter:webidl.converters.DOMString,allowedValues:requestCredentials},{key:"cache",converter:webidl.converters.DOMString,allowedValues:requestCache},{key:"redirect",converter:webidl.converters.DOMString,allowedValues:requestRedirect},{key:"integrity",converter:webidl.converters.DOMString},{key:"keepalive",converter:webidl.converters.boolean},{key:"signal",converter:webidl.nullableConverter(signal=>webidl.converters.AbortSignal(signal,"RequestInit","signal"))},{key:"window",converter:webidl.converters.any},{key:"duplex",converter:webidl.converters.DOMString,allowedValues:requestDuplex},{key:"dispatcher",converter:webidl.converters.any},{key:"priority",converter:webidl.converters.DOMString,allowedValues:["high","low","auto"],defaultValue:()=>"auto"}]);module.exports={Request:Request2,makeRequest,fromInnerRequest,cloneRequest,getRequestDispatcher,getRequestState}}});var require_subresource_integrity=__commonJS({"node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js"(exports,module){"use strict";var assert=__require("assert");var{runtimeFeatures}=require_runtime_features();var validSRIHashAlgorithmTokenSet=new Map([["sha256",0],["sha384",1],["sha512",2]]);var crypto5;if(runtimeFeatures.has("crypto")){crypto5=__require("crypto");const cryptoHashes=crypto5.getHashes();if(cryptoHashes.length===0){validSRIHashAlgorithmTokenSet.clear()}for(const algorithm of validSRIHashAlgorithmTokenSet.keys()){if(cryptoHashes.includes(algorithm)===false){validSRIHashAlgorithmTokenSet.delete(algorithm)}}}else{validSRIHashAlgorithmTokenSet.clear()}var getSRIHashAlgorithmIndex=Map.prototype.get.bind(validSRIHashAlgorithmTokenSet);var isValidSRIHashAlgorithm=Map.prototype.has.bind(validSRIHashAlgorithmTokenSet);var bytesMatch=runtimeFeatures.has("crypto")===false||validSRIHashAlgorithmTokenSet.size===0?()=>true:(bytes,metadataList)=>{const parsedMetadata=parseMetadata(metadataList);if(parsedMetadata.length===0){return true}const metadata=getStrongestMetadata(parsedMetadata);for(const item of metadata){const algorithm=item.alg;const expectedValue=item.val;const actualValue=applyAlgorithmToBytes(algorithm,bytes);if(caseSensitiveMatch(actualValue,expectedValue)){return true}}return false};function getStrongestMetadata(metadataList){const result=[];let strongest=null;for(const item of metadataList){assert(isValidSRIHashAlgorithm(item.alg),"Invalid SRI hash algorithm token");if(result.length===0){result.push(item);strongest=item;continue}const currentAlgorithm=strongest.alg;const currentAlgorithmIndex=getSRIHashAlgorithmIndex(currentAlgorithm);const newAlgorithm=item.alg;const newAlgorithmIndex=getSRIHashAlgorithmIndex(newAlgorithm);if(newAlgorithmIndex<currentAlgorithmIndex){continue}else if(newAlgorithmIndex>currentAlgorithmIndex){strongest=item;result[0]=item;result.length=1}else{result.push(item)}}return result}function parseMetadata(metadata){const result=[];for(const item of metadata.split(" ")){const expressionAndOptions=item.split("?",1);const algorithmExpression=expressionAndOptions[0];let base64Value="";const algorithmAndValue=[algorithmExpression.slice(0,6),algorithmExpression.slice(7)];const algorithm=algorithmAndValue[0];if(!isValidSRIHashAlgorithm(algorithm)){continue}if(algorithmAndValue[1]){base64Value=algorithmAndValue[1]}const metadata2={alg:algorithm,val:base64Value};result.push(metadata2)}return result}var applyAlgorithmToBytes=(algorithm,bytes)=>{return crypto5.hash(algorithm,bytes,"base64")};function caseSensitiveMatch(actualValue,expectedValue){let actualValueLength=actualValue.length;if(actualValueLength!==0&&actualValue[actualValueLength-1]==="="){actualValueLength-=1}if(actualValueLength!==0&&actualValue[actualValueLength-1]==="="){actualValueLength-=1}let expectedValueLength=expectedValue.length;if(expectedValueLength!==0&&expectedValue[expectedValueLength-1]==="="){expectedValueLength-=1}if(expectedValueLength!==0&&expectedValue[expectedValueLength-1]==="="){expectedValueLength-=1}if(actualValueLength!==expectedValueLength){return false}for(let i=0;i<actualValueLength;++i){if(actualValue[i]===expectedValue[i]||actualValue[i]==="+"&&expectedValue[i]==="-"||actualValue[i]==="/"&&expectedValue[i]==="_"){continue}return false}return true}module.exports={applyAlgorithmToBytes,bytesMatch,caseSensitiveMatch,isValidSRIHashAlgorithm,getStrongestMetadata,parseMetadata}}});var require_fetch=__commonJS({"node_modules/undici/lib/web/fetch/index.js"(exports,module){"use strict";var{makeNetworkError,makeAppropriateNetworkError,filterResponse,makeResponse,fromInnerResponse,getResponseState}=require_response();var{HeadersList}=require_headers();var{Request:Request2,cloneRequest,getRequestDispatcher,getRequestState}=require_request2();var zlib2=__require("zlib");var{makePolicyContainer,clonePolicyContainer,requestBadPort,TAOCheck,appendRequestOriginHeader,responseLocationURL,requestCurrentURL,setRequestReferrerPolicyOnRedirect,tryUpgradeRequestToAPotentiallyTrustworthyURL,createOpaqueTimingInfo,appendFetchMetadata,corsCheck,crossOriginResourcePolicyCheck,determineRequestsReferrer,coarsenedSharedCurrentTime,sameOrigin,isCancelled,isAborted,isErrorLike,fullyReadBody,readableStreamClose,urlIsLocal,urlIsHttpHttpsScheme,urlHasHttpsScheme,clampAndCoarsenConnectionTimingInfo,simpleRangeHeaderValue,buildContentRange,createInflate,extractMimeType,hasAuthenticationEntry,includesCredentials,isTraversableNavigable}=require_util3();var assert=__require("assert");var{safelyExtractBody,extractBody}=require_body();var{redirectStatusSet,nullBodyStatus,safeMethodsSet,requestBodyHeader,subresourceSet}=require_constants3();var EE=__require("events");var{Readable,pipeline,finished,isErrored,isReadable}=__require("stream");var{addAbortListener,bufferToLowerCasedHeaderName}=require_util2();var{dataURLProcessor,serializeAMimeType,minimizeSupportedMimeType}=require_data_url();var{getGlobalDispatcher}=require_global2();var{webidl}=require_webidl();var{STATUS_CODES}=__require("http");var{bytesMatch}=require_subresource_integrity();var{createDeferredPromise}=require_promise();var{isomorphicEncode}=require_infra();var{runtimeFeatures}=require_runtime_features();var hasZstd=runtimeFeatures.has("zstd");var GET_OR_HEAD=["GET","HEAD"];var defaultUserAgent=typeof __UNDICI_IS_NODE__!=="undefined"||typeof esbuildDetection!=="undefined"?"node":"undici";var resolveObjectURL;var Fetch=class extends EE{constructor(dispatcher){super();this.dispatcher=dispatcher;this.connection=null;this.dump=false;this.state="ongoing"}terminate(reason){if(this.state!=="ongoing"){return}this.state="terminated";this.connection?.destroy(reason);this.emit("terminated",reason)}abort(error){if(this.state!=="ongoing"){return}this.state="aborted";if(!error){error=new DOMException("The operation was aborted.","AbortError")}this.serializedAbortReason=error;this.connection?.destroy(error);this.emit("terminated",error)}};function handleFetchDone(response){finalizeAndReportTiming(response,"fetch")}function fetch2(input,init=void 0){webidl.argumentLengthCheck(arguments,1,"globalThis.fetch");let p2=createDeferredPromise();let requestObject;try{requestObject=new Request2(input,init)}catch(e){p2.reject(e);return p2.promise}const request=getRequestState(requestObject);if(requestObject.signal.aborted){abortFetch(p2,request,null,requestObject.signal.reason,null);return p2.promise}const globalObject=request.client.globalObject;if(globalObject?.constructor?.name==="ServiceWorkerGlobalScope"){request.serviceWorkers="none"}let responseObject=null;let locallyAborted=false;let controller=null;addAbortListener(requestObject.signal,()=>{locallyAborted=true;assert(controller!=null);controller.abort(requestObject.signal.reason);const realResponse=responseObject?.deref();abortFetch(p2,request,realResponse,requestObject.signal.reason,controller.controller)});const processResponse=response=>{if(locallyAborted){return}if(response.aborted){abortFetch(p2,request,responseObject,controller.serializedAbortReason,controller.controller);return}if(response.type==="error"){p2.reject(new TypeError("fetch failed",{cause:response.error}));return}responseObject=new WeakRef(fromInnerResponse(response,"immutable"));p2.resolve(responseObject.deref());p2=null};controller=fetching({request,processResponseEndOfBody:handleFetchDone,processResponse,dispatcher:getRequestDispatcher(requestObject),requestObject});return p2.promise}function finalizeAndReportTiming(response,initiatorType="other"){if(response.type==="error"&&response.aborted){return}if(!response.urlList?.length){return}const originalURL=response.urlList[0];let timingInfo=response.timingInfo;let cacheState=response.cacheState;if(!urlIsHttpHttpsScheme(originalURL)){return}if(timingInfo===null){return}if(!response.timingAllowPassed){timingInfo=createOpaqueTimingInfo({startTime:timingInfo.startTime});cacheState=""}timingInfo.endTime=coarsenedSharedCurrentTime();response.timingInfo=timingInfo;markResourceTiming(timingInfo,originalURL.href,initiatorType,globalThis,cacheState,"",response.status)}var markResourceTiming=performance.markResourceTiming;function abortFetch(p2,request,responseObject,error,controller){if(p2){p2.reject(error)}if(request.body?.stream!=null&&isReadable(request.body.stream)){request.body.stream.cancel(error).catch(err=>{if(err.code==="ERR_INVALID_STATE"){return}throw err})}if(responseObject==null){return}const response=getResponseState(responseObject);if(response.body?.stream!=null&&isReadable(response.body.stream)){controller.error(error)}}function fetching({request,processRequestBodyChunkLength,processRequestEndOfBody,processResponse,processResponseEndOfBody,processResponseConsumeBody,useParallelQueue=false,dispatcher=getGlobalDispatcher(),requestObject=null}){assert(dispatcher);let taskDestination=null;let crossOriginIsolatedCapability=false;if(request.client!=null){taskDestination=request.client.globalObject;crossOriginIsolatedCapability=request.client.crossOriginIsolatedCapability}const currentTime=coarsenedSharedCurrentTime(crossOriginIsolatedCapability);const timingInfo=createOpaqueTimingInfo({startTime:currentTime});const fetchParams={controller:new Fetch(dispatcher),request,timingInfo,processRequestBodyChunkLength,processRequestEndOfBody,processResponse,processResponseConsumeBody,processResponseEndOfBody,taskDestination,crossOriginIsolatedCapability,requestObject};assert(!request.body||request.body.stream);if(request.window==="client"){request.window=request.client?.globalObject?.constructor?.name==="Window"?request.client:"no-window"}if(request.origin==="client"){request.origin=request.client.origin}if(request.policyContainer==="client"){if(request.client!=null){request.policyContainer=clonePolicyContainer(request.client.policyContainer)}else{request.policyContainer=makePolicyContainer()}}if(!request.headersList.contains("accept",true)){const value="*/*";request.headersList.append("accept",value,true)}if(!request.headersList.contains("accept-language",true)){request.headersList.append("accept-language","*",true)}if(request.priority===null){}if(subresourceSet.has(request.destination)){}mainFetch(fetchParams,false);return fetchParams.controller}async function mainFetch(fetchParams,recursive){try{const request=fetchParams.request;let response=null;if(request.localURLsOnly&&!urlIsLocal(requestCurrentURL(request))){response=makeNetworkError("local URLs only")}tryUpgradeRequestToAPotentiallyTrustworthyURL(request);if(requestBadPort(request)==="blocked"){response=makeNetworkError("bad port")}if(request.referrerPolicy===""){request.referrerPolicy=request.policyContainer.referrerPolicy}if(request.referrer!=="no-referrer"){request.referrer=determineRequestsReferrer(request)}if(response===null){const currentURL=requestCurrentURL(request);if(sameOrigin(currentURL,request.url)&&request.responseTainting==="basic"||currentURL.protocol==="data:"||(request.mode==="navigate"||request.mode==="websocket")){request.responseTainting="basic";response=await schemeFetch(fetchParams)}else if(request.mode==="same-origin"){response=makeNetworkError('request mode cannot be "same-origin"')}else if(request.mode==="no-cors"){if(request.redirect!=="follow"){response=makeNetworkError('redirect mode cannot be "follow" for "no-cors" request')}else{request.responseTainting="opaque";response=await schemeFetch(fetchParams)}}else if(!urlIsHttpHttpsScheme(requestCurrentURL(request))){response=makeNetworkError("URL scheme must be a HTTP(S) scheme")}else{request.responseTainting="cors";response=await httpFetch(fetchParams)}}if(recursive){return response}if(response.status!==0&&!response.internalResponse){if(request.responseTainting==="cors"){}if(request.responseTainting==="basic"){response=filterResponse(response,"basic")}else if(request.responseTainting==="cors"){response=filterResponse(response,"cors")}else if(request.responseTainting==="opaque"){response=filterResponse(response,"opaque")}else{assert(false)}}let internalResponse=response.status===0?response:response.internalResponse;if(internalResponse.urlList.length===0){internalResponse.urlList.push(...request.urlList)}if(!request.timingAllowFailed){response.timingAllowPassed=true}if(response.type==="opaque"&&internalResponse.status===206&&internalResponse.rangeRequested&&!request.headers.contains("range",true)){response=internalResponse=makeNetworkError()}if(response.status!==0&&(request.method==="HEAD"||request.method==="CONNECT"||nullBodyStatus.includes(internalResponse.status))){internalResponse.body=null;fetchParams.controller.dump=true}if(request.integrity){const processBodyError=reason=>fetchFinale(fetchParams,makeNetworkError(reason));if(request.responseTainting==="opaque"||response.body==null){processBodyError(response.error);return}const processBody=bytes=>{if(!bytesMatch(bytes,request.integrity)){processBodyError("integrity mismatch");return}response.body=safelyExtractBody(bytes)[0];fetchFinale(fetchParams,response)};fullyReadBody(response.body,processBody,processBodyError)}else{fetchFinale(fetchParams,response)}}catch(err){fetchParams.controller.terminate(err)}}function schemeFetch(fetchParams){if(isCancelled(fetchParams)&&fetchParams.request.redirectCount===0){return Promise.resolve(makeAppropriateNetworkError(fetchParams))}const{request}=fetchParams;const{protocol:scheme}=requestCurrentURL(request);switch(scheme){case"about:":{return Promise.resolve(makeNetworkError("about scheme is not supported"))}case"blob:":{if(!resolveObjectURL){resolveObjectURL=__require("buffer").resolveObjectURL}const blobURLEntry=requestCurrentURL(request);if(blobURLEntry.search.length!==0){return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."))}const blob=resolveObjectURL(blobURLEntry.toString());if(request.method!=="GET"||!webidl.is.Blob(blob)){return Promise.resolve(makeNetworkError("invalid method"))}const response=makeResponse();const fullLength=blob.size;const serializedFullLength=isomorphicEncode(`${fullLength}`);const type=blob.type;if(!request.headersList.contains("range",true)){const bodyWithType=extractBody(blob);response.statusText="OK";response.body=bodyWithType[0];response.headersList.set("content-length",serializedFullLength,true);response.headersList.set("content-type",type,true)}else{response.rangeRequested=true;const rangeHeader=request.headersList.get("range",true);const rangeValue=simpleRangeHeaderValue(rangeHeader,true);if(rangeValue==="failure"){return Promise.resolve(makeNetworkError("failed to fetch the data URL"))}let{rangeStartValue:rangeStart,rangeEndValue:rangeEnd}=rangeValue;if(rangeStart===null){rangeStart=fullLength-rangeEnd;rangeEnd=rangeStart+rangeEnd-1}else{if(rangeStart>=fullLength){return Promise.resolve(makeNetworkError("Range start is greater than the blob's size."))}if(rangeEnd===null||rangeEnd>=fullLength){rangeEnd=fullLength-1}}const slicedBlob=blob.slice(rangeStart,rangeEnd+1,type);const slicedBodyWithType=extractBody(slicedBlob);response.body=slicedBodyWithType[0];const serializedSlicedLength=isomorphicEncode(`${slicedBlob.size}`);const contentRange=buildContentRange(rangeStart,rangeEnd,fullLength);response.status=206;response.statusText="Partial Content";response.headersList.set("content-length",serializedSlicedLength,true);response.headersList.set("content-type",type,true);response.headersList.set("content-range",contentRange,true)}return Promise.resolve(response)}case"data:":{const currentURL=requestCurrentURL(request);const dataURLStruct=dataURLProcessor(currentURL);if(dataURLStruct==="failure"){return Promise.resolve(makeNetworkError("failed to fetch the data URL"))}const mimeType=serializeAMimeType(dataURLStruct.mimeType);return Promise.resolve(makeResponse({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:mimeType}]],body:safelyExtractBody(dataURLStruct.body)[0]}))}case"file:":{return Promise.resolve(makeNetworkError("not implemented... yet..."))}case"http:":case"https:":{return httpFetch(fetchParams).catch(err=>makeNetworkError(err))}default:{return Promise.resolve(makeNetworkError("unknown scheme"))}}}function finalizeResponse(fetchParams,response){fetchParams.request.done=true;if(fetchParams.processResponseDone!=null){queueMicrotask(()=>fetchParams.processResponseDone(response))}}function fetchFinale(fetchParams,response){let timingInfo=fetchParams.timingInfo;const processResponseEndOfBody=()=>{const unsafeEndTime=Date.now();if(fetchParams.request.destination==="document"){fetchParams.controller.fullTimingInfo=timingInfo}fetchParams.controller.reportTimingSteps=()=>{if(!urlIsHttpHttpsScheme(fetchParams.request.url)){return}timingInfo.endTime=unsafeEndTime;let cacheState=response.cacheState;const bodyInfo=response.bodyInfo;if(!response.timingAllowPassed){timingInfo=createOpaqueTimingInfo(timingInfo);cacheState=""}let responseStatus=0;if(fetchParams.request.mode!=="navigate"||!response.hasCrossOriginRedirects){responseStatus=response.status;const mimeType=extractMimeType(response.headersList);if(mimeType!=="failure"){bodyInfo.contentType=minimizeSupportedMimeType(mimeType)}}if(fetchParams.request.initiatorType!=null){markResourceTiming(timingInfo,fetchParams.request.url.href,fetchParams.request.initiatorType,globalThis,cacheState,bodyInfo,responseStatus)}};const processResponseEndOfBodyTask=()=>{fetchParams.request.done=true;if(fetchParams.processResponseEndOfBody!=null){queueMicrotask(()=>fetchParams.processResponseEndOfBody(response))}if(fetchParams.request.initiatorType!=null){fetchParams.controller.reportTimingSteps()}};queueMicrotask(()=>processResponseEndOfBodyTask())};if(fetchParams.processResponse!=null){queueMicrotask(()=>{fetchParams.processResponse(response);fetchParams.processResponse=null})}const internalResponse=response.type==="error"?response:response.internalResponse??response;if(internalResponse.body==null){processResponseEndOfBody()}else{finished(internalResponse.body.stream,()=>{processResponseEndOfBody()})}}async function httpFetch(fetchParams){const request=fetchParams.request;let response=null;let actualResponse=null;const timingInfo=fetchParams.timingInfo;if(request.serviceWorkers==="all"){}if(response===null){if(request.redirect==="follow"){request.serviceWorkers="none"}actualResponse=response=await httpNetworkOrCacheFetch(fetchParams);if(request.responseTainting==="cors"&&corsCheck(request,response)==="failure"){return makeNetworkError("cors failure")}if(TAOCheck(request,response)==="failure"){request.timingAllowFailed=true}}if((request.responseTainting==="opaque"||response.type==="opaque")&&crossOriginResourcePolicyCheck(request.origin,request.client,request.destination,actualResponse)==="blocked"){return makeNetworkError("blocked")}if(redirectStatusSet.has(actualResponse.status)){if(request.redirect!=="manual"){fetchParams.controller.connection.destroy(void 0,false)}if(request.redirect==="error"){response=makeNetworkError("unexpected redirect")}else if(request.redirect==="manual"){response=actualResponse}else if(request.redirect==="follow"){response=await httpRedirectFetch(fetchParams,response)}else{assert(false)}}response.timingInfo=timingInfo;return response}function httpRedirectFetch(fetchParams,response){const request=fetchParams.request;const actualResponse=response.internalResponse?response.internalResponse:response;let locationURL;try{locationURL=responseLocationURL(actualResponse,requestCurrentURL(request).hash);if(locationURL==null){return response}}catch(err){return Promise.resolve(makeNetworkError(err))}if(!urlIsHttpHttpsScheme(locationURL)){return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"))}if(request.redirectCount===20){return Promise.resolve(makeNetworkError("redirect count exceeded"))}request.redirectCount+=1;if(request.mode==="cors"&&(locationURL.username||locationURL.password)&&!sameOrigin(request,locationURL)){return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))}if(request.responseTainting==="cors"&&(locationURL.username||locationURL.password)){return Promise.resolve(makeNetworkError('URL cannot contain credentials for request mode "cors"'))}if(actualResponse.status!==303&&request.body!=null&&request.body.source==null){return Promise.resolve(makeNetworkError())}if([301,302].includes(actualResponse.status)&&request.method==="POST"||actualResponse.status===303&&!GET_OR_HEAD.includes(request.method)){request.method="GET";request.body=null;for(const headerName of requestBodyHeader){request.headersList.delete(headerName)}}if(!sameOrigin(requestCurrentURL(request),locationURL)){request.headersList.delete("authorization",true);request.headersList.delete("proxy-authorization",true);request.headersList.delete("cookie",true);request.headersList.delete("host",true)}if(request.body!=null){assert(request.body.source!=null);request.body=safelyExtractBody(request.body.source)[0]}const timingInfo=fetchParams.timingInfo;timingInfo.redirectEndTime=timingInfo.postRedirectStartTime=coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);if(timingInfo.redirectStartTime===0){timingInfo.redirectStartTime=timingInfo.startTime}request.urlList.push(locationURL);setRequestReferrerPolicyOnRedirect(request,actualResponse);return mainFetch(fetchParams,true)}async function httpNetworkOrCacheFetch(fetchParams,isAuthenticationFetch=false,isNewConnectionFetch=false){const request=fetchParams.request;let httpFetchParams=null;let httpRequest=null;let response=null;const httpCache=null;const revalidatingFlag=false;if(request.window==="no-window"&&request.redirect==="error"){httpFetchParams=fetchParams;httpRequest=request}else{httpRequest=cloneRequest(request);httpFetchParams={...fetchParams};httpFetchParams.request=httpRequest}const includeCredentials=request.credentials==="include"||request.credentials==="same-origin"&&request.responseTainting==="basic";const contentLength=httpRequest.body?httpRequest.body.length:null;let contentLengthHeaderValue=null;if(httpRequest.body==null&&["POST","PUT"].includes(httpRequest.method)){contentLengthHeaderValue="0"}if(contentLength!=null){contentLengthHeaderValue=isomorphicEncode(`${contentLength}`)}if(contentLengthHeaderValue!=null&&!httpRequest.headersList.contains("content-length",true)){httpRequest.headersList.append("content-length",contentLengthHeaderValue,true)}if(contentLength!=null&&httpRequest.keepalive){}if(webidl.is.URL(httpRequest.referrer)){httpRequest.headersList.append("referer",isomorphicEncode(httpRequest.referrer.href),true)}appendRequestOriginHeader(httpRequest);appendFetchMetadata(httpRequest);if(!httpRequest.headersList.contains("user-agent",true)){httpRequest.headersList.append("user-agent",defaultUserAgent,true)}if(httpRequest.cache==="default"&&(httpRequest.headersList.contains("if-modified-since",true)||httpRequest.headersList.contains("if-none-match",true)||httpRequest.headersList.contains("if-unmodified-since",true)||httpRequest.headersList.contains("if-match",true)||httpRequest.headersList.contains("if-range",true))){httpRequest.cache="no-store"}if(httpRequest.cache==="no-cache"&&!httpRequest.preventNoCacheCacheControlHeaderModification&&!httpRequest.headersList.contains("cache-control",true)){httpRequest.headersList.append("cache-control","max-age=0",true)}if(httpRequest.cache==="no-store"||httpRequest.cache==="reload"){if(!httpRequest.headersList.contains("pragma",true)){httpRequest.headersList.append("pragma","no-cache",true)}if(!httpRequest.headersList.contains("cache-control",true)){httpRequest.headersList.append("cache-control","no-cache",true)}}if(httpRequest.headersList.contains("range",true)){httpRequest.headersList.append("accept-encoding","identity",true)}if(!httpRequest.headersList.contains("accept-encoding",true)){if(urlHasHttpsScheme(requestCurrentURL(httpRequest))){httpRequest.headersList.append("accept-encoding","br, gzip, deflate",true)}else{httpRequest.headersList.append("accept-encoding","gzip, deflate",true)}}httpRequest.headersList.delete("host",true);if(includeCredentials){if(!httpRequest.headersList.contains("authorization",true)){let authorizationValue=null;if(hasAuthenticationEntry(httpRequest)&&(httpRequest.useURLCredentials===void 0||!includesCredentials(requestCurrentURL(httpRequest)))){}else if(includesCredentials(requestCurrentURL(httpRequest))&&isAuthenticationFetch){const{username,password}=requestCurrentURL(httpRequest);authorizationValue=`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`}if(authorizationValue!==null){httpRequest.headersList.append("Authorization",authorizationValue,false)}}}if(httpCache==null){httpRequest.cache="no-store"}if(httpRequest.cache!=="no-store"&&httpRequest.cache!=="reload"){}if(response==null){if(httpRequest.cache==="only-if-cached"){return makeNetworkError("only if cached")}const forwardResponse=await httpNetworkFetch(httpFetchParams,includeCredentials,isNewConnectionFetch);if(!safeMethodsSet.has(httpRequest.method)&&forwardResponse.status>=200&&forwardResponse.status<=399){}if(revalidatingFlag&&forwardResponse.status===304){}if(response==null){response=forwardResponse}}response.urlList=[...httpRequest.urlList];if(httpRequest.headersList.contains("range",true)){response.rangeRequested=true}response.requestIncludesCredentials=includeCredentials;if(response.status===401&&httpRequest.responseTainting!=="cors"&&includeCredentials&&(request.useURLCredentials!==void 0||isTraversableNavigable(request.traversableForUserPrompts))){if(request.body!=null){if(request.body.source==null){return response}request.body=safelyExtractBody(request.body.source)[0]}if(request.useURLCredentials===void 0||isAuthenticationFetch){if(isCancelled(fetchParams)){return makeAppropriateNetworkError(fetchParams)}return response}fetchParams.controller.connection.destroy();response=await httpNetworkOrCacheFetch(fetchParams,true)}if(response.status===407){if(request.window==="no-window"){return makeNetworkError()}if(isCancelled(fetchParams)){return makeAppropriateNetworkError(fetchParams)}return makeNetworkError("proxy authentication required")}if(response.status===421&&!isNewConnectionFetch&&(request.body==null||request.body.source!=null)){if(isCancelled(fetchParams)){return makeAppropriateNetworkError(fetchParams)}fetchParams.controller.connection.destroy();response=await httpNetworkOrCacheFetch(fetchParams,isAuthenticationFetch,true)}if(isAuthenticationFetch){}return response}async function httpNetworkFetch(fetchParams,includeCredentials=false,forceNewConnection=false){assert(!fetchParams.controller.connection||fetchParams.controller.connection.destroyed);fetchParams.controller.connection={abort:null,destroyed:false,destroy(err,abort=true){if(!this.destroyed){this.destroyed=true;if(abort){this.abort?.(err??new DOMException("The operation was aborted.","AbortError"))}}}};const request=fetchParams.request;let response=null;const timingInfo=fetchParams.timingInfo;const httpCache=null;if(httpCache==null){request.cache="no-store"}const newConnection=forceNewConnection?"yes":"no";if(request.mode==="websocket"){}else{}let requestBody=null;if(request.body==null&&fetchParams.processRequestEndOfBody){queueMicrotask(()=>fetchParams.processRequestEndOfBody())}else if(request.body!=null){const processBodyChunk=async function*(bytes){if(isCancelled(fetchParams)){return}yield bytes;fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)};const processEndOfBody=()=>{if(isCancelled(fetchParams)){return}if(fetchParams.processRequestEndOfBody){fetchParams.processRequestEndOfBody()}};const processBodyError=e=>{if(isCancelled(fetchParams)){return}if(e.name==="AbortError"){fetchParams.controller.abort()}else{fetchParams.controller.terminate(e)}};requestBody=(async function*(){try{for await(const bytes of request.body.stream){yield*processBodyChunk(bytes)}processEndOfBody()}catch(err){processBodyError(err)}})()}try{const{body,status,statusText,headersList,socket}=await dispatch({body:requestBody});if(socket){response=makeResponse({status,statusText,headersList,socket})}else{const iterator=body[Symbol.asyncIterator]();fetchParams.controller.next=()=>iterator.next();response=makeResponse({status,statusText,headersList})}}catch(err){if(err.name==="AbortError"){fetchParams.controller.connection.destroy();return makeAppropriateNetworkError(fetchParams,err)}return makeNetworkError(err)}const pullAlgorithm=()=>{return fetchParams.controller.resume()};const cancelAlgorithm=reason=>{if(!isCancelled(fetchParams)){fetchParams.controller.abort(reason)}};const stream2=new ReadableStream({start(controller){fetchParams.controller.controller=controller},pull:pullAlgorithm,cancel:cancelAlgorithm,type:"bytes"});response.body={stream:stream2,source:null,length:null};if(!fetchParams.controller.resume){fetchParams.controller.on("terminated",onAborted)}fetchParams.controller.resume=async()=>{while(true){let bytes;let isFailure;try{const{done,value}=await fetchParams.controller.next();if(isAborted(fetchParams)){break}bytes=done?void 0:value}catch(err){if(fetchParams.controller.ended&&!timingInfo.encodedBodySize){bytes=void 0}else{bytes=err;isFailure=true}}if(bytes===void 0){readableStreamClose(fetchParams.controller.controller);finalizeResponse(fetchParams,response);return}timingInfo.decodedBodySize+=bytes?.byteLength??0;if(isFailure){fetchParams.controller.terminate(bytes);return}const buffer=new Uint8Array(bytes);if(buffer.byteLength){fetchParams.controller.controller.enqueue(buffer)}if(isErrored(stream2)){fetchParams.controller.terminate();return}if(fetchParams.controller.controller.desiredSize<=0){return}}};function onAborted(reason){if(isAborted(fetchParams)){response.aborted=true;if(isReadable(stream2)){fetchParams.controller.controller.error(fetchParams.controller.serializedAbortReason)}}else{if(isReadable(stream2)){fetchParams.controller.controller.error(new TypeError("terminated",{cause:isErrorLike(reason)?reason:void 0}))}}fetchParams.controller.connection.destroy()}return response;function dispatch({body}){const url=requestCurrentURL(request);const agent=fetchParams.controller.dispatcher;const path29=url.pathname+url.search;const hasTrailingQuestionMark=url.search.length===0&&url.href[url.href.length-url.hash.length-1]==="?";return new Promise((resolve,reject)=>agent.dispatch({path:hasTrailingQuestionMark?`${path29}?`:path29,origin:url.origin,method:request.method,body:agent.isMockActive?request.body&&(request.body.source||request.body.stream):body,headers:request.headersList.entries,maxRedirections:0,upgrade:request.mode==="websocket"?"websocket":void 0},{body:null,abort:null,onConnect(abort){const{connection}=fetchParams.controller;timingInfo.finalConnectionTimingInfo=clampAndCoarsenConnectionTimingInfo(void 0,timingInfo.postRedirectStartTime,fetchParams.crossOriginIsolatedCapability);if(connection.destroyed){abort(new DOMException("The operation was aborted.","AbortError"))}else{fetchParams.controller.on("terminated",abort);this.abort=connection.abort=abort}timingInfo.finalNetworkRequestStartTime=coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)},onResponseStarted(){timingInfo.finalNetworkResponseStartTime=coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)},onHeaders(status,rawHeaders,resume,statusText){if(status<200){return false}const headersList=new HeadersList;for(let i=0;i<rawHeaders.length;i+=2){const nameStr=bufferToLowerCasedHeaderName(rawHeaders[i]);const value=rawHeaders[i+1];if(Array.isArray(value)&&!Buffer.isBuffer(rawHeaders[i+1])){for(const val of value){headersList.append(nameStr,val.toString("latin1"),true)}}else{headersList.append(nameStr,value.toString("latin1"),true)}}const location=headersList.get("location",true);this.body=new Readable({read:resume});const willFollow=location&&request.redirect==="follow"&&redirectStatusSet.has(status);const decoders=[];if(request.method!=="HEAD"&&request.method!=="CONNECT"&&!nullBodyStatus.includes(status)&&!willFollow){const contentEncoding=headersList.get("content-encoding",true);const codings=contentEncoding?contentEncoding.toLowerCase().split(","):[];const maxContentEncodings=5;if(codings.length>maxContentEncodings){reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`));return true}for(let i=codings.length-1;i>=0;--i){const coding=codings[i].trim();if(coding==="x-gzip"||coding==="gzip"){decoders.push(zlib2.createGunzip({flush:zlib2.constants.Z_SYNC_FLUSH,finishFlush:zlib2.constants.Z_SYNC_FLUSH}))}else if(coding==="deflate"){decoders.push(createInflate({flush:zlib2.constants.Z_SYNC_FLUSH,finishFlush:zlib2.constants.Z_SYNC_FLUSH}))}else if(coding==="br"){decoders.push(zlib2.createBrotliDecompress({flush:zlib2.constants.BROTLI_OPERATION_FLUSH,finishFlush:zlib2.constants.BROTLI_OPERATION_FLUSH}))}else if(coding==="zstd"&&hasZstd){decoders.push(zlib2.createZstdDecompress({flush:zlib2.constants.ZSTD_e_continue,finishFlush:zlib2.constants.ZSTD_e_end}))}else{decoders.length=0;break}}}const onError=this.onError.bind(this);resolve({status,statusText,headersList,body:decoders.length?pipeline(this.body,...decoders,err=>{if(err){this.onError(err)}}).on("error",onError):this.body.on("error",onError)});return true},onData(chunk){if(fetchParams.controller.dump){return}const bytes=chunk;timingInfo.encodedBodySize+=bytes.byteLength;return this.body.push(bytes)},onComplete(){if(this.abort){fetchParams.controller.off("terminated",this.abort)}fetchParams.controller.ended=true;this.body.push(null)},onError(error){if(this.abort){fetchParams.controller.off("terminated",this.abort)}this.body?.destroy(error);fetchParams.controller.terminate(error);reject(error)},onRequestUpgrade(_controller,status,headers,socket){if(socket.session!=null&&status!==200||socket.session==null&&status!==101){return false}const headersList=new HeadersList;for(const[name2,value]of Object.entries(headers)){if(value==null){continue}const headerName=name2.toLowerCase();if(Array.isArray(value)){for(const entry of value){headersList.append(headerName,String(entry),true)}}else{headersList.append(headerName,String(value),true)}}resolve({status,statusText:STATUS_CODES[status],headersList,socket});return true},onUpgrade(status,rawHeaders,socket){if(socket.session!=null&&status!==200||socket.session==null&&status!==101){return false}const headersList=new HeadersList;for(let i=0;i<rawHeaders.length;i+=2){const nameStr=bufferToLowerCasedHeaderName(rawHeaders[i]);const value=rawHeaders[i+1];if(Array.isArray(value)&&!Buffer.isBuffer(rawHeaders[i+1])){for(const val of value){headersList.append(nameStr,val.toString("latin1"),true)}}else{headersList.append(nameStr,value.toString("latin1"),true)}}resolve({status,statusText:STATUS_CODES[status],headersList,socket});return true}}))}}module.exports={fetch:fetch2,Fetch,fetching,finalizeAndReportTiming}}});var require_util4=__commonJS({"node_modules/undici/lib/web/cache/util.js"(exports,module){"use strict";var assert=__require("assert");var{URLSerializer}=require_data_url();var{isValidHeaderName}=require_util3();function urlEquals(A2,B2,excludeFragment=false){const serializedA=URLSerializer(A2,excludeFragment);const serializedB=URLSerializer(B2,excludeFragment);return serializedA===serializedB}function getFieldValues(header){assert(header!==null);const values=[];for(let value of header.split(",")){value=value.trim();if(isValidHeaderName(value)){values.push(value)}}return values}module.exports={urlEquals,getFieldValues}}});var require_cache3=__commonJS({"node_modules/undici/lib/web/cache/cache.js"(exports,module){"use strict";var assert=__require("assert");var{kConstruct}=require_symbols();var{urlEquals,getFieldValues}=require_util4();var{kEnumerableProperty,isDisturbed}=require_util2();var{webidl}=require_webidl();var{cloneResponse,fromInnerResponse,getResponseState}=require_response();var{Request:Request2,fromInnerRequest,getRequestState}=require_request2();var{fetching}=require_fetch();var{urlIsHttpHttpsScheme,readAllBytes}=require_util3();var{createDeferredPromise}=require_promise();var Cache=class _Cache{#relevantRequestResponseList;constructor(){if(arguments[0]!==kConstruct){webidl.illegalConstructor()}webidl.util.markAsUncloneable(this);this.#relevantRequestResponseList=arguments[1]}async match(request,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.match";webidl.argumentLengthCheck(arguments,1,prefix);request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");const p2=this.#internalMatchAll(request,options,1);if(p2.length===0){return}return p2[0]}async matchAll(request=void 0,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.matchAll";if(request!==void 0)request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");return this.#internalMatchAll(request,options)}async add(request){webidl.brandCheck(this,_Cache);const prefix="Cache.add";webidl.argumentLengthCheck(arguments,1,prefix);request=webidl.converters.RequestInfo(request);const requests=[request];const responseArrayPromise=this.addAll(requests);return await responseArrayPromise}async addAll(requests){webidl.brandCheck(this,_Cache);const prefix="Cache.addAll";webidl.argumentLengthCheck(arguments,1,prefix);const responsePromises=[];const requestList=[];for(let request of requests){if(request===void 0){throw webidl.errors.conversionFailed({prefix,argument:"Argument 1",types:["undefined is not allowed"]})}request=webidl.converters.RequestInfo(request);if(typeof request==="string"){continue}const r=getRequestState(request);if(!urlIsHttpHttpsScheme(r.url)||r.method!=="GET"){throw webidl.errors.exception({header:prefix,message:"Expected http/s scheme when method is not GET."})}}const fetchControllers=[];for(const request of requests){const r=getRequestState(new Request2(request));if(!urlIsHttpHttpsScheme(r.url)){throw webidl.errors.exception({header:prefix,message:"Expected http/s scheme."})}r.initiator="fetch";r.destination="subresource";requestList.push(r);const responsePromise=createDeferredPromise();fetchControllers.push(fetching({request:r,processResponse(response){if(response.type==="error"||response.status===206||response.status<200||response.status>299){responsePromise.reject(webidl.errors.exception({header:"Cache.addAll",message:"Received an invalid status code or the request failed."}))}else if(response.headersList.contains("vary")){const fieldValues=getFieldValues(response.headersList.get("vary"));for(const fieldValue of fieldValues){if(fieldValue==="*"){responsePromise.reject(webidl.errors.exception({header:"Cache.addAll",message:"invalid vary field value"}));for(const controller of fetchControllers){controller.abort()}return}}}},processResponseEndOfBody(response){if(response.aborted){responsePromise.reject(new DOMException("aborted","AbortError"));return}responsePromise.resolve(response)}}));responsePromises.push(responsePromise.promise)}const p2=Promise.all(responsePromises);const responses=await p2;const operations=[];let index=0;for(const response of responses){const operation={type:"put",request:requestList[index],response};operations.push(operation);index++}const cacheJobPromise=createDeferredPromise();let errorData=null;try{this.#batchCacheOperations(operations)}catch(e){errorData=e}queueMicrotask(()=>{if(errorData===null){cacheJobPromise.resolve(void 0)}else{cacheJobPromise.reject(errorData)}});return cacheJobPromise.promise}async put(request,response){webidl.brandCheck(this,_Cache);const prefix="Cache.put";webidl.argumentLengthCheck(arguments,2,prefix);request=webidl.converters.RequestInfo(request);response=webidl.converters.Response(response,prefix,"response");let innerRequest=null;if(webidl.is.Request(request)){innerRequest=getRequestState(request)}else{innerRequest=getRequestState(new Request2(request))}if(!urlIsHttpHttpsScheme(innerRequest.url)||innerRequest.method!=="GET"){throw webidl.errors.exception({header:prefix,message:"Expected an http/s scheme when method is not GET"})}const innerResponse=getResponseState(response);if(innerResponse.status===206){throw webidl.errors.exception({header:prefix,message:"Got 206 status"})}if(innerResponse.headersList.contains("vary")){const fieldValues=getFieldValues(innerResponse.headersList.get("vary"));for(const fieldValue of fieldValues){if(fieldValue==="*"){throw webidl.errors.exception({header:prefix,message:"Got * vary field value"})}}}if(innerResponse.body&&(isDisturbed(innerResponse.body.stream)||innerResponse.body.stream.locked)){throw webidl.errors.exception({header:prefix,message:"Response body is locked or disturbed"})}const clonedResponse=cloneResponse(innerResponse);const bodyReadPromise=createDeferredPromise();if(innerResponse.body!=null){const stream2=innerResponse.body.stream;const reader=stream2.getReader();readAllBytes(reader,bodyReadPromise.resolve,bodyReadPromise.reject)}else{bodyReadPromise.resolve(void 0)}const operations=[];const operation={type:"put",request:innerRequest,response:clonedResponse};operations.push(operation);const bytes=await bodyReadPromise.promise;if(clonedResponse.body!=null){clonedResponse.body.source=bytes}const cacheJobPromise=createDeferredPromise();let errorData=null;try{this.#batchCacheOperations(operations)}catch(e){errorData=e}queueMicrotask(()=>{if(errorData===null){cacheJobPromise.resolve()}else{cacheJobPromise.reject(errorData)}});return cacheJobPromise.promise}async delete(request,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.delete";webidl.argumentLengthCheck(arguments,1,prefix);request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");let r=null;if(webidl.is.Request(request)){r=getRequestState(request);if(r.method!=="GET"&&!options.ignoreMethod){return false}}else{assert(typeof request==="string");r=getRequestState(new Request2(request))}const operations=[];const operation={type:"delete",request:r,options};operations.push(operation);const cacheJobPromise=createDeferredPromise();let errorData=null;let requestResponses;try{requestResponses=this.#batchCacheOperations(operations)}catch(e){errorData=e}queueMicrotask(()=>{if(errorData===null){cacheJobPromise.resolve(!!requestResponses?.length)}else{cacheJobPromise.reject(errorData)}});return cacheJobPromise.promise}async keys(request=void 0,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.keys";if(request!==void 0)request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");let r=null;if(request!==void 0){if(webidl.is.Request(request)){r=getRequestState(request);if(r.method!=="GET"&&!options.ignoreMethod){return[]}}else if(typeof request==="string"){r=getRequestState(new Request2(request))}}const promise=createDeferredPromise();const requests=[];if(request===void 0){for(const requestResponse of this.#relevantRequestResponseList){requests.push(requestResponse[0])}}else{const requestResponses=this.#queryCache(r,options);for(const requestResponse of requestResponses){requests.push(requestResponse[0])}}queueMicrotask(()=>{const requestList=[];for(const request2 of requests){const requestObject=fromInnerRequest(request2,void 0,new AbortController().signal,"immutable");requestList.push(requestObject)}promise.resolve(Object.freeze(requestList))});return promise.promise}#batchCacheOperations(operations){const cache2=this.#relevantRequestResponseList;const backupCache=[...cache2];const addedItems=[];const resultList=[];try{for(const operation of operations){if(operation.type!=="delete"&&operation.type!=="put"){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:'operation type does not match "delete" or "put"'})}if(operation.type==="delete"&&operation.response!=null){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"delete operation should not have an associated response"})}if(this.#queryCache(operation.request,operation.options,addedItems).length){throw new DOMException("???","InvalidStateError")}let requestResponses;if(operation.type==="delete"){requestResponses=this.#queryCache(operation.request,operation.options);if(requestResponses.length===0){return[]}for(const requestResponse of requestResponses){const idx=cache2.indexOf(requestResponse);assert(idx!==-1);cache2.splice(idx,1)}}else if(operation.type==="put"){if(operation.response==null){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"put operation should have an associated response"})}const r=operation.request;if(!urlIsHttpHttpsScheme(r.url)){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"expected http or https scheme"})}if(r.method!=="GET"){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"not get method"})}if(operation.options!=null){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"options must not be defined"})}requestResponses=this.#queryCache(operation.request);for(const requestResponse of requestResponses){const idx=cache2.indexOf(requestResponse);assert(idx!==-1);cache2.splice(idx,1)}cache2.push([operation.request,operation.response]);addedItems.push([operation.request,operation.response])}resultList.push([operation.request,operation.response])}return resultList}catch(e){this.#relevantRequestResponseList.length=0;this.#relevantRequestResponseList=backupCache;throw e}}#queryCache(requestQuery,options,targetStorage){const resultList=[];const storage=targetStorage??this.#relevantRequestResponseList;for(const requestResponse of storage){const[cachedRequest,cachedResponse]=requestResponse;if(this.#requestMatchesCachedItem(requestQuery,cachedRequest,cachedResponse,options)){resultList.push(requestResponse)}}return resultList}#requestMatchesCachedItem(requestQuery,request,response=null,options){const queryURL=new URL(requestQuery.url);const cachedURL=new URL(request.url);if(options?.ignoreSearch){cachedURL.search="";queryURL.search=""}if(!urlEquals(queryURL,cachedURL,true)){return false}if(response==null||options?.ignoreVary||!response.headersList.contains("vary")){return true}const fieldValues=getFieldValues(response.headersList.get("vary"));for(const fieldValue of fieldValues){if(fieldValue==="*"){return false}const requestValue=request.headersList.get(fieldValue);const queryValue=requestQuery.headersList.get(fieldValue);if(requestValue!==queryValue){return false}}return true}#internalMatchAll(request,options,maxResponses=Infinity){let r=null;if(request!==void 0){if(webidl.is.Request(request)){r=getRequestState(request);if(r.method!=="GET"&&!options.ignoreMethod){return[]}}else if(typeof request==="string"){r=getRequestState(new Request2(request))}}const responses=[];if(request===void 0){for(const requestResponse of this.#relevantRequestResponseList){responses.push(requestResponse[1])}}else{const requestResponses=this.#queryCache(r,options);for(const requestResponse of requestResponses){responses.push(requestResponse[1])}}const responseList=[];for(const response of responses){const responseObject=fromInnerResponse(cloneResponse(response),"immutable");responseList.push(responseObject);if(responseList.length>=maxResponses){break}}return Object.freeze(responseList)}};Object.defineProperties(Cache.prototype,{[Symbol.toStringTag]:{value:"Cache",configurable:true},match:kEnumerableProperty,matchAll:kEnumerableProperty,add:kEnumerableProperty,addAll:kEnumerableProperty,put:kEnumerableProperty,delete:kEnumerableProperty,keys:kEnumerableProperty});var cacheQueryOptionConverters=[{key:"ignoreSearch",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"ignoreMethod",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"ignoreVary",converter:webidl.converters.boolean,defaultValue:()=>false}];webidl.converters.CacheQueryOptions=webidl.dictionaryConverter(cacheQueryOptionConverters);webidl.converters.MultiCacheQueryOptions=webidl.dictionaryConverter([...cacheQueryOptionConverters,{key:"cacheName",converter:webidl.converters.DOMString}]);webidl.converters.Response=webidl.interfaceConverter(webidl.is.Response,"Response");webidl.converters["sequence<RequestInfo>"]=webidl.sequenceConverter(webidl.converters.RequestInfo);module.exports={Cache}}});var require_cachestorage=__commonJS({"node_modules/undici/lib/web/cache/cachestorage.js"(exports,module){"use strict";var{Cache}=require_cache3();var{webidl}=require_webidl();var{kEnumerableProperty}=require_util2();var{kConstruct}=require_symbols();var CacheStorage=class _CacheStorage{#caches=new Map;constructor(){if(arguments[0]!==kConstruct){webidl.illegalConstructor()}webidl.util.markAsUncloneable(this)}async match(request,options={}){webidl.brandCheck(this,_CacheStorage);webidl.argumentLengthCheck(arguments,1,"CacheStorage.match");request=webidl.converters.RequestInfo(request);options=webidl.converters.MultiCacheQueryOptions(options);if(options.cacheName!=null){if(this.#caches.has(options.cacheName)){const cacheList=this.#caches.get(options.cacheName);const cache2=new Cache(kConstruct,cacheList);return await cache2.match(request,options)}}else{for(const cacheList of this.#caches.values()){const cache2=new Cache(kConstruct,cacheList);const response=await cache2.match(request,options);if(response!==void 0){return response}}}}async has(cacheName){webidl.brandCheck(this,_CacheStorage);const prefix="CacheStorage.has";webidl.argumentLengthCheck(arguments,1,prefix);cacheName=webidl.converters.DOMString(cacheName,prefix,"cacheName");return this.#caches.has(cacheName)}async open(cacheName){webidl.brandCheck(this,_CacheStorage);const prefix="CacheStorage.open";webidl.argumentLengthCheck(arguments,1,prefix);cacheName=webidl.converters.DOMString(cacheName,prefix,"cacheName");if(this.#caches.has(cacheName)){const cache3=this.#caches.get(cacheName);return new Cache(kConstruct,cache3)}const cache2=[];this.#caches.set(cacheName,cache2);return new Cache(kConstruct,cache2)}async delete(cacheName){webidl.brandCheck(this,_CacheStorage);const prefix="CacheStorage.delete";webidl.argumentLengthCheck(arguments,1,prefix);cacheName=webidl.converters.DOMString(cacheName,prefix,"cacheName");return this.#caches.delete(cacheName)}async keys(){webidl.brandCheck(this,_CacheStorage);const keys=this.#caches.keys();return[...keys]}};Object.defineProperties(CacheStorage.prototype,{[Symbol.toStringTag]:{value:"CacheStorage",configurable:true},match:kEnumerableProperty,has:kEnumerableProperty,open:kEnumerableProperty,delete:kEnumerableProperty,keys:kEnumerableProperty});module.exports={CacheStorage}}});var require_constants4=__commonJS({"node_modules/undici/lib/web/cookies/constants.js"(exports,module){"use strict";var maxAttributeValueSize=1024;var maxNameValuePairSize=4096;module.exports={maxAttributeValueSize,maxNameValuePairSize}}});var require_util5=__commonJS({"node_modules/undici/lib/web/cookies/util.js"(exports,module){"use strict";function isCTLExcludingHtab(value){for(let i=0;i<value.length;++i){const code=value.charCodeAt(i);if(code>=0&&code<=8||code>=10&&code<=31||code===127){return true}}return false}function validateCookieName(name2){for(let i=0;i<name2.length;++i){const code=name2.charCodeAt(i);if(code<33||code>126||code===34||code===40||code===41||code===60||code===62||code===64||code===44||code===59||code===58||code===92||code===47||code===91||code===93||code===63||code===61||code===123||code===125){throw new Error("Invalid cookie name")}}}function validateCookieValue(value){let len=value.length;let i=0;if(value[0]==='"'){if(len===1||value[len-1]!=='"'){throw new Error("Invalid cookie value")}--len;++i}while(i<len){const code=value.charCodeAt(i++);if(code<33||code>126||code===34||code===44||code===59||code===92){throw new Error("Invalid cookie value")}}}function validateCookiePath(path29){for(let i=0;i<path29.length;++i){const code=path29.charCodeAt(i);if(code<32||code>126||code===59){throw new Error("Invalid cookie path")}}}function isLetterOrDigit(code){return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122}function validateCookieDomain(domain){if(domain===" "){return}if(domain.length>255){throw new Error("Invalid cookie domain")}let labelLength=0;for(let i=0;i<domain.length;++i){const code=domain.charCodeAt(i);if(code===46){if(labelLength===0){throw new Error("Invalid cookie domain")}if(domain.charCodeAt(i-1)===45){throw new Error("Invalid cookie domain")}labelLength=0;continue}if(labelLength===0&&!isLetterOrDigit(code)){throw new Error("Invalid cookie domain")}if(!isLetterOrDigit(code)&&code!==45){throw new Error("Invalid cookie domain")}if(++labelLength>63){throw new Error("Invalid cookie domain")}}if(labelLength===0||domain.charCodeAt(domain.length-1)===45){throw new Error("Invalid cookie domain")}}var IMFDays=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var IMFMonths=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var IMFPaddedNumbers=Array(61).fill(0).map((_2,i)=>i.toString().padStart(2,"0"));function toIMFDate(date){if(typeof date==="number"){date=new Date(date)}return`${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`}function validateCookieMaxAge(maxAge){if(maxAge<0){throw new Error("Invalid cookie max-age")}}function stringify(cookie){if(cookie.name.length===0){return null}validateCookieName(cookie.name);validateCookieValue(cookie.value);const out=[`${cookie.name}=${cookie.value}`];if(cookie.name.startsWith("__Secure-")){cookie.secure=true}if(cookie.name.startsWith("__Host-")){cookie.secure=true;cookie.domain=null;cookie.path="/"}if(cookie.secure){out.push("Secure")}if(cookie.httpOnly){out.push("HttpOnly")}if(typeof cookie.maxAge==="number"){validateCookieMaxAge(cookie.maxAge);out.push(`Max-Age=${cookie.maxAge}`)}if(cookie.domain){validateCookieDomain(cookie.domain);out.push(`Domain=${cookie.domain}`)}if(cookie.path){validateCookiePath(cookie.path);out.push(`Path=${cookie.path}`)}if(cookie.expires&&cookie.expires.toString()!=="Invalid Date"){out.push(`Expires=${toIMFDate(cookie.expires)}`)}if(cookie.sameSite){out.push(`SameSite=${cookie.sameSite}`)}for(const part of cookie.unparsed){if(!part.includes("=")){throw new Error("Invalid unparsed")}const[key,...value]=part.split("=");const trimmedKey=key.trim();const joinedValue=value.join("=");validateCookieName(trimmedKey);validateCookieValue(joinedValue);out.push(`${trimmedKey}=${joinedValue}`)}return out.join("; ")}module.exports={isCTLExcludingHtab,validateCookieName,validateCookiePath,validateCookieValue,toIMFDate,stringify}}});var require_parse=__commonJS({"node_modules/undici/lib/web/cookies/parse.js"(exports,module){"use strict";var{collectASequenceOfCodePointsFast}=require_infra();var{maxNameValuePairSize,maxAttributeValueSize}=require_constants4();var{isCTLExcludingHtab}=require_util5();var assert=__require("assert");function parseSetCookie(header){if(isCTLExcludingHtab(header)){return null}let nameValuePair="";let unparsedAttributes="";let name2="";let value="";if(header.includes(";")){const position={position:0};nameValuePair=collectASequenceOfCodePointsFast(";",header,position);unparsedAttributes=header.slice(position.position)}else{nameValuePair=header}if(!nameValuePair.includes("=")){value=nameValuePair}else{const position={position:0};name2=collectASequenceOfCodePointsFast("=",nameValuePair,position);value=nameValuePair.slice(position.position+1)}name2=name2.trim();value=value.trim();if(name2.length+value.length>maxNameValuePairSize){return null}return{name:name2,value,...parseUnparsedAttributes(unparsedAttributes)}}function parseUnparsedAttributes(unparsedAttributes,cookieAttributeList={}){if(unparsedAttributes.length===0){return cookieAttributeList}assert(unparsedAttributes[0]===";");unparsedAttributes=unparsedAttributes.slice(1);let cookieAv="";if(unparsedAttributes.includes(";")){cookieAv=collectASequenceOfCodePointsFast(";",unparsedAttributes,{position:0});unparsedAttributes=unparsedAttributes.slice(cookieAv.length)}else{cookieAv=unparsedAttributes;unparsedAttributes=""}let attributeName="";let attributeValue="";if(cookieAv.includes("=")){const position={position:0};attributeName=collectASequenceOfCodePointsFast("=",cookieAv,position);attributeValue=cookieAv.slice(position.position+1)}else{attributeName=cookieAv}attributeName=attributeName.trim();attributeValue=attributeValue.trim();if(attributeValue.length>maxAttributeValueSize){return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}const attributeNameLowercase=attributeName.toLowerCase();if(attributeNameLowercase==="expires"){const expiryTime=new Date(attributeValue);cookieAttributeList.expires=expiryTime}else if(attributeNameLowercase==="max-age"){const charCode=attributeValue.charCodeAt(0);if((charCode<48||charCode>57)&&attributeValue[0]!=="-"){return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}if(!/^\d+$/.test(attributeValue)){return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}const deltaSeconds=Number(attributeValue);cookieAttributeList.maxAge=deltaSeconds}else if(attributeNameLowercase==="domain"){let cookieDomain=attributeValue;if(cookieDomain[0]==="."){cookieDomain=cookieDomain.slice(1)}cookieDomain=cookieDomain.toLowerCase();cookieAttributeList.domain=cookieDomain}else if(attributeNameLowercase==="path"){let cookiePath="";if(attributeValue.length===0||attributeValue[0]!=="/"){cookiePath="/"}else{cookiePath=attributeValue}cookieAttributeList.path=cookiePath}else if(attributeNameLowercase==="secure"){cookieAttributeList.secure=true}else if(attributeNameLowercase==="httponly"){cookieAttributeList.httpOnly=true}else if(attributeNameLowercase==="samesite"){const attributeValueLowercase=attributeValue.toLowerCase();if(attributeValueLowercase==="none"){cookieAttributeList.sameSite="None"}else if(attributeValueLowercase==="strict"){cookieAttributeList.sameSite="Strict"}else if(attributeValueLowercase==="lax"){cookieAttributeList.sameSite="Lax"}}else{cookieAttributeList.unparsed??=[];cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)}return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}module.exports={parseSetCookie,parseUnparsedAttributes}}});var require_cookies=__commonJS({"node_modules/undici/lib/web/cookies/index.js"(exports,module){"use strict";var{parseSetCookie}=require_parse();var{stringify}=require_util5();var{webidl}=require_webidl();var{Headers:Headers2}=require_headers();var brandChecks=webidl.brandCheckMultiple([Headers2,globalThis.Headers].filter(Boolean));function getCookies(headers){webidl.argumentLengthCheck(arguments,1,"getCookies");brandChecks(headers);const cookie=headers.get("cookie");const out={};if(!cookie){return out}for(const piece of cookie.split(";")){const[name2,...value]=piece.split("=");out[name2.trim()]=value.join("=")}return out}function deleteCookie(headers,name2,attributes){brandChecks(headers);const prefix="deleteCookie";webidl.argumentLengthCheck(arguments,2,prefix);name2=webidl.converters.DOMString(name2,prefix,"name");attributes=webidl.converters.DeleteCookieAttributes(attributes);setCookie(headers,{name:name2,value:"",expires:new Date(0),...attributes})}function getSetCookies(headers){webidl.argumentLengthCheck(arguments,1,"getSetCookies");brandChecks(headers);const cookies=headers.getSetCookie();if(!cookies){return[]}return cookies.map(pair=>parseSetCookie(pair))}function parseCookie(cookie){cookie=webidl.converters.DOMString(cookie);return parseSetCookie(cookie)}function setCookie(headers,cookie){webidl.argumentLengthCheck(arguments,2,"setCookie");brandChecks(headers);cookie=webidl.converters.Cookie(cookie);const str=stringify(cookie);if(str){headers.append("set-cookie",str,true)}}webidl.converters.DeleteCookieAttributes=webidl.dictionaryConverter([{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"path",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"domain",defaultValue:()=>null}]);webidl.converters.Cookie=webidl.dictionaryConverter([{converter:webidl.converters.DOMString,key:"name"},{converter:webidl.converters.DOMString,key:"value"},{converter:webidl.nullableConverter(value=>{if(typeof value==="number"){return webidl.converters["unsigned long long"](value)}return new Date(value)}),key:"expires",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters["long long"]),key:"maxAge",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"domain",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"path",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.boolean),key:"secure",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.boolean),key:"httpOnly",defaultValue:()=>null},{converter:webidl.converters.USVString,key:"sameSite",allowedValues:["Strict","Lax","None"]},{converter:webidl.sequenceConverter(webidl.converters.DOMString),key:"unparsed",defaultValue:()=>[]}]);module.exports={getCookies,deleteCookie,getSetCookies,setCookie,parseCookie}}});var require_events=__commonJS({"node_modules/undici/lib/web/websocket/events.js"(exports,module){"use strict";var{webidl}=require_webidl();var{kEnumerableProperty}=require_util2();var{kConstruct}=require_symbols();var MessageEvent=class _MessageEvent extends Event{#eventInit;constructor(type,eventInitDict={}){if(type===kConstruct){super(arguments[1],arguments[2]);webidl.util.markAsUncloneable(this);return}const prefix="MessageEvent constructor";webidl.argumentLengthCheck(arguments,1,prefix);type=webidl.converters.DOMString(type,prefix,"type");eventInitDict=webidl.converters.MessageEventInit(eventInitDict,prefix,"eventInitDict");super(type,eventInitDict);this.#eventInit=eventInitDict;webidl.util.markAsUncloneable(this)}get data(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.data}get origin(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.origin}get lastEventId(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.lastEventId}get source(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.source}get ports(){webidl.brandCheck(this,_MessageEvent);if(!Object.isFrozen(this.#eventInit.ports)){Object.freeze(this.#eventInit.ports)}return this.#eventInit.ports}initMessageEvent(type,bubbles=false,cancelable=false,data=null,origin="",lastEventId="",source=null,ports=[]){webidl.brandCheck(this,_MessageEvent);webidl.argumentLengthCheck(arguments,1,"MessageEvent.initMessageEvent");return new _MessageEvent(type,{bubbles,cancelable,data,origin,lastEventId,source,ports})}static createFastMessageEvent(type,init){const messageEvent=new _MessageEvent(kConstruct,type,init);messageEvent.#eventInit=init;messageEvent.#eventInit.data??=null;messageEvent.#eventInit.origin??="";messageEvent.#eventInit.lastEventId??="";messageEvent.#eventInit.source??=null;messageEvent.#eventInit.ports??=[];return messageEvent}};var{createFastMessageEvent}=MessageEvent;delete MessageEvent.createFastMessageEvent;var CloseEvent=class _CloseEvent extends Event{#eventInit;constructor(type,eventInitDict={}){const prefix="CloseEvent constructor";webidl.argumentLengthCheck(arguments,1,prefix);type=webidl.converters.DOMString(type,prefix,"type");eventInitDict=webidl.converters.CloseEventInit(eventInitDict);super(type,eventInitDict);this.#eventInit=eventInitDict;webidl.util.markAsUncloneable(this)}get wasClean(){webidl.brandCheck(this,_CloseEvent);return this.#eventInit.wasClean}get code(){webidl.brandCheck(this,_CloseEvent);return this.#eventInit.code}get reason(){webidl.brandCheck(this,_CloseEvent);return this.#eventInit.reason}};var ErrorEvent=class _ErrorEvent extends Event{#eventInit;constructor(type,eventInitDict){const prefix="ErrorEvent constructor";webidl.argumentLengthCheck(arguments,1,prefix);super(type,eventInitDict);webidl.util.markAsUncloneable(this);type=webidl.converters.DOMString(type,prefix,"type");eventInitDict=webidl.converters.ErrorEventInit(eventInitDict??{});this.#eventInit=eventInitDict}get message(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.message}get filename(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.filename}get lineno(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.lineno}get colno(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.colno}get error(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.error}};Object.defineProperties(MessageEvent.prototype,{[Symbol.toStringTag]:{value:"MessageEvent",configurable:true},data:kEnumerableProperty,origin:kEnumerableProperty,lastEventId:kEnumerableProperty,source:kEnumerableProperty,ports:kEnumerableProperty,initMessageEvent:kEnumerableProperty});Object.defineProperties(CloseEvent.prototype,{[Symbol.toStringTag]:{value:"CloseEvent",configurable:true},reason:kEnumerableProperty,code:kEnumerableProperty,wasClean:kEnumerableProperty});Object.defineProperties(ErrorEvent.prototype,{[Symbol.toStringTag]:{value:"ErrorEvent",configurable:true},message:kEnumerableProperty,filename:kEnumerableProperty,lineno:kEnumerableProperty,colno:kEnumerableProperty,error:kEnumerableProperty});webidl.converters.MessagePort=webidl.interfaceConverter(webidl.is.MessagePort,"MessagePort");webidl.converters["sequence<MessagePort>"]=webidl.sequenceConverter(webidl.converters.MessagePort);var eventInit=[{key:"bubbles",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"cancelable",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"composed",converter:webidl.converters.boolean,defaultValue:()=>false}];webidl.converters.MessageEventInit=webidl.dictionaryConverter([...eventInit,{key:"data",converter:webidl.converters.any,defaultValue:()=>null},{key:"origin",converter:webidl.converters.USVString,defaultValue:()=>""},{key:"lastEventId",converter:webidl.converters.DOMString,defaultValue:()=>""},{key:"source",converter:webidl.nullableConverter(webidl.converters.MessagePort),defaultValue:()=>null},{key:"ports",converter:webidl.converters["sequence<MessagePort>"],defaultValue:()=>[]}]);webidl.converters.CloseEventInit=webidl.dictionaryConverter([...eventInit,{key:"wasClean",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"code",converter:webidl.converters["unsigned short"],defaultValue:()=>0},{key:"reason",converter:webidl.converters.USVString,defaultValue:()=>""}]);webidl.converters.ErrorEventInit=webidl.dictionaryConverter([...eventInit,{key:"message",converter:webidl.converters.DOMString,defaultValue:()=>""},{key:"filename",converter:webidl.converters.USVString,defaultValue:()=>""},{key:"lineno",converter:webidl.converters["unsigned long"],defaultValue:()=>0},{key:"colno",converter:webidl.converters["unsigned long"],defaultValue:()=>0},{key:"error",converter:webidl.converters.any}]);module.exports={MessageEvent,CloseEvent,ErrorEvent,createFastMessageEvent}}});var require_constants5=__commonJS({"node_modules/undici/lib/web/websocket/constants.js"(exports,module){"use strict";var uid="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";var staticPropertyDescriptors={enumerable:true,writable:false,configurable:false};var states={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var sentCloseFrameState={SENT:1,RECEIVED:2};var opcodes={CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10};var maxUnsigned16Bit=65535;var parserStates={INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4};var emptyBuffer=Buffer.allocUnsafe(0);var sendHints={text:1,typedArray:2,arrayBuffer:3,blob:4};module.exports={uid,sentCloseFrameState,staticPropertyDescriptors,states,opcodes,maxUnsigned16Bit,parserStates,emptyBuffer,sendHints}}});var require_util6=__commonJS({"node_modules/undici/lib/web/websocket/util.js"(exports,module){"use strict";var{states,opcodes}=require_constants5();var{isUtf8}=__require("buffer");var{removeHTTPWhitespace}=require_data_url();var{collectASequenceOfCodePointsFast}=require_infra();function isConnecting(readyState){return readyState===states.CONNECTING}function isEstablished(readyState){return readyState===states.OPEN}function isClosing(readyState){return readyState===states.CLOSING}function isClosed(readyState){return readyState===states.CLOSED}function fireEvent(e,target,eventFactory=(type,init)=>new Event(type,init),eventInitDict={}){const event=eventFactory(e,eventInitDict);target.dispatchEvent(event)}function websocketMessageReceived(handler,type,data){handler.onMessage(type,data)}function toArrayBuffer(buffer){if(buffer.byteLength===buffer.buffer.byteLength){return buffer.buffer}return new Uint8Array(buffer).buffer}function isValidSubprotocol(protocol){if(protocol.length===0){return false}for(let i=0;i<protocol.length;++i){const code=protocol.charCodeAt(i);if(code<33||code>126||code===34||code===40||code===41||code===44||code===47||code===58||code===59||code===60||code===61||code===62||code===63||code===64||code===91||code===92||code===93||code===123||code===125){return false}}return true}function isValidStatusCode(code){if(code>=1e3&&code<1015){return code!==1004&&code!==1005&&code!==1006}return code>=3e3&&code<=4999}function isControlFrame(opcode){return opcode===opcodes.CLOSE||opcode===opcodes.PING||opcode===opcodes.PONG}function isContinuationFrame(opcode){return opcode===opcodes.CONTINUATION}function isTextBinaryFrame(opcode){return opcode===opcodes.TEXT||opcode===opcodes.BINARY}function isValidOpcode(opcode){return isTextBinaryFrame(opcode)||isContinuationFrame(opcode)||isControlFrame(opcode)}function parseExtensions(extensions){const position={position:0};const extensionList=new Map;while(position.position<extensions.length){const pair=collectASequenceOfCodePointsFast(";",extensions,position);const[name2,value=""]=pair.split("=",2);extensionList.set(removeHTTPWhitespace(name2,true,false),removeHTTPWhitespace(value,false,true));position.position++}return extensionList}function isValidClientWindowBits(value){if(value.length===0){return false}for(let i=0;i<value.length;i++){const byte=value.charCodeAt(i);if(byte<48||byte>57){return false}}const num=Number.parseInt(value,10);return num>=8&&num<=15}function getURLRecord(url,baseURL){let urlRecord;try{urlRecord=new URL(url,baseURL)}catch(e){throw new DOMException(e,"SyntaxError")}if(urlRecord.protocol==="http:"){urlRecord.protocol="ws:"}else if(urlRecord.protocol==="https:"){urlRecord.protocol="wss:"}if(urlRecord.protocol!=="ws:"&&urlRecord.protocol!=="wss:"){throw new DOMException("expected a ws: or wss: url","SyntaxError")}if(urlRecord.hash.length||urlRecord.href.endsWith("#")){throw new DOMException("hash","SyntaxError")}return urlRecord}function validateCloseCodeAndReason(code,reason){if(code!==null){if(code!==1e3&&(code<3e3||code>4999)){throw new DOMException("invalid code","InvalidAccessError")}}if(reason!==null){const reasonBytesLength=Buffer.byteLength(reason);if(reasonBytesLength>123){throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`,"SyntaxError")}}}var utf8Decode=(()=>{if(typeof process.versions.icu==="string"){const fatalDecoder=new TextDecoder("utf-8",{fatal:true});return fatalDecoder.decode.bind(fatalDecoder)}return function(buffer){if(isUtf8(buffer)){return buffer.toString("utf-8")}throw new TypeError("Invalid utf-8 received.")}})();module.exports={isConnecting,isEstablished,isClosing,isClosed,fireEvent,isValidSubprotocol,isValidStatusCode,websocketMessageReceived,utf8Decode,isControlFrame,isContinuationFrame,isTextBinaryFrame,isValidOpcode,parseExtensions,isValidClientWindowBits,toArrayBuffer,getURLRecord,validateCloseCodeAndReason}}});var require_frame=__commonJS({"node_modules/undici/lib/web/websocket/frame.js"(exports,module){"use strict";var{runtimeFeatures}=require_runtime_features();var{maxUnsigned16Bit,opcodes}=require_constants5();var BUFFER_SIZE=8*1024;var buffer=null;var bufIdx=BUFFER_SIZE;var randomFillSync=runtimeFeatures.has("crypto")?__require("crypto").randomFillSync:function randomFillSync2(buffer2,_offset,_size){for(let i=0;i<buffer2.length;++i){buffer2[i]=Math.random()*255|0}return buffer2};function generateMask(){if(bufIdx===BUFFER_SIZE){bufIdx=0;randomFillSync(buffer??=Buffer.allocUnsafeSlow(BUFFER_SIZE),0,BUFFER_SIZE)}return[buffer[bufIdx++],buffer[bufIdx++],buffer[bufIdx++],buffer[bufIdx++]]}var WebsocketFrameSend=class{constructor(data){this.frameData=data}createFrame(opcode){const frameData=this.frameData;const maskKey=generateMask();const bodyLength=frameData?.byteLength??0;let payloadLength=bodyLength;let offset=6;if(bodyLength>maxUnsigned16Bit){offset+=8;payloadLength=127}else if(bodyLength>125){offset+=2;payloadLength=126}const buffer2=Buffer.allocUnsafe(bodyLength+offset);buffer2[0]=buffer2[1]=0;buffer2[0]|=128;buffer2[0]=(buffer2[0]&240)+opcode;buffer2[offset-4]=maskKey[0];buffer2[offset-3]=maskKey[1];buffer2[offset-2]=maskKey[2];buffer2[offset-1]=maskKey[3];buffer2[1]=payloadLength;if(payloadLength===126){buffer2.writeUInt16BE(bodyLength,2)}else if(payloadLength===127){buffer2[2]=buffer2[3]=0;buffer2.writeUIntBE(bodyLength,4,6)}buffer2[1]|=128;for(let i=0;i<bodyLength;++i){buffer2[offset+i]=frameData[i]^maskKey[i&3]}return buffer2}static createFastTextFrame(buffer2){const maskKey=generateMask();const bodyLength=buffer2.length;for(let i=0;i<bodyLength;++i){buffer2[i]^=maskKey[i&3]}let payloadLength=bodyLength;let offset=6;if(bodyLength>maxUnsigned16Bit){offset+=8;payloadLength=127}else if(bodyLength>125){offset+=2;payloadLength=126}const head=Buffer.allocUnsafeSlow(offset);head[0]=128|opcodes.TEXT;head[1]=payloadLength|128;head[offset-4]=maskKey[0];head[offset-3]=maskKey[1];head[offset-2]=maskKey[2];head[offset-1]=maskKey[3];if(payloadLength===126){head.writeUInt16BE(bodyLength,2)}else if(payloadLength===127){head[2]=head[3]=0;head.writeUIntBE(bodyLength,4,6)}return[head,buffer2]}};module.exports={WebsocketFrameSend,generateMask}}});var require_connection=__commonJS({"node_modules/undici/lib/web/websocket/connection.js"(exports,module){"use strict";var{uid,states,sentCloseFrameState,emptyBuffer,opcodes}=require_constants5();var{parseExtensions,isClosed,isClosing,isEstablished,isConnecting,validateCloseCodeAndReason}=require_util6();var{makeRequest}=require_request2();var{fetching}=require_fetch();var{Headers:Headers2,getHeadersList}=require_headers();var{getDecodeSplit}=require_util3();var{WebsocketFrameSend}=require_frame();var assert=__require("assert");var{runtimeFeatures}=require_runtime_features();var crypto5=runtimeFeatures.has("crypto")?__require("crypto"):null;var warningEmitted=false;function establishWebSocketConnection(url,protocols,client,handler,options){const requestURL=url;requestURL.protocol=url.protocol==="ws:"?"http:":"https:";const request=makeRequest({urlList:[requestURL],client,serviceWorkers:"none",referrer:"no-referrer",mode:"websocket",credentials:"include",cache:"no-store",redirect:"error",useURLCredentials:true});if(options.headers){const headersList=getHeadersList(new Headers2(options.headers));request.headersList=headersList}const keyValue=crypto5.randomBytes(16).toString("base64");request.headersList.append("sec-websocket-key",keyValue,true);request.headersList.append("sec-websocket-version","13",true);for(const protocol of protocols){request.headersList.append("sec-websocket-protocol",protocol,true)}const permessageDeflate="permessage-deflate; client_max_window_bits";request.headersList.append("sec-websocket-extensions",permessageDeflate,true);const controller=fetching({request,useParallelQueue:true,dispatcher:options.dispatcher,processResponse(response){if(response.type==="error"||response.status!==101){if(response.socket?.session==null){failWebsocketConnection(handler,1002,"Received network error or non-101 status code.",response.error);return}if(response.status!==200){failWebsocketConnection(handler,1002,"Received network error or non-200 status code.",response.error);return}}if(warningEmitted===false&&response.socket?.session!=null){process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.","ExperimentalWarning");warningEmitted=true}if(protocols.length!==0&&!response.headersList.get("Sec-WebSocket-Protocol")){failWebsocketConnection(handler,1002,"Server did not respond with sent protocols.");return}if(response.socket.session==null&&response.headersList.get("Upgrade")?.toLowerCase()!=="websocket"){failWebsocketConnection(handler,1002,'Server did not set Upgrade header to "websocket".');return}if(response.socket.session==null&&response.headersList.get("Connection")?.toLowerCase()!=="upgrade"){failWebsocketConnection(handler,1002,'Server did not set Connection header to "upgrade".');return}const secWSAccept=response.headersList.get("Sec-WebSocket-Accept");const digest=crypto5.hash("sha1",keyValue+uid,"base64");if(secWSAccept!==digest){failWebsocketConnection(handler,1002,"Incorrect hash received in Sec-WebSocket-Accept header.");return}const secExtension=response.headersList.get("Sec-WebSocket-Extensions");let extensions;if(secExtension!==null){extensions=parseExtensions(secExtension);if(!extensions.has("permessage-deflate")){failWebsocketConnection(handler,1002,"Sec-WebSocket-Extensions header does not match.");return}}const secProtocol=response.headersList.get("Sec-WebSocket-Protocol");if(secProtocol!==null){const requestProtocols=getDecodeSplit("sec-websocket-protocol",request.headersList);if(!requestProtocols.includes(secProtocol)){failWebsocketConnection(handler,1002,"Protocol was not set in the opening handshake.");return}}response.socket.on("data",handler.onSocketData);response.socket.on("close",handler.onSocketClose);response.socket.on("error",handler.onSocketError);handler.wasEverConnected=true;handler.onConnectionEstablished(response,extensions)}});return controller}function closeWebSocketConnection(object,code,reason,validate=false){code??=null;reason??="";if(validate)validateCloseCodeAndReason(code,reason);if(isClosed(object.readyState)||isClosing(object.readyState)){}else if(!isEstablished(object.readyState)){failWebsocketConnection(object);object.readyState=states.CLOSING}else if(!object.closeState.has(sentCloseFrameState.SENT)&&!object.closeState.has(sentCloseFrameState.RECEIVED)){const frame=new WebsocketFrameSend;if(reason.length!==0&&code===null){code=1e3}assert(code===null||Number.isInteger(code));if(code===null&&reason.length===0){frame.frameData=emptyBuffer}else if(code!==null&&reason===null){frame.frameData=Buffer.allocUnsafe(2);frame.frameData.writeUInt16BE(code,0)}else if(code!==null&&reason!==null){frame.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(reason));frame.frameData.writeUInt16BE(code,0);frame.frameData.write(reason,2,"utf-8")}else{frame.frameData=emptyBuffer}object.socket.write(frame.createFrame(opcodes.CLOSE));object.closeState.add(sentCloseFrameState.SENT);object.readyState=states.CLOSING}else{object.readyState=states.CLOSING}}function failWebsocketConnection(handler,code,reason,cause){if(isEstablished(handler.readyState)){closeWebSocketConnection(handler,code,reason,false)}handler.controller.abort();if(isConnecting(handler.readyState)){handler.onSocketClose()}else if(handler.socket?.destroyed===false){handler.socket.destroy()}}module.exports={establishWebSocketConnection,failWebsocketConnection,closeWebSocketConnection}}});var require_permessage_deflate=__commonJS({"node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports,module){"use strict";var{createInflateRaw,Z_DEFAULT_WINDOWBITS}=__require("zlib");var{isValidClientWindowBits}=require_util6();var{MessageSizeExceededError}=require_errors();var tail=Buffer.from([0,0,255,255]);var kBuffer=Symbol("kBuffer");var kLength=Symbol("kLength");var PerMessageDeflate=class{#inflate;#options={};#maxPayloadSize=0;constructor(extensions,options){this.#options.serverNoContextTakeover=extensions.has("server_no_context_takeover");this.#options.serverMaxWindowBits=extensions.get("server_max_window_bits");this.#maxPayloadSize=options.maxPayloadSize}decompress(chunk,fin,callback){if(!this.#inflate){let windowBits=Z_DEFAULT_WINDOWBITS;if(this.#options.serverMaxWindowBits){if(!isValidClientWindowBits(this.#options.serverMaxWindowBits)){callback(new Error("Invalid server_max_window_bits"));return}windowBits=Number.parseInt(this.#options.serverMaxWindowBits)}try{this.#inflate=createInflateRaw({windowBits})}catch(err){callback(err);return}this.#inflate[kBuffer]=[];this.#inflate[kLength]=0;this.#inflate.on("data",data=>{this.#inflate[kLength]+=data.length;if(this.#maxPayloadSize>0&&this.#inflate[kLength]>this.#maxPayloadSize){callback(new MessageSizeExceededError);this.#inflate.removeAllListeners();this.#inflate=null;return}this.#inflate[kBuffer].push(data)});this.#inflate.on("error",err=>{this.#inflate=null;callback(err)})}this.#inflate.write(chunk);if(fin){this.#inflate.write(tail)}this.#inflate.flush(()=>{if(!this.#inflate){return}const full=Buffer.concat(this.#inflate[kBuffer],this.#inflate[kLength]);this.#inflate[kBuffer].length=0;this.#inflate[kLength]=0;callback(null,full)})}};module.exports={PerMessageDeflate}}});var require_receiver=__commonJS({"node_modules/undici/lib/web/websocket/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var assert=__require("assert");var{parserStates,opcodes,states,emptyBuffer,sentCloseFrameState}=require_constants5();var{isValidStatusCode,isValidOpcode,websocketMessageReceived,utf8Decode,isControlFrame,isTextBinaryFrame,isContinuationFrame}=require_util6();var{failWebsocketConnection}=require_connection();var{WebsocketFrameSend}=require_frame();var{PerMessageDeflate}=require_permessage_deflate();var{MessageSizeExceededError}=require_errors();var ByteParser=class extends Writable{#buffers=[];#fragmentsBytes=0;#byteOffset=0;#loop=false;#state=parserStates.INFO;#info={};#fragments=[];#extensions;#handler;#maxFragments;#maxPayloadSize;constructor(handler,extensions,options={}){super();this.#handler=handler;this.#extensions=extensions==null?new Map:extensions;this.#maxFragments=options.maxFragments??0;this.#maxPayloadSize=options.maxPayloadSize??0;if(this.#extensions.has("permessage-deflate")){this.#extensions.set("permessage-deflate",new PerMessageDeflate(extensions,options))}}_write(chunk,_2,callback){this.#buffers.push(chunk);this.#byteOffset+=chunk.length;this.#loop=true;this.run(callback)}#validatePayloadLength(){if(this.#maxPayloadSize>0&&!isControlFrame(this.#info.opcode)&&this.#info.payloadLength+this.#fragmentsBytes>this.#maxPayloadSize){failWebsocketConnection(this.#handler,1009,"Payload size exceeds maximum allowed size");return false}return true}run(callback){while(this.#loop){if(this.#state===parserStates.INFO){if(this.#byteOffset<2){return callback()}const buffer=this.consume(2);const fin=(buffer[0]&128)!==0;const opcode=buffer[0]&15;const masked=(buffer[1]&128)===128;const fragmented=!fin&&opcode!==opcodes.CONTINUATION;const payloadLength=buffer[1]&127;const rsv1=buffer[0]&64;const rsv2=buffer[0]&32;const rsv3=buffer[0]&16;if(!isValidOpcode(opcode)){failWebsocketConnection(this.#handler,1002,"Invalid opcode received");return callback()}if(masked){failWebsocketConnection(this.#handler,1002,"Frame cannot be masked");return callback()}if(rsv1!==0&&!this.#extensions.has("permessage-deflate")){failWebsocketConnection(this.#handler,1002,"Expected RSV1 to be clear.");return}if(rsv2!==0||rsv3!==0){failWebsocketConnection(this.#handler,1002,"RSV1, RSV2, RSV3 must be clear");return}if(fragmented&&!isTextBinaryFrame(opcode)){failWebsocketConnection(this.#handler,1002,"Invalid frame type was fragmented.");return}if(isTextBinaryFrame(opcode)&&this.#fragments.length>0){failWebsocketConnection(this.#handler,1002,"Expected continuation frame");return}if(this.#info.fragmented&&fragmented){failWebsocketConnection(this.#handler,1002,"Fragmented frame exceeded 125 bytes.");return}if((payloadLength>125||fragmented)&&isControlFrame(opcode)){failWebsocketConnection(this.#handler,1002,"Control frame either too large or fragmented");return}if(isContinuationFrame(opcode)&&this.#fragments.length===0&&!this.#info.compressed){failWebsocketConnection(this.#handler,1002,"Unexpected continuation frame");return}if(payloadLength<=125){this.#info.payloadLength=payloadLength;this.#state=parserStates.READ_DATA;if(!this.#validatePayloadLength()){return}}else if(payloadLength===126){this.#state=parserStates.PAYLOADLENGTH_16}else if(payloadLength===127){this.#state=parserStates.PAYLOADLENGTH_64}if(isTextBinaryFrame(opcode)){this.#info.binaryType=opcode;this.#info.compressed=rsv1!==0}this.#info.opcode=opcode;this.#info.masked=masked;this.#info.fin=fin;this.#info.fragmented=fragmented}else if(this.#state===parserStates.PAYLOADLENGTH_16){if(this.#byteOffset<2){return callback()}const buffer=this.consume(2);this.#info.payloadLength=buffer.readUInt16BE(0);this.#state=parserStates.READ_DATA;if(!this.#validatePayloadLength()){return}}else if(this.#state===parserStates.PAYLOADLENGTH_64){if(this.#byteOffset<8){return callback()}const buffer=this.consume(8);const upper=buffer.readUInt32BE(0);const lower=buffer.readUInt32BE(4);if(upper!==0||lower>2**31-1){failWebsocketConnection(this.#handler,1009,"Received payload length > 2^31 bytes.");return}this.#info.payloadLength=lower;this.#state=parserStates.READ_DATA;if(!this.#validatePayloadLength()){return}}else if(this.#state===parserStates.READ_DATA){if(this.#byteOffset<this.#info.payloadLength){return callback()}const body=this.consume(this.#info.payloadLength);if(isControlFrame(this.#info.opcode)){this.#loop=this.parseControlFrame(body);this.#state=parserStates.INFO}else{if(!this.#info.compressed){if(!this.writeFragments(body)){return}if(!this.#info.fragmented&&this.#info.fin){websocketMessageReceived(this.#handler,this.#info.binaryType,this.consumeFragments())}this.#state=parserStates.INFO}else{this.#extensions.get("permessage-deflate").decompress(body,this.#info.fin,(error,data)=>{if(error){const code=error instanceof MessageSizeExceededError?1009:1007;failWebsocketConnection(this.#handler,code,error.message);return}if(!this.writeFragments(data)){return}if(this.#maxPayloadSize>0&&this.#fragmentsBytes>this.#maxPayloadSize){failWebsocketConnection(this.#handler,1009,new MessageSizeExceededError().message);return}if(!this.#info.fin){this.#state=parserStates.INFO;this.#loop=true;this.run(callback);return}websocketMessageReceived(this.#handler,this.#info.binaryType,this.consumeFragments());this.#loop=true;this.#state=parserStates.INFO;this.run(callback)},this.#fragmentsBytes);this.#loop=false;break}}}}}consume(n){if(n>this.#byteOffset){throw new Error("Called consume() before buffers satiated.")}else if(n===0){return emptyBuffer}this.#byteOffset-=n;const first=this.#buffers[0];if(first.length>n){this.#buffers[0]=first.subarray(n,first.length);return first.subarray(0,n)}else if(first.length===n){return this.#buffers.shift()}else{let offset=0;const buffer=Buffer.allocUnsafeSlow(n);while(offset!==n){const next=this.#buffers[0];const length=next.length;if(length+offset===n){buffer.set(this.#buffers.shift(),offset);break}else if(length+offset>n){buffer.set(next.subarray(0,n-offset),offset);this.#buffers[0]=next.subarray(n-offset);break}else{buffer.set(this.#buffers.shift(),offset);offset+=length}}return buffer}}writeFragments(fragment){if(this.#maxFragments>0&&this.#fragments.length===this.#maxFragments){failWebsocketConnection(this.#handler,1008,"Too many message fragments");return false}this.#fragmentsBytes+=fragment.length;this.#fragments.push(fragment);return true}consumeFragments(){const fragments=this.#fragments;if(fragments.length===1){this.#fragmentsBytes=0;return fragments.shift()}let offset=0;const output=Buffer.allocUnsafeSlow(this.#fragmentsBytes);for(let i=0;i<fragments.length;++i){const buffer=fragments[i];output.set(buffer,offset);offset+=buffer.length}this.#fragments=[];this.#fragmentsBytes=0;return output}parseCloseBody(data){assert(data.length!==1);let code;if(data.length>=2){code=data.readUInt16BE(0)}if(code!==void 0&&!isValidStatusCode(code)){return{code:1002,reason:"Invalid status code",error:true}}let reason=data.subarray(2);if(reason[0]===239&&reason[1]===187&&reason[2]===191){reason=reason.subarray(3)}try{reason=utf8Decode(reason)}catch{return{code:1007,reason:"Invalid UTF-8",error:true}}return{code,reason,error:false}}parseControlFrame(body){const{opcode,payloadLength}=this.#info;if(opcode===opcodes.CLOSE){if(payloadLength===1){failWebsocketConnection(this.#handler,1002,"Received close frame with a 1-byte body.");return false}this.#info.closeInfo=this.parseCloseBody(body);if(this.#info.closeInfo.error){const{code,reason}=this.#info.closeInfo;failWebsocketConnection(this.#handler,code,reason);return false}if(!this.#handler.closeState.has(sentCloseFrameState.SENT)&&!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){let body2=emptyBuffer;if(this.#info.closeInfo.code){body2=Buffer.allocUnsafe(2);body2.writeUInt16BE(this.#info.closeInfo.code,0)}const closeFrame=new WebsocketFrameSend(body2);this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));this.#handler.closeState.add(sentCloseFrameState.SENT)}this.#handler.readyState=states.CLOSING;this.#handler.closeState.add(sentCloseFrameState.RECEIVED);return false}else if(opcode===opcodes.PING){if(!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){const frame=new WebsocketFrameSend(body);this.#handler.socket.write(frame.createFrame(opcodes.PONG));this.#handler.onPing(body)}}else if(opcode===opcodes.PONG){this.#handler.onPong(body)}return true}get closingInfo(){return this.#info.closeInfo}};module.exports={ByteParser}}});var require_sender=__commonJS({"node_modules/undici/lib/web/websocket/sender.js"(exports,module){"use strict";var{WebsocketFrameSend}=require_frame();var{opcodes,sendHints}=require_constants5();var FixedQueue=require_fixed_queue();var SendQueue=class{#queue=new FixedQueue;#running=false;#socket;constructor(socket){this.#socket=socket}add(item,cb,hint){if(hint!==sendHints.blob){if(!this.#running){if(hint===sendHints.text){const{0:head,1:body}=WebsocketFrameSend.createFastTextFrame(item);this.#socket.cork();this.#socket.write(head);this.#socket.write(body,cb);this.#socket.uncork()}else{this.#socket.write(createFrame(item,hint),cb)}}else{const node2={promise:null,callback:cb,frame:createFrame(item,hint)};this.#queue.push(node2)}return}const node={promise:item.arrayBuffer().then(ab=>{node.promise=null;node.frame=createFrame(ab,hint)}),callback:cb,frame:null};this.#queue.push(node);if(!this.#running){this.#run()}}async#run(){this.#running=true;const queue=this.#queue;while(!queue.isEmpty()){const node=queue.shift();if(node.promise!==null){await node.promise}this.#socket.write(node.frame,node.callback);node.callback=node.frame=null}this.#running=false}};function createFrame(data,hint){return new WebsocketFrameSend(toBuffer(data,hint)).createFrame(hint===sendHints.text?opcodes.TEXT:opcodes.BINARY)}function toBuffer(data,hint){switch(hint){case sendHints.text:case sendHints.typedArray:return new Uint8Array(data.buffer,data.byteOffset,data.byteLength);case sendHints.arrayBuffer:case sendHints.blob:return new Uint8Array(data)}}module.exports={SendQueue}}});var require_websocket=__commonJS({"node_modules/undici/lib/web/websocket/websocket.js"(exports,module){"use strict";var{isArrayBuffer}=__require("util/types");var{webidl}=require_webidl();var{URLSerializer}=require_data_url();var{environmentSettingsObject}=require_util3();var{staticPropertyDescriptors,states,sentCloseFrameState,sendHints,opcodes}=require_constants5();var{isConnecting,isEstablished,isClosing,isClosed,isValidSubprotocol,fireEvent,utf8Decode,toArrayBuffer,getURLRecord}=require_util6();var{establishWebSocketConnection,closeWebSocketConnection,failWebsocketConnection}=require_connection();var{ByteParser}=require_receiver();var{kEnumerableProperty}=require_util2();var{getGlobalDispatcher}=require_global2();var{ErrorEvent,CloseEvent,createFastMessageEvent}=require_events();var{SendQueue}=require_sender();var{WebsocketFrameSend}=require_frame();var{channels}=require_diagnostics();function getSocketAddress(socket){if(typeof socket?.address==="function"){return socket.address()}if(typeof socket?.session?.socket?.address==="function"){return socket.session.socket.address()}return null}var WebSocket=class _WebSocket extends EventTarget{#events={open:null,error:null,close:null,message:null};#bufferedAmount=0;#protocol="";#extensions="";#sendQueue;#handler={onConnectionEstablished:(response,extensions)=>this.#onConnectionEstablished(response,extensions),onMessage:(opcode,data)=>this.#onMessage(opcode,data),onParserError:err=>failWebsocketConnection(this.#handler,null,err.message),onParserDrain:()=>this.#onParserDrain(),onSocketData:chunk=>{if(!this.#parser.write(chunk)){this.#handler.socket.pause()}},onSocketError:err=>{this.#handler.readyState=states.CLOSING;if(channels.socketError.hasSubscribers){channels.socketError.publish(err)}this.#handler.socket.destroy()},onSocketClose:()=>this.#onSocketClose(),onPing:body=>{if(channels.ping.hasSubscribers){channels.ping.publish({payload:body,websocket:this})}},onPong:body=>{if(channels.pong.hasSubscribers){channels.pong.publish({payload:body,websocket:this})}},readyState:states.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:false};#url;#binaryType;#parser;constructor(url,protocols=[]){super();webidl.util.markAsUncloneable(this);const prefix="WebSocket constructor";webidl.argumentLengthCheck(arguments,1,prefix);const options=webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"](protocols,prefix,"options");url=webidl.converters.USVString(url);protocols=options.protocols;const baseURL=environmentSettingsObject.settingsObject.baseUrl;const urlRecord=getURLRecord(url,baseURL);if(typeof protocols==="string"){protocols=[protocols]}if(protocols.length!==new Set(protocols.map(p2=>p2.toLowerCase())).size){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}if(protocols.length>0&&!protocols.every(p2=>isValidSubprotocol(p2))){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}this.#url=new URL(urlRecord.href);const client=environmentSettingsObject.settingsObject;this.#handler.controller=establishWebSocketConnection(urlRecord,protocols,client,this.#handler,options);this.#handler.readyState=_WebSocket.CONNECTING;this.#binaryType="blob"}close(code=void 0,reason=void 0){webidl.brandCheck(this,_WebSocket);const prefix="WebSocket.close";if(code!==void 0){code=webidl.converters["unsigned short"](code,prefix,"code",webidl.attributes.Clamp)}if(reason!==void 0){reason=webidl.converters.USVString(reason)}code??=null;reason??="";closeWebSocketConnection(this.#handler,code,reason,true)}send(data){webidl.brandCheck(this,_WebSocket);const prefix="WebSocket.send";webidl.argumentLengthCheck(arguments,1,prefix);data=webidl.converters.WebSocketSendData(data,prefix,"data");if(isConnecting(this.#handler.readyState)){throw new DOMException("Sent before connected.","InvalidStateError")}if(!isEstablished(this.#handler.readyState)||isClosing(this.#handler.readyState)){return}if(typeof data==="string"){const buffer=Buffer.from(data);this.#bufferedAmount+=buffer.byteLength;this.#sendQueue.add(buffer,()=>{this.#bufferedAmount-=buffer.byteLength},sendHints.text)}else if(isArrayBuffer(data)){this.#bufferedAmount+=data.byteLength;this.#sendQueue.add(data,()=>{this.#bufferedAmount-=data.byteLength},sendHints.arrayBuffer)}else if(ArrayBuffer.isView(data)){this.#bufferedAmount+=data.byteLength;this.#sendQueue.add(data,()=>{this.#bufferedAmount-=data.byteLength},sendHints.typedArray)}else if(webidl.is.Blob(data)){this.#bufferedAmount+=data.size;this.#sendQueue.add(data,()=>{this.#bufferedAmount-=data.size},sendHints.blob)}}get readyState(){webidl.brandCheck(this,_WebSocket);return this.#handler.readyState}get bufferedAmount(){webidl.brandCheck(this,_WebSocket);return this.#bufferedAmount}get url(){webidl.brandCheck(this,_WebSocket);return URLSerializer(this.#url)}get extensions(){webidl.brandCheck(this,_WebSocket);return this.#extensions}get protocol(){webidl.brandCheck(this,_WebSocket);return this.#protocol}get onopen(){webidl.brandCheck(this,_WebSocket);return this.#events.open}set onopen(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.open){this.removeEventListener("open",this.#events.open)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("open",listener);this.#events.open=fn}else{this.#events.open=null}}get onerror(){webidl.brandCheck(this,_WebSocket);return this.#events.error}set onerror(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.error){this.removeEventListener("error",this.#events.error)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("error",listener);this.#events.error=fn}else{this.#events.error=null}}get onclose(){webidl.brandCheck(this,_WebSocket);return this.#events.close}set onclose(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.close){this.removeEventListener("close",this.#events.close)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("close",listener);this.#events.close=fn}else{this.#events.close=null}}get onmessage(){webidl.brandCheck(this,_WebSocket);return this.#events.message}set onmessage(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.message){this.removeEventListener("message",this.#events.message)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("message",listener);this.#events.message=fn}else{this.#events.message=null}}get binaryType(){webidl.brandCheck(this,_WebSocket);return this.#binaryType}set binaryType(type){webidl.brandCheck(this,_WebSocket);if(type!=="blob"&&type!=="arraybuffer"){this.#binaryType="blob"}else{this.#binaryType=type}}#onConnectionEstablished(response,parsedExtensions){this.#handler.socket=response.socket;const webSocketOptions=this.#handler.controller.dispatcher?.webSocketOptions;const maxFragments=webSocketOptions?.maxFragments;const maxPayloadSize=webSocketOptions?.maxPayloadSize;const parser=new ByteParser(this.#handler,parsedExtensions,{maxFragments,maxPayloadSize});parser.on("drain",()=>this.#handler.onParserDrain());parser.on("error",err=>this.#handler.onParserError(err));this.#parser=parser;this.#sendQueue=new SendQueue(response.socket);this.#handler.readyState=states.OPEN;const extensions=response.headersList.get("sec-websocket-extensions");if(extensions!==null){this.#extensions=extensions}const protocol=response.headersList.get("sec-websocket-protocol");if(protocol!==null){this.#protocol=protocol}fireEvent("open",this);if(channels.open.hasSubscribers){const headers=response.headersList.entries;channels.open.publish({address:getSocketAddress(response.socket),protocol:this.#protocol,extensions:this.#extensions,websocket:this,handshakeResponse:{status:response.status,statusText:response.statusText,headers}})}}#onMessage(type,data){if(this.#handler.readyState!==states.OPEN){return}let dataForEvent;if(type===opcodes.TEXT){try{dataForEvent=utf8Decode(data)}catch{failWebsocketConnection(this.#handler,1007,"Received invalid UTF-8 in text frame.");return}}else if(type===opcodes.BINARY){if(this.#binaryType==="blob"){dataForEvent=new Blob([data])}else{dataForEvent=toArrayBuffer(data)}}fireEvent("message",this,createFastMessageEvent,{origin:this.#url.origin,data:dataForEvent})}#onParserDrain(){this.#handler.socket.resume()}#onSocketClose(){const wasClean=this.#handler.closeState.has(sentCloseFrameState.SENT)&&this.#handler.closeState.has(sentCloseFrameState.RECEIVED);let code=1005;let reason="";const result=this.#parser?.closingInfo;if(result&&!result.error){code=result.code??1005;reason=result.reason}this.#handler.readyState=states.CLOSED;if(!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){code=1006;fireEvent("error",this,(type,init)=>new ErrorEvent(type,init),{error:new TypeError(reason)})}fireEvent("close",this,(type,init)=>new CloseEvent(type,init),{wasClean,code,reason});if(channels.close.hasSubscribers){channels.close.publish({websocket:this,code,reason})}}static ping(ws2,buffer){if(Buffer.isBuffer(buffer)){if(buffer.length>125){throw new TypeError("A PING frame cannot have a body larger than 125 bytes.")}}else if(buffer!==void 0){throw new TypeError("Expected buffer payload")}const readyState=ws2.#handler.readyState;if(isEstablished(readyState)&&!isClosing(readyState)&&!isClosed(readyState)){const frame=new WebsocketFrameSend(buffer);ws2.#handler.socket.write(frame.createFrame(opcodes.PING))}}};var{ping}=WebSocket;Reflect.deleteProperty(WebSocket,"ping");WebSocket.CONNECTING=WebSocket.prototype.CONNECTING=states.CONNECTING;WebSocket.OPEN=WebSocket.prototype.OPEN=states.OPEN;WebSocket.CLOSING=WebSocket.prototype.CLOSING=states.CLOSING;WebSocket.CLOSED=WebSocket.prototype.CLOSED=states.CLOSED;Object.defineProperties(WebSocket.prototype,{CONNECTING:staticPropertyDescriptors,OPEN:staticPropertyDescriptors,CLOSING:staticPropertyDescriptors,CLOSED:staticPropertyDescriptors,url:kEnumerableProperty,readyState:kEnumerableProperty,bufferedAmount:kEnumerableProperty,onopen:kEnumerableProperty,onerror:kEnumerableProperty,onclose:kEnumerableProperty,close:kEnumerableProperty,onmessage:kEnumerableProperty,binaryType:kEnumerableProperty,send:kEnumerableProperty,extensions:kEnumerableProperty,protocol:kEnumerableProperty,[Symbol.toStringTag]:{value:"WebSocket",writable:false,enumerable:false,configurable:true}});Object.defineProperties(WebSocket,{CONNECTING:staticPropertyDescriptors,OPEN:staticPropertyDescriptors,CLOSING:staticPropertyDescriptors,CLOSED:staticPropertyDescriptors});webidl.converters["sequence<DOMString>"]=webidl.sequenceConverter(webidl.converters.DOMString);webidl.converters["DOMString or sequence<DOMString>"]=function(V2,prefix,argument){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT&&Symbol.iterator in V2){return webidl.converters["sequence<DOMString>"](V2)}return webidl.converters.DOMString(V2,prefix,argument)};webidl.converters.WebSocketInit=webidl.dictionaryConverter([{key:"protocols",converter:webidl.converters["DOMString or sequence<DOMString>"],defaultValue:()=>[]},{key:"dispatcher",converter:webidl.converters.any,defaultValue:()=>getGlobalDispatcher()},{key:"headers",converter:webidl.nullableConverter(webidl.converters.HeadersInit)}]);webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"]=function(V2){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT&&!(Symbol.iterator in V2)){return webidl.converters.WebSocketInit(V2)}return{protocols:webidl.converters["DOMString or sequence<DOMString>"](V2)}};webidl.converters.WebSocketSendData=function(V2){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT){if(webidl.is.Blob(V2)){return V2}if(webidl.is.BufferSource(V2)){return V2}}return webidl.converters.USVString(V2)};module.exports={WebSocket,ping}}});var require_websocketerror=__commonJS({"node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports,module){"use strict";var{webidl}=require_webidl();var{validateCloseCodeAndReason}=require_util6();var{kConstruct}=require_symbols();var{kEnumerableProperty}=require_util2();function createInheritableDOMException(){class Test extends DOMException{get reason(){return""}}if(new Test().reason!==void 0){return DOMException}return new Proxy(DOMException,{construct(target,args,newTarget){const instance=Reflect.construct(target,args,target);Object.setPrototypeOf(instance,newTarget.prototype);return instance}})}var WebSocketError=class _WebSocketError extends createInheritableDOMException(){#closeCode;#reason;constructor(message="",init=void 0){message=webidl.converters.DOMString(message,"WebSocketError","message");super(message,"WebSocketError");if(init===kConstruct){return}else if(init!==null){init=webidl.converters.WebSocketCloseInfo(init)}let code=init.closeCode??null;const reason=init.reason??"";validateCloseCodeAndReason(code,reason);if(reason.length!==0&&code===null){code=1e3}this.#closeCode=code;this.#reason=reason}get closeCode(){return this.#closeCode}get reason(){return this.#reason}static createUnvalidatedWebSocketError(message,code,reason){const error=new _WebSocketError(message,kConstruct);error.#closeCode=code;error.#reason=reason;return error}};var{createUnvalidatedWebSocketError}=WebSocketError;delete WebSocketError.createUnvalidatedWebSocketError;Object.defineProperties(WebSocketError.prototype,{closeCode:kEnumerableProperty,reason:kEnumerableProperty,[Symbol.toStringTag]:{value:"WebSocketError",writable:false,enumerable:false,configurable:true}});webidl.is.WebSocketError=webidl.util.MakeTypeAssertion(WebSocketError);module.exports={WebSocketError,createUnvalidatedWebSocketError}}});var require_websocketstream=__commonJS({"node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports,module){"use strict";var{createDeferredPromise}=require_promise();var{environmentSettingsObject}=require_util3();var{states,opcodes,sentCloseFrameState}=require_constants5();var{webidl}=require_webidl();var{getURLRecord,isValidSubprotocol,isEstablished,utf8Decode}=require_util6();var{establishWebSocketConnection,failWebsocketConnection,closeWebSocketConnection}=require_connection();var{channels}=require_diagnostics();var{WebsocketFrameSend}=require_frame();var{ByteParser}=require_receiver();var{WebSocketError,createUnvalidatedWebSocketError}=require_websocketerror();var{kEnumerableProperty}=require_util2();var{utf8DecodeBytes}=require_encoding();var emittedExperimentalWarning=false;var WebSocketStream=class{#url;#openedPromise;#closedPromise;#readableStream;#readableStreamController;#writableStream;#handshakeAborted=false;#handler={onConnectionEstablished:(response,extensions)=>this.#onConnectionEstablished(response,extensions),onMessage:(opcode,data)=>this.#onMessage(opcode,data),onParserError:err=>failWebsocketConnection(this.#handler,null,err.message),onParserDrain:()=>this.#handler.socket.resume(),onSocketData:chunk=>{if(!this.#parser.write(chunk)){this.#handler.socket.pause()}},onSocketError:err=>{this.#handler.readyState=states.CLOSING;if(channels.socketError.hasSubscribers){channels.socketError.publish(err)}this.#handler.socket.destroy()},onSocketClose:()=>this.#onSocketClose(),onPing:()=>{},onPong:()=>{},readyState:states.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:false};#parser;constructor(url,options=void 0){if(!emittedExperimentalWarning){process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.",{code:"UNDICI-WSS"});emittedExperimentalWarning=true}webidl.argumentLengthCheck(arguments,1,"WebSocket");url=webidl.converters.USVString(url);if(options!==null){options=webidl.converters.WebSocketStreamOptions(options)}const baseURL=environmentSettingsObject.settingsObject.baseUrl;const urlRecord=getURLRecord(url,baseURL);const protocols=options.protocols;if(protocols.length!==new Set(protocols.map(p2=>p2.toLowerCase())).size){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}if(protocols.length>0&&!protocols.every(p2=>isValidSubprotocol(p2))){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}this.#url=urlRecord.toString();this.#openedPromise=createDeferredPromise();this.#closedPromise=createDeferredPromise();if(options.signal!=null){const signal=options.signal;if(signal.aborted){this.#openedPromise.reject(signal.reason);this.#closedPromise.reject(signal.reason);return}signal.addEventListener("abort",()=>{if(!isEstablished(this.#handler.readyState)){failWebsocketConnection(this.#handler);this.#handler.readyState=states.CLOSING;this.#openedPromise.reject(signal.reason);this.#closedPromise.reject(signal.reason);this.#handshakeAborted=true}},{once:true})}const client=environmentSettingsObject.settingsObject;this.#handler.controller=establishWebSocketConnection(urlRecord,protocols,client,this.#handler,options)}get url(){return this.#url.toString()}get opened(){return this.#openedPromise.promise}get closed(){return this.#closedPromise.promise}close(closeInfo=void 0){if(closeInfo!==null){closeInfo=webidl.converters.WebSocketCloseInfo(closeInfo)}const code=closeInfo.closeCode??null;const reason=closeInfo.reason;closeWebSocketConnection(this.#handler,code,reason,true)}#write(chunk){chunk=webidl.converters.WebSocketStreamWrite(chunk);const promise=createDeferredPromise();let data=null;let opcode=null;if(webidl.is.BufferSource(chunk)){data=new Uint8Array(ArrayBuffer.isView(chunk)?new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength):chunk.slice());opcode=opcodes.BINARY}else{let string;try{string=webidl.converters.DOMString(chunk)}catch(e){promise.reject(e);return promise.promise}data=new TextEncoder().encode(string);opcode=opcodes.TEXT}if(!this.#handler.closeState.has(sentCloseFrameState.SENT)&&!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){const frame=new WebsocketFrameSend(data);this.#handler.socket.write(frame.createFrame(opcode),()=>{promise.resolve(void 0)})}return promise.promise}#onConnectionEstablished(response,parsedExtensions){this.#handler.socket=response.socket;const maxFragments=this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;const maxPayloadSize=this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;const parser=new ByteParser(this.#handler,parsedExtensions,{maxFragments,maxPayloadSize});parser.on("drain",()=>this.#handler.onParserDrain());parser.on("error",err=>this.#handler.onParserError(err));this.#parser=parser;this.#handler.readyState=states.OPEN;const extensions=parsedExtensions??"";const protocol=response.headersList.get("sec-websocket-protocol")??"";const readable=new ReadableStream({start:controller=>{this.#readableStreamController=controller},cancel:reason=>this.#cancel(reason)});const writable=new WritableStream({write:chunk=>this.#write(chunk),close:()=>closeWebSocketConnection(this.#handler,null,null),abort:reason=>this.#closeUsingReason(reason)});this.#readableStream=readable;this.#writableStream=writable;this.#openedPromise.resolve({extensions,protocol,readable,writable})}#onMessage(type,data){if(this.#handler.readyState!==states.OPEN){return}let chunk;if(type===opcodes.TEXT){try{chunk=utf8Decode(data)}catch{failWebsocketConnection(this.#handler,1007,"Received invalid UTF-8 in text frame.");return}}else if(type===opcodes.BINARY){chunk=new Uint8Array(data.buffer,data.byteOffset,data.byteLength)}this.#readableStreamController.enqueue(chunk)}#onSocketClose(){const wasClean=this.#handler.closeState.has(sentCloseFrameState.SENT)&&this.#handler.closeState.has(sentCloseFrameState.RECEIVED);this.#handler.readyState=states.CLOSED;if(this.#handshakeAborted){return}if(!this.#handler.wasEverConnected){this.#openedPromise.reject(new WebSocketError("Socket never opened"))}const result=this.#parser?.closingInfo;let code=result?.code??1005;if(!this.#handler.closeState.has(sentCloseFrameState.SENT)&&!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){code=1006}const reason=result?.reason==null?"":utf8DecodeBytes(Buffer.from(result.reason));if(wasClean){this.#readableStreamController.close();if(!this.#writableStream.locked){this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to","InvalidStateError"))}this.#closedPromise.resolve({closeCode:code,reason})}else{const error=createUnvalidatedWebSocketError("unclean close",code,reason);this.#readableStreamController?.error(error);this.#writableStream?.abort(error);this.#closedPromise.reject(error)}}#closeUsingReason(reason){let code=null;let reasonString="";if(webidl.is.WebSocketError(reason)){code=reason.closeCode;reasonString=reason.reason}closeWebSocketConnection(this.#handler,code,reasonString)}#cancel(reason){this.#closeUsingReason(reason)}};Object.defineProperties(WebSocketStream.prototype,{url:kEnumerableProperty,opened:kEnumerableProperty,closed:kEnumerableProperty,close:kEnumerableProperty,[Symbol.toStringTag]:{value:"WebSocketStream",writable:false,enumerable:false,configurable:true}});webidl.converters.WebSocketStreamOptions=webidl.dictionaryConverter([{key:"protocols",converter:webidl.sequenceConverter(webidl.converters.USVString),defaultValue:()=>[]},{key:"signal",converter:webidl.nullableConverter(webidl.converters.AbortSignal),defaultValue:()=>null}]);webidl.converters.WebSocketCloseInfo=webidl.dictionaryConverter([{key:"closeCode",converter:V2=>webidl.converters["unsigned short"](V2,webidl.attributes.EnforceRange)},{key:"reason",converter:webidl.converters.USVString,defaultValue:()=>""}]);webidl.converters.WebSocketStreamWrite=function(V2){if(typeof V2==="string"){return webidl.converters.USVString(V2)}return webidl.converters.BufferSource(V2)};module.exports={WebSocketStream}}});var require_util7=__commonJS({"node_modules/undici/lib/web/eventsource/util.js"(exports,module){"use strict";function isValidLastEventId(value){return value.indexOf("\0")===-1}function isASCIINumber(value){if(value.length===0)return false;for(let i=0;i<value.length;i++){if(value.charCodeAt(i)<48||value.charCodeAt(i)>57)return false}return true}module.exports={isValidLastEventId,isASCIINumber}}});var require_eventsource_stream=__commonJS({"node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports,module){"use strict";var{Transform}=__require("stream");var{isASCIINumber,isValidLastEventId}=require_util7();var BOM=[239,187,191];var LF=10;var CR=13;var COLON=58;var SPACE=32;var EventSourceStream=class extends Transform{state;checkBOM=true;crlfCheck=false;eventEndCheck=false;buffer=null;pos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(options={}){options.readableObjectMode=true;super(options);this.state=options.eventSourceSettings||{};if(options.push){this.push=options.push}}_transform(chunk,_encoding,callback){if(chunk.length===0){callback();return}if(this.buffer){this.buffer=Buffer.concat([this.buffer,chunk])}else{this.buffer=chunk}if(this.checkBOM){switch(this.buffer.length){case 1:if(this.buffer[0]===BOM[0]){callback();return}this.checkBOM=false;callback();return;case 2:if(this.buffer[0]===BOM[0]&&this.buffer[1]===BOM[1]){callback();return}this.checkBOM=false;break;case 3:if(this.buffer[0]===BOM[0]&&this.buffer[1]===BOM[1]&&this.buffer[2]===BOM[2]){this.buffer=Buffer.alloc(0);this.checkBOM=false;callback();return}this.checkBOM=false;break;default:if(this.buffer[0]===BOM[0]&&this.buffer[1]===BOM[1]&&this.buffer[2]===BOM[2]){this.buffer=this.buffer.subarray(3)}this.checkBOM=false;break}}while(this.pos<this.buffer.length){if(this.eventEndCheck){if(this.crlfCheck){if(this.buffer[this.pos]===LF){this.buffer=this.buffer.subarray(this.pos+1);this.pos=0;this.crlfCheck=false;continue}this.crlfCheck=false}if(this.buffer[this.pos]===LF||this.buffer[this.pos]===CR){if(this.buffer[this.pos]===CR){this.crlfCheck=true}this.buffer=this.buffer.subarray(this.pos+1);this.pos=0;if(this.event.data!==void 0||this.event.event||this.event.id!==void 0||this.event.retry){this.processEvent(this.event)}this.clearEvent();continue}this.eventEndCheck=false;continue}if(this.buffer[this.pos]===LF||this.buffer[this.pos]===CR){if(this.buffer[this.pos]===CR){this.crlfCheck=true}this.parseLine(this.buffer.subarray(0,this.pos),this.event);this.buffer=this.buffer.subarray(this.pos+1);this.pos=0;this.eventEndCheck=true;continue}this.pos++}callback()}parseLine(line,event){if(line.length===0){return}const colonPosition=line.indexOf(COLON);if(colonPosition===0){return}let field="";let value="";if(colonPosition!==-1){field=line.subarray(0,colonPosition).toString("utf8");let valueStart=colonPosition+1;if(line[valueStart]===SPACE){++valueStart}value=line.subarray(valueStart).toString("utf8")}else{field=line.toString("utf8");value=""}switch(field){case"data":if(event[field]===void 0){event[field]=value}else{event[field]+=`
|
|
124
124
|
${value}`}break;case"retry":if(isASCIINumber(value)){event[field]=value}break;case"id":if(isValidLastEventId(value)){event[field]=value}break;case"event":if(value.length>0){event[field]=value}break}}processEvent(event){if(event.retry&&isASCIINumber(event.retry)){this.state.reconnectionTime=parseInt(event.retry,10)}if(event.id!==void 0&&isValidLastEventId(event.id)){this.state.lastEventId=event.id}if(event.data!==void 0){this.push({type:event.event||"message",options:{data:event.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}};module.exports={EventSourceStream}}});var require_eventsource=__commonJS({"node_modules/undici/lib/web/eventsource/eventsource.js"(exports,module){"use strict";var{pipeline}=__require("stream");var{fetching}=require_fetch();var{makeRequest}=require_request2();var{webidl}=require_webidl();var{EventSourceStream}=require_eventsource_stream();var{parseMIMEType}=require_data_url();var{createFastMessageEvent}=require_events();var{isNetworkError}=require_response();var{kEnumerableProperty}=require_util2();var{environmentSettingsObject}=require_util3();var experimentalWarned=false;var defaultReconnectionTime=3e3;var CONNECTING=0;var OPEN=1;var CLOSED=2;var ANONYMOUS="anonymous";var USE_CREDENTIALS="use-credentials";var EventSource=class _EventSource extends EventTarget{#events={open:null,error:null,message:null};#url;#withCredentials=false;#readyState=CONNECTING;#request=null;#controller=null;#dispatcher;#state;constructor(url,eventSourceInitDict={}){super();webidl.util.markAsUncloneable(this);const prefix="EventSource constructor";webidl.argumentLengthCheck(arguments,1,prefix);if(!experimentalWarned){experimentalWarned=true;process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})}url=webidl.converters.USVString(url);eventSourceInitDict=webidl.converters.EventSourceInitDict(eventSourceInitDict,prefix,"eventSourceInitDict");this.#dispatcher=eventSourceInitDict.node.dispatcher||eventSourceInitDict.dispatcher;this.#state={lastEventId:"",reconnectionTime:eventSourceInitDict.node.reconnectionTime};const settings=environmentSettingsObject;let urlRecord;try{urlRecord=new URL(url,settings.settingsObject.baseUrl);this.#state.origin=urlRecord.origin}catch(e){throw new DOMException(e,"SyntaxError")}this.#url=urlRecord.href;let corsAttributeState=ANONYMOUS;if(eventSourceInitDict.withCredentials===true){corsAttributeState=USE_CREDENTIALS;this.#withCredentials=true}const initRequest={redirect:"follow",keepalive:true,mode:"cors",credentials:corsAttributeState==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};initRequest.client=environmentSettingsObject.settingsObject;initRequest.headersList=[["accept",{name:"accept",value:"text/event-stream"}]];initRequest.cache="no-store";initRequest.initiator="other";initRequest.urlList=[new URL(this.#url)];this.#request=makeRequest(initRequest);this.#connect()}get readyState(){return this.#readyState}get url(){return this.#url}get withCredentials(){return this.#withCredentials}#connect(){if(this.#readyState===CLOSED)return;this.#readyState=CONNECTING;const fetchParams={request:this.#request,dispatcher:this.#dispatcher};const processEventSourceEndOfBody=response=>{if(!isNetworkError(response)){return this.#reconnect()}};fetchParams.processResponseEndOfBody=processEventSourceEndOfBody;fetchParams.processResponse=response=>{if(isNetworkError(response)){if(response.aborted){this.close();this.dispatchEvent(new Event("error"));return}else{this.#reconnect();return}}const contentType=response.headersList.get("content-type",true);const mimeType=contentType!==null?parseMIMEType(contentType):"failure";const contentTypeValid=mimeType!=="failure"&&mimeType.essence==="text/event-stream";if(response.status!==200||contentTypeValid===false){this.close();this.dispatchEvent(new Event("error"));return}this.#readyState=OPEN;this.dispatchEvent(new Event("open"));this.#state.origin=response.urlList[response.urlList.length-1].origin;const eventSourceStream=new EventSourceStream({eventSourceSettings:this.#state,push:event=>{this.dispatchEvent(createFastMessageEvent(event.type,event.options))}});pipeline(response.body.stream,eventSourceStream,error=>{if(error?.aborted===false){this.close();this.dispatchEvent(new Event("error"))}})};this.#controller=fetching(fetchParams)}#reconnect(){if(this.#readyState===CLOSED)return;this.#readyState=CONNECTING;this.dispatchEvent(new Event("error"));setTimeout(()=>{if(this.#readyState!==CONNECTING)return;if(this.#state.lastEventId.length){this.#request.headersList.set("last-event-id",this.#state.lastEventId,true)}this.#connect()},this.#state.reconnectionTime)?.unref()}close(){webidl.brandCheck(this,_EventSource);if(this.#readyState===CLOSED)return;this.#readyState=CLOSED;this.#controller.abort();this.#request=null}get onopen(){return this.#events.open}set onopen(fn){if(this.#events.open){this.removeEventListener("open",this.#events.open)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("open",listener);this.#events.open=fn}else{this.#events.open=null}}get onmessage(){return this.#events.message}set onmessage(fn){if(this.#events.message){this.removeEventListener("message",this.#events.message)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("message",listener);this.#events.message=fn}else{this.#events.message=null}}get onerror(){return this.#events.error}set onerror(fn){if(this.#events.error){this.removeEventListener("error",this.#events.error)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("error",listener);this.#events.error=fn}else{this.#events.error=null}}};var constantsPropertyDescriptors={CONNECTING:{__proto__:null,configurable:false,enumerable:true,value:CONNECTING,writable:false},OPEN:{__proto__:null,configurable:false,enumerable:true,value:OPEN,writable:false},CLOSED:{__proto__:null,configurable:false,enumerable:true,value:CLOSED,writable:false}};Object.defineProperties(EventSource,constantsPropertyDescriptors);Object.defineProperties(EventSource.prototype,constantsPropertyDescriptors);Object.defineProperties(EventSource.prototype,{close:kEnumerableProperty,onerror:kEnumerableProperty,onmessage:kEnumerableProperty,onopen:kEnumerableProperty,readyState:kEnumerableProperty,url:kEnumerableProperty,withCredentials:kEnumerableProperty});webidl.converters.EventSourceInitDict=webidl.dictionaryConverter([{key:"withCredentials",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"dispatcher",converter:webidl.converters.any},{key:"node",converter:webidl.dictionaryConverter([{key:"reconnectionTime",converter:webidl.converters["unsigned long"],defaultValue:()=>defaultReconnectionTime},{key:"dispatcher",converter:webidl.converters.any}]),defaultValue:()=>({})}]);module.exports={EventSource,defaultReconnectionTime}}});var require_undici=__commonJS({"node_modules/undici/index.js"(exports,module){"use strict";var Client=require_client();var Dispatcher=require_dispatcher();var Pool2=require_pool();var BalancedPool=require_balanced_pool();var RoundRobinPool=require_round_robin_pool();var Agent2=require_agent();var ProxyAgent2=require_proxy_agent();var Socks5ProxyAgent=require_socks5_proxy_agent();var EnvHttpProxyAgent=require_env_http_proxy_agent();var RetryAgent=require_retry_agent();var H2CClient=require_h2c_client();var errors=require_errors();var util=require_util2();var{InvalidArgumentError}=errors;var api=require_api();var buildConnector=require_connect();var MockClient=require_mock_client();var{MockCallHistory,MockCallHistoryLog}=require_mock_call_history();var MockAgent=require_mock_agent();var MockPool=require_mock_pool();var SnapshotAgent=require_snapshot_agent();var mockErrors=require_mock_errors();var RetryHandler=require_retry_handler();var{getGlobalDispatcher,setGlobalDispatcher}=require_global2();var DecoratorHandler=require_decorator_handler();var RedirectHandler=require_redirect_handler();Object.assign(Dispatcher.prototype,api);module.exports.Dispatcher=Dispatcher;module.exports.Client=Client;module.exports.Pool=Pool2;module.exports.BalancedPool=BalancedPool;module.exports.RoundRobinPool=RoundRobinPool;module.exports.Agent=Agent2;module.exports.ProxyAgent=ProxyAgent2;module.exports.Socks5ProxyAgent=Socks5ProxyAgent;module.exports.EnvHttpProxyAgent=EnvHttpProxyAgent;module.exports.RetryAgent=RetryAgent;module.exports.H2CClient=H2CClient;module.exports.RetryHandler=RetryHandler;module.exports.DecoratorHandler=DecoratorHandler;module.exports.RedirectHandler=RedirectHandler;module.exports.interceptors={redirect:require_redirect(),responseError:require_response_error(),retry:require_retry(),dump:require_dump(),dns:require_dns(),cache:require_cache2(),decompress:require_decompress(),deduplicate:require_deduplicate()};module.exports.cacheStores={MemoryCacheStore:require_memory_cache_store()};var SqliteCacheStore=require_sqlite_cache_store();module.exports.cacheStores.SqliteCacheStore=SqliteCacheStore;module.exports.buildConnector=buildConnector;module.exports.errors=errors;module.exports.util={parseHeaders:util.parseHeaders,headerNameToString:util.headerNameToString};function makeDispatcher(fn){return(url,opts,handler)=>{if(typeof opts==="function"){handler=opts;opts=null}if(!url||typeof url!=="string"&&typeof url!=="object"&&!(url instanceof URL)){throw new InvalidArgumentError("invalid url")}if(opts!=null&&typeof opts!=="object"){throw new InvalidArgumentError("invalid opts")}if(opts&&opts.path!=null){if(typeof opts.path!=="string"){throw new InvalidArgumentError("invalid opts.path")}let path29=opts.path;if(!opts.path.startsWith("/")){path29=`/${path29}`}url=new URL(util.parseOrigin(url).origin+path29)}else{if(!opts){opts=typeof url==="object"?url:{}}url=util.parseURL(url)}const{agent,dispatcher=getGlobalDispatcher()}=opts;if(agent){throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?")}return fn.call(dispatcher,{...opts,origin:url.origin,path:url.search?`${url.pathname}${url.search}`:url.pathname,method:opts.method||(opts.body?"PUT":"GET")},handler)}}module.exports.setGlobalDispatcher=setGlobalDispatcher;module.exports.getGlobalDispatcher=getGlobalDispatcher;var fetchImpl=require_fetch().fetch;var currentFilename=typeof __filename!=="undefined"?__filename:void 0;function appendFetchStackTrace(err,filename){if(!err||typeof err!=="object"){return}const stack=typeof err.stack==="string"?err.stack:"";const normalizedFilename=filename.replace(/\\/g,"/");if(stack&&(stack.includes(filename)||stack.includes(normalizedFilename))){return}const capture2={};Error.captureStackTrace(capture2,appendFetchStackTrace);if(!capture2.stack){return}const captureLines=capture2.stack.split("\n").slice(1).join("\n");err.stack=stack?`${stack}
|
|
125
|
-
${captureLines}`:capture2.stack}module.exports.fetch=function fetch2(init,options=void 0){return fetchImpl(init,options).catch(err=>{if(currentFilename){appendFetchStackTrace(err,currentFilename)}else if(err&&typeof err==="object"){Error.captureStackTrace(err,module.exports.fetch)}throw err})};module.exports.Headers=require_headers().Headers;module.exports.Response=require_response().Response;module.exports.Request=require_request2().Request;module.exports.FormData=require_formdata().FormData;var{setGlobalOrigin,getGlobalOrigin}=require_global();module.exports.setGlobalOrigin=setGlobalOrigin;module.exports.getGlobalOrigin=getGlobalOrigin;var{CacheStorage}=require_cachestorage();var{kConstruct}=require_symbols();module.exports.caches=new CacheStorage(kConstruct);var{deleteCookie,getCookies,getSetCookies,setCookie,parseCookie}=require_cookies();module.exports.deleteCookie=deleteCookie;module.exports.getCookies=getCookies;module.exports.getSetCookies=getSetCookies;module.exports.setCookie=setCookie;module.exports.parseCookie=parseCookie;var{parseMIMEType,serializeAMimeType}=require_data_url();module.exports.parseMIMEType=parseMIMEType;module.exports.serializeAMimeType=serializeAMimeType;var{CloseEvent,ErrorEvent,MessageEvent}=require_events();var{WebSocket,ping}=require_websocket();module.exports.WebSocket=WebSocket;module.exports.CloseEvent=CloseEvent;module.exports.ErrorEvent=ErrorEvent;module.exports.MessageEvent=MessageEvent;module.exports.ping=ping;module.exports.WebSocketStream=require_websocketstream().WebSocketStream;module.exports.WebSocketError=require_websocketerror().WebSocketError;module.exports.request=makeDispatcher(api.request);module.exports.stream=makeDispatcher(api.stream);module.exports.pipeline=makeDispatcher(api.pipeline);module.exports.connect=makeDispatcher(api.connect);module.exports.upgrade=makeDispatcher(api.upgrade);module.exports.MockClient=MockClient;module.exports.MockCallHistory=MockCallHistory;module.exports.MockCallHistoryLog=MockCallHistoryLog;module.exports.MockPool=MockPool;module.exports.MockAgent=MockAgent;module.exports.SnapshotAgent=SnapshotAgent;module.exports.mockErrors=mockErrors;var{EventSource}=require_eventsource();module.exports.EventSource=EventSource;function install(){globalThis.fetch=module.exports.fetch;globalThis.Headers=module.exports.Headers;globalThis.Response=module.exports.Response;globalThis.Request=module.exports.Request;globalThis.FormData=module.exports.FormData;globalThis.WebSocket=module.exports.WebSocket;globalThis.CloseEvent=module.exports.CloseEvent;globalThis.ErrorEvent=module.exports.ErrorEvent;globalThis.MessageEvent=module.exports.MessageEvent;globalThis.EventSource=module.exports.EventSource}module.exports.install=install}});import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";var transports;var init_fetch_transport=__esm({"src/fetch-transport.ts"(){"use strict";transports=new AsyncLocalStorage2}});var init_upstream_fail=__esm({"src/upstream-fail.ts"(){"use strict"}});function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}return{setPosition,getPosition:()=>pos,scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:()=>token,getTokenValue:()=>value,getTokenOffset:()=>tokenOffset,getTokenLength:()=>pos-tokenOffset,getTokenStartLine:()=>lineStartOffset,getTokenStartCharacter:()=>tokenOffset-prevTokenLineStartOffset,getTokenError:()=>scanError}}function isWhiteSpace(ch){return ch===32||ch===9}function isLineBreak(ch){return ch===10||ch===13}function isDigit(ch){return ch>=48&&ch<=57}var CharacterCodes;var init_scanner=__esm({"node_modules/jsonc-parser/lib/esm/impl/scanner.js"(){"use strict";(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}))}});var cachedSpaces,maxCachedValues,cachedBreakLinesWithSpaces;var init_string_intern=__esm({"node_modules/jsonc-parser/lib/esm/impl/string-intern.js"(){"use strict";cachedSpaces=new Array(20).fill(0).map((_2,index)=>{return" ".repeat(index)});maxCachedValues=200;cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}}}});var init_format=__esm({"node_modules/jsonc-parser/lib/esm/impl/format.js"(){"use strict";init_scanner();init_string_intern()}});function parse(text,errors=[],options=ParseOptions.DEFAULT){let currentProperty=null;let currentParent=[];const previousParents=[];function onValue(value){if(Array.isArray(currentParent)){currentParent.push(value)}else if(currentProperty!==null){currentParent[currentProperty]=value}}const visitor={onObjectBegin:()=>{const object={};onValue(object);previousParents.push(currentParent);currentParent=object;currentProperty=null},onObjectProperty:name2=>{currentProperty=name2},onObjectEnd:()=>{currentParent=previousParents.pop()},onArrayBegin:()=>{const array=[];onValue(array);previousParents.push(currentParent);currentParent=array;currentProperty=null},onArrayEnd:()=>{currentParent=previousParents.pop()},onLiteralValue:onValue,onError:(error,offset,length)=>{errors.push({error,offset,length})}};visit(text,visitor,options);return currentParent[0]}function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}var ParseOptions;var init_parser=__esm({"node_modules/jsonc-parser/lib/esm/impl/parser.js"(){"use strict";init_scanner();(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}))}});var init_edit=__esm({"node_modules/jsonc-parser/lib/esm/impl/edit.js"(){"use strict";init_format();init_parser()}});function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}var ScanError,SyntaxKind,parse2,ParseErrorCode;var init_main=__esm({"node_modules/jsonc-parser/lib/esm/main.js"(){"use strict";init_format();init_edit();init_scanner();init_parser();(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));parse2=parse;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}))}});import{createHash as createHash2}from"crypto";function hashId(s3){return createHash2("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var BILI_PASSTHROUGH_HEADER,MIN_ASSUMED_WINDOW_TOKENS;var init_util=__esm({"src/util.ts"(){"use strict";BILI_PASSTHROUGH_HEADER="x-bili-passthrough";MIN_ASSUMED_WINDOW_TOKENS=1e6}});var DEFAULT_MITM_DOMAINS;var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict";DEFAULT_MITM_DOMAINS=["api.anthropic.com","api.openai.com","chatgpt.com"]}});var init_compat_roles=__esm({"src/compat-roles.ts"(){"use strict";init_config()}});var init_compat_drop=__esm({"src/compat-drop.ts"(){"use strict";init_config()}});var init_private_host=__esm({"src/private-host.ts"(){"use strict"}});var SUMMARY_DEFAULT_BUDGET;var init_external_summary_settings=__esm({"src/external-summary-settings.ts"(){"use strict";init_logger();init_private_host();init_knobs();SUMMARY_DEFAULT_BUDGET={totalTimeoutMs:5e4,targetTimeoutMs:25e3,maxSummaryBytes:64*1024}}});import{readFileSync as readFileSync2,existsSync,mkdirSync as mkdirSync3,writeFileSync}from"fs";import{createHash as createHash3}from"crypto";import{dirname}from"path";function resolveRecordedMitmDomains(passed,env=process.env){const fileConfig=loadConfigFile();const enabled=(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0";if(!enabled)return[];const effective=passed&&passed.length>0?passed.join(","):env.BILI_MITM_DOMAINS;return dedupeDomains([...fileConfig.mitm?.domains??[],...splitCsv(effective)])}function splitCsv(value){if(!value)return[];return value.split(",").map(s3=>s3.trim()).filter(s3=>s3.length>0)}function dedupeDomains(list){const seen=new Set;const out=[];for(const d of list){if(!seen.has(d)){seen.add(d);out.push(d)}}return out}function warnUnknownTopLevelKeys(obj){const unknown=Object.keys(obj).filter(key=>!KNOWN_TOP_LEVEL_KEYS.has(key)&&key!=="allowDshCompaction");if(unknown.length===0)return;const signature=[...unknown].sort().join("\0");if(seenUnknownTopLevelKeySignatures.has(signature))return;seenUnknownTopLevelKeySignatures.add(signature);const misplaced=unknown.filter(key=>COMPRESS_SETTING_FIELDS.has(key));const hint=misplaced.length>0?` \u2014 ${misplaced.map(k2=>`"${k2}" belongs under "compress" (did you mean "compress.${k2}"?)`).join("; ")}`:"";log("warn",`[acp-config] ignoring unknown top-level config key(s): ${unknown.join(", ")}${hint}`)}function parseBiliConfig(raw){try{return JSON.parse(raw)}catch{const errors=[];const value=parse2(raw,errors,{allowTrailingComma:true});if(errors.length===0)return value;const first=errors[0];throw new SyntaxError(`invalid JSON/JSONC at ${lineColumnOf(raw,first.offset)}: ${printParseErrorCode(first.error)}`)}}function lineColumnOf(text,offset){let line=1;let column=1;for(let i=0;i<offset&&i<text.length;i++){if(text.charAt(i)==="\n"){line++;column=1}else column++}return`line ${line} column ${column}`}function loadConfigFile(){const path29=configFile();let raw;let value;try{raw=readFileSync2(path29,"utf8").replace(/^\uFEFF/,"");const cached=configFileCache;if(cached&&cached.raw===raw)return cached.value;const parsed=parseBiliConfig(raw);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){const obj=parsed;warnRemovedDshAllowKey(obj);warnUnknownTopLevelKeys(obj);warnInertResignPassthrough(obj);warnInertStripImages(obj);warnInertRemovedCompressKeys(obj);value=obj}else{value={}}}catch(e){if(e.code!=="ENOENT"){log("error",`[acp-config] failed to parse ${path29}: ${String(e)}`)}if(raw!==void 0)value={}}if(raw===void 0||value===void 0)return{};configFileCache={raw,value};return value}function warnRemovedDshAllowKey(obj){const hits=[];if(Object.prototype.hasOwnProperty.call(obj,"allowDshCompaction")&&obj.allowDshCompaction!==null&&obj.allowDshCompaction!==void 0){hits.push('top-level "allowDshCompaction"')}const d=obj.dsh;if(d!==null&&typeof d==="object"&&!Array.isArray(d)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key of Object.keys(d))if(!live.has(key))hits.push(`dsh.${key}`)}hits.sort();const sig=hits.join(",");if(sig===""||sig===removedDshAllowKeySignature)return;removedDshAllowKeySignature=sig;log("warn",`[acp-config] ${hits.join(", ")} was removed (#3651, superseding #2028) \u2014 value(s) ignored: dsh native compaction is now refused unconditionally by the wire guard on every lane. Delete it from your config to silence this.`)}function resolveResignSettings(env=process.env,provider={},scheme=RESIGN_BUILTIN_SCHEME){const key=scheme.trim().toLowerCase();const file=loadConfigFile().resign?.[key]??{};const providerBlock=provider?.[key]??{};const enabled=env.BILI_RESIGN!==void 0?env.BILI_RESIGN!=="0":providerBlock.enabled!==void 0?providerBlock.enabled:file.enabled!==false;const passthrough=env.BILI_RESIGN_PASSTHROUGH!==void 0?env.BILI_RESIGN_PASSTHROUGH==="1"||env.BILI_RESIGN_PASSTHROUGH==="true":providerBlock.passthrough!==void 0?providerBlock.passthrough:file.passthrough===true;const credentialRef=env.BILI_CODEARTS_REF?.trim()||providerBlock.credentialRef||file.credentialRef||void 0;return{enabled,passthrough,credentialRef}}function warnInertStripImages(obj){const compress=obj.compress;if(!compress||typeof compress!=="object"||Array.isArray(compress))return;const hit=["stripImages","stripImagesKeepRecent"].filter(k2=>compress[k2]!==void 0);const sig=hit.join(",");if(sig===""||sig===seenInertStripImagesSignature)return;seenInertStripImagesSignature=sig;log("warn",`[acp-config] compress.${hit.join("/compress.")} is INERT \u2014 compress.stripImages was removed: media now folds by default (#2640) and decompress({ imageRef }) recovers folded pixels; nothing is stripped from the wire anymore. Remove the key(s) from the config.`)}function warnInertRemovedCompressKeys(obj){const hits=[];const scanBlock=(block,pathPrefix)=>{if(!block||typeof block!=="object"||Array.isArray(block))return;for(const key of INERT_REMOVED_COMPRESS_KEYS){if(block[key]!==void 0)hits.push(`${pathPrefix}.${key}`)}};scanBlock(obj.compress,"compress");const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const[url,entry]of Object.entries(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const p2=entry;scanBlock(p2.compress,`providers["${url}"].compress`);const models=p2.models;if(models&&typeof models==="object"&&!Array.isArray(models)){for(const[model,mEntry]of Object.entries(models)){if(!mEntry||typeof mEntry!=="object"||Array.isArray(mEntry))continue;scanBlock(mEntry.compress,`providers["${url}"].models["${model}"].compress`)}}}}hits.sort();const sig=hits.join(",");if(sig===""||sig===seenInertRemovedCompressKeysSignature)return;seenInertRemovedCompressKeysSignature=sig;log("warn",`[acp-config] ${hits.join(", ")} is INERT \u2014 compress.imageCompression was removed and no longer does anything at any level (image pre-compression + image_full restore channel, #3266). Remove it from the config; images pass through byte-identical.`)}function warnInertResignPassthrough(obj){const inert=[];const consider=(map,providerBlockFor)=>{if(!map||typeof map!=="object"||Array.isArray(map))return;for(const[key,val]of Object.entries(map)){if(key===RESIGN_BUILTIN_SCHEME)continue;const block=val!==null&&typeof val==="object"&&!Array.isArray(val)?val:{};if(block["passthrough"]!==true)continue;const fileBlock=(obj.resign??{})[key];const providerBlock=providerBlockFor(key);const enabled=process.env.BILI_RESIGN!==void 0?process.env.BILI_RESIGN!=="0":providerBlock?.enabled!==void 0?providerBlock.enabled:fileBlock?.enabled!==false;if(enabled)inert.push(key)}};consider(obj.resign,()=>void 0);const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const entry of Object.values(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const pmap=entry.resign;if(pmap===void 0)continue;consider(pmap,key=>(pmap??{})[key])}}inert.sort();const sig=inert.join(",");if(sig===""||sig===inertResignPassthroughSignature)return;inertResignPassthroughSignature=sig;const list=inert.map(k2=>`resign["${k2}"].passthrough`).join(", ");log("warn",`[acp-config] ${list}=true is INERT \u2014 since the #2090 compress-or-refuse contract, unsigned pass-through exists ONLY for the built-in scheme "${RESIGN_BUILTIN_SCHEME}"; those signed requests stay REFUSED until bili ships a re-signer for them. Restore pre-resign handling with resign["<scheme>"].enabled=false or BILI_RESIGN=0 (the upstream will then reject the rewritten bodies).`)}function resolveZonePortBase(env=process.env){const fromEnv=Number.parseInt(env.BILI_ZONE_PORT??"",10);if(Number.isInteger(fromEnv)&&fromEnv>0&&fromEnv<65536)return fromEnv;return ZONE_PORT_BASE}function resolveNativeAttachExternal(env=process.env){const fromEnv=(env.BILI_NATIVE_ATTACH_EXTERNAL??"").trim().toLowerCase();if(fromEnv==="1"||fromEnv==="true")return true;if(fromEnv==="0"||fromEnv==="false")return false;return loadConfigFile().native?.attachExternal===true}function resolveNativeAttachLanePriority(){const raw=loadConfigFile().native?.attachLanePriority;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item!=="string")continue;const t=item.trim();if(t.length>0&&!out.includes(t))out.push(t)}return out}function adminRelayEnabled(){return loadConfigFile().security?.adminRelay===true}function resolveNativeAttachPolicy(env=process.env){const norm=v2=>(v2??"").trim().toLowerCase();const fromEnv=norm(env.BILI_NATIVE_ATTACH_POLICY);if(fromEnv==="global-fallback"||fromEnv==="global")return"global-fallback";if(fromEnv==="own-lane"||fromEnv==="ownlane"||fromEnv==="strict")return"own-lane";const file=norm(loadConfigFile().native?.attachPolicy);if(file==="global-fallback"||file==="global")return"global-fallback";return"own-lane"}function resolveNativeAttachUrl(env=process.env){const fromEnv=(env.BILI_MCP_PROXY??"").trim();if(fromEnv.length>0)return fromEnv;const file=(loadConfigFile().native?.attachUrl??"").trim();return file.length>0?file:void 0}var KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature,ZONE_PORT_BASE;var init_config=__esm({"src/config.ts"(){"use strict";init_main();init_paths();init_logger();init_upstream_proxy();init_log_mask();init_util();init_mitm_domains();init_compat_roles();init_compat_drop();init_external_summary_settings();KNOWN_TOP_LEVEL_KEYS=new Set(["port","host","upstream","providersPath","providers","proxy","modelContextLimit","sessionHeader","log","debug","dumpSse","passthrough","autoUpdate","autoRestartOnUpdate","updateTag","advisoryCheck","advisoryUrl","releaseNotesCheck","releaseNotesUrl","upstreamProxy","upstreamProxyMode","logFile","compress","promptCache","mitm","maskHosts","subagentSplit","forkAdoption","affinitySimhash","resumeInheritance","chainContentDetection","chainEgressStamp","stableSystemAnchor","rollout","dsh","compat","imageBilling","imageTokenCap","claude","native","resign","pi","storage","security","network","persist","sessions","plugin","update","diagnostics","fakeCompletion","codexCompact","ccrRetrievalTtlMs","decompressTmpCap","autoModeForge","imageRescale","guardrails","cacheKeepalive"]);COMPRESS_SETTING_FIELDS=new Set(["modelContextLimit","maxContextLimit","emergencyThresholdPercent","nudgeGrowthTokens","minPressureBenefitTokens","tierNudgeTokens","nudgeModelDecided","nudgeDecisionMaxTokens","preserveRecentMessages","preserveRecentTokens","minCompressRange","minCompressRangeChars","outputHeadroomMaxPct","tiers","protectedLatestTools","protectedTools","neverPreserveRecentTools","preserveRecentTools","visibilityMarkers","rules","injectTool","injectNudge","acknowledgePromptsRisk","absorb","ccr","search","prompts","promptPack","reasoningGuard","outputSteering","priceProfile","reconcile","streamSummary"]);seenUnknownTopLevelKeySignatures=new Set;configFileCache=null;removedDshAllowKeySignature="";RESIGN_BUILTIN_SCHEME="sdk-hmac-sha256";inertResignPassthroughSignature=null;seenInertStripImagesSignature="";INERT_REMOVED_COMPRESS_KEYS=["imageCompression"];seenInertRemovedCompressKeysSignature="";ZONE_PORT_BASE=18787}});var init_duration=__esm({"src/duration.ts"(){"use strict"}});import{createHash as createHash4}from"crypto";var MIN_MEDIA_URL_SPLIT_BYTES,MEDIA_URL_MARKER_RE;var init_identity=__esm({"src/storage/identity.ts"(){"use strict";MIN_MEDIA_URL_SPLIT_BYTES=2048;MEDIA_URL_MARKER_RE=new RegExp(`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,"g")}});function storagePragmas(walJournalSizeLimitBytes){return["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA busy_timeout = 5000","PRAGMA foreign_keys = ON",`PRAGMA journal_size_limit = ${walJournalSizeLimitBytes}`,"PRAGMA auto_vacuum = INCREMENTAL"]}var WAL_JOURNAL_SIZE_LIMIT,STORAGE_PRAGMAS;var init_schema=__esm({"src/storage/schema.ts"(){"use strict";init_identity();WAL_JOURNAL_SIZE_LIMIT=8*1024*1024;STORAGE_PRAGMAS=storagePragmas(WAL_JOURNAL_SIZE_LIMIT)}});import path6 from"path";function tNumLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tInt(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v2=envRaw!==void 0?Number.parseInt(envRaw,10):(()=>{const f2=loadConfigFile().sessions?.max;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Math.max(1,v2||256)}function sessionResidentMaxBytes(){const v2=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v2)&&v2>=0?Math.floor(v2):512*1024*1024}function updateRegistryBase(){const envRaw=process.env.BILI_UPDATE_REGISTRY;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.registry;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateCheckIntervalMs(){const v2=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v2)&&v2>0?Math.floor(v2):3*60*1e3}function dshContextTabEnabled(){const envRaw=process.env.BILI_DSH_CONTEXT_TAB;if(envRaw!==void 0)return!(envRaw.trim()==="0"||envRaw.trim().toLowerCase()==="false");return loadConfigFile().dsh?.contextTab!==false}function dshContextTabLabel(){const f2=loadConfigFile().dsh?.contextTabLabel;const s3=typeof f2==="string"?f2.trim():"";return s3.length>0?s3:void 0}var DEFAULT_LIMITS_RECEIVE_BYTES,DEFAULT_LIMITS_DECODED_BYTES,DEFAULT_LIMITS_OUTBOUND_BYTES,DEFAULT_WS_OUTBOUND_BYTES;var init_knobs=__esm({"src/knobs.ts"(){"use strict";init_paths();init_config();init_duration();init_fetch_util();init_upstream_proxy();init_schema();DEFAULT_LIMITS_RECEIVE_BYTES=5*1024*1024*1024;DEFAULT_LIMITS_DECODED_BYTES=10*1024*1024*1024;DEFAULT_LIMITS_OUTBOUND_BYTES=5*1024*1024*1024;DEFAULT_WS_OUTBOUND_BYTES=10*1024*1024}});import{readFileSync as readFileSync3,statSync as statSync2}from"fs";import*as tls2 from"tls";var init_upstream_ca=__esm({"src/upstream-ca.ts"(){"use strict";init_logger();init_knobs()}});var MAX_REQUEST_BYTES,MAX_DECODED_REQUEST_BYTES;var init_request_body_budget=__esm({"src/request-body-budget.ts"(){"use strict";init_knobs();MAX_REQUEST_BYTES=100*1024*1024;MAX_DECODED_REQUEST_BYTES=2*MAX_REQUEST_BYTES}});var import_undici,UPSTREAM_TIMEOUT_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici=__toESM(require_undici(),1);init_fetch_transport();init_upstream_fail();init_upstream_ca();init_knobs();init_request_body_budget();init_request_body_budget();UPSTREAM_TIMEOUT_MS=12*60*1e3}});import{execFileSync as execFileSync3}from"child_process";import net from"net";import tls3 from"tls";var import_undici2;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs()}});var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path7 from"path";var TOML_KEY_PART_RE;var init_client_config=__esm({"src/client-config.ts"(){"use strict";init_main();init_vertex();TOML_KEY_PART_RE=new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`)}});import{createHash as createHash5,randomUUID}from"crypto";import fs4 from"fs";import os4 from"os";import path9 from"path";function isProxyInstanceFile(v2){return v2!==void 0&&"instanceId"in v2}function readProxyInstanceFile(file){let raw;try{raw=fs4.readFileSync(file??instanceFilePath(),"utf8").trim()}catch{return void 0}if(raw.startsWith("{")){try{const parsed=JSON.parse(raw);if(typeof parsed.origin==="string"&&/^https?:\/\/\S+$/.test(parsed.origin)){const windows={};if(parsed.modelWindows&&typeof parsed.modelWindows==="object"){for(const[k2,v2]of Object.entries(parsed.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(parsed.modelMaxOutputs&&typeof parsed.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(parsed.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{origin:parsed.origin,instanceId:typeof parsed.instanceId==="string"?parsed.instanceId:"",pid:typeof parsed.pid==="number"?parsed.pid:0,startedAt:typeof parsed.startedAt==="number"?parsed.startedAt:0,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,passthrough:Boolean(parsed.passthrough),mitmDomains:Array.isArray(parsed.mitmDomains)?parsed.mitmDomains.map(String):[],modelWindows:windows,modelMaxOutputs:Object.keys(maxOutputs).length>0?maxOutputs:void 0,launchToken:typeof parsed.launchToken==="string"?parsed.launchToken:void 0,lane:typeof parsed.lane==="string"&&parsed.lane!==""?parsed.lane:void 0,codeFingerprint:typeof parsed.codeFingerprint==="string"&&parsed.codeFingerprint!==""?parsed.codeFingerprint:void 0}}}catch{}}if(/^https?:\/\/\S+$/.test(raw))return{origin:raw};return void 0}function instanceFilePath(){return path9.join(stateDir(),"proxy-origin")}function portZoneFilePath(){return path9.join(stateDir(),"port-zone.json")}function readZonePort(lane,file=portZoneFilePath()){let raw;try{raw=fs4.readFileSync(file,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);const v2=parsed?.lanes?.[lane];if(typeof v2==="number"&&Number.isInteger(v2)&&v2>0&&v2<65536)return v2;return void 0}catch{return void 0}}function writeZonePort(lane,port,file=portZoneFilePath()){if(!Number.isInteger(port)||port<=0||port>=65536)return;let cur={};try{const parsed=JSON.parse(fs4.readFileSync(file,"utf8"));if(parsed!==null&&typeof parsed==="object"&&parsed.lanes!==null&&typeof parsed.lanes==="object")cur=parsed}catch{}atomicWriteJson({lanes:{...cur.lanes??{},[lane]:port}},file)}function lanePreferredPort(lane,env=process.env,file=portZoneFilePath()){return readZonePort(lane,file)??resolveZonePortBase(env)}function entryScriptFingerprint(scriptPath){if(!scriptPath)return void 0;const resolved=path9.resolve(scriptPath);const cached=scriptFingerprints.get(resolved);if(cached!==void 0)return cached;let digest;try{digest=createHash5("sha256").update(fs4.readFileSync(resolved)).digest("hex")}catch{return void 0}scriptFingerprints.set(resolved,digest);return digest}function atomicWriteJson(obj,filePath){fs4.mkdirSync(path9.dirname(filePath),{recursive:true});const tempPath=`${filePath}.${process.pid}.${randomUUID()}.tmp`;let descriptor;try{descriptor=fs4.openSync(tempPath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(obj)+"\n",null,"utf8");fs4.fsyncSync(descriptor);fs4.closeSync(descriptor);descriptor=void 0;fs4.renameSync(tempPath,filePath)}catch(error){if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}try{fs4.unlinkSync(tempPath)}catch{}throw error}}function startingMarkerPath(){return path9.join(stateDir(),"proxy-starting")}function readStartingMarker(file){let raw;try{raw=fs4.readFileSync(file??startingMarkerPath(),"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed.token!=="string"||parsed.token==="")return void 0;if(typeof parsed.pid!=="number"||!Number.isInteger(parsed.pid)||parsed.pid<=0)return void 0;if(typeof parsed.startedAt!=="number")return void 0;return{token:parsed.token,pid:parsed.pid,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,startedAt:parsed.startedAt,...typeof parsed.lane==="string"&&parsed.lane!==""?{lane:parsed.lane}:{}}}catch{return void 0}}function claimStartingMarker(marker,file){const filePath=file??startingMarkerPath();let descriptor;try{fs4.mkdirSync(path9.dirname(filePath),{recursive:true});descriptor=fs4.openSync(filePath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(marker)+"\n",null,"utf8");fs4.fsyncSync(descriptor);descriptor=void 0;return true}catch{if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}return false}}function clearStartingMarker(token,file){const filePath=file??startingMarkerPath();const current=readStartingMarker(filePath);if(current&¤t.token===token){try{fs4.unlinkSync(filePath)}catch{}}}function removeStartingMarker(file){try{fs4.unlinkSync(file??startingMarkerPath())}catch{}}function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err){return err.code==="EPERM"}}function registryDirPath(){return path9.join(stateDir(),"instances")}function legacyRegistryFilePath(){return path9.join(stateDir(),"instances.json")}function safeReadJson(file){try{return JSON.parse(fs4.readFileSync(file,"utf8"))}catch{return void 0}}function coerceEntry(value){if(!value||typeof value!=="object")return void 0;const o=value;if(typeof o.instanceId!=="string"||o.instanceId==="")return void 0;const windows={};if(o.modelWindows&&typeof o.modelWindows==="object"){for(const[k2,v2]of Object.entries(o.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(o.modelMaxOutputs&&typeof o.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(o.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{instanceId:o.instanceId,pid:typeof o.pid==="number"?o.pid:0,port:typeof o.port==="number"?o.port:0,origin:typeof o.origin==="string"?o.origin:"",startedAt:typeof o.startedAt==="number"?o.startedAt:0,...typeof o.host==="string"&&o.host!==""?{host:o.host}:{},...typeof o.passthrough==="boolean"?{passthrough:o.passthrough}:{},...Array.isArray(o.mitmDomains)?{mitmDomains:o.mitmDomains.map(String)}:{},...Object.keys(windows).length>0?{modelWindows:windows}:{},...Object.keys(maxOutputs).length>0?{modelMaxOutputs:maxOutputs}:{},...typeof o.lane==="string"&&o.lane!==""?{lane:o.lane}:{},...typeof o.codeFingerprint==="string"&&o.codeFingerprint!==""?{codeFingerprint:o.codeFingerprint}:{}}}function readMarkerNames(){try{return fs4.readdirSync(registryDirPath())}catch{return[]}}function readAllRegistryEntries(){const seen=new Set;const out=[];for(const name2 of readMarkerNames()){if(!name2.endsWith(".json"))continue;const entry=coerceEntry(safeReadJson(path9.join(registryDirPath(),name2)));if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}const legacy=safeReadJson(legacyRegistryFilePath());if(legacy&&Array.isArray(legacy.instances)){for(const raw of legacy.instances){const entry=coerceEntry(raw);if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}}return out}function discoverLiveInstances(){const out=[];for(const e of readAllRegistryEntries()){if(!isPidAlive(e.pid))continue;out.push({origin:e.origin,instanceId:e.instanceId,pid:e.pid,startedAt:e.startedAt,host:e.host??"",port:e.port,passthrough:Boolean(e.passthrough),mitmDomains:e.mitmDomains??[],modelWindows:e.modelWindows??{},modelMaxOutputs:e.modelMaxOutputs,lane:e.lane,codeFingerprint:e.codeFingerprint})}return out}var scriptFingerprints;var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths();scriptFingerprints=new Map}});var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs5 from"fs";import path10 from"path";import{execFile,spawnSync}from"child_process";import{promisify}from"util";var DSH_PACKAGE,DSH_EXEC_TIMEOUT_MS,pExecFile;var init_dsh_channel=__esm({"src/dsh-channel.ts"(){"use strict";init_client_config();init_win_cmd();DSH_PACKAGE="billion-context";DSH_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile=promisify(execFile)}});import fs6 from"fs";import path11 from"path";import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";var PI_NPM_SPEC,PI_EXEC_TIMEOUT_MS,pExecFile2;var init_pi_channel=__esm({"src/pi-channel.ts"(){"use strict";init_client_config();init_dsh_channel();PI_NPM_SPEC="npm:billion-context";PI_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile2=promisify2(execFile2)}});import Qr from"events";import I from"fs";import{EventEmitter as Di}from"events";import Cs from"stream";import{StringDecoder as Hr}from"string_decoder";import cr from"path";import Kt from"fs";import{dirname as Fn,parse as kn}from"path";import{EventEmitter as Dn}from"events";import zi from"assert";import{Buffer as Ot}from"buffer";import*as Ps from"zlib";import en from"zlib";import{posix as Zt}from"path";import{basename as _n}from"path";import mi from"fs";import X from"fs";import js from"path";import{win32 as Pn}from"path";import ar from"path";import Br from"fs";import co from"assert";import{randomBytes as Mr}from"crypto";import u from"fs";import R from"path";import pr from"fs";import wi from"fs";import we from"path";import k from"fs";import ro from"fs/promises";import Si from"path";import{join as xr}from"path";import v from"fs";import Pr from"path";function Zn(s3,t,e){let i=t,r=t?t.next:s3.head,n=new ue(e,i,r,s3);return n.next===void 0&&(s3.tail=n),n.prev===void 0&&(s3.head=n),s3.length++,n}function Yn(s3,t){s3.tail=new ue(t,s3.tail,void 0,s3),s3.head||(s3.head=s3.tail),s3.length++}function Kn(s3,t){s3.head=new ue(t,void 0,s3.head,s3),s3.tail||(s3.tail=s3.head),s3.length++}var zr,Ur,Ds,Wr,Gr,Zr,Q,J,nt,De,qt,Ne,Ns,Ae,As,z,Mt,g,Qt,Bt,b,N,_,bi,Ie,L,S,_i,Oi,Is,Ti,Z,xi,Ce,Jt,Rt,C,jt,Yr,Kr,Vr,$r,Fe,Li,Xr,qr,A,Jr,ht,H,te,m,Ni,tt,Ai,ki,vi,ie,ke,Ut,Ht,Ii,Pt,at,U,ot,Y,zt,Ci,j,ee,Fi,ve,gt,Me,bt,_t,Be,et,Wt,jr,Fs,ks,vs,Ms,Bs,tn,se,K,sn,M,rn,zs,nn,Bi,Tt,Gt,Pi,re,Pe,ze,Ue,He,We,Ge,Ze,Ye,Ke,Us,hn,an,Hs,ln,cn,Ws,Gs,Hi,ne,dn,Ui,oe,Ve,un,F,mn,xt,Wi,pn,lt,En,wn,Sn,ct,yn,Rn,gn,Gi,bn,Lt,ft,On,Tn,xn,Ln,f,$e,Dt,Nn,Xi,qi,An,B,Nt,it,Zi,Zs,V,he,dt,Ys,p,st,ut,Yi,At,w,Xe,qe,Ki,Ks,Vs,ae,Vi,Qe,Yt,$,Je,It,je,ti,$s,In,le,$i,Xs,Cn,rt,mt,vn,Qi,Mn,Bn,Ct,Ji,zn,qs,ce,ei,ji,Un,Hn,ts,Qs,rr,Wn,tr,er,ir,is,sr,fe,ii,ss,si,rs,ns,os5,hs,pt,ri,as,es,q,de,ni,oi,Gn,hi,ue,pi,nr,li,me,W,pe,Et,Ft,Ee,ai,G,ls,ci,or,ds,us,fi,di,hr,cs,ui,lr,fs7,wt,kt,Vn,$n,fr,dr,Xn,qn,Qn,Jn,Er,wr,ur,Sr,yr,Rr,jn,to,eo,mr,ms,ps,Ei,io,Es,so,ws,Se,St,no,gr,Ss,br,oo,_r,ys,Or,Vt,Tr,ho,ao,lo,yi,Lr,Dr,_s,Nr,Os,P,Ts,xs,gi,Ar,Ir,Re,Cr,Fr,Rs,yt,O,Ri,kr,$t,gs,bs,Ls,ge,be,_e,Oe,fo,Te,uo,mo,po,vr,Xt,ye,xe,Eo,wo,So,yo,Ro,go,bo,_o,vt,Oo,To;var init_index_min=__esm({"node_modules/tar/dist/esm/index.min.js"(){"use strict";zr=Object.defineProperty;Ur=(s3,t)=>{for(var e in t)zr(s3,e,{get:t[e],enumerable:true})};Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null};Wr=s3=>!!s3&&typeof s3=="object"&&(s3 instanceof A||s3 instanceof Cs||Gr(s3)||Zr(s3));Gr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.pipe=="function"&&s3.pipe!==Cs.Writable.prototype.pipe;Zr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.write=="function"&&typeof s3.end=="function";Q=Symbol("EOF");J=Symbol("maybeEmitEnd");nt=Symbol("emittedEnd");De=Symbol("emittingEnd");qt=Symbol("emittedError");Ne=Symbol("closed");Ns=Symbol("read");Ae=Symbol("flush");As=Symbol("flushChunk");z=Symbol("encoding");Mt=Symbol("decoder");g=Symbol("flowing");Qt=Symbol("paused");Bt=Symbol("resume");b=Symbol("buffer");N=Symbol("pipes");_=Symbol("bufferLength");bi=Symbol("bufferPush");Ie=Symbol("bufferShift");L=Symbol("objectMode");S=Symbol("destroyed");_i=Symbol("error");Oi=Symbol("emitData");Is=Symbol("emitEnd");Ti=Symbol("emitEnd2");Z=Symbol("async");xi=Symbol("abort");Ce=Symbol("aborted");Jt=Symbol("signal");Rt=Symbol("dataListeners");C=Symbol("discarded");jt=s3=>Promise.resolve().then(s3);Yr=s3=>s3();Kr=s3=>s3==="end"||s3==="finish"||s3==="prefinish";Vr=s3=>s3 instanceof ArrayBuffer||!!s3&&typeof s3=="object"&&s3.constructor&&s3.constructor.name==="ArrayBuffer"&&s3.byteLength>=0;$r=s3=>!Buffer.isBuffer(s3)&&ArrayBuffer.isView(s3);Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}};Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}};Xr=s3=>!!s3.objectMode;qr=s3=>!s3.objectMode&&!!s3.encoding&&s3.encoding!=="buffer";A=class extends Di{[g]=false;[Qt]=false;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=false;[nt]=false;[De]=false;[Ne]=false;[qt]=null;[_]=0;[S]=false;[Jt];[Ce]=false;[Rt]=0;[C]=false;writable=true;readable=true;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=true,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=false):(this[L]=false,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=true,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return false;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=false,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Q]=true,this.writable=false,(this[g]||!this[Qt])&&this[J](),this}[Bt](){this[S]||(!this[Rt]&&!this[N].length&&(this[C]=true),this[Qt]=false,this[g]=true,this.emit("resume"),this[b].length?this[Ae]():this[Q]?this[J]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=false,this[Qt]=true,this[C]=false}get destroyed(){return this[S]}get flowing(){return this[g]}get paused(){return this[Qt]}[bi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ie](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[Ae](t=false){do;while(this[As](this[Ie]())&&this[b].length);!t&&!this[b].length&&!this[Q]&&this.emit("drain")}[As](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[S])return t;this[C]=false;let i=this[nt];return e=e||{},t===Ds.stdout||t===Ds.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[N].push(e.proxyErrors?new Li(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[N].find(i=>i.dest===t);e&&(this[N].length===1?(this[g]&&this[Rt]===0&&(this[g]=false),this[N]=[]):this[N].splice(this[N].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[C]=false,this[Rt]++,!this[N].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Kr(t)&&this[nt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[C]&&!this[N].length&&(this[g]=false)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[C]&&!this[N].length&&(this[g]=false)),e}get emittedEnd(){return this[nt]}[J](){!this[De]&&!this[nt]&&!this[S]&&this[b].length===0&&this[Q]&&(this[De]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[De]=false)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==S&&this[S])return false;if(t==="data")return!this[L]&&!i?false:this[Z]?(jt(()=>this[Oi](i)),true):this[Oi](i);if(t==="end")return this[Is]();if(t==="close"){if(this[Ne]=true,!this[nt]&&!this[S])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(_i,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):false;return this[J](),n}else if(t==="resume"){let n=super.emit("resume");return this[J](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[J](),r}[Oi](t){for(let i of this[N])i.dest.write(t)===false&&this.pause();let e=this[C]?false:super.emit("data",t);return this[J](),e}[Is](){return this[nt]?false:(this[nt]=true,this.readable=false,this[Z]?(jt(()=>this[Ti]()),true):this[Ti]())}[Ti](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[N])i.dest.write(e);this[C]||super.emit("data",e)}}for(let e of this[N])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(S,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[C]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Q])return e();let n,o,h=d=>{this.off("data",a),this.off("end",l),this.off(S,c),e(),o(d)},a=d=>{this.off("error",h),this.off("end",l),this.off(S,c),this.pause(),n({value:d,done:!!this[Q]})},l=()=>{this.off("error",h),this.off("data",a),this.off(S,c),e(),n({done:true,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((d,y)=>{o=y,n=d,this.once(S,c),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[C]=false;let t=false,e=()=>(this.pause(),this.off(_i,e),this.off(S,e),this.off("end",e),t=true,{done:true,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(_i,e),this.once(S,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[S])return t?this.emit("error",t):this.emit(S),this;this[S]=true,this[C]=true,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(S),this}static get isStream(){return Wr}};Jr=I.writev;ht=Symbol("_autoClose");H=Symbol("_close");te=Symbol("_ended");m=Symbol("_fd");Ni=Symbol("_finished");tt=Symbol("_flags");Ai=Symbol("_flush");ki=Symbol("_handleChunk");vi=Symbol("_makeBuf");ie=Symbol("_mode");ke=Symbol("_needDrain");Ut=Symbol("_onerror");Ht=Symbol("_onopen");Ii=Symbol("_onread");Pt=Symbol("_onwrite");at=Symbol("_open");U=Symbol("_path");ot=Symbol("_pos");Y=Symbol("_queue");zt=Symbol("_read");Ci=Symbol("_readSize");j=Symbol("_reading");ee=Symbol("_remain");Fi=Symbol("_size");ve=Symbol("_write");gt=Symbol("_writing");Me=Symbol("_defaultFlag");bt=Symbol("_errored");_t=class extends A{[bt]=false;[m];[U];[Ci];[j]=false;[Fi];[ee];[ht];constructor(t,e){if(e=e||{},super(e),this.readable=true,this.writable=false,typeof t!="string")throw new TypeError("path must be a string");this[bt]=false,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ci]=e.readSize||16*1024*1024,this[j]=false,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true,typeof this[m]=="number"?this[zt]():this[at]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[at](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[vi](){return Buffer.allocUnsafe(Math.min(this[Ci],this[ee]))}[zt](){if(!this[j]){this[j]=true;let t=this[vi]();if(t.length===0)return process.nextTick(()=>this[Ii](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ii](e,i,r))}}[Ii](t,e,i){this[j]=false,t?this[Ut](t):this[ki](e,i)&&this[zt]()}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[j]=true,this[H](),this.emit("error",t)}[ki](t,e){let i=false;return this[ee]-=t,t>0&&(i=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ee]<=0)&&(i=false,this[H](),super.end()),i}emit(t,...e){switch(t){case"prefinish":case"finish":return false;case"drain":return typeof this[m]=="number"&&this[zt](),false;case"error":return this[bt]?false:(this[bt]=true,super.emit(t,...e));default:return super.emit(t,...e)}}};Be=class extends _t{[at](){let t=true;try{this[Ht](null,I.openSync(this[U],"r")),t=false}finally{t&&this[H]()}}[zt](){let t=true;try{if(!this[j]){this[j]=true;do{let e=this[vi](),i=e.length===0?0:I.readSync(this[m],e,0,e.length,null);if(!this[ki](i,e))break}while(true);this[j]=false}t=false}finally{t&&this[H]()}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}};et=class extends Qr{readable=false;writable=true;[bt]=false;[gt]=false;[te]=false;[Y]=[];[ke]=false;[U];[ie];[ht];[m];[Me];[tt];[Ni]=false;[ot];constructor(t,e){e=e||{},super(e),this[U]=t,this[m]=typeof e.fd=="number"?e.fd:void 0,this[ie]=e.mode===void 0?438:e.mode,this[ot]=typeof e.start=="number"?e.start:void 0,this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true;let i=this[ot]!==void 0?"r+":"w";this[Me]=e.flags===void 0,this[tt]=e.flags===void 0?i:e.flags,this[m]===void 0&&this[at]()}emit(t,...e){if(t==="error"){if(this[bt])return false;this[bt]=true}return super.emit(t,...e)}get fd(){return this[m]}get path(){return this[U]}[Ut](t){this[H](),this[gt]=true,this.emit("error",t)}[at](){I.open(this[U],this[tt],this[ie],(t,e)=>this[Ht](t,e))}[Ht](t,e){this[Me]&&this[tt]==="r+"&&t&&t.code==="ENOENT"?(this[tt]="w",this[at]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Ai]())}end(t,e){return t&&this.write(t,e),this[te]=true,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),false):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[ke]=true,false):(this[gt]=true,this[ve](t),true)}[ve](t){I.write(this[m],t,0,t.length,this[ot],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[ot]!==void 0&&typeof e=="number"&&(this[ot]+=e),this[Y].length?this[Ai]():(this[gt]=false,this[te]&&!this[Ni]?(this[Ni]=true,this[H](),this.emit("finish")):this[ke]&&(this[ke]=false,this.emit("drain"))))}[Ai](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ve](this[Y].pop());else{let t=this[Y];this[Y]=[],Jr(this[m],t,this[ot],(e,i)=>this[Pt](e,i))}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}};Wt=class extends et{[at](){let t;if(this[Me]&&this[tt]==="r+")try{t=I.openSync(this[U],this[tt],this[ie])}catch(e){if(e?.code==="ENOENT")return this[tt]="w",this[at]();throw e}else t=I.openSync(this[U],this[tt],this[ie]);this[Ht](null,t)}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ve](t){let e=true;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[ot])),e=false}finally{if(e)try{this[H]()}catch{}}}};jr=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]);Fs=s3=>!!s3.sync&&!!s3.file;ks=s3=>!s3.sync&&!!s3.file;vs=s3=>!!s3.sync&&!s3.file;Ms=s3=>!s3.sync&&!s3.file;Bs=s3=>!!s3.file;tn=s3=>{let t=jr.get(s3);return t||s3};se=(s3={})=>{if(!s3)return{};let t={};for(let[e,i]of Object.entries(s3)){let r=tn(e);t[r]=i}return t.chmod===void 0&&t.noChmod===false&&(t.chmod=true),delete t.noChmod,t};K=(s3,t,e,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=se(n);if(r?.(a,o),Fs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s3(a,o)}else if(ks(a)){let l=t(a,o);return h?l.then(()=>h(),h):l}else if(vs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return e(a,o)}else if(Ms(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s3,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});sn=en.constants||{ZLIB_VERNUM:4736};M=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sn));rn=Ot.concat;zs=Object.getOwnPropertyDescriptor(Ot,"concat");nn=s3=>s3;Bi=zs?.writable===true||zs?.set!==void 0?s3=>{Ot.concat=s3?nn:rn}:s3=>{};Tt=Symbol("_superWrite");Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}};Pi=Symbol("flushFlag");re=class extends A{#t=false;#i=false;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ps[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ps[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=true,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return zi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Pi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=true,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;zi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Bi(true);let h;try{let l=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l),Bi(false)}catch(l){Bi(false),this.#o(new Gt(l,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l=>this.#o(new Gt(l,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l=h[0];a=this[Tt](Ot.from(l));for(let c=1;c<h.length;c++)a=this[Tt](h[c])}else a=this[Tt](Ot.from(h));return i&&i(),a}};Pe=class extends re{#t;#i;constructor(t,e){t=t||{},t.flush=t.flush||M.Z_NO_FLUSH,t.finishFlush=t.finishFlush||M.Z_FINISH,t.fullFlushFlag=M.Z_FULL_FLUSH,super(t,e),this.#t=t.level,this.#i=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#t!==t||this.#i!==e){this.flush(M.Z_SYNC_FLUSH),zi(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(r,n)=>{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};ze=class extends Pe{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=false,t[9]=255,super[Tt](t)):super[Tt](t)}};Ue=class extends Pe{constructor(t){super(t,"Unzip")}};He=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}};We=class extends He{constructor(t){super(t,"BrotliCompress")}};Ge=class extends He{constructor(t){super(t,"BrotliDecompress")}};Ze=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}};Ye=class extends Ze{constructor(t){super(t,"ZstdCompress")}};Ke=class extends Ze{constructor(t){super(t,"ZstdDecompress")}};Us=(s3,t)=>{if(Number.isSafeInteger(s3))s3<0?an(s3,t):hn(s3,t);else throw Error("cannot encode number outside of javascript safe integer range");return t};hn=(s3,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s3&255,s3=Math.floor(s3/256)};an=(s3,t)=>{t[0]=255;var e=false;s3=s3*-1;for(var i=t.length;i>1;i--){var r=s3&255;s3=Math.floor(s3/256),e?t[i-1]=Ws(r):r===0?t[i-1]=0:(e=true,t[i-1]=Gs(r))}};Hs=s3=>{let t=s3[0],e=t===128?cn(s3.subarray(1,s3.length)):t===255?ln(s3):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e};ln=s3=>{for(var t=s3.length,e=0,i=false,r=t-1;r>-1;r--){var n=Number(s3[r]),o;i?o=Ws(n):n===0?o=n:(i=true,o=Gs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e};cn=s3=>{for(var t=s3.length,e=0,i=t-1;i>-1;i--){var r=Number(s3[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e};Ws=s3=>(255^s3)&255;Gs=s3=>(255^s3)+1&255;Hi={};Ur(Hi,{code:()=>Ve,isCode:()=>ne,isName:()=>dn,name:()=>oe,normalFsTypes:()=>Ui});ne=s3=>oe.has(s3);dn=s3=>Ve.has(s3);Ui=new Set(["0","","1","2","3","4","5","6","7","D"]);oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Ve=new Map(Array.from(oe).map(s3=>[s3[1],s3[0]]));un=s3=>s3===void 0||s3<0?void 0:s3;F=class{cksumValid=false;needPax=false;nullBlock=false;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=Ui.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??xt(t,e,100),this.mode=h?.mode??a?.mode??lt(t,e+100,8),this.uid=h?.uid??a?.uid??lt(t,e+108,8),this.gid=h?.gid??a?.gid??lt(t,e+116,8),this.size=un(h?.size??a?.size??lt(t,e+124,12)),this.mtime=h?.mtime??a?.mtime??Wi(t,e+136,12),this.cksum=lt(t,e+148,12),a&&this.#i(a,true),h&&this.#i(h),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??xt(t,e+265,32),this.gname=h?.gname??a?.gname??xt(t,e+297,32),this.devmaj=h?.devmaj??a?.devmaj??lt(t,e+329,8)??0,this.devmin=h?.devmin??a?.devmin??lt(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Wi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Wi(t,e+488,12)}let l=256;for(let c=e;c<e+148;c++)l+=t[c];for(let c=e+156;c<e+512;c++)l+=t[c];this.cksumValid=l===this.cksum,this.cksum===void 0&&l===256&&(this.nullBlock=true)}#i(t,e=false){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="size"&&Number(r)<0||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=mn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=ct(t,e+100,8,this.mode)||this.needPax,this.needPax=ct(t,e+108,8,this.uid)||this.needPax,this.needPax=ct(t,e+116,8,this.gid)||this.needPax,this.needPax=ct(t,e+124,12,this.size)||this.needPax,this.needPax=Gi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Gi(t,e+476,12,this.atime)||this.needPax,this.needPax=Gi(t,e+488,12,this.ctime)||this.needPax);let h=256;for(let a=e;a<e+148;a++)h+=t[a];for(let a=e+156;a<e+512;a++)h+=t[a];return this.cksum=h,ct(t,e+148,8,this.cksum),this.cksumValid=true,this.needPax}get type(){return this.#t==="Unsupported"?this.#t:oe.get(this.#t)}get typeKey(){return this.#t}set type(t){let e=String(Ve.get(t));if(ne(e)||e==="Unsupported")this.#t=e;else if(ne(t))this.#t=t;else throw new TypeError("invalid entry type: "+t)}};mn=(s3,t)=>{let i=s3,r="",n,o=Zt.parse(s3).root||".";if(Buffer.byteLength(i)<100)n=[i,r,false];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,false]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,true]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s3.slice(0,99),"",true])}return n};xt=(s3,t,e)=>s3.subarray(t,t+e).toString("utf8").replace(/\0.*/,"");Wi=(s3,t,e)=>pn(lt(s3,t,e));pn=s3=>s3===void 0?void 0:new Date(s3*1e3);lt=(s3,t,e)=>Number(s3[t])&128?Hs(s3.subarray(t,t+e)):wn(s3,t,e);En=s3=>isNaN(s3)?void 0:s3;wn=(s3,t,e)=>En(parseInt(s3.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8));Sn={12:8589934591,8:2097151};ct=(s3,t,e,i)=>i===void 0?false:i>Sn[e]||i<0?(Us(i,s3.subarray(t,t+e)),true):(yn(s3,t,e,i),false);yn=(s3,t,e,i)=>s3.write(Rn(i,e),t,e,"ascii");Rn=(s3,t)=>gn(Math.floor(s3).toString(8),t);gn=(s3,t)=>(s3.length===t-1?s3:new Array(t-s3.length-1).join("0")+s3+" ")+"\0";Gi=(s3,t,e,i)=>i===void 0?false:ct(s3,t,e,i.getTime()/1e3);bn=new Array(156).join("\0");Lt=(s3,t,e,i)=>i===void 0?false:(s3.write(i+bn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);ft=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=false){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new F({path:("PaxHeader/"+_n(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(r),r.write(t,512,e,"utf8");for(let n=e+512;n<r.length;n++)r[n]=0;return r}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let e=this[t],i=e instanceof Date?e.getTime()/1e3:e,r=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
|
|
125
|
+
${captureLines}`:capture2.stack}module.exports.fetch=function fetch2(init,options=void 0){return fetchImpl(init,options).catch(err=>{if(currentFilename){appendFetchStackTrace(err,currentFilename)}else if(err&&typeof err==="object"){Error.captureStackTrace(err,module.exports.fetch)}throw err})};module.exports.Headers=require_headers().Headers;module.exports.Response=require_response().Response;module.exports.Request=require_request2().Request;module.exports.FormData=require_formdata().FormData;var{setGlobalOrigin,getGlobalOrigin}=require_global();module.exports.setGlobalOrigin=setGlobalOrigin;module.exports.getGlobalOrigin=getGlobalOrigin;var{CacheStorage}=require_cachestorage();var{kConstruct}=require_symbols();module.exports.caches=new CacheStorage(kConstruct);var{deleteCookie,getCookies,getSetCookies,setCookie,parseCookie}=require_cookies();module.exports.deleteCookie=deleteCookie;module.exports.getCookies=getCookies;module.exports.getSetCookies=getSetCookies;module.exports.setCookie=setCookie;module.exports.parseCookie=parseCookie;var{parseMIMEType,serializeAMimeType}=require_data_url();module.exports.parseMIMEType=parseMIMEType;module.exports.serializeAMimeType=serializeAMimeType;var{CloseEvent,ErrorEvent,MessageEvent}=require_events();var{WebSocket,ping}=require_websocket();module.exports.WebSocket=WebSocket;module.exports.CloseEvent=CloseEvent;module.exports.ErrorEvent=ErrorEvent;module.exports.MessageEvent=MessageEvent;module.exports.ping=ping;module.exports.WebSocketStream=require_websocketstream().WebSocketStream;module.exports.WebSocketError=require_websocketerror().WebSocketError;module.exports.request=makeDispatcher(api.request);module.exports.stream=makeDispatcher(api.stream);module.exports.pipeline=makeDispatcher(api.pipeline);module.exports.connect=makeDispatcher(api.connect);module.exports.upgrade=makeDispatcher(api.upgrade);module.exports.MockClient=MockClient;module.exports.MockCallHistory=MockCallHistory;module.exports.MockCallHistoryLog=MockCallHistoryLog;module.exports.MockPool=MockPool;module.exports.MockAgent=MockAgent;module.exports.SnapshotAgent=SnapshotAgent;module.exports.mockErrors=mockErrors;var{EventSource}=require_eventsource();module.exports.EventSource=EventSource;function install(){globalThis.fetch=module.exports.fetch;globalThis.Headers=module.exports.Headers;globalThis.Response=module.exports.Response;globalThis.Request=module.exports.Request;globalThis.FormData=module.exports.FormData;globalThis.WebSocket=module.exports.WebSocket;globalThis.CloseEvent=module.exports.CloseEvent;globalThis.ErrorEvent=module.exports.ErrorEvent;globalThis.MessageEvent=module.exports.MessageEvent;globalThis.EventSource=module.exports.EventSource}module.exports.install=install}});import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";var transports;var init_fetch_transport=__esm({"src/fetch-transport.ts"(){"use strict";transports=new AsyncLocalStorage2}});var init_upstream_fail=__esm({"src/upstream-fail.ts"(){"use strict"}});function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}return{setPosition,getPosition:()=>pos,scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:()=>token,getTokenValue:()=>value,getTokenOffset:()=>tokenOffset,getTokenLength:()=>pos-tokenOffset,getTokenStartLine:()=>lineStartOffset,getTokenStartCharacter:()=>tokenOffset-prevTokenLineStartOffset,getTokenError:()=>scanError}}function isWhiteSpace(ch){return ch===32||ch===9}function isLineBreak(ch){return ch===10||ch===13}function isDigit(ch){return ch>=48&&ch<=57}var CharacterCodes;var init_scanner=__esm({"node_modules/jsonc-parser/lib/esm/impl/scanner.js"(){"use strict";(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}))}});var cachedSpaces,maxCachedValues,cachedBreakLinesWithSpaces;var init_string_intern=__esm({"node_modules/jsonc-parser/lib/esm/impl/string-intern.js"(){"use strict";cachedSpaces=new Array(20).fill(0).map((_2,index)=>{return" ".repeat(index)});maxCachedValues=200;cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}}}});var init_format=__esm({"node_modules/jsonc-parser/lib/esm/impl/format.js"(){"use strict";init_scanner();init_string_intern()}});function parse(text,errors=[],options=ParseOptions.DEFAULT){let currentProperty=null;let currentParent=[];const previousParents=[];function onValue(value){if(Array.isArray(currentParent)){currentParent.push(value)}else if(currentProperty!==null){currentParent[currentProperty]=value}}const visitor={onObjectBegin:()=>{const object={};onValue(object);previousParents.push(currentParent);currentParent=object;currentProperty=null},onObjectProperty:name2=>{currentProperty=name2},onObjectEnd:()=>{currentParent=previousParents.pop()},onArrayBegin:()=>{const array=[];onValue(array);previousParents.push(currentParent);currentParent=array;currentProperty=null},onArrayEnd:()=>{currentParent=previousParents.pop()},onLiteralValue:onValue,onError:(error,offset,length)=>{errors.push({error,offset,length})}};visit(text,visitor,options);return currentParent[0]}function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}var ParseOptions;var init_parser=__esm({"node_modules/jsonc-parser/lib/esm/impl/parser.js"(){"use strict";init_scanner();(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}))}});var init_edit=__esm({"node_modules/jsonc-parser/lib/esm/impl/edit.js"(){"use strict";init_format();init_parser()}});function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}var ScanError,SyntaxKind,parse2,ParseErrorCode;var init_main=__esm({"node_modules/jsonc-parser/lib/esm/main.js"(){"use strict";init_format();init_edit();init_scanner();init_parser();(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));parse2=parse;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}))}});import{createHash as createHash2}from"crypto";function hashId(s3){return createHash2("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var BILI_PASSTHROUGH_HEADER,MIN_ASSUMED_WINDOW_TOKENS;var init_util=__esm({"src/util.ts"(){"use strict";BILI_PASSTHROUGH_HEADER="x-bili-passthrough";MIN_ASSUMED_WINDOW_TOKENS=1e6}});var DEFAULT_MITM_DOMAINS;var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict";DEFAULT_MITM_DOMAINS=["api.anthropic.com","api.openai.com","chatgpt.com"]}});var init_compat_roles=__esm({"src/compat-roles.ts"(){"use strict";init_config()}});var init_compat_drop=__esm({"src/compat-drop.ts"(){"use strict";init_config()}});var init_private_host=__esm({"src/private-host.ts"(){"use strict"}});var SUMMARY_DEFAULT_BUDGET;var init_external_summary_settings=__esm({"src/external-summary-settings.ts"(){"use strict";init_logger();init_private_host();init_knobs();SUMMARY_DEFAULT_BUDGET={totalTimeoutMs:5e4,targetTimeoutMs:25e3,maxSummaryBytes:64*1024}}});import{readFileSync as readFileSync2,existsSync,mkdirSync as mkdirSync3,writeFileSync}from"fs";import{createHash as createHash3}from"crypto";import{dirname}from"path";function resolveRecordedMitmDomains(passed,env=process.env){const fileConfig=loadConfigFile();const enabled=(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0";if(!enabled)return[];const effective=passed&&passed.length>0?passed.join(","):env.BILI_MITM_DOMAINS;return dedupeDomains([...fileConfig.mitm?.domains??[],...splitCsv(effective)])}function splitCsv(value){if(!value)return[];return value.split(",").map(s3=>s3.trim()).filter(s3=>s3.length>0)}function dedupeDomains(list){const seen=new Set;const out=[];for(const d of list){if(!seen.has(d)){seen.add(d);out.push(d)}}return out}function warnUnknownTopLevelKeys(obj){const unknown=Object.keys(obj).filter(key=>!KNOWN_TOP_LEVEL_KEYS.has(key)&&key!=="allowDshCompaction");if(unknown.length===0)return;const signature=[...unknown].sort().join("\0");if(seenUnknownTopLevelKeySignatures.has(signature))return;seenUnknownTopLevelKeySignatures.add(signature);const misplaced=unknown.filter(key=>COMPRESS_SETTING_FIELDS.has(key));const hint=misplaced.length>0?` \u2014 ${misplaced.map(k2=>`"${k2}" belongs under "compress" (did you mean "compress.${k2}"?)`).join("; ")}`:"";log("warn",`[acp-config] ignoring unknown top-level config key(s): ${unknown.join(", ")}${hint}`)}function parseBiliConfig(raw){try{return JSON.parse(raw)}catch{const errors=[];const value=parse2(raw,errors,{allowTrailingComma:true});if(errors.length===0)return value;const first=errors[0];throw new SyntaxError(`invalid JSON/JSONC at ${lineColumnOf(raw,first.offset)}: ${printParseErrorCode(first.error)}`)}}function lineColumnOf(text,offset){let line=1;let column=1;for(let i=0;i<offset&&i<text.length;i++){if(text.charAt(i)==="\n"){line++;column=1}else column++}return`line ${line} column ${column}`}function loadConfigFile(){const path29=configFile();let raw;let value;try{raw=readFileSync2(path29,"utf8").replace(/^\uFEFF/,"");const cached=configFileCache;if(cached&&cached.raw===raw)return cached.value;const parsed=parseBiliConfig(raw);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){const obj=parsed;warnRemovedDshAllowKey(obj);warnUnknownTopLevelKeys(obj);warnInertResignPassthrough(obj);warnInertStripImages(obj);warnInertRemovedCompressKeys(obj);value=obj}else{value={}}}catch(e){if(e.code!=="ENOENT"){log("error",`[acp-config] failed to parse ${path29}: ${String(e)}`)}if(raw!==void 0)value={}}if(raw===void 0||value===void 0)return{};configFileCache={raw,value};return value}function warnRemovedDshAllowKey(obj){const hits=[];if(Object.prototype.hasOwnProperty.call(obj,"allowDshCompaction")&&obj.allowDshCompaction!==null&&obj.allowDshCompaction!==void 0){hits.push('top-level "allowDshCompaction"')}const d=obj.dsh;if(d!==null&&typeof d==="object"&&!Array.isArray(d)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key of Object.keys(d))if(!live.has(key))hits.push(`dsh.${key}`)}hits.sort();const sig=hits.join(",");if(sig===""||sig===removedDshAllowKeySignature)return;removedDshAllowKeySignature=sig;log("warn",`[acp-config] ${hits.join(", ")} was removed (#3651, superseding #2028) \u2014 value(s) ignored: dsh native compaction is now refused unconditionally by the wire guard on every lane. Delete it from your config to silence this.`)}function resolveResignSettings(env=process.env,provider={},scheme=RESIGN_BUILTIN_SCHEME){const key=scheme.trim().toLowerCase();const file=loadConfigFile().resign?.[key]??{};const providerBlock=provider?.[key]??{};const enabled=env.BILI_RESIGN!==void 0?env.BILI_RESIGN!=="0":providerBlock.enabled!==void 0?providerBlock.enabled:file.enabled!==false;const passthrough=env.BILI_RESIGN_PASSTHROUGH!==void 0?env.BILI_RESIGN_PASSTHROUGH==="1"||env.BILI_RESIGN_PASSTHROUGH==="true":providerBlock.passthrough!==void 0?providerBlock.passthrough:file.passthrough===true;const credentialRef=env.BILI_CODEARTS_REF?.trim()||providerBlock.credentialRef||file.credentialRef||void 0;return{enabled,passthrough,credentialRef}}function warnInertStripImages(obj){const compress=obj.compress;if(!compress||typeof compress!=="object"||Array.isArray(compress))return;const hit=["stripImages","stripImagesKeepRecent"].filter(k2=>compress[k2]!==void 0);const sig=hit.join(",");if(sig===""||sig===seenInertStripImagesSignature)return;seenInertStripImagesSignature=sig;log("warn",`[acp-config] compress.${hit.join("/compress.")} is INERT \u2014 compress.stripImages was removed: media now folds by default (#2640) and decompress({ imageRef }) recovers folded pixels; nothing is stripped from the wire anymore. Remove the key(s) from the config.`)}function warnInertRemovedCompressKeys(obj){const hits=[];const scanBlock=(block,pathPrefix)=>{if(!block||typeof block!=="object"||Array.isArray(block))return;for(const key of INERT_REMOVED_COMPRESS_KEYS){if(block[key]!==void 0)hits.push(`${pathPrefix}.${key}`)}};scanBlock(obj.compress,"compress");const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const[url,entry]of Object.entries(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const p2=entry;scanBlock(p2.compress,`providers["${url}"].compress`);const models=p2.models;if(models&&typeof models==="object"&&!Array.isArray(models)){for(const[model,mEntry]of Object.entries(models)){if(!mEntry||typeof mEntry!=="object"||Array.isArray(mEntry))continue;scanBlock(mEntry.compress,`providers["${url}"].models["${model}"].compress`)}}}}hits.sort();const sig=hits.join(",");if(sig===""||sig===seenInertRemovedCompressKeysSignature)return;seenInertRemovedCompressKeysSignature=sig;log("warn",`[acp-config] ${hits.join(", ")} is INERT \u2014 compress.imageCompression was removed and no longer does anything at any level (image pre-compression + image_full restore channel, #3266). Remove it from the config; images pass through byte-identical.`)}function warnInertResignPassthrough(obj){const inert=[];const consider=(map,providerBlockFor)=>{if(!map||typeof map!=="object"||Array.isArray(map))return;for(const[key,val]of Object.entries(map)){if(key===RESIGN_BUILTIN_SCHEME)continue;const block=val!==null&&typeof val==="object"&&!Array.isArray(val)?val:{};if(block["passthrough"]!==true)continue;const fileBlock=(obj.resign??{})[key];const providerBlock=providerBlockFor(key);const enabled=process.env.BILI_RESIGN!==void 0?process.env.BILI_RESIGN!=="0":providerBlock?.enabled!==void 0?providerBlock.enabled:fileBlock?.enabled!==false;if(enabled)inert.push(key)}};consider(obj.resign,()=>void 0);const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const entry of Object.values(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const pmap=entry.resign;if(pmap===void 0)continue;consider(pmap,key=>(pmap??{})[key])}}inert.sort();const sig=inert.join(",");if(sig===""||sig===inertResignPassthroughSignature)return;inertResignPassthroughSignature=sig;const list=inert.map(k2=>`resign["${k2}"].passthrough`).join(", ");log("warn",`[acp-config] ${list}=true is INERT \u2014 since the #2090 compress-or-refuse contract, unsigned pass-through exists ONLY for the built-in scheme "${RESIGN_BUILTIN_SCHEME}"; those signed requests stay REFUSED until bili ships a re-signer for them. Restore pre-resign handling with resign["<scheme>"].enabled=false or BILI_RESIGN=0 (the upstream will then reject the rewritten bodies).`)}function resolveZonePortBase(env=process.env){const fromEnv=Number.parseInt(env.BILI_ZONE_PORT??"",10);if(Number.isInteger(fromEnv)&&fromEnv>0&&fromEnv<65536)return fromEnv;return ZONE_PORT_BASE}function resolveNativeAttachExternal(env=process.env){const fromEnv=(env.BILI_NATIVE_ATTACH_EXTERNAL??"").trim().toLowerCase();if(fromEnv==="1"||fromEnv==="true")return true;if(fromEnv==="0"||fromEnv==="false")return false;return loadConfigFile().native?.attachExternal===true}function resolveNativeAttachLanePriority(){const raw=loadConfigFile().native?.attachLanePriority;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item!=="string")continue;const t=item.trim();if(t.length>0&&!out.includes(t))out.push(t)}return out}function adminRelayEnabled(){return loadConfigFile().security?.adminRelay===true}function resolveNativeAttachPolicy(env=process.env){const norm=v2=>(v2??"").trim().toLowerCase();const fromEnv=norm(env.BILI_NATIVE_ATTACH_POLICY);if(fromEnv==="global-fallback"||fromEnv==="global")return"global-fallback";if(fromEnv==="own-lane"||fromEnv==="ownlane"||fromEnv==="strict")return"own-lane";const file=norm(loadConfigFile().native?.attachPolicy);if(file==="global-fallback"||file==="global")return"global-fallback";return"own-lane"}function resolveNativeAttachUrl(env=process.env){const fromEnv=(env.BILI_MCP_PROXY??"").trim();if(fromEnv.length>0)return fromEnv;const file=(loadConfigFile().native?.attachUrl??"").trim();return file.length>0?file:void 0}var KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature,ZONE_PORT_BASE;var init_config=__esm({"src/config.ts"(){"use strict";init_main();init_paths();init_logger();init_upstream_proxy();init_log_mask();init_util();init_mitm_domains();init_compat_roles();init_compat_drop();init_external_summary_settings();KNOWN_TOP_LEVEL_KEYS=new Set(["port","host","upstream","providersPath","providers","proxy","modelContextLimit","sessionHeader","log","debug","dumpSse","passthrough","autoUpdate","autoRestartOnUpdate","updateTag","advisoryCheck","advisoryUrl","releaseNotesCheck","releaseNotesUrl","upstreamProxy","upstreamProxyMode","logFile","compress","promptCache","mitm","maskHosts","subagentSplit","forkAdoption","affinitySimhash","resumeInheritance","chainContentDetection","chainEgressStamp","stableSystemAnchor","rollout","dsh","compat","imageBilling","imageTokenCap","claude","native","resign","pi","storage","security","network","persist","sessions","plugin","update","diagnostics","fakeCompletion","codexCompact","ccrRetrievalTtlMs","decompressTmpCap","autoModeForge","imageRescale","guardrails","cacheKeepalive"]);COMPRESS_SETTING_FIELDS=new Set(["modelContextLimit","maxContextLimit","emergencyThresholdPercent","nudgeGrowthTokens","minPressureBenefitTokens","tierNudgeTokens","nudgeModelDecided","nudgeDecisionMaxTokens","preserveRecentMessages","preserveRecentTokens","minCompressRange","minCompressRangeChars","outputHeadroomMaxPct","tiers","protectedLatestTools","protectedTools","neverPreserveRecentTools","preserveRecentTools","visibilityMarkers","rules","injectTool","injectNudge","acknowledgePromptsRisk","absorb","ccr","search","prompts","promptPack","reasoningGuard","outputSteering","priceProfile","reconcile","streamSummary"]);seenUnknownTopLevelKeySignatures=new Set;configFileCache=null;removedDshAllowKeySignature="";RESIGN_BUILTIN_SCHEME="sdk-hmac-sha256";inertResignPassthroughSignature=null;seenInertStripImagesSignature="";INERT_REMOVED_COMPRESS_KEYS=["imageCompression"];seenInertRemovedCompressKeysSignature="";ZONE_PORT_BASE=18787}});var init_duration=__esm({"src/duration.ts"(){"use strict"}});import{createHash as createHash4}from"crypto";var MIN_MEDIA_URL_SPLIT_BYTES,MEDIA_URL_MARKER_RE;var init_identity=__esm({"src/storage/identity.ts"(){"use strict";MIN_MEDIA_URL_SPLIT_BYTES=2048;MEDIA_URL_MARKER_RE=new RegExp(`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,"g")}});function storagePragmas(walJournalSizeLimitBytes){return["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA busy_timeout = 5000","PRAGMA foreign_keys = ON",`PRAGMA journal_size_limit = ${walJournalSizeLimitBytes}`,"PRAGMA auto_vacuum = INCREMENTAL"]}var WAL_JOURNAL_SIZE_LIMIT,STORAGE_PRAGMAS;var init_schema=__esm({"src/storage/schema.ts"(){"use strict";init_identity();init_logger();WAL_JOURNAL_SIZE_LIMIT=8*1024*1024;STORAGE_PRAGMAS=storagePragmas(WAL_JOURNAL_SIZE_LIMIT)}});import path6 from"path";function tNumLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tInt(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v2=envRaw!==void 0?Number.parseInt(envRaw,10):(()=>{const f2=loadConfigFile().sessions?.max;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Math.max(1,v2||256)}function sessionResidentMaxBytes(){const v2=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v2)&&v2>=0?Math.floor(v2):512*1024*1024}function updateRegistryBase(){const envRaw=process.env.BILI_UPDATE_REGISTRY;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.registry;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateCheckIntervalMs(){const v2=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v2)&&v2>0?Math.floor(v2):3*60*1e3}function dshContextTabEnabled(){const envRaw=process.env.BILI_DSH_CONTEXT_TAB;if(envRaw!==void 0)return!(envRaw.trim()==="0"||envRaw.trim().toLowerCase()==="false");return loadConfigFile().dsh?.contextTab!==false}function dshContextTabLabel(){const f2=loadConfigFile().dsh?.contextTabLabel;const s3=typeof f2==="string"?f2.trim():"";return s3.length>0?s3:void 0}var DEFAULT_LIMITS_RECEIVE_BYTES,DEFAULT_LIMITS_DECODED_BYTES,DEFAULT_LIMITS_OUTBOUND_BYTES,DEFAULT_WS_OUTBOUND_BYTES;var init_knobs=__esm({"src/knobs.ts"(){"use strict";init_paths();init_config();init_duration();init_fetch_util();init_upstream_proxy();init_schema();DEFAULT_LIMITS_RECEIVE_BYTES=5*1024*1024*1024;DEFAULT_LIMITS_DECODED_BYTES=10*1024*1024*1024;DEFAULT_LIMITS_OUTBOUND_BYTES=5*1024*1024*1024;DEFAULT_WS_OUTBOUND_BYTES=10*1024*1024}});import{readFileSync as readFileSync3,statSync as statSync2}from"fs";import*as tls2 from"tls";var init_upstream_ca=__esm({"src/upstream-ca.ts"(){"use strict";init_logger();init_knobs()}});var MAX_REQUEST_BYTES,MAX_DECODED_REQUEST_BYTES;var init_request_body_budget=__esm({"src/request-body-budget.ts"(){"use strict";init_knobs();MAX_REQUEST_BYTES=100*1024*1024;MAX_DECODED_REQUEST_BYTES=2*MAX_REQUEST_BYTES}});var import_undici,UPSTREAM_TIMEOUT_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici=__toESM(require_undici(),1);init_fetch_transport();init_upstream_fail();init_upstream_ca();init_knobs();init_request_body_budget();init_request_body_budget();UPSTREAM_TIMEOUT_MS=12*60*1e3}});import{execFileSync as execFileSync3}from"child_process";import net from"net";import tls3 from"tls";var import_undici2;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs()}});var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path7 from"path";var TOML_KEY_PART_RE;var init_client_config=__esm({"src/client-config.ts"(){"use strict";init_main();init_vertex();TOML_KEY_PART_RE=new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`)}});import{createHash as createHash5,randomUUID}from"crypto";import fs4 from"fs";import os4 from"os";import path9 from"path";function isProxyInstanceFile(v2){return v2!==void 0&&"instanceId"in v2}function readProxyInstanceFile(file){let raw;try{raw=fs4.readFileSync(file??instanceFilePath(),"utf8").trim()}catch{return void 0}if(raw.startsWith("{")){try{const parsed=JSON.parse(raw);if(typeof parsed.origin==="string"&&/^https?:\/\/\S+$/.test(parsed.origin)){const windows={};if(parsed.modelWindows&&typeof parsed.modelWindows==="object"){for(const[k2,v2]of Object.entries(parsed.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(parsed.modelMaxOutputs&&typeof parsed.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(parsed.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{origin:parsed.origin,instanceId:typeof parsed.instanceId==="string"?parsed.instanceId:"",pid:typeof parsed.pid==="number"?parsed.pid:0,startedAt:typeof parsed.startedAt==="number"?parsed.startedAt:0,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,passthrough:Boolean(parsed.passthrough),mitmDomains:Array.isArray(parsed.mitmDomains)?parsed.mitmDomains.map(String):[],modelWindows:windows,modelMaxOutputs:Object.keys(maxOutputs).length>0?maxOutputs:void 0,launchToken:typeof parsed.launchToken==="string"?parsed.launchToken:void 0,lane:typeof parsed.lane==="string"&&parsed.lane!==""?parsed.lane:void 0,codeFingerprint:typeof parsed.codeFingerprint==="string"&&parsed.codeFingerprint!==""?parsed.codeFingerprint:void 0}}}catch{}}if(/^https?:\/\/\S+$/.test(raw))return{origin:raw};return void 0}function instanceFilePath(){return path9.join(stateDir(),"proxy-origin")}function portZoneFilePath(){return path9.join(stateDir(),"port-zone.json")}function readZonePort(lane,file=portZoneFilePath()){let raw;try{raw=fs4.readFileSync(file,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);const v2=parsed?.lanes?.[lane];if(typeof v2==="number"&&Number.isInteger(v2)&&v2>0&&v2<65536)return v2;return void 0}catch{return void 0}}function writeZonePort(lane,port,file=portZoneFilePath()){if(!Number.isInteger(port)||port<=0||port>=65536)return;let cur={};try{const parsed=JSON.parse(fs4.readFileSync(file,"utf8"));if(parsed!==null&&typeof parsed==="object"&&parsed.lanes!==null&&typeof parsed.lanes==="object")cur=parsed}catch{}atomicWriteJson({lanes:{...cur.lanes??{},[lane]:port}},file)}function lanePreferredPort(lane,env=process.env,file=portZoneFilePath()){return readZonePort(lane,file)??resolveZonePortBase(env)}function entryScriptFingerprint(scriptPath){if(!scriptPath)return void 0;const resolved=path9.resolve(scriptPath);const cached=scriptFingerprints.get(resolved);if(cached!==void 0)return cached;let digest;try{digest=createHash5("sha256").update(fs4.readFileSync(resolved)).digest("hex")}catch{return void 0}scriptFingerprints.set(resolved,digest);return digest}function atomicWriteJson(obj,filePath){fs4.mkdirSync(path9.dirname(filePath),{recursive:true});const tempPath=`${filePath}.${process.pid}.${randomUUID()}.tmp`;let descriptor;try{descriptor=fs4.openSync(tempPath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(obj)+"\n",null,"utf8");fs4.fsyncSync(descriptor);fs4.closeSync(descriptor);descriptor=void 0;fs4.renameSync(tempPath,filePath)}catch(error){if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}try{fs4.unlinkSync(tempPath)}catch{}throw error}}function startingMarkerPath(){return path9.join(stateDir(),"proxy-starting")}function readStartingMarker(file){let raw;try{raw=fs4.readFileSync(file??startingMarkerPath(),"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed.token!=="string"||parsed.token==="")return void 0;if(typeof parsed.pid!=="number"||!Number.isInteger(parsed.pid)||parsed.pid<=0)return void 0;if(typeof parsed.startedAt!=="number")return void 0;return{token:parsed.token,pid:parsed.pid,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,startedAt:parsed.startedAt,...typeof parsed.lane==="string"&&parsed.lane!==""?{lane:parsed.lane}:{}}}catch{return void 0}}function claimStartingMarker(marker,file){const filePath=file??startingMarkerPath();let descriptor;try{fs4.mkdirSync(path9.dirname(filePath),{recursive:true});descriptor=fs4.openSync(filePath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(marker)+"\n",null,"utf8");fs4.fsyncSync(descriptor);descriptor=void 0;return true}catch{if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}return false}}function clearStartingMarker(token,file){const filePath=file??startingMarkerPath();const current=readStartingMarker(filePath);if(current&¤t.token===token){try{fs4.unlinkSync(filePath)}catch{}}}function removeStartingMarker(file){try{fs4.unlinkSync(file??startingMarkerPath())}catch{}}function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err){return err.code==="EPERM"}}function registryDirPath(){return path9.join(stateDir(),"instances")}function legacyRegistryFilePath(){return path9.join(stateDir(),"instances.json")}function safeReadJson(file){try{return JSON.parse(fs4.readFileSync(file,"utf8"))}catch{return void 0}}function coerceEntry(value){if(!value||typeof value!=="object")return void 0;const o=value;if(typeof o.instanceId!=="string"||o.instanceId==="")return void 0;const windows={};if(o.modelWindows&&typeof o.modelWindows==="object"){for(const[k2,v2]of Object.entries(o.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(o.modelMaxOutputs&&typeof o.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(o.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{instanceId:o.instanceId,pid:typeof o.pid==="number"?o.pid:0,port:typeof o.port==="number"?o.port:0,origin:typeof o.origin==="string"?o.origin:"",startedAt:typeof o.startedAt==="number"?o.startedAt:0,...typeof o.host==="string"&&o.host!==""?{host:o.host}:{},...typeof o.passthrough==="boolean"?{passthrough:o.passthrough}:{},...Array.isArray(o.mitmDomains)?{mitmDomains:o.mitmDomains.map(String)}:{},...Object.keys(windows).length>0?{modelWindows:windows}:{},...Object.keys(maxOutputs).length>0?{modelMaxOutputs:maxOutputs}:{},...typeof o.lane==="string"&&o.lane!==""?{lane:o.lane}:{},...typeof o.codeFingerprint==="string"&&o.codeFingerprint!==""?{codeFingerprint:o.codeFingerprint}:{}}}function readMarkerNames(){try{return fs4.readdirSync(registryDirPath())}catch{return[]}}function readAllRegistryEntries(){const seen=new Set;const out=[];for(const name2 of readMarkerNames()){if(!name2.endsWith(".json"))continue;const entry=coerceEntry(safeReadJson(path9.join(registryDirPath(),name2)));if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}const legacy=safeReadJson(legacyRegistryFilePath());if(legacy&&Array.isArray(legacy.instances)){for(const raw of legacy.instances){const entry=coerceEntry(raw);if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}}return out}function discoverLiveInstances(){const out=[];for(const e of readAllRegistryEntries()){if(!isPidAlive(e.pid))continue;out.push({origin:e.origin,instanceId:e.instanceId,pid:e.pid,startedAt:e.startedAt,host:e.host??"",port:e.port,passthrough:Boolean(e.passthrough),mitmDomains:e.mitmDomains??[],modelWindows:e.modelWindows??{},modelMaxOutputs:e.modelMaxOutputs,lane:e.lane,codeFingerprint:e.codeFingerprint})}return out}var scriptFingerprints;var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths();scriptFingerprints=new Map}});var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs5 from"fs";import path10 from"path";import{execFile,spawnSync}from"child_process";import{promisify}from"util";var DSH_PACKAGE,DSH_EXEC_TIMEOUT_MS,pExecFile;var init_dsh_channel=__esm({"src/dsh-channel.ts"(){"use strict";init_client_config();init_win_cmd();DSH_PACKAGE="billion-context";DSH_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile=promisify(execFile)}});import fs6 from"fs";import path11 from"path";import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";var PI_NPM_SPEC,PI_EXEC_TIMEOUT_MS,pExecFile2;var init_pi_channel=__esm({"src/pi-channel.ts"(){"use strict";init_client_config();init_dsh_channel();PI_NPM_SPEC="npm:billion-context";PI_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile2=promisify2(execFile2)}});import Qr from"events";import I from"fs";import{EventEmitter as Di}from"events";import Cs from"stream";import{StringDecoder as Hr}from"string_decoder";import cr from"path";import Kt from"fs";import{dirname as Fn,parse as kn}from"path";import{EventEmitter as Dn}from"events";import zi from"assert";import{Buffer as Ot}from"buffer";import*as Ps from"zlib";import en from"zlib";import{posix as Zt}from"path";import{basename as _n}from"path";import mi from"fs";import X from"fs";import js from"path";import{win32 as Pn}from"path";import ar from"path";import Br from"fs";import co from"assert";import{randomBytes as Mr}from"crypto";import u from"fs";import R from"path";import pr from"fs";import wi from"fs";import we from"path";import k from"fs";import ro from"fs/promises";import Si from"path";import{join as xr}from"path";import v from"fs";import Pr from"path";function Zn(s3,t,e){let i=t,r=t?t.next:s3.head,n=new ue(e,i,r,s3);return n.next===void 0&&(s3.tail=n),n.prev===void 0&&(s3.head=n),s3.length++,n}function Yn(s3,t){s3.tail=new ue(t,s3.tail,void 0,s3),s3.head||(s3.head=s3.tail),s3.length++}function Kn(s3,t){s3.head=new ue(t,void 0,s3.head,s3),s3.tail||(s3.tail=s3.head),s3.length++}var zr,Ur,Ds,Wr,Gr,Zr,Q,J,nt,De,qt,Ne,Ns,Ae,As,z,Mt,g,Qt,Bt,b,N,_,bi,Ie,L,S,_i,Oi,Is,Ti,Z,xi,Ce,Jt,Rt,C,jt,Yr,Kr,Vr,$r,Fe,Li,Xr,qr,A,Jr,ht,H,te,m,Ni,tt,Ai,ki,vi,ie,ke,Ut,Ht,Ii,Pt,at,U,ot,Y,zt,Ci,j,ee,Fi,ve,gt,Me,bt,_t,Be,et,Wt,jr,Fs,ks,vs,Ms,Bs,tn,se,K,sn,M,rn,zs,nn,Bi,Tt,Gt,Pi,re,Pe,ze,Ue,He,We,Ge,Ze,Ye,Ke,Us,hn,an,Hs,ln,cn,Ws,Gs,Hi,ne,dn,Ui,oe,Ve,un,F,mn,xt,Wi,pn,lt,En,wn,Sn,ct,yn,Rn,gn,Gi,bn,Lt,ft,On,Tn,xn,Ln,f,$e,Dt,Nn,Xi,qi,An,B,Nt,it,Zi,Zs,V,he,dt,Ys,p,st,ut,Yi,At,w,Xe,qe,Ki,Ks,Vs,ae,Vi,Qe,Yt,$,Je,It,je,ti,$s,In,le,$i,Xs,Cn,rt,mt,vn,Qi,Mn,Bn,Ct,Ji,zn,qs,ce,ei,ji,Un,Hn,ts,Qs,rr,Wn,tr,er,ir,is,sr,fe,ii,ss,si,rs,ns,os5,hs,pt,ri,as,es,q,de,ni,oi,Gn,hi,ue,pi,nr,li,me,W,pe,Et,Ft,Ee,ai,G,ls,ci,or,ds,us,fi,di,hr,cs,ui,lr,fs7,wt,kt,Vn,$n,fr,dr,Xn,qn,Qn,Jn,Er,wr,ur,Sr,yr,Rr,jn,to,eo,mr,ms,ps,Ei,io,Es,so,ws,Se,St,no,gr,Ss,br,oo,_r,ys,Or,Vt,Tr,ho,ao,lo,yi,Lr,Dr,_s,Nr,Os,P,Ts,xs,gi,Ar,Ir,Re,Cr,Fr,Rs,yt,O,Ri,kr,$t,gs,bs,Ls,ge,be,_e,Oe,fo,Te,uo,mo,po,vr,Xt,ye,xe,Eo,wo,So,yo,Ro,go,bo,_o,vt,Oo,To;var init_index_min=__esm({"node_modules/tar/dist/esm/index.min.js"(){"use strict";zr=Object.defineProperty;Ur=(s3,t)=>{for(var e in t)zr(s3,e,{get:t[e],enumerable:true})};Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null};Wr=s3=>!!s3&&typeof s3=="object"&&(s3 instanceof A||s3 instanceof Cs||Gr(s3)||Zr(s3));Gr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.pipe=="function"&&s3.pipe!==Cs.Writable.prototype.pipe;Zr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.write=="function"&&typeof s3.end=="function";Q=Symbol("EOF");J=Symbol("maybeEmitEnd");nt=Symbol("emittedEnd");De=Symbol("emittingEnd");qt=Symbol("emittedError");Ne=Symbol("closed");Ns=Symbol("read");Ae=Symbol("flush");As=Symbol("flushChunk");z=Symbol("encoding");Mt=Symbol("decoder");g=Symbol("flowing");Qt=Symbol("paused");Bt=Symbol("resume");b=Symbol("buffer");N=Symbol("pipes");_=Symbol("bufferLength");bi=Symbol("bufferPush");Ie=Symbol("bufferShift");L=Symbol("objectMode");S=Symbol("destroyed");_i=Symbol("error");Oi=Symbol("emitData");Is=Symbol("emitEnd");Ti=Symbol("emitEnd2");Z=Symbol("async");xi=Symbol("abort");Ce=Symbol("aborted");Jt=Symbol("signal");Rt=Symbol("dataListeners");C=Symbol("discarded");jt=s3=>Promise.resolve().then(s3);Yr=s3=>s3();Kr=s3=>s3==="end"||s3==="finish"||s3==="prefinish";Vr=s3=>s3 instanceof ArrayBuffer||!!s3&&typeof s3=="object"&&s3.constructor&&s3.constructor.name==="ArrayBuffer"&&s3.byteLength>=0;$r=s3=>!Buffer.isBuffer(s3)&&ArrayBuffer.isView(s3);Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}};Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}};Xr=s3=>!!s3.objectMode;qr=s3=>!s3.objectMode&&!!s3.encoding&&s3.encoding!=="buffer";A=class extends Di{[g]=false;[Qt]=false;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=false;[nt]=false;[De]=false;[Ne]=false;[qt]=null;[_]=0;[S]=false;[Jt];[Ce]=false;[Rt]=0;[C]=false;writable=true;readable=true;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=true,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=false):(this[L]=false,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=true,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return false;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=false,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Q]=true,this.writable=false,(this[g]||!this[Qt])&&this[J](),this}[Bt](){this[S]||(!this[Rt]&&!this[N].length&&(this[C]=true),this[Qt]=false,this[g]=true,this.emit("resume"),this[b].length?this[Ae]():this[Q]?this[J]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=false,this[Qt]=true,this[C]=false}get destroyed(){return this[S]}get flowing(){return this[g]}get paused(){return this[Qt]}[bi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ie](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[Ae](t=false){do;while(this[As](this[Ie]())&&this[b].length);!t&&!this[b].length&&!this[Q]&&this.emit("drain")}[As](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[S])return t;this[C]=false;let i=this[nt];return e=e||{},t===Ds.stdout||t===Ds.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[N].push(e.proxyErrors?new Li(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[N].find(i=>i.dest===t);e&&(this[N].length===1?(this[g]&&this[Rt]===0&&(this[g]=false),this[N]=[]):this[N].splice(this[N].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[C]=false,this[Rt]++,!this[N].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Kr(t)&&this[nt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[C]&&!this[N].length&&(this[g]=false)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[C]&&!this[N].length&&(this[g]=false)),e}get emittedEnd(){return this[nt]}[J](){!this[De]&&!this[nt]&&!this[S]&&this[b].length===0&&this[Q]&&(this[De]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[De]=false)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==S&&this[S])return false;if(t==="data")return!this[L]&&!i?false:this[Z]?(jt(()=>this[Oi](i)),true):this[Oi](i);if(t==="end")return this[Is]();if(t==="close"){if(this[Ne]=true,!this[nt]&&!this[S])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(_i,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):false;return this[J](),n}else if(t==="resume"){let n=super.emit("resume");return this[J](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[J](),r}[Oi](t){for(let i of this[N])i.dest.write(t)===false&&this.pause();let e=this[C]?false:super.emit("data",t);return this[J](),e}[Is](){return this[nt]?false:(this[nt]=true,this.readable=false,this[Z]?(jt(()=>this[Ti]()),true):this[Ti]())}[Ti](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[N])i.dest.write(e);this[C]||super.emit("data",e)}}for(let e of this[N])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(S,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[C]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Q])return e();let n,o,h=d=>{this.off("data",a),this.off("end",l),this.off(S,c),e(),o(d)},a=d=>{this.off("error",h),this.off("end",l),this.off(S,c),this.pause(),n({value:d,done:!!this[Q]})},l=()=>{this.off("error",h),this.off("data",a),this.off(S,c),e(),n({done:true,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((d,y)=>{o=y,n=d,this.once(S,c),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[C]=false;let t=false,e=()=>(this.pause(),this.off(_i,e),this.off(S,e),this.off("end",e),t=true,{done:true,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(_i,e),this.once(S,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[S])return t?this.emit("error",t):this.emit(S),this;this[S]=true,this[C]=true,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(S),this}static get isStream(){return Wr}};Jr=I.writev;ht=Symbol("_autoClose");H=Symbol("_close");te=Symbol("_ended");m=Symbol("_fd");Ni=Symbol("_finished");tt=Symbol("_flags");Ai=Symbol("_flush");ki=Symbol("_handleChunk");vi=Symbol("_makeBuf");ie=Symbol("_mode");ke=Symbol("_needDrain");Ut=Symbol("_onerror");Ht=Symbol("_onopen");Ii=Symbol("_onread");Pt=Symbol("_onwrite");at=Symbol("_open");U=Symbol("_path");ot=Symbol("_pos");Y=Symbol("_queue");zt=Symbol("_read");Ci=Symbol("_readSize");j=Symbol("_reading");ee=Symbol("_remain");Fi=Symbol("_size");ve=Symbol("_write");gt=Symbol("_writing");Me=Symbol("_defaultFlag");bt=Symbol("_errored");_t=class extends A{[bt]=false;[m];[U];[Ci];[j]=false;[Fi];[ee];[ht];constructor(t,e){if(e=e||{},super(e),this.readable=true,this.writable=false,typeof t!="string")throw new TypeError("path must be a string");this[bt]=false,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ci]=e.readSize||16*1024*1024,this[j]=false,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true,typeof this[m]=="number"?this[zt]():this[at]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[at](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[vi](){return Buffer.allocUnsafe(Math.min(this[Ci],this[ee]))}[zt](){if(!this[j]){this[j]=true;let t=this[vi]();if(t.length===0)return process.nextTick(()=>this[Ii](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ii](e,i,r))}}[Ii](t,e,i){this[j]=false,t?this[Ut](t):this[ki](e,i)&&this[zt]()}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[j]=true,this[H](),this.emit("error",t)}[ki](t,e){let i=false;return this[ee]-=t,t>0&&(i=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ee]<=0)&&(i=false,this[H](),super.end()),i}emit(t,...e){switch(t){case"prefinish":case"finish":return false;case"drain":return typeof this[m]=="number"&&this[zt](),false;case"error":return this[bt]?false:(this[bt]=true,super.emit(t,...e));default:return super.emit(t,...e)}}};Be=class extends _t{[at](){let t=true;try{this[Ht](null,I.openSync(this[U],"r")),t=false}finally{t&&this[H]()}}[zt](){let t=true;try{if(!this[j]){this[j]=true;do{let e=this[vi](),i=e.length===0?0:I.readSync(this[m],e,0,e.length,null);if(!this[ki](i,e))break}while(true);this[j]=false}t=false}finally{t&&this[H]()}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}};et=class extends Qr{readable=false;writable=true;[bt]=false;[gt]=false;[te]=false;[Y]=[];[ke]=false;[U];[ie];[ht];[m];[Me];[tt];[Ni]=false;[ot];constructor(t,e){e=e||{},super(e),this[U]=t,this[m]=typeof e.fd=="number"?e.fd:void 0,this[ie]=e.mode===void 0?438:e.mode,this[ot]=typeof e.start=="number"?e.start:void 0,this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true;let i=this[ot]!==void 0?"r+":"w";this[Me]=e.flags===void 0,this[tt]=e.flags===void 0?i:e.flags,this[m]===void 0&&this[at]()}emit(t,...e){if(t==="error"){if(this[bt])return false;this[bt]=true}return super.emit(t,...e)}get fd(){return this[m]}get path(){return this[U]}[Ut](t){this[H](),this[gt]=true,this.emit("error",t)}[at](){I.open(this[U],this[tt],this[ie],(t,e)=>this[Ht](t,e))}[Ht](t,e){this[Me]&&this[tt]==="r+"&&t&&t.code==="ENOENT"?(this[tt]="w",this[at]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Ai]())}end(t,e){return t&&this.write(t,e),this[te]=true,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),false):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[ke]=true,false):(this[gt]=true,this[ve](t),true)}[ve](t){I.write(this[m],t,0,t.length,this[ot],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[ot]!==void 0&&typeof e=="number"&&(this[ot]+=e),this[Y].length?this[Ai]():(this[gt]=false,this[te]&&!this[Ni]?(this[Ni]=true,this[H](),this.emit("finish")):this[ke]&&(this[ke]=false,this.emit("drain"))))}[Ai](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ve](this[Y].pop());else{let t=this[Y];this[Y]=[],Jr(this[m],t,this[ot],(e,i)=>this[Pt](e,i))}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}};Wt=class extends et{[at](){let t;if(this[Me]&&this[tt]==="r+")try{t=I.openSync(this[U],this[tt],this[ie])}catch(e){if(e?.code==="ENOENT")return this[tt]="w",this[at]();throw e}else t=I.openSync(this[U],this[tt],this[ie]);this[Ht](null,t)}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ve](t){let e=true;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[ot])),e=false}finally{if(e)try{this[H]()}catch{}}}};jr=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]);Fs=s3=>!!s3.sync&&!!s3.file;ks=s3=>!s3.sync&&!!s3.file;vs=s3=>!!s3.sync&&!s3.file;Ms=s3=>!s3.sync&&!s3.file;Bs=s3=>!!s3.file;tn=s3=>{let t=jr.get(s3);return t||s3};se=(s3={})=>{if(!s3)return{};let t={};for(let[e,i]of Object.entries(s3)){let r=tn(e);t[r]=i}return t.chmod===void 0&&t.noChmod===false&&(t.chmod=true),delete t.noChmod,t};K=(s3,t,e,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=se(n);if(r?.(a,o),Fs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s3(a,o)}else if(ks(a)){let l=t(a,o);return h?l.then(()=>h(),h):l}else if(vs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return e(a,o)}else if(Ms(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s3,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});sn=en.constants||{ZLIB_VERNUM:4736};M=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sn));rn=Ot.concat;zs=Object.getOwnPropertyDescriptor(Ot,"concat");nn=s3=>s3;Bi=zs?.writable===true||zs?.set!==void 0?s3=>{Ot.concat=s3?nn:rn}:s3=>{};Tt=Symbol("_superWrite");Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}};Pi=Symbol("flushFlag");re=class extends A{#t=false;#i=false;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ps[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ps[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=true,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return zi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Pi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=true,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;zi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Bi(true);let h;try{let l=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l),Bi(false)}catch(l){Bi(false),this.#o(new Gt(l,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l=>this.#o(new Gt(l,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l=h[0];a=this[Tt](Ot.from(l));for(let c=1;c<h.length;c++)a=this[Tt](h[c])}else a=this[Tt](Ot.from(h));return i&&i(),a}};Pe=class extends re{#t;#i;constructor(t,e){t=t||{},t.flush=t.flush||M.Z_NO_FLUSH,t.finishFlush=t.finishFlush||M.Z_FINISH,t.fullFlushFlag=M.Z_FULL_FLUSH,super(t,e),this.#t=t.level,this.#i=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#t!==t||this.#i!==e){this.flush(M.Z_SYNC_FLUSH),zi(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(r,n)=>{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};ze=class extends Pe{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=false,t[9]=255,super[Tt](t)):super[Tt](t)}};Ue=class extends Pe{constructor(t){super(t,"Unzip")}};He=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}};We=class extends He{constructor(t){super(t,"BrotliCompress")}};Ge=class extends He{constructor(t){super(t,"BrotliDecompress")}};Ze=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}};Ye=class extends Ze{constructor(t){super(t,"ZstdCompress")}};Ke=class extends Ze{constructor(t){super(t,"ZstdDecompress")}};Us=(s3,t)=>{if(Number.isSafeInteger(s3))s3<0?an(s3,t):hn(s3,t);else throw Error("cannot encode number outside of javascript safe integer range");return t};hn=(s3,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s3&255,s3=Math.floor(s3/256)};an=(s3,t)=>{t[0]=255;var e=false;s3=s3*-1;for(var i=t.length;i>1;i--){var r=s3&255;s3=Math.floor(s3/256),e?t[i-1]=Ws(r):r===0?t[i-1]=0:(e=true,t[i-1]=Gs(r))}};Hs=s3=>{let t=s3[0],e=t===128?cn(s3.subarray(1,s3.length)):t===255?ln(s3):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e};ln=s3=>{for(var t=s3.length,e=0,i=false,r=t-1;r>-1;r--){var n=Number(s3[r]),o;i?o=Ws(n):n===0?o=n:(i=true,o=Gs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e};cn=s3=>{for(var t=s3.length,e=0,i=t-1;i>-1;i--){var r=Number(s3[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e};Ws=s3=>(255^s3)&255;Gs=s3=>(255^s3)+1&255;Hi={};Ur(Hi,{code:()=>Ve,isCode:()=>ne,isName:()=>dn,name:()=>oe,normalFsTypes:()=>Ui});ne=s3=>oe.has(s3);dn=s3=>Ve.has(s3);Ui=new Set(["0","","1","2","3","4","5","6","7","D"]);oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Ve=new Map(Array.from(oe).map(s3=>[s3[1],s3[0]]));un=s3=>s3===void 0||s3<0?void 0:s3;F=class{cksumValid=false;needPax=false;nullBlock=false;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=Ui.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??xt(t,e,100),this.mode=h?.mode??a?.mode??lt(t,e+100,8),this.uid=h?.uid??a?.uid??lt(t,e+108,8),this.gid=h?.gid??a?.gid??lt(t,e+116,8),this.size=un(h?.size??a?.size??lt(t,e+124,12)),this.mtime=h?.mtime??a?.mtime??Wi(t,e+136,12),this.cksum=lt(t,e+148,12),a&&this.#i(a,true),h&&this.#i(h),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??xt(t,e+265,32),this.gname=h?.gname??a?.gname??xt(t,e+297,32),this.devmaj=h?.devmaj??a?.devmaj??lt(t,e+329,8)??0,this.devmin=h?.devmin??a?.devmin??lt(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Wi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Wi(t,e+488,12)}let l=256;for(let c=e;c<e+148;c++)l+=t[c];for(let c=e+156;c<e+512;c++)l+=t[c];this.cksumValid=l===this.cksum,this.cksum===void 0&&l===256&&(this.nullBlock=true)}#i(t,e=false){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="size"&&Number(r)<0||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=mn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=ct(t,e+100,8,this.mode)||this.needPax,this.needPax=ct(t,e+108,8,this.uid)||this.needPax,this.needPax=ct(t,e+116,8,this.gid)||this.needPax,this.needPax=ct(t,e+124,12,this.size)||this.needPax,this.needPax=Gi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Gi(t,e+476,12,this.atime)||this.needPax,this.needPax=Gi(t,e+488,12,this.ctime)||this.needPax);let h=256;for(let a=e;a<e+148;a++)h+=t[a];for(let a=e+156;a<e+512;a++)h+=t[a];return this.cksum=h,ct(t,e+148,8,this.cksum),this.cksumValid=true,this.needPax}get type(){return this.#t==="Unsupported"?this.#t:oe.get(this.#t)}get typeKey(){return this.#t}set type(t){let e=String(Ve.get(t));if(ne(e)||e==="Unsupported")this.#t=e;else if(ne(t))this.#t=t;else throw new TypeError("invalid entry type: "+t)}};mn=(s3,t)=>{let i=s3,r="",n,o=Zt.parse(s3).root||".";if(Buffer.byteLength(i)<100)n=[i,r,false];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,false]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,true]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s3.slice(0,99),"",true])}return n};xt=(s3,t,e)=>s3.subarray(t,t+e).toString("utf8").replace(/\0.*/,"");Wi=(s3,t,e)=>pn(lt(s3,t,e));pn=s3=>s3===void 0?void 0:new Date(s3*1e3);lt=(s3,t,e)=>Number(s3[t])&128?Hs(s3.subarray(t,t+e)):wn(s3,t,e);En=s3=>isNaN(s3)?void 0:s3;wn=(s3,t,e)=>En(parseInt(s3.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8));Sn={12:8589934591,8:2097151};ct=(s3,t,e,i)=>i===void 0?false:i>Sn[e]||i<0?(Us(i,s3.subarray(t,t+e)),true):(yn(s3,t,e,i),false);yn=(s3,t,e,i)=>s3.write(Rn(i,e),t,e,"ascii");Rn=(s3,t)=>gn(Math.floor(s3).toString(8),t);gn=(s3,t)=>(s3.length===t-1?s3:new Array(t-s3.length-1).join("0")+s3+" ")+"\0";Gi=(s3,t,e,i)=>i===void 0?false:ct(s3,t,e,i.getTime()/1e3);bn=new Array(156).join("\0");Lt=(s3,t,e,i)=>i===void 0?false:(s3.write(i+bn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);ft=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=false){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new F({path:("PaxHeader/"+_n(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(r),r.write(t,512,e,"utf8");for(let n=e+512;n<r.length;n++)r[n]=0;return r}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let e=this[t],i=e instanceof Date?e.getTime()/1e3:e,r=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
|
|
126
126
|
`,n=Buffer.byteLength(r),o=Math.floor(Math.log(n)/Math.log(10))+1;return n+o>=Math.pow(10,o)&&(o+=1),o+n+r}static parse(t,e,i=false){return new s(On(Tn(t),e),i)}};On=(s3,t)=>t?Object.assign({},t,s3):s3;Tn=s3=>s3.replace(/\n$/,"").split(`
|
|
127
127
|
`).reduce(xn,Object.create(null));xn=(s3,t)=>{let e=parseInt(t,10);if(e!==Buffer.byteLength(t)+1)return s3;t=t.slice((e+" ").length);let i=t.split("="),r=i.shift();if(!r)return s3;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=").replace(/\0.*/,"");switch(n){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":s3[n]=o;break;case"ctime":case"atime":case"mtime":s3[n]=new Date(Number(o)*1e3);break;case"size":let h=+o;h>=0&&(s3[n]=h);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":s3[n]=+o;break}return s3};Ln=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;f=Ln!=="win32"?s3=>String(s3):s3=>String(s3).replaceAll(/\\/g,"/");$e=class extends A{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=false;ignore=false;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=false;absolute;unsupported=false;constructor(t,e,i){switch(super({}),this.pause(),this.extended=e,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=true;break;default:this.ignore=true}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=f(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?f(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#t(e),i&&this.#t(i,true)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-e),this.blockRemain=Math.max(0,r-e),this.ignore?true:i>=e?super.write(t):super.write(t.subarray(0,i))}#t(t,e=false){t.path&&(t.path=f(t.path)),t.linkpath&&(t.linkpath=f(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="path"&&e))))}};Dt=(s3,t,e,i={})=>{s3.file&&(i.file=s3.file),s3.cwd&&(i.cwd=s3.cwd),i.code=e instanceof Error&&e.code||t,i.tarCode=t,!s3.strict&&i.recoverable!==false?(e instanceof Error&&(i=Object.assign(e,i),e=e.message),s3.emit("warn",t,e,i)):e instanceof Error?s3.emit("error",Object.assign(e,i)):s3.emit("error",Object.assign(new Error(`${t}: ${e}`),i))};Nn=1024*1024;Xi=Buffer.from([31,139]);qi=Buffer.from([40,181,47,253]);An=Math.max(Xi.length,qi.length);B=Symbol("state");Nt=Symbol("writeEntry");it=Symbol("readEntry");Zi=Symbol("nextEntry");Zs=Symbol("processEntry");V=Symbol("extendedHeader");he=Symbol("globalExtendedHeader");dt=Symbol("meta");Ys=Symbol("emitMeta");p=Symbol("buffer");st=Symbol("queue");ut=Symbol("ended");Yi=Symbol("emittedEnd");At=Symbol("emit");w=Symbol("unzip");Xe=Symbol("consumeChunk");qe=Symbol("consumeChunkSub");Ki=Symbol("consumeBody");Ks=Symbol("consumeMeta");Vs=Symbol("consumeHeader");ae=Symbol("consuming");Vi=Symbol("bufferConcat");Qe=Symbol("maybeEnd");Yt=Symbol("writing");$=Symbol("aborted");Je=Symbol("onDone");It=Symbol("sawValidEntry");je=Symbol("sawNullBlock");ti=Symbol("sawEOF");$s=Symbol("closeStream");In=1e3;le=Symbol("compressedBytesRead");$i=Symbol("decompressedBytesRead");Xs=Symbol("checkDecompressionRatio");Cn=()=>true;rt=class extends Dn{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=true;readable=false;[st]=[];[p];[it];[Nt];[B]="begin";[dt]="";[V];[he];[ut]=false;[w];[$]=false;[It];[je]=false;[ti]=false;[Yt]=false;[ae]=false;[Yi]=false;[le]=0;[$i]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Je,()=>{(this[B]==="begin"||this[It]===false)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Je,t.ondone):this.on(Je,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:In,this.maxMetaEntrySize=t.maxMetaEntrySize||Nn,this.filter=typeof t.filter=="function"?t.filter:Cn;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:false;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?true:void 0,this.on("end",()=>this[$s]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,i={}){Dt(this,t,e,i)}[Vs](t,e){this[It]===void 0&&(this[It]=false);let i;try{i=new F(t,e,this[V],this[he])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[je]?(this[ti]=true,this[B]==="begin"&&(this[B]="header"),this[At]("eof")):(this[je]=true,this[At]("nullBlock"));else if(this[je]=false,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let n=this[Nt]=new $e(i,this[V],this[he]);if(!this[It])if(n.remain){let o=()=>{n.invalid||(this[It]=true)};n.on("end",o)}else this[It]=true;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=true,this[At]("ignoredEntry",n),this[B]="ignore",n.resume()):n.size>0&&(this[dt]="",n.on("data",o=>this[dt]+=o),this[B]="meta"):(this[V]=void 0,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[At]("ignoredEntry",n),this[B]=n.remain?"ignore":"header",n.resume()):(n.remain?this[B]="body":(this[B]="header",n.end()),this[it]?this[st].push(n):(this[st].push(n),this[Zi]())))}}}[$s](){queueMicrotask(()=>this.emit("close"))}[Zs](t){let e=true;if(!t)this[it]=void 0,e=false;else if(Array.isArray(t)){let[i,...r]=t;this.emit(i,...r)}else this[it]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Zi]()),e=false);return e}[Zi](){do;while(this[Zs](this[st].shift()));if(this[st].length===0){let t=this[it];!t||t.flowing||t.size===t.remain?this[Yt]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ki](t,e){let i=this[Nt];if(!i)throw new Error("attempt to consume body without entry??");let r=i.blockRemain??0,n=r>=t.length&&e===0?t:t.subarray(e,e+r);return i.write(n),i.blockRemain||(this[B]="header",this[Nt]=void 0,i.end()),n.length}[Ks](t,e){let i=this[Nt],r=this[Ki](t,e);return!this[Nt]&&i&&this[Ys](i),r}[At](t,e,i){this[st].length===0&&!this[it]?this.emit(t,e,i):this[st].push([t,e,i])}[Ys](t){switch(this[At]("meta",this[dt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[V]=ft.parse(this[dt],this[V],false);break;case"GlobalExtendedHeader":this[he]=ft.parse(this[dt],this[he],true);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[V]??Object.create(null);this[V]=e,e.path=this[dt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[V]||Object.create(null);this[V]=e,e.linkpath=this[dt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[$]){if(this[w]){let e=this[w];e.write=()=>true,e.end=()=>e,e.emit=()=>false,e.destroy?.()}this[$]=true,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:false})}}[Xs](t){this[$i]+=t.length;let e=this[$i]/this[le];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),false):true}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[$])return i?.(),false;if((this[w]===void 0||this.brotli===void 0&&this[w]===false)&&t){if(this[p]&&(t=Buffer.concat([this[p],t]),this[p]=void 0),t.length<An)return this[p]=t,i?.(),true;for(let a=0;this[w]===void 0&&a<Xi.length;a++)t[a]!==Xi[a]&&(this[w]=false);let o=false;if(this[w]===false&&this.zstd!==false){o=true;for(let a=0;a<qi.length;a++)if(t[a]!==qi[a]){o=false;break}}let h=this.brotli===void 0&&!o;if(this[w]===false&&h)if(t.length<512)if(this[ut])this.brotli=true;else return this[p]=t,i?.(),true;else try{new F(t.subarray(0,512)),this.brotli=false}catch{this.brotli=true}if(this[w]===void 0||this[w]===false&&(this.brotli||o)){let a=this[ut];this[ut]=false,this[w]=this[w]===void 0?new Ue({}):o?new Ke({}):new Ge({}),this[w].on("data",c=>{this[Xs](c)&&this[Xe](c)}),this[w].on("error",c=>{this[$]||this.abort(c)}),this[w].on("end",()=>{this[ut]=true,this[Xe]()}),this[Yt]=true,this[le]+=t.length;let l=!!this[w][a?"end":"write"](t);return this[Yt]=false,i?.(),l}}this[Yt]=true,this[w]?(this[le]+=t.length,this[w].write(t)):this[Xe](t),this[Yt]=false;let n=this[st].length>0?false:this[it]?this[it].flowing:true;return!n&&this[st].length===0&&this[it]?.once("drain",()=>this.emit("drain")),i?.(),n}[Vi](t){t&&!this[$]&&(this[p]=this[p]?Buffer.concat([this[p],t]):t)}[Qe](){if(this[ut]&&!this[Yi]&&!this[$]&&!this[ae]){this[Yi]=true;let t=this[Nt];if(t?.blockRemain){let e=this[p]?this[p].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[p]&&t.write(this[p]),t.end()}this[At](Je)}}[Xe](t){if(this[ae]&&t)this[Vi](t);else if(!t&&!this[p])this[Qe]();else if(t){if(this[ae]=true,this[p]){this[Vi](t);let e=this[p];this[p]=void 0,this[qe](e)}else this[qe](t);for(;this[p]&&this[p]?.length>=512&&!this[$]&&!this[ti];){let e=this[p];this[p]=void 0,this[qe](e)}this[ae]=false}(!this[p]||this[ut])&&this[Qe]()}[qe](t){let e=0,i=t.length;for(;e+512<=i&&!this[$]&&!this[ti];)switch(this[B]){case"begin":case"header":this[Vs](t,e),e+=512;break;case"ignore":case"body":e+=this[Ki](t,e);break;case"meta":e+=this[Ks](t,e);break;default:throw new Error("invalid state: "+this[B])}e<i&&(this[p]=this[p]?Buffer.concat([t.subarray(e),this[p]]):t.subarray(e))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),i&&this.once("finish",i),this[$]||(this[w]?(t&&(this[le]+=t.length,this[w].write(t)),this[w].end()):(this[ut]=true,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Qe]())),this}};mt=s3=>{let t=s3.length-1,e=-1;for(;t>-1&&s3.charAt(t)==="/";)e=t,t--;return e===-1?s3:s3.slice(0,e)};vn=s3=>{let t=s3.onReadEntry;s3.onReadEntry=t?e=>{t(e),e.resume()}:e=>e.resume()};Qi=(s3,t)=>{let e=new Map(t.map(o=>[mt(o),true])),i=s3.filter,r=100,n=(o,h="",a=0)=>{if(a>=r)return e.set(o,false),false;let l=h||kn(o).root||".",c;if(o===l)c=false;else{let d=e.get(o);c=d!==void 0?d:n(Fn(o),l,a+1)}return e.set(o,c),c};s3.filter=i?(o,h)=>i(o,h)&&n(mt(o)):o=>n(mt(o))};Mn=s3=>{let t=new rt(s3),e=s3.file,i;try{i=Kt.openSync(e,"r");let r=Kt.fstatSync(i),n=s3.maxReadSize||16*1024*1024;if(r.size<n){let o=Buffer.allocUnsafe(r.size),h=Kt.readSync(i,o,0,r.size,0);t.end(h===o.byteLength?o:o.subarray(0,h))}else{let o=0,h=Buffer.allocUnsafe(n);for(;o<r.size;){let a=Kt.readSync(i,h,0,n,o);if(a===0)break;o+=a,t.write(h.subarray(0,a))}t.end()}}finally{if(typeof i=="number")try{Kt.closeSync(i)}catch{}}};Bn=(s3,t)=>{let e=new rt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("end",o),Kt.stat(r,(a,l)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l.size});c.on("error",h),c.pipe(e)}})})};Ct=K(Mn,Bn,s3=>new rt(s3),s3=>new rt(s3),(s3,t)=>{t?.length&&Qi(s3,t),s3.noResume||vn(s3)});Ji=(s3,t,e)=>(s3&=4095,e&&(s3=(s3|384)&-19),t&&(s3&256&&(s3|=64),s3&32&&(s3|=8),s3&4&&(s3|=1)),s3);({isAbsolute:zn,parse:qs}=Pn);ce=s3=>{let t="",e=qs(s3);for(;zn(s3)||e.root;){let i=s3.charAt(0)==="/"&&s3.slice(0,4)!=="//?/"?"/":e.root;s3=s3.slice(i.length),t+=i,e=qs(s3)}return[t,s3]};ei=["|","<",">","?",":"];ji=ei.map(s3=>String.fromCodePoint(61440+Number(s3.codePointAt(0))));Un=new Map(ei.map((s3,t)=>[s3,ji[t]]));Hn=new Map(ji.map((s3,t)=>[s3,ei[t]]));ts=s3=>ei.reduce((t,e)=>t.split(e).join(Un.get(e)),s3);Qs=s3=>ji.reduce((t,e)=>t.split(e).join(Hn.get(e)),s3);rr=(s3,t)=>t?(s3=f(s3).replace(/^\.(\/|$)/,""),mt(t)+"/"+s3):f(s3);Wn=16*1024*1024;tr=Symbol("process");er=Symbol("file");ir=Symbol("directory");is=Symbol("symlink");sr=Symbol("hardlink");fe=Symbol("header");ii=Symbol("read");ss=Symbol("lstat");si=Symbol("onlstat");rs=Symbol("onread");ns=Symbol("onreadlink");os5=Symbol("openfile");hs=Symbol("onopenfile");pt=Symbol("close");ri=Symbol("mode");as=Symbol("awaitDrain");es=Symbol("ondrain");q=Symbol("prefix");de=class extends A{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#t=false;constructor(t,e={}){let i=se(e);super(),this.path=f(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||Wn,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=f(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?f(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let r=false;if(!this.preservePaths){let[o,h]=ce(this.path);o&&typeof h=="string"&&(this.path=h,r=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=Qs(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=f(i.absolute||js.resolve(this.cwd,t)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let n=this.statCache.get(this.absolute);n?this[si](n):this[ss]()}warn(t,e,i={}){return Dt(this,t,e,i)}emit(t,...e){return t==="error"&&(this.#t=true),super.emit(t,...e)}[ss](){X.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[si](e)})}[si](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Gn(t),this.emit("stat",t),this[tr]()}[tr](){switch(this.type){case"File":return this[er]();case"Directory":return this[ir]();case"SymbolicLink":return this[is]();default:return this.end()}}[ri](t){return Ji(t,this.type==="Directory",this.portable)}[q](t){return rr(t,this.prefix)}[fe](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=true),this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this[ri](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new ft({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[ir](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[fe](),this.end()}[is](){X.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ns](e)})}[ns](t){this.linkpath=f(t),this[fe](),this.end()}[sr](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=f(js.relative(this.cwd,t)),this.stat.size=0,this[fe](),this.end()}[er](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[sr](e);this.linkCache.set(t,this.absolute)}if(this[fe](),this.stat.size===0)return this.end();this[os5]()}[os5](){X.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[hs](e)})}[hs](t){if(this.fd=t,this.#t)return this[pt]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[ii]()}[ii](){let{fd:t,buf:e,offset:i,length:r,pos:n}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");X.read(t,e,i,r,n,(o,h)=>{if(o)return this[pt](()=>this.emit("error",o));this[rs](h)})}[pt](t=()=>{}){this.fd!==void 0&&X.close(this.fd,t)}[rs](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[es]():this[as](()=>this[es]())}[as](t){this.once("drain",t)}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let r=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",r)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,i)}[es](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[pt](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[ii]()}};ni=class extends de{sync=true;[ss](){this[si](X.lstatSync(this.absolute))}[is](){this[ns](X.readlinkSync(this.absolute))}[os5](){this[hs](X.openSync(this.absolute,"r"))}[ii](){let t=true;try{let{fd:e,buf:i,offset:r,length:n,pos:o}=this;if(e===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let h=X.readSync(e,i,r,n,o);this[rs](h),t=false}finally{if(t)try{this[pt](()=>{})}catch{}}}[as](t){t()}[pt](t=()=>{}){this.fd!==void 0&&X.closeSync(this.fd),t()}};oi=class extends A{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,i={}){return Dt(this,t,e,i)}constructor(t,e={}){let i=se(e);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=t;let{type:r}=t;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=true),this.prefix=i.prefix,this.path=f(t.path),this.mode=t.mode!==void 0?this[ri](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?f(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=false;if(!this.preservePaths){let[h,a]=ce(this.path);h&&typeof a=="string"&&(this.path=a,n=h)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new ft({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[q](t){return rr(t,this.prefix)}[ri](t){return Ji(t,this.type==="Directory",this.portable)}write(t,e,i){typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(t,i)}end(t,e,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}};Gn=s3=>s3.isFile()?"File":s3.isDirectory()?"Directory":s3.isSymbolicLink()?"SymbolicLink":"Unsupported";hi=class s2{tail;head;length=0;static create(t=[]){return new s2(t)}constructor(t=[]){for(let e of t)this.push(e)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let e=t.next,i=t.prev;return e&&(e.prev=i),i&&(i.next=e),t===this.head&&(this.head=e),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,e}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let e=this.head;t.list=this,t.next=e,e&&(e.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let e=this.tail;t.list=this,t.prev=e,e&&(e.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let e=0,i=t.length;e<i;e++)Yn(this,t[e]);return this.length}unshift(...t){for(var e=0,i=t.length;e<i;e++)Kn(this,t[e]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,e=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,e.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,e=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,e.list=void 0,this.length--,t}forEach(t,e){e=e||this;for(let i=this.head,r=0;i;r++)t.call(e,i.value,r,this),i=i.next}forEachReverse(t,e){e=e||this;for(let i=this.tail,r=this.length-1;i;r--)t.call(e,i.value,r,this),i=i.prev}get(t){let e=0,i=this.head;for(;i&&e<t;e++)i=i.next;if(e===t&&i)return i.value}getReverse(t){let e=0,i=this.tail;for(;i&&e<t;e++)i=i.prev;if(e===t&&i)return i.value}map(t,e){e=e||this;let i=new s2;for(let r=this.head;r;)i.push(t.call(e,r.value,this)),r=r.next;return i}mapReverse(t,e){e=e||this;var i=new s2;for(let r=this.tail;r;)i.push(t.call(e,r.value,this)),r=r.prev;return i}reduce(t,e){let i,r=this.head;if(arguments.length>1)i=e;else if(this.head)r=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;r;n++)i=t(i,r.value,n),r=r.next;return i}reduceReverse(t,e){let i,r=this.tail;if(arguments.length>1)i=e;else if(this.tail)r=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let n=this.length-1;r;n--)i=t(i,r.value,n),r=r.prev;return i}toArray(){let t=new Array(this.length);for(let e=0,i=this.head;i;e++)t[e]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let e=0,i=this.tail;i;e++)t[e]=i.value,i=i.prev;return t}slice(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.head,n=0;for(n=0;r&&n<t;n++)r=r.next;for(;r&&n<e;n++,r=r.next)i.push(r.value);return i}sliceReverse(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.length,n=this.tail;for(;n&&r>e;r--)n=n.prev;for(;n&&r>t;r--,n=n.prev)i.push(n.value);return i}splice(t,e=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let r=this.head;for(let o=0;r&&o<t;o++)r=r.next;let n=[];for(let o=0;r&&o<e;o++)n.push(r.value),r=this.removeNode(r);r?r!==this.tail&&(r=r.prev):r=this.tail;for(let o of i)r=Zn(this,r,o);return n}reverse(){let t=this.head,e=this.tail;for(let i=t;i;i=i.prev){let r=i.prev;i.prev=i.next,i.next=r}return this.head=e,this.tail=t,this}};ue=class{list;next;prev;value;constructor(t,e,i,r){this.list=r,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,i?(i.prev=this,this.next=i):this.next=void 0}};pi=class{path;absolute;entry;stat;readdir;pending=false;pendingLink=false;ignore=false;piped=false;constructor(t,e){this.path=t||"./",this.absolute=e}};nr=Buffer.alloc(1024);li=Symbol("onStat");me=Symbol("ended");W=Symbol("queue");pe=Symbol("pendingLinks");Et=Symbol("current");Ft=Symbol("process");Ee=Symbol("processing");ai=Symbol("processJob");G=Symbol("jobs");ls=Symbol("jobDone");ci=Symbol("addFSEntry");or=Symbol("addTarEntry");ds=Symbol("stat");us=Symbol("readdir");fi=Symbol("onreaddir");di=Symbol("pipe");hr=Symbol("entry");cs=Symbol("entryOpt");ui=Symbol("writeEntryClass");lr=Symbol("write");fs7=Symbol("ondrain");wt=class extends A{sync=false;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ui];onWriteEntry;[W];[pe]=new Map;[G]=0;[Ee]=false;[me]=false;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=f(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[ui]=de,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=true),this.zip=new ze(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new We(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ye(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",i=>super.write(i)),e.on("end",()=>super.end()),e.on("drain",()=>this[fs7]()),this.on("resume",()=>e.resume())}else this.on("drain",this[fs7]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>true,this[W]=new hi,this[G]=0,this.jobs=Number(t.jobs)||4,this[Ee]=false,this[me]=false}[lr](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&this.add(t),this[me]=true,this[Ft](),i&&i(),this}write(t){if(this[me])throw new Error("write after end");return typeof t=="string"?this[ci](t):this[or](t),this.flowing}[or](t){let e=f(ar.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new pi(t.path,e);i.entry=new oi(t,this[cs](i)),i.entry.on("end",()=>this[ls](i)),this[G]+=1,this[W].push(i)}this[Ft]()}[ci](t){let e=f(ar.resolve(this.cwd,t));this[W].push(new pi(t,e)),this[Ft]()}[ds](t){t.pending=true,this[G]+=1;let e=this.follow?"stat":"lstat";mi[e](t.absolute,(i,r)=>{t.pending=false,this[G]-=1,i?this.emit("error",i):this[li](t,r)})}[li](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=true;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Et])this[ai](t);else{let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);r?r.push(t):this[pe].set(i,[t]),t.pendingLink=true,t.pending=true}this[Ft]()}[us](t){t.pending=true,this[G]+=1,mi.readdir(t.absolute,(e,i)=>{if(t.pending=false,this[G]-=1,e)return this.emit("error",e);this[fi](t,i)})}[fi](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Ft]()}[Ft](){if(!this[Ee]){this[Ee]=true;for(let t=this[W].head;t&&this[G]<this.jobs;t=t.next)if(this[ai](t.value),t.value.ignore){let e=t.next;this[W].removeNode(t),t.next=e}this[Ee]=false,this[me]&&this[W].length===0&&this[G]===0&&(this.zip?this.zip.end(nr):(super.write(nr),super.end()))}}get[Et](){return this[W]&&this[W].head&&this[W].head.value}[ls](t){this[W].shift(),this[G]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);if(r){this[pe].delete(i);for(let n of r)n.pending=false,this[ai](n)}}this[Ft]()}[ai](t){if(t.pending&&t.pendingLink&&t===this[Et]&&(t.pending=false,t.pendingLink=false),!t.pending){if(t.entry){t===this[Et]&&!t.piped&&this[di](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[li](t,e):this[ds](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[fi](t,e):this[us](t),!t.readdir)return}if(t.entry=this[hr](t),!t.entry){t.ignore=true;return}t===this[Et]&&!t.piped&&this[di](t)}}}[cs](t){return{onwarn:(e,i,r)=>this.warn(e,i,r),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[hr](t){this[G]+=1;try{return new this[ui](t.path,this[cs](t)).on("end",()=>this[ls](t)).on("error",i=>this.emit("error",i))}catch(e){this.emit("error",e)}}[fs7](){this[Et]&&this[Et].entry&&this[Et].entry.resume()}[di](t){t.piped=true,t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)});let e=t.entry,i=this.zip;if(!e)throw new Error("cannot pipe without source");i?e.on("data",r=>{i.write(r)||e.pause()}):e.on("data",r=>{super.write(r)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,i={}){Dt(this,t,e,i)}};kt=class extends wt{sync=true;constructor(t){super(t),this[ui]=ni}pause(){}resume(){}[ds](t){let e=this.follow?"statSync":"lstatSync";this[li](t,mi[e](t.absolute))}[us](t){this[fi](t,mi.readdirSync(t.absolute))}[di](t){let e=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)}),!e)throw new Error("Cannot pipe without source");i?e.on("data",r=>{i.write(r)}):e.on("data",r=>{super[lr](r)})}};Vn=(s3,t)=>{let e=new kt(s3),i=new Wt(s3.file,{mode:s3.mode||438});e.pipe(i),fr(e,t)};$n=(s3,t)=>{let e=new wt(s3),i=new et(s3.file,{mode:s3.mode||438});e.pipe(i);let r=new Promise((n,o)=>{i.on("error",o),i.on("close",n),e.on("error",o)});return dr(e,t).catch(n=>e.emit("error",n)),r};fr=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:cr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};dr=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:cr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>{s3.add(i)}}):s3.add(e);s3.end()};Xn=(s3,t)=>{let e=new kt(s3);return fr(e,t),e};qn=(s3,t)=>{let e=new wt(s3);return dr(e,t).catch(i=>e.emit("error",i)),e};Qn=K(Vn,$n,Xn,qn,(s3,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});Jn=process.env.__FAKE_PLATFORM__||process.platform;Er=Jn==="win32";({O_CREAT:wr,O_NOFOLLOW:ur,O_TRUNC:Sr,O_WRONLY:yr}=pr.constants);Rr=Number(process.env.__FAKE_FS_O_FILENAME__)||pr.constants.UV_FS_O_FILEMAP||0;jn=Er&&!!Rr;to=512*1024;eo=Rr|Sr|wr|yr;mr=!Er&&typeof ur=="number"?ur|Sr|wr|yr:null;ms=mr!==null?()=>mr:jn?s3=>s3<to?eo:"w":()=>"w";ps=(s3,t,e)=>{try{return wi.lchownSync(s3,t,e)}catch(i){if(i?.code!=="ENOENT")throw i}};Ei=(s3,t,e,i)=>{wi.lchown(s3,t,e,r=>{i(r&&r?.code!=="ENOENT"?r:null)})};io=(s3,t,e,i,r)=>{if(t.isDirectory())Es(we.resolve(s3,t.name),e,i,n=>{if(n)return r(n);let o=we.resolve(s3,t.name);Ei(o,e,i,r)});else{let n=we.resolve(s3,t.name);Ei(n,e,i,r)}};Es=(s3,t,e,i)=>{wi.readdir(s3,{withFileTypes:true},(r,n)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!n.length)return Ei(s3,t,e,i);let o=n.length,h=null,a=l=>{if(!h){if(l)return i(h=l);if(--o===0)return Ei(s3,t,e,i)}};for(let l of n)io(s3,l,t,e,a)})};so=(s3,t,e,i)=>{t.isDirectory()&&ws(we.resolve(s3,t.name),e,i),ps(we.resolve(s3,t.name),e,i)};ws=(s3,t,e)=>{let i;try{i=wi.readdirSync(s3,{withFileTypes:true})}catch(r){let n=r;if(n?.code==="ENOENT")return;if(n?.code==="ENOTDIR"||n?.code==="ENOTSUP")return ps(s3,t,e);throw n}for(let r of i)so(s3,r,t,e);return ps(s3,t,e)};Se=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}};St=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}};no=(s3,t)=>{k.stat(s3,(e,i)=>{(e||!i.isDirectory())&&(e=new Se(s3,e?.code||"ENOTDIR")),t(e)})};gr=(s3,t,e)=>{s3=f(s3);let i=t.umask??18,r=t.mode|448,n=(r&i)!==0,o=t.uid,h=t.gid,a=typeof o=="number"&&typeof h=="number"&&(o!==t.processUid||h!==t.processGid),l=t.preserve,c=t.unlink,d=f(t.cwd),y=(E,x)=>{E?e(E):x&&a?Es(x,o,h,Le=>y(Le)):n?k.chmod(s3,r,e):e()};if(s3===d)return no(s3,y);if(l)return ro.mkdir(s3,{mode:r,recursive:true}).then(E=>y(null,E??void 0),y);let D=f(Si.relative(d,s3)).split("/");Ss(d,D,r,c,d,void 0,y)};Ss=(s3,t,e,i,r,n,o)=>{if(t.length===0)return o(null,n);let h=t.shift(),a=f(Si.resolve(s3+"/"+h));k.mkdir(a,e,br(a,t,e,i,r,n,o))};br=(s3,t,e,i,r,n,o)=>h=>{h?k.lstat(s3,(a,l)=>{if(a)a.path=a.path&&f(a.path),o(a);else if(l.isDirectory())Ss(s3,t,e,i,r,n,o);else if(i)k.unlink(s3,c=>{if(c)return o(c);k.mkdir(s3,e,br(s3,t,e,i,r,n,o))});else{if(l.isSymbolicLink())return o(new St(s3,s3+"/"+t.join("/")));o(h)}}):(n=n||s3,Ss(s3,t,e,i,r,n,o))};oo=s3=>{let t=false,e;try{t=k.statSync(s3).isDirectory()}catch(i){e=i?.code}finally{if(!t)throw new Se(s3,e??"ENOTDIR")}};_r=(s3,t)=>{s3=f(s3);let e=t.umask??18,i=t.mode|448,r=(i&e)!==0,n=t.uid,o=t.gid,h=typeof n=="number"&&typeof o=="number"&&(n!==t.processUid||o!==t.processGid),a=t.preserve,l=t.unlink,c=f(t.cwd),d=E=>{E&&h&&ws(E,n,o),r&&k.chmodSync(s3,i)};if(s3===c)return oo(c),d();if(a)return d(k.mkdirSync(s3,{mode:i,recursive:true})??void 0);let T=f(Si.relative(c,s3)).split("/"),D;for(let E=T.shift(),x=c;E&&(x+="/"+E);E=T.shift()){x=f(Si.resolve(x));try{k.mkdirSync(x,i),D=D||x}catch{let Le=k.lstatSync(x);if(Le.isDirectory())continue;if(l){k.unlinkSync(x),k.mkdirSync(x,i),D=D||x;continue}else if(Le.isSymbolicLink())return new St(x,x+"/"+T.join("/"))}}return d(D)};ys=Object.create(null);Or=1e4;Vt=new Set;Tr=s3=>{Vt.has(s3)?Vt.delete(s3):ys[s3]=s3.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Vt.add(s3);let t=ys[s3],e=Vt.size-Or;if(e>Or/10){for(let i of Vt)if(Vt.delete(i),delete ys[i],--e<=0)break}return t};ho=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;ao=ho==="win32";lo=s3=>s3.split("/").slice(0,-1).reduce((e,i)=>{let r=e.at(-1);return r!==void 0&&(i=xr(r,i)),e.push(i||"/"),e},[]);yi=class{#t=new Map;#i=new Map;#s=new Set;reserve(t,e){t=ao?["win32 parallelization disabled"]:t.map(r=>mt(xr(Tr(r))));let i=new Set(t.map(r=>lo(r)).reduce((r,n)=>r.concat(n)));this.#i.set(e,{dirs:i,paths:t});for(let r of t){let n=this.#t.get(r);n?n.push(e):this.#t.set(r,[e])}for(let r of i){let n=this.#t.get(r);if(!n)this.#t.set(r,[new Set([e])]);else{let o=n.at(-1);o instanceof Set?o.add(e):n.push(new Set([e]))}}return this.#r(e)}#n(t){let e=this.#i.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(i=>this.#t.get(i)),dirs:[...e.dirs].map(i=>this.#t.get(i))}}check(t){let{paths:e,dirs:i}=this.#n(t);return e.every(r=>r&&r[0]===t)&&i.every(r=>r&&r[0]instanceof Set&&r[0].has(t))}#r(t){return this.#s.has(t)||!this.check(t)?false:(this.#s.add(t),t(()=>this.#e(t)),true)}#e(t){if(!this.#s.has(t))return false;let e=this.#i.get(t);if(!e)throw new Error("invalid reservation");let{paths:i,dirs:r}=e,n=new Set;for(let o of i){let h=this.#t.get(o);if(!h||h?.[0]!==t)continue;let a=h[1];if(!a){this.#t.delete(o);continue}if(h.shift(),typeof a=="function")n.add(a);else for(let l of a)n.add(l)}for(let o of r){let h=this.#t.get(o),a=h?.[0];if(!(!h||!(a instanceof Set)))if(a.size===1&&h.length===1){this.#t.delete(o);continue}else if(a.size===1){h.shift();let l=h[0];typeof l=="function"&&n.add(l)}else a.delete(t)}return this.#s.delete(t),n.forEach(o=>this.#r(o)),true}};Lr=()=>process.umask();Dr=Symbol("onEntry");_s=Symbol("checkFs");Nr=Symbol("checkFs2");Os=Symbol("isReusable");P=Symbol("makeFs");Ts=Symbol("file");xs=Symbol("directory");gi=Symbol("link");Ar=Symbol("symlink");Ir=Symbol("hardlink");Re=Symbol("ensureNoSymlink");Cr=Symbol("unsupported");Fr=Symbol("checkPath");Rs=Symbol("stripAbsolutePath");yt=Symbol("mkdir");O=Symbol("onError");Ri=Symbol("pending");kr=Symbol("pend");$t=Symbol("unpend");gs=Symbol("ended");bs=Symbol("maybeClose");Ls=Symbol("skip");ge=Symbol("doChown");be=Symbol("uid");_e=Symbol("gid");Oe=Symbol("checkedCwd");fo=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;Te=fo==="win32";uo=1024;mo=(s3,t)=>{if(!Te)return u.unlink(s3,t);let e=s3+".DELETE."+Mr(16).toString("hex");u.rename(s3,e,i=>{if(i)return t(i);u.unlink(e,t)})};po=s3=>{if(!Te)return u.unlinkSync(s3);let t=s3+".DELETE."+Mr(16).toString("hex");u.renameSync(s3,t),u.unlinkSync(t)};vr=(s3,t,e)=>s3!==void 0&&s3===s3>>>0?s3:t!==void 0&&t===t>>>0?t:e;Xt=class extends rt{[gs]=false;[Oe]=false;[Ri]=0;reservations=new yi;transform;writable=true;readable=false;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[gs]=true,this[bs]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=true}else this.uid=void 0,this.gid=void 0,this.setOwner=false;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:uo,this.forceChown=t.forceChown===true,this.win32=!!t.win32||Te,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=f(R.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Lr():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Dr](e))}warn(t,e,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=false),super.warn(t,e,i)}[bs](){this[gs]&&this[Ri]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Rs](t,e){let i=t[e],{type:r}=t;if(!i||this.preservePaths)return true;let[n,o]=ce(i),h=o.replaceAll(/\\/g,"/").split("/");if(h.includes("..")||Te&&/^[a-z]:\.\.$/i.test(h[0]??"")){if(e==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:i}),false;let a=R.posix.dirname(t.path),l=R.posix.normalize(R.posix.join(a,h.join("/")));if(l.startsWith("../")||l==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:i}),false}return n&&(t[e]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute ${e}`,{entry:t,[e]:i})),true}[Fr](t){let e=f(t.path),i=e.split("/");if(this.strip){if(i.length<this.strip)return false;if(t.type==="Link"){let r=f(String(t.linkpath)).split("/");if(r.length>=this.strip)t.linkpath=r.slice(this.strip).join("/");else return false}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:i.length,maxDepth:this.maxDepth}),false;if(!this[Rs](t,"path")||!this[Rs](t,"linkpath"))return false;if(t.absolute=R.isAbsolute(t.path)?f(R.resolve(t.path)):f(R.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:f(t.path),resolvedPath:t.absolute,cwd:this.cwd}),false;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return false;if(this.win32){let{root:r}=R.win32.parse(String(t.absolute));t.absolute=r+ts(String(t.absolute).slice(r.length));let{root:n}=R.win32.parse(t.path);t.path=n+ts(t.path.slice(n.length))}return true}[Dr](t){if(!this[Fr](t))return t.resume();switch(co.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[_s](t);default:return this[Cr](t)}}[O](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[$t](),e.resume())}[yt](t,e,i){gr(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},i)}[ge](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[be](t){return vr(this.uid,t.uid,this.processUid)}[_e](t){return vr(this.gid,t.gid,this.processGid)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new et(String(t.absolute),{flags:ms(t.size),mode:i,autoClose:false});r.on("error",a=>{r.fd&&u.close(r.fd,()=>{}),r.write=()=>true,this[O](a,t),e()});let n=1,o=a=>{if(a){r.fd&&u.close(r.fd,()=>{}),this[O](a,t),e();return}--n===0&&r.fd!==void 0&&u.close(r.fd,l=>{l?this[O](l,t):this[$t](),e()})};r.on("finish",()=>{let a=String(t.absolute),l=r.fd;if(typeof l=="number"&&t.mtime&&!this.noMtime){n++;let c=t.atime||new Date,d=t.mtime;u.futimes(l,c,d,y=>y?u.utimes(a,c,d,T=>o(T&&y)):o())}if(typeof l=="number"&&this[ge](t)){n++;let c=this[be](t),d=this[_e](t);typeof c=="number"&&typeof d=="number"&&u.fchown(l,c,d,y=>y?u.chown(a,c,d,T=>o(T&&y)):o())}o()});let h=this.transform&&this.transform(t)||t;h!==t&&(h.on("error",a=>{this[O](a,t),e()}),t.pipe(h)),h.pipe(r)}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yt](String(t.absolute),i,r=>{if(r){this[O](r,t),e();return}let n=1,o=()=>{--n===0&&(e(),this[$t](),t.resume())};t.mtime&&!this.noMtime&&(n++,u.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[ge](t)&&(n++,u.chown(String(t.absolute),Number(this[be](t)),Number(this[_e](t)),o)),o()})}[Cr](t){t.unsupported=true,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ar](t,e){let i=f(R.relative(this.cwd,R.resolve(R.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Re](t,this.cwd,i,()=>this[gi](t,String(t.linkpath),"symlink",e),r=>{this[O](r,t),e()})}[Ir](t,e){let i=f(R.resolve(this.cwd,String(t.linkpath))),r=f(String(t.linkpath)).split("/");this[Re](t,this.cwd,r,()=>this[gi](t,i,"link",e),n=>{this[O](n,t),e()})}[Re](t,e,i,r,n){let o=i.shift();if(this.preservePaths||o===void 0)return r();let h=R.resolve(e,o);u.lstat(h,(a,l)=>{if(a)return r();if(l?.isSymbolicLink())return n(new St(h,R.resolve(h,i.join("/"))));this[Re](t,h,i,r,n)})}[kr](){this[Ri]++}[$t](){this[Ri]--,this[bs]()}[Ls](t){this[$t](),t.resume()}[Os](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Te}[_s](t){this[kr]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,i=>this[Nr](t,i))}[Nr](t,e){let i=h=>{e(h)},r=()=>{this[yt](this.cwd,this.dmode,h=>{if(h){this[O](h,t),i();return}this[Oe]=true,n()})},n=()=>{if(t.absolute!==this.cwd){let h=f(R.dirname(String(t.absolute)));if(h!==this.cwd)return this[yt](h,this.dmode,a=>{if(a){this[O](a,t),i();return}o()})}o()},o=()=>{u.lstat(String(t.absolute),(h,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Ls](t),i();return}if(h||this[Os](t,a))return this[P](null,t,i);if(a.isDirectory()){if(t.type==="Directory"){let l=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,c=d=>this[P](d??null,t,i);return l?u.chmod(String(t.absolute),Number(t.mode),c):c()}if(t.absolute!==this.cwd)return u.rmdir(String(t.absolute),l=>this[P](l??null,t,i))}if(t.absolute===this.cwd)return this[P](null,t,i);mo(String(t.absolute),l=>this[P](l??null,t,i))})};this[Oe]?n():r()}[P](t,e,i){if(t){this[O](t,e),i();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Ts](e,i);case"Link":return this[Ir](e,i);case"SymbolicLink":return this[Ar](e,i);case"Directory":case"GNUDumpDir":return this[xs](e,i)}}[gi](t,e,i,r){u[i](e,String(t.absolute),n=>{n?this[O](n,t):(this[$t](),t.resume()),r()})}};ye=s3=>{try{return[null,s3()]}catch(t){return[t,null]}};xe=class extends Xt{sync=true;[P](t,e){return super[P](t,e,()=>{})}[_s](t){if(!this[Oe]){let n=this[yt](this.cwd,this.dmode);if(n)return this[O](n,t);this[Oe]=true}if(t.absolute!==this.cwd){let n=f(R.dirname(String(t.absolute)));if(n!==this.cwd){let o=this[yt](n,this.dmode);if(o)return this[O](o,t)}}let[e,i]=ye(()=>u.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[Ls](t);if(e||this[Os](t,i))return this[P](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[h]=o?ye(()=>{u.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[P](h,t)}let[n]=ye(()=>u.rmdirSync(String(t.absolute)));this[P](n,t)}let[r]=t.absolute===this.cwd?[]:ye(()=>po(String(t.absolute)));this[P](r,t)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=h=>{let a;try{u.closeSync(n)}catch(l){a=l}(h||a)&&this[O](h||a,t),e()},n;try{n=u.openSync(String(t.absolute),ms(t.size),i)}catch(h){return r(h)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",h=>this[O](h,t)),t.pipe(o)),o.on("data",h=>{try{u.writeSync(n,h,0,h.length)}catch(a){r(a)}}),o.on("end",()=>{let h=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,l=t.mtime;try{u.futimesSync(n,a,l)}catch(c){try{u.utimesSync(String(t.absolute),a,l)}catch{h=c}}}if(this[ge](t)){let a=this[be](t),l=this[_e](t);try{u.fchownSync(n,Number(a),Number(l))}catch(c){try{u.chownSync(String(t.absolute),Number(a),Number(l))}catch{h=h||c}}}r(h)})}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[yt](String(t.absolute),i);if(r){this[O](r,t),e();return}if(t.mtime&&!this.noMtime)try{u.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ge](t))try{u.chownSync(String(t.absolute),Number(this[be](t)),Number(this[_e](t)))}catch{}e(),t.resume()}[yt](t,e){try{return _r(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(i){return i}}[Re](t,e,i,r,n){if(this.preservePaths||i.length===0)return r();let o=e;for(let h of i){o=R.resolve(o,h);let[a,l]=ye(()=>u.lstatSync(o));if(a)return r();if(l.isSymbolicLink())return n(new St(o,R.resolve(e,i.join("/"))))}r()}[gi](t,e,i,r){let n=`${i}Sync`;try{u[n](e,String(t.absolute)),r(),t.resume()}catch(o){return this[O](o,t)}}};Eo=s3=>{let t=new xe(s3),e=s3.file,i=Br.statSync(e),r=s3.maxReadSize||16*1024*1024;new Be(e,{readSize:r,size:i.size}).pipe(t)};wo=(s3,t)=>{let e=new Xt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("close",o),Br.stat(r,(a,l)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l.size});c.on("error",h),c.pipe(e)}})})};So=K(Eo,wo,s3=>new xe(s3),s3=>new Xt(s3),(s3,t)=>{t?.length&&Qi(s3,t)});yo=(s3,t)=>{let e=new kt(s3),i=true,r,n;try{try{r=v.openSync(s3.file,"r+")}catch(a){if(a?.code==="ENOENT")r=v.openSync(s3.file,"w+");else throw a}let o=v.fstatSync(r),h=Buffer.alloc(512);t:for(n=0;n<o.size;n+=512){for(let c=0,d=0;c<512;c+=d){if(d=v.readSync(r,h,c,h.length-c,n+c),n===0&&h[0]===31&&h[1]===139)throw new Error("cannot append to compressed archives");if(!d)break t}let a=new F(h);if(!a.cksumValid)break;let l=512*Math.ceil((a.size||0)/512);if(n+l+512>o.size)break;n+=l,s3.mtimeCache&&a.mtime&&s3.mtimeCache.set(String(a.path),a.mtime)}i=false,Ro(s3,e,n,r,t)}finally{if(i)try{v.closeSync(r)}catch{}}};Ro=(s3,t,e,i,r)=>{let n=new Wt(s3.file,{fd:i,start:e});t.pipe(n),bo(t,r)};go=(s3,t)=>{t=Array.from(t);let e=new wt(s3),i=(n,o,h)=>{let a=(T,D)=>{T?v.close(n,E=>h(T)):h(null,D)},l=0;if(o===0)return a(null,0);let c=0,d=Buffer.alloc(512),y=(T,D)=>{if(T||D===void 0)return a(T);if(c+=D,c<512&&D)return v.read(n,d,c,d.length-c,l+c,y);if(l===0&&d[0]===31&&d[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,l);let E=new F(d);if(!E.cksumValid)return a(null,l);let x=512*Math.ceil((E.size??0)/512);if(l+x+512>o||(l+=x+512,l>=o))return a(null,l);s3.mtimeCache&&E.mtime&&s3.mtimeCache.set(String(E.path),E.mtime),c=0,v.read(n,d,0,512,l,y)};v.read(n,d,0,512,l,y)};return new Promise((n,o)=>{e.on("error",o);let h="r+",a=(l,c)=>{if(l&&l.code==="ENOENT"&&h==="r+")return h="w+",v.open(s3.file,h,a);if(l||!c)return o(l);v.fstat(c,(d,y)=>{if(d)return v.close(c,()=>o(d));i(c,y.size,(T,D)=>{if(T)return o(T);let E=new et(s3.file,{fd:c,start:D});e.pipe(E),E.on("error",o),E.on("close",n),_o(e,t)})})};v.open(s3.file,h,a)})};bo=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:Pr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};_o=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:Pr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e);s3.end()};vt=K(yo,go,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(s3,t)=>{if(!Bs(s3))throw new TypeError("file is required");if(s3.gzip||s3.brotli||s3.zstd||s3.file.endsWith(".br")||s3.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});Oo=K(vt.syncFile,vt.asyncFile,vt.syncNoFile,vt.asyncNoFile,(s3,t=[])=>{vt.validate?.(s3,t),To(s3)});To=s3=>{let t=s3.filter;s3.mtimeCache||(s3.mtimeCache=new Map),s3.filter=t?(e,i)=>t(e,i)&&!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0)):(e,i)=>!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0))}}});var init_text_safe=__esm({"src/text-safe.ts"(){"use strict"}});import fs8 from"fs";import path12 from"path";var PKG_ESCAPED,PKG_ENTRY_RE;var init_dsh_ledger=__esm({"src/dsh-ledger.ts"(){"use strict";init_dsh_channel();PKG_ESCAPED=DSH_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");PKG_ENTRY_RE=new RegExp(`^([ \\t]+)${PKG_ESCAPED}:([ \\t]*(\\S+))?[ \\t]*$`)}});import{readFile,writeFile,mkdir,rename,unlink}from"fs/promises";import path13 from"path";var STAGGER_MIN_DELAY_DEFAULT_MS,STAGGER_MAX_DELAY_DEFAULT_MS,POLICY_STALE_CAP_MS,DELAY_SANITY_CAP_MS,PUBLISHED_VERSIONS_TTL_MS,STAGGER_PRUNE_MS;var init_update_policy=__esm({"src/update-policy.ts"(){"use strict";init_paths();init_logger();init_upstream_proxy();init_duration();STAGGER_MIN_DELAY_DEFAULT_MS=15*6e4;STAGGER_MAX_DELAY_DEFAULT_MS=48*36e5;POLICY_STALE_CAP_MS=30*864e5;DELAY_SANITY_CAP_MS=366*864e5;PUBLISHED_VERSIONS_TTL_MS=10*6e4;STAGGER_PRUNE_MS=7*864e5}});import{readFile as readFile2,writeFile as writeFile2,mkdir as mkdir2,access,constants,rm,cp,unlink as unlink2,lstat,stat,rename as rename2,mkdtemp,readdir}from"fs/promises";import{execFile as execFile3,spawn}from"child_process";import{realpathSync}from"fs";import crypto2 from"crypto";import path14 from"path";import os6 from"os";import{fileURLToPath as fileURLToPath2}from"url";function normalizeRegistryBase(raw){const v2=raw?.trim();if(!v2)return"https://registry.npmjs.org";return v2.replace(/\/+$/,"")}function isVersionNewer(latest,current){const next=parseSemVer(latest);const prev=parseSemVer(current);if(!next||!prev)return false;for(let i=0;i<3;i++){const a=next.parts[i]??0;const b2=prev.parts[i]??0;if(a!==b2)return a>b2}if(!next.pre.length&&prev.pre.length)return true;if(next.pre.length&&!prev.pre.length)return false;for(let i=0;i<Math.max(next.pre.length,prev.pre.length);i++){const a=next.pre[i];const b2=prev.pre[i];if(a===void 0)return false;if(b2===void 0)return true;if(a===b2)continue;const aNumber=/^\d+$/.test(a)?Number(a):void 0;const bNumber=/^\d+$/.test(b2)?Number(b2):void 0;if(aNumber!==void 0&&bNumber!==void 0)return aNumber>bNumber;if(aNumber!==void 0)return false;if(bNumber!==void 0)return true;return a>b2}return false}function parseSemVer(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/);if(!match)return void 0;return{parts:[Number(match[1]),Number(match[2]),Number(match[3])],pre:match[4]?.split(".")??[]}}var REGISTRY_BASE,CHECK_INTERVAL_MS,THROTTLE_FILE,OWNER_THROTTLE_FILE,LOCK_FILE,OWNER_LANE_CHECK_BASE_MS,OWNER_LANE_CHECK_JITTER_MS,LOCK_MAX_AGE_MS,UPDATE_TMP_MAX_AGE_MS,BACKOFF_BASE_MS,BACKOFF_CAP_MS,BACKOFF_STATE_FILE,BACKOFF_PRUNE_MS,LAST_INSTALL_FILE,PI_LANE_HINT;var init_update=__esm({"src/update.ts"(){"use strict";init_index_min();init_text_safe();init_paths();init_logger();init_dsh_channel();init_dsh_ledger();init_pi_channel();init_client_config();init_upstream_proxy();init_knobs();init_update_policy();REGISTRY_BASE=normalizeRegistryBase(updateRegistryBase());CHECK_INTERVAL_MS=updateCheckIntervalMs();THROTTLE_FILE=path14.join(cacheDir(),".update-check");OWNER_THROTTLE_FILE=path14.join(cacheDir(),".owner-update-check");LOCK_FILE=path14.join(cacheDir(),".update-lock");OWNER_LANE_CHECK_BASE_MS=10*60*1e3;OWNER_LANE_CHECK_JITTER_MS=5*60*1e3;LOCK_MAX_AGE_MS=30*60*1e3;UPDATE_TMP_MAX_AGE_MS=60*60*1e3;BACKOFF_BASE_MS=5*60*1e3;BACKOFF_CAP_MS=6*60*60*1e3;BACKOFF_STATE_FILE=path14.join(cacheDir(),".install-backoff.json");BACKOFF_PRUNE_MS=7*24*60*60*1e3;LAST_INSTALL_FILE=path14.join(cacheDir(),".last-install.json");PI_LANE_HINT=`run \`pi update --extension ${PI_NPM_SPEC}\` from a shell where \`pi\` resolves (or point BILI_PI_BIN at pi's executable)`}});import{createRequire}from"module";var require2;var init_driver=__esm({"src/storage/driver.ts"(){"use strict";require2=createRequire(import.meta.url)}});import{createHash as createHash6,randomBytes}from"crypto";import{existsSync as existsSync3,readFileSync as readFileSync4}from"fs";import{promises as fsp}from"fs";import{createRequire as createRequire2}from"module";import path21 from"path";import{gunzipSync}from"zlib";var ENGINE_SPECS,COOLDOWN_MS,PINNED_DIR_PREFIXES;var init_engine_bootstrap=__esm({"src/storage/engine-bootstrap.ts"(){"use strict";init_logger();init_paths();init_driver();init_knobs();init_update();init_upstream_proxy();ENGINE_SPECS=Object.freeze([{version:"13.0.3",sha512Base64:"RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdVVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==",minNodeMajor:22,minNapiVersion:10},{version:"12.9.0",sha512Base64:"wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==",minNodeMajor:20,prebuild:{sha512Base64ByAbi:Object.freeze({"115":Object.freeze({"linux-x64":"fNMKurhPKb0ki9mnZJK9PVazCiRugcdmauo5qGjqQjUGIrdaVWrb4nlLwU7IiyppcfLu8n/qUsQ5CEZ36uoGaw==","linux-arm64":"7q7wZe0+5LLQt2YUkocGb41B9TvEMLKIaNI+CiQUQQ2DFBO1RPr3ixj/Gtb+0noMYHjJrqtqKUMO1xMQXnE0iw==","linuxmusl-x64":"GCriICDKw7K5dNjAVo8xFpSJXcYXXBAK9RDoeuSUv6rB5IVRP96IwxeynTy4Xc21l1507Efz+I2yy6FW5gKQ/w==","linuxmusl-arm64":"2OWfVP1nklnuR8ZfCwozJcLB0ZpOTRHqAkDpsLonEF5uHZMBnOAzGtd5d+nuPU+KaS5czciU0tXZFhsCUw7dbg==","darwin-x64":"tW2Vb19+Bh+PLfcGVnrERhc9Mk50Vi8HciIc0nwIJXlPm21xzKL6uEQHMoyKIAxF+vNXxDsUoJyNRg/TgCXjkA==","darwin-arm64":"H6jehr7s1D/RSTRplCL++hneLTgpqVzgzjrX/NJCsf0OMBSKNGCd9kMYAZJjMlp0IetS39sG5PTG7AcLCTQKeg==","win32-x64":"r+BAeN980mQEdIwDcrNU3iJqzAryuOyfeICFfYHuHVclonTr2L0IlzsaGp2D50KNWUeLQrIhBCFuNoT2+iBDTw==","win32-arm64":"jMSa36VrAiLsWFtnwWX+FEs4JWIjHeduVITY44ZcHsqn7BzPcMljL8LdJ0tVVGssV8x9PuqgIqMD5gFmzcYh9w=="}),"127":Object.freeze({"linux-x64":"jpVKlRCjwmKDIfohRK4Zf/potrKjl2CuvKiWm2SOL1eY7pTRQrGBc1DSEr4OBulYHE6PTl59w7hoAlzNOefG3g==","linux-arm64":"ei++r3DQbhwXsP97PHYENHnNd3jrai5dy11SCDZqzmqEm6mjloT1qwrpglVJmW4TLliYBJ8U9bMG/6Y8nbDBCQ==","linuxmusl-x64":"eFglLYVSmdQo7ehLh30dOF4H9csX92XIn1oKB3TdtTZ+7TTh7cfViO7TQIC4NPt6Ufbl3cos9y6/pU8FNL1dQg==","linuxmusl-arm64":"e72bURjJ4SYseIMY7uW1IkubTqzuKzD6NIVP0InsD8+DJBnRwi8+yIEEcODIK4xsFKSO6tE8TLuvPmetXEk8aA==","darwin-x64":"GxXg+WENfyP9DGnvOSMnPge+kDkEZmU8cF7EFOoFSzAFhEwYOBvFB4VTTqhZ6G4y54I7ufkjgkOxZmafdSOXOw==","darwin-arm64":"V1mPpKKnv3AvfZb/++CSOx49tmUi4fba4vORsD8GTaJVwvKmveJ/uPqXaEVhYQgDkao5VLiWL6gN2wk9rQXfPw==","win32-x64":"7chlb4LP9ETESK6djkGxDq4aDTTByiG1VoUwadJk7JZFhfn2u7vblPCulZaM2C3Ju3jHowc8LBKKQZiH52Uc5g==","win32-arm64":"0mD1nLGHG066cUFdIgMTEJfhbIeOgD52+dE0r8LAALarhU5JD0uyKPvpQH/V3rBjvwTOtaQtYqeEFgRj5NUL/g=="})})}}]);COOLDOWN_MS=6*60*60*1e3;PINNED_DIR_PREFIXES=ENGINE_SPECS.map(s3=>`better-sqlite3-${s3.version}`)}});import{createHash as createHash7}from"crypto";import{mkdirSync as mkdirSync4,writeFileSync as writeFileSync2,appendFileSync as appendFileSync2,readFileSync as readFileSync5,existsSync as existsSync4,unlinkSync as unlinkSync2,statSync as statSync4}from"fs";import{dirname as dirname2,join}from"path";var EXT_VALUE_MAX_BYTES;var init_store=__esm({"src/storage/store.ts"(){"use strict";init_logger();init_driver();init_schema();init_identity();init_runtime_status();init_instance();EXT_VALUE_MAX_BYTES=4*1024*1024}});function createInitialState(){return{blocks:[],messageRefs:{byRaw:{},byRef:{}},tokenSnapshot:{},nudge:{lastPerMessageNudgeTokens:0,lastNudgeShownTokens:0,baselineTokens:0,anchors:{},lastShownByTier:{}},stats:{tokensCompressed:0,compressionCount:0,absorbedTokens:0,storedCount:0,retrievalCount:0},absorbed:[],rules:[],nextRuleId:1,nextBlockId:1,nextRunId:1}}var init_state=__esm({"kernel/src/state.ts"(){"use strict"}});function isResponsesTurnSeparatorId(id){return id.startsWith(RESPONSES_TURN_SEPARATOR_ID_PREFIX)}function scrubTurnSeparatorIds(blocks){let removed=0;for(const block of blocks){for(const key of["directMessageIds","effectiveMessageIds"]){const ids=block[key];if(!ids)continue;const kept=ids.filter(id=>!isResponsesTurnSeparatorId(id));if(kept.length!==ids.length){removed+=ids.length-kept.length;block[key]=kept}}}return removed}var RESPONSES_TURN_SEPARATOR_ID_PREFIX;var init_turn_separator=__esm({"src/turn-separator.ts"(){"use strict";RESPONSES_TURN_SEPARATOR_ID_PREFIX="acp_turn_sep_"}});function mergeState(parsed){const fresh=createInitialState();return{blocks:(()=>{const blocks=parsed.blocks??fresh.blocks;scrubTurnSeparatorIds(blocks);return blocks})(),messageRefs:parsed.messageRefs??fresh.messageRefs,nudge:{...fresh.nudge,...parsed.nudge??{}},stats:{...fresh.stats,...parsed.stats??{}},nextBlockId:parsed.nextBlockId??fresh.nextBlockId,nextRunId:parsed.nextRunId??fresh.nextRunId,tokenSnapshot:parsed.tokenSnapshot??fresh.tokenSnapshot,lastPassIds:parsed.lastPassIds??fresh.lastPassIds,hiddenOrphanRefs:parsed.hiddenOrphanRefs??fresh.hiddenOrphanRefs,deadRefs:parsed.deadRefs??fresh.deadRefs,terminalStreak:parsed.terminalStreak??fresh.terminalStreak,nextRuleId:parsed.nextRuleId??fresh.nextRuleId,absorbed:parsed.absorbed??fresh.absorbed,rules:parsed.rules??fresh.rules,sweptOrphanCallIds:parsed.sweptOrphanCallIds??fresh.sweptOrphanCallIds,pendingOrphanSweepMinRef:parsed.pendingOrphanSweepMinRef??fresh.pendingOrphanSweepMinRef,emergencyTruncateLatch:parsed.emergencyTruncateLatch??fresh.emergencyTruncateLatch,renderDeferredRefs:parsed.renderDeferredRefs??fresh.renderDeferredRefs,viewLatches:parsed.viewLatches??fresh.viewLatches,viewLatchConfigDigest:parsed.viewLatchConfigDigest??fresh.viewLatchConfigDigest}}var COMPRESSION_STATE_FIELDS;var init_state_hydration=__esm({"src/state-hydration.ts"(){"use strict";init_state();init_turn_separator();COMPRESSION_STATE_FIELDS=Object.keys(mergeState(createInitialState()))}});var init_ingest=__esm({"src/storage/ingest.ts"(){"use strict";init_store();init_identity();init_state_hydration()}});var init_backend=__esm({"src/storage/backend.ts"(){"use strict";init_store()}});import{createHash as createHash8}from"crypto";var init_canonical=__esm({"src/storage/canonical.ts"(){"use strict"}});import{renameSync as renameSync2}from"fs";import path22 from"path";var init_shadow=__esm({"src/storage/shadow.ts"(){"use strict";init_logger();init_ingest();init_knobs();init_store();init_backend();init_canonical();init_runtime_status();init_knobs()}});function freshState(){return{requested:null,encryptionBlocked:false,persistDisabled:false,sidecar:null,sidecarOpenError:null,bootstrap:null,integrity:null,secondProcess:null,splitBrain:null,splitBrainAcks:new Map,backup:null}}var state;var init_runtime_status=__esm({"src/storage/runtime-status.ts"(){"use strict";init_engine_bootstrap();init_knobs();init_logger();init_shadow();state=freshState()}});import{AsyncLocalStorage as AsyncLocalStorage4}from"async_hooks";import{readFileSync as readFileSync8}from"fs";import{homedir as homedir2}from"os";import path28 from"path";init_log_mask();init_paths();init_version();import{appendFileSync,mkdirSync}from"fs";import path3 from"path";function logHostEvent(level,origin,msg){try{const file=defaultLogFile();mkdirSync(path3.dirname(file),{recursive:true});const safe=maskUrlsForDiagnostics(maskIpsInText(redactSecretsInText(msg)));appendFileSync(file,`${new Date().toISOString()} [${level}] [v=${VERSION}] ${origin?`${origin} `:""}${safe}
|
|
128
128
|
`)}catch{}}import{createHash as createHash14,randomUUID as randomUUID5}from"crypto";import fs14 from"fs";import net3 from"net";import os8 from"os";import path26 from"path";import{createRequire as createRequire3}from"module";import{pathToFileURL as pathToFileURL2}from"url";import{execFileSync as execFileSync5,spawn as spawn2,spawnSync as spawnSync3}from"child_process";import tls4 from"tls";var import_node_forge=__toESM(require_lib(),1);init_paths();init_logger();import crypto from"crypto";import{execFileSync as execFileSync2}from"child_process";import fs from"fs";import os from"os";import path5 from"path";import tls from"tls";var COMBINED_MAX_AGE_MS=24*60*60*1e3;var PLATFORM_CA_CANDIDATES=process.platform==="darwin"?["/etc/ssl/cert.pem","/private/etc/ssl/cert.pem"]:process.platform==="win32"?[]:["/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem","/etc/ssl/ca-bundle.pem","/etc/ssl/cert.pem"];init_upstream_proxy();init_client_config();init_vertex();import fs3 from"fs";import os3 from"os";import path8 from"path";init_util();init_log_mask();init_knobs();init_mitm_domains();init_private_host();init_instance();var TWIN_ADOPT_EXIT_CODE=3;import net2 from"net";var CONNECT_PROBE_TIMEOUT_MS=2e3;function originHostPort(origin){try{const u2=new URL(origin);if(u2.protocol!=="http:"&&u2.protocol!=="https:")return void 0;const host=u2.hostname.replace(/^\[|\]$/g,"");if(host==="")return void 0;const port=u2.port!==""?Number(u2.port):u2.protocol==="https:"?443:80;return Number.isInteger(port)&&port>0?{host,port}:void 0}catch{return void 0}}function attemptConnect(host,port,timeoutMs){return new Promise(resolve=>{let settled=false;const settle=outcome=>{if(settled)return;settled=true;socket.destroy();resolve(outcome)};const socket=net2.connect({host,port});socket.setTimeout(timeoutMs);socket.once("connect",()=>settle({ok:true}));socket.once("timeout",()=>settle({ok:false,detail:`connect timeout after ${timeoutMs}ms`}));socket.once("error",err=>settle({ok:false,detail:typeof err.code==="string"&&err.code.length>0?err.code:String(err.message??err)}))})}async function tcpConnectable(origin,timeoutMs=CONNECT_PROBE_TIMEOUT_MS){const hp=originHostPort(origin);if(hp===void 0)return false;const outcome=await attemptConnect(hp.host,hp.port,timeoutMs);return outcome.ok}init_main();init_client_config();init_vertex();init_config();init_instance();init_dsh_channel();init_pi_channel();init_update();import fs12 from"fs";import path19 from"path";import os7 from"os";import crypto4 from"crypto";import{execFileSync as execFileSync4,spawnSync as spawnSync2}from"child_process";import{fileURLToPath as fileURLToPath4}from"url";import fs9 from"fs";import path16 from"path";init_client_config();init_instance();import path15 from"path";import{fileURLToPath as fileURLToPath3}from"url";function nativeProxyScriptPath(fromUrl=import.meta.url){return path15.resolve(path15.dirname(fileURLToPath3(fromUrl)),"..","index.js")}function nativeBootstrapGate(env,optOutKey){if(env.BILLION_CONTEXT_PLUGIN==="0")return false;if(env[optOutKey]==="0")return false;if(env.BILLION_CONTEXT_PROXY!==void 0&&env.BILLION_CONTEXT_PROXY.trim().length>0)return false;if(env.BILI_PROVIDER_REWRITES!==void 0)return false;return true}function proxyEnvOrigin(env){const raw=env.BILLION_CONTEXT_PROXY;if(raw===void 0)return void 0;const url=raw.trim();if(url.length===0||!/^https?:\/\//i.test(url))return void 0;try{new URL(url)}catch{return void 0}return url.replace(/\/+$/,"")}function nativeAttachOrigin(env){const raw=env.BILLION_CONTEXT_ATTACH;if(raw===void 0)return void 0;const url=raw.trim();if(url.length===0||!/^https?:\/\//i.test(url))return void 0;try{new URL(url)}catch{return void 0}return url.replace(/\/+$/,"")}function envMillis(env,name2,fallback){const raw=env[name2];if(raw===void 0)return fallback;const n=Number(raw);return Number.isFinite(n)&&n>0?Math.floor(n):fallback}function markNativeHost(env,host){if(env.BILLION_CONTEXT_NATIVE===void 0||env.BILLION_CONTEXT_NATIVE.length===0){env.BILLION_CONTEXT_NATIVE=host}}function singleFlight(fn){let inFlight;return()=>{if(inFlight===void 0){inFlight=fn().finally(()=>{inFlight=void 0})}return inFlight}}function parseToolOutcome(value){return value==="applied"||value==="partial"||value==="refused"||value==="success"||value==="failure"?value:void 0}function parseBlocksCreated(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}function partialOutcomeNote(blocksCreated){const created=blocksCreated!==void 0?`${blocksCreated} block(s) created; `:"";return`[acp-result: PARTIAL \u2014 ${created}some requested range(s) were NOT folded. Retry ONLY the failed range(s) listed above; do not re-fold the ranges that were applied.]`}var MANIFEST_TIMEOUT_MS=5e3;var TOOL_TIMEOUT_MS=6e4;var TOOL_TIMEOUT_OVERHEAD_MARGIN_MS=3e4;var STATUS_TIMEOUT_MS=5e3;var ATTACH_HEALTH_DEADLINE_MS=15e3;var ATTACH_HEALTH_POLL_MS=250;function asciiHeaderValue(value){return/^[\x21-\x7e]{1,256}$/.test(value)?value:void 0}async function fetchJson(url,init,timeoutMs,externalSignal){const ac=new AbortController;if(externalSignal?.aborted)ac.abort();const timer=setTimeout(()=>ac.abort(),timeoutMs);const onExternalAbort=()=>ac.abort();externalSignal?.addEventListener("abort",onExternalAbort,{once:true});try{let res;try{res=await fetch(url,{...init,signal:ac.signal})}catch(err){if(ac.signal.aborted&&!externalSignal?.aborted)throw new Error(`timeout after ${timeoutMs}ms: ${url}`);throw err}const text=await res.text();let json=void 0;try{json=JSON.parse(text)}catch{json=void 0}return{ok:res.ok,status:res.status,json}}finally{clearTimeout(timer);externalSignal?.removeEventListener("abort",onExternalAbort)}}var manifestToolDurations=new Map;function recordManifestToolDuration(proxyBase,json){const caps=json?.capabilities?.externalSummary;const value=caps?.maxToolDurationMs;if(typeof value==="number"&&Number.isFinite(value)&&value>0)manifestToolDurations.set(proxyBase,value)}function effectiveToolTimeoutMs(proxyBase,tool){if(tool!=="compress")return TOOL_TIMEOUT_MS;const advertised=manifestToolDurations.get(proxyBase);if(advertised===void 0)return TOOL_TIMEOUT_MS;return Math.max(TOOL_TIMEOUT_MS,advertised+TOOL_TIMEOUT_OVERHEAD_MARGIN_MS)}async function fetchManifest(proxyBase,format2="anthropic"){const{ok,status,json}=await fetchJson(`${proxyBase}/__bili/plugin/manifest`,void 0,MANIFEST_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")throw new Error(`manifest fetch failed: ${status}`);recordManifestToolDuration(proxyBase,json);if(format2==="openai"){const data2=json;const tools2=[];for(const t of data2.tools?.openai??[]){const name2=t.name??t.function?.name;if(typeof name2!=="string"||name2.length===0)continue;tools2.push({name:name2,description:t.description??t.function?.description,inputSchema:t.parameters??t.function?.parameters??{type:"object",properties:{}}})}if(tools2.length===0)throw new Error("manifest served no openai tools");return tools2}const data=json;const tools=(data.tools?.anthropic??[]).filter(t=>typeof t.name==="string");if(tools.length===0)throw new Error("manifest served no anthropic tools");return tools.map(t=>({name:t.name,description:t.description,inputSchema:t.input_schema??{type:"object",properties:{}}}))}async function reportRuntimeInfo(proxyBase,info){const{ok,status}=await fetchJson(`${proxyBase}/__bili/plugin/runtime-info`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(info)},STATUS_TIMEOUT_MS);if(!ok)throw new Error(`runtime-info report failed (${status})`)}async function reportAttributionHealth(proxyBase,health){const{ok,status}=await fetchJson(`${proxyBase}/__bili/plugin/attribution`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(health)},STATUS_TIMEOUT_MS);if(!ok)throw new Error(`attribution report failed (${status})`)}async function forwardTool(proxyBase,conversationId,tool,args,signal,nativeCaller=false){const body={conversationId,tool,args:args??{}};if(nativeCaller&&conversationId)body.nativeCaller=true;const{ok,status,json}=await fetchJson(`${proxyBase}/__bili/plugin/tool`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)},effectiveToolTimeoutMs(proxyBase,tool),signal);const data=json;if(!ok||!data?.ok){throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error??"unknown error"}`)}const outcome=parseToolOutcome(data.outcome);const blocksCreated=parseBlocksCreated(data.blocksCreated);let text=data.result??"";if(outcome==="partial")text+=`
|