buildx-cli 1.0.11 → 1.0.12
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/README.md +10 -1
- package/dist/README.md +10 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -11,4 +11,4 @@ var require$$0$4=require("events"),require$$1$2=require("child_process"),path=re
|
|
|
11
11
|
* Copyright(c) 2014 Jonathan Ong
|
|
12
12
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
13
13
|
* MIT Licensed
|
|
14
|
-
*/(),extname=path.extname,EXTRACT_TYPE_REGEXP=/^\s*([^;\s]*)(?:;|\s|$)/,TEXT_TYPE_REGEXP=/^text\//i;function charset(type){if(!type||"string"!=typeof type)return!1;var match=EXTRACT_TYPE_REGEXP.exec(type),mime=match&&db[match[1].toLowerCase()];return mime&&mime.charset?mime.charset:!(!match||!TEXT_TYPE_REGEXP.test(match[1]))&&"UTF-8"}exports$1.charset=charset,exports$1.charsets={lookup:charset},exports$1.contentType=function contentType(str){if(!str||"string"!=typeof str)return!1;var mime=-1===str.indexOf("/")?exports$1.lookup(str):str;if(!mime)return!1;if(-1===mime.indexOf("charset")){var charset=exports$1.charset(mime);charset&&(mime+="; charset="+charset.toLowerCase())}return mime},exports$1.extension=function extension(type){if(!type||"string"!=typeof type)return!1;var match=EXTRACT_TYPE_REGEXP.exec(type),exts=match&&exports$1.extensions[match[1].toLowerCase()];if(!exts||!exts.length)return!1;return exts[0]},exports$1.extensions=Object.create(null),exports$1.lookup=function lookup(path){if(!path||"string"!=typeof path)return!1;var extension=extname("x."+path).toLowerCase().substr(1);if(!extension)return!1;return exports$1.types[extension]||!1},exports$1.types=Object.create(null),function populateMaps(extensions,types){var preference=["nginx","apache",void 0,"iana"];Object.keys(db).forEach(function forEachMimeType(type){var mime=db[type],exts=mime.extensions;if(exts&&exts.length){extensions[type]=exts;for(var i=0;i<exts.length;i++){var extension=exts[i];if(types[extension]){var from=preference.indexOf(db[types[extension]].source),to=preference.indexOf(mime.source);if("application/octet-stream"!==types[extension]&&(from>to||from===to&&"application/"===types[extension].substr(0,12)))continue}types[extension]=type}}})}(exports$1.extensions,exports$1.types)}(mimeTypes)),mimeTypes}function requireAsync$1(){if(hasRequiredAsync$1)return async_1;hasRequiredAsync$1=1;var defer=function requireDefer(){return hasRequiredDefer?defer_1:(hasRequiredDefer=1,defer_1=function defer(fn){var nextTick="function"==typeof setImmediate?setImmediate:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:null;nextTick?nextTick(fn):setTimeout(fn,0)})}();return async_1=function async(callback){var isAsync=!1;return defer(function(){isAsync=!0}),function async_callback(err,result){isAsync?callback(err,result):defer(function nextTick_callback(){callback(err,result)})}}}function requireAbort(){if(hasRequiredAbort)return abort_1;function clean(key){"function"==typeof this.jobs[key]&&this.jobs[key]()}return hasRequiredAbort=1,abort_1=function abort(state){Object.keys(state.jobs).forEach(clean.bind(state)),state.jobs={}},abort_1}function requireIterate(){if(hasRequiredIterate)return iterate_1;hasRequiredIterate=1;var async=requireAsync$1(),abort=requireAbort();return iterate_1=function iterate(list,iterator,state,callback){var key=state.keyedList?state.keyedList[state.index]:state.index;state.jobs[key]=function runJob(iterator,key,item,callback){var aborter;aborter=2==iterator.length?iterator(item,async(callback)):iterator(item,key,async(callback));return aborter}(iterator,key,list[key],function(error,output){key in state.jobs&&(delete state.jobs[key],error?abort(state):state.results[key]=output,callback(error,state.results))})},iterate_1}function requireState(){if(hasRequiredState)return state_1;return hasRequiredState=1,state_1=function state(list,sortMethod){var isNamedList=!Array.isArray(list),initState={index:0,keyedList:isNamedList||sortMethod?Object.keys(list):null,jobs:{},results:isNamedList?{}:[],size:isNamedList?Object.keys(list).length:list.length};sortMethod&&initState.keyedList.sort(isNamedList?sortMethod:function(a,b){return sortMethod(list[a],list[b])});return initState}}function requireTerminator(){if(hasRequiredTerminator)return terminator_1;hasRequiredTerminator=1;var abort=requireAbort(),async=requireAsync$1();return terminator_1=function terminator(callback){if(!Object.keys(this.jobs).length)return;this.index=this.size,abort(this),async(callback)(null,this.results)}}function requireParallel(){if(hasRequiredParallel)return parallel_1;hasRequiredParallel=1;var iterate=requireIterate(),initState=requireState(),terminator=requireTerminator();return parallel_1=function parallel(list,iterator,callback){var state=initState(list);for(;state.index<(state.keyedList||list).length;)iterate(list,iterator,state,function(error,result){error?callback(error,result):0!==Object.keys(state.jobs).length||callback(null,state.results)}),state.index++;return terminator.bind(state,callback)},parallel_1}var hasRequiredSerialOrdered,serial_1,hasRequiredSerial,asynckit,hasRequiredAsynckit,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,shams$1,hasRequiredShams$1,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,shams,hasRequiredShams,esSetTostringtag,hasRequiredEsSetTostringtag,populate,hasRequiredPopulate,form_data,hasRequiredForm_data,serialOrdered={exports:{}};function requireSerialOrdered(){if(hasRequiredSerialOrdered)return serialOrdered.exports;hasRequiredSerialOrdered=1;var iterate=requireIterate(),initState=requireState(),terminator=requireTerminator();function ascending(a,b){return a<b?-1:a>b?1:0}return serialOrdered.exports=function serialOrdered$1(list,iterator,sortMethod,callback){var state=initState(list,sortMethod);return iterate(list,iterator,state,function iteratorHandler(error,result){error?callback(error,result):(state.index++,state.index<(state.keyedList||list).length?iterate(list,iterator,state,iteratorHandler):callback(null,state.results))}),terminator.bind(state,callback)},serialOrdered.exports.ascending=ascending,serialOrdered.exports.descending=function descending(a,b){return-1*ascending(a,b)},serialOrdered.exports}function requireSerial(){if(hasRequiredSerial)return serial_1;hasRequiredSerial=1;var serialOrdered=requireSerialOrdered();return serial_1=function serial(list,iterator,callback){return serialOrdered(list,iterator,null,callback)},serial_1}function requireAsynckit(){return hasRequiredAsynckit?asynckit:(hasRequiredAsynckit=1,asynckit={parallel:requireParallel(),serial:requireSerial(),serialOrdered:requireSerialOrdered()})}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var $isNaN=function require_isNaN(){return hasRequired_isNaN?_isNaN:(hasRequired_isNaN=1,_isNaN=Number.isNaN||function isNaN(a){return a!=a})}();return sign=function sign(number){return $isNaN(number)||0===number?number:number<0?-1:1}}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var $gOPD=function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}();if($gOPD)try{$gOPD([],"length")}catch(e){$gOPD=null}return gopd=$gOPD}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var $defineProperty=Object.defineProperty||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}return esDefineProperty=$defineProperty}function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;for(var _ in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;var syms=Object.getOwnPropertySymbols(obj);if(1!==syms.length||syms[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(42!==descriptor.value||!0!==descriptor.enumerable)return!1}return!0})}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=requireShams$1();return hasSymbols=function hasNativeSymbols(){return"function"==typeof origSymbol&&("function"==typeof Symbol&&("symbol"==typeof origSymbol("foo")&&("symbol"==typeof Symbol("bar")&&hasSymbolSham())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var toStr=Object.prototype.toString,max=Math.max,concatty=function concatty(a,b){for(var arr=[],i=0;i<a.length;i+=1)arr[i]=a[i];for(var j=0;j<b.length;j+=1)arr[j+a.length]=b[j];return arr};return implementation=function bind(that){var target=this;if("function"!=typeof target||"[object Function]"!==toStr.apply(target))throw new TypeError("Function.prototype.bind called on incompatible "+target);for(var bound,args=function slicy(arrLike,offset){for(var arr=[],i=offset,j=0;i<arrLike.length;i+=1,j+=1)arr[j]=arrLike[i];return arr}(arguments,1),boundLength=max(0,target.length-args.length),boundArgs=[],i=0;i<boundLength;i++)boundArgs[i]="$"+i;if(bound=Function("binder","return function ("+function(arr,joiner){for(var str="",i=0;i<arr.length;i+=1)str+=arr[i],i+1<arr.length&&(str+=joiner);return str}(boundArgs,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof bound){var result=target.apply(this,concatty(args,arguments));return Object(result)===result?result:this}return target.apply(that,concatty(args,arguments))}),target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null}return bound},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var implementation=requireImplementation();return functionBind=Function.prototype.bind||implementation}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var bind=requireFunctionBind(),$apply=requireFunctionApply(),$call=requireFunctionCall(),$reflectApply=function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}();return actualApply=$reflectApply||bind.call($call,$apply)}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var hasProtoAccessor,callBind=function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var bind=requireFunctionBind(),$TypeError=requireType(),$call=requireFunctionCall(),$actualApply=requireActualApply();return callBindApplyHelpers=function callBindBasic(args){if(args.length<1||"function"!=typeof args[0])throw new $TypeError("a function is required");return $actualApply(bind,$call,args)},callBindApplyHelpers}(),gOPD=requireGopd();try{hasProtoAccessor=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,"__proto__"),$Object=Object,$getPrototypeOf=$Object.getPrototypeOf;return get=desc&&"function"==typeof desc.get?callBind([desc.get]):"function"==typeof $getPrototypeOf&&function getDunder(value){return $getPrototypeOf(null==value?value:$Object(value))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var reflectGetProto=requireReflect_getPrototypeOf(),originalGetProto=requireObject_getPrototypeOf(),getDunderProto=requireGet();return getProto=reflectGetProto?function getProto(O){return reflectGetProto(O)}:originalGetProto?function getProto(O){if(!O||"object"!=typeof O&&"function"!=typeof O)throw new TypeError("getProto: not an object");return originalGetProto(O)}:getDunderProto?function getProto(O){return getDunderProto(O)}:null}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var call=Function.prototype.call,$hasOwn=Object.prototype.hasOwnProperty,bind=requireFunctionBind();return hasown=bind.call(call,$hasOwn)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;hasRequiredGetIntrinsic=1;var $Object=requireEsObjectAtoms(),$Error=requireEsErrors(),$EvalError=require_eval(),$RangeError=requireRange(),$ReferenceError=requireRef(),$SyntaxError=requireSyntax(),$TypeError=requireType(),$URIError=requireUri(),abs=requireAbs(),floor=requireFloor(),max=requireMax(),min=requireMin(),pow=requirePow(),round=requireRound(),sign=requireSign(),$Function=Function,getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=requireGopd(),$defineProperty=requireEsDefineProperty(),throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=requireHasSymbols()(),getProto=requireGetProto(),$ObjectGPO=requireObject_getPrototypeOf(),$ReflectGPO=requireReflect_getPrototypeOf(),$apply=requireFunctionApply(),$call=requireFunctionCall(),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):void 0,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?void 0:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?void 0:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float16Array%":"undefined"==typeof Float16Array?void 0:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":$Object,"%Object.getOwnPropertyDescriptor%":$gOPD,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):void 0,"%Symbol%":hasSymbols?Symbol:void 0,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet,"%Function.prototype.call%":$call,"%Function.prototype.apply%":$apply,"%Object.defineProperty%":$defineProperty,"%Object.getPrototypeOf%":$ObjectGPO,"%Math.abs%":abs,"%Math.floor%":floor,"%Math.max%":max,"%Math.min%":min,"%Math.pow%":pow,"%Math.round%":round,"%Math.sign%":sign,"%Reflect.getPrototypeOf%":$ReflectGPO};if(getProto)try{null.error}catch(e){var errorProto=getProto(getProto(e));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(name){var value;if("%AsyncFunction%"===name)value=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===name)value=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===name)value=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===name){var fn=doEval("%AsyncGeneratorFunction%");fn&&(value=fn.prototype)}else if("%AsyncIteratorPrototype%"===name){var gen=doEval("%AsyncGenerator%");gen&&getProto&&(value=getProto(gen.prototype))}return INTRINSICS[name]=value,value},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=requireFunctionBind(),hasOwn=requireHasown(),$concat=bind.call($call,Array.prototype.concat),$spliceApply=bind.call($apply,Array.prototype.splice),$replace=bind.call($call,String.prototype.replace),$strSlice=bind.call($call,String.prototype.slice),$exec=bind.call($call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var alias,intrinsicName=name;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(intrinsicName="%"+(alias=LEGACY_ALIASES[intrinsicName])[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval&&(value=doEval(intrinsicName)),void 0===value&&!allowMissing)throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!");return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};return getIntrinsic=function GetIntrinsic(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof allowMissing)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,name))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var parts=function stringToPath(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match}),result}(name),intrinsicBaseName=parts.length>0?parts[0]:"",intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing),intrinsicRealName=intrinsic.name,value=intrinsic.value,skipFurtherCaching=!1,alias=intrinsic.alias;alias&&(intrinsicBaseName=alias[0],$spliceApply(parts,$concat([0,1],alias)));for(var i=1,isOwn=!0;i<parts.length;i+=1){var part=parts[i],first=$strSlice(part,0,1),last=$strSlice(part,-1);if(('"'===first||"'"===first||"`"===first||'"'===last||"'"===last||"`"===last)&&first!==last)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==part&&isOwn||(skipFurtherCaching=!0),hasOwn(INTRINSICS,intrinsicRealName="%"+(intrinsicBaseName+="."+part)+"%"))value=INTRINSICS[intrinsicRealName];else if(null!=value){if(!(part in value)){if(!allowMissing)throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");return}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);value=(isOwn=!!desc)&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[part]}else isOwn=hasOwn(value,part),value=value[part];isOwn&&!skipFurtherCaching&&(INTRINSICS[intrinsicRealName]=value)}}return value},getIntrinsic}function requireEsSetTostringtag(){if(hasRequiredEsSetTostringtag)return esSetTostringtag;hasRequiredEsSetTostringtag=1;var $defineProperty=requireGetIntrinsic()("%Object.defineProperty%",!0),hasToStringTag=function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var hasSymbols=requireShams$1();return shams=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}}()(),hasOwn=requireHasown(),$TypeError=requireType(),toStringTag=hasToStringTag?Symbol.toStringTag:null;return esSetTostringtag=function setToStringTag(object,value){var overrideIfSet=arguments.length>2&&!!arguments[2]&&arguments[2].force,nonConfigurable=arguments.length>2&&!!arguments[2]&&arguments[2].nonConfigurable;if(void 0!==overrideIfSet&&"boolean"!=typeof overrideIfSet||void 0!==nonConfigurable&&"boolean"!=typeof nonConfigurable)throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");!toStringTag||!overrideIfSet&&hasOwn(object,toStringTag)||($defineProperty?$defineProperty(object,toStringTag,{configurable:!nonConfigurable,enumerable:!1,value:value,writable:!1}):object[toStringTag]=value)},esSetTostringtag}function requirePopulate(){return hasRequiredPopulate||(hasRequiredPopulate=1,populate=function(dst,src){return Object.keys(src).forEach(function(prop){dst[prop]=dst[prop]||src[prop]}),dst}),populate}var form_dataExports=function requireForm_data(){if(hasRequiredForm_data)return form_data;hasRequiredForm_data=1;var CombinedStream=requireCombined_stream(),util=require$$1$3,path$1=path,http=require$$3$3,https=require$$4$3,parseUrl=require$$0$a.parse,fs=fs$2,Stream=stream$1.Stream,crypto=crypto$1,mime=requireMimeTypes(),asynckit=requireAsynckit(),setToStringTag=requireEsSetTostringtag(),hasOwn=requireHasown(),populate=requirePopulate();function FormData(options){if(!(this instanceof FormData))return new FormData(options);for(var option in this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],CombinedStream.call(this),options=options||{})this[option]=options[option]}return util.inherits(FormData,CombinedStream),FormData.LINE_BREAK="\r\n",FormData.DEFAULT_CONTENT_TYPE="application/octet-stream",FormData.prototype.append=function(field,value,options){"string"==typeof(options=options||{})&&(options={filename:options});var append=CombinedStream.prototype.append.bind(this);if("number"!=typeof value&&null!=value||(value=String(value)),Array.isArray(value))this._error(new Error("Arrays are not supported."));else{var header=this._multiPartHeader(field,value,options),footer=this._multiPartFooter();append(header),append(value),append(footer),this._trackLength(header,value,options)}},FormData.prototype._trackLength=function(header,value,options){var valueLength=0;null!=options.knownLength?valueLength+=Number(options.knownLength):Buffer.isBuffer(value)?valueLength=value.length:"string"==typeof value&&(valueLength=Buffer.byteLength(value)),this._valueLength+=valueLength,this._overheadLength+=Buffer.byteLength(header)+FormData.LINE_BREAK.length,value&&(value.path||value.readable&&hasOwn(value,"httpVersion")||value instanceof Stream)&&(options.knownLength||this._valuesToMeasure.push(value))},FormData.prototype._lengthRetriever=function(value,callback){hasOwn(value,"fd")?null!=value.end&&value.end!=1/0&&null!=value.start?callback(null,value.end+1-(value.start?value.start:0)):fs.stat(value.path,function(err,stat){if(err)callback(err);else{var fileSize=stat.size-(value.start?value.start:0);callback(null,fileSize)}}):hasOwn(value,"httpVersion")?callback(null,Number(value.headers["content-length"])):hasOwn(value,"httpModule")?(value.on("response",function(response){value.pause(),callback(null,Number(response.headers["content-length"]))}),value.resume()):callback("Unknown stream")},FormData.prototype._multiPartHeader=function(field,value,options){if("string"==typeof options.header)return options.header;var header,contentDisposition=this._getContentDisposition(value,options),contentType=this._getContentType(value,options),contents="",headers={"Content-Disposition":["form-data",'name="'+field+'"'].concat(contentDisposition||[]),"Content-Type":[].concat(contentType||[])};for(var prop in"object"==typeof options.header&&populate(headers,options.header),headers)if(hasOwn(headers,prop)){if(null==(header=headers[prop]))continue;Array.isArray(header)||(header=[header]),header.length&&(contents+=prop+": "+header.join("; ")+FormData.LINE_BREAK)}return"--"+this.getBoundary()+FormData.LINE_BREAK+contents+FormData.LINE_BREAK},FormData.prototype._getContentDisposition=function(value,options){var filename;if("string"==typeof options.filepath?filename=path$1.normalize(options.filepath).replace(/\\/g,"/"):options.filename||value&&(value.name||value.path)?filename=path$1.basename(options.filename||value&&(value.name||value.path)):value&&value.readable&&hasOwn(value,"httpVersion")&&(filename=path$1.basename(value.client._httpMessage.path||"")),filename)return'filename="'+filename+'"'},FormData.prototype._getContentType=function(value,options){var contentType=options.contentType;return!contentType&&value&&value.name&&(contentType=mime.lookup(value.name)),!contentType&&value&&value.path&&(contentType=mime.lookup(value.path)),!contentType&&value&&value.readable&&hasOwn(value,"httpVersion")&&(contentType=value.headers["content-type"]),contentType||!options.filepath&&!options.filename||(contentType=mime.lookup(options.filepath||options.filename)),!contentType&&value&&"object"==typeof value&&(contentType=FormData.DEFAULT_CONTENT_TYPE),contentType},FormData.prototype._multiPartFooter=function(){return function(next){var footer=FormData.LINE_BREAK;0===this._streams.length&&(footer+=this._lastBoundary()),next(footer)}.bind(this)},FormData.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+FormData.LINE_BREAK},FormData.prototype.getHeaders=function(userHeaders){var header,formHeaders={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(header in userHeaders)hasOwn(userHeaders,header)&&(formHeaders[header.toLowerCase()]=userHeaders[header]);return formHeaders},FormData.prototype.setBoundary=function(boundary){if("string"!=typeof boundary)throw new TypeError("FormData boundary must be a string");this._boundary=boundary},FormData.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary},FormData.prototype.getBuffer=function(){for(var dataBuffer=new Buffer.alloc(0),boundary=this.getBoundary(),i=0,len=this._streams.length;i<len;i++)"function"!=typeof this._streams[i]&&(dataBuffer=Buffer.isBuffer(this._streams[i])?Buffer.concat([dataBuffer,this._streams[i]]):Buffer.concat([dataBuffer,Buffer.from(this._streams[i])]),"string"==typeof this._streams[i]&&this._streams[i].substring(2,boundary.length+2)===boundary||(dataBuffer=Buffer.concat([dataBuffer,Buffer.from(FormData.LINE_BREAK)])));return Buffer.concat([dataBuffer,Buffer.from(this._lastBoundary())])},FormData.prototype._generateBoundary=function(){this._boundary="--------------------------"+crypto.randomBytes(12).toString("hex")},FormData.prototype.getLengthSync=function(){var knownLength=this._overheadLength+this._valueLength;return this._streams.length&&(knownLength+=this._lastBoundary().length),this.hasKnownLength()||this._error(new Error("Cannot calculate proper length in synchronous way.")),knownLength},FormData.prototype.hasKnownLength=function(){var hasKnownLength=!0;return this._valuesToMeasure.length&&(hasKnownLength=!1),hasKnownLength},FormData.prototype.getLength=function(cb){var knownLength=this._overheadLength+this._valueLength;this._streams.length&&(knownLength+=this._lastBoundary().length),this._valuesToMeasure.length?asynckit.parallel(this._valuesToMeasure,this._lengthRetriever,function(err,values){err?cb(err):(values.forEach(function(length){knownLength+=length}),cb(null,knownLength))}):process.nextTick(cb.bind(this,null,knownLength))},FormData.prototype.submit=function(params,cb){var request,options,defaults={method:"post"};return"string"==typeof params?(params=parseUrl(params),options=populate({port:params.port,path:params.pathname,host:params.hostname,protocol:params.protocol},defaults)):(options=populate(params,defaults)).port||(options.port="https:"===options.protocol?443:80),options.headers=this.getHeaders(params.headers),request="https:"===options.protocol?https.request(options):http.request(options),this.getLength(function(err,length){if(err&&"Unknown stream"!==err)this._error(err);else if(length&&request.setHeader("Content-Length",length),this.pipe(request),cb){var onResponse,callback=function(error,responce){return request.removeListener("error",callback),request.removeListener("response",onResponse),cb.call(this,error,responce)};onResponse=callback.bind(this,null),request.on("error",callback),request.on("response",onResponse)}}.bind(this)),request},FormData.prototype._error=function(err){this.error||(this.error=err,this.pause(),this.emit("error",err))},FormData.prototype.toString=function(){return"[object FormData]"},setToStringTag(FormData.prototype,"FormData"),form_data=FormData}(),FormData$1=getDefaultExportFromCjs(form_dataExports);function isVisitable(thing){return utils$3.isPlainObject(thing)||utils$3.isArray(thing)}function removeBrackets(key){return utils$3.endsWith(key,"[]")?key.slice(0,-2):key}function renderKey(path,key,dots){return path?path.concat(key).map(function each(token,i){return token=removeBrackets(token),!dots&&i?"["+token+"]":token}).join(dots?".":""):key}const predicates=utils$3.toFlatObject(utils$3,{},null,function filter(prop){return/^is[A-Z]/.test(prop)});function toFormData$1(obj,formData,options){if(!utils$3.isObject(obj))throw new TypeError("target must be an object");formData=formData||new(FormData$1||FormData),options=utils$3.toFlatObject(options,{metaTokens:!0,dots:!1,indexes:!1},!1,function defined(option,source){return!utils$3.isUndefined(source[option])});const metaTokens=options.metaTokens,visitor=options.visitor||defaultVisitor,dots=options.dots,indexes=options.indexes,useBlob=(options.Blob||"undefined"!=typeof Blob&&Blob)&&utils$3.isSpecCompliantForm(formData);if(!utils$3.isFunction(visitor))throw new TypeError("visitor must be a function");function convertValue(value){if(null===value)return"";if(utils$3.isDate(value))return value.toISOString();if(utils$3.isBoolean(value))return value.toString();if(!useBlob&&utils$3.isBlob(value))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$3.isArrayBuffer(value)||utils$3.isTypedArray(value)?useBlob&&"function"==typeof Blob?new Blob([value]):Buffer.from(value):value}function defaultVisitor(value,key,path){let arr=value;if(utils$3.isReactNative(formData)&&utils$3.isReactNativeBlob(value))return formData.append(renderKey(path,key,dots),convertValue(value)),!1;if(value&&!path&&"object"==typeof value)if(utils$3.endsWith(key,"{}"))key=metaTokens?key:key.slice(0,-2),value=JSON.stringify(value);else if(utils$3.isArray(value)&&function isFlatArray(arr){return utils$3.isArray(arr)&&!arr.some(isVisitable)}(value)||(utils$3.isFileList(value)||utils$3.endsWith(key,"[]"))&&(arr=utils$3.toArray(value)))return key=removeBrackets(key),arr.forEach(function each(el,index){!utils$3.isUndefined(el)&&null!==el&&formData.append(!0===indexes?renderKey([key],index,dots):null===indexes?key:key+"[]",convertValue(el))}),!1;return!!isVisitable(value)||(formData.append(renderKey(path,key,dots),convertValue(value)),!1)}const stack=[],exposedHelpers=Object.assign(predicates,{defaultVisitor:defaultVisitor,convertValue:convertValue,isVisitable:isVisitable});if(!utils$3.isObject(obj))throw new TypeError("data must be an object");return function build(value,path){if(!utils$3.isUndefined(value)){if(-1!==stack.indexOf(value))throw Error("Circular reference detected in "+path.join("."));stack.push(value),utils$3.forEach(value,function each(el,key){!0===(!(utils$3.isUndefined(el)||null===el)&&visitor.call(formData,el,utils$3.isString(key)?key.trim():key,path,exposedHelpers))&&build(el,path?path.concat(key):[key])}),stack.pop()}}(obj),formData}function encode$1(str){const charMap={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g,function replacer(match){return charMap[match]})}function AxiosURLSearchParams(params,options){this._pairs=[],params&&toFormData$1(params,this,options)}const prototype=AxiosURLSearchParams.prototype;function encode(val){return encodeURIComponent(val).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(url,params,options){if(!params)return url;const _encode=options&&options.encode||encode,_options=utils$3.isFunction(options)?{serialize:options}:options,serializeFn=_options&&_options.serialize;let serializedParams;if(serializedParams=serializeFn?serializeFn(params,_options):utils$3.isURLSearchParams(params)?params.toString():new AxiosURLSearchParams(params,_options).toString(_encode),serializedParams){const hashmarkIndex=url.indexOf("#");-1!==hashmarkIndex&&(url=url.slice(0,hashmarkIndex)),url+=(-1===url.indexOf("?")?"?":"&")+serializedParams}return url}prototype.append=function append(name,value){this._pairs.push([name,value])},prototype.toString=function toString(encoder){const _encode=encoder?function(value){return encoder.call(this,value,encode$1)}:encode$1;return this._pairs.map(function each(pair){return _encode(pair[0])+"="+_encode(pair[1])},"").join("&")};class InterceptorManager{constructor(){this.handlers=[]}use(fulfilled,rejected,options){return this.handlers.push({fulfilled:fulfilled,rejected:rejected,synchronous:!!options&&options.synchronous,runWhen:options?options.runWhen:null}),this.handlers.length-1}eject(id){this.handlers[id]&&(this.handlers[id]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(fn){utils$3.forEach(this.handlers,function forEachHandler(h){null!==h&&fn(h)})}}var transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},URLSearchParams=require$$0$a.URLSearchParams;const ALPHA="abcdefghijklmnopqrstuvwxyz",ALPHABET={DIGIT:"0123456789",ALPHA:ALPHA,ALPHA_DIGIT:ALPHA+ALPHA.toUpperCase()+"0123456789"};var platform$1={isNode:!0,classes:{URLSearchParams:URLSearchParams,FormData:FormData$1,Blob:"undefined"!=typeof Blob&&Blob||null},ALPHABET:ALPHABET,generateString:(size=16,alphabet=ALPHABET.ALPHA_DIGIT)=>{let str="";const{length:length}=alphabet,randomValues=new Uint32Array(size);crypto$1.randomFillSync(randomValues);for(let i=0;i<size;i++)str+=alphabet[randomValues[i]%length];return str},protocols:["http","https","file","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var platform={...Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),...platform$1};function formDataToJSON(formData){function buildPath(path,value,target,index){let name=path[index++];if("__proto__"===name)return!0;const isNumericKey=Number.isFinite(+name),isLast=index>=path.length;if(name=!name&&utils$3.isArray(target)?target.length:name,isLast)return utils$3.hasOwnProp(target,name)?target[name]=[target[name],value]:target[name]=value,!isNumericKey;target[name]&&utils$3.isObject(target[name])||(target[name]=[]);return buildPath(path,value,target[name],index)&&utils$3.isArray(target[name])&&(target[name]=function arrayToObject(arr){const obj={},keys=Object.keys(arr);let i;const len=keys.length;let key;for(i=0;i<len;i++)key=keys[i],obj[key]=arr[key];return obj}(target[name])),!isNumericKey}if(utils$3.isFormData(formData)&&utils$3.isFunction(formData.entries)){const obj={};return utils$3.forEachEntry(formData,(name,value)=>{buildPath(function parsePropPath(name){return utils$3.matchAll(/\w+|\[(\w*)]/g,name).map(match=>"[]"===match[0]?"":match[1]||match[0])}(name),value,obj,0)}),obj}return null}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function transformRequest(data,headers){const contentType=headers.getContentType()||"",hasJSONContentType=contentType.indexOf("application/json")>-1,isObjectPayload=utils$3.isObject(data);isObjectPayload&&utils$3.isHTMLForm(data)&&(data=new FormData(data));if(utils$3.isFormData(data))return hasJSONContentType?JSON.stringify(formDataToJSON(data)):data;if(utils$3.isArrayBuffer(data)||utils$3.isBuffer(data)||utils$3.isStream(data)||utils$3.isFile(data)||utils$3.isBlob(data)||utils$3.isReadableStream(data))return data;if(utils$3.isArrayBufferView(data))return data.buffer;if(utils$3.isURLSearchParams(data))return headers.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),data.toString();let isFileList;if(isObjectPayload){if(contentType.indexOf("application/x-www-form-urlencoded")>-1)return function toURLEncodedForm(data,options){return toFormData$1(data,new platform.classes.URLSearchParams,{visitor:function(value,key,path,helpers){return platform.isNode&&utils$3.isBuffer(value)?(this.append(key,value.toString("base64")),!1):helpers.defaultVisitor.apply(this,arguments)},...options})}(data,this.formSerializer).toString();if((isFileList=utils$3.isFileList(data))||contentType.indexOf("multipart/form-data")>-1){const _FormData=this.env&&this.env.FormData;return toFormData$1(isFileList?{"files[]":data}:data,_FormData&&new _FormData,this.formSerializer)}}return isObjectPayload||hasJSONContentType?(headers.setContentType("application/json",!1),function stringifySafely(rawValue,parser,encoder){if(utils$3.isString(rawValue))try{return(parser||JSON.parse)(rawValue),utils$3.trim(rawValue)}catch(e){if("SyntaxError"!==e.name)throw e}return(encoder||JSON.stringify)(rawValue)}(data)):data}],transformResponse:[function transformResponse(data){const transitional=this.transitional||defaults.transitional,forcedJSONParsing=transitional&&transitional.forcedJSONParsing,JSONRequested="json"===this.responseType;if(utils$3.isResponse(data)||utils$3.isReadableStream(data))return data;if(data&&utils$3.isString(data)&&(forcedJSONParsing&&!this.responseType||JSONRequested)){const strictJSONParsing=!(transitional&&transitional.silentJSONParsing)&&JSONRequested;try{return JSON.parse(data,this.parseReviver)}catch(e){if(strictJSONParsing){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function validateStatus(status){return status>=200&&status<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$3.forEach(["delete","get","head","post","put","patch"],method=>{defaults.headers[method]={}});const ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const $internals=Symbol("internals");function normalizeHeader(header){return header&&String(header).trim().toLowerCase()}function normalizeValue(value){return!1===value||null==value?value:utils$3.isArray(value)?value.map(normalizeValue):String(value)}function matchHeaderValue(context,value,header,filter,isHeaderNameFilter){return utils$3.isFunction(filter)?filter.call(this,value,header):(isHeaderNameFilter&&(value=header),utils$3.isString(value)?utils$3.isString(filter)?-1!==value.indexOf(filter):utils$3.isRegExp(filter)?filter.test(value):void 0:void 0)}let AxiosHeaders$1=class AxiosHeaders{constructor(headers){headers&&this.set(headers)}set(header,valueOrRewrite,rewrite){const self=this;function setHeader(_value,_header,_rewrite){const lHeader=normalizeHeader(_header);if(!lHeader)throw new Error("header name must be a non-empty string");const key=utils$3.findKey(self,lHeader);(!key||void 0===self[key]||!0===_rewrite||void 0===_rewrite&&!1!==self[key])&&(self[key||_header]=normalizeValue(_value))}const setHeaders=(headers,_rewrite)=>utils$3.forEach(headers,(_value,_header)=>setHeader(_value,_header,_rewrite));if(utils$3.isPlainObject(header)||header instanceof this.constructor)setHeaders(header,valueOrRewrite);else if(utils$3.isString(header)&&(header=header.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(header.trim()))setHeaders((rawHeaders=>{const parsed={};let key,val,i;return rawHeaders&&rawHeaders.split("\n").forEach(function parser(line){i=line.indexOf(":"),key=line.substring(0,i).trim().toLowerCase(),val=line.substring(i+1).trim(),!key||parsed[key]&&ignoreDuplicateOf[key]||("set-cookie"===key?parsed[key]?parsed[key].push(val):parsed[key]=[val]:parsed[key]=parsed[key]?parsed[key]+", "+val:val)}),parsed})(header),valueOrRewrite);else if(utils$3.isObject(header)&&utils$3.isIterable(header)){let dest,key,obj={};for(const entry of header){if(!utils$3.isArray(entry))throw TypeError("Object iterator must return a key-value pair");obj[key=entry[0]]=(dest=obj[key])?utils$3.isArray(dest)?[...dest,entry[1]]:[dest,entry[1]]:entry[1]}setHeaders(obj,valueOrRewrite)}else null!=header&&setHeader(valueOrRewrite,header,rewrite);return this}get(header,parser){if(header=normalizeHeader(header)){const key=utils$3.findKey(this,header);if(key){const value=this[key];if(!parser)return value;if(!0===parser)return function parseTokens(str){const tokens=Object.create(null),tokensRE=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let match;for(;match=tokensRE.exec(str);)tokens[match[1]]=match[2];return tokens}(value);if(utils$3.isFunction(parser))return parser.call(this,value,key);if(utils$3.isRegExp(parser))return parser.exec(value);throw new TypeError("parser must be boolean|regexp|function")}}}has(header,matcher){if(header=normalizeHeader(header)){const key=utils$3.findKey(this,header);return!(!key||void 0===this[key]||matcher&&!matchHeaderValue(0,this[key],key,matcher))}return!1}delete(header,matcher){const self=this;let deleted=!1;function deleteHeader(_header){if(_header=normalizeHeader(_header)){const key=utils$3.findKey(self,_header);!key||matcher&&!matchHeaderValue(0,self[key],key,matcher)||(delete self[key],deleted=!0)}}return utils$3.isArray(header)?header.forEach(deleteHeader):deleteHeader(header),deleted}clear(matcher){const keys=Object.keys(this);let i=keys.length,deleted=!1;for(;i--;){const key=keys[i];matcher&&!matchHeaderValue(0,this[key],key,matcher,!0)||(delete this[key],deleted=!0)}return deleted}normalize(format){const self=this,headers={};return utils$3.forEach(this,(value,header)=>{const key=utils$3.findKey(headers,header);if(key)return self[key]=normalizeValue(value),void delete self[header];const normalized=format?function formatHeader(header){return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(w,char,str)=>char.toUpperCase()+str)}(header):String(header).trim();normalized!==header&&delete self[header],self[normalized]=normalizeValue(value),headers[normalized]=!0}),this}concat(...targets){return this.constructor.concat(this,...targets)}toJSON(asStrings){const obj=Object.create(null);return utils$3.forEach(this,(value,header)=>{null!=value&&!1!==value&&(obj[header]=asStrings&&utils$3.isArray(value)?value.join(", "):value)}),obj}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([header,value])=>header+": "+value).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(thing){return thing instanceof this?thing:new this(thing)}static concat(first,...targets){const computed=new this(first);return targets.forEach(target=>computed.set(target)),computed}static accessor(header){const accessors=(this[$internals]=this[$internals]={accessors:{}}).accessors,prototype=this.prototype;function defineAccessor(_header){const lHeader=normalizeHeader(_header);accessors[lHeader]||(!function buildAccessors(obj,header){const accessorName=utils$3.toCamelCase(" "+header);["get","set","has"].forEach(methodName=>{Object.defineProperty(obj,methodName+accessorName,{value:function(arg1,arg2,arg3){return this[methodName].call(this,header,arg1,arg2,arg3)},configurable:!0})})}(prototype,_header),accessors[lHeader]=!0)}return utils$3.isArray(header)?header.forEach(defineAccessor):defineAccessor(header),this}};function transformData(fns,response){const config=this||defaults,context=response||config,headers=AxiosHeaders$1.from(context.headers);let data=context.data;return utils$3.forEach(fns,function transform(fn){data=fn.call(config,data,headers.normalize(),response?response.status:void 0)}),headers.normalize(),data}function isCancel$1(value){return!(!value||!value.__CANCEL__)}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$3.reduceDescriptors(AxiosHeaders$1.prototype,({value:value},key)=>{let mapped=key[0].toUpperCase()+key.slice(1);return{get:()=>value,set(headerValue){this[mapped]=headerValue}}}),utils$3.freezeMethods(AxiosHeaders$1);let CanceledError$1=class CanceledError extends AxiosError$1{constructor(message,config,request){super(null==message?"canceled":message,AxiosError$1.ERR_CANCELED,config,request),this.name="CanceledError",this.__CANCEL__=!0}};function settle(resolve,reject,response){const validateStatus=response.config.validateStatus;response.status&&validateStatus&&!validateStatus(response.status)?reject(new AxiosError$1("Request failed with status code "+response.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status/100)-4],response.config,response.request,response)):resolve(response)}function buildFullPath(baseURL,requestedURL,allowAbsoluteUrls){let isRelativeUrl=!function isAbsoluteURL(url){return"string"==typeof url&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)}(requestedURL);return baseURL&&(isRelativeUrl||0==allowAbsoluteUrls)?function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/?\/$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}(baseURL,requestedURL):requestedURL}var hasRequiredProxyFromEnv,proxyFromEnv$1={};var ms,hasRequiredMs,common,hasRequiredCommon,hasRequiredBrowser,proxyFromEnvExports=function requireProxyFromEnv(){if(hasRequiredProxyFromEnv)return proxyFromEnv$1;hasRequiredProxyFromEnv=1;var parseUrl=require$$0$a.parse,DEFAULT_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443},stringEndsWith=String.prototype.endsWith||function(s){return s.length<=this.length&&-1!==this.indexOf(s,this.length-s.length)};function getEnv(key){return process.env[key.toLowerCase()]||process.env[key.toUpperCase()]||""}return proxyFromEnv$1.getProxyForUrl=function getProxyForUrl(url){var parsedUrl="string"==typeof url?parseUrl(url):url||{},proto=parsedUrl.protocol,hostname=parsedUrl.host,port=parsedUrl.port;if("string"!=typeof hostname||!hostname||"string"!=typeof proto)return"";if(proto=proto.split(":",1)[0],!function shouldProxy(hostname,port){var NO_PROXY=(getEnv("npm_config_no_proxy")||getEnv("no_proxy")).toLowerCase();if(!NO_PROXY)return!0;if("*"===NO_PROXY)return!1;return NO_PROXY.split(/[,\s]/).every(function(proxy){if(!proxy)return!0;var parsedProxy=proxy.match(/^(.+):(\d+)$/),parsedProxyHostname=parsedProxy?parsedProxy[1]:proxy,parsedProxyPort=parsedProxy?parseInt(parsedProxy[2]):0;return!(!parsedProxyPort||parsedProxyPort===port)||(/^[.*]/.test(parsedProxyHostname)?("*"===parsedProxyHostname.charAt(0)&&(parsedProxyHostname=parsedProxyHostname.slice(1)),!stringEndsWith.call(hostname,parsedProxyHostname)):hostname!==parsedProxyHostname)})}(hostname=hostname.replace(/:\d*$/,""),port=parseInt(port)||DEFAULT_PORTS[proto]||0))return"";var proxy=getEnv("npm_config_"+proto+"_proxy")||getEnv(proto+"_proxy")||getEnv("npm_config_proxy")||getEnv("all_proxy");return proxy&&-1===proxy.indexOf("://")&&(proxy=proto+"://"+proxy),proxy},proxyFromEnv$1}(),proxyFromEnv=getDefaultExportFromCjs(proxyFromEnvExports),followRedirects$1={exports:{}},src={exports:{}},browser={exports:{}};function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var s=1e3,m=60*s,h=60*m,d=24*h,w=7*d,y=365.25*d;function plural(ms,msAbs,n,name){var isPlural=msAbs>=1.5*n;return Math.round(ms/n)+" "+name+(isPlural?"s":"")}return ms=function(val,options){options=options||{};var type=typeof val;if("string"===type&&val.length>0)return function parse(str){if((str=String(str)).length>100)return;var match=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);switch((match[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"weeks":case"week":case"w":return n*w;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(val);if("number"===type&&isFinite(val))return options.long?function fmtLong(ms){var msAbs=Math.abs(ms);if(msAbs>=d)return plural(ms,msAbs,d,"day");if(msAbs>=h)return plural(ms,msAbs,h,"hour");if(msAbs>=m)return plural(ms,msAbs,m,"minute");if(msAbs>=s)return plural(ms,msAbs,s,"second");return ms+" ms"}(val):function fmtShort(ms){var msAbs=Math.abs(ms);if(msAbs>=d)return Math.round(ms/d)+"d";if(msAbs>=h)return Math.round(ms/h)+"h";if(msAbs>=m)return Math.round(ms/m)+"m";if(msAbs>=s)return Math.round(ms/s)+"s";return ms+"ms"}(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))},ms}function requireCommon(){if(hasRequiredCommon)return common;return hasRequiredCommon=1,common=function setup(env){function createDebug(namespace){let prevTime,namespacesCache,enabledCache,enableOverride=null;function debug(...args){if(!debug.enabled)return;const self=debug,curr=Number(new Date),ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return"%";index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);(self.log||createDebug.log).apply(self,args)}return debug.namespace=namespace,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==enableOverride?enableOverride:(namespacesCache!==createDebug.namespaces&&(namespacesCache=createDebug.namespaces,enabledCache=createDebug.enabled(namespace)),enabledCache),set:v=>{enableOverride=v}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+(void 0===delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function matchesTemplate(search,template){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;for(;searchIndex<search.length;)if(templateIndex<template.length&&(template[templateIndex]===search[searchIndex]||"*"===template[templateIndex]))"*"===template[templateIndex]?(starIndex=templateIndex,matchIndex=searchIndex,templateIndex++):(searchIndex++,templateIndex++);else{if(-1===starIndex)return!1;templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex}for(;templateIndex<template.length&&"*"===template[templateIndex];)templateIndex++;return templateIndex===template.length}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function coerce(val){if(val instanceof Error)return val.stack||val.message;return val},createDebug.disable=function disable(){const namespaces=[...createDebug.names,...createDebug.skips.map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function enable(namespaces){createDebug.save(namespaces),createDebug.namespaces=namespaces,createDebug.names=[],createDebug.skips=[];const split=("string"==typeof namespaces?namespaces:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const ns of split)"-"===ns[0]?createDebug.skips.push(ns.slice(1)):createDebug.names.push(ns)},createDebug.enabled=function enabled(name){for(const skip of createDebug.skips)if(matchesTemplate(name,skip))return!1;for(const ns of createDebug.names)if(matchesTemplate(name,ns))return!0;return!1},createDebug.humanize=requireMs(),createDebug.destroy=function destroy(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(env).forEach(key=>{createDebug[key]=env[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function selectColor(namespace){let hash=0;for(let i=0;i<namespace.length;i++)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return createDebug.colors[Math.abs(hash)%createDebug.colors.length]},createDebug.enable(createDebug.load()),createDebug},common}var hasRequiredNode,hasRequiredSrc,debug_1,hasRequiredDebug,hasRequiredFollowRedirects,node={exports:{}};function requireNode(){return hasRequiredNode||(hasRequiredNode=1,function(module,exports$1){const tty=require$$0$5,util=require$$1$3;exports$1.init=function init(debug){debug.inspectOpts={};const keys=Object.keys(exports$1.inspectOpts);for(let i=0;i<keys.length;i++)debug.inspectOpts[keys[i]]=exports$1.inspectOpts[keys[i]]},exports$1.log=function log(...args){return process.stderr.write(util.formatWithOptions(exports$1.inspectOpts,...args)+"\n")},exports$1.formatArgs=function formatArgs(args){const{namespace:name,useColors:useColors}=this;if(useColors){const c=this.color,colorCode="[3"+(c<8?c:"8;5;"+c),prefix=` ${colorCode};1m${name} [0m`;args[0]=prefix+args[0].split("\n").join("\n"+prefix),args.push(colorCode+"m+"+module.exports.humanize(this.diff)+"[0m")}else args[0]=function getDate(){if(exports$1.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+name+" "+args[0]},exports$1.save=function save(namespaces){namespaces?process.env.DEBUG=namespaces:delete process.env.DEBUG},exports$1.load=function load(){return process.env.DEBUG},exports$1.useColors=function useColors(){return"colors"in exports$1.inspectOpts?Boolean(exports$1.inspectOpts.colors):tty.isatty(process.stderr.fd)},exports$1.destroy=util.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),exports$1.colors=[6,2,3,4,5,1];try{const supportsColor=requireSupportsColor();supportsColor&&(supportsColor.stderr||supportsColor).level>=2&&(exports$1.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(error){}exports$1.inspectOpts=Object.keys(process.env).filter(key=>/^debug_/i.test(key)).reduce((obj,key)=>{const prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_,k)=>k.toUpperCase());let val=process.env[key];return val=!!/^(yes|on|true|enabled)$/i.test(val)||!/^(no|off|false|disabled)$/i.test(val)&&("null"===val?null:Number(val)),obj[prop]=val,obj},{}),module.exports=requireCommon()(exports$1);const{formatters:formatters}=module.exports;formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split("\n").map(str=>str.trim()).join(" ")},formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)}}(node,node.exports)),node.exports}function requireSrc(){return hasRequiredSrc||(hasRequiredSrc=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?src.exports=function requireBrowser(){return hasRequiredBrowser||(hasRequiredBrowser=1,function(module,exports$1){exports$1.formatArgs=function formatArgs(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"!==match&&(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports$1.save=function save(namespaces){try{namespaces?exports$1.storage.setItem("debug",namespaces):exports$1.storage.removeItem("debug")}catch(error){}},exports$1.load=function load(){let r;try{r=exports$1.storage.getItem("debug")||exports$1.storage.getItem("DEBUG")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r},exports$1.useColors=function useColors(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let m;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(m=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},exports$1.storage=function localstorage(){try{return localStorage}catch(error){}}(),exports$1.destroy=(()=>{let warned=!1;return()=>{warned||(warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),exports$1.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports$1.log=console.debug||console.log||(()=>{}),module.exports=requireCommon()(exports$1);const{formatters:formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}(browser,browser.exports)),browser.exports}():src.exports=requireNode()),src.exports}var followRedirectsExports=function requireFollowRedirects(){if(hasRequiredFollowRedirects)return followRedirects$1.exports;hasRequiredFollowRedirects=1;var url=require$$0$a,URL=url.URL,http=require$$3$3,https=require$$4$3,Writable=stream$1.Writable,assert=require$$0$7,debug=function requireDebug(){return hasRequiredDebug||(hasRequiredDebug=1,debug_1=function(){if(!debug){try{debug=requireSrc()("follow-redirects")}catch(error){}"function"!=typeof debug&&(debug=function(){})}debug.apply(null,arguments)}),debug_1;var debug}();!function detectUnsupportedEnvironment(){var looksLikeNode="undefined"!=typeof process,looksLikeBrowser="undefined"!=typeof window&&"undefined"!=typeof document,looksLikeV8=isFunction(Error.captureStackTrace);looksLikeNode||!looksLikeBrowser&&looksLikeV8||console.warn("The follow-redirects package should be excluded from browser builds.")}();var useNativeURL=!1;try{assert(new URL(""))}catch(error){useNativeURL="ERR_INVALID_URL"===error.code}var preservedUrlFields=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],events=["abort","aborted","connect","error","socket","timeout"],eventHandlers=Object.create(null);events.forEach(function(event){eventHandlers[event]=function(arg1,arg2,arg3){this._redirectable.emit(event,arg1,arg2,arg3)}});var InvalidUrlError=createErrorType("ERR_INVALID_URL","Invalid URL",TypeError),RedirectionError=createErrorType("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),TooManyRedirectsError=createErrorType("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",RedirectionError),MaxBodyLengthExceededError=createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),WriteAfterEndError=createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),destroy=Writable.prototype.destroy||noop;function RedirectableRequest(options,responseCallback){Writable.call(this),this._sanitizeOptions(options),this._options=options,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],responseCallback&&this.on("response",responseCallback);var self=this;this._onNativeResponse=function(response){try{self._processResponse(response)}catch(cause){self.emit("error",cause instanceof RedirectionError?cause:new RedirectionError({cause:cause}))}},this._performRequest()}function wrap(protocols){var exports$1={maxRedirects:21,maxBodyLength:10485760},nativeProtocols={};return Object.keys(protocols).forEach(function(scheme){var protocol=scheme+":",nativeProtocol=nativeProtocols[protocol]=protocols[scheme],wrappedProtocol=exports$1[scheme]=Object.create(nativeProtocol);Object.defineProperties(wrappedProtocol,{request:{value:function request(input,options,callback){return!function isURL(value){return URL&&value instanceof URL}(input)?isString(input)?input=spreadUrlObject(parseUrl(input)):(callback=options,options=validateUrl(input),input={protocol:protocol}):input=spreadUrlObject(input),isFunction(options)&&(callback=options,options=null),(options=Object.assign({maxRedirects:exports$1.maxRedirects,maxBodyLength:exports$1.maxBodyLength},input,options)).nativeProtocols=nativeProtocols,isString(options.host)||isString(options.hostname)||(options.hostname="::1"),assert.equal(options.protocol,protocol,"protocol mismatch"),debug("options",options),new RedirectableRequest(options,callback)},configurable:!0,enumerable:!0,writable:!0},get:{value:function get(input,options,callback){var wrappedRequest=wrappedProtocol.request(input,options,callback);return wrappedRequest.end(),wrappedRequest},configurable:!0,enumerable:!0,writable:!0}})}),exports$1}function noop(){}function parseUrl(input){var parsed;if(useNativeURL)parsed=new URL(input);else if(!isString((parsed=validateUrl(url.parse(input))).protocol))throw new InvalidUrlError({input:input});return parsed}function validateUrl(input){if(/^\[/.test(input.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(input.hostname))throw new InvalidUrlError({input:input.href||input});if(/^\[/.test(input.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host))throw new InvalidUrlError({input:input.href||input});return input}function spreadUrlObject(urlObject,target){var spread=target||{};for(var key of preservedUrlFields)spread[key]=urlObject[key];return spread.hostname.startsWith("[")&&(spread.hostname=spread.hostname.slice(1,-1)),""!==spread.port&&(spread.port=Number(spread.port)),spread.path=spread.search?spread.pathname+spread.search:spread.pathname,spread}function removeMatchingHeaders(regex,headers){var lastValue;for(var header in headers)regex.test(header)&&(lastValue=headers[header],delete headers[header]);return null==lastValue?void 0:String(lastValue).trim()}function createErrorType(code,message,baseClass){function CustomError(properties){isFunction(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,properties||{}),this.code=code,this.message=this.cause?message+": "+this.cause.message:message}return CustomError.prototype=new(baseClass||Error),Object.defineProperties(CustomError.prototype,{constructor:{value:CustomError,enumerable:!1},name:{value:"Error ["+code+"]",enumerable:!1}}),CustomError}function destroyRequest(request,error){for(var event of events)request.removeListener(event,eventHandlers[event]);request.on("error",noop),request.destroy(error)}function isString(value){return"string"==typeof value||value instanceof String}function isFunction(value){return"function"==typeof value}return RedirectableRequest.prototype=Object.create(Writable.prototype),RedirectableRequest.prototype.abort=function(){destroyRequest(this._currentRequest),this._currentRequest.abort(),this.emit("abort")},RedirectableRequest.prototype.destroy=function(error){return destroyRequest(this._currentRequest,error),destroy.call(this,error),this},RedirectableRequest.prototype.write=function(data,encoding,callback){if(this._ending)throw new WriteAfterEndError;if(!isString(data)&&!function isBuffer(value){return"object"==typeof value&&"length"in value}(data))throw new TypeError("data should be a string, Buffer or Uint8Array");isFunction(encoding)&&(callback=encoding,encoding=null),0!==data.length?this._requestBodyLength+data.length<=this._options.maxBodyLength?(this._requestBodyLength+=data.length,this._requestBodyBuffers.push({data:data,encoding:encoding}),this._currentRequest.write(data,encoding,callback)):(this.emit("error",new MaxBodyLengthExceededError),this.abort()):callback&&callback()},RedirectableRequest.prototype.end=function(data,encoding,callback){if(isFunction(data)?(callback=data,data=encoding=null):isFunction(encoding)&&(callback=encoding,encoding=null),data){var self=this,currentRequest=this._currentRequest;this.write(data,encoding,function(){self._ended=!0,currentRequest.end(null,null,callback)}),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,callback)},RedirectableRequest.prototype.setHeader=function(name,value){this._options.headers[name]=value,this._currentRequest.setHeader(name,value)},RedirectableRequest.prototype.removeHeader=function(name){delete this._options.headers[name],this._currentRequest.removeHeader(name)},RedirectableRequest.prototype.setTimeout=function(msecs,callback){var self=this;function destroyOnTimeout(socket){socket.setTimeout(msecs),socket.removeListener("timeout",socket.destroy),socket.addListener("timeout",socket.destroy)}function startTimer(socket){self._timeout&&clearTimeout(self._timeout),self._timeout=setTimeout(function(){self.emit("timeout"),clearTimer()},msecs),destroyOnTimeout(socket)}function clearTimer(){self._timeout&&(clearTimeout(self._timeout),self._timeout=null),self.removeListener("abort",clearTimer),self.removeListener("error",clearTimer),self.removeListener("response",clearTimer),self.removeListener("close",clearTimer),callback&&self.removeListener("timeout",callback),self.socket||self._currentRequest.removeListener("socket",startTimer)}return callback&&this.on("timeout",callback),this.socket?startTimer(this.socket):this._currentRequest.once("socket",startTimer),this.on("socket",destroyOnTimeout),this.on("abort",clearTimer),this.on("error",clearTimer),this.on("response",clearTimer),this.on("close",clearTimer),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(method){RedirectableRequest.prototype[method]=function(a,b){return this._currentRequest[method](a,b)}}),["aborted","connection","socket"].forEach(function(property){Object.defineProperty(RedirectableRequest.prototype,property,{get:function(){return this._currentRequest[property]}})}),RedirectableRequest.prototype._sanitizeOptions=function(options){if(options.headers||(options.headers={}),options.host&&(options.hostname||(options.hostname=options.host),delete options.host),!options.pathname&&options.path){var searchPos=options.path.indexOf("?");searchPos<0?options.pathname=options.path:(options.pathname=options.path.substring(0,searchPos),options.search=options.path.substring(searchPos))}},RedirectableRequest.prototype._performRequest=function(){var protocol=this._options.protocol,nativeProtocol=this._options.nativeProtocols[protocol];if(!nativeProtocol)throw new TypeError("Unsupported protocol "+protocol);if(this._options.agents){var scheme=protocol.slice(0,-1);this._options.agent=this._options.agents[scheme]}var request=this._currentRequest=nativeProtocol.request(this._options,this._onNativeResponse);for(var event of(request._redirectable=this,events))request.on(event,eventHandlers[event]);if(this._currentUrl=/^\//.test(this._options.path)?url.format(this._options):this._options.path,this._isRedirect){var i=0,self=this,buffers=this._requestBodyBuffers;!function writeNext(error){if(request===self._currentRequest)if(error)self.emit("error",error);else if(i<buffers.length){var buffer=buffers[i++];request.finished||request.write(buffer.data,buffer.encoding,writeNext)}else self._ended&&request.end()}()}},RedirectableRequest.prototype._processResponse=function(response){var statusCode=response.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:response.headers,statusCode:statusCode});var requestHeaders,location=response.headers.location;if(!location||!1===this._options.followRedirects||statusCode<300||statusCode>=400)return response.responseUrl=this._currentUrl,response.redirects=this._redirects,this.emit("response",response),void(this._requestBodyBuffers=[]);if(destroyRequest(this._currentRequest),response.destroy(),++this._redirectCount>this._options.maxRedirects)throw new TooManyRedirectsError;var beforeRedirect=this._options.beforeRedirect;beforeRedirect&&(requestHeaders=Object.assign({Host:response.req.getHeader("host")},this._options.headers));var method=this._options.method;((301===statusCode||302===statusCode)&&"POST"===this._options.method||303===statusCode&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],removeMatchingHeaders(/^content-/i,this._options.headers));var currentHostHeader=removeMatchingHeaders(/^host$/i,this._options.headers),currentUrlParts=parseUrl(this._currentUrl),currentHost=currentHostHeader||currentUrlParts.host,currentUrl=/^\w+:/.test(location)?this._currentUrl:url.format(Object.assign(currentUrlParts,{host:currentHost})),redirectUrl=function resolveUrl(relative,base){return useNativeURL?new URL(relative,base):parseUrl(url.resolve(base,relative))}(location,currentUrl);if(debug("redirecting to",redirectUrl.href),this._isRedirect=!0,spreadUrlObject(redirectUrl,this._options),(redirectUrl.protocol!==currentUrlParts.protocol&&"https:"!==redirectUrl.protocol||redirectUrl.host!==currentHost&&!function isSubdomain(subdomain,domain){assert(isString(subdomain)&&isString(domain));var dot=subdomain.length-domain.length-1;return dot>0&&"."===subdomain[dot]&&subdomain.endsWith(domain)}(redirectUrl.host,currentHost))&&removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i,this._options.headers),isFunction(beforeRedirect)){var responseDetails={headers:response.headers,statusCode:statusCode},requestDetails={url:currentUrl,method:method,headers:requestHeaders};beforeRedirect(this._options,responseDetails,requestDetails),this._sanitizeOptions(this._options)}this._performRequest()},followRedirects$1.exports=wrap({http:http,https:https}),followRedirects$1.exports.wrap=wrap,followRedirects$1.exports}(),followRedirects=getDefaultExportFromCjs(followRedirectsExports);function parseProtocol(url){const match=/^([-+\w]{1,25})(:?\/\/|:)/.exec(url);return match&&match[1]||""}const DATA_URL_PATTERN=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;const kInternals=Symbol("internals");class AxiosTransformStream extends stream$1.Transform{constructor(options){options=utils$3.toFlatObject(options,{maxRate:0,chunkSize:65536,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(prop,source)=>!utils$3.isUndefined(source[prop])),super({readableHighWaterMark:options.chunkSize});const internals=this[kInternals]={timeWindow:options.timeWindow,chunkSize:options.chunkSize,maxRate:options.maxRate,minChunkSize:options.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",event=>{"progress"===event&&(internals.isCaptured||(internals.isCaptured=!0))})}_read(size){const internals=this[kInternals];return internals.onReadCallback&&internals.onReadCallback(),super._read(size)}_transform(chunk,encoding,callback){const internals=this[kInternals],maxRate=internals.maxRate,readableHighWaterMark=this.readableHighWaterMark,timeWindow=internals.timeWindow,bytesThreshold=maxRate/(1e3/timeWindow),minChunkSize=!1!==internals.minChunkSize?Math.max(internals.minChunkSize,.01*bytesThreshold):0,pushChunk=(_chunk,_callback)=>{const bytes=Buffer.byteLength(_chunk);internals.bytesSeen+=bytes,internals.bytes+=bytes,internals.isCaptured&&this.emit("progress",internals.bytesSeen),this.push(_chunk)?process.nextTick(_callback):internals.onReadCallback=()=>{internals.onReadCallback=null,process.nextTick(_callback)}},transformChunk=(_chunk,_callback)=>{const chunkSize=Buffer.byteLength(_chunk);let bytesLeft,chunkRemainder=null,maxChunkSize=readableHighWaterMark,passed=0;if(maxRate){const now=Date.now();(!internals.ts||(passed=now-internals.ts)>=timeWindow)&&(internals.ts=now,bytesLeft=bytesThreshold-internals.bytes,internals.bytes=bytesLeft<0?-bytesLeft:0,passed=0),bytesLeft=bytesThreshold-internals.bytes}if(maxRate){if(bytesLeft<=0)return setTimeout(()=>{_callback(null,_chunk)},timeWindow-passed);bytesLeft<maxChunkSize&&(maxChunkSize=bytesLeft)}maxChunkSize&&chunkSize>maxChunkSize&&chunkSize-maxChunkSize>minChunkSize&&(chunkRemainder=_chunk.subarray(maxChunkSize),_chunk=_chunk.subarray(0,maxChunkSize)),pushChunk(_chunk,chunkRemainder?()=>{process.nextTick(_callback,null,chunkRemainder)}:_callback)};transformChunk(chunk,function transformNextChunk(err,_chunk){if(err)return callback(err);_chunk?transformChunk(_chunk,transformNextChunk):callback(null)})}}const{asyncIterator:asyncIterator}=Symbol,readBlob=async function*(blob){blob.stream?yield*blob.stream():blob.arrayBuffer?yield await blob.arrayBuffer():blob[asyncIterator]?yield*blob[asyncIterator]():yield blob},BOUNDARY_ALPHABET=platform.ALPHABET.ALPHA_DIGIT+"-_",textEncoder="function"==typeof TextEncoder?new TextEncoder:new require$$1$3.TextEncoder,CRLF_BYTES=textEncoder.encode("\r\n");class FormDataPart{constructor(name,value){const{escapeName:escapeName}=this.constructor,isStringValue=utils$3.isString(value);let headers=`Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue&&value.name?`; filename="${escapeName(value.name)}"`:""}\r\n`;isStringValue?value=textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g,"\r\n")):headers+=`Content-Type: ${value.type||"application/octet-stream"}\r\n`,this.headers=textEncoder.encode(headers+"\r\n"),this.contentLength=isStringValue?value.byteLength:value.size,this.size=this.headers.byteLength+this.contentLength+2,this.name=name,this.value=value}async*encode(){yield this.headers;const{value:value}=this;utils$3.isTypedArray(value)?yield value:yield*readBlob(value),yield CRLF_BYTES}static escapeName(name){return String(name).replace(/[\r\n"]/g,match=>({"\r":"%0D","\n":"%0A",'"':"%22"}[match]))}}class ZlibHeaderTransformStream extends stream$1.Transform{__transform(chunk,encoding,callback){this.push(chunk),callback()}_transform(chunk,encoding,callback){if(0!==chunk.length&&(this._transform=this.__transform,120!==chunk[0])){const header=Buffer.alloc(2);header[0]=120,header[1]=156,this.push(header,encoding)}this.__transform(chunk,encoding,callback)}}const callbackify=(fn,reducer)=>utils$3.isAsyncFn(fn)?function(...args){const cb=args.pop();fn.apply(this,args).then(value=>{try{reducer?cb(null,...reducer(value)):cb(null,value)}catch(err){cb(err)}},cb)}:fn;const progressEventReducer=(listener,isDownloadStream,freq=3)=>{let bytesNotified=0;const _speedometer=function speedometer(samplesCount,min){samplesCount=samplesCount||10;const bytes=new Array(samplesCount),timestamps=new Array(samplesCount);let firstSampleTS,head=0,tail=0;return min=void 0!==min?min:1e3,function push(chunkLength){const now=Date.now(),startedAt=timestamps[tail];firstSampleTS||(firstSampleTS=now),bytes[head]=chunkLength,timestamps[head]=now;let i=tail,bytesCount=0;for(;i!==head;)bytesCount+=bytes[i++],i%=samplesCount;if(head=(head+1)%samplesCount,head===tail&&(tail=(tail+1)%samplesCount),now-firstSampleTS<min)return;const passed=startedAt&&now-startedAt;return passed?Math.round(1e3*bytesCount/passed):void 0}}(50,250);return function throttle(fn,freq){let lastArgs,timer,timestamp=0,threshold=1e3/freq;const invoke=(args,now=Date.now())=>{timestamp=now,lastArgs=null,timer&&(clearTimeout(timer),timer=null),fn(...args)};return[(...args)=>{const now=Date.now(),passed=now-timestamp;passed>=threshold?invoke(args,now):(lastArgs=args,timer||(timer=setTimeout(()=>{timer=null,invoke(lastArgs)},threshold-passed)))},()=>lastArgs&&invoke(lastArgs)]}(e=>{const loaded=e.loaded,total=e.lengthComputable?e.total:void 0,progressBytes=loaded-bytesNotified,rate=_speedometer(progressBytes);bytesNotified=loaded;listener({loaded:loaded,total:total,progress:total?loaded/total:void 0,bytes:progressBytes,rate:rate||void 0,estimated:rate&&total&&loaded<=total?(total-loaded)/rate:void 0,event:e,lengthComputable:null!=total,[isDownloadStream?"download":"upload"]:!0})},freq)},progressEventDecorator=(total,throttled)=>{const lengthComputable=null!=total;return[loaded=>throttled[0]({lengthComputable:lengthComputable,total:total,loaded:loaded}),throttled[1]]},asyncDecorator=fn=>(...args)=>utils$3.asap(()=>fn(...args));const zlibOptions={flush:zlib.constants.Z_SYNC_FLUSH,finishFlush:zlib.constants.Z_SYNC_FLUSH},brotliOptions={flush:zlib.constants.BROTLI_OPERATION_FLUSH,finishFlush:zlib.constants.BROTLI_OPERATION_FLUSH},isBrotliSupported=utils$3.isFunction(zlib.createBrotliDecompress),{http:httpFollow,https:httpsFollow}=followRedirects,isHttps=/https:?/,supportedProtocols=platform.protocols.map(protocol=>protocol+":"),flushOnFinish=(stream,[throttled,flush])=>(stream.on("end",flush).on("error",flush),throttled);const http2Sessions=new class Http2Sessions{constructor(){this.sessions=Object.create(null)}getSession(authority,options){options=Object.assign({sessionTimeout:1e3},options);let authoritySessions=this.sessions[authority];if(authoritySessions){let len=authoritySessions.length;for(let i=0;i<len;i++){const[sessionHandle,sessionOptions]=authoritySessions[i];if(!sessionHandle.destroyed&&!sessionHandle.closed&&require$$1$3.isDeepStrictEqual(sessionOptions,options))return sessionHandle}}const session=http2.connect(authority,options);let removed;const removeSession=()=>{if(removed)return;removed=!0;let entries=authoritySessions,len=entries.length,i=len;for(;i--;)if(entries[i][0]===session)return void(1===len?delete this.sessions[authority]:entries.splice(i,1))},originalRequestFn=session.request,{sessionTimeout:sessionTimeout}=options;if(null!=sessionTimeout){let timer,streamsCount=0;session.request=function(){const stream=originalRequestFn.apply(this,arguments);return streamsCount++,timer&&(clearTimeout(timer),timer=null),stream.once("close",()=>{--streamsCount||(timer=setTimeout(()=>{timer=null,removeSession()},sessionTimeout))}),stream}}session.once("close",removeSession);let entry=[session,options];return authoritySessions?authoritySessions.push(entry):authoritySessions=this.sessions[authority]=[entry],session}};function dispatchBeforeRedirect(options,responseDetails){options.beforeRedirects.proxy&&options.beforeRedirects.proxy(options),options.beforeRedirects.config&&options.beforeRedirects.config(options,responseDetails)}function setProxy(options,configProxy,location){let proxy=configProxy;if(!proxy&&!1!==proxy){const proxyUrl=proxyFromEnv.getProxyForUrl(location);proxyUrl&&(proxy=new URL(proxyUrl))}if(proxy){if(proxy.username&&(proxy.auth=(proxy.username||"")+":"+(proxy.password||"")),proxy.auth){if(Boolean(proxy.auth.username||proxy.auth.password))proxy.auth=(proxy.auth.username||"")+":"+(proxy.auth.password||"");else if("object"==typeof proxy.auth)throw new AxiosError$1("Invalid proxy authorization",AxiosError$1.ERR_BAD_OPTION,{proxy:proxy});const base64=Buffer.from(proxy.auth,"utf8").toString("base64");options.headers["Proxy-Authorization"]="Basic "+base64}options.headers.host=options.hostname+(options.port?":"+options.port:"");const proxyHost=proxy.hostname||proxy.host;options.hostname=proxyHost,options.host=proxyHost,options.port=proxy.port,options.path=location,proxy.protocol&&(options.protocol=proxy.protocol.includes(":")?proxy.protocol:`${proxy.protocol}:`)}options.beforeRedirects.proxy=function beforeRedirect(redirectOptions){setProxy(redirectOptions,configProxy,redirectOptions.href)}}const isHttpAdapterSupported="undefined"!=typeof process&&"process"===utils$3.kindOf(process),buildAddressEntry=(address,family)=>(({address:address,family:family})=>{if(!utils$3.isString(address))throw TypeError("address must be a string");return{address:address,family:family||(address.indexOf(".")<0?6:4)}})(utils$3.isObject(address)?address:{address:address,family:family}),http2Transport={request(options,cb){const authority=options.protocol+"//"+options.hostname+":"+(options.port||("https:"===options.protocol?443:80)),{http2Options:http2Options,headers:headers}=options,session=http2Sessions.getSession(authority,http2Options),{HTTP2_HEADER_SCHEME:HTTP2_HEADER_SCHEME,HTTP2_HEADER_METHOD:HTTP2_HEADER_METHOD,HTTP2_HEADER_PATH:HTTP2_HEADER_PATH,HTTP2_HEADER_STATUS:HTTP2_HEADER_STATUS}=http2.constants,http2Headers={[HTTP2_HEADER_SCHEME]:options.protocol.replace(":",""),[HTTP2_HEADER_METHOD]:options.method,[HTTP2_HEADER_PATH]:options.path};utils$3.forEach(headers,(header,name)=>{":"!==name.charAt(0)&&(http2Headers[name]=header)});const req=session.request(http2Headers);return req.once("response",responseHeaders=>{const response=req,status=(responseHeaders=Object.assign({},responseHeaders))[HTTP2_HEADER_STATUS];delete responseHeaders[HTTP2_HEADER_STATUS],response.headers=responseHeaders,response.statusCode=+status,cb(response)}),req}};var httpAdapter=isHttpAdapterSupported&&function httpAdapter(config){return asyncExecutor=async function dispatchHttpRequest(resolve,reject,onDone){let{data:data,lookup:lookup,family:family,httpVersion:httpVersion=1,http2Options:http2Options}=config;const{responseType:responseType,responseEncoding:responseEncoding}=config,method=config.method.toUpperCase();let isDone,req,rejected=!1;if(httpVersion=+httpVersion,Number.isNaN(httpVersion))throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);if(1!==httpVersion&&2!==httpVersion)throw TypeError(`Unsupported protocol version '${httpVersion}'`);const isHttp2=2===httpVersion;if(lookup){const _lookup=callbackify(lookup,value=>utils$3.isArray(value)?value:[value]);lookup=(hostname,opt,cb)=>{_lookup(hostname,opt,(err,arg0,arg1)=>{if(err)return cb(err);const addresses=utils$3.isArray(arg0)?arg0.map(addr=>buildAddressEntry(addr)):[buildAddressEntry(arg0,arg1)];opt.all?cb(err,addresses):cb(err,addresses[0].address,addresses[0].family)})}}const abortEmitter=new require$$0$4.EventEmitter;function abort(reason){try{abortEmitter.emit("abort",!reason||reason.type?new CanceledError$1(null,config,req):reason)}catch(err){console.warn("emit error",err)}}abortEmitter.once("abort",reject);const onFinished=()=>{config.cancelToken&&config.cancelToken.unsubscribe(abort),config.signal&&config.signal.removeEventListener("abort",abort),abortEmitter.removeAllListeners()};(config.cancelToken||config.signal)&&(config.cancelToken&&config.cancelToken.subscribe(abort),config.signal&&(config.signal.aborted?abort():config.signal.addEventListener("abort",abort))),onDone((response,isRejected)=>{if(isDone=!0,isRejected)return rejected=!0,void onFinished();const{data:data}=response;if(data instanceof stream$1.Readable||data instanceof stream$1.Duplex){const offListeners=stream$1.finished(data,()=>{offListeners(),onFinished()})}else onFinished()});const fullPath=buildFullPath(config.baseURL,config.url,config.allowAbsoluteUrls),parsed=new URL(fullPath,platform.hasBrowserEnv?platform.origin:void 0),protocol=parsed.protocol||supportedProtocols[0];if("data:"===protocol){if(config.maxContentLength>-1&&function estimateDataURLDecodedBytes(url){if(!url||"string"!=typeof url)return 0;if(!url.startsWith("data:"))return 0;const comma=url.indexOf(",");if(comma<0)return 0;const meta=url.slice(5,comma),body=url.slice(comma+1);if(/;base64/i.test(meta)){let effectiveLen=body.length;const len=body.length;for(let i=0;i<len;i++)if(37===body.charCodeAt(i)&&i+2<len){const a=body.charCodeAt(i+1),b=body.charCodeAt(i+2);(a>=48&&a<=57||a>=65&&a<=70||a>=97&&a<=102)&&(b>=48&&b<=57||b>=65&&b<=70||b>=97&&b<=102)&&(effectiveLen-=2,i+=2)}let pad=0,idx=len-1;const tailIsPct3D=j=>j>=2&&37===body.charCodeAt(j-2)&&51===body.charCodeAt(j-1)&&(68===body.charCodeAt(j)||100===body.charCodeAt(j));idx>=0&&(61===body.charCodeAt(idx)?(pad++,idx--):tailIsPct3D(idx)&&(pad++,idx-=3)),1===pad&&idx>=0&&(61===body.charCodeAt(idx)||tailIsPct3D(idx))&&pad++;const bytes=3*Math.floor(effectiveLen/4)-(pad||0);return bytes>0?bytes:0}return Buffer.byteLength(body,"utf8")}(String(config.url||fullPath||""))>config.maxContentLength)return reject(new AxiosError$1("maxContentLength size of "+config.maxContentLength+" exceeded",AxiosError$1.ERR_BAD_RESPONSE,config));let convertedData;if("GET"!==method)return settle(resolve,reject,{status:405,statusText:"method not allowed",headers:{},config:config});try{convertedData=function fromDataURI(uri,asBlob,options){const _Blob=options&&options.Blob||platform.classes.Blob,protocol=parseProtocol(uri);if(void 0===asBlob&&_Blob&&(asBlob=!0),"data"===protocol){uri=protocol.length?uri.slice(protocol.length+1):uri;const match=DATA_URL_PATTERN.exec(uri);if(!match)throw new AxiosError$1("Invalid URL",AxiosError$1.ERR_INVALID_URL);const mime=match[1],isBase64=match[2],body=match[3],buffer=Buffer.from(decodeURIComponent(body),isBase64?"base64":"utf8");if(asBlob){if(!_Blob)throw new AxiosError$1("Blob is not supported",AxiosError$1.ERR_NOT_SUPPORT);return new _Blob([buffer],{type:mime})}return buffer}throw new AxiosError$1("Unsupported protocol "+protocol,AxiosError$1.ERR_NOT_SUPPORT)}(config.url,"blob"===responseType,{Blob:config.env&&config.env.Blob})}catch(err){throw AxiosError$1.from(err,AxiosError$1.ERR_BAD_REQUEST,config)}return"text"===responseType?(convertedData=convertedData.toString(responseEncoding),responseEncoding&&"utf8"!==responseEncoding||(convertedData=utils$3.stripBOM(convertedData))):"stream"===responseType&&(convertedData=stream$1.Readable.from(convertedData)),settle(resolve,reject,{data:convertedData,status:200,statusText:"OK",headers:new AxiosHeaders$1,config:config})}if(-1===supportedProtocols.indexOf(protocol))return reject(new AxiosError$1("Unsupported protocol "+protocol,AxiosError$1.ERR_BAD_REQUEST,config));const headers=AxiosHeaders$1.from(config.headers).normalize();headers.set("User-Agent","axios/1.13.6",!1);const{onUploadProgress:onUploadProgress,onDownloadProgress:onDownloadProgress}=config,maxRate=config.maxRate;let maxUploadRate,maxDownloadRate;if(utils$3.isSpecCompliantForm(data)){const userBoundary=headers.getContentType(/boundary=([-_\w\d]{10,70})/i);data=((form,headersHandler,options)=>{const{tag:tag="form-data-boundary",size:size=25,boundary:boundary=tag+"-"+platform.generateString(size,BOUNDARY_ALPHABET)}=options||{};if(!utils$3.isFormData(form))throw TypeError("FormData instance required");if(boundary.length<1||boundary.length>70)throw Error("boundary must be 10-70 characters long");const boundaryBytes=textEncoder.encode("--"+boundary+"\r\n"),footerBytes=textEncoder.encode("--"+boundary+"--\r\n");let contentLength=footerBytes.byteLength;const parts=Array.from(form.entries()).map(([name,value])=>{const part=new FormDataPart(name,value);return contentLength+=part.size,part});contentLength+=boundaryBytes.byteLength*parts.length,contentLength=utils$3.toFiniteNumber(contentLength);const computedHeaders={"Content-Type":`multipart/form-data; boundary=${boundary}`};return Number.isFinite(contentLength)&&(computedHeaders["Content-Length"]=contentLength),headersHandler&&headersHandler(computedHeaders),stream$1.Readable.from(async function*(){for(const part of parts)yield boundaryBytes,yield*part.encode();yield footerBytes}())})(data,formHeaders=>{headers.set(formHeaders)},{tag:"axios-1.13.6-boundary",boundary:userBoundary&&userBoundary[1]||void 0})}else if(utils$3.isFormData(data)&&utils$3.isFunction(data.getHeaders)){if(headers.set(data.getHeaders()),!headers.hasContentLength())try{const knownLength=await require$$1$3.promisify(data.getLength).call(data);Number.isFinite(knownLength)&&knownLength>=0&&headers.setContentLength(knownLength)}catch(e){}}else if(utils$3.isBlob(data)||utils$3.isFile(data))data.size&&headers.setContentType(data.type||"application/octet-stream"),headers.setContentLength(data.size||0),data=stream$1.Readable.from(readBlob(data));else if(data&&!utils$3.isStream(data)){if(Buffer.isBuffer(data));else if(utils$3.isArrayBuffer(data))data=Buffer.from(new Uint8Array(data));else{if(!utils$3.isString(data))return reject(new AxiosError$1("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",AxiosError$1.ERR_BAD_REQUEST,config));data=Buffer.from(data,"utf-8")}if(headers.setContentLength(data.length,!1),config.maxBodyLength>-1&&data.length>config.maxBodyLength)return reject(new AxiosError$1("Request body larger than maxBodyLength limit",AxiosError$1.ERR_BAD_REQUEST,config))}const contentLength=utils$3.toFiniteNumber(headers.getContentLength());let auth,path;utils$3.isArray(maxRate)?(maxUploadRate=maxRate[0],maxDownloadRate=maxRate[1]):maxUploadRate=maxDownloadRate=maxRate,data&&(onUploadProgress||maxUploadRate)&&(utils$3.isStream(data)||(data=stream$1.Readable.from(data,{objectMode:!1})),data=stream$1.pipeline([data,new AxiosTransformStream({maxRate:utils$3.toFiniteNumber(maxUploadRate)})],utils$3.noop),onUploadProgress&&data.on("progress",flushOnFinish(data,progressEventDecorator(contentLength,progressEventReducer(asyncDecorator(onUploadProgress),!1,3))))),config.auth&&(auth=(config.auth.username||"")+":"+(config.auth.password||"")),!auth&&parsed.username&&(auth=parsed.username+":"+parsed.password),auth&&headers.delete("authorization");try{path=buildURL(parsed.pathname+parsed.search,config.params,config.paramsSerializer).replace(/^\?/,"")}catch(err){const customErr=new Error(err.message);return customErr.config=config,customErr.url=config.url,customErr.exists=!0,reject(customErr)}headers.set("Accept-Encoding","gzip, compress, deflate"+(isBrotliSupported?", br":""),!1);const options={path:path,method:method,headers:headers.toJSON(),agents:{http:config.httpAgent,https:config.httpsAgent},auth:auth,protocol:protocol,family:family,beforeRedirect:dispatchBeforeRedirect,beforeRedirects:{},http2Options:http2Options};let transport;!utils$3.isUndefined(lookup)&&(options.lookup=lookup),config.socketPath?options.socketPath=config.socketPath:(options.hostname=parsed.hostname.startsWith("[")?parsed.hostname.slice(1,-1):parsed.hostname,options.port=parsed.port,setProxy(options,config.proxy,protocol+"//"+parsed.hostname+(parsed.port?":"+parsed.port:"")+options.path));const isHttpsRequest=isHttps.test(options.protocol);if(options.agent=isHttpsRequest?config.httpsAgent:config.httpAgent,isHttp2?transport=http2Transport:config.transport?transport=config.transport:0===config.maxRedirects?transport=isHttpsRequest?require$$4$3:require$$3$3:(config.maxRedirects&&(options.maxRedirects=config.maxRedirects),config.beforeRedirect&&(options.beforeRedirects.config=config.beforeRedirect),transport=isHttpsRequest?httpsFollow:httpFollow),config.maxBodyLength>-1?options.maxBodyLength=config.maxBodyLength:options.maxBodyLength=1/0,config.insecureHTTPParser&&(options.insecureHTTPParser=config.insecureHTTPParser),req=transport.request(options,function handleResponse(res){if(req.destroyed)return;const streams=[res],responseLength=utils$3.toFiniteNumber(res.headers["content-length"]);if(onDownloadProgress||maxDownloadRate){const transformStream=new AxiosTransformStream({maxRate:utils$3.toFiniteNumber(maxDownloadRate)});onDownloadProgress&&transformStream.on("progress",flushOnFinish(transformStream,progressEventDecorator(responseLength,progressEventReducer(asyncDecorator(onDownloadProgress),!0,3)))),streams.push(transformStream)}let responseStream=res;const lastRequest=res.req||req;if(!1!==config.decompress&&res.headers["content-encoding"])switch("HEAD"!==method&&204!==res.statusCode||delete res.headers["content-encoding"],(res.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":streams.push(zlib.createUnzip(zlibOptions)),delete res.headers["content-encoding"];break;case"deflate":streams.push(new ZlibHeaderTransformStream),streams.push(zlib.createUnzip(zlibOptions)),delete res.headers["content-encoding"];break;case"br":isBrotliSupported&&(streams.push(zlib.createBrotliDecompress(brotliOptions)),delete res.headers["content-encoding"])}responseStream=streams.length>1?stream$1.pipeline(streams,utils$3.noop):streams[0];const response={status:res.statusCode,statusText:res.statusMessage,headers:new AxiosHeaders$1(res.headers),config:config,request:lastRequest};if("stream"===responseType)response.data=responseStream,settle(resolve,reject,response);else{const responseBuffer=[];let totalResponseBytes=0;responseStream.on("data",function handleStreamData(chunk){responseBuffer.push(chunk),totalResponseBytes+=chunk.length,config.maxContentLength>-1&&totalResponseBytes>config.maxContentLength&&(rejected=!0,responseStream.destroy(),abort(new AxiosError$1("maxContentLength size of "+config.maxContentLength+" exceeded",AxiosError$1.ERR_BAD_RESPONSE,config,lastRequest)))}),responseStream.on("aborted",function handlerStreamAborted(){if(rejected)return;const err=new AxiosError$1("stream has been aborted",AxiosError$1.ERR_BAD_RESPONSE,config,lastRequest);responseStream.destroy(err),reject(err)}),responseStream.on("error",function handleStreamError(err){req.destroyed||reject(AxiosError$1.from(err,null,config,lastRequest))}),responseStream.on("end",function handleStreamEnd(){try{let responseData=1===responseBuffer.length?responseBuffer[0]:Buffer.concat(responseBuffer);"arraybuffer"!==responseType&&(responseData=responseData.toString(responseEncoding),responseEncoding&&"utf8"!==responseEncoding||(responseData=utils$3.stripBOM(responseData))),response.data=responseData}catch(err){return reject(AxiosError$1.from(err,null,config,response.request,response))}settle(resolve,reject,response)})}abortEmitter.once("abort",err=>{responseStream.destroyed||(responseStream.emit("error",err),responseStream.destroy())})}),abortEmitter.once("abort",err=>{req.close?req.close():req.destroy(err)}),req.on("error",function handleRequestError(err){reject(AxiosError$1.from(err,null,config,req))}),req.on("socket",function handleRequestSocket(socket){socket.setKeepAlive(!0,6e4)}),config.timeout){const timeout=parseInt(config.timeout,10);if(Number.isNaN(timeout))return void abort(new AxiosError$1("error trying to parse `config.timeout` to int",AxiosError$1.ERR_BAD_OPTION_VALUE,config,req));req.setTimeout(timeout,function handleRequestTimeout(){if(isDone)return;let timeoutErrorMessage=config.timeout?"timeout of "+config.timeout+"ms exceeded":"timeout exceeded";const transitional=config.transitional||transitionalDefaults;config.timeoutErrorMessage&&(timeoutErrorMessage=config.timeoutErrorMessage),abort(new AxiosError$1(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,config,req))})}else req.setTimeout(0);if(utils$3.isStream(data)){let ended=!1,errored=!1;data.on("end",()=>{ended=!0}),data.once("error",err=>{errored=!0,req.destroy(err)}),data.on("close",()=>{ended||errored||abort(new CanceledError$1("Request stream has been aborted",config,req))}),data.pipe(req)}else data&&req.write(data),req.end()},new Promise((resolve,reject)=>{let onDone,isDone;const done=(value,isRejected)=>{isDone||(isDone=!0,onDone&&onDone(value,isRejected))},_reject=reason=>{done(reason,!0),reject(reason)};asyncExecutor(value=>{done(value),resolve(value)},_reject,onDoneHandler=>onDone=onDoneHandler).catch(_reject)});var asyncExecutor},isURLSameOrigin=platform.hasStandardBrowserEnv?((origin,isMSIE)=>url=>(url=new URL(url,platform.origin),origin.protocol===url.protocol&&origin.host===url.host&&(isMSIE||origin.port===url.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(name,value,expires,path,domain,secure,sameSite){if("undefined"==typeof document)return;const cookie=[`${name}=${encodeURIComponent(value)}`];utils$3.isNumber(expires)&&cookie.push(`expires=${new Date(expires).toUTCString()}`),utils$3.isString(path)&&cookie.push(`path=${path}`),utils$3.isString(domain)&&cookie.push(`domain=${domain}`),!0===secure&&cookie.push("secure"),utils$3.isString(sameSite)&&cookie.push(`SameSite=${sameSite}`),document.cookie=cookie.join("; ")},read(name){if("undefined"==typeof document)return null;const match=document.cookie.match(new RegExp("(?:^|; )"+name+"=([^;]*)"));return match?decodeURIComponent(match[1]):null},remove(name){this.write(name,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};const headersToObject=thing=>thing instanceof AxiosHeaders$1?{...thing}:thing;function mergeConfig$1(config1,config2){config2=config2||{};const config={};function getMergedValue(target,source,prop,caseless){return utils$3.isPlainObject(target)&&utils$3.isPlainObject(source)?utils$3.merge.call({caseless:caseless},target,source):utils$3.isPlainObject(source)?utils$3.merge({},source):utils$3.isArray(source)?source.slice():source}function mergeDeepProperties(a,b,prop,caseless){return utils$3.isUndefined(b)?utils$3.isUndefined(a)?void 0:getMergedValue(void 0,a,0,caseless):getMergedValue(a,b,0,caseless)}function valueFromConfig2(a,b){if(!utils$3.isUndefined(b))return getMergedValue(void 0,b)}function defaultToConfig2(a,b){return utils$3.isUndefined(b)?utils$3.isUndefined(a)?void 0:getMergedValue(void 0,a):getMergedValue(void 0,b)}function mergeDirectKeys(a,b,prop){return prop in config2?getMergedValue(a,b):prop in config1?getMergedValue(void 0,a):void 0}const mergeMap={url:valueFromConfig2,method:valueFromConfig2,data:valueFromConfig2,baseURL:defaultToConfig2,transformRequest:defaultToConfig2,transformResponse:defaultToConfig2,paramsSerializer:defaultToConfig2,timeout:defaultToConfig2,timeoutMessage:defaultToConfig2,withCredentials:defaultToConfig2,withXSRFToken:defaultToConfig2,adapter:defaultToConfig2,responseType:defaultToConfig2,xsrfCookieName:defaultToConfig2,xsrfHeaderName:defaultToConfig2,onUploadProgress:defaultToConfig2,onDownloadProgress:defaultToConfig2,decompress:defaultToConfig2,maxContentLength:defaultToConfig2,maxBodyLength:defaultToConfig2,beforeRedirect:defaultToConfig2,transport:defaultToConfig2,httpAgent:defaultToConfig2,httpsAgent:defaultToConfig2,cancelToken:defaultToConfig2,socketPath:defaultToConfig2,responseEncoding:defaultToConfig2,validateStatus:mergeDirectKeys,headers:(a,b,prop)=>mergeDeepProperties(headersToObject(a),headersToObject(b),0,!0)};return utils$3.forEach(Object.keys({...config1,...config2}),function computeConfigValue(prop){if("__proto__"===prop||"constructor"===prop||"prototype"===prop)return;const merge=utils$3.hasOwnProp(mergeMap,prop)?mergeMap[prop]:mergeDeepProperties,configValue=merge(config1[prop],config2[prop],prop);utils$3.isUndefined(configValue)&&merge!==mergeDirectKeys||(config[prop]=configValue)}),config}var resolveConfig=config=>{const newConfig=mergeConfig$1({},config);let{data:data,withXSRFToken:withXSRFToken,xsrfHeaderName:xsrfHeaderName,xsrfCookieName:xsrfCookieName,headers:headers,auth:auth}=newConfig;if(newConfig.headers=headers=AxiosHeaders$1.from(headers),newConfig.url=buildURL(buildFullPath(newConfig.baseURL,newConfig.url,newConfig.allowAbsoluteUrls),config.params,config.paramsSerializer),auth&&headers.set("Authorization","Basic "+btoa((auth.username||"")+":"+(auth.password?unescape(encodeURIComponent(auth.password)):""))),utils$3.isFormData(data))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)headers.setContentType(void 0);else if(utils$3.isFunction(data.getHeaders)){const formHeaders=data.getHeaders(),allowedHeaders=["content-type","content-length"];Object.entries(formHeaders).forEach(([key,val])=>{allowedHeaders.includes(key.toLowerCase())&&headers.set(key,val)})}if(platform.hasStandardBrowserEnv&&(withXSRFToken&&utils$3.isFunction(withXSRFToken)&&(withXSRFToken=withXSRFToken(newConfig)),withXSRFToken||!1!==withXSRFToken&&isURLSameOrigin(newConfig.url))){const xsrfValue=xsrfHeaderName&&xsrfCookieName&&cookies.read(xsrfCookieName);xsrfValue&&headers.set(xsrfHeaderName,xsrfValue)}return newConfig};var xhrAdapter="undefined"!=typeof XMLHttpRequest&&function(config){return new Promise(function dispatchXhrRequest(resolve,reject){const _config=resolveConfig(config);let requestData=_config.data;const requestHeaders=AxiosHeaders$1.from(_config.headers).normalize();let onCanceled,uploadThrottled,downloadThrottled,flushUpload,flushDownload,{responseType:responseType,onUploadProgress:onUploadProgress,onDownloadProgress:onDownloadProgress}=_config;function done(){flushUpload&&flushUpload(),flushDownload&&flushDownload(),_config.cancelToken&&_config.cancelToken.unsubscribe(onCanceled),_config.signal&&_config.signal.removeEventListener("abort",onCanceled)}let request=new XMLHttpRequest;function onloadend(){if(!request)return;const responseHeaders=AxiosHeaders$1.from("getAllResponseHeaders"in request&&request.getAllResponseHeaders());settle(function _resolve(value){resolve(value),done()},function _reject(err){reject(err),done()},{data:responseType&&"text"!==responseType&&"json"!==responseType?request.response:request.responseText,status:request.status,statusText:request.statusText,headers:responseHeaders,config:config,request:request}),request=null}request.open(_config.method.toUpperCase(),_config.url,!0),request.timeout=_config.timeout,"onloadend"in request?request.onloadend=onloadend:request.onreadystatechange=function handleLoad(){request&&4===request.readyState&&(0!==request.status||request.responseURL&&0===request.responseURL.indexOf("file:"))&&setTimeout(onloadend)},request.onabort=function handleAbort(){request&&(reject(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,config,request)),request=null)},request.onerror=function handleError(event){const msg=event&&event.message?event.message:"Network Error",err=new AxiosError$1(msg,AxiosError$1.ERR_NETWORK,config,request);err.event=event||null,reject(err),request=null},request.ontimeout=function handleTimeout(){let timeoutErrorMessage=_config.timeout?"timeout of "+_config.timeout+"ms exceeded":"timeout exceeded";const transitional=_config.transitional||transitionalDefaults;_config.timeoutErrorMessage&&(timeoutErrorMessage=_config.timeoutErrorMessage),reject(new AxiosError$1(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,config,request)),request=null},void 0===requestData&&requestHeaders.setContentType(null),"setRequestHeader"in request&&utils$3.forEach(requestHeaders.toJSON(),function setRequestHeader(val,key){request.setRequestHeader(key,val)}),utils$3.isUndefined(_config.withCredentials)||(request.withCredentials=!!_config.withCredentials),responseType&&"json"!==responseType&&(request.responseType=_config.responseType),onDownloadProgress&&([downloadThrottled,flushDownload]=progressEventReducer(onDownloadProgress,!0),request.addEventListener("progress",downloadThrottled)),onUploadProgress&&request.upload&&([uploadThrottled,flushUpload]=progressEventReducer(onUploadProgress),request.upload.addEventListener("progress",uploadThrottled),request.upload.addEventListener("loadend",flushUpload)),(_config.cancelToken||_config.signal)&&(onCanceled=cancel=>{request&&(reject(!cancel||cancel.type?new CanceledError$1(null,config,request):cancel),request.abort(),request=null)},_config.cancelToken&&_config.cancelToken.subscribe(onCanceled),_config.signal&&(_config.signal.aborted?onCanceled():_config.signal.addEventListener("abort",onCanceled)));const protocol=parseProtocol(_config.url);protocol&&-1===platform.protocols.indexOf(protocol)?reject(new AxiosError$1("Unsupported protocol "+protocol+":",AxiosError$1.ERR_BAD_REQUEST,config)):request.send(requestData||null)})};const composeSignals=(signals,timeout)=>{const{length:length}=signals=signals?signals.filter(Boolean):[];if(timeout||length){let aborted,controller=new AbortController;const onabort=function(reason){if(!aborted){aborted=!0,unsubscribe();const err=reason instanceof Error?reason:this.reason;controller.abort(err instanceof AxiosError$1?err:new CanceledError$1(err instanceof Error?err.message:err))}};let timer=timeout&&setTimeout(()=>{timer=null,onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`,AxiosError$1.ETIMEDOUT))},timeout);const unsubscribe=()=>{signals&&(timer&&clearTimeout(timer),timer=null,signals.forEach(signal=>{signal.unsubscribe?signal.unsubscribe(onabort):signal.removeEventListener("abort",onabort)}),signals=null)};signals.forEach(signal=>signal.addEventListener("abort",onabort));const{signal:signal}=controller;return signal.unsubscribe=()=>utils$3.asap(unsubscribe),signal}},streamChunk=function*(chunk,chunkSize){let len=chunk.byteLength;if(len<chunkSize)return void(yield chunk);let end,pos=0;for(;pos<len;)end=pos+chunkSize,yield chunk.slice(pos,end),pos=end},readStream=async function*(stream){if(stream[Symbol.asyncIterator])return void(yield*stream);const reader=stream.getReader();try{for(;;){const{done:done,value:value}=await reader.read();if(done)break;yield value}}finally{await reader.cancel()}},trackStream=(stream,chunkSize,onProgress,onFinish)=>{const iterator=async function*(iterable,chunkSize){for await(const chunk of readStream(iterable))yield*streamChunk(chunk,chunkSize)}(stream,chunkSize);let done,bytes=0,_onFinish=e=>{done||(done=!0,onFinish&&onFinish(e))};return new ReadableStream({async pull(controller){try{const{done:done,value:value}=await iterator.next();if(done)return _onFinish(),void controller.close();let len=value.byteLength;if(onProgress){let loadedBytes=bytes+=len;onProgress(loadedBytes)}controller.enqueue(new Uint8Array(value))}catch(err){throw _onFinish(err),err}},cancel:reason=>(_onFinish(reason),iterator.return())},{highWaterMark:2})},{isFunction:isFunction}=utils$3,globalFetchAPI=(({Request:Request,Response:Response})=>({Request:Request,Response:Response}))(utils$3.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$3.global,test=(fn,...args)=>{try{return!!fn(...args)}catch(e){return!1}},factory=env=>{env=utils$3.merge.call({skipUndefined:!0},globalFetchAPI,env);const{fetch:envFetch,Request:Request,Response:Response}=env,isFetchSupported=envFetch?isFunction(envFetch):"function"==typeof fetch,isRequestSupported=isFunction(Request),isResponseSupported=isFunction(Response);if(!isFetchSupported)return!1;const isReadableStreamSupported=isFetchSupported&&isFunction(ReadableStream$1),encodeText=isFetchSupported&&("function"==typeof TextEncoder$1?(encoder=new TextEncoder$1,str=>encoder.encode(str)):async str=>new Uint8Array(await new Request(str).arrayBuffer()));var encoder;const supportsRequestStream=isRequestSupported&&isReadableStreamSupported&&test(()=>{let duplexAccessed=!1;const hasContentType=new Request(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return duplexAccessed=!0,"half"}}).headers.has("Content-Type");return duplexAccessed&&!hasContentType}),supportsResponseStream=isResponseSupported&&isReadableStreamSupported&&test(()=>utils$3.isReadableStream(new Response("").body)),resolvers={stream:supportsResponseStream&&(res=>res.body)};isFetchSupported&&["text","arrayBuffer","blob","formData","stream"].forEach(type=>{!resolvers[type]&&(resolvers[type]=(res,config)=>{let method=res&&res[type];if(method)return method.call(res);throw new AxiosError$1(`Response type '${type}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,config)})});const resolveBodyLength=async(headers,body)=>{const length=utils$3.toFiniteNumber(headers.getContentLength());return null==length?(async body=>{if(null==body)return 0;if(utils$3.isBlob(body))return body.size;if(utils$3.isSpecCompliantForm(body)){const _request=new Request(platform.origin,{method:"POST",body:body});return(await _request.arrayBuffer()).byteLength}return utils$3.isArrayBufferView(body)||utils$3.isArrayBuffer(body)?body.byteLength:(utils$3.isURLSearchParams(body)&&(body+=""),utils$3.isString(body)?(await encodeText(body)).byteLength:void 0)})(body):length};return async config=>{let{url:url,method:method,data:data,signal:signal,cancelToken:cancelToken,timeout:timeout,onDownloadProgress:onDownloadProgress,onUploadProgress:onUploadProgress,responseType:responseType,headers:headers,withCredentials:withCredentials="same-origin",fetchOptions:fetchOptions}=resolveConfig(config),_fetch=envFetch||fetch;responseType=responseType?(responseType+"").toLowerCase():"text";let composedSignal=composeSignals([signal,cancelToken&&cancelToken.toAbortSignal()],timeout),request=null;const unsubscribe=composedSignal&&composedSignal.unsubscribe&&(()=>{composedSignal.unsubscribe()});let requestContentLength;try{if(onUploadProgress&&supportsRequestStream&&"get"!==method&&"head"!==method&&0!==(requestContentLength=await resolveBodyLength(headers,data))){let contentTypeHeader,_request=new Request(url,{method:"POST",body:data,duplex:"half"});if(utils$3.isFormData(data)&&(contentTypeHeader=_request.headers.get("content-type"))&&headers.setContentType(contentTypeHeader),_request.body){const[onProgress,flush]=progressEventDecorator(requestContentLength,progressEventReducer(asyncDecorator(onUploadProgress)));data=trackStream(_request.body,65536,onProgress,flush)}}utils$3.isString(withCredentials)||(withCredentials=withCredentials?"include":"omit");const isCredentialsSupported=isRequestSupported&&"credentials"in Request.prototype,resolvedOptions={...fetchOptions,signal:composedSignal,method:method.toUpperCase(),headers:headers.normalize().toJSON(),body:data,duplex:"half",credentials:isCredentialsSupported?withCredentials:void 0};request=isRequestSupported&&new Request(url,resolvedOptions);let response=await(isRequestSupported?_fetch(request,fetchOptions):_fetch(url,resolvedOptions));const isStreamResponse=supportsResponseStream&&("stream"===responseType||"response"===responseType);if(supportsResponseStream&&(onDownloadProgress||isStreamResponse&&unsubscribe)){const options={};["status","statusText","headers"].forEach(prop=>{options[prop]=response[prop]});const responseContentLength=utils$3.toFiniteNumber(response.headers.get("content-length")),[onProgress,flush]=onDownloadProgress&&progressEventDecorator(responseContentLength,progressEventReducer(asyncDecorator(onDownloadProgress),!0))||[];response=new Response(trackStream(response.body,65536,onProgress,()=>{flush&&flush(),unsubscribe&&unsubscribe()}),options)}responseType=responseType||"text";let responseData=await resolvers[utils$3.findKey(resolvers,responseType)||"text"](response,config);return!isStreamResponse&&unsubscribe&&unsubscribe(),await new Promise((resolve,reject)=>{settle(resolve,reject,{data:responseData,headers:AxiosHeaders$1.from(response.headers),status:response.status,statusText:response.statusText,config:config,request:request})})}catch(err){if(unsubscribe&&unsubscribe(),err&&"TypeError"===err.name&&/Load failed|fetch/i.test(err.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,config,request,err&&err.response),{cause:err.cause||err});throw AxiosError$1.from(err,err&&err.code,config,request,err&&err.response)}}},seedCache=new Map,getFetch=config=>{let env=config&&config.env||{};const{fetch:fetch,Request:Request,Response:Response}=env,seeds=[Request,Response,fetch];let seed,target,i=seeds.length,map=seedCache;for(;i--;)seed=seeds[i],target=map.get(seed),void 0===target&&map.set(seed,target=i?new Map:factory(env)),map=target;return target};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$3.forEach(knownAdapters,(fn,value)=>{if(fn){try{Object.defineProperty(fn,"name",{value:value})}catch(e){}Object.defineProperty(fn,"adapterName",{value:value})}});const renderReason=reason=>`- ${reason}`,isResolvedHandle=adapter=>utils$3.isFunction(adapter)||null===adapter||!1===adapter;var adapters={getAdapter:function getAdapter$1(adapters,config){adapters=utils$3.isArray(adapters)?adapters:[adapters];const{length:length}=adapters;let nameOrAdapter,adapter;const rejectedReasons={};for(let i=0;i<length;i++){let id;if(nameOrAdapter=adapters[i],adapter=nameOrAdapter,!isResolvedHandle(nameOrAdapter)&&(adapter=knownAdapters[(id=String(nameOrAdapter)).toLowerCase()],void 0===adapter))throw new AxiosError$1(`Unknown adapter '${id}'`);if(adapter&&(utils$3.isFunction(adapter)||(adapter=adapter.get(config))))break;rejectedReasons[id||"#"+i]=adapter}if(!adapter){const reasons=Object.entries(rejectedReasons).map(([id,state])=>`adapter ${id} `+(!1===state?"is not supported by the environment":"is not available in the build"));let s=length?reasons.length>1?"since :\n"+reasons.map(renderReason).join("\n"):" "+renderReason(reasons[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return adapter},adapters:knownAdapters};function throwIfCancellationRequested(config){if(config.cancelToken&&config.cancelToken.throwIfRequested(),config.signal&&config.signal.aborted)throw new CanceledError$1(null,config)}function dispatchRequest(config){throwIfCancellationRequested(config),config.headers=AxiosHeaders$1.from(config.headers),config.data=transformData.call(config,config.transformRequest),-1!==["post","put","patch"].indexOf(config.method)&&config.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(config.adapter||defaults.adapter,config)(config).then(function onAdapterResolution(response){return throwIfCancellationRequested(config),response.data=transformData.call(config,config.transformResponse,response),response.headers=AxiosHeaders$1.from(response.headers),response},function onAdapterRejection(reason){return isCancel$1(reason)||(throwIfCancellationRequested(config),reason&&reason.response&&(reason.response.data=transformData.call(config,config.transformResponse,reason.response),reason.response.headers=AxiosHeaders$1.from(reason.response.headers))),Promise.reject(reason)})}const validators$1={};["object","boolean","number","function","string","symbol"].forEach((type,i)=>{validators$1[type]=function validator(thing){return typeof thing===type||"a"+(i<1?"n ":" ")+type}});const deprecatedWarnings={};validators$1.transitional=function transitional(validator,version,message){function formatMessage(opt,desc){return"[Axios v1.13.6] Transitional option '"+opt+"'"+desc+(message?". "+message:"")}return(value,opt,opts)=>{if(!1===validator)throw new AxiosError$1(formatMessage(opt," has been removed"+(version?" in "+version:"")),AxiosError$1.ERR_DEPRECATED);return version&&!deprecatedWarnings[opt]&&(deprecatedWarnings[opt]=!0,console.warn(formatMessage(opt," has been deprecated since v"+version+" and will be removed in the near future"))),!validator||validator(value,opt,opts)}},validators$1.spelling=function spelling(correctSpelling){return(value,opt)=>(console.warn(`${opt} is likely a misspelling of ${correctSpelling}`),!0)};var validator={assertOptions:function assertOptions(options,schema,allowUnknown){if("object"!=typeof options)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const keys=Object.keys(options);let i=keys.length;for(;i-- >0;){const opt=keys[i],validator=schema[opt];if(validator){const value=options[opt],result=void 0===value||validator(value,opt,options);if(!0!==result)throw new AxiosError$1("option "+opt+" must be "+result,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(!0!==allowUnknown)throw new AxiosError$1("Unknown option "+opt,AxiosError$1.ERR_BAD_OPTION)}},validators:validators$1};const validators=validator.validators;let Axios$1=class Axios{constructor(instanceConfig){this.defaults=instanceConfig||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(configOrUrl,config){try{return await this._request(configOrUrl,config)}catch(err){if(err instanceof Error){let dummy={};Error.captureStackTrace?Error.captureStackTrace(dummy):dummy=new Error;const stack=dummy.stack?dummy.stack.replace(/^.+\n/,""):"";try{err.stack?stack&&!String(err.stack).endsWith(stack.replace(/^.+\n.+\n/,""))&&(err.stack+="\n"+stack):err.stack=stack}catch(e){}}throw err}}_request(configOrUrl,config){"string"==typeof configOrUrl?(config=config||{}).url=configOrUrl:config=configOrUrl||{},config=mergeConfig$1(this.defaults,config);const{transitional:transitional,paramsSerializer:paramsSerializer,headers:headers}=config;void 0!==transitional&&validator.assertOptions(transitional,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean)},!1),null!=paramsSerializer&&(utils$3.isFunction(paramsSerializer)?config.paramsSerializer={serialize:paramsSerializer}:validator.assertOptions(paramsSerializer,{encode:validators.function,serialize:validators.function},!0)),void 0!==config.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?config.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:config.allowAbsoluteUrls=!0),validator.assertOptions(config,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),config.method=(config.method||this.defaults.method||"get").toLowerCase();let contextHeaders=headers&&utils$3.merge(headers.common,headers[config.method]);headers&&utils$3.forEach(["delete","get","head","post","put","patch","common"],method=>{delete headers[method]}),config.headers=AxiosHeaders$1.concat(contextHeaders,headers);const requestInterceptorChain=[];let synchronousRequestInterceptors=!0;this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor){if("function"==typeof interceptor.runWhen&&!1===interceptor.runWhen(config))return;synchronousRequestInterceptors=synchronousRequestInterceptors&&interceptor.synchronous;const transitional=config.transitional||transitionalDefaults;transitional&&transitional.legacyInterceptorReqResOrdering?requestInterceptorChain.unshift(interceptor.fulfilled,interceptor.rejected):requestInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)});const responseInterceptorChain=[];let promise;this.interceptors.response.forEach(function pushResponseInterceptors(interceptor){responseInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)});let len,i=0;if(!synchronousRequestInterceptors){const chain=[dispatchRequest.bind(this),void 0];for(chain.unshift(...requestInterceptorChain),chain.push(...responseInterceptorChain),len=chain.length,promise=Promise.resolve(config);i<len;)promise=promise.then(chain[i++],chain[i++]);return promise}len=requestInterceptorChain.length;let newConfig=config;for(;i<len;){const onFulfilled=requestInterceptorChain[i++],onRejected=requestInterceptorChain[i++];try{newConfig=onFulfilled(newConfig)}catch(error){onRejected.call(this,error);break}}try{promise=dispatchRequest.call(this,newConfig)}catch(error){return Promise.reject(error)}for(i=0,len=responseInterceptorChain.length;i<len;)promise=promise.then(responseInterceptorChain[i++],responseInterceptorChain[i++]);return promise}getUri(config){return buildURL(buildFullPath((config=mergeConfig$1(this.defaults,config)).baseURL,config.url,config.allowAbsoluteUrls),config.params,config.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function forEachMethodNoData(method){Axios$1.prototype[method]=function(url,config){return this.request(mergeConfig$1(config||{},{method:method,url:url,data:(config||{}).data}))}}),utils$3.forEach(["post","put","patch"],function forEachMethodWithData(method){function generateHTTPMethod(isForm){return function httpMethod(url,data,config){return this.request(mergeConfig$1(config||{},{method:method,headers:isForm?{"Content-Type":"multipart/form-data"}:{},url:url,data:data}))}}Axios$1.prototype[method]=generateHTTPMethod(),Axios$1.prototype[method+"Form"]=generateHTTPMethod(!0)});const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(HttpStatusCode$1).forEach(([key,value])=>{HttpStatusCode$1[value]=key});const axios=function createInstance(defaultConfig){const context=new Axios$1(defaultConfig),instance=bind(Axios$1.prototype.request,context);return utils$3.extend(instance,Axios$1.prototype,context,{allOwnKeys:!0}),utils$3.extend(instance,context,null,{allOwnKeys:!0}),instance.create=function create(instanceConfig){return createInstance(mergeConfig$1(defaultConfig,instanceConfig))},instance}(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=class CancelToken{constructor(executor){if("function"!=typeof executor)throw new TypeError("executor must be a function.");let resolvePromise;this.promise=new Promise(function promiseExecutor(resolve){resolvePromise=resolve});const token=this;this.promise.then(cancel=>{if(!token._listeners)return;let i=token._listeners.length;for(;i-- >0;)token._listeners[i](cancel);token._listeners=null}),this.promise.then=onfulfilled=>{let _resolve;const promise=new Promise(resolve=>{token.subscribe(resolve),_resolve=resolve}).then(onfulfilled);return promise.cancel=function reject(){token.unsubscribe(_resolve)},promise},executor(function cancel(message,config,request){token.reason||(token.reason=new CanceledError$1(message,config,request),resolvePromise(token.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(listener){this.reason?listener(this.reason):this._listeners?this._listeners.push(listener):this._listeners=[listener]}unsubscribe(listener){if(!this._listeners)return;const index=this._listeners.indexOf(listener);-1!==index&&this._listeners.splice(index,1)}toAbortSignal(){const controller=new AbortController,abort=err=>{controller.abort(err)};return this.subscribe(abort),controller.signal.unsubscribe=()=>this.unsubscribe(abort),controller.signal}static source(){let cancel;return{token:new CancelToken(function executor(c){cancel=c}),cancel:cancel}}},axios.isCancel=isCancel$1,axios.VERSION="1.13.6",axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function all(promises){return Promise.all(promises)},axios.spread=function spread$1(callback){return function wrap(arr){return callback.apply(null,arr)}},axios.isAxiosError=function isAxiosError$1(payload){return utils$3.isObject(payload)&&!0===payload.isAxiosError},axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=thing=>formDataToJSON(utils$3.isHTMLForm(thing)?new FormData(thing):thing),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig}=axios;const apiService=new class ApiService{constructor(){this.client=axios.create({timeout:3e4,headers:{"Content-Type":"application/json","User-Agent":"buildx-cli/1.0.0"}}),this.client.interceptors.request.use(config=>{this.initializeClient();const apiConfig=configManager.getApiConfig();(null==apiConfig?void 0:apiConfig.apiKey)&&(config.headers["X-API-Key"]=apiConfig.apiKey);const auth=configManager.getAuth();return(null==auth?void 0:auth.token)&&(config.headers.Authorization=`Bearer ${auth.token}`),config}),this.client.interceptors.response.use(response=>response,error=>{var _a;if(401===(null==(_a=error.response)?void 0:_a.status))throw configManager.clearAuth(),new Error("Authentication failed. Please login again.");throw error})}initializeClient(){const apiConfig=configManager.getApiConfig();if(!(null==apiConfig?void 0:apiConfig.endpoint))throw new Error("API endpoint not configured. Please run 'buildx config setup' first.");this.client.defaults.baseURL=apiConfig.endpoint}async request(config){var _a;const apiConfig=configManager.getApiConfig();if(!(null==apiConfig?void 0:apiConfig.endpoint))throw new Error("API endpoint not configured. Please run 'buildx config setup' first.");config.baseURL=apiConfig.endpoint;try{const response=await this.client.request(config);if(response.data.error)throw response.data.message?new Error(`${response.data.error} (${response.data.message})`):new Error(response.data.error);return{data:response.data,status:response.status,message:response.statusText}}catch(error){throw error.response?new Error(`API Error: ${error.response.status} - ${(null==(_a=error.response.data)?void 0:_a.message)||error.response.statusText}`):error.request?new Error("Network error: Unable to connect to the API"):new Error(`Request error: ${error.message}`)}}async login(credentials){return(await this.request({method:"POST",url:"/auth/login",data:credentials})).data}async getProjects(){return(await this.request({method:"GET",url:"/projects"})).data}async getSchema(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/collections/schema`})).data}async getCollections(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/collections`})).data}async upsertCollection(projectId,collection){return(await this.request({method:"POST",url:`/project/${projectId}/collections`,data:collection})).data}async getFunctionContextSchema(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/functions/context/schema`})).data}async getFunctionContextSchemaInfo(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/functions/context/schema/info`})).data}async listFunctions(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/functions`})).data}async getFunction(projectId,functionName){return(await this.request({method:"GET",url:`/project/${projectId}/functions/${encodeURIComponent(functionName)}`})).data}async upsertFunction(projectId,functionName,payload){return(await this.request({method:"POST",url:`/project/${projectId}/functions/${encodeURIComponent(functionName)}`,data:payload})).data}async getMe(){return(await this.request({method:"GET",url:"/auth/me"})).data}setBaseUrl(baseUrl){this.client.defaults.baseURL=baseUrl}getBaseUrl(){return this.client.defaults.baseURL||""}isConfigured(){return configManager.isApiConfigured()}},loginCommand=new Command("auth:login").description("Authenticate with BuildX API").option("-t, --token <token>","API token for authentication").option("-u, --username <username>","Username for authentication").option("-p, --password <password>","Password for authentication").option("-i, --interactive","Interactive login mode").action(async options=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config setup")),process.exit(1));let token=options.token,username=options.username,password=options.password;if(!token&&!username&&!password){if("credentials"===(await inquirer.prompt([{type:"list",name:"authMethod",message:"Choose authentication method:",choices:[{name:"Username & Password",value:"credentials"},{name:"API Token",value:"token"}]}])).authMethod){const credentialAnswers=await inquirer.prompt([{type:"input",name:"username",message:"Enter your username:",validate:input=>!(!input||0===input.trim().length)||"Username is required"},{type:"password",name:"password",message:"Enter your password:",validate:input=>!(!input||0===input.trim().length)||"Password is required"}]);username=credentialAnswers.username,password=credentialAnswers.password}else{token=(await inquirer.prompt([{type:"password",name:"token",message:"Enter your API token:",validate:input=>!(!input||0===input.trim().length)||"Token is required"}])).token}}const spinner=ora("Authenticating...").start();try{if(!username||!password){const credentialAnswers=await inquirer.prompt([{type:"input",name:"username",message:"Enter your username:",validate:input=>!(!input||0===input.trim().length)||"Username is required"},{type:"password",name:"password",message:"Enter your password:",validate:input=>!(!input||0===input.trim().length)||"Password is required"}]);username=credentialAnswers.username,password=credentialAnswers.password}const loginResponse=await apiService.login({username:username,password:password});let authToken=loginResponse.token,expiresAt=loginResponse.expiresAt;username=username??"",authToken=authToken??"",expiresAt=expiresAt??new Date(Date.now()+2592e6).toISOString(),configManager.setAuth({token:authToken,expiresAt:expiresAt,username:username}),spinner.succeed("Successfully authenticated!"),console.log(chalk.green("✓ Authentication stored securely")),console.log(chalk.blue("You can now use other BuildX CLI commands"))}catch(error){spinner.fail("Authentication failed"),console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),logoutCommand=new Command("auth:logout").description("Logout and clear stored authentication").action(()=>{try{configManager.clearAuth(),console.log(chalk.green("✓ Successfully logged out")),console.log(chalk.blue("Authentication token has been cleared"))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),authStatusCommand=new Command("auth:status").description("Check authentication status").action(async()=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config setup")),process.exit(1));const isAuthenticated=configManager.isAuthenticated(),auth=configManager.getAuth();if(isAuthenticated&&auth){const spinner=ora("Validating session...").start();try{const me=await apiService.getMe();spinner.succeed("Authenticated"),console.log(chalk.green("✓ Authenticated")),console.log(chalk.blue("Username:"),me.username),auth.token&&console.log(chalk.blue("Token:"),auth.token.substring(0,8)+"..."),auth.expiresAt&&console.log(chalk.blue("Expires:"),new Date(auth.expiresAt).toLocaleString()),me.username&&console.log(chalk.blue(`You are authenticated as ${me.source}:${me.username}`))}catch(error){spinner.fail("Session invalid"),console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}else console.log(chalk.red("✗ Not authenticated")),console.log(chalk.yellow('Run "buildx login" to authenticate'))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}});var hasRequiredUniversalify,polyfills,hasRequiredPolyfills,legacyStreams,hasRequiredLegacyStreams,clone_1,hasRequiredClone,gracefulFs,hasRequiredGracefulFs,hasRequiredFs,fs$1={},universalify={};function requireUniversalify(){return hasRequiredUniversalify||(hasRequiredUniversalify=1,universalify.fromCallback=function(fn){return Object.defineProperty(function(...args){if("function"!=typeof args[args.length-1])return new Promise((resolve,reject)=>{args.push((err,res)=>null!=err?reject(err):resolve(res)),fn.apply(this,args)});fn.apply(this,args)},"name",{value:fn.name})},universalify.fromPromise=function(fn){return Object.defineProperty(function(...args){const cb=args[args.length-1];if("function"!=typeof cb)return fn.apply(this,args);args.pop(),fn.apply(this,args).then(r=>cb(null,r),cb)},"name",{value:fn.name})}),universalify}function requirePolyfills(){if(hasRequiredPolyfills)return polyfills;hasRequiredPolyfills=1;var constants=require$$0$b,origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch(er){}if("function"==typeof process.chdir){var chdir=process.chdir;process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir)}return polyfills=function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&function patchLchmod(fs){fs.lchmod=function(path,mode,callback){fs.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){err?callback&&callback(err):fs.fchmod(fd,mode,function(err){fs.close(fd,function(err2){callback&&callback(err||err2)})})})},fs.lchmodSync=function(path,mode){var ret,fd=fs.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0;try{ret=fs.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}}(fs);fs.lutimes||function patchLutimes(fs){constants.hasOwnProperty("O_SYMLINK")&&fs.futimes?(fs.lutimes=function(path,at,mt,cb){fs.open(path,constants.O_SYMLINK,function(er,fd){er?cb&&cb(er):fs.futimes(fd,at,mt,function(er){fs.close(fd,function(er2){cb&&cb(er||er2)})})})},fs.lutimesSync=function(path,at,mt){var ret,fd=fs.openSync(path,constants.O_SYMLINK),threw=!0;try{ret=fs.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}):fs.futimes&&(fs.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs.lutimesSync=function(){})}(fs);fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){});fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){});"win32"===platform&&(fs.rename="function"!=typeof fs.rename?fs.rename:function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&("EACCES"===er.code||"EPERM"===er.code||"EBUSY"===er.code)&&Date.now()-start<6e4)return setTimeout(function(){fs.stat(to,function(stater,st){stater&&"ENOENT"===stater.code?fs$rename(from,to,CB):cb(er)})},backoff),void(backoff<100&&(backoff+=10));cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename}(fs.rename));function chmodFix(orig){return orig?function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chmodFixSync(orig){return orig?function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}:orig}function chownFix(orig){return orig?function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chownFixSync(orig){return orig?function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}:orig}function statFix(orig){return orig?function(target,options,cb){function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return"function"==typeof options&&(cb=options,options=null),options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}:orig}function statFixSync(orig){return orig?function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}:orig}function chownErOk(er){return!er||("ENOSYS"===er.code||!(process.getuid&&0===process.getuid()||"EINVAL"!==er.code&&"EPERM"!==er.code))}fs.read="function"!=typeof fs.read?fs.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&"function"==typeof callback_){var eagCounter=0;callback=function(er,_,__){if(er&&"EAGAIN"===er.code&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read}(fs.read),fs.readSync="function"!=typeof fs.readSync?fs.readSync:(fs$readSync=fs.readSync,function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if("EAGAIN"===er.code&&eagCounter<10){eagCounter++;continue}throw er}});var fs$readSync},polyfills}function requireGracefulFs(){if(hasRequiredGracefulFs)return gracefulFs;hasRequiredGracefulFs=1;var gracefulQueue,previousSymbol,fs=fs$2,polyfills=requirePolyfills(),legacy=function requireLegacyStreams(){if(hasRequiredLegacyStreams)return legacyStreams;hasRequiredLegacyStreams=1;var Stream=stream$1.Stream;return legacyStreams=function legacy(fs){return{ReadStream:function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),void 0!==this.start){if("number"!=typeof this.start)throw TypeError("start must be a Number");if(void 0===this.end)this.end=1/0;else if("number"!=typeof this.end)throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}null===this.fd?fs.open(this.path,this.flags,this.mode,function(err,fd){if(err)return self.emit("error",err),void(self.readable=!1);self.fd=fd,self.emit("open",fd),self._read()}):process.nextTick(function(){self._read()})},WriteStream:function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(void 0!==this.start){if("number"!=typeof this.start)throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],null===this.fd&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}},legacyStreams}(),clone=function requireClone(){if(hasRequiredClone)return clone_1;hasRequiredClone=1,clone_1=function clone(obj){if(null===obj||"object"!=typeof obj)return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy};var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};return clone_1}(),util=require$$1$3;function publishQueue(context,queue){Object.defineProperty(context,gracefulQueue,{get:function(){return queue}})}"function"==typeof Symbol&&"function"==typeof Symbol.for?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");var retryTimer,debug=function noop(){};if(util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join("\nGFS4: "),console.error(m)}),!fs[gracefulQueue]){var queue=commonjsGlobal[gracefulQueue]||[];publishQueue(fs,queue),fs.close=function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),"function"==typeof cb&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs.close),fs.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),require$$0$7.equal(fs[gracefulQueue].length,0)})}function patch(fs){polyfills(fs),fs.gracefulify=patch,fs.createReadStream=function createReadStream(path,options){return new fs.ReadStream(path,options)},fs.createWriteStream=function createWriteStream(path,options){return new fs.WriteStream(path,options)};var fs$readFile=fs.readFile;fs.readFile=function readFile(path,options,cb){"function"==typeof options&&(cb=options,options=null);return function go$readFile(path,options,cb,startTime){return fs$readFile(path,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$readFile,[path,options,cb],err,startTime||Date.now(),Date.now()])})}(path,options,cb)};var fs$writeFile=fs.writeFile;fs.writeFile=function writeFile(path,data,options,cb){"function"==typeof options&&(cb=options,options=null);return function go$writeFile(path,data,options,cb,startTime){return fs$writeFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$writeFile,[path,data,options,cb],err,startTime||Date.now(),Date.now()])})}(path,data,options,cb)};var fs$appendFile=fs.appendFile;fs$appendFile&&(fs.appendFile=function appendFile(path,data,options,cb){"function"==typeof options&&(cb=options,options=null);return function go$appendFile(path,data,options,cb,startTime){return fs$appendFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$appendFile,[path,data,options,cb],err,startTime||Date.now(),Date.now()])})}(path,data,options,cb)});var fs$copyFile=fs.copyFile;fs$copyFile&&(fs.copyFile=function copyFile(src,dest,flags,cb){"function"==typeof flags&&(cb=flags,flags=0);return function go$copyFile(src,dest,flags,cb,startTime){return fs$copyFile(src,dest,flags,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$copyFile,[src,dest,flags,cb],err,startTime||Date.now(),Date.now()])})}(src,dest,flags,cb)});var fs$readdir=fs.readdir;fs.readdir=function readdir(path,options,cb){"function"==typeof options&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function go$readdir(path,options,cb,startTime){return fs$readdir(path,fs$readdirCallback(path,options,cb,startTime))}:function go$readdir(path,options,cb,startTime){return fs$readdir(path,options,fs$readdirCallback(path,options,cb,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path,options,cb,startTime){return function(err,files){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?(files&&files.sort&&files.sort(),"function"==typeof cb&&cb.call(this,err,files)):enqueue([go$readdir,[path,options,cb],err,startTime||Date.now(),Date.now()])}}};var noReaddirOptionVersions=/^v[0-5]\./;if("v0.8"===process.version.substr(0,4)){var legStreams=legacy(fs);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})});var fs$WriteStream=fs.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}),Object.defineProperty(fs,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}Object.defineProperty(fs,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});var fs$open=fs.open;function open(path,flags,mode,cb){return"function"==typeof mode&&(cb=mode,mode=null),function go$open(path,flags,mode,cb,startTime){return fs$open(path,flags,mode,function(err,fd){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$open,[path,flags,mode,cb],err,startTime||Date.now(),Date.now()])})}(path,flags,mode,cb)}return fs.open=open,fs}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,0!==fs[gracefulQueue].length){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(void 0===startTime)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();"function"==typeof cb&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1);sinceAttempt>=Math.min(1.2*sinceStart,100)?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}void 0===retryTimer&&(retryTimer=setTimeout(retry,0))}}return commonjsGlobal[gracefulQueue]||publishQueue(commonjsGlobal,fs[gracefulQueue]),gracefulFs=patch(clone(fs)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(gracefulFs=patch(fs),fs.__patched=!0),gracefulFs}function requireFs(){return hasRequiredFs||(hasRequiredFs=1,function(exports$1){const u=requireUniversalify().fromCallback,fs=requireGracefulFs(),api=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(key=>"function"==typeof fs[key]);Object.assign(exports$1,fs),api.forEach(method=>{exports$1[method]=u(fs[method])}),exports$1.exists=function(filename,callback){return"function"==typeof callback?fs.exists(filename,callback):new Promise(resolve=>fs.exists(filename,resolve))},exports$1.read=function(fd,buffer,offset,length,position,callback){return"function"==typeof callback?fs.read(fd,buffer,offset,length,position,callback):new Promise((resolve,reject)=>{fs.read(fd,buffer,offset,length,position,(err,bytesRead,buffer)=>{if(err)return reject(err);resolve({bytesRead:bytesRead,buffer:buffer})})})},exports$1.write=function(fd,buffer,...args){return"function"==typeof args[args.length-1]?fs.write(fd,buffer,...args):new Promise((resolve,reject)=>{fs.write(fd,buffer,...args,(err,bytesWritten,buffer)=>{if(err)return reject(err);resolve({bytesWritten:bytesWritten,buffer:buffer})})})},exports$1.readv=function(fd,buffers,...args){return"function"==typeof args[args.length-1]?fs.readv(fd,buffers,...args):new Promise((resolve,reject)=>{fs.readv(fd,buffers,...args,(err,bytesRead,buffers)=>{if(err)return reject(err);resolve({bytesRead:bytesRead,buffers:buffers})})})},exports$1.writev=function(fd,buffers,...args){return"function"==typeof args[args.length-1]?fs.writev(fd,buffers,...args):new Promise((resolve,reject)=>{fs.writev(fd,buffers,...args,(err,bytesWritten,buffers)=>{if(err)return reject(err);resolve({bytesWritten:bytesWritten,buffers:buffers})})})},"function"==typeof fs.realpath.native?exports$1.realpath.native=u(fs.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")}(fs$1)),fs$1}var hasRequiredUtils$1,hasRequiredMakeDir,mkdirs,hasRequiredMkdirs,pathExists_1,hasRequiredPathExists,utimes,hasRequiredUtimes,stat,hasRequiredStat,async,hasRequiredAsync,copy_1,hasRequiredCopy$1,copySync_1,hasRequiredCopySync,copy,hasRequiredCopy,remove_1,hasRequiredRemove,empty,hasRequiredEmpty,file,hasRequiredFile,link,hasRequiredLink,symlinkPaths_1,hasRequiredSymlinkPaths,symlinkType_1,hasRequiredSymlinkType,symlink,hasRequiredSymlink,ensure,hasRequiredEnsure,utils,hasRequiredUtils,jsonfile$1,hasRequiredJsonfile$1,jsonfile,hasRequiredJsonfile,outputFile_1,hasRequiredOutputFile,outputJson_1,hasRequiredOutputJson,outputJsonSync_1,hasRequiredOutputJsonSync,json,hasRequiredJson,move_1,hasRequiredMove$1,moveSync_1,hasRequiredMoveSync,move,hasRequiredMove,lib,hasRequiredLib,makeDir={},utils$1={};function requireMakeDir(){if(hasRequiredMakeDir)return makeDir;hasRequiredMakeDir=1;const fs=requireFs(),{checkPath:checkPath}=function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;hasRequiredUtils$1=1;const path$1=path;return utils$1.checkPath=function checkPath(pth){if("win32"===process.platform&&/[<>:"|?*]/.test(pth.replace(path$1.parse(pth).root,""))){const error=new Error(`Path contains invalid characters: ${pth}`);throw error.code="EINVAL",error}},utils$1}(),getMode=options=>"number"==typeof options?options:{mode:511,...options}.mode;return makeDir.makeDir=async(dir,options)=>(checkPath(dir),fs.mkdir(dir,{mode:getMode(options),recursive:!0})),makeDir.makeDirSync=(dir,options)=>(checkPath(dir),fs.mkdirSync(dir,{mode:getMode(options),recursive:!0})),makeDir}function requireMkdirs(){if(hasRequiredMkdirs)return mkdirs;hasRequiredMkdirs=1;const u=requireUniversalify().fromPromise,{makeDir:_makeDir,makeDirSync:makeDirSync}=requireMakeDir(),makeDir=u(_makeDir);return mkdirs={mkdirs:makeDir,mkdirsSync:makeDirSync,mkdirp:makeDir,mkdirpSync:makeDirSync,ensureDir:makeDir,ensureDirSync:makeDirSync}}function requirePathExists(){if(hasRequiredPathExists)return pathExists_1;hasRequiredPathExists=1;const u=requireUniversalify().fromPromise,fs=requireFs();return pathExists_1={pathExists:u(function pathExists(path){return fs.access(path).then(()=>!0).catch(()=>!1)}),pathExistsSync:fs.existsSync},pathExists_1}function requireUtimes(){if(hasRequiredUtimes)return utimes;hasRequiredUtimes=1;const fs=requireFs(),u=requireUniversalify().fromPromise;return utimes={utimesMillis:u(async function utimesMillis(path,atime,mtime){const fd=await fs.open(path,"r+");let closeErr=null;try{await fs.futimes(fd,atime,mtime)}finally{try{await fs.close(fd)}catch(e){closeErr=e}}if(closeErr)throw closeErr}),utimesMillisSync:function utimesMillisSync(path,atime,mtime){const fd=fs.openSync(path,"r+");return fs.futimesSync(fd,atime,mtime),fs.closeSync(fd)}},utimes}function requireStat(){if(hasRequiredStat)return stat;hasRequiredStat=1;const fs=requireFs(),path$1=path,u=requireUniversalify().fromPromise;function areIdentical(srcStat,destStat){return void 0!==destStat.ino&&void 0!==destStat.dev&&destStat.ino===srcStat.ino&&destStat.dev===srcStat.dev}function isSrcSubdir(src,dest){const srcArr=path$1.resolve(src).split(path$1.sep).filter(i=>i),destArr=path$1.resolve(dest).split(path$1.sep).filter(i=>i);return srcArr.every((cur,i)=>destArr[i]===cur)}function errMsg(src,dest,funcName){return`Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`}return stat={checkPaths:u(async function checkPaths(src,dest,funcName,opts){const{srcStat:srcStat,destStat:destStat}=await function getStats(src,dest,opts){const statFunc=opts.dereference?file=>fs.stat(file,{bigint:!0}):file=>fs.lstat(file,{bigint:!0});return Promise.all([statFunc(src),statFunc(dest).catch(err=>{if("ENOENT"===err.code)return null;throw err})]).then(([srcStat,destStat])=>({srcStat:srcStat,destStat:destStat}))}(src,dest,opts);if(destStat){if(areIdentical(srcStat,destStat)){const srcBaseName=path$1.basename(src),destBaseName=path$1.basename(dest);if("move"===funcName&&srcBaseName!==destBaseName&&srcBaseName.toLowerCase()===destBaseName.toLowerCase())return{srcStat:srcStat,destStat:destStat,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(srcStat.isDirectory()&&!destStat.isDirectory())throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);if(!srcStat.isDirectory()&&destStat.isDirectory())throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)}if(srcStat.isDirectory()&&isSrcSubdir(src,dest))throw new Error(errMsg(src,dest,funcName));return{srcStat:srcStat,destStat:destStat}}),checkPathsSync:function checkPathsSync(src,dest,funcName,opts){const{srcStat:srcStat,destStat:destStat}=function getStatsSync(src,dest,opts){let destStat;const statFunc=opts.dereference?file=>fs.statSync(file,{bigint:!0}):file=>fs.lstatSync(file,{bigint:!0}),srcStat=statFunc(src);try{destStat=statFunc(dest)}catch(err){if("ENOENT"===err.code)return{srcStat:srcStat,destStat:null};throw err}return{srcStat:srcStat,destStat:destStat}}(src,dest,opts);if(destStat){if(areIdentical(srcStat,destStat)){const srcBaseName=path$1.basename(src),destBaseName=path$1.basename(dest);if("move"===funcName&&srcBaseName!==destBaseName&&srcBaseName.toLowerCase()===destBaseName.toLowerCase())return{srcStat:srcStat,destStat:destStat,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(srcStat.isDirectory()&&!destStat.isDirectory())throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);if(!srcStat.isDirectory()&&destStat.isDirectory())throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)}if(srcStat.isDirectory()&&isSrcSubdir(src,dest))throw new Error(errMsg(src,dest,funcName));return{srcStat:srcStat,destStat:destStat}},checkParentPaths:u(async function checkParentPaths(src,srcStat,dest,funcName){const srcParent=path$1.resolve(path$1.dirname(src)),destParent=path$1.resolve(path$1.dirname(dest));if(destParent===srcParent||destParent===path$1.parse(destParent).root)return;let destStat;try{destStat=await fs.stat(destParent,{bigint:!0})}catch(err){if("ENOENT"===err.code)return;throw err}if(areIdentical(srcStat,destStat))throw new Error(errMsg(src,dest,funcName));return checkParentPaths(src,srcStat,destParent,funcName)}),checkParentPathsSync:function checkParentPathsSync(src,srcStat,dest,funcName){const srcParent=path$1.resolve(path$1.dirname(src)),destParent=path$1.resolve(path$1.dirname(dest));if(destParent===srcParent||destParent===path$1.parse(destParent).root)return;let destStat;try{destStat=fs.statSync(destParent,{bigint:!0})}catch(err){if("ENOENT"===err.code)return;throw err}if(areIdentical(srcStat,destStat))throw new Error(errMsg(src,dest,funcName));return checkParentPathsSync(src,srcStat,destParent,funcName)},isSrcSubdir:isSrcSubdir,areIdentical:areIdentical},stat}function requireCopy$1(){if(hasRequiredCopy$1)return copy_1;hasRequiredCopy$1=1;const fs=requireFs(),path$1=path,{mkdirs:mkdirs}=requireMkdirs(),{pathExists:pathExists}=requirePathExists(),{utimesMillis:utimesMillis}=requireUtimes(),stat=requireStat(),{asyncIteratorConcurrentProcess:asyncIteratorConcurrentProcess}=function requireAsync(){return hasRequiredAsync||(hasRequiredAsync=1,async={asyncIteratorConcurrentProcess:async function asyncIteratorConcurrentProcess(iterator,fn){const promises=[];for await(const item of iterator)promises.push(fn(item).then(()=>null,err=>err??new Error("unknown error")));await Promise.all(promises.map(promise=>promise.then(possibleErr=>{if(null!==possibleErr)throw possibleErr})))}}),async}();async function runFilter(src,dest,opts){return!opts.filter||opts.filter(src,dest)}async function getStatsAndPerformCopy(destStat,src,dest,opts){const statFn=opts.dereference?fs.stat:fs.lstat,srcStat=await statFn(src);if(srcStat.isDirectory())return async function onDir(srcStat,destStat,src,dest,opts){destStat||await fs.mkdir(dest);await asyncIteratorConcurrentProcess(await fs.opendir(src),async item=>{const srcItem=path$1.join(src,item.name),destItem=path$1.join(dest,item.name);if(await runFilter(srcItem,destItem,opts)){const{destStat:destStat}=await stat.checkPaths(srcItem,destItem,"copy",opts);await getStatsAndPerformCopy(destStat,srcItem,destItem,opts)}}),destStat||await fs.chmod(dest,srcStat.mode)}(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return async function onFile(srcStat,destStat,src,dest,opts){if(!destStat)return copyFile(srcStat,src,dest,opts);if(opts.overwrite)return await fs.unlink(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return async function onLink(destStat,src,dest,opts){let resolvedSrc=await fs.readlink(src);opts.dereference&&(resolvedSrc=path$1.resolve(process.cwd(),resolvedSrc));if(!destStat)return fs.symlink(resolvedSrc,dest);let resolvedDest=null;try{resolvedDest=await fs.readlink(dest)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return fs.symlink(resolvedSrc,dest);throw e}opts.dereference&&(resolvedDest=path$1.resolve(process.cwd(),resolvedDest));if(resolvedSrc!==resolvedDest){if(stat.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(stat.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return await fs.unlink(dest),fs.symlink(resolvedSrc,dest)}(destStat,src,dest,opts);if(srcStat.isSocket())throw new Error(`Cannot copy a socket file: ${src}`);if(srcStat.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${src}`);throw new Error(`Unknown file: ${src}`)}async function copyFile(srcStat,src,dest,opts){if(await fs.copyFile(src,dest),opts.preserveTimestamps){(function fileIsNotWritable(srcMode){return!(128&srcMode)})(srcStat.mode)&&await function makeFileWritable(dest,srcMode){return fs.chmod(dest,128|srcMode)}(dest,srcStat.mode);const updatedSrcStat=await fs.stat(src);await utimesMillis(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}return fs.chmod(dest,srcStat.mode)}return copy_1=async function copy(src,dest,opts={}){"function"==typeof opts&&(opts={filter:opts}),opts.clobber=!("clobber"in opts)||!!opts.clobber,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0001");const{srcStat:srcStat,destStat:destStat}=await stat.checkPaths(src,dest,"copy",opts);if(await stat.checkParentPaths(src,srcStat,dest,"copy"),!await runFilter(src,dest,opts))return;const destParent=path$1.dirname(dest);await pathExists(destParent)||await mkdirs(destParent),await getStatsAndPerformCopy(destStat,src,dest,opts)},copy_1}function requireCopySync(){if(hasRequiredCopySync)return copySync_1;hasRequiredCopySync=1;const fs=requireGracefulFs(),path$1=path,mkdirsSync=requireMkdirs().mkdirsSync,utimesMillisSync=requireUtimes().utimesMillisSync,stat=requireStat();function getStats(destStat,src,dest,opts){const srcStat=(opts.dereference?fs.statSync:fs.lstatSync)(src);if(srcStat.isDirectory())return function onDir(srcStat,destStat,src,dest,opts){return destStat?copyDir(src,dest,opts):function mkDirAndCopy(srcMode,src,dest,opts){return fs.mkdirSync(dest),copyDir(src,dest,opts),setDestMode(dest,srcMode)}(srcStat.mode,src,dest,opts)}(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return function onFile(srcStat,destStat,src,dest,opts){return destStat?function mayCopyFile(srcStat,src,dest,opts){if(opts.overwrite)return fs.unlinkSync(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}(srcStat,src,dest,opts):copyFile(srcStat,src,dest,opts)}(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return function onLink(destStat,src,dest,opts){let resolvedSrc=fs.readlinkSync(src);opts.dereference&&(resolvedSrc=path$1.resolve(process.cwd(),resolvedSrc));if(destStat){let resolvedDest;try{resolvedDest=fs.readlinkSync(dest)}catch(err){if("EINVAL"===err.code||"UNKNOWN"===err.code)return fs.symlinkSync(resolvedSrc,dest);throw err}if(opts.dereference&&(resolvedDest=path$1.resolve(process.cwd(),resolvedDest)),resolvedSrc!==resolvedDest){if(stat.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(stat.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return function copyLink(resolvedSrc,dest){return fs.unlinkSync(dest),fs.symlinkSync(resolvedSrc,dest)}(resolvedSrc,dest)}return fs.symlinkSync(resolvedSrc,dest)}(destStat,src,dest,opts);if(srcStat.isSocket())throw new Error(`Cannot copy a socket file: ${src}`);if(srcStat.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${src}`);throw new Error(`Unknown file: ${src}`)}function copyFile(srcStat,src,dest,opts){return fs.copyFileSync(src,dest),opts.preserveTimestamps&&function handleTimestamps(srcMode,src,dest){(function fileIsNotWritable(srcMode){return!(128&srcMode)})(srcMode)&&function makeFileWritable(dest,srcMode){return setDestMode(dest,128|srcMode)}(dest,srcMode);return function setDestTimestamps(src,dest){const updatedSrcStat=fs.statSync(src);return utimesMillisSync(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}(src,dest)}(srcStat.mode,src,dest),setDestMode(dest,srcStat.mode)}function setDestMode(dest,srcMode){return fs.chmodSync(dest,srcMode)}function copyDir(src,dest,opts){const dir=fs.opendirSync(src);try{let dirent;for(;null!==(dirent=dir.readSync());)copyDirItem(dirent.name,src,dest,opts)}finally{dir.closeSync()}}function copyDirItem(item,src,dest,opts){const srcItem=path$1.join(src,item),destItem=path$1.join(dest,item);if(opts.filter&&!opts.filter(srcItem,destItem))return;const{destStat:destStat}=stat.checkPathsSync(srcItem,destItem,"copy",opts);return getStats(destStat,srcItem,destItem,opts)}return copySync_1=function copySync(src,dest,opts){"function"==typeof opts&&(opts={filter:opts}),(opts=opts||{}).clobber=!("clobber"in opts)||!!opts.clobber,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0002");const{srcStat:srcStat,destStat:destStat}=stat.checkPathsSync(src,dest,"copy",opts);if(stat.checkParentPathsSync(src,srcStat,dest,"copy"),opts.filter&&!opts.filter(src,dest))return;const destParent=path$1.dirname(dest);return fs.existsSync(destParent)||mkdirsSync(destParent),getStats(destStat,src,dest,opts)},copySync_1}function requireCopy(){if(hasRequiredCopy)return copy;hasRequiredCopy=1;const u=requireUniversalify().fromPromise;return copy={copy:u(requireCopy$1()),copySync:requireCopySync()}}function requireRemove(){if(hasRequiredRemove)return remove_1;hasRequiredRemove=1;const fs=requireGracefulFs(),u=requireUniversalify().fromCallback;return remove_1={remove:u(function remove(path,callback){fs.rm(path,{recursive:!0,force:!0},callback)}),removeSync:function removeSync(path){fs.rmSync(path,{recursive:!0,force:!0})}},remove_1}function requireEmpty(){if(hasRequiredEmpty)return empty;hasRequiredEmpty=1;const u=requireUniversalify().fromPromise,fs=requireFs(),path$1=path,mkdir=requireMkdirs(),remove=requireRemove(),emptyDir=u(async function emptyDir(dir){let items;try{items=await fs.readdir(dir)}catch{return mkdir.mkdirs(dir)}return Promise.all(items.map(item=>remove.remove(path$1.join(dir,item))))});function emptyDirSync(dir){let items;try{items=fs.readdirSync(dir)}catch{return mkdir.mkdirsSync(dir)}items.forEach(item=>{item=path$1.join(dir,item),remove.removeSync(item)})}return empty={emptyDirSync:emptyDirSync,emptydirSync:emptyDirSync,emptyDir:emptyDir,emptydir:emptyDir}}function requireSymlink(){if(hasRequiredSymlink)return symlink;hasRequiredSymlink=1;const u=requireUniversalify().fromPromise,path$1=path,fs=requireFs(),{mkdirs:mkdirs,mkdirsSync:mkdirsSync}=requireMkdirs(),{symlinkPaths:symlinkPaths,symlinkPathsSync:symlinkPathsSync}=function requireSymlinkPaths(){if(hasRequiredSymlinkPaths)return symlinkPaths_1;hasRequiredSymlinkPaths=1;const path$1=path,fs=requireFs(),{pathExists:pathExists}=requirePathExists(),u=requireUniversalify().fromPromise;return symlinkPaths_1={symlinkPaths:u(async function symlinkPaths(srcpath,dstpath){if(path$1.isAbsolute(srcpath)){try{await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureSymlink"),err}return{toCwd:srcpath,toDst:srcpath}}const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);if(await pathExists(relativeToDst))return{toCwd:relativeToDst,toDst:srcpath};try{await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureSymlink"),err}return{toCwd:srcpath,toDst:path$1.relative(dstdir,srcpath)}}),symlinkPathsSync:function symlinkPathsSync(srcpath,dstpath){if(path$1.isAbsolute(srcpath)){if(!fs.existsSync(srcpath))throw new Error("absolute srcpath does not exist");return{toCwd:srcpath,toDst:srcpath}}const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);if(fs.existsSync(relativeToDst))return{toCwd:relativeToDst,toDst:srcpath};if(!fs.existsSync(srcpath))throw new Error("relative srcpath does not exist");return{toCwd:srcpath,toDst:path$1.relative(dstdir,srcpath)}}}}(),{symlinkType:symlinkType,symlinkTypeSync:symlinkTypeSync}=function requireSymlinkType(){if(hasRequiredSymlinkType)return symlinkType_1;hasRequiredSymlinkType=1;const fs=requireFs(),u=requireUniversalify().fromPromise;return symlinkType_1={symlinkType:u(async function symlinkType(srcpath,type){if(type)return type;let stats;try{stats=await fs.lstat(srcpath)}catch{return"file"}return stats&&stats.isDirectory()?"dir":"file"}),symlinkTypeSync:function symlinkTypeSync(srcpath,type){if(type)return type;let stats;try{stats=fs.lstatSync(srcpath)}catch{return"file"}return stats&&stats.isDirectory()?"dir":"file"}},symlinkType_1}(),{pathExists:pathExists}=requirePathExists(),{areIdentical:areIdentical}=requireStat();return symlink={createSymlink:u(async function createSymlink(srcpath,dstpath,type){let stats;try{stats=await fs.lstat(dstpath)}catch{}if(stats&&stats.isSymbolicLink()){let srcStat;if(path$1.isAbsolute(srcpath))srcStat=await fs.stat(srcpath);else{const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);try{srcStat=await fs.stat(relativeToDst)}catch{srcStat=await fs.stat(srcpath)}}const dstStat=await fs.stat(dstpath);if(areIdentical(srcStat,dstStat))return}const relative=await symlinkPaths(srcpath,dstpath);srcpath=relative.toDst;const toType=await symlinkType(relative.toCwd,type),dir=path$1.dirname(dstpath);return await pathExists(dir)||await mkdirs(dir),fs.symlink(srcpath,dstpath,toType)}),createSymlinkSync:function createSymlinkSync(srcpath,dstpath,type){let stats;try{stats=fs.lstatSync(dstpath)}catch{}if(stats&&stats.isSymbolicLink()){let srcStat;if(path$1.isAbsolute(srcpath))srcStat=fs.statSync(srcpath);else{const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);try{srcStat=fs.statSync(relativeToDst)}catch{srcStat=fs.statSync(srcpath)}}const dstStat=fs.statSync(dstpath);if(areIdentical(srcStat,dstStat))return}const relative=symlinkPathsSync(srcpath,dstpath);srcpath=relative.toDst,type=symlinkTypeSync(relative.toCwd,type);const dir=path$1.dirname(dstpath);return fs.existsSync(dir)||mkdirsSync(dir),fs.symlinkSync(srcpath,dstpath,type)}},symlink}function requireEnsure(){if(hasRequiredEnsure)return ensure;hasRequiredEnsure=1;const{createFile:createFile,createFileSync:createFileSync}=function requireFile(){if(hasRequiredFile)return file;hasRequiredFile=1;const u=requireUniversalify().fromPromise,path$1=path,fs=requireFs(),mkdir=requireMkdirs();return file={createFile:u(async function createFile(file){let stats;try{stats=await fs.stat(file)}catch{}if(stats&&stats.isFile())return;const dir=path$1.dirname(file);let dirStats=null;try{dirStats=await fs.stat(dir)}catch(err){if("ENOENT"===err.code)return await mkdir.mkdirs(dir),void await fs.writeFile(file,"");throw err}dirStats.isDirectory()?await fs.writeFile(file,""):await fs.readdir(dir)}),createFileSync:function createFileSync(file){let stats;try{stats=fs.statSync(file)}catch{}if(stats&&stats.isFile())return;const dir=path$1.dirname(file);try{fs.statSync(dir).isDirectory()||fs.readdirSync(dir)}catch(err){if(!err||"ENOENT"!==err.code)throw err;mkdir.mkdirsSync(dir)}fs.writeFileSync(file,"")}}}(),{createLink:createLink,createLinkSync:createLinkSync}=function requireLink(){if(hasRequiredLink)return link;hasRequiredLink=1;const u=requireUniversalify().fromPromise,path$1=path,fs=requireFs(),mkdir=requireMkdirs(),{pathExists:pathExists}=requirePathExists(),{areIdentical:areIdentical}=requireStat();return link={createLink:u(async function createLink(srcpath,dstpath){let dstStat,srcStat;try{dstStat=await fs.lstat(dstpath)}catch{}try{srcStat=await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureLink"),err}if(dstStat&&areIdentical(srcStat,dstStat))return;const dir=path$1.dirname(dstpath);await pathExists(dir)||await mkdir.mkdirs(dir),await fs.link(srcpath,dstpath)}),createLinkSync:function createLinkSync(srcpath,dstpath){let dstStat;try{dstStat=fs.lstatSync(dstpath)}catch{}try{const srcStat=fs.lstatSync(srcpath);if(dstStat&&areIdentical(srcStat,dstStat))return}catch(err){throw err.message=err.message.replace("lstat","ensureLink"),err}const dir=path$1.dirname(dstpath);return fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.linkSync(srcpath,dstpath)}}}(),{createSymlink:createSymlink,createSymlinkSync:createSymlinkSync}=requireSymlink();return ensure={createFile:createFile,createFileSync:createFileSync,ensureFile:createFile,ensureFileSync:createFileSync,createLink:createLink,createLinkSync:createLinkSync,ensureLink:createLink,ensureLinkSync:createLinkSync,createSymlink:createSymlink,createSymlinkSync:createSymlinkSync,ensureSymlink:createSymlink,ensureSymlinkSync:createSymlinkSync}}function requireUtils(){if(hasRequiredUtils)return utils;return hasRequiredUtils=1,utils={stringify:function stringify(obj,{EOL:EOL="\n",finalEOL:finalEOL=!0,replacer:replacer=null,spaces:spaces}={}){const EOF=finalEOL?EOL:"";return JSON.stringify(obj,replacer,spaces).replace(/\n/g,EOL)+EOF},stripBom:function stripBom(content){return Buffer.isBuffer(content)&&(content=content.toString("utf8")),content.replace(/^\uFEFF/,"")}}}function requireJsonfile(){if(hasRequiredJsonfile)return jsonfile;hasRequiredJsonfile=1;const jsonFile=function requireJsonfile$1(){if(hasRequiredJsonfile$1)return jsonfile$1;let _fs;hasRequiredJsonfile$1=1;try{_fs=requireGracefulFs()}catch(_){_fs=fs$2}const universalify=requireUniversalify(),{stringify:stringify,stripBom:stripBom}=requireUtils(),readFile=universalify.fromPromise(async function _readFile(file,options={}){"string"==typeof options&&(options={encoding:options});const fs=options.fs||_fs,shouldThrow=!("throws"in options)||options.throws;let obj,data=await universalify.fromCallback(fs.readFile)(file,options);data=stripBom(data);try{obj=JSON.parse(data,options?options.reviver:null)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}return obj}),writeFile=universalify.fromPromise(async function _writeFile(file,obj,options={}){const fs=options.fs||_fs,str=stringify(obj,options);await universalify.fromCallback(fs.writeFile)(file,str,options)});return jsonfile$1={readFile:readFile,readFileSync:function readFileSync(file,options={}){"string"==typeof options&&(options={encoding:options});const fs=options.fs||_fs,shouldThrow=!("throws"in options)||options.throws;try{let content=fs.readFileSync(file,options);return content=stripBom(content),JSON.parse(content,options.reviver)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}},writeFile:writeFile,writeFileSync:function writeFileSync(file,obj,options={}){const fs=options.fs||_fs,str=stringify(obj,options);return fs.writeFileSync(file,str,options)}},jsonfile$1}();return jsonfile={readJson:jsonFile.readFile,readJsonSync:jsonFile.readFileSync,writeJson:jsonFile.writeFile,writeJsonSync:jsonFile.writeFileSync}}function requireOutputFile(){if(hasRequiredOutputFile)return outputFile_1;hasRequiredOutputFile=1;const u=requireUniversalify().fromPromise,fs=requireFs(),path$1=path,mkdir=requireMkdirs(),pathExists=requirePathExists().pathExists;return outputFile_1={outputFile:u(async function outputFile(file,data,encoding="utf-8"){const dir=path$1.dirname(file);return await pathExists(dir)||await mkdir.mkdirs(dir),fs.writeFile(file,data,encoding)}),outputFileSync:function outputFileSync(file,...args){const dir=path$1.dirname(file);fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.writeFileSync(file,...args)}},outputFile_1}function requireJson(){if(hasRequiredJson)return json;hasRequiredJson=1;const u=requireUniversalify().fromPromise,jsonFile=requireJsonfile();return jsonFile.outputJson=u(function requireOutputJson(){if(hasRequiredOutputJson)return outputJson_1;hasRequiredOutputJson=1;const{stringify:stringify}=requireUtils(),{outputFile:outputFile}=requireOutputFile();return outputJson_1=async function outputJson(file,data,options={}){const str=stringify(data,options);await outputFile(file,str,options)},outputJson_1}()),jsonFile.outputJsonSync=function requireOutputJsonSync(){if(hasRequiredOutputJsonSync)return outputJsonSync_1;hasRequiredOutputJsonSync=1;const{stringify:stringify}=requireUtils(),{outputFileSync:outputFileSync}=requireOutputFile();return outputJsonSync_1=function outputJsonSync(file,data,options){const str=stringify(data,options);outputFileSync(file,str,options)},outputJsonSync_1}(),jsonFile.outputJSON=jsonFile.outputJson,jsonFile.outputJSONSync=jsonFile.outputJsonSync,jsonFile.writeJSON=jsonFile.writeJson,jsonFile.writeJSONSync=jsonFile.writeJsonSync,jsonFile.readJSON=jsonFile.readJson,jsonFile.readJSONSync=jsonFile.readJsonSync,json=jsonFile}function requireMove$1(){if(hasRequiredMove$1)return move_1;hasRequiredMove$1=1;const fs=requireFs(),path$1=path,{copy:copy}=requireCopy(),{remove:remove}=requireRemove(),{mkdirp:mkdirp}=requireMkdirs(),{pathExists:pathExists}=requirePathExists(),stat=requireStat();return move_1=async function move(src,dest,opts={}){const overwrite=opts.overwrite||opts.clobber||!1,{srcStat:srcStat,isChangingCase:isChangingCase=!1}=await stat.checkPaths(src,dest,"move",opts);await stat.checkParentPaths(src,srcStat,dest,"move");const destParent=path$1.dirname(dest);return path$1.parse(destParent).root!==destParent&&await mkdirp(destParent),async function doRename(src,dest,overwrite,isChangingCase){if(!isChangingCase)if(overwrite)await remove(dest);else if(await pathExists(dest))throw new Error("dest already exists.");try{await fs.rename(src,dest)}catch(err){if("EXDEV"!==err.code)throw err;await async function moveAcrossDevice(src,dest,overwrite){const opts={overwrite:overwrite,errorOnExist:!0,preserveTimestamps:!0};return await copy(src,dest,opts),remove(src)}(src,dest,overwrite)}}(src,dest,overwrite,isChangingCase)},move_1}function requireMoveSync(){if(hasRequiredMoveSync)return moveSync_1;hasRequiredMoveSync=1;const fs=requireGracefulFs(),path$1=path,copySync=requireCopy().copySync,removeSync=requireRemove().removeSync,mkdirpSync=requireMkdirs().mkdirpSync,stat=requireStat();function rename(src,dest,overwrite){try{fs.renameSync(src,dest)}catch(err){if("EXDEV"!==err.code)throw err;return function moveAcrossDevice(src,dest,overwrite){const opts={overwrite:overwrite,errorOnExist:!0,preserveTimestamps:!0};return copySync(src,dest,opts),removeSync(src)}(src,dest,overwrite)}}return moveSync_1=function moveSync(src,dest,opts){const overwrite=(opts=opts||{}).overwrite||opts.clobber||!1,{srcStat:srcStat,isChangingCase:isChangingCase=!1}=stat.checkPathsSync(src,dest,"move",opts);return stat.checkParentPathsSync(src,srcStat,dest,"move"),function isParentRoot(dest){const parent=path$1.dirname(dest);return path$1.parse(parent).root===parent}(dest)||mkdirpSync(path$1.dirname(dest)),function doRename(src,dest,overwrite,isChangingCase){if(isChangingCase)return rename(src,dest,overwrite);if(overwrite)return removeSync(dest),rename(src,dest,overwrite);if(fs.existsSync(dest))throw new Error("dest already exists.");return rename(src,dest,overwrite)}(src,dest,overwrite,isChangingCase)},moveSync_1}function requireMove(){if(hasRequiredMove)return move;hasRequiredMove=1;const u=requireUniversalify().fromPromise;return move={move:u(requireMove$1()),moveSync:requireMoveSync()}}function requireLib(){return hasRequiredLib?lib:(hasRequiredLib=1,lib={...requireFs(),...requireCopy(),...requireEmpty(),...requireEnsure(),...requireJson(),...requireMkdirs(),...requireMove(),...requireOutputFile(),...requirePathExists(),...requireRemove()})}var fs=getDefaultExportFromCjs(requireLib());function sha256(content){return crypto$1.createHash("sha256").update(content).digest("hex")}function deepSort(value){if(Array.isArray(value))return value.map(deepSort);if(value&&"object"==typeof value){const sorted={};for(const key of Object.keys(value).sort())sorted[key]=deepSort(value[key]);return sorted}return value}function objectChecksum(value){return sha256(function stableStringify(value){return JSON.stringify(deepSort(value))}(value))}function toAbsolutePath(filePath){return path.isAbsolute(filePath)?filePath:path.resolve(process.cwd(),filePath)}async function readJsonIfExists(filePath){return await fs.pathExists(filePath)?fs.readJson(filePath):null}function parseFilters(filterInput){if(!filterInput)return[];return(Array.isArray(filterInput)?filterInput:[filterInput]).flatMap(item=>String(item).split(",")).map(item=>item.trim()).filter(Boolean)}function matchByFilters(value,filters){return!filters.length||filters.some(filter=>{const regExp=function wildcardToRegExp(pattern){const regexText=`^${pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(regexText,"i")}(filter);return regExp.test(value)})}function splitTopLevelMembers(objectBody){const members=[];let current="",braceDepth=0,bracketDepth=0,parenDepth=0,angleDepth=0;for(let i=0;i<objectBody.length;i++){const ch=objectBody[i];"{"===ch&&braceDepth++,"}"===ch&&(braceDepth=Math.max(0,braceDepth-1)),"["===ch&&bracketDepth++,"]"===ch&&(bracketDepth=Math.max(0,bracketDepth-1)),"("===ch&&parenDepth++,")"===ch&&(parenDepth=Math.max(0,parenDepth-1)),"<"===ch&&angleDepth++,">"===ch&&(angleDepth=Math.max(0,angleDepth-1)),";"!==ch||0!==braceDepth||0!==bracketDepth||0!==parenDepth||0!==angleDepth?current+=ch:(current.trim()&&members.push(current.trim()),current="")}return current.trim()&&members.push(current.trim()),members}function parseCollectionIdEnum(source){const map=new Map,enumMatch=source.match(/export\s+enum\s+BxCollectionId\s*{([\s\S]*?)}/m);if(!enumMatch)return map;const body=enumMatch[1],entryRegex=/([A-Za-z0-9_]+)\s*=\s*"([^"]+)"/g;let m;for(;null!==(m=entryRegex.exec(body));)map.set(m[1],m[2]);return map}function resolveCollectionId(typeName,enumMap){const mapped=enumMap.get(typeName);return mapped||typeName.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/-/g,"_").toLowerCase()}function mapScalarTypeToFieldType(typeText){const normalized=typeText.trim().replace(/^\((.*)\)$/,"$1");return["string","BxText","BxEmail","BxUrl","BxObjectId","BxAuth","BxPhoneNumber","BxSequence"].includes(normalized)?"Text":["BxLongText","BxRichText"].includes(normalized)?"LongText":["number","BxNumber","BxInteger"].includes(normalized)?"Number":["boolean","BxBoolean"].includes(normalized)?"Toggle":["BxCheckbox"].includes(normalized)?"Checkbox":["Date","BxDate"].includes(normalized)?"Date":["BxDateTime"].includes(normalized)?"DateTime":["BxChoices"].includes(normalized)?"Choices":["BxMultipleChoices"].includes(normalized)?"MultipleChoices":["BxUser"].includes(normalized)?"User":["BxUsers"].includes(normalized)?"Users":["BxFiles"].includes(normalized)?"Files":["BxImages"].includes(normalized)?"Images":["BxObject"].includes(normalized)?"Object":["BxList"].includes(normalized)?"List":["BxContent"].includes(normalized)?"Content":"Text"}function convertTypeFieldToSchemaField(typeText,optional){const requiredPart=!optional?{required:!0}:{},raw=typeText.trim(),compact=raw.replace(/\s+/g,""),primary=raw.split("|").map(part=>part.trim()).filter(Boolean).filter(part=>"null"!==part&&"undefined"!==part)[0]||raw,singleRefMatch=compact.match(/^(?:Partial<([A-Za-z0-9_]+)>\|BxDataObject|BxDataObject\|Partial<([A-Za-z0-9_]+)>)$/),singleRef=(null==singleRefMatch?void 0:singleRefMatch[1])||(null==singleRefMatch?void 0:singleRefMatch[2]);if(singleRef)return{type:"DataObject",...requiredPart,propertiesScheme:{ref:singleRef}};const manyRefMatch=compact.match(/^(?:Partial<([A-Za-z0-9_]+)>\[\]\|BxDataObject\[\]|BxDataObject\[\]\|Partial<([A-Za-z0-9_]+)>\[\])$/),manyRef=(null==manyRefMatch?void 0:manyRefMatch[1])||(null==manyRefMatch?void 0:manyRefMatch[2]);if(manyRef)return{type:"DataObjects",...requiredPart,propertiesScheme:{ref:manyRef}};if(primary.endsWith("[]")){const inner=primary.slice(0,-2).trim().replace(/^\((.*)\)$/,"$1");return{type:"List",...requiredPart,propertiesScheme:{children:[{name:"item",type:mapScalarTypeToFieldType(inner)}]}}}return primary.startsWith("{")&&primary.endsWith("}")?{type:"Object",...requiredPart,propertiesScheme:{children:[]}}:{type:mapScalarTypeToFieldType(primary),...requiredPart}}function parseBxFieldAnnotations(memberText){const annotations={},blocks=memberText.match(/\/\*\*[\s\S]*?\*\//g)||[];for(const block of blocks){const content=block.replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map(line=>line.replace(/^\s*\*\s?/,"")).join("\n"),tagRegex=/@bx\.([a-z_]+)\s*([\s\S]*?)(?=@bx\.|$)/gi;let match;for(;null!==(match=tagRegex.exec(content));){const[,keyRaw,valueRaw]=match,key=keyRaw.toLowerCase(),value=valueRaw.trim();"title"===key&&value&&(annotations.title=value),"description"===key&&value&&(annotations.description=value),"ref"===key&&value&&(annotations.ref=value),"required"===key&&(annotations.required=!value||!["false","0","no"].includes(value.toLowerCase())),"choices"===key&&value&&(annotations.choices=value.split("|").map(part=>part.trim()).filter(Boolean).map(part=>{const separator=part.indexOf(":");if(separator<0)return{value:part,label:part};return{value:part.slice(0,separator).trim(),label:part.slice(separator+1).trim()}}))}}return annotations}function stripCommentsForFieldParse(memberText){return memberText.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").trim()}function applyFieldAnnotations(fieldSchema,annotations,warnings,fieldPath){const next={...fieldSchema};return annotations.title&&(next.title=annotations.title),annotations.description&&(next.description=annotations.description),void 0!==annotations.required&&(annotations.required?next.required=!0:delete next.required),annotations.ref&&(next.propertiesScheme={...next.propertiesScheme||{},ref:annotations.ref}),annotations.choices&&("Choices"===next.type||"MultipleChoices"===next.type?next.propertiesScheme={...next.propertiesScheme||{},choices:annotations.choices}:warnings.push(`Field "${fieldPath}" has @bx.choices but inferred type is "${next.type}"`)),next}function mergeSchemaField(baseField,inferredField){if(!baseField)return inferredField;if(!inferredField)return baseField;const merged={...baseField,...inferredField},fieldType=String(inferredField.type||merged.type||""),baseProperties=baseField.propertiesScheme||{},inferredProperties=inferredField.propertiesScheme||{};return"DataObject"===fieldType||"DataObjects"===fieldType?merged.propertiesScheme={...baseProperties.ref?{ref:baseProperties.ref}:{},...baseProperties.local_key?{local_key:baseProperties.local_key}:{},...baseProperties.foreign_key?{foreign_key:baseProperties.foreign_key}:{},...baseProperties.schema?{schema:baseProperties.schema}:{},...inferredProperties.ref?{ref:inferredProperties.ref}:{},...inferredProperties.local_key?{local_key:inferredProperties.local_key}:{},...inferredProperties.foreign_key?{foreign_key:inferredProperties.foreign_key}:{},...inferredProperties.schema?{schema:inferredProperties.schema}:{}}:(baseField.propertiesScheme||inferredField.propertiesScheme)&&(merged.propertiesScheme={...baseProperties,...inferredProperties}),merged}const COLLECTION_EXPORT_KEYS=["collection_id","name","description","form_schema","timestamps","auditable"],FIELD_INTERNAL_KEYS=new Set(["_expanded","inherited","inheried"]);function applySchemaPullOptions(command){return command.option("-p, --project-id <project-id>","Project ID to sync schema from (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("-o, --output <path>","Output path for generated TypeScript types","./buildx/generated/types.ts").option("--collections-file <path>","Path to store editable collections-as-code JSON","./buildx/generated/collections.json").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only include collections matching wildcard pattern(s), ex: users* or order_*").option("--dry-run","Preview sync result without writing local files").option("--skip-collections-code","Skip writing collections-as-code JSON").option("--no-annotate-types","Disable @bx annotations injection into pulled types.ts").option("--raw-collections","Export raw collections payload without normalization").option("--include-buildx","Include buildx_* collections in collections-as-code JSON").option("-f, --force","Force overwrite existing files")}function printDryRunFilePreview$1(filePath,content){console.log(chalk.cyan(`\n--- DRY RUN: ${filePath} ---`)),console.log(content),console.log(chalk.cyan(`--- END DRY RUN: ${filePath} ---\n`))}function ensureConfigured$1(){apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config:setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1))}function resolveProjectId$1(projectId){if(projectId)return projectId;const defaultProjectId=configManager.getDefaultProject();if(defaultProjectId)return console.log(chalk.blue("Using project ID:"),defaultProjectId),defaultProjectId;const envConfig=loadEnvConfig();if(envConfig.BUILDX_PROJECT_ID)return console.log(chalk.blue("Using project ID from environment variable:"),envConfig.BUILDX_PROJECT_ID),envConfig.BUILDX_PROJECT_ID;console.error(chalk.red("Error: No project ID specified")),console.log(chalk.yellow("Use --project-id option, set a default project with 'buildx projects:set-default', or set BUILDX_PROJECT_ID environment variable")),process.exit(1)}function filterCollections(collections,filters){return filters.length?collections.filter(collection=>matchByFilters(String(collection.collection_id||""),filters)):collections}function sanitizeFieldValue(value){if(Array.isArray(value))return value.map(sanitizeFieldValue);if(value&&"object"==typeof value){const result={};for(const[key,subValue]of Object.entries(value))FIELD_INTERNAL_KEYS.has(key)||(result[key]=sanitizeFieldValue(subValue));return result}return value}function normalizeCollectionForCode(collection){if(!collection||"object"!=typeof collection)return null;if(!collection.collection_id||"string"!=typeof collection.collection_id)return null;const result={};for(const key of COLLECTION_EXPORT_KEYS)void 0!==collection[key]&&(result[key]="form_schema"===key?sanitizeFieldValue(collection[key]):collection[key]);return result.form_schema&&"object"==typeof result.form_schema||(result.form_schema={}),result}function validateCollectionForPushDetailed(collection){var _a,_b;const errors=[];if(!collection||"object"!=typeof collection||Array.isArray(collection))return["Collection must be an object"];const collectionId=String(collection.collection_id||"");if(collectionId?(collectionId.includes(" ")&&errors.push(`collection_id "${collectionId}" cannot contain spaces`),/^[A-Za-z0-9_-]+$/.test(collectionId)||errors.push(`collection_id "${collectionId}" must match [A-Za-z0-9_-]+`)):errors.push("Missing collection_id"),!collection.form_schema||"object"!=typeof collection.form_schema||Array.isArray(collection.form_schema))return errors.push(`Collection "${collectionId||"unknown"}" is missing valid form_schema object`),errors;const formSchema=collection.form_schema;for(const[fieldName,fieldSchema]of Object.entries(formSchema)){const pathPrefix=`${collectionId||"unknown"}.form_schema.${fieldName}`;if(!fieldSchema||"object"!=typeof fieldSchema||Array.isArray(fieldSchema)){errors.push(`${pathPrefix} must be an object`);continue}if(!fieldSchema.type||"string"!=typeof fieldSchema.type){errors.push(`${pathPrefix}.type is required and must be a string`);continue}const fieldType=String(fieldSchema.type);if(["DataObject","DataObjects","ReverseReference","ReverseReferences"].includes(fieldType)){const ref=null==(_a=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_a.ref;ref&&"string"==typeof ref||errors.push(`${pathPrefix}.propertiesScheme.ref is required for ${fieldType}`)}if(["Choices","MultipleChoices"].includes(fieldType)){const choices=null==(_b=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_b.choices;void 0!==choices&&(Array.isArray(choices)?choices.forEach((choice,index)=>{const choicePath=`${pathPrefix}.propertiesScheme.choices[${index}]`;choice&&"object"==typeof choice?void 0!==choice.value&&null!==choice.value&&""!==String(choice.value).trim()||errors.push(`${choicePath}.value is required`):errors.push(`${choicePath} must be an object`)}):errors.push(`${pathPrefix}.propertiesScheme.choices must be an array`))}}return errors}function diffCollectionsDetailed(local,remote,basePath=""){if(local===remote)return[];const localIsArray=Array.isArray(local),remoteIsArray=Array.isArray(remote);if(localIsArray||remoteIsArray)return JSON.stringify(local)===JSON.stringify(remote)?[]:[{type:"changed",path:basePath||".",local:local,remote:remote}];if(!(!!local&&"object"==typeof local)||!(!!remote&&"object"==typeof remote))return[{type:"changed",path:basePath||".",local:local,remote:remote}];const result=[],keys=new Set([...Object.keys(local),...Object.keys(remote)]);for(const key of[...keys].sort()){const nextPath=basePath?`${basePath}.${key}`:key,hasLocal=Object.prototype.hasOwnProperty.call(local,key),hasRemote=Object.prototype.hasOwnProperty.call(remote,key);!hasLocal||hasRemote?hasLocal||!hasRemote?result.push(...diffCollectionsDetailed(local[key],remote[key],nextPath)):result.push({type:"added",path:nextPath,remote:remote[key]}):result.push({type:"removed",path:nextPath,local:local[key]})}return result}function formatDiffValue(value){const text=JSON.stringify(value);return void 0===text?"undefined":text.length>140?`${text.slice(0,137)}...`:text}function toSingleLineText(value){return String(value??"").replace(/\s+/g," ").trim()}function buildBxAnnotationLine(fieldSchema){var _a,_b;if(!fieldSchema||"object"!=typeof fieldSchema)return null;const tags=[],title=toSingleLineText(fieldSchema.title),description=toSingleLineText(fieldSchema.description);title&&tags.push(`@bx.title ${title}`),description&&tags.push(`@bx.description ${description}`),!0===fieldSchema.required&&tags.push("@bx.required");const ref=toSingleLineText(null==(_a=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_a.ref);ref&&tags.push(`@bx.ref ${ref}`);const choices=null==(_b=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_b.choices;if(Array.isArray(choices)&&choices.length>0){const encoded=choices.map(choice=>{const value=toSingleLineText(null==choice?void 0:choice.value);if(!value)return null;return`${value}:${!!choice&&Object.prototype.hasOwnProperty.call(choice,"label")?toSingleLineText(null==choice?void 0:choice.label):value}`}).filter(Boolean).join("|");encoded&&tags.push(`@bx.choices ${encoded}`)}return tags.length?`/** ${tags.join(" ")} */`:null}async function runSchemaPull(options){ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,outputPath=targetDirPath?path.join(targetDirPath,"types.ts"):toAbsolutePath(options.output),collectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile),manifestPath=path.join(path.dirname(collectionsFilePath),"collections.manifest.json"),spinner=ora("Fetching TypeScript types...").start(),typescriptCode=await apiService.getSchema(projectId);if(!typescriptCode||"string"!=typeof typescriptCode)throw spinner.fail("Failed to fetch TypeScript types"),new Error("Schema endpoint returned empty content");spinner.succeed("TypeScript types fetched successfully");let finalTypescriptCode=typescriptCode;if(!options.skipCollectionsCode){const collectionsSpinner=ora("Fetching collections-as-code...").start(),filters=parseFilters(options.filter),collections=await apiService.getCollections(projectId);let editableCollections=options.rawCollections?collections:collections.map(normalizeCollectionForCode).filter(Boolean);options.includeBuildx||(editableCollections=editableCollections.filter(col=>!String((null==col?void 0:col.collection_id)||"").startsWith("buildx_"))),editableCollections=filterCollections(editableCollections,filters),editableCollections=editableCollections.sort((a,b)=>String(a.collection_id).localeCompare(String(b.collection_id))),options.annotateTypes&&(finalTypescriptCode=function injectTypesAnnotations(typeContent,collections){const enumMap=parseCollectionIdEnum(typeContent),collectionById=new Map;for(const collection of collections){const id=String((null==collection?void 0:collection.collection_id)||"").trim();id&&collectionById.set(id,collection)}return collectionById.size?typeContent.replace(/export\s+type\s+([A-Za-z0-9_]+)\s*=\s*{([\s\S]*?)}\s*;/g,(full,typeName,body)=>{const collectionId=resolveCollectionId(typeName,enumMap),collection=collectionById.get(collectionId);if(!(null==collection?void 0:collection.form_schema)||"object"!=typeof collection.form_schema)return full;const formSchema=collection.form_schema,lines=body.split("\n"),output=[];for(const line of lines){const fieldMatch=line.match(/^(\s*)([A-Za-z_][A-Za-z0-9_]*)\??\s*:/);if(!fieldMatch){output.push(line);continue}const[,indent,fieldName]=fieldMatch,annotationLine=buildBxAnnotationLine(formSchema[fieldName]);if(annotationLine){const prev=output.length>0?output[output.length-1]:"";/@bx\./.test(prev)||output.push(`${indent}${annotationLine}`)}output.push(line)}return`export type ${typeName} = {${output.join("\n")}};`}):typeContent}(finalTypescriptCode,editableCollections)),await fs.ensureDir(path.dirname(collectionsFilePath));const manifest={version:1,projectId:projectId,generatedAt:(new Date).toISOString(),collections:{}};for(const collection of editableCollections)manifest.collections[collection.collection_id]={checksum:objectChecksum(collection)};options.dryRun?(collectionsSpinner.succeed("Collections-as-code preview ready"),console.log(chalk.cyan(`~ would write collections JSON: ${collectionsFilePath}`)),console.log(chalk.cyan(`~ would write collections manifest: ${manifestPath}`)),console.log(chalk.blue("Collections count:"),editableCollections.length),printDryRunFilePreview$1(collectionsFilePath,JSON.stringify(editableCollections,null,2)),printDryRunFilePreview$1(manifestPath,JSON.stringify(manifest,null,2))):(await fs.writeJson(collectionsFilePath,editableCollections,{spaces:2}),await fs.writeJson(manifestPath,manifest,{spaces:2}),collectionsSpinner.succeed("Collections-as-code saved"),console.log(chalk.green("✓ Collections JSON:"),collectionsFilePath),console.log(chalk.green("✓ Collections manifest:"),manifestPath))}if(await fs.ensureDir(path.dirname(outputPath)),await fs.pathExists(outputPath)&&!options.force){if(sha256(await fs.readFile(outputPath,"utf8"))!==sha256(finalTypescriptCode))throw new Error(`Output file already exists with local edits: ${outputPath}. Use --force to overwrite.`)}options.dryRun?(console.log(chalk.cyan(`~ would write types to: ${outputPath}`)),console.log(chalk.blue("Types size:"),`${(finalTypescriptCode.length/1024).toFixed(2)} KB`),printDryRunFilePreview$1(outputPath,finalTypescriptCode)):(await fs.writeFile(outputPath,finalTypescriptCode,"utf8"),console.log(chalk.green("✓ Types generated at:"),outputPath),console.log(chalk.blue("File size:"),`${(finalTypescriptCode.length/1024).toFixed(2)} KB`))}const schemaSyncCommand=applySchemaPullOptions(new Command("schema:sync").description("Deprecated alias of schema:pull (kept for compatibility)")).action(async options=>{try{console.log(chalk.yellow("schema:sync is deprecated. Use schema:pull.")),await runSchemaPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaPullCommand=applySchemaPullOptions(new Command("schema:pull").description("Pull project schema/types as code into local files")).action(async options=>{try{await runSchemaPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaPushCommand=new Command("schema:push").description("Push local collections-as-code JSON back to project").option("-p, --project-id <project-id>","Project ID to push schema to (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("--collections-file <path>","Path to collections-as-code JSON","./buildx/generated/collections.json").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only push collections matching wildcard pattern(s)").option("--dry-run","Show what would change without pushing").option("--allow-create","Allow creating new collections when collection_id does not exist on remote").option("-f, --force","Force push even when remote drift is detected").action(async options=>{var _a,_b;try{ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,collectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile),manifestPath=path.join(path.dirname(collectionsFilePath),"collections.manifest.json");if(!await fs.pathExists(collectionsFilePath))throw new Error(`Collections file not found: ${collectionsFilePath}`);const localCollections=await fs.readJson(collectionsFilePath);if(!Array.isArray(localCollections))throw new Error("Collections file must be a JSON array");const normalizedLocalCollections=localCollections.map(normalizeCollectionForCode).filter(Boolean),targetCollections=filterCollections(normalizedLocalCollections,parseFilters(options.filter)),duplicateIds=function findDuplicateCollectionIds(collections){const seen=new Set,duplicates=new Set;for(const collection of collections){const id=String((null==collection?void 0:collection.collection_id)||"").trim();id&&(seen.has(id)?duplicates.add(id):seen.add(id))}return[...duplicates]}(targetCollections);if(duplicateIds.length>0)throw new Error(`Duplicate collection_id is not allowed:\n- ${duplicateIds.join("\n- ")}`);const validationErrors=[];for(const collection of targetCollections)validationErrors.push(...validateCollectionForPushDetailed(collection));if(validationErrors.length>0)throw new Error(`Invalid collections file:\n- ${validationErrors.join("\n- ")}`);const manifest=await readJsonIfExists(manifestPath),remoteCollections=(await apiService.getCollections(projectId)).map(normalizeCollectionForCode).filter(Boolean),remoteById=new Map(remoteCollections.map(collection=>[collection.collection_id,collection]));let pushed=0,skipped=0;for(const collection of targetCollections){const collectionId=collection.collection_id,remoteCollection=remoteById.get(collectionId);if(!remoteCollection&&!options.allowCreate){console.log(chalk.yellow(`⚠ Skipped ${collectionId}: does not exist on remote (use --allow-create to create)`)),skipped++;continue}const localChecksum=objectChecksum(collection),remoteChecksum=remoteCollection?objectChecksum(remoteCollection):null,lastPulledChecksum=null==(_b=null==(_a=null==manifest?void 0:manifest.collections)?void 0:_a[collectionId])?void 0:_b.checksum;!!(!lastPulledChecksum||!remoteChecksum||lastPulledChecksum===remoteChecksum)||options.force?localChecksum!==remoteChecksum?options.dryRun?(console.log(chalk.cyan(`~ would push ${collectionId}`)),pushed++):(await apiService.upsertCollection(projectId,collection),console.log(chalk.green(`✓ pushed ${collectionId}`)),pushed++):console.log(chalk.gray(`- ${collectionId}: no changes`)):(console.log(chalk.yellow(`⚠ Skipped ${collectionId}: remote changed since last pull (use --force to override)`)),skipped++)}console.log(chalk.blue(`Done. pushed=${pushed}, skipped=${skipped}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaListCommand=new Command("schema:list").description("List remote collections in project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-u, --api-url <url>","Custom API base URL").option("--include-buildx","Include buildx_* collections").option("--filter <pattern...>","Filter collection ids by wildcard pattern(s)").action(async options=>{try{ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const filters=parseFilters(options.filter);let collections=await apiService.getCollections(projectId);options.includeBuildx||(collections=collections.filter(collection=>!String(collection.collection_id||"").startsWith("buildx_"))),collections=filterCollections(collections,filters).sort((a,b)=>String(a.collection_id).localeCompare(String(b.collection_id)));for(const collection of collections)console.log(collection.collection_id);console.log(chalk.blue(`Total: ${collections.length}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaDiffCommand=new Command("schema:diff").description("Diff local collections-as-code against remote project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("--collections-file <path>","Path to collections-as-code JSON","./buildx/generated/collections.json").option("-u, --api-url <url>","Custom API base URL").option("--include-buildx","Include buildx_* collections").option("--filter <pattern...>","Filter collection ids by wildcard pattern(s)").option("--details","Show field-level diff details for changed collections").option("--details-limit <count>","Max number of detail lines per changed collection","30").action(async options=>{try{ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const filters=parseFilters(options.filter),targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,collectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile);if(!await fs.pathExists(collectionsFilePath))throw new Error(`Collections file not found: ${collectionsFilePath}`);let localCollections=await fs.readJson(collectionsFilePath);if(!Array.isArray(localCollections))throw new Error("Collections file must be a JSON array");let remoteCollections=await apiService.getCollections(projectId);localCollections=localCollections.map(normalizeCollectionForCode).filter(Boolean),remoteCollections=remoteCollections.map(normalizeCollectionForCode).filter(Boolean),options.includeBuildx||(localCollections=localCollections.filter(collection=>!String(collection.collection_id||"").startsWith("buildx_")),remoteCollections=remoteCollections.filter(collection=>!String(collection.collection_id||"").startsWith("buildx_"))),localCollections=filterCollections(localCollections,filters),remoteCollections=filterCollections(remoteCollections,filters);const localById=new Map(localCollections.map(collection=>[collection.collection_id,collection])),remoteById=new Map(remoteCollections.map(collection=>[collection.collection_id,collection])),localIds=new Set(localById.keys()),remoteIds=new Set(remoteById.keys()),allIds=[...new Set([...localIds,...remoteIds])].sort((a,b)=>a.localeCompare(b));let onlyLocal=0,onlyRemote=0,changed=0,same=0;for(const id of allIds){const local=localById.get(id),remote=remoteById.get(id);if(!local||remote)if(local||!remote){if(local&&remote)if(objectChecksum(local)===objectChecksum(remote))console.log(chalk.gray(`= same ${id}`)),same++;else{if(console.log(chalk.cyan(`~ changed ${id}`)),options.details){const detailsLimit=Number(options.detailsLimit)>0?Number(options.detailsLimit):30,details=diffCollectionsDetailed(local,remote),show=details.slice(0,detailsLimit);for(const item of show)"added"===item.type?console.log(chalk.yellow(` + ${item.path} (remote-only) = ${formatDiffValue(item.remote)}`)):"removed"===item.type?console.log(chalk.yellow(` - ${item.path} (local-only) = ${formatDiffValue(item.local)}`)):console.log(chalk.cyan(` ~ ${item.path} local=${formatDiffValue(item.local)} remote=${formatDiffValue(item.remote)}`));details.length>show.length&&console.log(chalk.gray(` ... and ${details.length-show.length} more changes`))}changed++}}else console.log(chalk.yellow(`- remote-only ${id}`)),onlyRemote++;else console.log(chalk.yellow(`+ local-only ${id}`)),onlyLocal++}console.log(chalk.blue(`Summary: changed=${changed}, same=${same}, local-only=${onlyLocal}, remote-only=${onlyRemote}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaTypesConvertCommand=new Command("schema:types:convert").description("Convert local TypeScript types file into collections-as-code JSON (review before push)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("--types-file <path>","Path to TypeScript types file","./buildx/generated/types.ts").option("--collections-file <path>","Output collections JSON path","./buildx/generated/collections.json").option("--base-collections-file <path>","Optional base collections file to merge metadata from").option("--no-allow-lossy","Require base collections metadata file (strict mode)").option("--filter <pattern...>","Filter collection ids by wildcard pattern(s)").option("--dry-run","Preview output content without writing files").action(async options=>{try{const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,typesFilePath=targetDirPath?path.join(targetDirPath,"types.ts"):toAbsolutePath(options.typesFile),outputCollectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile),baseCollectionsFilePath=options.baseCollectionsFile?toAbsolutePath(options.baseCollectionsFile):outputCollectionsFilePath,filters=parseFilters(options.filter);if(!await fs.pathExists(typesFilePath))throw new Error(`Types file not found: ${typesFilePath}`);const typeContent=await fs.readFile(typesFilePath,"utf8"),{collections:collections,warnings:warnings}=function buildCollectionsFromTypes(typeContent,filters){var _a,_b;const enumMap=parseCollectionIdEnum(typeContent),typeBlocks=function parseExportedObjectTypes(source){const results=[],regex=/export\s+type\s+([A-Za-z0-9_]+)\s*=\s*{/g;let match;for(;null!==(match=regex.exec(source));){const typeName=match[1];if(typeName.startsWith("Bx"))continue;const braceStart=source.indexOf("{",match.index);if(braceStart<0)continue;let depth=0,end=-1;for(let i=braceStart;i<source.length;i++){const ch=source[i];if("{"===ch&&depth++,"}"===ch&&(depth--,0===depth)){end=i;break}}end<0||(results.push({typeName:typeName,body:source.slice(braceStart+1,end)}),regex.lastIndex=end)}return results}(typeContent),warnings=[],collections=[];for(const block of typeBlocks){const collectionId=resolveCollectionId(block.typeName,enumMap);if(!matchByFilters(collectionId,filters))continue;const members=splitTopLevelMembers(block.body),formSchema={};for(const member of members){const annotations=parseBxFieldAnnotations(member),trimmed=stripCommentsForFieldParse(member);if(!trimmed||trimmed.startsWith("//"))continue;const match=trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\??\s*:\s*([\s\S]+)$/);if(!match)continue;const[,fieldName,typeTextRaw]=match,optional=/\?\s*:/.test(trimmed);if(["_id","__bxstate"].includes(fieldName))continue;const fieldSchema=convertTypeFieldToSchemaField(typeTextRaw.trim(),optional);"Text"!==fieldSchema.type||/^(string|BxText|BxEmail|BxUrl|BxObjectId|BxAuth|BxUser|BxPhoneNumber|BxSequence)\b/.test(typeTextRaw.trim())||warnings.push(`Field "${collectionId}.${fieldName}" used fallback Text for type "${typeTextRaw.trim()}"`),(null==(_a=fieldSchema.propertiesScheme)?void 0:_a.ref)&&enumMap.has(fieldSchema.propertiesScheme.ref)&&(fieldSchema.propertiesScheme.ref=enumMap.get(fieldSchema.propertiesScheme.ref));const annotatedField=applyFieldAnnotations(fieldSchema,annotations,warnings,`${collectionId}.${fieldName}`);(null==(_b=annotatedField.propertiesScheme)?void 0:_b.ref)&&enumMap.has(annotatedField.propertiesScheme.ref)&&(annotatedField.propertiesScheme.ref=enumMap.get(annotatedField.propertiesScheme.ref)),formSchema[fieldName]=annotatedField}collections.push({collection_id:collectionId,form_schema:formSchema})}return{collections:collections,warnings:warnings}}(typeContent,filters);let finalCollections=collections,hasBaseCollections=!1;if(baseCollectionsFilePath&&await fs.pathExists(baseCollectionsFilePath)){hasBaseCollections=!0;const baseCollections=await fs.readJson(baseCollectionsFilePath);if(Array.isArray(baseCollections)){const baseById=new Map(baseCollections.map(collection=>[collection.collection_id,collection]));finalCollections=collections.map(collection=>{const base=baseById.get(collection.collection_id);return base?normalizeCollectionForCode(function mergeCollectionWithBase(baseCollection,inferredCollection){const baseSchema=(null==baseCollection?void 0:baseCollection.form_schema)&&"object"==typeof baseCollection.form_schema?baseCollection.form_schema:{},inferredSchema=(null==inferredCollection?void 0:inferredCollection.form_schema)&&"object"==typeof inferredCollection.form_schema?inferredCollection.form_schema:{},mergedSchema={},keys=new Set([...Object.keys(baseSchema),...Object.keys(inferredSchema)]);for(const key of keys)mergedSchema[key]=mergeSchemaField(baseSchema[key],inferredSchema[key]);return{...inferredCollection,...baseCollection,form_schema:mergedSchema}}(base,collection)):collection}).filter(Boolean)}}if(!hasBaseCollections&&!1===options.allowLossy)throw new Error([`Base collections file not found: ${baseCollectionsFilePath||"(not specified)"}`,"Conversion without base metadata is lossy and usually produces a large schema:diff.","Run schema:pull first, or pass --base-collections-file <path>, or remove --no-allow-lossy."].join("\n"));if(hasBaseCollections||console.log(chalk.yellow("! Running lossy convert without base metadata (titles/choices/collection metadata may be dropped)")),warnings.length){console.log(chalk.yellow(`Conversion warnings (${warnings.length}):`));for(const warning of warnings)console.log(chalk.yellow(` - ${warning}`))}options.dryRun?(console.log(chalk.cyan(`~ would write converted collections to: ${outputCollectionsFilePath}`)),printDryRunFilePreview$1(outputCollectionsFilePath,JSON.stringify(finalCollections,null,2))):(await fs.ensureDir(path.dirname(outputCollectionsFilePath)),await fs.writeJson(outputCollectionsFilePath,finalCollections,{spaces:2}),console.log(chalk.green("✓ Converted collections written to:"),outputCollectionsFilePath),console.log(chalk.blue("Next step:")),console.log(chalk.cyan(` buildx-cli schema:push --collections-file "${outputCollectionsFilePath}" --project-id <project-id> --dry-run`)))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),syncCommand=schemaSyncCommand,ASYNC_ARROW_FUNCTION_REGEX=/^\s*async\s*\(\s*[A-Za-z_$][\w$]*(?:\s*:[^,]+)?\s*,\s*[A-Za-z_$][\w$]*(?:\s*:[^)]+)?\s*\)\s*=>\s*\{([\s\S]*)\}\s*;?\s*$/,FUNCTION_DECLARATION_REGEX=/^\s*(?:async\s+)?function(?:\s+[A-Za-z_$][\w$]*)?\s*\(\s*[A-Za-z_$][\w$]*(?:\s*:[^,]+)?\s*,\s*[A-Za-z_$][\w$]*(?:\s*:[^)]+)?\s*\)\s*\{[\s\S]*\}\s*;?\s*$/;function applyFunctionPullOptions(command){return command.option("-p, --project-id <project-id>","Project ID to sync functions from (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for function artifacts").option("--context-output <path>","Output path for function context schema","./buildx/generated/function-context.d.ts").option("--functions-dir <path>","Directory to store function source files","./buildx/functions").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only include functions matching wildcard pattern(s)").option("--full-context","Write full context schema from API (default writes compact schema)").option("--module-wrap","Wrap function code into ESM module format (experimental)").option("--no-validate-code","Skip runtime compatibility validation").option("--no-lint","Skip basic syntax lint checks").option("--dry-run","Preview sync result without writing local files").option("-f, --force","Force overwrite existing local files")}function printDryRunFilePreview(filePath,content){console.log(chalk.cyan(`\n--- DRY RUN: ${filePath} ---`)),console.log(content),console.log(chalk.cyan(`--- END DRY RUN: ${filePath} ---\n`))}function ensureConfigured(){apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config:setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1))}function resolveProjectId(projectId){if(projectId)return projectId;const defaultProjectId=configManager.getDefaultProject();if(defaultProjectId)return console.log(chalk.blue("Using project ID:"),defaultProjectId),defaultProjectId;const envConfig=loadEnvConfig();if(envConfig.BUILDX_PROJECT_ID)return console.log(chalk.blue("Using project ID from environment variable:"),envConfig.BUILDX_PROJECT_ID),envConfig.BUILDX_PROJECT_ID;console.error(chalk.red("Error: No project ID specified")),console.log(chalk.yellow("Use --project-id option, set a default project with 'buildx projects:set-default', or set BUILDX_PROJECT_ID environment variable")),process.exit(1)}function toFunctionFilename(functionName){return`${function sanitizeFileName(name){return name.replace(/[^a-zA-Z0-9._-]/g,"_")}(functionName)}.ts`}function getFunctionManifestPath(functionsDirPath){return path.join(functionsDirPath,"functions.manifest.json")}function filterFunctions(functions,filters){return filters.length?functions.filter(fn=>matchByFilters(String(fn.name||""),filters)):functions}function toImportPathWithoutExtension(fromFilePath,toFilePath){const withoutExt=path.relative(path.dirname(fromFilePath),toFilePath).split(path.sep).join("/").replace(/\.[^.]+$/,"");return withoutExt.startsWith(".")?withoutExt:`./${withoutExt}`}function normalizeFunctionSource(code,contextImportPath){const trimmed=code.trim();if(!trimmed)return[`import type { FlowContext, FlowData } from "${contextImportPath}";`,"","const handler = async (data: FlowData, context: FlowContext) => {","\treturn { data, context };","};","","export default handler;",""].join("\n");if(/\bexport\s+default\b/.test(trimmed)||/\bmodule\.exports\b/.test(trimmed))return`${trimmed}\n`;return/^(async\s*)?\([\s\S]*\)\s*=>\s*[\s\S]+$/.test(trimmed)?function wrapArrowFunctionSource(code,contextImportPath){return[`import type { FlowContext, FlowData } from "${contextImportPath}";`,"",`const handler = ${code.trim()};`,"","export default handler;",""].join("\n")}(trimmed,contextImportPath):`${trimmed}\n`}function preserveFunctionSource(code){const trimmed=code.trim();return trimmed?`${trimmed}\n`:""}function compactFunctionMetadata(detail){const metadata={};return detail.group_path&&(metadata.group_path=detail.group_path),Array.isArray(detail.compatible)&&detail.compatible.length>0&&(metadata.compatible=detail.compatible),detail.collection_id&&(metadata.collection_id=detail.collection_id),"boolean"==typeof detail.allow_anonymous&&(metadata.allow_anonymous=detail.allow_anonymous),Array.isArray(detail.allow_method)&&detail.allow_method.length>0&&(metadata.allow_method=detail.allow_method),detail.input_schema&&"{}"!==detail.input_schema&&(metadata.input_schema=detail.input_schema),detail.output_schema&&"{}"!==detail.output_schema&&(metadata.output_schema=detail.output_schema),detail.output_format&&"object"==typeof detail.output_format&&(metadata.output_format=detail.output_format),metadata}function validateFunctionRuntimeCode(code){const trimmed=String(code||"").trim();if(!trimmed)return{valid:!1,reason:"code is empty"};if(FUNCTION_DECLARATION_REGEX.test(trimmed))return{valid:!0};const arrowMatch=trimmed.match(ASYNC_ARROW_FUNCTION_REGEX);if(arrowMatch){const body=(arrowMatch[1]||"").trim();return ASYNC_ARROW_FUNCTION_REGEX.test(body)?{valid:!1,reason:"nested async wrapper detected (double-wrapped function body)"}:{valid:!0}}return{valid:!1,reason:"expected runtime wrapper function, e.g. async (data, context) => { ... }"}}function stripTypeFromParam(param){const withoutDefault=param.trim(),colonIndex=withoutDefault.indexOf(":");return(colonIndex>=0?withoutDefault.slice(0,colonIndex).trim():withoutDefault).replace(/\?/g,"")}function lintFunctionRuntimeCode(code){const trimmed=String(code||"").trim();if(!trimmed)return{valid:!1,reason:"code is empty"};try{const jsLikeCode=function toLintableRuntimeCode(code){const trimmed=String(code||"").trim();if(!trimmed)return trimmed;const arrowSignature=trimmed.match(/^(\s*async\s*)\(([\s\S]*?)\)(\s*=>\s*\{[\s\S]*\}\s*;?\s*)$/);if(arrowSignature){const params=arrowSignature[2].split(",").map(p=>stripTypeFromParam(p)).join(", ");return`${arrowSignature[1]}(${params})${arrowSignature[3]}`}const fnSignature=trimmed.match(/^(\s*(?:async\s+)?function(?:\s+[A-Za-z_$][\w$]*)?\s*)\(([\s\S]*?)\)(\s*\{[\s\S]*\}\s*;?\s*)$/);if(fnSignature){const params=fnSignature[2].split(",").map(p=>stripTypeFromParam(p)).join(", ");return`${fnSignature[1]}(${params})${fnSignature[3]}`}return trimmed}(trimmed);return jsLikeCode.startsWith("async")?new Function(`return (${jsLikeCode});`)():new Function(`${jsLikeCode}; return true;`)(),{valid:!0}}catch(error){return{valid:!1,reason:`syntax check failed (${error instanceof Error?error.message:"unknown error"})`}}}async function runFunctionPull(options){var _a;ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,contextOutputPath=targetDirPath?path.join(targetDirPath,"function-context.d.ts"):toAbsolutePath(options.contextOutput),functionsDirPath=targetDirPath?path.join(targetDirPath,"functions"):toAbsolutePath(options.functionsDir),manifestPath=getFunctionManifestPath(functionsDirPath),previousManifest=await readJsonIfExists(manifestPath),contextSpinner=ora("Fetching function context schema...").start(),contextInfo=await apiService.getFunctionContextSchemaInfo(projectId),contextSchema=options.fullContext?function ensureFlowDataType(schema){return/\btype\s+FlowData\b/.test(schema)||/\binterface\s+FlowData\b/.test(schema)?schema:`${schema.trimEnd()}\n\nexport type FlowData = Record<string, any>;\n`}(contextInfo.schema):function buildCompactContextSchema(rawSchema){const lines=["// Auto-generated by buildx-cli (compact mode).","// Use --full-context to keep the full remote schema.","","export type FlowData = Record<string, any>;","export type FlowContext = Record<string, any>;","","export interface CodeContext {","\tcontext: FlowContext;","\tdata: FlowData;","\t[key: string]: any;","}",""];return rawSchema.includes("type LODASH_TYPE")&&lines.splice(3,0,"type LODASH_TYPE = any;"),rawSchema.includes("type URL_SEARCH_PARAMS_TYPE")&&lines.splice(3,0,"type URL_SEARCH_PARAMS_TYPE = any;"),lines.join("\n")}(contextInfo.schema);if(contextSpinner.succeed("Function context schema fetched"),await fs.ensureDir(path.dirname(contextOutputPath)),await fs.pathExists(contextOutputPath)&&!options.force){if(sha256(await fs.readFile(contextOutputPath,"utf8"))!==sha256(contextSchema))throw new Error(`Context file has local edits: ${contextOutputPath}. Use --force to overwrite.`)}options.dryRun?(console.log(chalk.cyan(`~ would write function context schema: ${contextOutputPath}`)),printDryRunFilePreview(contextOutputPath,contextSchema)):await fs.writeFile(contextOutputPath,contextSchema,"utf8"),await fs.ensureDir(functionsDirPath);const listSpinner=ora("Fetching function list...").start(),filters=parseFilters(options.filter),functions=filterFunctions(await apiService.listFunctions(projectId),filters);listSpinner.succeed(`Fetched ${functions.length} functions`);const entries=[];for(const fn of functions){const name=String(fn.name||"");if(!name)continue;const detail=await apiService.getFunction(projectId,name),filename=toFunctionFilename(name),filePath=path.join(functionsDirPath,filename),contextImportPath=toImportPathWithoutExtension(filePath,contextOutputPath),sourceCode=String(detail.code||"");if(options.validateCode){const validation=validateFunctionRuntimeCode(sourceCode);validation.valid||console.log(chalk.yellow(`⚠ ${name}: runtime validation warning (${validation.reason})`))}if(options.lint){const lintResult=lintFunctionRuntimeCode(sourceCode);lintResult.valid||console.log(chalk.yellow(`⚠ ${name}: lint warning (${lintResult.reason})`))}const code=options.moduleWrap?normalizeFunctionSource(sourceCode,contextImportPath):preserveFunctionSource(sourceCode),localChecksum=sha256(code);if(await fs.pathExists(filePath)&&!options.force){const previousEntry=null==(_a=null==previousManifest?void 0:previousManifest.functions)?void 0:_a.find(entry=>entry.name===name),existingChecksum=sha256(await fs.readFile(filePath,"utf8"));if(previousEntry&&existingChecksum!==previousEntry.localChecksum){console.log(chalk.yellow(`⚠ Skipped ${name}: local file changed (use --force to overwrite)`));continue}}options.dryRun?(console.log(chalk.cyan(`~ would write function source: ${filePath}`)),printDryRunFilePreview(filePath,code)):await fs.writeFile(filePath,code,"utf8"),entries.push({name:name,file:filename,remoteChecksum:detail.checksum,localChecksum:localChecksum,metadata:compactFunctionMetadata(detail)})}const manifest={version:1,projectId:projectId,generatedAt:(new Date).toISOString(),context:{file:path.relative(path.dirname(manifestPath),contextOutputPath),checksum:contextInfo.checksum,version:contextInfo.version},functions:entries.sort((a,b)=>a.name.localeCompare(b.name))};options.dryRun?(console.log(chalk.cyan(`~ would write function manifest: ${manifestPath}`)),console.log(chalk.blue("Functions count:"),entries.length),printDryRunFilePreview(manifestPath,JSON.stringify(manifest,null,2))):(await fs.writeJson(manifestPath,manifest,{spaces:2}),console.log(chalk.green("✓ Function context schema:"),contextOutputPath),console.log(chalk.green("✓ Function sources:"),functionsDirPath),console.log(chalk.green("✓ Function manifest:"),manifestPath))}const functionSyncCommand=applyFunctionPullOptions(new Command("function:sync").description("Deprecated alias of function:pull (kept for compatibility)")).action(async options=>{try{console.log(chalk.yellow("function:sync is deprecated. Use function:pull.")),await runFunctionPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionPullCommand=applyFunctionPullOptions(new Command("function:pull").description("Pull function context type + function source files into local project")).action(async options=>{try{await runFunctionPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionPushCommand=new Command("function:push").description("Push local function source files back to project").option("-p, --project-id <project-id>","Project ID to push functions to (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for function artifacts").option("--functions-dir <path>","Directory containing function source files","./buildx/functions").option("-n, --name <function-name>","Push only one function by name").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only push functions matching wildcard pattern(s)").option("--no-validate-code","Skip runtime compatibility validation before push").option("--no-lint","Skip basic syntax lint checks before push").option("--dry-run","Show what would be pushed").option("-f, --force","Force push even when remote drift is detected").action(async options=>{try{ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,functionsDirPath=targetDirPath?path.join(targetDirPath,"functions"):toAbsolutePath(options.functionsDir),manifestPath=getFunctionManifestPath(functionsDirPath),manifest=await readJsonIfExists(manifestPath);if(!manifest)throw new Error(`Function manifest not found: ${manifestPath}. Run function:sync first.`);const filters=parseFilters(options.filter),filteredFromManifest=filterFunctions(manifest.functions,filters),targets=options.name?filteredFromManifest.filter(entry=>entry.name===options.name):filteredFromManifest;if(0===targets.length)throw new Error(options.name?`Function "${options.name}" not found in manifest`:"No functions in manifest");if(options.validateCode){const invalidEntries=[];for(const entry of targets){const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath))continue;const validation=validateFunctionRuntimeCode(await fs.readFile(filePath,"utf8"));validation.valid||invalidEntries.push(`${entry.name}: ${validation.reason}`)}if(invalidEntries.length>0)throw new Error(`Function code validation failed:\n- ${invalidEntries.join("\n- ")}\nUse --no-validate-code to bypass.`)}if(options.lint){const lintErrors=[];for(const entry of targets){const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath))continue;const lintResult=lintFunctionRuntimeCode(await fs.readFile(filePath,"utf8"));lintResult.valid||lintErrors.push(`${entry.name}: ${lintResult.reason}`)}if(lintErrors.length>0)throw new Error(`Function lint failed:\n- ${lintErrors.join("\n- ")}\nUse --no-lint to bypass.`)}let pushed=0,skipped=0;const updatedEntries=[];for(const entry of manifest.functions){if(!targets.find(item=>item.name===entry.name)){updatedEntries.push(entry);continue}const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath)){console.log(chalk.yellow(`⚠ Skipped ${entry.name}: source file missing (${filePath})`)),skipped++,updatedEntries.push(entry);continue}const code=await fs.readFile(filePath,"utf8"),localChecksum=sha256(code),remote=await apiService.getFunction(projectId,entry.name).catch(()=>null),remoteChecksum=null==remote?void 0:remote.checksum;if(!(!entry.remoteChecksum||!remoteChecksum||remoteChecksum===entry.remoteChecksum)&&!options.force){console.log(chalk.yellow(`⚠ Skipped ${entry.name}: remote changed since last sync (use --force to override)`)),skipped++,updatedEntries.push(entry);continue}if(options.dryRun){console.log(chalk.cyan(`~ would push ${entry.name}`)),pushed++,updatedEntries.push({...entry,localChecksum:localChecksum});continue}const payload={...entry.metadata,code:code},saved=await apiService.upsertFunction(projectId,entry.name,payload),nextEntry={...entry,remoteChecksum:(null==saved?void 0:saved.checksum)||remoteChecksum,localChecksum:localChecksum};updatedEntries.push(nextEntry),console.log(chalk.green(`✓ pushed ${entry.name}`)),pushed++}manifest.generatedAt=(new Date).toISOString(),manifest.functions=updatedEntries.sort((a,b)=>a.name.localeCompare(b.name)),await fs.writeJson(manifestPath,manifest,{spaces:2}),console.log(chalk.blue(`Done. pushed=${pushed}, skipped=${skipped}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionListCommand=new Command("function:list").description("List remote functions in project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Filter function names by wildcard pattern(s)").action(async options=>{try{ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const filters=parseFilters(options.filter),functions=filterFunctions(await apiService.listFunctions(projectId),filters).sort((a,b)=>String(a.name||"").localeCompare(String(b.name||"")));for(const fn of functions)console.log(fn.name);console.log(chalk.blue(`Total: ${functions.length}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionDiffCommand=new Command("function:diff").description("Diff local function sources against remote project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for function artifacts").option("--functions-dir <path>","Directory containing function source files","./buildx/functions").option("-u, --api-url <url>","Custom API base URL").option("-n, --name <function-name>","Diff only one function by name").option("--filter <pattern...>","Filter function names by wildcard pattern(s)").action(async options=>{try{ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,functionsDirPath=targetDirPath?path.join(targetDirPath,"functions"):toAbsolutePath(options.functionsDir),manifestPath=getFunctionManifestPath(functionsDirPath),manifest=await readJsonIfExists(manifestPath);if(!manifest)throw new Error(`Function manifest not found: ${manifestPath}. Run function:sync first.`);const filters=parseFilters(options.filter);let targets=filterFunctions(manifest.functions,filters);if(options.name&&(targets=targets.filter(entry=>entry.name===options.name)),!targets.length)throw new Error("No functions matched filters/name");let same=0,changed=0,missingLocal=0,missingRemote=0,remoteDrift=0;for(const entry of targets){const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath)){console.log(chalk.yellow(`+ local-missing ${entry.name}`)),missingLocal++;continue}const localChecksum=sha256(await fs.readFile(filePath,"utf8")),remote=await apiService.getFunction(projectId,entry.name).catch(()=>null);if(!remote){console.log(chalk.yellow(`- remote-missing ${entry.name}`)),missingRemote++;continue}entry.remoteChecksum&&remote.checksum&&entry.remoteChecksum!==remote.checksum&&(console.log(chalk.yellow(`! remote-drift ${entry.name}`)),remoteDrift++);localChecksum===(remote.checksum||sha256(String(remote.code||"")))?(console.log(chalk.gray(`= same ${entry.name}`)),same++):(console.log(chalk.cyan(`~ changed ${entry.name}`)),changed++)}console.log(chalk.blue(`Summary: changed=${changed}, same=${same}, local-missing=${missingLocal}, remote-missing=${missingRemote}, remote-drift=${remoteDrift}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),projectsListCommand=new Command("projects:list").description("List available projects").action(async()=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1));const spinner=ora("Fetching projects...").start();try{const projects=await apiService.getProjects();if(spinner.succeed(`Found ${projects.length} projects`),0===projects.length)return void console.log(chalk.yellow("No projects found"));const defaultProject=configManager.getDefaultProject();console.log("\n"+chalk.blue.bold("Available Projects:")),projects.forEach(project=>{const prefix=project.project_id===defaultProject?chalk.green("★ "):" ";console.log(`${prefix}${chalk.bold(project.name)} (${project.project_id})`),project.apiUrl&&console.log(` API: ${chalk.gray(project.apiUrl)}`)}),defaultProject&&console.log(chalk.green("\n★ Default project"))}catch(error){throw spinner.fail("Failed to fetch projects"),error}}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),projectsSetDefaultCommand=new Command("projects:set-default").description("Set default project").argument("<project-id>","Project ID to set as default").action(async projectId=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config:setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1));let project=configManager.getProject(projectId);if(!project){console.log(chalk.yellow("Project not found in local config. Fetching from API..."));const found=(await apiService.getProjects()).find(p=>p.project_id===projectId);if(found)configManager.addProject(found),project=found;else{loadEnvConfig().BUILDX_PROJECT_ID===projectId?(project={project_id:projectId,name:projectId},configManager.addProject(project)):(console.error(chalk.red("Error: Project not found in configuration or API")),console.log(chalk.yellow('Run "buildx projects:list" to see available projects')),process.exit(1))}}configManager.setDefaultProject(projectId),console.log(chalk.green("✓ Default project set to:"),project.name),console.log(chalk.blue("Project ID:"),project.project_id)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),projectsCurrentCommand=new Command("projects:current").description("Show current default project").action(()=>{try{const defaultProjectId=configManager.getDefaultProject();if(!defaultProjectId)return console.log(chalk.yellow("No default project set")),void console.log(chalk.blue('Use "buildx projects:set-default <project-id>" to set a default project'));const project=configManager.getProject(defaultProjectId);if(!project)return console.log(chalk.red("Error: Default project not found in configuration")),void console.log(chalk.blue("Project ID:"),defaultProjectId);console.log(chalk.green("Current default project:")),console.log(chalk.blue("Name:"),project.name),console.log(chalk.blue("ID:"),project.project_id),project.apiUrl&&console.log(chalk.blue("API URL:"),project.apiUrl)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),setupCommand=new Command("config:setup").description("Configure API endpoint and API key").option("-e, --endpoint <endpoint>","API endpoint URL").option("-k, --api-key <apiKey>","API key").action(async options=>{var _a,_b;try{let endpoint=options.endpoint,apiKey=options.apiKey;if(!endpoint||!apiKey){console.log(chalk.blue("🔧 BuildX CLI Setup")),console.log(chalk.gray("Configure your API endpoint and API key to get started.")),console.log(chalk.gray("Supports .env / env aliases: NEXT_PUBLIC_API_ENDPOINT, NEXT_PUBLIC_API_KEY, NEXT_PUBLIC_BUILDX_API_ENDPOINT, NEXT_PUBLIC_BUILDX_API_KEY, BUILDX_API_ENDPOINT, BUILDX_API_KEY.\n"));const currentConfig=configManager.getApiConfig(),envConfig=loadEnvConfig();if(!endpoint&&!apiKey&&envConfig.BUILDX_API_ENDPOINT&&envConfig.BUILDX_API_KEY){const envApiKey=envConfig.BUILDX_API_KEY,slicedApiKey2=envApiKey.substring(0,2),endpointSource=(null==(_a=envConfig._sources)?void 0:_a.endpointKey)||"unknown",apiKeySource=(null==(_b=envConfig._sources)?void 0:_b.apiKeyKey)||"unknown";console.log(chalk.yellow("Detected API config from environment/.env")),console.log(chalk.gray(` Endpoint: ${envConfig.BUILDX_API_ENDPOINT} (${endpointSource})`)),console.log(chalk.gray(` API Key: ${slicedApiKey2}${"*".repeat(Math.min(envApiKey.length-slicedApiKey2.length,8))}... (${apiKeySource})`));const{useEnvConfig:useEnvConfig}=await inquirer.prompt([{type:"confirm",name:"useEnvConfig",message:"Use detected environment values?",default:!0}]);useEnvConfig&&(endpoint=envConfig.BUILDX_API_ENDPOINT,apiKey=envConfig.BUILDX_API_KEY)}if(!endpoint||!apiKey){const answers=await inquirer.prompt([{type:"input",name:"endpoint",message:"Enter your API endpoint URL:",default:endpoint||(null==currentConfig?void 0:currentConfig.endpoint)||envConfig.BUILDX_API_ENDPOINT||"https://api.buildx.com",validate:input=>{if(!input.trim())return"Endpoint URL is required";try{return new URL(input),!0}catch{return"Please enter a valid URL"}}},{type:"password",name:"apiKey",message:"Enter your API key:",default:apiKey||(null==currentConfig?void 0:currentConfig.apiKey)||envConfig.BUILDX_API_KEY||"",validate:input=>!!input.trim()||"API key is required"}]);endpoint=answers.endpoint,apiKey=answers.apiKey}}configManager.setApiConfig({endpoint:endpoint.trim(),apiKey:apiKey.trim()});const slicedApiKey=apiKey.substring(0,2);console.log(chalk.green("✅ Configuration saved successfully!")),console.log(chalk.gray(`Endpoint: ${endpoint}`)),console.log(chalk.gray(`API Key: ${slicedApiKey}${"*".repeat(Math.min(apiKey.length-slicedApiKey.length,8))}...`)),console.log(chalk.blue("\nYou can now use the CLI commands. Start with:")),console.log(chalk.cyan(" buildx auth:login")),console.log(chalk.cyan(" buildx projects:list"))}catch(error){console.error(chalk.red("❌ Setup failed:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),configShowCommand=new Command("config:show").description("Show current configuration").action(()=>{var _a,_b,_c;try{const apiConfig=configManager.getApiConfig(),authConfig=configManager.getAuth(),projectsConfig=configManager.getProjects(),syncConfig=configManager.getSyncConfig(),envConfig=loadEnvConfig();if(console.log(chalk.blue("🔧 BuildX CLI Configuration")),console.log(chalk.gray("=".repeat(50))),console.log(chalk.yellow("\n📡 API Configuration:")),apiConfig){console.log(chalk.green(" ✅ Configured")),console.log(chalk.gray(` Endpoint: ${apiConfig.endpoint}`));const slicedApiKey=apiConfig.apiKey.substring(0,2);console.log(chalk.gray(` API Key: ${slicedApiKey}${"*".repeat(Math.min(apiConfig.apiKey.length-slicedApiKey.length,8))}...`));const storedConfig=configManager.config.get("api");if((null==storedConfig?void 0:storedConfig.endpoint)&&(null==storedConfig?void 0:storedConfig.apiKey))console.log(chalk.gray(" Source: Stored configuration"));else if(envConfig.BUILDX_API_ENDPOINT&&envConfig.BUILDX_API_KEY){if(console.log(chalk.gray(" Source: Environment variables")),envConfig.BUILDX_API_ENDPOINT){const endpointKey=(null==(_a=envConfig._sources)?void 0:_a.endpointKey)||"BUILDX_API_ENDPOINT";console.log(chalk.gray(` Env: ${endpointKey}=${envConfig.BUILDX_API_ENDPOINT}`))}if(envConfig.BUILDX_API_KEY){const slicedApiKey2=envConfig.BUILDX_API_KEY.substring(0,2),apiKeyKey=(null==(_b=envConfig._sources)?void 0:_b.apiKeyKey)||"BUILDX_API_KEY";console.log(chalk.gray(` Env: ${apiKeyKey}=${slicedApiKey2}${"*".repeat(Math.min(envConfig.BUILDX_API_KEY.length-slicedApiKey2.length,8))}...`))}}}else console.log(chalk.red(" ❌ Not configured")),console.log(chalk.gray(' Run "buildx config setup" to configure')),console.log(chalk.gray(" Or set BUILDX_API_ENDPOINT and BUILDX_API_KEY environment variables"));if(console.log(chalk.yellow("\n🔐 Authentication:")),authConfig&&configManager.isAuthenticated()?(console.log(chalk.green(" ✅ Authenticated")),console.log(chalk.gray(` Token: ${authConfig.token.substring(0,20)}...`)),authConfig.expiresAt&&console.log(chalk.gray(` Expires: ${new Date(authConfig.expiresAt).toLocaleString()}`))):(console.log(chalk.red(" ❌ Not authenticated")),console.log(chalk.gray(' Run "buildx auth:login" to authenticate'))),console.log(chalk.yellow("\n📁 Projects:")),(null==projectsConfig?void 0:projectsConfig.list)&&projectsConfig.list.length>0){if(console.log(chalk.green(` ✅ ${projectsConfig.list.length} project(s) available`)),projectsConfig.default){const defaultProject=projectsConfig.list.find(p=>p.project_id===projectsConfig.default);console.log(chalk.gray(` Default: ${(null==defaultProject?void 0:defaultProject.name)||projectsConfig.default}`))}}else if(console.log(chalk.red(" ❌ No projects available")),console.log(chalk.gray(' Run "buildx projects:list" to fetch projects')),envConfig.BUILDX_PROJECT_ID){const projectIdKey=(null==(_c=envConfig._sources)?void 0:_c.projectIdKey)||"BUILDX_PROJECT_ID";console.log(chalk.gray(` Env default candidate: ${projectIdKey}=${envConfig.BUILDX_PROJECT_ID}`))}console.log(chalk.yellow("\n🔄 Sync Configuration:")),syncConfig?console.log(chalk.gray(` Output Path: ${syncConfig.outputPath}`)):console.log(chalk.gray(" Using default sync configuration")),console.log(chalk.yellow("\n📂 Configuration File:")),console.log(chalk.gray(` ${configManager.getConfigPath()}`))}catch(error){console.error(chalk.red("❌ Failed to show configuration:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),configClearCommand=new Command("config:clear").description("Clear all CLI configuration (API, auth, projects, sync)").action(()=>{try{configManager.clear(),console.log(chalk.green("✅ All configuration cleared.")),console.log(chalk.yellow('You must run "buildx config setup" before using the CLI again.'))}catch(error){console.error(chalk.red("❌ Failed to clear configuration:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}});new Command("config").description("Manage CLI configuration").addCommand(setupCommand).addCommand(configShowCommand).addCommand(configClearCommand);const program=new Command,version=JSON.parse(fs$2.readFileSync("./package.json","utf8")).version;program.name("buildx").description("BuildX CLI - API authentication, project management, and schema synchronization tool").version(version,"-v, --version"),program.addCommand(loginCommand),program.addCommand(logoutCommand),program.addCommand(authStatusCommand),program.addCommand(syncCommand),program.addCommand(schemaPullCommand),program.addCommand(schemaPushCommand),program.addCommand(schemaListCommand),program.addCommand(schemaDiffCommand),program.addCommand(schemaTypesConvertCommand),program.addCommand(functionSyncCommand),program.addCommand(functionPullCommand),program.addCommand(functionPushCommand),program.addCommand(functionListCommand),program.addCommand(functionDiffCommand),program.addCommand(projectsListCommand),program.addCommand(projectsSetDefaultCommand),program.addCommand(projectsCurrentCommand),program.addCommand(setupCommand),program.addCommand(configShowCommand),program.addCommand(configClearCommand),program.exitOverride();try{program.parse()}catch(err){err instanceof Error?console.error(chalk.red("Error:"),err.message):console.error(chalk.red("An unexpected error occurred")),process.exit(1)}
|
|
14
|
+
*/(),extname=path.extname,EXTRACT_TYPE_REGEXP=/^\s*([^;\s]*)(?:;|\s|$)/,TEXT_TYPE_REGEXP=/^text\//i;function charset(type){if(!type||"string"!=typeof type)return!1;var match=EXTRACT_TYPE_REGEXP.exec(type),mime=match&&db[match[1].toLowerCase()];return mime&&mime.charset?mime.charset:!(!match||!TEXT_TYPE_REGEXP.test(match[1]))&&"UTF-8"}exports$1.charset=charset,exports$1.charsets={lookup:charset},exports$1.contentType=function contentType(str){if(!str||"string"!=typeof str)return!1;var mime=-1===str.indexOf("/")?exports$1.lookup(str):str;if(!mime)return!1;if(-1===mime.indexOf("charset")){var charset=exports$1.charset(mime);charset&&(mime+="; charset="+charset.toLowerCase())}return mime},exports$1.extension=function extension(type){if(!type||"string"!=typeof type)return!1;var match=EXTRACT_TYPE_REGEXP.exec(type),exts=match&&exports$1.extensions[match[1].toLowerCase()];if(!exts||!exts.length)return!1;return exts[0]},exports$1.extensions=Object.create(null),exports$1.lookup=function lookup(path){if(!path||"string"!=typeof path)return!1;var extension=extname("x."+path).toLowerCase().substr(1);if(!extension)return!1;return exports$1.types[extension]||!1},exports$1.types=Object.create(null),function populateMaps(extensions,types){var preference=["nginx","apache",void 0,"iana"];Object.keys(db).forEach(function forEachMimeType(type){var mime=db[type],exts=mime.extensions;if(exts&&exts.length){extensions[type]=exts;for(var i=0;i<exts.length;i++){var extension=exts[i];if(types[extension]){var from=preference.indexOf(db[types[extension]].source),to=preference.indexOf(mime.source);if("application/octet-stream"!==types[extension]&&(from>to||from===to&&"application/"===types[extension].substr(0,12)))continue}types[extension]=type}}})}(exports$1.extensions,exports$1.types)}(mimeTypes)),mimeTypes}function requireAsync$1(){if(hasRequiredAsync$1)return async_1;hasRequiredAsync$1=1;var defer=function requireDefer(){return hasRequiredDefer?defer_1:(hasRequiredDefer=1,defer_1=function defer(fn){var nextTick="function"==typeof setImmediate?setImmediate:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:null;nextTick?nextTick(fn):setTimeout(fn,0)})}();return async_1=function async(callback){var isAsync=!1;return defer(function(){isAsync=!0}),function async_callback(err,result){isAsync?callback(err,result):defer(function nextTick_callback(){callback(err,result)})}}}function requireAbort(){if(hasRequiredAbort)return abort_1;function clean(key){"function"==typeof this.jobs[key]&&this.jobs[key]()}return hasRequiredAbort=1,abort_1=function abort(state){Object.keys(state.jobs).forEach(clean.bind(state)),state.jobs={}},abort_1}function requireIterate(){if(hasRequiredIterate)return iterate_1;hasRequiredIterate=1;var async=requireAsync$1(),abort=requireAbort();return iterate_1=function iterate(list,iterator,state,callback){var key=state.keyedList?state.keyedList[state.index]:state.index;state.jobs[key]=function runJob(iterator,key,item,callback){var aborter;aborter=2==iterator.length?iterator(item,async(callback)):iterator(item,key,async(callback));return aborter}(iterator,key,list[key],function(error,output){key in state.jobs&&(delete state.jobs[key],error?abort(state):state.results[key]=output,callback(error,state.results))})},iterate_1}function requireState(){if(hasRequiredState)return state_1;return hasRequiredState=1,state_1=function state(list,sortMethod){var isNamedList=!Array.isArray(list),initState={index:0,keyedList:isNamedList||sortMethod?Object.keys(list):null,jobs:{},results:isNamedList?{}:[],size:isNamedList?Object.keys(list).length:list.length};sortMethod&&initState.keyedList.sort(isNamedList?sortMethod:function(a,b){return sortMethod(list[a],list[b])});return initState}}function requireTerminator(){if(hasRequiredTerminator)return terminator_1;hasRequiredTerminator=1;var abort=requireAbort(),async=requireAsync$1();return terminator_1=function terminator(callback){if(!Object.keys(this.jobs).length)return;this.index=this.size,abort(this),async(callback)(null,this.results)}}function requireParallel(){if(hasRequiredParallel)return parallel_1;hasRequiredParallel=1;var iterate=requireIterate(),initState=requireState(),terminator=requireTerminator();return parallel_1=function parallel(list,iterator,callback){var state=initState(list);for(;state.index<(state.keyedList||list).length;)iterate(list,iterator,state,function(error,result){error?callback(error,result):0!==Object.keys(state.jobs).length||callback(null,state.results)}),state.index++;return terminator.bind(state,callback)},parallel_1}var hasRequiredSerialOrdered,serial_1,hasRequiredSerial,asynckit,hasRequiredAsynckit,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,shams$1,hasRequiredShams$1,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,shams,hasRequiredShams,esSetTostringtag,hasRequiredEsSetTostringtag,populate,hasRequiredPopulate,form_data,hasRequiredForm_data,serialOrdered={exports:{}};function requireSerialOrdered(){if(hasRequiredSerialOrdered)return serialOrdered.exports;hasRequiredSerialOrdered=1;var iterate=requireIterate(),initState=requireState(),terminator=requireTerminator();function ascending(a,b){return a<b?-1:a>b?1:0}return serialOrdered.exports=function serialOrdered$1(list,iterator,sortMethod,callback){var state=initState(list,sortMethod);return iterate(list,iterator,state,function iteratorHandler(error,result){error?callback(error,result):(state.index++,state.index<(state.keyedList||list).length?iterate(list,iterator,state,iteratorHandler):callback(null,state.results))}),terminator.bind(state,callback)},serialOrdered.exports.ascending=ascending,serialOrdered.exports.descending=function descending(a,b){return-1*ascending(a,b)},serialOrdered.exports}function requireSerial(){if(hasRequiredSerial)return serial_1;hasRequiredSerial=1;var serialOrdered=requireSerialOrdered();return serial_1=function serial(list,iterator,callback){return serialOrdered(list,iterator,null,callback)},serial_1}function requireAsynckit(){return hasRequiredAsynckit?asynckit:(hasRequiredAsynckit=1,asynckit={parallel:requireParallel(),serial:requireSerial(),serialOrdered:requireSerialOrdered()})}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var $isNaN=function require_isNaN(){return hasRequired_isNaN?_isNaN:(hasRequired_isNaN=1,_isNaN=Number.isNaN||function isNaN(a){return a!=a})}();return sign=function sign(number){return $isNaN(number)||0===number?number:number<0?-1:1}}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var $gOPD=function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}();if($gOPD)try{$gOPD([],"length")}catch(e){$gOPD=null}return gopd=$gOPD}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var $defineProperty=Object.defineProperty||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}return esDefineProperty=$defineProperty}function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;for(var _ in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;var syms=Object.getOwnPropertySymbols(obj);if(1!==syms.length||syms[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(42!==descriptor.value||!0!==descriptor.enumerable)return!1}return!0})}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=requireShams$1();return hasSymbols=function hasNativeSymbols(){return"function"==typeof origSymbol&&("function"==typeof Symbol&&("symbol"==typeof origSymbol("foo")&&("symbol"==typeof Symbol("bar")&&hasSymbolSham())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var toStr=Object.prototype.toString,max=Math.max,concatty=function concatty(a,b){for(var arr=[],i=0;i<a.length;i+=1)arr[i]=a[i];for(var j=0;j<b.length;j+=1)arr[j+a.length]=b[j];return arr};return implementation=function bind(that){var target=this;if("function"!=typeof target||"[object Function]"!==toStr.apply(target))throw new TypeError("Function.prototype.bind called on incompatible "+target);for(var bound,args=function slicy(arrLike,offset){for(var arr=[],i=offset,j=0;i<arrLike.length;i+=1,j+=1)arr[j]=arrLike[i];return arr}(arguments,1),boundLength=max(0,target.length-args.length),boundArgs=[],i=0;i<boundLength;i++)boundArgs[i]="$"+i;if(bound=Function("binder","return function ("+function(arr,joiner){for(var str="",i=0;i<arr.length;i+=1)str+=arr[i],i+1<arr.length&&(str+=joiner);return str}(boundArgs,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof bound){var result=target.apply(this,concatty(args,arguments));return Object(result)===result?result:this}return target.apply(that,concatty(args,arguments))}),target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null}return bound},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var implementation=requireImplementation();return functionBind=Function.prototype.bind||implementation}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var bind=requireFunctionBind(),$apply=requireFunctionApply(),$call=requireFunctionCall(),$reflectApply=function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}();return actualApply=$reflectApply||bind.call($call,$apply)}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var hasProtoAccessor,callBind=function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var bind=requireFunctionBind(),$TypeError=requireType(),$call=requireFunctionCall(),$actualApply=requireActualApply();return callBindApplyHelpers=function callBindBasic(args){if(args.length<1||"function"!=typeof args[0])throw new $TypeError("a function is required");return $actualApply(bind,$call,args)},callBindApplyHelpers}(),gOPD=requireGopd();try{hasProtoAccessor=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,"__proto__"),$Object=Object,$getPrototypeOf=$Object.getPrototypeOf;return get=desc&&"function"==typeof desc.get?callBind([desc.get]):"function"==typeof $getPrototypeOf&&function getDunder(value){return $getPrototypeOf(null==value?value:$Object(value))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var reflectGetProto=requireReflect_getPrototypeOf(),originalGetProto=requireObject_getPrototypeOf(),getDunderProto=requireGet();return getProto=reflectGetProto?function getProto(O){return reflectGetProto(O)}:originalGetProto?function getProto(O){if(!O||"object"!=typeof O&&"function"!=typeof O)throw new TypeError("getProto: not an object");return originalGetProto(O)}:getDunderProto?function getProto(O){return getDunderProto(O)}:null}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var call=Function.prototype.call,$hasOwn=Object.prototype.hasOwnProperty,bind=requireFunctionBind();return hasown=bind.call(call,$hasOwn)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;hasRequiredGetIntrinsic=1;var $Object=requireEsObjectAtoms(),$Error=requireEsErrors(),$EvalError=require_eval(),$RangeError=requireRange(),$ReferenceError=requireRef(),$SyntaxError=requireSyntax(),$TypeError=requireType(),$URIError=requireUri(),abs=requireAbs(),floor=requireFloor(),max=requireMax(),min=requireMin(),pow=requirePow(),round=requireRound(),sign=requireSign(),$Function=Function,getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=requireGopd(),$defineProperty=requireEsDefineProperty(),throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=requireHasSymbols()(),getProto=requireGetProto(),$ObjectGPO=requireObject_getPrototypeOf(),$ReflectGPO=requireReflect_getPrototypeOf(),$apply=requireFunctionApply(),$call=requireFunctionCall(),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):void 0,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?void 0:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?void 0:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float16Array%":"undefined"==typeof Float16Array?void 0:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":$Object,"%Object.getOwnPropertyDescriptor%":$gOPD,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):void 0,"%Symbol%":hasSymbols?Symbol:void 0,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet,"%Function.prototype.call%":$call,"%Function.prototype.apply%":$apply,"%Object.defineProperty%":$defineProperty,"%Object.getPrototypeOf%":$ObjectGPO,"%Math.abs%":abs,"%Math.floor%":floor,"%Math.max%":max,"%Math.min%":min,"%Math.pow%":pow,"%Math.round%":round,"%Math.sign%":sign,"%Reflect.getPrototypeOf%":$ReflectGPO};if(getProto)try{null.error}catch(e){var errorProto=getProto(getProto(e));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(name){var value;if("%AsyncFunction%"===name)value=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===name)value=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===name)value=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===name){var fn=doEval("%AsyncGeneratorFunction%");fn&&(value=fn.prototype)}else if("%AsyncIteratorPrototype%"===name){var gen=doEval("%AsyncGenerator%");gen&&getProto&&(value=getProto(gen.prototype))}return INTRINSICS[name]=value,value},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=requireFunctionBind(),hasOwn=requireHasown(),$concat=bind.call($call,Array.prototype.concat),$spliceApply=bind.call($apply,Array.prototype.splice),$replace=bind.call($call,String.prototype.replace),$strSlice=bind.call($call,String.prototype.slice),$exec=bind.call($call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var alias,intrinsicName=name;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(intrinsicName="%"+(alias=LEGACY_ALIASES[intrinsicName])[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval&&(value=doEval(intrinsicName)),void 0===value&&!allowMissing)throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!");return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};return getIntrinsic=function GetIntrinsic(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof allowMissing)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,name))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var parts=function stringToPath(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match}),result}(name),intrinsicBaseName=parts.length>0?parts[0]:"",intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing),intrinsicRealName=intrinsic.name,value=intrinsic.value,skipFurtherCaching=!1,alias=intrinsic.alias;alias&&(intrinsicBaseName=alias[0],$spliceApply(parts,$concat([0,1],alias)));for(var i=1,isOwn=!0;i<parts.length;i+=1){var part=parts[i],first=$strSlice(part,0,1),last=$strSlice(part,-1);if(('"'===first||"'"===first||"`"===first||'"'===last||"'"===last||"`"===last)&&first!==last)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==part&&isOwn||(skipFurtherCaching=!0),hasOwn(INTRINSICS,intrinsicRealName="%"+(intrinsicBaseName+="."+part)+"%"))value=INTRINSICS[intrinsicRealName];else if(null!=value){if(!(part in value)){if(!allowMissing)throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");return}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);value=(isOwn=!!desc)&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[part]}else isOwn=hasOwn(value,part),value=value[part];isOwn&&!skipFurtherCaching&&(INTRINSICS[intrinsicRealName]=value)}}return value},getIntrinsic}function requireEsSetTostringtag(){if(hasRequiredEsSetTostringtag)return esSetTostringtag;hasRequiredEsSetTostringtag=1;var $defineProperty=requireGetIntrinsic()("%Object.defineProperty%",!0),hasToStringTag=function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var hasSymbols=requireShams$1();return shams=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}}()(),hasOwn=requireHasown(),$TypeError=requireType(),toStringTag=hasToStringTag?Symbol.toStringTag:null;return esSetTostringtag=function setToStringTag(object,value){var overrideIfSet=arguments.length>2&&!!arguments[2]&&arguments[2].force,nonConfigurable=arguments.length>2&&!!arguments[2]&&arguments[2].nonConfigurable;if(void 0!==overrideIfSet&&"boolean"!=typeof overrideIfSet||void 0!==nonConfigurable&&"boolean"!=typeof nonConfigurable)throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");!toStringTag||!overrideIfSet&&hasOwn(object,toStringTag)||($defineProperty?$defineProperty(object,toStringTag,{configurable:!nonConfigurable,enumerable:!1,value:value,writable:!1}):object[toStringTag]=value)},esSetTostringtag}function requirePopulate(){return hasRequiredPopulate||(hasRequiredPopulate=1,populate=function(dst,src){return Object.keys(src).forEach(function(prop){dst[prop]=dst[prop]||src[prop]}),dst}),populate}var form_dataExports=function requireForm_data(){if(hasRequiredForm_data)return form_data;hasRequiredForm_data=1;var CombinedStream=requireCombined_stream(),util=require$$1$3,path$1=path,http=require$$3$3,https=require$$4$3,parseUrl=require$$0$a.parse,fs=fs$2,Stream=stream$1.Stream,crypto=crypto$1,mime=requireMimeTypes(),asynckit=requireAsynckit(),setToStringTag=requireEsSetTostringtag(),hasOwn=requireHasown(),populate=requirePopulate();function FormData(options){if(!(this instanceof FormData))return new FormData(options);for(var option in this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],CombinedStream.call(this),options=options||{})this[option]=options[option]}return util.inherits(FormData,CombinedStream),FormData.LINE_BREAK="\r\n",FormData.DEFAULT_CONTENT_TYPE="application/octet-stream",FormData.prototype.append=function(field,value,options){"string"==typeof(options=options||{})&&(options={filename:options});var append=CombinedStream.prototype.append.bind(this);if("number"!=typeof value&&null!=value||(value=String(value)),Array.isArray(value))this._error(new Error("Arrays are not supported."));else{var header=this._multiPartHeader(field,value,options),footer=this._multiPartFooter();append(header),append(value),append(footer),this._trackLength(header,value,options)}},FormData.prototype._trackLength=function(header,value,options){var valueLength=0;null!=options.knownLength?valueLength+=Number(options.knownLength):Buffer.isBuffer(value)?valueLength=value.length:"string"==typeof value&&(valueLength=Buffer.byteLength(value)),this._valueLength+=valueLength,this._overheadLength+=Buffer.byteLength(header)+FormData.LINE_BREAK.length,value&&(value.path||value.readable&&hasOwn(value,"httpVersion")||value instanceof Stream)&&(options.knownLength||this._valuesToMeasure.push(value))},FormData.prototype._lengthRetriever=function(value,callback){hasOwn(value,"fd")?null!=value.end&&value.end!=1/0&&null!=value.start?callback(null,value.end+1-(value.start?value.start:0)):fs.stat(value.path,function(err,stat){if(err)callback(err);else{var fileSize=stat.size-(value.start?value.start:0);callback(null,fileSize)}}):hasOwn(value,"httpVersion")?callback(null,Number(value.headers["content-length"])):hasOwn(value,"httpModule")?(value.on("response",function(response){value.pause(),callback(null,Number(response.headers["content-length"]))}),value.resume()):callback("Unknown stream")},FormData.prototype._multiPartHeader=function(field,value,options){if("string"==typeof options.header)return options.header;var header,contentDisposition=this._getContentDisposition(value,options),contentType=this._getContentType(value,options),contents="",headers={"Content-Disposition":["form-data",'name="'+field+'"'].concat(contentDisposition||[]),"Content-Type":[].concat(contentType||[])};for(var prop in"object"==typeof options.header&&populate(headers,options.header),headers)if(hasOwn(headers,prop)){if(null==(header=headers[prop]))continue;Array.isArray(header)||(header=[header]),header.length&&(contents+=prop+": "+header.join("; ")+FormData.LINE_BREAK)}return"--"+this.getBoundary()+FormData.LINE_BREAK+contents+FormData.LINE_BREAK},FormData.prototype._getContentDisposition=function(value,options){var filename;if("string"==typeof options.filepath?filename=path$1.normalize(options.filepath).replace(/\\/g,"/"):options.filename||value&&(value.name||value.path)?filename=path$1.basename(options.filename||value&&(value.name||value.path)):value&&value.readable&&hasOwn(value,"httpVersion")&&(filename=path$1.basename(value.client._httpMessage.path||"")),filename)return'filename="'+filename+'"'},FormData.prototype._getContentType=function(value,options){var contentType=options.contentType;return!contentType&&value&&value.name&&(contentType=mime.lookup(value.name)),!contentType&&value&&value.path&&(contentType=mime.lookup(value.path)),!contentType&&value&&value.readable&&hasOwn(value,"httpVersion")&&(contentType=value.headers["content-type"]),contentType||!options.filepath&&!options.filename||(contentType=mime.lookup(options.filepath||options.filename)),!contentType&&value&&"object"==typeof value&&(contentType=FormData.DEFAULT_CONTENT_TYPE),contentType},FormData.prototype._multiPartFooter=function(){return function(next){var footer=FormData.LINE_BREAK;0===this._streams.length&&(footer+=this._lastBoundary()),next(footer)}.bind(this)},FormData.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+FormData.LINE_BREAK},FormData.prototype.getHeaders=function(userHeaders){var header,formHeaders={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(header in userHeaders)hasOwn(userHeaders,header)&&(formHeaders[header.toLowerCase()]=userHeaders[header]);return formHeaders},FormData.prototype.setBoundary=function(boundary){if("string"!=typeof boundary)throw new TypeError("FormData boundary must be a string");this._boundary=boundary},FormData.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary},FormData.prototype.getBuffer=function(){for(var dataBuffer=new Buffer.alloc(0),boundary=this.getBoundary(),i=0,len=this._streams.length;i<len;i++)"function"!=typeof this._streams[i]&&(dataBuffer=Buffer.isBuffer(this._streams[i])?Buffer.concat([dataBuffer,this._streams[i]]):Buffer.concat([dataBuffer,Buffer.from(this._streams[i])]),"string"==typeof this._streams[i]&&this._streams[i].substring(2,boundary.length+2)===boundary||(dataBuffer=Buffer.concat([dataBuffer,Buffer.from(FormData.LINE_BREAK)])));return Buffer.concat([dataBuffer,Buffer.from(this._lastBoundary())])},FormData.prototype._generateBoundary=function(){this._boundary="--------------------------"+crypto.randomBytes(12).toString("hex")},FormData.prototype.getLengthSync=function(){var knownLength=this._overheadLength+this._valueLength;return this._streams.length&&(knownLength+=this._lastBoundary().length),this.hasKnownLength()||this._error(new Error("Cannot calculate proper length in synchronous way.")),knownLength},FormData.prototype.hasKnownLength=function(){var hasKnownLength=!0;return this._valuesToMeasure.length&&(hasKnownLength=!1),hasKnownLength},FormData.prototype.getLength=function(cb){var knownLength=this._overheadLength+this._valueLength;this._streams.length&&(knownLength+=this._lastBoundary().length),this._valuesToMeasure.length?asynckit.parallel(this._valuesToMeasure,this._lengthRetriever,function(err,values){err?cb(err):(values.forEach(function(length){knownLength+=length}),cb(null,knownLength))}):process.nextTick(cb.bind(this,null,knownLength))},FormData.prototype.submit=function(params,cb){var request,options,defaults={method:"post"};return"string"==typeof params?(params=parseUrl(params),options=populate({port:params.port,path:params.pathname,host:params.hostname,protocol:params.protocol},defaults)):(options=populate(params,defaults)).port||(options.port="https:"===options.protocol?443:80),options.headers=this.getHeaders(params.headers),request="https:"===options.protocol?https.request(options):http.request(options),this.getLength(function(err,length){if(err&&"Unknown stream"!==err)this._error(err);else if(length&&request.setHeader("Content-Length",length),this.pipe(request),cb){var onResponse,callback=function(error,responce){return request.removeListener("error",callback),request.removeListener("response",onResponse),cb.call(this,error,responce)};onResponse=callback.bind(this,null),request.on("error",callback),request.on("response",onResponse)}}.bind(this)),request},FormData.prototype._error=function(err){this.error||(this.error=err,this.pause(),this.emit("error",err))},FormData.prototype.toString=function(){return"[object FormData]"},setToStringTag(FormData.prototype,"FormData"),form_data=FormData}(),FormData$1=getDefaultExportFromCjs(form_dataExports);function isVisitable(thing){return utils$3.isPlainObject(thing)||utils$3.isArray(thing)}function removeBrackets(key){return utils$3.endsWith(key,"[]")?key.slice(0,-2):key}function renderKey(path,key,dots){return path?path.concat(key).map(function each(token,i){return token=removeBrackets(token),!dots&&i?"["+token+"]":token}).join(dots?".":""):key}const predicates=utils$3.toFlatObject(utils$3,{},null,function filter(prop){return/^is[A-Z]/.test(prop)});function toFormData$1(obj,formData,options){if(!utils$3.isObject(obj))throw new TypeError("target must be an object");formData=formData||new(FormData$1||FormData),options=utils$3.toFlatObject(options,{metaTokens:!0,dots:!1,indexes:!1},!1,function defined(option,source){return!utils$3.isUndefined(source[option])});const metaTokens=options.metaTokens,visitor=options.visitor||defaultVisitor,dots=options.dots,indexes=options.indexes,useBlob=(options.Blob||"undefined"!=typeof Blob&&Blob)&&utils$3.isSpecCompliantForm(formData);if(!utils$3.isFunction(visitor))throw new TypeError("visitor must be a function");function convertValue(value){if(null===value)return"";if(utils$3.isDate(value))return value.toISOString();if(utils$3.isBoolean(value))return value.toString();if(!useBlob&&utils$3.isBlob(value))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$3.isArrayBuffer(value)||utils$3.isTypedArray(value)?useBlob&&"function"==typeof Blob?new Blob([value]):Buffer.from(value):value}function defaultVisitor(value,key,path){let arr=value;if(utils$3.isReactNative(formData)&&utils$3.isReactNativeBlob(value))return formData.append(renderKey(path,key,dots),convertValue(value)),!1;if(value&&!path&&"object"==typeof value)if(utils$3.endsWith(key,"{}"))key=metaTokens?key:key.slice(0,-2),value=JSON.stringify(value);else if(utils$3.isArray(value)&&function isFlatArray(arr){return utils$3.isArray(arr)&&!arr.some(isVisitable)}(value)||(utils$3.isFileList(value)||utils$3.endsWith(key,"[]"))&&(arr=utils$3.toArray(value)))return key=removeBrackets(key),arr.forEach(function each(el,index){!utils$3.isUndefined(el)&&null!==el&&formData.append(!0===indexes?renderKey([key],index,dots):null===indexes?key:key+"[]",convertValue(el))}),!1;return!!isVisitable(value)||(formData.append(renderKey(path,key,dots),convertValue(value)),!1)}const stack=[],exposedHelpers=Object.assign(predicates,{defaultVisitor:defaultVisitor,convertValue:convertValue,isVisitable:isVisitable});if(!utils$3.isObject(obj))throw new TypeError("data must be an object");return function build(value,path){if(!utils$3.isUndefined(value)){if(-1!==stack.indexOf(value))throw Error("Circular reference detected in "+path.join("."));stack.push(value),utils$3.forEach(value,function each(el,key){!0===(!(utils$3.isUndefined(el)||null===el)&&visitor.call(formData,el,utils$3.isString(key)?key.trim():key,path,exposedHelpers))&&build(el,path?path.concat(key):[key])}),stack.pop()}}(obj),formData}function encode$1(str){const charMap={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g,function replacer(match){return charMap[match]})}function AxiosURLSearchParams(params,options){this._pairs=[],params&&toFormData$1(params,this,options)}const prototype=AxiosURLSearchParams.prototype;function encode(val){return encodeURIComponent(val).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(url,params,options){if(!params)return url;const _encode=options&&options.encode||encode,_options=utils$3.isFunction(options)?{serialize:options}:options,serializeFn=_options&&_options.serialize;let serializedParams;if(serializedParams=serializeFn?serializeFn(params,_options):utils$3.isURLSearchParams(params)?params.toString():new AxiosURLSearchParams(params,_options).toString(_encode),serializedParams){const hashmarkIndex=url.indexOf("#");-1!==hashmarkIndex&&(url=url.slice(0,hashmarkIndex)),url+=(-1===url.indexOf("?")?"?":"&")+serializedParams}return url}prototype.append=function append(name,value){this._pairs.push([name,value])},prototype.toString=function toString(encoder){const _encode=encoder?function(value){return encoder.call(this,value,encode$1)}:encode$1;return this._pairs.map(function each(pair){return _encode(pair[0])+"="+_encode(pair[1])},"").join("&")};class InterceptorManager{constructor(){this.handlers=[]}use(fulfilled,rejected,options){return this.handlers.push({fulfilled:fulfilled,rejected:rejected,synchronous:!!options&&options.synchronous,runWhen:options?options.runWhen:null}),this.handlers.length-1}eject(id){this.handlers[id]&&(this.handlers[id]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(fn){utils$3.forEach(this.handlers,function forEachHandler(h){null!==h&&fn(h)})}}var transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},URLSearchParams=require$$0$a.URLSearchParams;const ALPHA="abcdefghijklmnopqrstuvwxyz",ALPHABET={DIGIT:"0123456789",ALPHA:ALPHA,ALPHA_DIGIT:ALPHA+ALPHA.toUpperCase()+"0123456789"};var platform$1={isNode:!0,classes:{URLSearchParams:URLSearchParams,FormData:FormData$1,Blob:"undefined"!=typeof Blob&&Blob||null},ALPHABET:ALPHABET,generateString:(size=16,alphabet=ALPHABET.ALPHA_DIGIT)=>{let str="";const{length:length}=alphabet,randomValues=new Uint32Array(size);crypto$1.randomFillSync(randomValues);for(let i=0;i<size;i++)str+=alphabet[randomValues[i]%length];return str},protocols:["http","https","file","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var platform={...Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),...platform$1};function formDataToJSON(formData){function buildPath(path,value,target,index){let name=path[index++];if("__proto__"===name)return!0;const isNumericKey=Number.isFinite(+name),isLast=index>=path.length;if(name=!name&&utils$3.isArray(target)?target.length:name,isLast)return utils$3.hasOwnProp(target,name)?target[name]=[target[name],value]:target[name]=value,!isNumericKey;target[name]&&utils$3.isObject(target[name])||(target[name]=[]);return buildPath(path,value,target[name],index)&&utils$3.isArray(target[name])&&(target[name]=function arrayToObject(arr){const obj={},keys=Object.keys(arr);let i;const len=keys.length;let key;for(i=0;i<len;i++)key=keys[i],obj[key]=arr[key];return obj}(target[name])),!isNumericKey}if(utils$3.isFormData(formData)&&utils$3.isFunction(formData.entries)){const obj={};return utils$3.forEachEntry(formData,(name,value)=>{buildPath(function parsePropPath(name){return utils$3.matchAll(/\w+|\[(\w*)]/g,name).map(match=>"[]"===match[0]?"":match[1]||match[0])}(name),value,obj,0)}),obj}return null}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function transformRequest(data,headers){const contentType=headers.getContentType()||"",hasJSONContentType=contentType.indexOf("application/json")>-1,isObjectPayload=utils$3.isObject(data);isObjectPayload&&utils$3.isHTMLForm(data)&&(data=new FormData(data));if(utils$3.isFormData(data))return hasJSONContentType?JSON.stringify(formDataToJSON(data)):data;if(utils$3.isArrayBuffer(data)||utils$3.isBuffer(data)||utils$3.isStream(data)||utils$3.isFile(data)||utils$3.isBlob(data)||utils$3.isReadableStream(data))return data;if(utils$3.isArrayBufferView(data))return data.buffer;if(utils$3.isURLSearchParams(data))return headers.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),data.toString();let isFileList;if(isObjectPayload){if(contentType.indexOf("application/x-www-form-urlencoded")>-1)return function toURLEncodedForm(data,options){return toFormData$1(data,new platform.classes.URLSearchParams,{visitor:function(value,key,path,helpers){return platform.isNode&&utils$3.isBuffer(value)?(this.append(key,value.toString("base64")),!1):helpers.defaultVisitor.apply(this,arguments)},...options})}(data,this.formSerializer).toString();if((isFileList=utils$3.isFileList(data))||contentType.indexOf("multipart/form-data")>-1){const _FormData=this.env&&this.env.FormData;return toFormData$1(isFileList?{"files[]":data}:data,_FormData&&new _FormData,this.formSerializer)}}return isObjectPayload||hasJSONContentType?(headers.setContentType("application/json",!1),function stringifySafely(rawValue,parser,encoder){if(utils$3.isString(rawValue))try{return(parser||JSON.parse)(rawValue),utils$3.trim(rawValue)}catch(e){if("SyntaxError"!==e.name)throw e}return(encoder||JSON.stringify)(rawValue)}(data)):data}],transformResponse:[function transformResponse(data){const transitional=this.transitional||defaults.transitional,forcedJSONParsing=transitional&&transitional.forcedJSONParsing,JSONRequested="json"===this.responseType;if(utils$3.isResponse(data)||utils$3.isReadableStream(data))return data;if(data&&utils$3.isString(data)&&(forcedJSONParsing&&!this.responseType||JSONRequested)){const strictJSONParsing=!(transitional&&transitional.silentJSONParsing)&&JSONRequested;try{return JSON.parse(data,this.parseReviver)}catch(e){if(strictJSONParsing){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function validateStatus(status){return status>=200&&status<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$3.forEach(["delete","get","head","post","put","patch"],method=>{defaults.headers[method]={}});const ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const $internals=Symbol("internals");function normalizeHeader(header){return header&&String(header).trim().toLowerCase()}function normalizeValue(value){return!1===value||null==value?value:utils$3.isArray(value)?value.map(normalizeValue):String(value)}function matchHeaderValue(context,value,header,filter,isHeaderNameFilter){return utils$3.isFunction(filter)?filter.call(this,value,header):(isHeaderNameFilter&&(value=header),utils$3.isString(value)?utils$3.isString(filter)?-1!==value.indexOf(filter):utils$3.isRegExp(filter)?filter.test(value):void 0:void 0)}let AxiosHeaders$1=class AxiosHeaders{constructor(headers){headers&&this.set(headers)}set(header,valueOrRewrite,rewrite){const self=this;function setHeader(_value,_header,_rewrite){const lHeader=normalizeHeader(_header);if(!lHeader)throw new Error("header name must be a non-empty string");const key=utils$3.findKey(self,lHeader);(!key||void 0===self[key]||!0===_rewrite||void 0===_rewrite&&!1!==self[key])&&(self[key||_header]=normalizeValue(_value))}const setHeaders=(headers,_rewrite)=>utils$3.forEach(headers,(_value,_header)=>setHeader(_value,_header,_rewrite));if(utils$3.isPlainObject(header)||header instanceof this.constructor)setHeaders(header,valueOrRewrite);else if(utils$3.isString(header)&&(header=header.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(header.trim()))setHeaders((rawHeaders=>{const parsed={};let key,val,i;return rawHeaders&&rawHeaders.split("\n").forEach(function parser(line){i=line.indexOf(":"),key=line.substring(0,i).trim().toLowerCase(),val=line.substring(i+1).trim(),!key||parsed[key]&&ignoreDuplicateOf[key]||("set-cookie"===key?parsed[key]?parsed[key].push(val):parsed[key]=[val]:parsed[key]=parsed[key]?parsed[key]+", "+val:val)}),parsed})(header),valueOrRewrite);else if(utils$3.isObject(header)&&utils$3.isIterable(header)){let dest,key,obj={};for(const entry of header){if(!utils$3.isArray(entry))throw TypeError("Object iterator must return a key-value pair");obj[key=entry[0]]=(dest=obj[key])?utils$3.isArray(dest)?[...dest,entry[1]]:[dest,entry[1]]:entry[1]}setHeaders(obj,valueOrRewrite)}else null!=header&&setHeader(valueOrRewrite,header,rewrite);return this}get(header,parser){if(header=normalizeHeader(header)){const key=utils$3.findKey(this,header);if(key){const value=this[key];if(!parser)return value;if(!0===parser)return function parseTokens(str){const tokens=Object.create(null),tokensRE=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let match;for(;match=tokensRE.exec(str);)tokens[match[1]]=match[2];return tokens}(value);if(utils$3.isFunction(parser))return parser.call(this,value,key);if(utils$3.isRegExp(parser))return parser.exec(value);throw new TypeError("parser must be boolean|regexp|function")}}}has(header,matcher){if(header=normalizeHeader(header)){const key=utils$3.findKey(this,header);return!(!key||void 0===this[key]||matcher&&!matchHeaderValue(0,this[key],key,matcher))}return!1}delete(header,matcher){const self=this;let deleted=!1;function deleteHeader(_header){if(_header=normalizeHeader(_header)){const key=utils$3.findKey(self,_header);!key||matcher&&!matchHeaderValue(0,self[key],key,matcher)||(delete self[key],deleted=!0)}}return utils$3.isArray(header)?header.forEach(deleteHeader):deleteHeader(header),deleted}clear(matcher){const keys=Object.keys(this);let i=keys.length,deleted=!1;for(;i--;){const key=keys[i];matcher&&!matchHeaderValue(0,this[key],key,matcher,!0)||(delete this[key],deleted=!0)}return deleted}normalize(format){const self=this,headers={};return utils$3.forEach(this,(value,header)=>{const key=utils$3.findKey(headers,header);if(key)return self[key]=normalizeValue(value),void delete self[header];const normalized=format?function formatHeader(header){return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(w,char,str)=>char.toUpperCase()+str)}(header):String(header).trim();normalized!==header&&delete self[header],self[normalized]=normalizeValue(value),headers[normalized]=!0}),this}concat(...targets){return this.constructor.concat(this,...targets)}toJSON(asStrings){const obj=Object.create(null);return utils$3.forEach(this,(value,header)=>{null!=value&&!1!==value&&(obj[header]=asStrings&&utils$3.isArray(value)?value.join(", "):value)}),obj}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([header,value])=>header+": "+value).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(thing){return thing instanceof this?thing:new this(thing)}static concat(first,...targets){const computed=new this(first);return targets.forEach(target=>computed.set(target)),computed}static accessor(header){const accessors=(this[$internals]=this[$internals]={accessors:{}}).accessors,prototype=this.prototype;function defineAccessor(_header){const lHeader=normalizeHeader(_header);accessors[lHeader]||(!function buildAccessors(obj,header){const accessorName=utils$3.toCamelCase(" "+header);["get","set","has"].forEach(methodName=>{Object.defineProperty(obj,methodName+accessorName,{value:function(arg1,arg2,arg3){return this[methodName].call(this,header,arg1,arg2,arg3)},configurable:!0})})}(prototype,_header),accessors[lHeader]=!0)}return utils$3.isArray(header)?header.forEach(defineAccessor):defineAccessor(header),this}};function transformData(fns,response){const config=this||defaults,context=response||config,headers=AxiosHeaders$1.from(context.headers);let data=context.data;return utils$3.forEach(fns,function transform(fn){data=fn.call(config,data,headers.normalize(),response?response.status:void 0)}),headers.normalize(),data}function isCancel$1(value){return!(!value||!value.__CANCEL__)}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$3.reduceDescriptors(AxiosHeaders$1.prototype,({value:value},key)=>{let mapped=key[0].toUpperCase()+key.slice(1);return{get:()=>value,set(headerValue){this[mapped]=headerValue}}}),utils$3.freezeMethods(AxiosHeaders$1);let CanceledError$1=class CanceledError extends AxiosError$1{constructor(message,config,request){super(null==message?"canceled":message,AxiosError$1.ERR_CANCELED,config,request),this.name="CanceledError",this.__CANCEL__=!0}};function settle(resolve,reject,response){const validateStatus=response.config.validateStatus;response.status&&validateStatus&&!validateStatus(response.status)?reject(new AxiosError$1("Request failed with status code "+response.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status/100)-4],response.config,response.request,response)):resolve(response)}function buildFullPath(baseURL,requestedURL,allowAbsoluteUrls){let isRelativeUrl=!function isAbsoluteURL(url){return"string"==typeof url&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)}(requestedURL);return baseURL&&(isRelativeUrl||0==allowAbsoluteUrls)?function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/?\/$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}(baseURL,requestedURL):requestedURL}var hasRequiredProxyFromEnv,proxyFromEnv$1={};var ms,hasRequiredMs,common,hasRequiredCommon,hasRequiredBrowser,proxyFromEnvExports=function requireProxyFromEnv(){if(hasRequiredProxyFromEnv)return proxyFromEnv$1;hasRequiredProxyFromEnv=1;var parseUrl=require$$0$a.parse,DEFAULT_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443},stringEndsWith=String.prototype.endsWith||function(s){return s.length<=this.length&&-1!==this.indexOf(s,this.length-s.length)};function getEnv(key){return process.env[key.toLowerCase()]||process.env[key.toUpperCase()]||""}return proxyFromEnv$1.getProxyForUrl=function getProxyForUrl(url){var parsedUrl="string"==typeof url?parseUrl(url):url||{},proto=parsedUrl.protocol,hostname=parsedUrl.host,port=parsedUrl.port;if("string"!=typeof hostname||!hostname||"string"!=typeof proto)return"";if(proto=proto.split(":",1)[0],!function shouldProxy(hostname,port){var NO_PROXY=(getEnv("npm_config_no_proxy")||getEnv("no_proxy")).toLowerCase();if(!NO_PROXY)return!0;if("*"===NO_PROXY)return!1;return NO_PROXY.split(/[,\s]/).every(function(proxy){if(!proxy)return!0;var parsedProxy=proxy.match(/^(.+):(\d+)$/),parsedProxyHostname=parsedProxy?parsedProxy[1]:proxy,parsedProxyPort=parsedProxy?parseInt(parsedProxy[2]):0;return!(!parsedProxyPort||parsedProxyPort===port)||(/^[.*]/.test(parsedProxyHostname)?("*"===parsedProxyHostname.charAt(0)&&(parsedProxyHostname=parsedProxyHostname.slice(1)),!stringEndsWith.call(hostname,parsedProxyHostname)):hostname!==parsedProxyHostname)})}(hostname=hostname.replace(/:\d*$/,""),port=parseInt(port)||DEFAULT_PORTS[proto]||0))return"";var proxy=getEnv("npm_config_"+proto+"_proxy")||getEnv(proto+"_proxy")||getEnv("npm_config_proxy")||getEnv("all_proxy");return proxy&&-1===proxy.indexOf("://")&&(proxy=proto+"://"+proxy),proxy},proxyFromEnv$1}(),proxyFromEnv=getDefaultExportFromCjs(proxyFromEnvExports),followRedirects$1={exports:{}},src={exports:{}},browser={exports:{}};function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var s=1e3,m=60*s,h=60*m,d=24*h,w=7*d,y=365.25*d;function plural(ms,msAbs,n,name){var isPlural=msAbs>=1.5*n;return Math.round(ms/n)+" "+name+(isPlural?"s":"")}return ms=function(val,options){options=options||{};var type=typeof val;if("string"===type&&val.length>0)return function parse(str){if((str=String(str)).length>100)return;var match=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);switch((match[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"weeks":case"week":case"w":return n*w;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(val);if("number"===type&&isFinite(val))return options.long?function fmtLong(ms){var msAbs=Math.abs(ms);if(msAbs>=d)return plural(ms,msAbs,d,"day");if(msAbs>=h)return plural(ms,msAbs,h,"hour");if(msAbs>=m)return plural(ms,msAbs,m,"minute");if(msAbs>=s)return plural(ms,msAbs,s,"second");return ms+" ms"}(val):function fmtShort(ms){var msAbs=Math.abs(ms);if(msAbs>=d)return Math.round(ms/d)+"d";if(msAbs>=h)return Math.round(ms/h)+"h";if(msAbs>=m)return Math.round(ms/m)+"m";if(msAbs>=s)return Math.round(ms/s)+"s";return ms+"ms"}(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))},ms}function requireCommon(){if(hasRequiredCommon)return common;return hasRequiredCommon=1,common=function setup(env){function createDebug(namespace){let prevTime,namespacesCache,enabledCache,enableOverride=null;function debug(...args){if(!debug.enabled)return;const self=debug,curr=Number(new Date),ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return"%";index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);(self.log||createDebug.log).apply(self,args)}return debug.namespace=namespace,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==enableOverride?enableOverride:(namespacesCache!==createDebug.namespaces&&(namespacesCache=createDebug.namespaces,enabledCache=createDebug.enabled(namespace)),enabledCache),set:v=>{enableOverride=v}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+(void 0===delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function matchesTemplate(search,template){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;for(;searchIndex<search.length;)if(templateIndex<template.length&&(template[templateIndex]===search[searchIndex]||"*"===template[templateIndex]))"*"===template[templateIndex]?(starIndex=templateIndex,matchIndex=searchIndex,templateIndex++):(searchIndex++,templateIndex++);else{if(-1===starIndex)return!1;templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex}for(;templateIndex<template.length&&"*"===template[templateIndex];)templateIndex++;return templateIndex===template.length}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function coerce(val){if(val instanceof Error)return val.stack||val.message;return val},createDebug.disable=function disable(){const namespaces=[...createDebug.names,...createDebug.skips.map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function enable(namespaces){createDebug.save(namespaces),createDebug.namespaces=namespaces,createDebug.names=[],createDebug.skips=[];const split=("string"==typeof namespaces?namespaces:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const ns of split)"-"===ns[0]?createDebug.skips.push(ns.slice(1)):createDebug.names.push(ns)},createDebug.enabled=function enabled(name){for(const skip of createDebug.skips)if(matchesTemplate(name,skip))return!1;for(const ns of createDebug.names)if(matchesTemplate(name,ns))return!0;return!1},createDebug.humanize=requireMs(),createDebug.destroy=function destroy(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(env).forEach(key=>{createDebug[key]=env[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function selectColor(namespace){let hash=0;for(let i=0;i<namespace.length;i++)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return createDebug.colors[Math.abs(hash)%createDebug.colors.length]},createDebug.enable(createDebug.load()),createDebug},common}var hasRequiredNode,hasRequiredSrc,debug_1,hasRequiredDebug,hasRequiredFollowRedirects,node={exports:{}};function requireNode(){return hasRequiredNode||(hasRequiredNode=1,function(module,exports$1){const tty=require$$0$5,util=require$$1$3;exports$1.init=function init(debug){debug.inspectOpts={};const keys=Object.keys(exports$1.inspectOpts);for(let i=0;i<keys.length;i++)debug.inspectOpts[keys[i]]=exports$1.inspectOpts[keys[i]]},exports$1.log=function log(...args){return process.stderr.write(util.formatWithOptions(exports$1.inspectOpts,...args)+"\n")},exports$1.formatArgs=function formatArgs(args){const{namespace:name,useColors:useColors}=this;if(useColors){const c=this.color,colorCode="[3"+(c<8?c:"8;5;"+c),prefix=` ${colorCode};1m${name} [0m`;args[0]=prefix+args[0].split("\n").join("\n"+prefix),args.push(colorCode+"m+"+module.exports.humanize(this.diff)+"[0m")}else args[0]=function getDate(){if(exports$1.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+name+" "+args[0]},exports$1.save=function save(namespaces){namespaces?process.env.DEBUG=namespaces:delete process.env.DEBUG},exports$1.load=function load(){return process.env.DEBUG},exports$1.useColors=function useColors(){return"colors"in exports$1.inspectOpts?Boolean(exports$1.inspectOpts.colors):tty.isatty(process.stderr.fd)},exports$1.destroy=util.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),exports$1.colors=[6,2,3,4,5,1];try{const supportsColor=requireSupportsColor();supportsColor&&(supportsColor.stderr||supportsColor).level>=2&&(exports$1.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(error){}exports$1.inspectOpts=Object.keys(process.env).filter(key=>/^debug_/i.test(key)).reduce((obj,key)=>{const prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_,k)=>k.toUpperCase());let val=process.env[key];return val=!!/^(yes|on|true|enabled)$/i.test(val)||!/^(no|off|false|disabled)$/i.test(val)&&("null"===val?null:Number(val)),obj[prop]=val,obj},{}),module.exports=requireCommon()(exports$1);const{formatters:formatters}=module.exports;formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split("\n").map(str=>str.trim()).join(" ")},formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)}}(node,node.exports)),node.exports}function requireSrc(){return hasRequiredSrc||(hasRequiredSrc=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?src.exports=function requireBrowser(){return hasRequiredBrowser||(hasRequiredBrowser=1,function(module,exports$1){exports$1.formatArgs=function formatArgs(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"!==match&&(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports$1.save=function save(namespaces){try{namespaces?exports$1.storage.setItem("debug",namespaces):exports$1.storage.removeItem("debug")}catch(error){}},exports$1.load=function load(){let r;try{r=exports$1.storage.getItem("debug")||exports$1.storage.getItem("DEBUG")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r},exports$1.useColors=function useColors(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let m;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(m=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},exports$1.storage=function localstorage(){try{return localStorage}catch(error){}}(),exports$1.destroy=(()=>{let warned=!1;return()=>{warned||(warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),exports$1.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports$1.log=console.debug||console.log||(()=>{}),module.exports=requireCommon()(exports$1);const{formatters:formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}(browser,browser.exports)),browser.exports}():src.exports=requireNode()),src.exports}var followRedirectsExports=function requireFollowRedirects(){if(hasRequiredFollowRedirects)return followRedirects$1.exports;hasRequiredFollowRedirects=1;var url=require$$0$a,URL=url.URL,http=require$$3$3,https=require$$4$3,Writable=stream$1.Writable,assert=require$$0$7,debug=function requireDebug(){return hasRequiredDebug||(hasRequiredDebug=1,debug_1=function(){if(!debug){try{debug=requireSrc()("follow-redirects")}catch(error){}"function"!=typeof debug&&(debug=function(){})}debug.apply(null,arguments)}),debug_1;var debug}();!function detectUnsupportedEnvironment(){var looksLikeNode="undefined"!=typeof process,looksLikeBrowser="undefined"!=typeof window&&"undefined"!=typeof document,looksLikeV8=isFunction(Error.captureStackTrace);looksLikeNode||!looksLikeBrowser&&looksLikeV8||console.warn("The follow-redirects package should be excluded from browser builds.")}();var useNativeURL=!1;try{assert(new URL(""))}catch(error){useNativeURL="ERR_INVALID_URL"===error.code}var preservedUrlFields=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],events=["abort","aborted","connect","error","socket","timeout"],eventHandlers=Object.create(null);events.forEach(function(event){eventHandlers[event]=function(arg1,arg2,arg3){this._redirectable.emit(event,arg1,arg2,arg3)}});var InvalidUrlError=createErrorType("ERR_INVALID_URL","Invalid URL",TypeError),RedirectionError=createErrorType("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),TooManyRedirectsError=createErrorType("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",RedirectionError),MaxBodyLengthExceededError=createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),WriteAfterEndError=createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),destroy=Writable.prototype.destroy||noop;function RedirectableRequest(options,responseCallback){Writable.call(this),this._sanitizeOptions(options),this._options=options,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],responseCallback&&this.on("response",responseCallback);var self=this;this._onNativeResponse=function(response){try{self._processResponse(response)}catch(cause){self.emit("error",cause instanceof RedirectionError?cause:new RedirectionError({cause:cause}))}},this._performRequest()}function wrap(protocols){var exports$1={maxRedirects:21,maxBodyLength:10485760},nativeProtocols={};return Object.keys(protocols).forEach(function(scheme){var protocol=scheme+":",nativeProtocol=nativeProtocols[protocol]=protocols[scheme],wrappedProtocol=exports$1[scheme]=Object.create(nativeProtocol);Object.defineProperties(wrappedProtocol,{request:{value:function request(input,options,callback){return!function isURL(value){return URL&&value instanceof URL}(input)?isString(input)?input=spreadUrlObject(parseUrl(input)):(callback=options,options=validateUrl(input),input={protocol:protocol}):input=spreadUrlObject(input),isFunction(options)&&(callback=options,options=null),(options=Object.assign({maxRedirects:exports$1.maxRedirects,maxBodyLength:exports$1.maxBodyLength},input,options)).nativeProtocols=nativeProtocols,isString(options.host)||isString(options.hostname)||(options.hostname="::1"),assert.equal(options.protocol,protocol,"protocol mismatch"),debug("options",options),new RedirectableRequest(options,callback)},configurable:!0,enumerable:!0,writable:!0},get:{value:function get(input,options,callback){var wrappedRequest=wrappedProtocol.request(input,options,callback);return wrappedRequest.end(),wrappedRequest},configurable:!0,enumerable:!0,writable:!0}})}),exports$1}function noop(){}function parseUrl(input){var parsed;if(useNativeURL)parsed=new URL(input);else if(!isString((parsed=validateUrl(url.parse(input))).protocol))throw new InvalidUrlError({input:input});return parsed}function validateUrl(input){if(/^\[/.test(input.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(input.hostname))throw new InvalidUrlError({input:input.href||input});if(/^\[/.test(input.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host))throw new InvalidUrlError({input:input.href||input});return input}function spreadUrlObject(urlObject,target){var spread=target||{};for(var key of preservedUrlFields)spread[key]=urlObject[key];return spread.hostname.startsWith("[")&&(spread.hostname=spread.hostname.slice(1,-1)),""!==spread.port&&(spread.port=Number(spread.port)),spread.path=spread.search?spread.pathname+spread.search:spread.pathname,spread}function removeMatchingHeaders(regex,headers){var lastValue;for(var header in headers)regex.test(header)&&(lastValue=headers[header],delete headers[header]);return null==lastValue?void 0:String(lastValue).trim()}function createErrorType(code,message,baseClass){function CustomError(properties){isFunction(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,properties||{}),this.code=code,this.message=this.cause?message+": "+this.cause.message:message}return CustomError.prototype=new(baseClass||Error),Object.defineProperties(CustomError.prototype,{constructor:{value:CustomError,enumerable:!1},name:{value:"Error ["+code+"]",enumerable:!1}}),CustomError}function destroyRequest(request,error){for(var event of events)request.removeListener(event,eventHandlers[event]);request.on("error",noop),request.destroy(error)}function isString(value){return"string"==typeof value||value instanceof String}function isFunction(value){return"function"==typeof value}return RedirectableRequest.prototype=Object.create(Writable.prototype),RedirectableRequest.prototype.abort=function(){destroyRequest(this._currentRequest),this._currentRequest.abort(),this.emit("abort")},RedirectableRequest.prototype.destroy=function(error){return destroyRequest(this._currentRequest,error),destroy.call(this,error),this},RedirectableRequest.prototype.write=function(data,encoding,callback){if(this._ending)throw new WriteAfterEndError;if(!isString(data)&&!function isBuffer(value){return"object"==typeof value&&"length"in value}(data))throw new TypeError("data should be a string, Buffer or Uint8Array");isFunction(encoding)&&(callback=encoding,encoding=null),0!==data.length?this._requestBodyLength+data.length<=this._options.maxBodyLength?(this._requestBodyLength+=data.length,this._requestBodyBuffers.push({data:data,encoding:encoding}),this._currentRequest.write(data,encoding,callback)):(this.emit("error",new MaxBodyLengthExceededError),this.abort()):callback&&callback()},RedirectableRequest.prototype.end=function(data,encoding,callback){if(isFunction(data)?(callback=data,data=encoding=null):isFunction(encoding)&&(callback=encoding,encoding=null),data){var self=this,currentRequest=this._currentRequest;this.write(data,encoding,function(){self._ended=!0,currentRequest.end(null,null,callback)}),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,callback)},RedirectableRequest.prototype.setHeader=function(name,value){this._options.headers[name]=value,this._currentRequest.setHeader(name,value)},RedirectableRequest.prototype.removeHeader=function(name){delete this._options.headers[name],this._currentRequest.removeHeader(name)},RedirectableRequest.prototype.setTimeout=function(msecs,callback){var self=this;function destroyOnTimeout(socket){socket.setTimeout(msecs),socket.removeListener("timeout",socket.destroy),socket.addListener("timeout",socket.destroy)}function startTimer(socket){self._timeout&&clearTimeout(self._timeout),self._timeout=setTimeout(function(){self.emit("timeout"),clearTimer()},msecs),destroyOnTimeout(socket)}function clearTimer(){self._timeout&&(clearTimeout(self._timeout),self._timeout=null),self.removeListener("abort",clearTimer),self.removeListener("error",clearTimer),self.removeListener("response",clearTimer),self.removeListener("close",clearTimer),callback&&self.removeListener("timeout",callback),self.socket||self._currentRequest.removeListener("socket",startTimer)}return callback&&this.on("timeout",callback),this.socket?startTimer(this.socket):this._currentRequest.once("socket",startTimer),this.on("socket",destroyOnTimeout),this.on("abort",clearTimer),this.on("error",clearTimer),this.on("response",clearTimer),this.on("close",clearTimer),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(method){RedirectableRequest.prototype[method]=function(a,b){return this._currentRequest[method](a,b)}}),["aborted","connection","socket"].forEach(function(property){Object.defineProperty(RedirectableRequest.prototype,property,{get:function(){return this._currentRequest[property]}})}),RedirectableRequest.prototype._sanitizeOptions=function(options){if(options.headers||(options.headers={}),options.host&&(options.hostname||(options.hostname=options.host),delete options.host),!options.pathname&&options.path){var searchPos=options.path.indexOf("?");searchPos<0?options.pathname=options.path:(options.pathname=options.path.substring(0,searchPos),options.search=options.path.substring(searchPos))}},RedirectableRequest.prototype._performRequest=function(){var protocol=this._options.protocol,nativeProtocol=this._options.nativeProtocols[protocol];if(!nativeProtocol)throw new TypeError("Unsupported protocol "+protocol);if(this._options.agents){var scheme=protocol.slice(0,-1);this._options.agent=this._options.agents[scheme]}var request=this._currentRequest=nativeProtocol.request(this._options,this._onNativeResponse);for(var event of(request._redirectable=this,events))request.on(event,eventHandlers[event]);if(this._currentUrl=/^\//.test(this._options.path)?url.format(this._options):this._options.path,this._isRedirect){var i=0,self=this,buffers=this._requestBodyBuffers;!function writeNext(error){if(request===self._currentRequest)if(error)self.emit("error",error);else if(i<buffers.length){var buffer=buffers[i++];request.finished||request.write(buffer.data,buffer.encoding,writeNext)}else self._ended&&request.end()}()}},RedirectableRequest.prototype._processResponse=function(response){var statusCode=response.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:response.headers,statusCode:statusCode});var requestHeaders,location=response.headers.location;if(!location||!1===this._options.followRedirects||statusCode<300||statusCode>=400)return response.responseUrl=this._currentUrl,response.redirects=this._redirects,this.emit("response",response),void(this._requestBodyBuffers=[]);if(destroyRequest(this._currentRequest),response.destroy(),++this._redirectCount>this._options.maxRedirects)throw new TooManyRedirectsError;var beforeRedirect=this._options.beforeRedirect;beforeRedirect&&(requestHeaders=Object.assign({Host:response.req.getHeader("host")},this._options.headers));var method=this._options.method;((301===statusCode||302===statusCode)&&"POST"===this._options.method||303===statusCode&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],removeMatchingHeaders(/^content-/i,this._options.headers));var currentHostHeader=removeMatchingHeaders(/^host$/i,this._options.headers),currentUrlParts=parseUrl(this._currentUrl),currentHost=currentHostHeader||currentUrlParts.host,currentUrl=/^\w+:/.test(location)?this._currentUrl:url.format(Object.assign(currentUrlParts,{host:currentHost})),redirectUrl=function resolveUrl(relative,base){return useNativeURL?new URL(relative,base):parseUrl(url.resolve(base,relative))}(location,currentUrl);if(debug("redirecting to",redirectUrl.href),this._isRedirect=!0,spreadUrlObject(redirectUrl,this._options),(redirectUrl.protocol!==currentUrlParts.protocol&&"https:"!==redirectUrl.protocol||redirectUrl.host!==currentHost&&!function isSubdomain(subdomain,domain){assert(isString(subdomain)&&isString(domain));var dot=subdomain.length-domain.length-1;return dot>0&&"."===subdomain[dot]&&subdomain.endsWith(domain)}(redirectUrl.host,currentHost))&&removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i,this._options.headers),isFunction(beforeRedirect)){var responseDetails={headers:response.headers,statusCode:statusCode},requestDetails={url:currentUrl,method:method,headers:requestHeaders};beforeRedirect(this._options,responseDetails,requestDetails),this._sanitizeOptions(this._options)}this._performRequest()},followRedirects$1.exports=wrap({http:http,https:https}),followRedirects$1.exports.wrap=wrap,followRedirects$1.exports}(),followRedirects=getDefaultExportFromCjs(followRedirectsExports);function parseProtocol(url){const match=/^([-+\w]{1,25})(:?\/\/|:)/.exec(url);return match&&match[1]||""}const DATA_URL_PATTERN=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;const kInternals=Symbol("internals");class AxiosTransformStream extends stream$1.Transform{constructor(options){options=utils$3.toFlatObject(options,{maxRate:0,chunkSize:65536,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(prop,source)=>!utils$3.isUndefined(source[prop])),super({readableHighWaterMark:options.chunkSize});const internals=this[kInternals]={timeWindow:options.timeWindow,chunkSize:options.chunkSize,maxRate:options.maxRate,minChunkSize:options.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",event=>{"progress"===event&&(internals.isCaptured||(internals.isCaptured=!0))})}_read(size){const internals=this[kInternals];return internals.onReadCallback&&internals.onReadCallback(),super._read(size)}_transform(chunk,encoding,callback){const internals=this[kInternals],maxRate=internals.maxRate,readableHighWaterMark=this.readableHighWaterMark,timeWindow=internals.timeWindow,bytesThreshold=maxRate/(1e3/timeWindow),minChunkSize=!1!==internals.minChunkSize?Math.max(internals.minChunkSize,.01*bytesThreshold):0,pushChunk=(_chunk,_callback)=>{const bytes=Buffer.byteLength(_chunk);internals.bytesSeen+=bytes,internals.bytes+=bytes,internals.isCaptured&&this.emit("progress",internals.bytesSeen),this.push(_chunk)?process.nextTick(_callback):internals.onReadCallback=()=>{internals.onReadCallback=null,process.nextTick(_callback)}},transformChunk=(_chunk,_callback)=>{const chunkSize=Buffer.byteLength(_chunk);let bytesLeft,chunkRemainder=null,maxChunkSize=readableHighWaterMark,passed=0;if(maxRate){const now=Date.now();(!internals.ts||(passed=now-internals.ts)>=timeWindow)&&(internals.ts=now,bytesLeft=bytesThreshold-internals.bytes,internals.bytes=bytesLeft<0?-bytesLeft:0,passed=0),bytesLeft=bytesThreshold-internals.bytes}if(maxRate){if(bytesLeft<=0)return setTimeout(()=>{_callback(null,_chunk)},timeWindow-passed);bytesLeft<maxChunkSize&&(maxChunkSize=bytesLeft)}maxChunkSize&&chunkSize>maxChunkSize&&chunkSize-maxChunkSize>minChunkSize&&(chunkRemainder=_chunk.subarray(maxChunkSize),_chunk=_chunk.subarray(0,maxChunkSize)),pushChunk(_chunk,chunkRemainder?()=>{process.nextTick(_callback,null,chunkRemainder)}:_callback)};transformChunk(chunk,function transformNextChunk(err,_chunk){if(err)return callback(err);_chunk?transformChunk(_chunk,transformNextChunk):callback(null)})}}const{asyncIterator:asyncIterator}=Symbol,readBlob=async function*(blob){blob.stream?yield*blob.stream():blob.arrayBuffer?yield await blob.arrayBuffer():blob[asyncIterator]?yield*blob[asyncIterator]():yield blob},BOUNDARY_ALPHABET=platform.ALPHABET.ALPHA_DIGIT+"-_",textEncoder="function"==typeof TextEncoder?new TextEncoder:new require$$1$3.TextEncoder,CRLF_BYTES=textEncoder.encode("\r\n");class FormDataPart{constructor(name,value){const{escapeName:escapeName}=this.constructor,isStringValue=utils$3.isString(value);let headers=`Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue&&value.name?`; filename="${escapeName(value.name)}"`:""}\r\n`;isStringValue?value=textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g,"\r\n")):headers+=`Content-Type: ${value.type||"application/octet-stream"}\r\n`,this.headers=textEncoder.encode(headers+"\r\n"),this.contentLength=isStringValue?value.byteLength:value.size,this.size=this.headers.byteLength+this.contentLength+2,this.name=name,this.value=value}async*encode(){yield this.headers;const{value:value}=this;utils$3.isTypedArray(value)?yield value:yield*readBlob(value),yield CRLF_BYTES}static escapeName(name){return String(name).replace(/[\r\n"]/g,match=>({"\r":"%0D","\n":"%0A",'"':"%22"}[match]))}}class ZlibHeaderTransformStream extends stream$1.Transform{__transform(chunk,encoding,callback){this.push(chunk),callback()}_transform(chunk,encoding,callback){if(0!==chunk.length&&(this._transform=this.__transform,120!==chunk[0])){const header=Buffer.alloc(2);header[0]=120,header[1]=156,this.push(header,encoding)}this.__transform(chunk,encoding,callback)}}const callbackify=(fn,reducer)=>utils$3.isAsyncFn(fn)?function(...args){const cb=args.pop();fn.apply(this,args).then(value=>{try{reducer?cb(null,...reducer(value)):cb(null,value)}catch(err){cb(err)}},cb)}:fn;const progressEventReducer=(listener,isDownloadStream,freq=3)=>{let bytesNotified=0;const _speedometer=function speedometer(samplesCount,min){samplesCount=samplesCount||10;const bytes=new Array(samplesCount),timestamps=new Array(samplesCount);let firstSampleTS,head=0,tail=0;return min=void 0!==min?min:1e3,function push(chunkLength){const now=Date.now(),startedAt=timestamps[tail];firstSampleTS||(firstSampleTS=now),bytes[head]=chunkLength,timestamps[head]=now;let i=tail,bytesCount=0;for(;i!==head;)bytesCount+=bytes[i++],i%=samplesCount;if(head=(head+1)%samplesCount,head===tail&&(tail=(tail+1)%samplesCount),now-firstSampleTS<min)return;const passed=startedAt&&now-startedAt;return passed?Math.round(1e3*bytesCount/passed):void 0}}(50,250);return function throttle(fn,freq){let lastArgs,timer,timestamp=0,threshold=1e3/freq;const invoke=(args,now=Date.now())=>{timestamp=now,lastArgs=null,timer&&(clearTimeout(timer),timer=null),fn(...args)};return[(...args)=>{const now=Date.now(),passed=now-timestamp;passed>=threshold?invoke(args,now):(lastArgs=args,timer||(timer=setTimeout(()=>{timer=null,invoke(lastArgs)},threshold-passed)))},()=>lastArgs&&invoke(lastArgs)]}(e=>{const loaded=e.loaded,total=e.lengthComputable?e.total:void 0,progressBytes=loaded-bytesNotified,rate=_speedometer(progressBytes);bytesNotified=loaded;listener({loaded:loaded,total:total,progress:total?loaded/total:void 0,bytes:progressBytes,rate:rate||void 0,estimated:rate&&total&&loaded<=total?(total-loaded)/rate:void 0,event:e,lengthComputable:null!=total,[isDownloadStream?"download":"upload"]:!0})},freq)},progressEventDecorator=(total,throttled)=>{const lengthComputable=null!=total;return[loaded=>throttled[0]({lengthComputable:lengthComputable,total:total,loaded:loaded}),throttled[1]]},asyncDecorator=fn=>(...args)=>utils$3.asap(()=>fn(...args));const zlibOptions={flush:zlib.constants.Z_SYNC_FLUSH,finishFlush:zlib.constants.Z_SYNC_FLUSH},brotliOptions={flush:zlib.constants.BROTLI_OPERATION_FLUSH,finishFlush:zlib.constants.BROTLI_OPERATION_FLUSH},isBrotliSupported=utils$3.isFunction(zlib.createBrotliDecompress),{http:httpFollow,https:httpsFollow}=followRedirects,isHttps=/https:?/,supportedProtocols=platform.protocols.map(protocol=>protocol+":"),flushOnFinish=(stream,[throttled,flush])=>(stream.on("end",flush).on("error",flush),throttled);const http2Sessions=new class Http2Sessions{constructor(){this.sessions=Object.create(null)}getSession(authority,options){options=Object.assign({sessionTimeout:1e3},options);let authoritySessions=this.sessions[authority];if(authoritySessions){let len=authoritySessions.length;for(let i=0;i<len;i++){const[sessionHandle,sessionOptions]=authoritySessions[i];if(!sessionHandle.destroyed&&!sessionHandle.closed&&require$$1$3.isDeepStrictEqual(sessionOptions,options))return sessionHandle}}const session=http2.connect(authority,options);let removed;const removeSession=()=>{if(removed)return;removed=!0;let entries=authoritySessions,len=entries.length,i=len;for(;i--;)if(entries[i][0]===session)return void(1===len?delete this.sessions[authority]:entries.splice(i,1))},originalRequestFn=session.request,{sessionTimeout:sessionTimeout}=options;if(null!=sessionTimeout){let timer,streamsCount=0;session.request=function(){const stream=originalRequestFn.apply(this,arguments);return streamsCount++,timer&&(clearTimeout(timer),timer=null),stream.once("close",()=>{--streamsCount||(timer=setTimeout(()=>{timer=null,removeSession()},sessionTimeout))}),stream}}session.once("close",removeSession);let entry=[session,options];return authoritySessions?authoritySessions.push(entry):authoritySessions=this.sessions[authority]=[entry],session}};function dispatchBeforeRedirect(options,responseDetails){options.beforeRedirects.proxy&&options.beforeRedirects.proxy(options),options.beforeRedirects.config&&options.beforeRedirects.config(options,responseDetails)}function setProxy(options,configProxy,location){let proxy=configProxy;if(!proxy&&!1!==proxy){const proxyUrl=proxyFromEnv.getProxyForUrl(location);proxyUrl&&(proxy=new URL(proxyUrl))}if(proxy){if(proxy.username&&(proxy.auth=(proxy.username||"")+":"+(proxy.password||"")),proxy.auth){if(Boolean(proxy.auth.username||proxy.auth.password))proxy.auth=(proxy.auth.username||"")+":"+(proxy.auth.password||"");else if("object"==typeof proxy.auth)throw new AxiosError$1("Invalid proxy authorization",AxiosError$1.ERR_BAD_OPTION,{proxy:proxy});const base64=Buffer.from(proxy.auth,"utf8").toString("base64");options.headers["Proxy-Authorization"]="Basic "+base64}options.headers.host=options.hostname+(options.port?":"+options.port:"");const proxyHost=proxy.hostname||proxy.host;options.hostname=proxyHost,options.host=proxyHost,options.port=proxy.port,options.path=location,proxy.protocol&&(options.protocol=proxy.protocol.includes(":")?proxy.protocol:`${proxy.protocol}:`)}options.beforeRedirects.proxy=function beforeRedirect(redirectOptions){setProxy(redirectOptions,configProxy,redirectOptions.href)}}const isHttpAdapterSupported="undefined"!=typeof process&&"process"===utils$3.kindOf(process),buildAddressEntry=(address,family)=>(({address:address,family:family})=>{if(!utils$3.isString(address))throw TypeError("address must be a string");return{address:address,family:family||(address.indexOf(".")<0?6:4)}})(utils$3.isObject(address)?address:{address:address,family:family}),http2Transport={request(options,cb){const authority=options.protocol+"//"+options.hostname+":"+(options.port||("https:"===options.protocol?443:80)),{http2Options:http2Options,headers:headers}=options,session=http2Sessions.getSession(authority,http2Options),{HTTP2_HEADER_SCHEME:HTTP2_HEADER_SCHEME,HTTP2_HEADER_METHOD:HTTP2_HEADER_METHOD,HTTP2_HEADER_PATH:HTTP2_HEADER_PATH,HTTP2_HEADER_STATUS:HTTP2_HEADER_STATUS}=http2.constants,http2Headers={[HTTP2_HEADER_SCHEME]:options.protocol.replace(":",""),[HTTP2_HEADER_METHOD]:options.method,[HTTP2_HEADER_PATH]:options.path};utils$3.forEach(headers,(header,name)=>{":"!==name.charAt(0)&&(http2Headers[name]=header)});const req=session.request(http2Headers);return req.once("response",responseHeaders=>{const response=req,status=(responseHeaders=Object.assign({},responseHeaders))[HTTP2_HEADER_STATUS];delete responseHeaders[HTTP2_HEADER_STATUS],response.headers=responseHeaders,response.statusCode=+status,cb(response)}),req}};var httpAdapter=isHttpAdapterSupported&&function httpAdapter(config){return asyncExecutor=async function dispatchHttpRequest(resolve,reject,onDone){let{data:data,lookup:lookup,family:family,httpVersion:httpVersion=1,http2Options:http2Options}=config;const{responseType:responseType,responseEncoding:responseEncoding}=config,method=config.method.toUpperCase();let isDone,req,rejected=!1;if(httpVersion=+httpVersion,Number.isNaN(httpVersion))throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);if(1!==httpVersion&&2!==httpVersion)throw TypeError(`Unsupported protocol version '${httpVersion}'`);const isHttp2=2===httpVersion;if(lookup){const _lookup=callbackify(lookup,value=>utils$3.isArray(value)?value:[value]);lookup=(hostname,opt,cb)=>{_lookup(hostname,opt,(err,arg0,arg1)=>{if(err)return cb(err);const addresses=utils$3.isArray(arg0)?arg0.map(addr=>buildAddressEntry(addr)):[buildAddressEntry(arg0,arg1)];opt.all?cb(err,addresses):cb(err,addresses[0].address,addresses[0].family)})}}const abortEmitter=new require$$0$4.EventEmitter;function abort(reason){try{abortEmitter.emit("abort",!reason||reason.type?new CanceledError$1(null,config,req):reason)}catch(err){console.warn("emit error",err)}}abortEmitter.once("abort",reject);const onFinished=()=>{config.cancelToken&&config.cancelToken.unsubscribe(abort),config.signal&&config.signal.removeEventListener("abort",abort),abortEmitter.removeAllListeners()};(config.cancelToken||config.signal)&&(config.cancelToken&&config.cancelToken.subscribe(abort),config.signal&&(config.signal.aborted?abort():config.signal.addEventListener("abort",abort))),onDone((response,isRejected)=>{if(isDone=!0,isRejected)return rejected=!0,void onFinished();const{data:data}=response;if(data instanceof stream$1.Readable||data instanceof stream$1.Duplex){const offListeners=stream$1.finished(data,()=>{offListeners(),onFinished()})}else onFinished()});const fullPath=buildFullPath(config.baseURL,config.url,config.allowAbsoluteUrls),parsed=new URL(fullPath,platform.hasBrowserEnv?platform.origin:void 0),protocol=parsed.protocol||supportedProtocols[0];if("data:"===protocol){if(config.maxContentLength>-1&&function estimateDataURLDecodedBytes(url){if(!url||"string"!=typeof url)return 0;if(!url.startsWith("data:"))return 0;const comma=url.indexOf(",");if(comma<0)return 0;const meta=url.slice(5,comma),body=url.slice(comma+1);if(/;base64/i.test(meta)){let effectiveLen=body.length;const len=body.length;for(let i=0;i<len;i++)if(37===body.charCodeAt(i)&&i+2<len){const a=body.charCodeAt(i+1),b=body.charCodeAt(i+2);(a>=48&&a<=57||a>=65&&a<=70||a>=97&&a<=102)&&(b>=48&&b<=57||b>=65&&b<=70||b>=97&&b<=102)&&(effectiveLen-=2,i+=2)}let pad=0,idx=len-1;const tailIsPct3D=j=>j>=2&&37===body.charCodeAt(j-2)&&51===body.charCodeAt(j-1)&&(68===body.charCodeAt(j)||100===body.charCodeAt(j));idx>=0&&(61===body.charCodeAt(idx)?(pad++,idx--):tailIsPct3D(idx)&&(pad++,idx-=3)),1===pad&&idx>=0&&(61===body.charCodeAt(idx)||tailIsPct3D(idx))&&pad++;const bytes=3*Math.floor(effectiveLen/4)-(pad||0);return bytes>0?bytes:0}return Buffer.byteLength(body,"utf8")}(String(config.url||fullPath||""))>config.maxContentLength)return reject(new AxiosError$1("maxContentLength size of "+config.maxContentLength+" exceeded",AxiosError$1.ERR_BAD_RESPONSE,config));let convertedData;if("GET"!==method)return settle(resolve,reject,{status:405,statusText:"method not allowed",headers:{},config:config});try{convertedData=function fromDataURI(uri,asBlob,options){const _Blob=options&&options.Blob||platform.classes.Blob,protocol=parseProtocol(uri);if(void 0===asBlob&&_Blob&&(asBlob=!0),"data"===protocol){uri=protocol.length?uri.slice(protocol.length+1):uri;const match=DATA_URL_PATTERN.exec(uri);if(!match)throw new AxiosError$1("Invalid URL",AxiosError$1.ERR_INVALID_URL);const mime=match[1],isBase64=match[2],body=match[3],buffer=Buffer.from(decodeURIComponent(body),isBase64?"base64":"utf8");if(asBlob){if(!_Blob)throw new AxiosError$1("Blob is not supported",AxiosError$1.ERR_NOT_SUPPORT);return new _Blob([buffer],{type:mime})}return buffer}throw new AxiosError$1("Unsupported protocol "+protocol,AxiosError$1.ERR_NOT_SUPPORT)}(config.url,"blob"===responseType,{Blob:config.env&&config.env.Blob})}catch(err){throw AxiosError$1.from(err,AxiosError$1.ERR_BAD_REQUEST,config)}return"text"===responseType?(convertedData=convertedData.toString(responseEncoding),responseEncoding&&"utf8"!==responseEncoding||(convertedData=utils$3.stripBOM(convertedData))):"stream"===responseType&&(convertedData=stream$1.Readable.from(convertedData)),settle(resolve,reject,{data:convertedData,status:200,statusText:"OK",headers:new AxiosHeaders$1,config:config})}if(-1===supportedProtocols.indexOf(protocol))return reject(new AxiosError$1("Unsupported protocol "+protocol,AxiosError$1.ERR_BAD_REQUEST,config));const headers=AxiosHeaders$1.from(config.headers).normalize();headers.set("User-Agent","axios/1.13.6",!1);const{onUploadProgress:onUploadProgress,onDownloadProgress:onDownloadProgress}=config,maxRate=config.maxRate;let maxUploadRate,maxDownloadRate;if(utils$3.isSpecCompliantForm(data)){const userBoundary=headers.getContentType(/boundary=([-_\w\d]{10,70})/i);data=((form,headersHandler,options)=>{const{tag:tag="form-data-boundary",size:size=25,boundary:boundary=tag+"-"+platform.generateString(size,BOUNDARY_ALPHABET)}=options||{};if(!utils$3.isFormData(form))throw TypeError("FormData instance required");if(boundary.length<1||boundary.length>70)throw Error("boundary must be 10-70 characters long");const boundaryBytes=textEncoder.encode("--"+boundary+"\r\n"),footerBytes=textEncoder.encode("--"+boundary+"--\r\n");let contentLength=footerBytes.byteLength;const parts=Array.from(form.entries()).map(([name,value])=>{const part=new FormDataPart(name,value);return contentLength+=part.size,part});contentLength+=boundaryBytes.byteLength*parts.length,contentLength=utils$3.toFiniteNumber(contentLength);const computedHeaders={"Content-Type":`multipart/form-data; boundary=${boundary}`};return Number.isFinite(contentLength)&&(computedHeaders["Content-Length"]=contentLength),headersHandler&&headersHandler(computedHeaders),stream$1.Readable.from(async function*(){for(const part of parts)yield boundaryBytes,yield*part.encode();yield footerBytes}())})(data,formHeaders=>{headers.set(formHeaders)},{tag:"axios-1.13.6-boundary",boundary:userBoundary&&userBoundary[1]||void 0})}else if(utils$3.isFormData(data)&&utils$3.isFunction(data.getHeaders)){if(headers.set(data.getHeaders()),!headers.hasContentLength())try{const knownLength=await require$$1$3.promisify(data.getLength).call(data);Number.isFinite(knownLength)&&knownLength>=0&&headers.setContentLength(knownLength)}catch(e){}}else if(utils$3.isBlob(data)||utils$3.isFile(data))data.size&&headers.setContentType(data.type||"application/octet-stream"),headers.setContentLength(data.size||0),data=stream$1.Readable.from(readBlob(data));else if(data&&!utils$3.isStream(data)){if(Buffer.isBuffer(data));else if(utils$3.isArrayBuffer(data))data=Buffer.from(new Uint8Array(data));else{if(!utils$3.isString(data))return reject(new AxiosError$1("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",AxiosError$1.ERR_BAD_REQUEST,config));data=Buffer.from(data,"utf-8")}if(headers.setContentLength(data.length,!1),config.maxBodyLength>-1&&data.length>config.maxBodyLength)return reject(new AxiosError$1("Request body larger than maxBodyLength limit",AxiosError$1.ERR_BAD_REQUEST,config))}const contentLength=utils$3.toFiniteNumber(headers.getContentLength());let auth,path;utils$3.isArray(maxRate)?(maxUploadRate=maxRate[0],maxDownloadRate=maxRate[1]):maxUploadRate=maxDownloadRate=maxRate,data&&(onUploadProgress||maxUploadRate)&&(utils$3.isStream(data)||(data=stream$1.Readable.from(data,{objectMode:!1})),data=stream$1.pipeline([data,new AxiosTransformStream({maxRate:utils$3.toFiniteNumber(maxUploadRate)})],utils$3.noop),onUploadProgress&&data.on("progress",flushOnFinish(data,progressEventDecorator(contentLength,progressEventReducer(asyncDecorator(onUploadProgress),!1,3))))),config.auth&&(auth=(config.auth.username||"")+":"+(config.auth.password||"")),!auth&&parsed.username&&(auth=parsed.username+":"+parsed.password),auth&&headers.delete("authorization");try{path=buildURL(parsed.pathname+parsed.search,config.params,config.paramsSerializer).replace(/^\?/,"")}catch(err){const customErr=new Error(err.message);return customErr.config=config,customErr.url=config.url,customErr.exists=!0,reject(customErr)}headers.set("Accept-Encoding","gzip, compress, deflate"+(isBrotliSupported?", br":""),!1);const options={path:path,method:method,headers:headers.toJSON(),agents:{http:config.httpAgent,https:config.httpsAgent},auth:auth,protocol:protocol,family:family,beforeRedirect:dispatchBeforeRedirect,beforeRedirects:{},http2Options:http2Options};let transport;!utils$3.isUndefined(lookup)&&(options.lookup=lookup),config.socketPath?options.socketPath=config.socketPath:(options.hostname=parsed.hostname.startsWith("[")?parsed.hostname.slice(1,-1):parsed.hostname,options.port=parsed.port,setProxy(options,config.proxy,protocol+"//"+parsed.hostname+(parsed.port?":"+parsed.port:"")+options.path));const isHttpsRequest=isHttps.test(options.protocol);if(options.agent=isHttpsRequest?config.httpsAgent:config.httpAgent,isHttp2?transport=http2Transport:config.transport?transport=config.transport:0===config.maxRedirects?transport=isHttpsRequest?require$$4$3:require$$3$3:(config.maxRedirects&&(options.maxRedirects=config.maxRedirects),config.beforeRedirect&&(options.beforeRedirects.config=config.beforeRedirect),transport=isHttpsRequest?httpsFollow:httpFollow),config.maxBodyLength>-1?options.maxBodyLength=config.maxBodyLength:options.maxBodyLength=1/0,config.insecureHTTPParser&&(options.insecureHTTPParser=config.insecureHTTPParser),req=transport.request(options,function handleResponse(res){if(req.destroyed)return;const streams=[res],responseLength=utils$3.toFiniteNumber(res.headers["content-length"]);if(onDownloadProgress||maxDownloadRate){const transformStream=new AxiosTransformStream({maxRate:utils$3.toFiniteNumber(maxDownloadRate)});onDownloadProgress&&transformStream.on("progress",flushOnFinish(transformStream,progressEventDecorator(responseLength,progressEventReducer(asyncDecorator(onDownloadProgress),!0,3)))),streams.push(transformStream)}let responseStream=res;const lastRequest=res.req||req;if(!1!==config.decompress&&res.headers["content-encoding"])switch("HEAD"!==method&&204!==res.statusCode||delete res.headers["content-encoding"],(res.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":streams.push(zlib.createUnzip(zlibOptions)),delete res.headers["content-encoding"];break;case"deflate":streams.push(new ZlibHeaderTransformStream),streams.push(zlib.createUnzip(zlibOptions)),delete res.headers["content-encoding"];break;case"br":isBrotliSupported&&(streams.push(zlib.createBrotliDecompress(brotliOptions)),delete res.headers["content-encoding"])}responseStream=streams.length>1?stream$1.pipeline(streams,utils$3.noop):streams[0];const response={status:res.statusCode,statusText:res.statusMessage,headers:new AxiosHeaders$1(res.headers),config:config,request:lastRequest};if("stream"===responseType)response.data=responseStream,settle(resolve,reject,response);else{const responseBuffer=[];let totalResponseBytes=0;responseStream.on("data",function handleStreamData(chunk){responseBuffer.push(chunk),totalResponseBytes+=chunk.length,config.maxContentLength>-1&&totalResponseBytes>config.maxContentLength&&(rejected=!0,responseStream.destroy(),abort(new AxiosError$1("maxContentLength size of "+config.maxContentLength+" exceeded",AxiosError$1.ERR_BAD_RESPONSE,config,lastRequest)))}),responseStream.on("aborted",function handlerStreamAborted(){if(rejected)return;const err=new AxiosError$1("stream has been aborted",AxiosError$1.ERR_BAD_RESPONSE,config,lastRequest);responseStream.destroy(err),reject(err)}),responseStream.on("error",function handleStreamError(err){req.destroyed||reject(AxiosError$1.from(err,null,config,lastRequest))}),responseStream.on("end",function handleStreamEnd(){try{let responseData=1===responseBuffer.length?responseBuffer[0]:Buffer.concat(responseBuffer);"arraybuffer"!==responseType&&(responseData=responseData.toString(responseEncoding),responseEncoding&&"utf8"!==responseEncoding||(responseData=utils$3.stripBOM(responseData))),response.data=responseData}catch(err){return reject(AxiosError$1.from(err,null,config,response.request,response))}settle(resolve,reject,response)})}abortEmitter.once("abort",err=>{responseStream.destroyed||(responseStream.emit("error",err),responseStream.destroy())})}),abortEmitter.once("abort",err=>{req.close?req.close():req.destroy(err)}),req.on("error",function handleRequestError(err){reject(AxiosError$1.from(err,null,config,req))}),req.on("socket",function handleRequestSocket(socket){socket.setKeepAlive(!0,6e4)}),config.timeout){const timeout=parseInt(config.timeout,10);if(Number.isNaN(timeout))return void abort(new AxiosError$1("error trying to parse `config.timeout` to int",AxiosError$1.ERR_BAD_OPTION_VALUE,config,req));req.setTimeout(timeout,function handleRequestTimeout(){if(isDone)return;let timeoutErrorMessage=config.timeout?"timeout of "+config.timeout+"ms exceeded":"timeout exceeded";const transitional=config.transitional||transitionalDefaults;config.timeoutErrorMessage&&(timeoutErrorMessage=config.timeoutErrorMessage),abort(new AxiosError$1(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,config,req))})}else req.setTimeout(0);if(utils$3.isStream(data)){let ended=!1,errored=!1;data.on("end",()=>{ended=!0}),data.once("error",err=>{errored=!0,req.destroy(err)}),data.on("close",()=>{ended||errored||abort(new CanceledError$1("Request stream has been aborted",config,req))}),data.pipe(req)}else data&&req.write(data),req.end()},new Promise((resolve,reject)=>{let onDone,isDone;const done=(value,isRejected)=>{isDone||(isDone=!0,onDone&&onDone(value,isRejected))},_reject=reason=>{done(reason,!0),reject(reason)};asyncExecutor(value=>{done(value),resolve(value)},_reject,onDoneHandler=>onDone=onDoneHandler).catch(_reject)});var asyncExecutor},isURLSameOrigin=platform.hasStandardBrowserEnv?((origin,isMSIE)=>url=>(url=new URL(url,platform.origin),origin.protocol===url.protocol&&origin.host===url.host&&(isMSIE||origin.port===url.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(name,value,expires,path,domain,secure,sameSite){if("undefined"==typeof document)return;const cookie=[`${name}=${encodeURIComponent(value)}`];utils$3.isNumber(expires)&&cookie.push(`expires=${new Date(expires).toUTCString()}`),utils$3.isString(path)&&cookie.push(`path=${path}`),utils$3.isString(domain)&&cookie.push(`domain=${domain}`),!0===secure&&cookie.push("secure"),utils$3.isString(sameSite)&&cookie.push(`SameSite=${sameSite}`),document.cookie=cookie.join("; ")},read(name){if("undefined"==typeof document)return null;const match=document.cookie.match(new RegExp("(?:^|; )"+name+"=([^;]*)"));return match?decodeURIComponent(match[1]):null},remove(name){this.write(name,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};const headersToObject=thing=>thing instanceof AxiosHeaders$1?{...thing}:thing;function mergeConfig$1(config1,config2){config2=config2||{};const config={};function getMergedValue(target,source,prop,caseless){return utils$3.isPlainObject(target)&&utils$3.isPlainObject(source)?utils$3.merge.call({caseless:caseless},target,source):utils$3.isPlainObject(source)?utils$3.merge({},source):utils$3.isArray(source)?source.slice():source}function mergeDeepProperties(a,b,prop,caseless){return utils$3.isUndefined(b)?utils$3.isUndefined(a)?void 0:getMergedValue(void 0,a,0,caseless):getMergedValue(a,b,0,caseless)}function valueFromConfig2(a,b){if(!utils$3.isUndefined(b))return getMergedValue(void 0,b)}function defaultToConfig2(a,b){return utils$3.isUndefined(b)?utils$3.isUndefined(a)?void 0:getMergedValue(void 0,a):getMergedValue(void 0,b)}function mergeDirectKeys(a,b,prop){return prop in config2?getMergedValue(a,b):prop in config1?getMergedValue(void 0,a):void 0}const mergeMap={url:valueFromConfig2,method:valueFromConfig2,data:valueFromConfig2,baseURL:defaultToConfig2,transformRequest:defaultToConfig2,transformResponse:defaultToConfig2,paramsSerializer:defaultToConfig2,timeout:defaultToConfig2,timeoutMessage:defaultToConfig2,withCredentials:defaultToConfig2,withXSRFToken:defaultToConfig2,adapter:defaultToConfig2,responseType:defaultToConfig2,xsrfCookieName:defaultToConfig2,xsrfHeaderName:defaultToConfig2,onUploadProgress:defaultToConfig2,onDownloadProgress:defaultToConfig2,decompress:defaultToConfig2,maxContentLength:defaultToConfig2,maxBodyLength:defaultToConfig2,beforeRedirect:defaultToConfig2,transport:defaultToConfig2,httpAgent:defaultToConfig2,httpsAgent:defaultToConfig2,cancelToken:defaultToConfig2,socketPath:defaultToConfig2,responseEncoding:defaultToConfig2,validateStatus:mergeDirectKeys,headers:(a,b,prop)=>mergeDeepProperties(headersToObject(a),headersToObject(b),0,!0)};return utils$3.forEach(Object.keys({...config1,...config2}),function computeConfigValue(prop){if("__proto__"===prop||"constructor"===prop||"prototype"===prop)return;const merge=utils$3.hasOwnProp(mergeMap,prop)?mergeMap[prop]:mergeDeepProperties,configValue=merge(config1[prop],config2[prop],prop);utils$3.isUndefined(configValue)&&merge!==mergeDirectKeys||(config[prop]=configValue)}),config}var resolveConfig=config=>{const newConfig=mergeConfig$1({},config);let{data:data,withXSRFToken:withXSRFToken,xsrfHeaderName:xsrfHeaderName,xsrfCookieName:xsrfCookieName,headers:headers,auth:auth}=newConfig;if(newConfig.headers=headers=AxiosHeaders$1.from(headers),newConfig.url=buildURL(buildFullPath(newConfig.baseURL,newConfig.url,newConfig.allowAbsoluteUrls),config.params,config.paramsSerializer),auth&&headers.set("Authorization","Basic "+btoa((auth.username||"")+":"+(auth.password?unescape(encodeURIComponent(auth.password)):""))),utils$3.isFormData(data))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)headers.setContentType(void 0);else if(utils$3.isFunction(data.getHeaders)){const formHeaders=data.getHeaders(),allowedHeaders=["content-type","content-length"];Object.entries(formHeaders).forEach(([key,val])=>{allowedHeaders.includes(key.toLowerCase())&&headers.set(key,val)})}if(platform.hasStandardBrowserEnv&&(withXSRFToken&&utils$3.isFunction(withXSRFToken)&&(withXSRFToken=withXSRFToken(newConfig)),withXSRFToken||!1!==withXSRFToken&&isURLSameOrigin(newConfig.url))){const xsrfValue=xsrfHeaderName&&xsrfCookieName&&cookies.read(xsrfCookieName);xsrfValue&&headers.set(xsrfHeaderName,xsrfValue)}return newConfig};var xhrAdapter="undefined"!=typeof XMLHttpRequest&&function(config){return new Promise(function dispatchXhrRequest(resolve,reject){const _config=resolveConfig(config);let requestData=_config.data;const requestHeaders=AxiosHeaders$1.from(_config.headers).normalize();let onCanceled,uploadThrottled,downloadThrottled,flushUpload,flushDownload,{responseType:responseType,onUploadProgress:onUploadProgress,onDownloadProgress:onDownloadProgress}=_config;function done(){flushUpload&&flushUpload(),flushDownload&&flushDownload(),_config.cancelToken&&_config.cancelToken.unsubscribe(onCanceled),_config.signal&&_config.signal.removeEventListener("abort",onCanceled)}let request=new XMLHttpRequest;function onloadend(){if(!request)return;const responseHeaders=AxiosHeaders$1.from("getAllResponseHeaders"in request&&request.getAllResponseHeaders());settle(function _resolve(value){resolve(value),done()},function _reject(err){reject(err),done()},{data:responseType&&"text"!==responseType&&"json"!==responseType?request.response:request.responseText,status:request.status,statusText:request.statusText,headers:responseHeaders,config:config,request:request}),request=null}request.open(_config.method.toUpperCase(),_config.url,!0),request.timeout=_config.timeout,"onloadend"in request?request.onloadend=onloadend:request.onreadystatechange=function handleLoad(){request&&4===request.readyState&&(0!==request.status||request.responseURL&&0===request.responseURL.indexOf("file:"))&&setTimeout(onloadend)},request.onabort=function handleAbort(){request&&(reject(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,config,request)),request=null)},request.onerror=function handleError(event){const msg=event&&event.message?event.message:"Network Error",err=new AxiosError$1(msg,AxiosError$1.ERR_NETWORK,config,request);err.event=event||null,reject(err),request=null},request.ontimeout=function handleTimeout(){let timeoutErrorMessage=_config.timeout?"timeout of "+_config.timeout+"ms exceeded":"timeout exceeded";const transitional=_config.transitional||transitionalDefaults;_config.timeoutErrorMessage&&(timeoutErrorMessage=_config.timeoutErrorMessage),reject(new AxiosError$1(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,config,request)),request=null},void 0===requestData&&requestHeaders.setContentType(null),"setRequestHeader"in request&&utils$3.forEach(requestHeaders.toJSON(),function setRequestHeader(val,key){request.setRequestHeader(key,val)}),utils$3.isUndefined(_config.withCredentials)||(request.withCredentials=!!_config.withCredentials),responseType&&"json"!==responseType&&(request.responseType=_config.responseType),onDownloadProgress&&([downloadThrottled,flushDownload]=progressEventReducer(onDownloadProgress,!0),request.addEventListener("progress",downloadThrottled)),onUploadProgress&&request.upload&&([uploadThrottled,flushUpload]=progressEventReducer(onUploadProgress),request.upload.addEventListener("progress",uploadThrottled),request.upload.addEventListener("loadend",flushUpload)),(_config.cancelToken||_config.signal)&&(onCanceled=cancel=>{request&&(reject(!cancel||cancel.type?new CanceledError$1(null,config,request):cancel),request.abort(),request=null)},_config.cancelToken&&_config.cancelToken.subscribe(onCanceled),_config.signal&&(_config.signal.aborted?onCanceled():_config.signal.addEventListener("abort",onCanceled)));const protocol=parseProtocol(_config.url);protocol&&-1===platform.protocols.indexOf(protocol)?reject(new AxiosError$1("Unsupported protocol "+protocol+":",AxiosError$1.ERR_BAD_REQUEST,config)):request.send(requestData||null)})};const composeSignals=(signals,timeout)=>{const{length:length}=signals=signals?signals.filter(Boolean):[];if(timeout||length){let aborted,controller=new AbortController;const onabort=function(reason){if(!aborted){aborted=!0,unsubscribe();const err=reason instanceof Error?reason:this.reason;controller.abort(err instanceof AxiosError$1?err:new CanceledError$1(err instanceof Error?err.message:err))}};let timer=timeout&&setTimeout(()=>{timer=null,onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`,AxiosError$1.ETIMEDOUT))},timeout);const unsubscribe=()=>{signals&&(timer&&clearTimeout(timer),timer=null,signals.forEach(signal=>{signal.unsubscribe?signal.unsubscribe(onabort):signal.removeEventListener("abort",onabort)}),signals=null)};signals.forEach(signal=>signal.addEventListener("abort",onabort));const{signal:signal}=controller;return signal.unsubscribe=()=>utils$3.asap(unsubscribe),signal}},streamChunk=function*(chunk,chunkSize){let len=chunk.byteLength;if(len<chunkSize)return void(yield chunk);let end,pos=0;for(;pos<len;)end=pos+chunkSize,yield chunk.slice(pos,end),pos=end},readStream=async function*(stream){if(stream[Symbol.asyncIterator])return void(yield*stream);const reader=stream.getReader();try{for(;;){const{done:done,value:value}=await reader.read();if(done)break;yield value}}finally{await reader.cancel()}},trackStream=(stream,chunkSize,onProgress,onFinish)=>{const iterator=async function*(iterable,chunkSize){for await(const chunk of readStream(iterable))yield*streamChunk(chunk,chunkSize)}(stream,chunkSize);let done,bytes=0,_onFinish=e=>{done||(done=!0,onFinish&&onFinish(e))};return new ReadableStream({async pull(controller){try{const{done:done,value:value}=await iterator.next();if(done)return _onFinish(),void controller.close();let len=value.byteLength;if(onProgress){let loadedBytes=bytes+=len;onProgress(loadedBytes)}controller.enqueue(new Uint8Array(value))}catch(err){throw _onFinish(err),err}},cancel:reason=>(_onFinish(reason),iterator.return())},{highWaterMark:2})},{isFunction:isFunction}=utils$3,globalFetchAPI=(({Request:Request,Response:Response})=>({Request:Request,Response:Response}))(utils$3.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$3.global,test=(fn,...args)=>{try{return!!fn(...args)}catch(e){return!1}},factory=env=>{env=utils$3.merge.call({skipUndefined:!0},globalFetchAPI,env);const{fetch:envFetch,Request:Request,Response:Response}=env,isFetchSupported=envFetch?isFunction(envFetch):"function"==typeof fetch,isRequestSupported=isFunction(Request),isResponseSupported=isFunction(Response);if(!isFetchSupported)return!1;const isReadableStreamSupported=isFetchSupported&&isFunction(ReadableStream$1),encodeText=isFetchSupported&&("function"==typeof TextEncoder$1?(encoder=new TextEncoder$1,str=>encoder.encode(str)):async str=>new Uint8Array(await new Request(str).arrayBuffer()));var encoder;const supportsRequestStream=isRequestSupported&&isReadableStreamSupported&&test(()=>{let duplexAccessed=!1;const hasContentType=new Request(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return duplexAccessed=!0,"half"}}).headers.has("Content-Type");return duplexAccessed&&!hasContentType}),supportsResponseStream=isResponseSupported&&isReadableStreamSupported&&test(()=>utils$3.isReadableStream(new Response("").body)),resolvers={stream:supportsResponseStream&&(res=>res.body)};isFetchSupported&&["text","arrayBuffer","blob","formData","stream"].forEach(type=>{!resolvers[type]&&(resolvers[type]=(res,config)=>{let method=res&&res[type];if(method)return method.call(res);throw new AxiosError$1(`Response type '${type}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,config)})});const resolveBodyLength=async(headers,body)=>{const length=utils$3.toFiniteNumber(headers.getContentLength());return null==length?(async body=>{if(null==body)return 0;if(utils$3.isBlob(body))return body.size;if(utils$3.isSpecCompliantForm(body)){const _request=new Request(platform.origin,{method:"POST",body:body});return(await _request.arrayBuffer()).byteLength}return utils$3.isArrayBufferView(body)||utils$3.isArrayBuffer(body)?body.byteLength:(utils$3.isURLSearchParams(body)&&(body+=""),utils$3.isString(body)?(await encodeText(body)).byteLength:void 0)})(body):length};return async config=>{let{url:url,method:method,data:data,signal:signal,cancelToken:cancelToken,timeout:timeout,onDownloadProgress:onDownloadProgress,onUploadProgress:onUploadProgress,responseType:responseType,headers:headers,withCredentials:withCredentials="same-origin",fetchOptions:fetchOptions}=resolveConfig(config),_fetch=envFetch||fetch;responseType=responseType?(responseType+"").toLowerCase():"text";let composedSignal=composeSignals([signal,cancelToken&&cancelToken.toAbortSignal()],timeout),request=null;const unsubscribe=composedSignal&&composedSignal.unsubscribe&&(()=>{composedSignal.unsubscribe()});let requestContentLength;try{if(onUploadProgress&&supportsRequestStream&&"get"!==method&&"head"!==method&&0!==(requestContentLength=await resolveBodyLength(headers,data))){let contentTypeHeader,_request=new Request(url,{method:"POST",body:data,duplex:"half"});if(utils$3.isFormData(data)&&(contentTypeHeader=_request.headers.get("content-type"))&&headers.setContentType(contentTypeHeader),_request.body){const[onProgress,flush]=progressEventDecorator(requestContentLength,progressEventReducer(asyncDecorator(onUploadProgress)));data=trackStream(_request.body,65536,onProgress,flush)}}utils$3.isString(withCredentials)||(withCredentials=withCredentials?"include":"omit");const isCredentialsSupported=isRequestSupported&&"credentials"in Request.prototype,resolvedOptions={...fetchOptions,signal:composedSignal,method:method.toUpperCase(),headers:headers.normalize().toJSON(),body:data,duplex:"half",credentials:isCredentialsSupported?withCredentials:void 0};request=isRequestSupported&&new Request(url,resolvedOptions);let response=await(isRequestSupported?_fetch(request,fetchOptions):_fetch(url,resolvedOptions));const isStreamResponse=supportsResponseStream&&("stream"===responseType||"response"===responseType);if(supportsResponseStream&&(onDownloadProgress||isStreamResponse&&unsubscribe)){const options={};["status","statusText","headers"].forEach(prop=>{options[prop]=response[prop]});const responseContentLength=utils$3.toFiniteNumber(response.headers.get("content-length")),[onProgress,flush]=onDownloadProgress&&progressEventDecorator(responseContentLength,progressEventReducer(asyncDecorator(onDownloadProgress),!0))||[];response=new Response(trackStream(response.body,65536,onProgress,()=>{flush&&flush(),unsubscribe&&unsubscribe()}),options)}responseType=responseType||"text";let responseData=await resolvers[utils$3.findKey(resolvers,responseType)||"text"](response,config);return!isStreamResponse&&unsubscribe&&unsubscribe(),await new Promise((resolve,reject)=>{settle(resolve,reject,{data:responseData,headers:AxiosHeaders$1.from(response.headers),status:response.status,statusText:response.statusText,config:config,request:request})})}catch(err){if(unsubscribe&&unsubscribe(),err&&"TypeError"===err.name&&/Load failed|fetch/i.test(err.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,config,request,err&&err.response),{cause:err.cause||err});throw AxiosError$1.from(err,err&&err.code,config,request,err&&err.response)}}},seedCache=new Map,getFetch=config=>{let env=config&&config.env||{};const{fetch:fetch,Request:Request,Response:Response}=env,seeds=[Request,Response,fetch];let seed,target,i=seeds.length,map=seedCache;for(;i--;)seed=seeds[i],target=map.get(seed),void 0===target&&map.set(seed,target=i?new Map:factory(env)),map=target;return target};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$3.forEach(knownAdapters,(fn,value)=>{if(fn){try{Object.defineProperty(fn,"name",{value:value})}catch(e){}Object.defineProperty(fn,"adapterName",{value:value})}});const renderReason=reason=>`- ${reason}`,isResolvedHandle=adapter=>utils$3.isFunction(adapter)||null===adapter||!1===adapter;var adapters={getAdapter:function getAdapter$1(adapters,config){adapters=utils$3.isArray(adapters)?adapters:[adapters];const{length:length}=adapters;let nameOrAdapter,adapter;const rejectedReasons={};for(let i=0;i<length;i++){let id;if(nameOrAdapter=adapters[i],adapter=nameOrAdapter,!isResolvedHandle(nameOrAdapter)&&(adapter=knownAdapters[(id=String(nameOrAdapter)).toLowerCase()],void 0===adapter))throw new AxiosError$1(`Unknown adapter '${id}'`);if(adapter&&(utils$3.isFunction(adapter)||(adapter=adapter.get(config))))break;rejectedReasons[id||"#"+i]=adapter}if(!adapter){const reasons=Object.entries(rejectedReasons).map(([id,state])=>`adapter ${id} `+(!1===state?"is not supported by the environment":"is not available in the build"));let s=length?reasons.length>1?"since :\n"+reasons.map(renderReason).join("\n"):" "+renderReason(reasons[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return adapter},adapters:knownAdapters};function throwIfCancellationRequested(config){if(config.cancelToken&&config.cancelToken.throwIfRequested(),config.signal&&config.signal.aborted)throw new CanceledError$1(null,config)}function dispatchRequest(config){throwIfCancellationRequested(config),config.headers=AxiosHeaders$1.from(config.headers),config.data=transformData.call(config,config.transformRequest),-1!==["post","put","patch"].indexOf(config.method)&&config.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(config.adapter||defaults.adapter,config)(config).then(function onAdapterResolution(response){return throwIfCancellationRequested(config),response.data=transformData.call(config,config.transformResponse,response),response.headers=AxiosHeaders$1.from(response.headers),response},function onAdapterRejection(reason){return isCancel$1(reason)||(throwIfCancellationRequested(config),reason&&reason.response&&(reason.response.data=transformData.call(config,config.transformResponse,reason.response),reason.response.headers=AxiosHeaders$1.from(reason.response.headers))),Promise.reject(reason)})}const validators$1={};["object","boolean","number","function","string","symbol"].forEach((type,i)=>{validators$1[type]=function validator(thing){return typeof thing===type||"a"+(i<1?"n ":" ")+type}});const deprecatedWarnings={};validators$1.transitional=function transitional(validator,version,message){function formatMessage(opt,desc){return"[Axios v1.13.6] Transitional option '"+opt+"'"+desc+(message?". "+message:"")}return(value,opt,opts)=>{if(!1===validator)throw new AxiosError$1(formatMessage(opt," has been removed"+(version?" in "+version:"")),AxiosError$1.ERR_DEPRECATED);return version&&!deprecatedWarnings[opt]&&(deprecatedWarnings[opt]=!0,console.warn(formatMessage(opt," has been deprecated since v"+version+" and will be removed in the near future"))),!validator||validator(value,opt,opts)}},validators$1.spelling=function spelling(correctSpelling){return(value,opt)=>(console.warn(`${opt} is likely a misspelling of ${correctSpelling}`),!0)};var validator={assertOptions:function assertOptions(options,schema,allowUnknown){if("object"!=typeof options)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const keys=Object.keys(options);let i=keys.length;for(;i-- >0;){const opt=keys[i],validator=schema[opt];if(validator){const value=options[opt],result=void 0===value||validator(value,opt,options);if(!0!==result)throw new AxiosError$1("option "+opt+" must be "+result,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(!0!==allowUnknown)throw new AxiosError$1("Unknown option "+opt,AxiosError$1.ERR_BAD_OPTION)}},validators:validators$1};const validators=validator.validators;let Axios$1=class Axios{constructor(instanceConfig){this.defaults=instanceConfig||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(configOrUrl,config){try{return await this._request(configOrUrl,config)}catch(err){if(err instanceof Error){let dummy={};Error.captureStackTrace?Error.captureStackTrace(dummy):dummy=new Error;const stack=dummy.stack?dummy.stack.replace(/^.+\n/,""):"";try{err.stack?stack&&!String(err.stack).endsWith(stack.replace(/^.+\n.+\n/,""))&&(err.stack+="\n"+stack):err.stack=stack}catch(e){}}throw err}}_request(configOrUrl,config){"string"==typeof configOrUrl?(config=config||{}).url=configOrUrl:config=configOrUrl||{},config=mergeConfig$1(this.defaults,config);const{transitional:transitional,paramsSerializer:paramsSerializer,headers:headers}=config;void 0!==transitional&&validator.assertOptions(transitional,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean)},!1),null!=paramsSerializer&&(utils$3.isFunction(paramsSerializer)?config.paramsSerializer={serialize:paramsSerializer}:validator.assertOptions(paramsSerializer,{encode:validators.function,serialize:validators.function},!0)),void 0!==config.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?config.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:config.allowAbsoluteUrls=!0),validator.assertOptions(config,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),config.method=(config.method||this.defaults.method||"get").toLowerCase();let contextHeaders=headers&&utils$3.merge(headers.common,headers[config.method]);headers&&utils$3.forEach(["delete","get","head","post","put","patch","common"],method=>{delete headers[method]}),config.headers=AxiosHeaders$1.concat(contextHeaders,headers);const requestInterceptorChain=[];let synchronousRequestInterceptors=!0;this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor){if("function"==typeof interceptor.runWhen&&!1===interceptor.runWhen(config))return;synchronousRequestInterceptors=synchronousRequestInterceptors&&interceptor.synchronous;const transitional=config.transitional||transitionalDefaults;transitional&&transitional.legacyInterceptorReqResOrdering?requestInterceptorChain.unshift(interceptor.fulfilled,interceptor.rejected):requestInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)});const responseInterceptorChain=[];let promise;this.interceptors.response.forEach(function pushResponseInterceptors(interceptor){responseInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)});let len,i=0;if(!synchronousRequestInterceptors){const chain=[dispatchRequest.bind(this),void 0];for(chain.unshift(...requestInterceptorChain),chain.push(...responseInterceptorChain),len=chain.length,promise=Promise.resolve(config);i<len;)promise=promise.then(chain[i++],chain[i++]);return promise}len=requestInterceptorChain.length;let newConfig=config;for(;i<len;){const onFulfilled=requestInterceptorChain[i++],onRejected=requestInterceptorChain[i++];try{newConfig=onFulfilled(newConfig)}catch(error){onRejected.call(this,error);break}}try{promise=dispatchRequest.call(this,newConfig)}catch(error){return Promise.reject(error)}for(i=0,len=responseInterceptorChain.length;i<len;)promise=promise.then(responseInterceptorChain[i++],responseInterceptorChain[i++]);return promise}getUri(config){return buildURL(buildFullPath((config=mergeConfig$1(this.defaults,config)).baseURL,config.url,config.allowAbsoluteUrls),config.params,config.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function forEachMethodNoData(method){Axios$1.prototype[method]=function(url,config){return this.request(mergeConfig$1(config||{},{method:method,url:url,data:(config||{}).data}))}}),utils$3.forEach(["post","put","patch"],function forEachMethodWithData(method){function generateHTTPMethod(isForm){return function httpMethod(url,data,config){return this.request(mergeConfig$1(config||{},{method:method,headers:isForm?{"Content-Type":"multipart/form-data"}:{},url:url,data:data}))}}Axios$1.prototype[method]=generateHTTPMethod(),Axios$1.prototype[method+"Form"]=generateHTTPMethod(!0)});const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(HttpStatusCode$1).forEach(([key,value])=>{HttpStatusCode$1[value]=key});const axios=function createInstance(defaultConfig){const context=new Axios$1(defaultConfig),instance=bind(Axios$1.prototype.request,context);return utils$3.extend(instance,Axios$1.prototype,context,{allOwnKeys:!0}),utils$3.extend(instance,context,null,{allOwnKeys:!0}),instance.create=function create(instanceConfig){return createInstance(mergeConfig$1(defaultConfig,instanceConfig))},instance}(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=class CancelToken{constructor(executor){if("function"!=typeof executor)throw new TypeError("executor must be a function.");let resolvePromise;this.promise=new Promise(function promiseExecutor(resolve){resolvePromise=resolve});const token=this;this.promise.then(cancel=>{if(!token._listeners)return;let i=token._listeners.length;for(;i-- >0;)token._listeners[i](cancel);token._listeners=null}),this.promise.then=onfulfilled=>{let _resolve;const promise=new Promise(resolve=>{token.subscribe(resolve),_resolve=resolve}).then(onfulfilled);return promise.cancel=function reject(){token.unsubscribe(_resolve)},promise},executor(function cancel(message,config,request){token.reason||(token.reason=new CanceledError$1(message,config,request),resolvePromise(token.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(listener){this.reason?listener(this.reason):this._listeners?this._listeners.push(listener):this._listeners=[listener]}unsubscribe(listener){if(!this._listeners)return;const index=this._listeners.indexOf(listener);-1!==index&&this._listeners.splice(index,1)}toAbortSignal(){const controller=new AbortController,abort=err=>{controller.abort(err)};return this.subscribe(abort),controller.signal.unsubscribe=()=>this.unsubscribe(abort),controller.signal}static source(){let cancel;return{token:new CancelToken(function executor(c){cancel=c}),cancel:cancel}}},axios.isCancel=isCancel$1,axios.VERSION="1.13.6",axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function all(promises){return Promise.all(promises)},axios.spread=function spread$1(callback){return function wrap(arr){return callback.apply(null,arr)}},axios.isAxiosError=function isAxiosError$1(payload){return utils$3.isObject(payload)&&!0===payload.isAxiosError},axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=thing=>formDataToJSON(utils$3.isHTMLForm(thing)?new FormData(thing):thing),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig}=axios;const apiService=new class ApiService{constructor(){this.client=axios.create({timeout:3e4,headers:{"Content-Type":"application/json","User-Agent":"buildx-cli/1.0.0"}}),this.client.interceptors.request.use(config=>{this.initializeClient();const apiConfig=configManager.getApiConfig();(null==apiConfig?void 0:apiConfig.apiKey)&&(config.headers["X-API-Key"]=apiConfig.apiKey);const auth=configManager.getAuth();return(null==auth?void 0:auth.token)&&(config.headers.Authorization=`Bearer ${auth.token}`),config}),this.client.interceptors.response.use(response=>response,error=>{var _a;if(401===(null==(_a=error.response)?void 0:_a.status))throw configManager.clearAuth(),new Error("Authentication failed. Please login again.");throw error})}initializeClient(){const apiConfig=configManager.getApiConfig();if(!(null==apiConfig?void 0:apiConfig.endpoint))throw new Error("API endpoint not configured. Please run 'buildx config setup' first.");this.client.defaults.baseURL=apiConfig.endpoint}async request(config){var _a;const apiConfig=configManager.getApiConfig();if(!(null==apiConfig?void 0:apiConfig.endpoint))throw new Error("API endpoint not configured. Please run 'buildx config setup' first.");config.baseURL=apiConfig.endpoint;try{const response=await this.client.request(config);if(response.data.error)throw response.data.message?new Error(`${response.data.error} (${response.data.message})`):new Error(response.data.error);return{data:response.data,status:response.status,message:response.statusText}}catch(error){throw error.response?new Error(`API Error: ${error.response.status} - ${(null==(_a=error.response.data)?void 0:_a.message)||error.response.statusText}`):error.request?new Error("Network error: Unable to connect to the API"):new Error(`Request error: ${error.message}`)}}async login(credentials){return(await this.request({method:"POST",url:"/auth/login",data:credentials})).data}async getProjects(){return(await this.request({method:"GET",url:"/projects"})).data}async getSchema(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/collections/schema`})).data}async getCollections(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/collections`})).data}async upsertCollection(projectId,collection){return(await this.request({method:"POST",url:`/project/${projectId}/collections`,data:collection})).data}async getFunctionContextSchema(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/functions/context/schema`})).data}async getFunctionContextSchemaInfo(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/functions/context/schema/info`})).data}async listFunctions(projectId){return(await this.request({method:"GET",url:`/project/${projectId}/functions`})).data}async getFunction(projectId,functionName){return(await this.request({method:"GET",url:`/project/${projectId}/functions/${encodeURIComponent(functionName)}`})).data}async upsertFunction(projectId,functionName,payload){return(await this.request({method:"POST",url:`/project/${projectId}/functions/${encodeURIComponent(functionName)}`,data:payload})).data}async getMe(){return(await this.request({method:"GET",url:"/auth/me"})).data}setBaseUrl(baseUrl){this.client.defaults.baseURL=baseUrl}getBaseUrl(){return this.client.defaults.baseURL||""}isConfigured(){return configManager.isApiConfigured()}},loginCommand=new Command("auth:login").description("Authenticate with BuildX API").option("-t, --token <token>","API token for authentication").option("-u, --username <username>","Username for authentication").option("-p, --password <password>","Password for authentication").option("-i, --interactive","Interactive login mode").action(async options=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config setup")),process.exit(1));let token=options.token,username=options.username,password=options.password;if(!token&&!username&&!password){if("credentials"===(await inquirer.prompt([{type:"list",name:"authMethod",message:"Choose authentication method:",choices:[{name:"Username & Password",value:"credentials"},{name:"API Token",value:"token"}]}])).authMethod){const credentialAnswers=await inquirer.prompt([{type:"input",name:"username",message:"Enter your username:",validate:input=>!(!input||0===input.trim().length)||"Username is required"},{type:"password",name:"password",message:"Enter your password:",validate:input=>!(!input||0===input.trim().length)||"Password is required"}]);username=credentialAnswers.username,password=credentialAnswers.password}else{token=(await inquirer.prompt([{type:"password",name:"token",message:"Enter your API token:",validate:input=>!(!input||0===input.trim().length)||"Token is required"}])).token}}const spinner=ora("Authenticating...").start();try{if(!username||!password){const credentialAnswers=await inquirer.prompt([{type:"input",name:"username",message:"Enter your username:",validate:input=>!(!input||0===input.trim().length)||"Username is required"},{type:"password",name:"password",message:"Enter your password:",validate:input=>!(!input||0===input.trim().length)||"Password is required"}]);username=credentialAnswers.username,password=credentialAnswers.password}const loginResponse=await apiService.login({username:username,password:password});let authToken=loginResponse.token,expiresAt=loginResponse.expiresAt;username=username??"",authToken=authToken??"",expiresAt=expiresAt??new Date(Date.now()+2592e6).toISOString(),configManager.setAuth({token:authToken,expiresAt:expiresAt,username:username}),spinner.succeed("Successfully authenticated!"),console.log(chalk.green("✓ Authentication stored securely")),console.log(chalk.blue("You can now use other BuildX CLI commands"))}catch(error){spinner.fail("Authentication failed"),console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),logoutCommand=new Command("auth:logout").description("Logout and clear stored authentication").action(()=>{try{configManager.clearAuth(),console.log(chalk.green("✓ Successfully logged out")),console.log(chalk.blue("Authentication token has been cleared"))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),authStatusCommand=new Command("auth:status").description("Check authentication status").action(async()=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config setup")),process.exit(1));const isAuthenticated=configManager.isAuthenticated(),auth=configManager.getAuth();if(isAuthenticated&&auth){const spinner=ora("Validating session...").start();try{const me=await apiService.getMe();spinner.succeed("Authenticated"),console.log(chalk.green("✓ Authenticated")),console.log(chalk.blue("Username:"),me.username),auth.token&&console.log(chalk.blue("Token:"),auth.token.substring(0,8)+"..."),auth.expiresAt&&console.log(chalk.blue("Expires:"),new Date(auth.expiresAt).toLocaleString()),me.username&&console.log(chalk.blue(`You are authenticated as ${me.source}:${me.username}`))}catch(error){spinner.fail("Session invalid"),console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}else console.log(chalk.red("✗ Not authenticated")),console.log(chalk.yellow('Run "buildx login" to authenticate'))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}});var hasRequiredUniversalify,polyfills,hasRequiredPolyfills,legacyStreams,hasRequiredLegacyStreams,clone_1,hasRequiredClone,gracefulFs,hasRequiredGracefulFs,hasRequiredFs,fs$1={},universalify={};function requireUniversalify(){return hasRequiredUniversalify||(hasRequiredUniversalify=1,universalify.fromCallback=function(fn){return Object.defineProperty(function(...args){if("function"!=typeof args[args.length-1])return new Promise((resolve,reject)=>{args.push((err,res)=>null!=err?reject(err):resolve(res)),fn.apply(this,args)});fn.apply(this,args)},"name",{value:fn.name})},universalify.fromPromise=function(fn){return Object.defineProperty(function(...args){const cb=args[args.length-1];if("function"!=typeof cb)return fn.apply(this,args);args.pop(),fn.apply(this,args).then(r=>cb(null,r),cb)},"name",{value:fn.name})}),universalify}function requirePolyfills(){if(hasRequiredPolyfills)return polyfills;hasRequiredPolyfills=1;var constants=require$$0$b,origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch(er){}if("function"==typeof process.chdir){var chdir=process.chdir;process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir)}return polyfills=function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&function patchLchmod(fs){fs.lchmod=function(path,mode,callback){fs.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){err?callback&&callback(err):fs.fchmod(fd,mode,function(err){fs.close(fd,function(err2){callback&&callback(err||err2)})})})},fs.lchmodSync=function(path,mode){var ret,fd=fs.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0;try{ret=fs.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}}(fs);fs.lutimes||function patchLutimes(fs){constants.hasOwnProperty("O_SYMLINK")&&fs.futimes?(fs.lutimes=function(path,at,mt,cb){fs.open(path,constants.O_SYMLINK,function(er,fd){er?cb&&cb(er):fs.futimes(fd,at,mt,function(er){fs.close(fd,function(er2){cb&&cb(er||er2)})})})},fs.lutimesSync=function(path,at,mt){var ret,fd=fs.openSync(path,constants.O_SYMLINK),threw=!0;try{ret=fs.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}):fs.futimes&&(fs.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs.lutimesSync=function(){})}(fs);fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){});fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){});"win32"===platform&&(fs.rename="function"!=typeof fs.rename?fs.rename:function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&("EACCES"===er.code||"EPERM"===er.code||"EBUSY"===er.code)&&Date.now()-start<6e4)return setTimeout(function(){fs.stat(to,function(stater,st){stater&&"ENOENT"===stater.code?fs$rename(from,to,CB):cb(er)})},backoff),void(backoff<100&&(backoff+=10));cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename}(fs.rename));function chmodFix(orig){return orig?function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chmodFixSync(orig){return orig?function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}:orig}function chownFix(orig){return orig?function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chownFixSync(orig){return orig?function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}:orig}function statFix(orig){return orig?function(target,options,cb){function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return"function"==typeof options&&(cb=options,options=null),options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}:orig}function statFixSync(orig){return orig?function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}:orig}function chownErOk(er){return!er||("ENOSYS"===er.code||!(process.getuid&&0===process.getuid()||"EINVAL"!==er.code&&"EPERM"!==er.code))}fs.read="function"!=typeof fs.read?fs.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&"function"==typeof callback_){var eagCounter=0;callback=function(er,_,__){if(er&&"EAGAIN"===er.code&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read}(fs.read),fs.readSync="function"!=typeof fs.readSync?fs.readSync:(fs$readSync=fs.readSync,function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if("EAGAIN"===er.code&&eagCounter<10){eagCounter++;continue}throw er}});var fs$readSync},polyfills}function requireGracefulFs(){if(hasRequiredGracefulFs)return gracefulFs;hasRequiredGracefulFs=1;var gracefulQueue,previousSymbol,fs=fs$2,polyfills=requirePolyfills(),legacy=function requireLegacyStreams(){if(hasRequiredLegacyStreams)return legacyStreams;hasRequiredLegacyStreams=1;var Stream=stream$1.Stream;return legacyStreams=function legacy(fs){return{ReadStream:function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),void 0!==this.start){if("number"!=typeof this.start)throw TypeError("start must be a Number");if(void 0===this.end)this.end=1/0;else if("number"!=typeof this.end)throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}null===this.fd?fs.open(this.path,this.flags,this.mode,function(err,fd){if(err)return self.emit("error",err),void(self.readable=!1);self.fd=fd,self.emit("open",fd),self._read()}):process.nextTick(function(){self._read()})},WriteStream:function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(void 0!==this.start){if("number"!=typeof this.start)throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],null===this.fd&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}},legacyStreams}(),clone=function requireClone(){if(hasRequiredClone)return clone_1;hasRequiredClone=1,clone_1=function clone(obj){if(null===obj||"object"!=typeof obj)return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy};var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};return clone_1}(),util=require$$1$3;function publishQueue(context,queue){Object.defineProperty(context,gracefulQueue,{get:function(){return queue}})}"function"==typeof Symbol&&"function"==typeof Symbol.for?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");var retryTimer,debug=function noop(){};if(util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join("\nGFS4: "),console.error(m)}),!fs[gracefulQueue]){var queue=commonjsGlobal[gracefulQueue]||[];publishQueue(fs,queue),fs.close=function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),"function"==typeof cb&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs.close),fs.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),require$$0$7.equal(fs[gracefulQueue].length,0)})}function patch(fs){polyfills(fs),fs.gracefulify=patch,fs.createReadStream=function createReadStream(path,options){return new fs.ReadStream(path,options)},fs.createWriteStream=function createWriteStream(path,options){return new fs.WriteStream(path,options)};var fs$readFile=fs.readFile;fs.readFile=function readFile(path,options,cb){"function"==typeof options&&(cb=options,options=null);return function go$readFile(path,options,cb,startTime){return fs$readFile(path,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$readFile,[path,options,cb],err,startTime||Date.now(),Date.now()])})}(path,options,cb)};var fs$writeFile=fs.writeFile;fs.writeFile=function writeFile(path,data,options,cb){"function"==typeof options&&(cb=options,options=null);return function go$writeFile(path,data,options,cb,startTime){return fs$writeFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$writeFile,[path,data,options,cb],err,startTime||Date.now(),Date.now()])})}(path,data,options,cb)};var fs$appendFile=fs.appendFile;fs$appendFile&&(fs.appendFile=function appendFile(path,data,options,cb){"function"==typeof options&&(cb=options,options=null);return function go$appendFile(path,data,options,cb,startTime){return fs$appendFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$appendFile,[path,data,options,cb],err,startTime||Date.now(),Date.now()])})}(path,data,options,cb)});var fs$copyFile=fs.copyFile;fs$copyFile&&(fs.copyFile=function copyFile(src,dest,flags,cb){"function"==typeof flags&&(cb=flags,flags=0);return function go$copyFile(src,dest,flags,cb,startTime){return fs$copyFile(src,dest,flags,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$copyFile,[src,dest,flags,cb],err,startTime||Date.now(),Date.now()])})}(src,dest,flags,cb)});var fs$readdir=fs.readdir;fs.readdir=function readdir(path,options,cb){"function"==typeof options&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function go$readdir(path,options,cb,startTime){return fs$readdir(path,fs$readdirCallback(path,options,cb,startTime))}:function go$readdir(path,options,cb,startTime){return fs$readdir(path,options,fs$readdirCallback(path,options,cb,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path,options,cb,startTime){return function(err,files){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?(files&&files.sort&&files.sort(),"function"==typeof cb&&cb.call(this,err,files)):enqueue([go$readdir,[path,options,cb],err,startTime||Date.now(),Date.now()])}}};var noReaddirOptionVersions=/^v[0-5]\./;if("v0.8"===process.version.substr(0,4)){var legStreams=legacy(fs);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})});var fs$WriteStream=fs.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}),Object.defineProperty(fs,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}Object.defineProperty(fs,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});var fs$open=fs.open;function open(path,flags,mode,cb){return"function"==typeof mode&&(cb=mode,mode=null),function go$open(path,flags,mode,cb,startTime){return fs$open(path,flags,mode,function(err,fd){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?"function"==typeof cb&&cb.apply(this,arguments):enqueue([go$open,[path,flags,mode,cb],err,startTime||Date.now(),Date.now()])})}(path,flags,mode,cb)}return fs.open=open,fs}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,0!==fs[gracefulQueue].length){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(void 0===startTime)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();"function"==typeof cb&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1);sinceAttempt>=Math.min(1.2*sinceStart,100)?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}void 0===retryTimer&&(retryTimer=setTimeout(retry,0))}}return commonjsGlobal[gracefulQueue]||publishQueue(commonjsGlobal,fs[gracefulQueue]),gracefulFs=patch(clone(fs)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(gracefulFs=patch(fs),fs.__patched=!0),gracefulFs}function requireFs(){return hasRequiredFs||(hasRequiredFs=1,function(exports$1){const u=requireUniversalify().fromCallback,fs=requireGracefulFs(),api=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(key=>"function"==typeof fs[key]);Object.assign(exports$1,fs),api.forEach(method=>{exports$1[method]=u(fs[method])}),exports$1.exists=function(filename,callback){return"function"==typeof callback?fs.exists(filename,callback):new Promise(resolve=>fs.exists(filename,resolve))},exports$1.read=function(fd,buffer,offset,length,position,callback){return"function"==typeof callback?fs.read(fd,buffer,offset,length,position,callback):new Promise((resolve,reject)=>{fs.read(fd,buffer,offset,length,position,(err,bytesRead,buffer)=>{if(err)return reject(err);resolve({bytesRead:bytesRead,buffer:buffer})})})},exports$1.write=function(fd,buffer,...args){return"function"==typeof args[args.length-1]?fs.write(fd,buffer,...args):new Promise((resolve,reject)=>{fs.write(fd,buffer,...args,(err,bytesWritten,buffer)=>{if(err)return reject(err);resolve({bytesWritten:bytesWritten,buffer:buffer})})})},exports$1.readv=function(fd,buffers,...args){return"function"==typeof args[args.length-1]?fs.readv(fd,buffers,...args):new Promise((resolve,reject)=>{fs.readv(fd,buffers,...args,(err,bytesRead,buffers)=>{if(err)return reject(err);resolve({bytesRead:bytesRead,buffers:buffers})})})},exports$1.writev=function(fd,buffers,...args){return"function"==typeof args[args.length-1]?fs.writev(fd,buffers,...args):new Promise((resolve,reject)=>{fs.writev(fd,buffers,...args,(err,bytesWritten,buffers)=>{if(err)return reject(err);resolve({bytesWritten:bytesWritten,buffers:buffers})})})},"function"==typeof fs.realpath.native?exports$1.realpath.native=u(fs.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")}(fs$1)),fs$1}var hasRequiredUtils$1,hasRequiredMakeDir,mkdirs,hasRequiredMkdirs,pathExists_1,hasRequiredPathExists,utimes,hasRequiredUtimes,stat,hasRequiredStat,async,hasRequiredAsync,copy_1,hasRequiredCopy$1,copySync_1,hasRequiredCopySync,copy,hasRequiredCopy,remove_1,hasRequiredRemove,empty,hasRequiredEmpty,file,hasRequiredFile,link,hasRequiredLink,symlinkPaths_1,hasRequiredSymlinkPaths,symlinkType_1,hasRequiredSymlinkType,symlink,hasRequiredSymlink,ensure,hasRequiredEnsure,utils,hasRequiredUtils,jsonfile$1,hasRequiredJsonfile$1,jsonfile,hasRequiredJsonfile,outputFile_1,hasRequiredOutputFile,outputJson_1,hasRequiredOutputJson,outputJsonSync_1,hasRequiredOutputJsonSync,json,hasRequiredJson,move_1,hasRequiredMove$1,moveSync_1,hasRequiredMoveSync,move,hasRequiredMove,lib,hasRequiredLib,makeDir={},utils$1={};function requireMakeDir(){if(hasRequiredMakeDir)return makeDir;hasRequiredMakeDir=1;const fs=requireFs(),{checkPath:checkPath}=function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;hasRequiredUtils$1=1;const path$1=path;return utils$1.checkPath=function checkPath(pth){if("win32"===process.platform&&/[<>:"|?*]/.test(pth.replace(path$1.parse(pth).root,""))){const error=new Error(`Path contains invalid characters: ${pth}`);throw error.code="EINVAL",error}},utils$1}(),getMode=options=>"number"==typeof options?options:{mode:511,...options}.mode;return makeDir.makeDir=async(dir,options)=>(checkPath(dir),fs.mkdir(dir,{mode:getMode(options),recursive:!0})),makeDir.makeDirSync=(dir,options)=>(checkPath(dir),fs.mkdirSync(dir,{mode:getMode(options),recursive:!0})),makeDir}function requireMkdirs(){if(hasRequiredMkdirs)return mkdirs;hasRequiredMkdirs=1;const u=requireUniversalify().fromPromise,{makeDir:_makeDir,makeDirSync:makeDirSync}=requireMakeDir(),makeDir=u(_makeDir);return mkdirs={mkdirs:makeDir,mkdirsSync:makeDirSync,mkdirp:makeDir,mkdirpSync:makeDirSync,ensureDir:makeDir,ensureDirSync:makeDirSync}}function requirePathExists(){if(hasRequiredPathExists)return pathExists_1;hasRequiredPathExists=1;const u=requireUniversalify().fromPromise,fs=requireFs();return pathExists_1={pathExists:u(function pathExists(path){return fs.access(path).then(()=>!0).catch(()=>!1)}),pathExistsSync:fs.existsSync},pathExists_1}function requireUtimes(){if(hasRequiredUtimes)return utimes;hasRequiredUtimes=1;const fs=requireFs(),u=requireUniversalify().fromPromise;return utimes={utimesMillis:u(async function utimesMillis(path,atime,mtime){const fd=await fs.open(path,"r+");let closeErr=null;try{await fs.futimes(fd,atime,mtime)}finally{try{await fs.close(fd)}catch(e){closeErr=e}}if(closeErr)throw closeErr}),utimesMillisSync:function utimesMillisSync(path,atime,mtime){const fd=fs.openSync(path,"r+");return fs.futimesSync(fd,atime,mtime),fs.closeSync(fd)}},utimes}function requireStat(){if(hasRequiredStat)return stat;hasRequiredStat=1;const fs=requireFs(),path$1=path,u=requireUniversalify().fromPromise;function areIdentical(srcStat,destStat){return void 0!==destStat.ino&&void 0!==destStat.dev&&destStat.ino===srcStat.ino&&destStat.dev===srcStat.dev}function isSrcSubdir(src,dest){const srcArr=path$1.resolve(src).split(path$1.sep).filter(i=>i),destArr=path$1.resolve(dest).split(path$1.sep).filter(i=>i);return srcArr.every((cur,i)=>destArr[i]===cur)}function errMsg(src,dest,funcName){return`Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`}return stat={checkPaths:u(async function checkPaths(src,dest,funcName,opts){const{srcStat:srcStat,destStat:destStat}=await function getStats(src,dest,opts){const statFunc=opts.dereference?file=>fs.stat(file,{bigint:!0}):file=>fs.lstat(file,{bigint:!0});return Promise.all([statFunc(src),statFunc(dest).catch(err=>{if("ENOENT"===err.code)return null;throw err})]).then(([srcStat,destStat])=>({srcStat:srcStat,destStat:destStat}))}(src,dest,opts);if(destStat){if(areIdentical(srcStat,destStat)){const srcBaseName=path$1.basename(src),destBaseName=path$1.basename(dest);if("move"===funcName&&srcBaseName!==destBaseName&&srcBaseName.toLowerCase()===destBaseName.toLowerCase())return{srcStat:srcStat,destStat:destStat,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(srcStat.isDirectory()&&!destStat.isDirectory())throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);if(!srcStat.isDirectory()&&destStat.isDirectory())throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)}if(srcStat.isDirectory()&&isSrcSubdir(src,dest))throw new Error(errMsg(src,dest,funcName));return{srcStat:srcStat,destStat:destStat}}),checkPathsSync:function checkPathsSync(src,dest,funcName,opts){const{srcStat:srcStat,destStat:destStat}=function getStatsSync(src,dest,opts){let destStat;const statFunc=opts.dereference?file=>fs.statSync(file,{bigint:!0}):file=>fs.lstatSync(file,{bigint:!0}),srcStat=statFunc(src);try{destStat=statFunc(dest)}catch(err){if("ENOENT"===err.code)return{srcStat:srcStat,destStat:null};throw err}return{srcStat:srcStat,destStat:destStat}}(src,dest,opts);if(destStat){if(areIdentical(srcStat,destStat)){const srcBaseName=path$1.basename(src),destBaseName=path$1.basename(dest);if("move"===funcName&&srcBaseName!==destBaseName&&srcBaseName.toLowerCase()===destBaseName.toLowerCase())return{srcStat:srcStat,destStat:destStat,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(srcStat.isDirectory()&&!destStat.isDirectory())throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);if(!srcStat.isDirectory()&&destStat.isDirectory())throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)}if(srcStat.isDirectory()&&isSrcSubdir(src,dest))throw new Error(errMsg(src,dest,funcName));return{srcStat:srcStat,destStat:destStat}},checkParentPaths:u(async function checkParentPaths(src,srcStat,dest,funcName){const srcParent=path$1.resolve(path$1.dirname(src)),destParent=path$1.resolve(path$1.dirname(dest));if(destParent===srcParent||destParent===path$1.parse(destParent).root)return;let destStat;try{destStat=await fs.stat(destParent,{bigint:!0})}catch(err){if("ENOENT"===err.code)return;throw err}if(areIdentical(srcStat,destStat))throw new Error(errMsg(src,dest,funcName));return checkParentPaths(src,srcStat,destParent,funcName)}),checkParentPathsSync:function checkParentPathsSync(src,srcStat,dest,funcName){const srcParent=path$1.resolve(path$1.dirname(src)),destParent=path$1.resolve(path$1.dirname(dest));if(destParent===srcParent||destParent===path$1.parse(destParent).root)return;let destStat;try{destStat=fs.statSync(destParent,{bigint:!0})}catch(err){if("ENOENT"===err.code)return;throw err}if(areIdentical(srcStat,destStat))throw new Error(errMsg(src,dest,funcName));return checkParentPathsSync(src,srcStat,destParent,funcName)},isSrcSubdir:isSrcSubdir,areIdentical:areIdentical},stat}function requireCopy$1(){if(hasRequiredCopy$1)return copy_1;hasRequiredCopy$1=1;const fs=requireFs(),path$1=path,{mkdirs:mkdirs}=requireMkdirs(),{pathExists:pathExists}=requirePathExists(),{utimesMillis:utimesMillis}=requireUtimes(),stat=requireStat(),{asyncIteratorConcurrentProcess:asyncIteratorConcurrentProcess}=function requireAsync(){return hasRequiredAsync||(hasRequiredAsync=1,async={asyncIteratorConcurrentProcess:async function asyncIteratorConcurrentProcess(iterator,fn){const promises=[];for await(const item of iterator)promises.push(fn(item).then(()=>null,err=>err??new Error("unknown error")));await Promise.all(promises.map(promise=>promise.then(possibleErr=>{if(null!==possibleErr)throw possibleErr})))}}),async}();async function runFilter(src,dest,opts){return!opts.filter||opts.filter(src,dest)}async function getStatsAndPerformCopy(destStat,src,dest,opts){const statFn=opts.dereference?fs.stat:fs.lstat,srcStat=await statFn(src);if(srcStat.isDirectory())return async function onDir(srcStat,destStat,src,dest,opts){destStat||await fs.mkdir(dest);await asyncIteratorConcurrentProcess(await fs.opendir(src),async item=>{const srcItem=path$1.join(src,item.name),destItem=path$1.join(dest,item.name);if(await runFilter(srcItem,destItem,opts)){const{destStat:destStat}=await stat.checkPaths(srcItem,destItem,"copy",opts);await getStatsAndPerformCopy(destStat,srcItem,destItem,opts)}}),destStat||await fs.chmod(dest,srcStat.mode)}(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return async function onFile(srcStat,destStat,src,dest,opts){if(!destStat)return copyFile(srcStat,src,dest,opts);if(opts.overwrite)return await fs.unlink(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return async function onLink(destStat,src,dest,opts){let resolvedSrc=await fs.readlink(src);opts.dereference&&(resolvedSrc=path$1.resolve(process.cwd(),resolvedSrc));if(!destStat)return fs.symlink(resolvedSrc,dest);let resolvedDest=null;try{resolvedDest=await fs.readlink(dest)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return fs.symlink(resolvedSrc,dest);throw e}opts.dereference&&(resolvedDest=path$1.resolve(process.cwd(),resolvedDest));if(resolvedSrc!==resolvedDest){if(stat.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(stat.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return await fs.unlink(dest),fs.symlink(resolvedSrc,dest)}(destStat,src,dest,opts);if(srcStat.isSocket())throw new Error(`Cannot copy a socket file: ${src}`);if(srcStat.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${src}`);throw new Error(`Unknown file: ${src}`)}async function copyFile(srcStat,src,dest,opts){if(await fs.copyFile(src,dest),opts.preserveTimestamps){(function fileIsNotWritable(srcMode){return!(128&srcMode)})(srcStat.mode)&&await function makeFileWritable(dest,srcMode){return fs.chmod(dest,128|srcMode)}(dest,srcStat.mode);const updatedSrcStat=await fs.stat(src);await utimesMillis(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}return fs.chmod(dest,srcStat.mode)}return copy_1=async function copy(src,dest,opts={}){"function"==typeof opts&&(opts={filter:opts}),opts.clobber=!("clobber"in opts)||!!opts.clobber,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0001");const{srcStat:srcStat,destStat:destStat}=await stat.checkPaths(src,dest,"copy",opts);if(await stat.checkParentPaths(src,srcStat,dest,"copy"),!await runFilter(src,dest,opts))return;const destParent=path$1.dirname(dest);await pathExists(destParent)||await mkdirs(destParent),await getStatsAndPerformCopy(destStat,src,dest,opts)},copy_1}function requireCopySync(){if(hasRequiredCopySync)return copySync_1;hasRequiredCopySync=1;const fs=requireGracefulFs(),path$1=path,mkdirsSync=requireMkdirs().mkdirsSync,utimesMillisSync=requireUtimes().utimesMillisSync,stat=requireStat();function getStats(destStat,src,dest,opts){const srcStat=(opts.dereference?fs.statSync:fs.lstatSync)(src);if(srcStat.isDirectory())return function onDir(srcStat,destStat,src,dest,opts){return destStat?copyDir(src,dest,opts):function mkDirAndCopy(srcMode,src,dest,opts){return fs.mkdirSync(dest),copyDir(src,dest,opts),setDestMode(dest,srcMode)}(srcStat.mode,src,dest,opts)}(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return function onFile(srcStat,destStat,src,dest,opts){return destStat?function mayCopyFile(srcStat,src,dest,opts){if(opts.overwrite)return fs.unlinkSync(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}(srcStat,src,dest,opts):copyFile(srcStat,src,dest,opts)}(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return function onLink(destStat,src,dest,opts){let resolvedSrc=fs.readlinkSync(src);opts.dereference&&(resolvedSrc=path$1.resolve(process.cwd(),resolvedSrc));if(destStat){let resolvedDest;try{resolvedDest=fs.readlinkSync(dest)}catch(err){if("EINVAL"===err.code||"UNKNOWN"===err.code)return fs.symlinkSync(resolvedSrc,dest);throw err}if(opts.dereference&&(resolvedDest=path$1.resolve(process.cwd(),resolvedDest)),resolvedSrc!==resolvedDest){if(stat.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(stat.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return function copyLink(resolvedSrc,dest){return fs.unlinkSync(dest),fs.symlinkSync(resolvedSrc,dest)}(resolvedSrc,dest)}return fs.symlinkSync(resolvedSrc,dest)}(destStat,src,dest,opts);if(srcStat.isSocket())throw new Error(`Cannot copy a socket file: ${src}`);if(srcStat.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${src}`);throw new Error(`Unknown file: ${src}`)}function copyFile(srcStat,src,dest,opts){return fs.copyFileSync(src,dest),opts.preserveTimestamps&&function handleTimestamps(srcMode,src,dest){(function fileIsNotWritable(srcMode){return!(128&srcMode)})(srcMode)&&function makeFileWritable(dest,srcMode){return setDestMode(dest,128|srcMode)}(dest,srcMode);return function setDestTimestamps(src,dest){const updatedSrcStat=fs.statSync(src);return utimesMillisSync(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}(src,dest)}(srcStat.mode,src,dest),setDestMode(dest,srcStat.mode)}function setDestMode(dest,srcMode){return fs.chmodSync(dest,srcMode)}function copyDir(src,dest,opts){const dir=fs.opendirSync(src);try{let dirent;for(;null!==(dirent=dir.readSync());)copyDirItem(dirent.name,src,dest,opts)}finally{dir.closeSync()}}function copyDirItem(item,src,dest,opts){const srcItem=path$1.join(src,item),destItem=path$1.join(dest,item);if(opts.filter&&!opts.filter(srcItem,destItem))return;const{destStat:destStat}=stat.checkPathsSync(srcItem,destItem,"copy",opts);return getStats(destStat,srcItem,destItem,opts)}return copySync_1=function copySync(src,dest,opts){"function"==typeof opts&&(opts={filter:opts}),(opts=opts||{}).clobber=!("clobber"in opts)||!!opts.clobber,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0002");const{srcStat:srcStat,destStat:destStat}=stat.checkPathsSync(src,dest,"copy",opts);if(stat.checkParentPathsSync(src,srcStat,dest,"copy"),opts.filter&&!opts.filter(src,dest))return;const destParent=path$1.dirname(dest);return fs.existsSync(destParent)||mkdirsSync(destParent),getStats(destStat,src,dest,opts)},copySync_1}function requireCopy(){if(hasRequiredCopy)return copy;hasRequiredCopy=1;const u=requireUniversalify().fromPromise;return copy={copy:u(requireCopy$1()),copySync:requireCopySync()}}function requireRemove(){if(hasRequiredRemove)return remove_1;hasRequiredRemove=1;const fs=requireGracefulFs(),u=requireUniversalify().fromCallback;return remove_1={remove:u(function remove(path,callback){fs.rm(path,{recursive:!0,force:!0},callback)}),removeSync:function removeSync(path){fs.rmSync(path,{recursive:!0,force:!0})}},remove_1}function requireEmpty(){if(hasRequiredEmpty)return empty;hasRequiredEmpty=1;const u=requireUniversalify().fromPromise,fs=requireFs(),path$1=path,mkdir=requireMkdirs(),remove=requireRemove(),emptyDir=u(async function emptyDir(dir){let items;try{items=await fs.readdir(dir)}catch{return mkdir.mkdirs(dir)}return Promise.all(items.map(item=>remove.remove(path$1.join(dir,item))))});function emptyDirSync(dir){let items;try{items=fs.readdirSync(dir)}catch{return mkdir.mkdirsSync(dir)}items.forEach(item=>{item=path$1.join(dir,item),remove.removeSync(item)})}return empty={emptyDirSync:emptyDirSync,emptydirSync:emptyDirSync,emptyDir:emptyDir,emptydir:emptyDir}}function requireSymlink(){if(hasRequiredSymlink)return symlink;hasRequiredSymlink=1;const u=requireUniversalify().fromPromise,path$1=path,fs=requireFs(),{mkdirs:mkdirs,mkdirsSync:mkdirsSync}=requireMkdirs(),{symlinkPaths:symlinkPaths,symlinkPathsSync:symlinkPathsSync}=function requireSymlinkPaths(){if(hasRequiredSymlinkPaths)return symlinkPaths_1;hasRequiredSymlinkPaths=1;const path$1=path,fs=requireFs(),{pathExists:pathExists}=requirePathExists(),u=requireUniversalify().fromPromise;return symlinkPaths_1={symlinkPaths:u(async function symlinkPaths(srcpath,dstpath){if(path$1.isAbsolute(srcpath)){try{await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureSymlink"),err}return{toCwd:srcpath,toDst:srcpath}}const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);if(await pathExists(relativeToDst))return{toCwd:relativeToDst,toDst:srcpath};try{await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureSymlink"),err}return{toCwd:srcpath,toDst:path$1.relative(dstdir,srcpath)}}),symlinkPathsSync:function symlinkPathsSync(srcpath,dstpath){if(path$1.isAbsolute(srcpath)){if(!fs.existsSync(srcpath))throw new Error("absolute srcpath does not exist");return{toCwd:srcpath,toDst:srcpath}}const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);if(fs.existsSync(relativeToDst))return{toCwd:relativeToDst,toDst:srcpath};if(!fs.existsSync(srcpath))throw new Error("relative srcpath does not exist");return{toCwd:srcpath,toDst:path$1.relative(dstdir,srcpath)}}}}(),{symlinkType:symlinkType,symlinkTypeSync:symlinkTypeSync}=function requireSymlinkType(){if(hasRequiredSymlinkType)return symlinkType_1;hasRequiredSymlinkType=1;const fs=requireFs(),u=requireUniversalify().fromPromise;return symlinkType_1={symlinkType:u(async function symlinkType(srcpath,type){if(type)return type;let stats;try{stats=await fs.lstat(srcpath)}catch{return"file"}return stats&&stats.isDirectory()?"dir":"file"}),symlinkTypeSync:function symlinkTypeSync(srcpath,type){if(type)return type;let stats;try{stats=fs.lstatSync(srcpath)}catch{return"file"}return stats&&stats.isDirectory()?"dir":"file"}},symlinkType_1}(),{pathExists:pathExists}=requirePathExists(),{areIdentical:areIdentical}=requireStat();return symlink={createSymlink:u(async function createSymlink(srcpath,dstpath,type){let stats;try{stats=await fs.lstat(dstpath)}catch{}if(stats&&stats.isSymbolicLink()){let srcStat;if(path$1.isAbsolute(srcpath))srcStat=await fs.stat(srcpath);else{const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);try{srcStat=await fs.stat(relativeToDst)}catch{srcStat=await fs.stat(srcpath)}}const dstStat=await fs.stat(dstpath);if(areIdentical(srcStat,dstStat))return}const relative=await symlinkPaths(srcpath,dstpath);srcpath=relative.toDst;const toType=await symlinkType(relative.toCwd,type),dir=path$1.dirname(dstpath);return await pathExists(dir)||await mkdirs(dir),fs.symlink(srcpath,dstpath,toType)}),createSymlinkSync:function createSymlinkSync(srcpath,dstpath,type){let stats;try{stats=fs.lstatSync(dstpath)}catch{}if(stats&&stats.isSymbolicLink()){let srcStat;if(path$1.isAbsolute(srcpath))srcStat=fs.statSync(srcpath);else{const dstdir=path$1.dirname(dstpath),relativeToDst=path$1.join(dstdir,srcpath);try{srcStat=fs.statSync(relativeToDst)}catch{srcStat=fs.statSync(srcpath)}}const dstStat=fs.statSync(dstpath);if(areIdentical(srcStat,dstStat))return}const relative=symlinkPathsSync(srcpath,dstpath);srcpath=relative.toDst,type=symlinkTypeSync(relative.toCwd,type);const dir=path$1.dirname(dstpath);return fs.existsSync(dir)||mkdirsSync(dir),fs.symlinkSync(srcpath,dstpath,type)}},symlink}function requireEnsure(){if(hasRequiredEnsure)return ensure;hasRequiredEnsure=1;const{createFile:createFile,createFileSync:createFileSync}=function requireFile(){if(hasRequiredFile)return file;hasRequiredFile=1;const u=requireUniversalify().fromPromise,path$1=path,fs=requireFs(),mkdir=requireMkdirs();return file={createFile:u(async function createFile(file){let stats;try{stats=await fs.stat(file)}catch{}if(stats&&stats.isFile())return;const dir=path$1.dirname(file);let dirStats=null;try{dirStats=await fs.stat(dir)}catch(err){if("ENOENT"===err.code)return await mkdir.mkdirs(dir),void await fs.writeFile(file,"");throw err}dirStats.isDirectory()?await fs.writeFile(file,""):await fs.readdir(dir)}),createFileSync:function createFileSync(file){let stats;try{stats=fs.statSync(file)}catch{}if(stats&&stats.isFile())return;const dir=path$1.dirname(file);try{fs.statSync(dir).isDirectory()||fs.readdirSync(dir)}catch(err){if(!err||"ENOENT"!==err.code)throw err;mkdir.mkdirsSync(dir)}fs.writeFileSync(file,"")}}}(),{createLink:createLink,createLinkSync:createLinkSync}=function requireLink(){if(hasRequiredLink)return link;hasRequiredLink=1;const u=requireUniversalify().fromPromise,path$1=path,fs=requireFs(),mkdir=requireMkdirs(),{pathExists:pathExists}=requirePathExists(),{areIdentical:areIdentical}=requireStat();return link={createLink:u(async function createLink(srcpath,dstpath){let dstStat,srcStat;try{dstStat=await fs.lstat(dstpath)}catch{}try{srcStat=await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureLink"),err}if(dstStat&&areIdentical(srcStat,dstStat))return;const dir=path$1.dirname(dstpath);await pathExists(dir)||await mkdir.mkdirs(dir),await fs.link(srcpath,dstpath)}),createLinkSync:function createLinkSync(srcpath,dstpath){let dstStat;try{dstStat=fs.lstatSync(dstpath)}catch{}try{const srcStat=fs.lstatSync(srcpath);if(dstStat&&areIdentical(srcStat,dstStat))return}catch(err){throw err.message=err.message.replace("lstat","ensureLink"),err}const dir=path$1.dirname(dstpath);return fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.linkSync(srcpath,dstpath)}}}(),{createSymlink:createSymlink,createSymlinkSync:createSymlinkSync}=requireSymlink();return ensure={createFile:createFile,createFileSync:createFileSync,ensureFile:createFile,ensureFileSync:createFileSync,createLink:createLink,createLinkSync:createLinkSync,ensureLink:createLink,ensureLinkSync:createLinkSync,createSymlink:createSymlink,createSymlinkSync:createSymlinkSync,ensureSymlink:createSymlink,ensureSymlinkSync:createSymlinkSync}}function requireUtils(){if(hasRequiredUtils)return utils;return hasRequiredUtils=1,utils={stringify:function stringify(obj,{EOL:EOL="\n",finalEOL:finalEOL=!0,replacer:replacer=null,spaces:spaces}={}){const EOF=finalEOL?EOL:"";return JSON.stringify(obj,replacer,spaces).replace(/\n/g,EOL)+EOF},stripBom:function stripBom(content){return Buffer.isBuffer(content)&&(content=content.toString("utf8")),content.replace(/^\uFEFF/,"")}}}function requireJsonfile(){if(hasRequiredJsonfile)return jsonfile;hasRequiredJsonfile=1;const jsonFile=function requireJsonfile$1(){if(hasRequiredJsonfile$1)return jsonfile$1;let _fs;hasRequiredJsonfile$1=1;try{_fs=requireGracefulFs()}catch(_){_fs=fs$2}const universalify=requireUniversalify(),{stringify:stringify,stripBom:stripBom}=requireUtils(),readFile=universalify.fromPromise(async function _readFile(file,options={}){"string"==typeof options&&(options={encoding:options});const fs=options.fs||_fs,shouldThrow=!("throws"in options)||options.throws;let obj,data=await universalify.fromCallback(fs.readFile)(file,options);data=stripBom(data);try{obj=JSON.parse(data,options?options.reviver:null)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}return obj}),writeFile=universalify.fromPromise(async function _writeFile(file,obj,options={}){const fs=options.fs||_fs,str=stringify(obj,options);await universalify.fromCallback(fs.writeFile)(file,str,options)});return jsonfile$1={readFile:readFile,readFileSync:function readFileSync(file,options={}){"string"==typeof options&&(options={encoding:options});const fs=options.fs||_fs,shouldThrow=!("throws"in options)||options.throws;try{let content=fs.readFileSync(file,options);return content=stripBom(content),JSON.parse(content,options.reviver)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}},writeFile:writeFile,writeFileSync:function writeFileSync(file,obj,options={}){const fs=options.fs||_fs,str=stringify(obj,options);return fs.writeFileSync(file,str,options)}},jsonfile$1}();return jsonfile={readJson:jsonFile.readFile,readJsonSync:jsonFile.readFileSync,writeJson:jsonFile.writeFile,writeJsonSync:jsonFile.writeFileSync}}function requireOutputFile(){if(hasRequiredOutputFile)return outputFile_1;hasRequiredOutputFile=1;const u=requireUniversalify().fromPromise,fs=requireFs(),path$1=path,mkdir=requireMkdirs(),pathExists=requirePathExists().pathExists;return outputFile_1={outputFile:u(async function outputFile(file,data,encoding="utf-8"){const dir=path$1.dirname(file);return await pathExists(dir)||await mkdir.mkdirs(dir),fs.writeFile(file,data,encoding)}),outputFileSync:function outputFileSync(file,...args){const dir=path$1.dirname(file);fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.writeFileSync(file,...args)}},outputFile_1}function requireJson(){if(hasRequiredJson)return json;hasRequiredJson=1;const u=requireUniversalify().fromPromise,jsonFile=requireJsonfile();return jsonFile.outputJson=u(function requireOutputJson(){if(hasRequiredOutputJson)return outputJson_1;hasRequiredOutputJson=1;const{stringify:stringify}=requireUtils(),{outputFile:outputFile}=requireOutputFile();return outputJson_1=async function outputJson(file,data,options={}){const str=stringify(data,options);await outputFile(file,str,options)},outputJson_1}()),jsonFile.outputJsonSync=function requireOutputJsonSync(){if(hasRequiredOutputJsonSync)return outputJsonSync_1;hasRequiredOutputJsonSync=1;const{stringify:stringify}=requireUtils(),{outputFileSync:outputFileSync}=requireOutputFile();return outputJsonSync_1=function outputJsonSync(file,data,options){const str=stringify(data,options);outputFileSync(file,str,options)},outputJsonSync_1}(),jsonFile.outputJSON=jsonFile.outputJson,jsonFile.outputJSONSync=jsonFile.outputJsonSync,jsonFile.writeJSON=jsonFile.writeJson,jsonFile.writeJSONSync=jsonFile.writeJsonSync,jsonFile.readJSON=jsonFile.readJson,jsonFile.readJSONSync=jsonFile.readJsonSync,json=jsonFile}function requireMove$1(){if(hasRequiredMove$1)return move_1;hasRequiredMove$1=1;const fs=requireFs(),path$1=path,{copy:copy}=requireCopy(),{remove:remove}=requireRemove(),{mkdirp:mkdirp}=requireMkdirs(),{pathExists:pathExists}=requirePathExists(),stat=requireStat();return move_1=async function move(src,dest,opts={}){const overwrite=opts.overwrite||opts.clobber||!1,{srcStat:srcStat,isChangingCase:isChangingCase=!1}=await stat.checkPaths(src,dest,"move",opts);await stat.checkParentPaths(src,srcStat,dest,"move");const destParent=path$1.dirname(dest);return path$1.parse(destParent).root!==destParent&&await mkdirp(destParent),async function doRename(src,dest,overwrite,isChangingCase){if(!isChangingCase)if(overwrite)await remove(dest);else if(await pathExists(dest))throw new Error("dest already exists.");try{await fs.rename(src,dest)}catch(err){if("EXDEV"!==err.code)throw err;await async function moveAcrossDevice(src,dest,overwrite){const opts={overwrite:overwrite,errorOnExist:!0,preserveTimestamps:!0};return await copy(src,dest,opts),remove(src)}(src,dest,overwrite)}}(src,dest,overwrite,isChangingCase)},move_1}function requireMoveSync(){if(hasRequiredMoveSync)return moveSync_1;hasRequiredMoveSync=1;const fs=requireGracefulFs(),path$1=path,copySync=requireCopy().copySync,removeSync=requireRemove().removeSync,mkdirpSync=requireMkdirs().mkdirpSync,stat=requireStat();function rename(src,dest,overwrite){try{fs.renameSync(src,dest)}catch(err){if("EXDEV"!==err.code)throw err;return function moveAcrossDevice(src,dest,overwrite){const opts={overwrite:overwrite,errorOnExist:!0,preserveTimestamps:!0};return copySync(src,dest,opts),removeSync(src)}(src,dest,overwrite)}}return moveSync_1=function moveSync(src,dest,opts){const overwrite=(opts=opts||{}).overwrite||opts.clobber||!1,{srcStat:srcStat,isChangingCase:isChangingCase=!1}=stat.checkPathsSync(src,dest,"move",opts);return stat.checkParentPathsSync(src,srcStat,dest,"move"),function isParentRoot(dest){const parent=path$1.dirname(dest);return path$1.parse(parent).root===parent}(dest)||mkdirpSync(path$1.dirname(dest)),function doRename(src,dest,overwrite,isChangingCase){if(isChangingCase)return rename(src,dest,overwrite);if(overwrite)return removeSync(dest),rename(src,dest,overwrite);if(fs.existsSync(dest))throw new Error("dest already exists.");return rename(src,dest,overwrite)}(src,dest,overwrite,isChangingCase)},moveSync_1}function requireMove(){if(hasRequiredMove)return move;hasRequiredMove=1;const u=requireUniversalify().fromPromise;return move={move:u(requireMove$1()),moveSync:requireMoveSync()}}function requireLib(){return hasRequiredLib?lib:(hasRequiredLib=1,lib={...requireFs(),...requireCopy(),...requireEmpty(),...requireEnsure(),...requireJson(),...requireMkdirs(),...requireMove(),...requireOutputFile(),...requirePathExists(),...requireRemove()})}var fs=getDefaultExportFromCjs(requireLib());function sha256(content){return crypto$1.createHash("sha256").update(content).digest("hex")}function deepSort(value){if(Array.isArray(value))return value.map(deepSort);if(value&&"object"==typeof value){const sorted={};for(const key of Object.keys(value).sort())sorted[key]=deepSort(value[key]);return sorted}return value}function objectChecksum(value){return sha256(function stableStringify(value){return JSON.stringify(deepSort(value))}(value))}function toAbsolutePath(filePath){return path.isAbsolute(filePath)?filePath:path.resolve(process.cwd(),filePath)}async function readJsonIfExists(filePath){return await fs.pathExists(filePath)?fs.readJson(filePath):null}function parseFilters(filterInput){if(!filterInput)return[];return(Array.isArray(filterInput)?filterInput:[filterInput]).flatMap(item=>String(item).split(",")).map(item=>item.trim()).filter(Boolean)}function matchByFilters(value,filters){return!filters.length||filters.some(filter=>{const regExp=function wildcardToRegExp(pattern){const regexText=`^${pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(regexText,"i")}(filter);return regExp.test(value)})}const SYSTEM_MANAGED_FIELD_NAMES$1=new Set(["createdAt","updatedAt","createdBy","updatedBy"]);function splitTopLevelMembers(objectBody){const members=[];let current="",braceDepth=0,bracketDepth=0,parenDepth=0,angleDepth=0;for(let i=0;i<objectBody.length;i++){const ch=objectBody[i];"{"===ch&&braceDepth++,"}"===ch&&(braceDepth=Math.max(0,braceDepth-1)),"["===ch&&bracketDepth++,"]"===ch&&(bracketDepth=Math.max(0,bracketDepth-1)),"("===ch&&parenDepth++,")"===ch&&(parenDepth=Math.max(0,parenDepth-1)),"<"===ch&&angleDepth++,">"===ch&&(angleDepth=Math.max(0,angleDepth-1)),";"!==ch||0!==braceDepth||0!==bracketDepth||0!==parenDepth||0!==angleDepth?current+=ch:(current.trim()&&members.push(current.trim()),current="")}return current.trim()&&members.push(current.trim()),members}function parseCollectionIdEnum(source){const map=new Map,enumMatch=source.match(/export\s+enum\s+BxCollectionId\s*{([\s\S]*?)}/m);if(!enumMatch)return map;const body=enumMatch[1],entryRegex=/([A-Za-z0-9_]+)\s*=\s*"([^"]+)"/g;let m;for(;null!==(m=entryRegex.exec(body));)map.set(m[1],m[2]);return map}function resolveCollectionId(typeName,enumMap){const mapped=enumMap.get(typeName);return mapped||typeName.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/-/g,"_").toLowerCase()}function mapScalarTypeToFieldType(typeText){const normalized=typeText.trim().replace(/^\((.*)\)$/,"$1");return["string","BxText","BxEmail","BxUrl","BxObjectId","BxPhoneNumber","BxSequence"].includes(normalized)?"Text":["BxAuth"].includes(normalized)?"Auth":["BxLongText","BxRichText"].includes(normalized)?"LongText":["number","BxNumber","BxInteger"].includes(normalized)?"Number":["boolean","BxBoolean"].includes(normalized)?"Toggle":["BxCheckbox"].includes(normalized)?"Checkbox":["Date","BxDate"].includes(normalized)?"Date":["BxDateTime"].includes(normalized)?"DateTime":["BxChoices"].includes(normalized)?"Choices":["BxMultipleChoices"].includes(normalized)?"MultipleChoices":["BxUser"].includes(normalized)?"User":["BxUsers"].includes(normalized)?"Users":["BxFiles"].includes(normalized)?"Files":["BxImages"].includes(normalized)?"Images":["BxObject"].includes(normalized)?"Object":["BxList"].includes(normalized)?"List":["BxContent"].includes(normalized)?"Content":"Text"}function convertTypeFieldToSchemaField(typeText,optional){const requiredPart=!optional?{required:!0}:{},raw=typeText.trim(),compact=raw.replace(/\s+/g,""),primary=raw.split("|").map(part=>part.trim()).filter(Boolean).filter(part=>"null"!==part&&"undefined"!==part)[0]||raw,singleRefMatch=compact.match(/^(?:Partial<([A-Za-z0-9_]+)>\|BxDataObject|BxDataObject\|Partial<([A-Za-z0-9_]+)>)$/),singleRef=(null==singleRefMatch?void 0:singleRefMatch[1])||(null==singleRefMatch?void 0:singleRefMatch[2]);if(singleRef)return{type:"DataObject",...requiredPart,propertiesScheme:{ref:singleRef}};const manyRefMatch=compact.match(/^(?:Partial<([A-Za-z0-9_]+)>\[\]\|BxDataObject\[\]|BxDataObject\[\]\|Partial<([A-Za-z0-9_]+)>\[\])$/),manyRef=(null==manyRefMatch?void 0:manyRefMatch[1])||(null==manyRefMatch?void 0:manyRefMatch[2]);if(manyRef)return{type:"DataObjects",...requiredPart,propertiesScheme:{ref:manyRef}};if(primary.endsWith("[]")){const inner=primary.slice(0,-2).trim().replace(/^\((.*)\)$/,"$1");return{type:"List",...requiredPart,propertiesScheme:{children:[{name:"item",type:mapScalarTypeToFieldType(inner)}]}}}return primary.startsWith("{")&&primary.endsWith("}")?{type:"Object",...requiredPart,propertiesScheme:{children:[]}}:{type:mapScalarTypeToFieldType(primary),...requiredPart}}function parseBxFieldAnnotations(memberText){const annotations={},blocks=memberText.match(/\/\*\*[\s\S]*?\*\//g)||[];for(const block of blocks){const content=block.replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map(line=>line.replace(/^\s*\*\s?/,"")).join("\n"),tagRegex=/@bx\.([a-z_]+)\s*([\s\S]*?)(?=@bx\.|$)/gi;let match;for(;null!==(match=tagRegex.exec(content));){const[,keyRaw,valueRaw]=match,key=keyRaw.toLowerCase(),value=valueRaw.trim();"title"===key&&value&&(annotations.title=value),"description"===key&&value&&(annotations.description=value),"ref"===key&&value&&(annotations.ref=value),"required"===key&&(annotations.required=!value||!["false","0","no"].includes(value.toLowerCase())),"choices"===key&&value&&(annotations.choices=value.split("|").map(part=>part.trim()).filter(Boolean).map(part=>{const separator=part.indexOf(":");if(separator<0)return{value:part,label:part};return{value:part.slice(0,separator).trim(),label:part.slice(separator+1).trim()}}))}}return annotations}function stripCommentsForFieldParse(memberText){return memberText.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").trim()}function applyFieldAnnotations(fieldSchema,annotations,warnings,fieldPath){const next={...fieldSchema};return annotations.title&&(next.title=annotations.title),annotations.description&&(next.description=annotations.description),void 0!==annotations.required&&(annotations.required?next.required=!0:delete next.required),annotations.ref&&(next.propertiesScheme={...next.propertiesScheme||{},ref:annotations.ref}),annotations.choices&&("Choices"===next.type||"MultipleChoices"===next.type?next.propertiesScheme={...next.propertiesScheme||{},choices:annotations.choices}:warnings.push(`Field "${fieldPath}" has @bx.choices but inferred type is "${next.type}"`)),next}function mergeSchemaField(baseField,inferredField){if(!baseField)return inferredField;if(!inferredField)return baseField;const merged={...baseField,...inferredField},fieldType=String(inferredField.type||merged.type||""),baseProperties=baseField.propertiesScheme||{},inferredProperties=inferredField.propertiesScheme||{};return"DataObject"===fieldType||"DataObjects"===fieldType?merged.propertiesScheme={...baseProperties.ref?{ref:baseProperties.ref}:{},...baseProperties.local_key?{local_key:baseProperties.local_key}:{},...baseProperties.foreign_key?{foreign_key:baseProperties.foreign_key}:{},...baseProperties.schema?{schema:baseProperties.schema}:{},...inferredProperties.ref?{ref:inferredProperties.ref}:{},...inferredProperties.local_key?{local_key:inferredProperties.local_key}:{},...inferredProperties.foreign_key?{foreign_key:inferredProperties.foreign_key}:{},...inferredProperties.schema?{schema:inferredProperties.schema}:{}}:(baseField.propertiesScheme||inferredField.propertiesScheme)&&(merged.propertiesScheme={...baseProperties,...inferredProperties}),merged}const COLLECTION_EXPORT_KEYS=["collection_id","name","description","form_schema","timestamps","auditable"],FIELD_INTERNAL_KEYS=new Set(["_expanded","inherited","inheried"]),SYSTEM_MANAGED_FIELD_NAMES=new Set(["createdAt","updatedAt","createdBy","updatedBy"]),SYSTEM_MANAGED_TYPE_FIELDS=[{name:"createdAt",type:"BxDateTime"},{name:"updatedAt",type:"BxDateTime"},{name:"createdBy",type:"BxAuth"},{name:"updatedBy",type:"BxAuth"}];function applySchemaPullOptions(command){return command.option("-p, --project-id <project-id>","Project ID to sync schema from (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("-o, --output <path>","Output path for generated TypeScript types","./buildx/generated/types.ts").option("--collections-file <path>","Path to store editable collections-as-code JSON","./buildx/generated/collections.json").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only include collections matching wildcard pattern(s), ex: users* or order_*").option("--dry-run","Preview sync result without writing local files").option("--skip-collections-code","Skip writing collections-as-code JSON").option("--no-annotate-types","Disable @bx annotations injection into pulled types.ts").option("--raw-collections","Export raw collections payload without normalization").option("--include-buildx","Include buildx_* collections in collections-as-code JSON").option("-f, --force","Force overwrite existing files")}function printDryRunFilePreview$1(filePath,content){console.log(chalk.cyan(`\n--- DRY RUN: ${filePath} ---`)),console.log(content),console.log(chalk.cyan(`--- END DRY RUN: ${filePath} ---\n`))}function ensureConfigured$1(){apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config:setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1))}function resolveProjectId$1(projectId){if(projectId)return projectId;const defaultProjectId=configManager.getDefaultProject();if(defaultProjectId)return console.log(chalk.blue("Using project ID:"),defaultProjectId),defaultProjectId;const envConfig=loadEnvConfig();if(envConfig.BUILDX_PROJECT_ID)return console.log(chalk.blue("Using project ID from environment variable:"),envConfig.BUILDX_PROJECT_ID),envConfig.BUILDX_PROJECT_ID;console.error(chalk.red("Error: No project ID specified")),console.log(chalk.yellow("Use --project-id option, set a default project with 'buildx projects:set-default', or set BUILDX_PROJECT_ID environment variable")),process.exit(1)}function filterCollections(collections,filters){return filters.length?collections.filter(collection=>matchByFilters(String(collection.collection_id||""),filters)):collections}function sanitizeFieldValue(value){if(Array.isArray(value))return value.map(sanitizeFieldValue);if(value&&"object"==typeof value){const result={};for(const[key,subValue]of Object.entries(value))FIELD_INTERNAL_KEYS.has(key)||(result[key]=sanitizeFieldValue(subValue));return result}return value}function normalizeCollectionForCode(collection){if(!collection||"object"!=typeof collection)return null;if(!collection.collection_id||"string"!=typeof collection.collection_id)return null;const result={};for(const key of COLLECTION_EXPORT_KEYS)void 0!==collection[key]&&(result[key]="form_schema"===key?sanitizeFieldValue(collection[key]):collection[key]);return result.form_schema&&"object"==typeof result.form_schema||(result.form_schema={}),result.form_schema=function stripSystemManagedFieldsFromSchema(formSchema){if(!formSchema||"object"!=typeof formSchema||Array.isArray(formSchema))return{};const result={};for(const[fieldName,fieldSchema]of Object.entries(formSchema))SYSTEM_MANAGED_FIELD_NAMES.has(fieldName)||(result[fieldName]=fieldSchema);return result}(result.form_schema),result}function validateCollectionForPushDetailed(collection){var _a,_b;const errors=[];if(!collection||"object"!=typeof collection||Array.isArray(collection))return["Collection must be an object"];const collectionId=String(collection.collection_id||"");if(collectionId?(collectionId.includes(" ")&&errors.push(`collection_id "${collectionId}" cannot contain spaces`),/^[A-Za-z0-9_-]+$/.test(collectionId)||errors.push(`collection_id "${collectionId}" must match [A-Za-z0-9_-]+`)):errors.push("Missing collection_id"),!collection.form_schema||"object"!=typeof collection.form_schema||Array.isArray(collection.form_schema))return errors.push(`Collection "${collectionId||"unknown"}" is missing valid form_schema object`),errors;const formSchema=collection.form_schema;for(const[fieldName,fieldSchema]of Object.entries(formSchema)){const pathPrefix=`${collectionId||"unknown"}.form_schema.${fieldName}`;if(!fieldSchema||"object"!=typeof fieldSchema||Array.isArray(fieldSchema)){errors.push(`${pathPrefix} must be an object`);continue}if(!fieldSchema.type||"string"!=typeof fieldSchema.type){errors.push(`${pathPrefix}.type is required and must be a string`);continue}const fieldType=String(fieldSchema.type);if(["DataObject","DataObjects","ReverseReference","ReverseReferences"].includes(fieldType)){const ref=null==(_a=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_a.ref;ref&&"string"==typeof ref||errors.push(`${pathPrefix}.propertiesScheme.ref is required for ${fieldType}`)}if(["Choices","MultipleChoices"].includes(fieldType)){const choices=null==(_b=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_b.choices;void 0!==choices&&(Array.isArray(choices)?choices.forEach((choice,index)=>{const choicePath=`${pathPrefix}.propertiesScheme.choices[${index}]`;choice&&"object"==typeof choice?void 0!==choice.value&&null!==choice.value&&""!==String(choice.value).trim()||errors.push(`${choicePath}.value is required`):errors.push(`${choicePath} must be an object`)}):errors.push(`${pathPrefix}.propertiesScheme.choices must be an array`))}}return errors}function diffCollectionsDetailed(local,remote,basePath=""){if(local===remote)return[];const localIsArray=Array.isArray(local),remoteIsArray=Array.isArray(remote);if(localIsArray||remoteIsArray)return JSON.stringify(local)===JSON.stringify(remote)?[]:[{type:"changed",path:basePath||".",local:local,remote:remote}];if(!(!!local&&"object"==typeof local)||!(!!remote&&"object"==typeof remote))return[{type:"changed",path:basePath||".",local:local,remote:remote}];const result=[],keys=new Set([...Object.keys(local),...Object.keys(remote)]);for(const key of[...keys].sort()){const nextPath=basePath?`${basePath}.${key}`:key,hasLocal=Object.prototype.hasOwnProperty.call(local,key),hasRemote=Object.prototype.hasOwnProperty.call(remote,key);!hasLocal||hasRemote?hasLocal||!hasRemote?result.push(...diffCollectionsDetailed(local[key],remote[key],nextPath)):result.push({type:"added",path:nextPath,remote:remote[key]}):result.push({type:"removed",path:nextPath,local:local[key]})}return result}function formatDiffValue(value){const text=JSON.stringify(value);return void 0===text?"undefined":text.length>140?`${text.slice(0,137)}...`:text}function toSingleLineText(value){return String(value??"").replace(/\s+/g," ").trim()}function buildBxAnnotationLine(fieldSchema){var _a,_b;if(!fieldSchema||"object"!=typeof fieldSchema)return null;const tags=[],title=toSingleLineText(fieldSchema.title),description=toSingleLineText(fieldSchema.description);title&&tags.push(`@bx.title ${title}`),description&&tags.push(`@bx.description ${description}`),!0===fieldSchema.required&&tags.push("@bx.required");const ref=toSingleLineText(null==(_a=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_a.ref);ref&&tags.push(`@bx.ref ${ref}`);const choices=null==(_b=null==fieldSchema?void 0:fieldSchema.propertiesScheme)?void 0:_b.choices;if(Array.isArray(choices)&&choices.length>0){const encoded=choices.map(choice=>{const value=toSingleLineText(null==choice?void 0:choice.value);if(!value)return null;return`${value}:${!!choice&&Object.prototype.hasOwnProperty.call(choice,"label")?toSingleLineText(null==choice?void 0:choice.label):value}`}).filter(Boolean).join("|");encoded&&tags.push(`@bx.choices ${encoded}`)}return tags.length?`/** ${tags.join(" ")} */`:null}async function runSchemaPull(options){ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,outputPath=targetDirPath?path.join(targetDirPath,"types.ts"):toAbsolutePath(options.output),collectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile),manifestPath=path.join(path.dirname(collectionsFilePath),"collections.manifest.json"),spinner=ora("Fetching TypeScript types...").start(),typescriptCode=await apiService.getSchema(projectId);if(!typescriptCode||"string"!=typeof typescriptCode)throw spinner.fail("Failed to fetch TypeScript types"),new Error("Schema endpoint returned empty content");spinner.succeed("TypeScript types fetched successfully");let finalTypescriptCode=function ensureSystemManagedFieldsInTypes(typeContent){return typeContent.replace(/export\s+type\s+([A-Za-z0-9_]+)\s*=\s*{([\s\S]*?)}\s*;/g,(full,typeName,body)=>{const lines=body.split("\n"),existing=new Set;let baseIndent="\t";for(const line of lines){const fieldMatch=line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\??\s*:/);if(fieldMatch){existing.add(fieldMatch[1]);const indentMatch=line.match(/^(\s*)[A-Za-z_][A-Za-z0-9_]*\??\s*:/);indentMatch&&indentMatch[1]&&(baseIndent=indentMatch[1])}}const additions=[];for(const field of SYSTEM_MANAGED_TYPE_FIELDS)existing.has(field.name)||additions.push(`${baseIndent}${field.name}?: ${field.type};`);if(!additions.length)return full;const normalizedBody=body.trimEnd();return`export type ${typeName} = {\n${normalizedBody?`${normalizedBody}\n${additions.join("\n")}\n`:`${additions.join("\n")}\n`}};`})}(function ensureBxAuthTypeInTypes(typeContent){return/\b(?:export\s+type|type|export\s+interface|interface)\s+BxAuth\b/.test(typeContent)?typeContent:`${["export type BxAuth = {","\tid: string;","\tsource: string;","\tusername: string;","\tapi_key: string;",'\tauth_type: "system" | "jwt" | "api";',"};",""].join("\n")}\n${typeContent}`}(typescriptCode));if(!options.skipCollectionsCode){const collectionsSpinner=ora("Fetching collections-as-code...").start(),filters=parseFilters(options.filter),collections=await apiService.getCollections(projectId);let editableCollections=options.rawCollections?collections:collections.map(normalizeCollectionForCode).filter(Boolean);options.includeBuildx||(editableCollections=editableCollections.filter(col=>!String((null==col?void 0:col.collection_id)||"").startsWith("buildx_"))),editableCollections=filterCollections(editableCollections,filters),editableCollections=editableCollections.sort((a,b)=>String(a.collection_id).localeCompare(String(b.collection_id))),options.annotateTypes&&(finalTypescriptCode=function injectTypesAnnotations(typeContent,collections){const enumMap=parseCollectionIdEnum(typeContent),collectionById=new Map;for(const collection of collections){const id=String((null==collection?void 0:collection.collection_id)||"").trim();id&&collectionById.set(id,collection)}return collectionById.size?typeContent.replace(/export\s+type\s+([A-Za-z0-9_]+)\s*=\s*{([\s\S]*?)}\s*;/g,(full,typeName,body)=>{const collectionId=resolveCollectionId(typeName,enumMap),collection=collectionById.get(collectionId);if(!(null==collection?void 0:collection.form_schema)||"object"!=typeof collection.form_schema)return full;const formSchema=collection.form_schema,lines=body.split("\n"),output=[];for(const line of lines){const fieldMatch=line.match(/^(\s*)([A-Za-z_][A-Za-z0-9_]*)\??\s*:/);if(!fieldMatch){output.push(line);continue}const[,indent,fieldName]=fieldMatch,annotationLine=buildBxAnnotationLine(formSchema[fieldName]);if(annotationLine){const prev=output.length>0?output[output.length-1]:"";/@bx\./.test(prev)||output.push(`${indent}${annotationLine}`)}output.push(line)}return`export type ${typeName} = {${output.join("\n")}};`}):typeContent}(finalTypescriptCode,editableCollections)),await fs.ensureDir(path.dirname(collectionsFilePath));const manifest={version:1,projectId:projectId,generatedAt:(new Date).toISOString(),collections:{}};for(const collection of editableCollections)manifest.collections[collection.collection_id]={checksum:objectChecksum(collection)};options.dryRun?(collectionsSpinner.succeed("Collections-as-code preview ready"),console.log(chalk.cyan(`~ would write collections JSON: ${collectionsFilePath}`)),console.log(chalk.cyan(`~ would write collections manifest: ${manifestPath}`)),console.log(chalk.blue("Collections count:"),editableCollections.length),printDryRunFilePreview$1(collectionsFilePath,JSON.stringify(editableCollections,null,2)),printDryRunFilePreview$1(manifestPath,JSON.stringify(manifest,null,2))):(await fs.writeJson(collectionsFilePath,editableCollections,{spaces:2}),await fs.writeJson(manifestPath,manifest,{spaces:2}),collectionsSpinner.succeed("Collections-as-code saved"),console.log(chalk.green("✓ Collections JSON:"),collectionsFilePath),console.log(chalk.green("✓ Collections manifest:"),manifestPath))}if(await fs.ensureDir(path.dirname(outputPath)),await fs.pathExists(outputPath)&&!options.force){if(sha256(await fs.readFile(outputPath,"utf8"))!==sha256(finalTypescriptCode))throw new Error(`Output file already exists with local edits: ${outputPath}. Use --force to overwrite.`)}options.dryRun?(console.log(chalk.cyan(`~ would write types to: ${outputPath}`)),console.log(chalk.blue("Types size:"),`${(finalTypescriptCode.length/1024).toFixed(2)} KB`),printDryRunFilePreview$1(outputPath,finalTypescriptCode)):(await fs.writeFile(outputPath,finalTypescriptCode,"utf8"),console.log(chalk.green("✓ Types generated at:"),outputPath),console.log(chalk.blue("File size:"),`${(finalTypescriptCode.length/1024).toFixed(2)} KB`))}const schemaSyncCommand=applySchemaPullOptions(new Command("schema:sync").description("Deprecated alias of schema:pull (kept for compatibility)")).action(async options=>{try{console.log(chalk.yellow("schema:sync is deprecated. Use schema:pull.")),await runSchemaPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaPullCommand=applySchemaPullOptions(new Command("schema:pull").description("Pull project schema/types as code into local files")).action(async options=>{try{await runSchemaPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaPushCommand=new Command("schema:push").description("Push local collections-as-code JSON back to project").option("-p, --project-id <project-id>","Project ID to push schema to (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("--collections-file <path>","Path to collections-as-code JSON","./buildx/generated/collections.json").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only push collections matching wildcard pattern(s)").option("--dry-run","Show what would change without pushing").option("--allow-create","Allow creating new collections when collection_id does not exist on remote").option("-f, --force","Force push even when remote drift is detected").action(async options=>{var _a,_b;try{ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,collectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile),manifestPath=path.join(path.dirname(collectionsFilePath),"collections.manifest.json");if(!await fs.pathExists(collectionsFilePath))throw new Error(`Collections file not found: ${collectionsFilePath}`);const localCollections=await fs.readJson(collectionsFilePath);if(!Array.isArray(localCollections))throw new Error("Collections file must be a JSON array");const normalizedLocalCollections=localCollections.map(normalizeCollectionForCode).filter(Boolean),targetCollections=filterCollections(normalizedLocalCollections,parseFilters(options.filter)),duplicateIds=function findDuplicateCollectionIds(collections){const seen=new Set,duplicates=new Set;for(const collection of collections){const id=String((null==collection?void 0:collection.collection_id)||"").trim();id&&(seen.has(id)?duplicates.add(id):seen.add(id))}return[...duplicates]}(targetCollections);if(duplicateIds.length>0)throw new Error(`Duplicate collection_id is not allowed:\n- ${duplicateIds.join("\n- ")}`);const validationErrors=[];for(const collection of targetCollections)validationErrors.push(...validateCollectionForPushDetailed(collection));if(validationErrors.length>0)throw new Error(`Invalid collections file:\n- ${validationErrors.join("\n- ")}`);const manifest=await readJsonIfExists(manifestPath),remoteCollections=(await apiService.getCollections(projectId)).map(normalizeCollectionForCode).filter(Boolean),remoteById=new Map(remoteCollections.map(collection=>[collection.collection_id,collection]));let pushed=0,skipped=0;for(const collection of targetCollections){const collectionId=collection.collection_id,remoteCollection=remoteById.get(collectionId);if(!remoteCollection&&!options.allowCreate){console.log(chalk.yellow(`⚠ Skipped ${collectionId}: does not exist on remote (use --allow-create to create)`)),skipped++;continue}const localChecksum=objectChecksum(collection),remoteChecksum=remoteCollection?objectChecksum(remoteCollection):null,lastPulledChecksum=null==(_b=null==(_a=null==manifest?void 0:manifest.collections)?void 0:_a[collectionId])?void 0:_b.checksum;!!(!lastPulledChecksum||!remoteChecksum||lastPulledChecksum===remoteChecksum)||options.force?localChecksum!==remoteChecksum?options.dryRun?(console.log(chalk.cyan(`~ would push ${collectionId}`)),pushed++):(await apiService.upsertCollection(projectId,collection),console.log(chalk.green(`✓ pushed ${collectionId}`)),pushed++):console.log(chalk.gray(`- ${collectionId}: no changes`)):(console.log(chalk.yellow(`⚠ Skipped ${collectionId}: remote changed since last pull (use --force to override)`)),skipped++)}console.log(chalk.blue(`Done. pushed=${pushed}, skipped=${skipped}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaListCommand=new Command("schema:list").description("List remote collections in project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-u, --api-url <url>","Custom API base URL").option("--include-buildx","Include buildx_* collections").option("--filter <pattern...>","Filter collection ids by wildcard pattern(s)").action(async options=>{try{ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const filters=parseFilters(options.filter);let collections=await apiService.getCollections(projectId);options.includeBuildx||(collections=collections.filter(collection=>!String(collection.collection_id||"").startsWith("buildx_"))),collections=filterCollections(collections,filters).sort((a,b)=>String(a.collection_id).localeCompare(String(b.collection_id)));for(const collection of collections)console.log(collection.collection_id);console.log(chalk.blue(`Total: ${collections.length}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaDiffCommand=new Command("schema:diff").description("Diff local collections-as-code against remote project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("--collections-file <path>","Path to collections-as-code JSON","./buildx/generated/collections.json").option("-u, --api-url <url>","Custom API base URL").option("--include-buildx","Include buildx_* collections").option("--filter <pattern...>","Filter collection ids by wildcard pattern(s)").option("--details","Show field-level diff details for changed collections").option("--details-limit <count>","Max number of detail lines per changed collection","30").action(async options=>{try{ensureConfigured$1();const projectId=resolveProjectId$1(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const filters=parseFilters(options.filter),targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,collectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile);if(!await fs.pathExists(collectionsFilePath))throw new Error(`Collections file not found: ${collectionsFilePath}`);let localCollections=await fs.readJson(collectionsFilePath);if(!Array.isArray(localCollections))throw new Error("Collections file must be a JSON array");let remoteCollections=await apiService.getCollections(projectId);localCollections=localCollections.map(normalizeCollectionForCode).filter(Boolean),remoteCollections=remoteCollections.map(normalizeCollectionForCode).filter(Boolean),options.includeBuildx||(localCollections=localCollections.filter(collection=>!String(collection.collection_id||"").startsWith("buildx_")),remoteCollections=remoteCollections.filter(collection=>!String(collection.collection_id||"").startsWith("buildx_"))),localCollections=filterCollections(localCollections,filters),remoteCollections=filterCollections(remoteCollections,filters);const localById=new Map(localCollections.map(collection=>[collection.collection_id,collection])),remoteById=new Map(remoteCollections.map(collection=>[collection.collection_id,collection])),localIds=new Set(localById.keys()),remoteIds=new Set(remoteById.keys()),allIds=[...new Set([...localIds,...remoteIds])].sort((a,b)=>a.localeCompare(b));let onlyLocal=0,onlyRemote=0,changed=0,same=0;for(const id of allIds){const local=localById.get(id),remote=remoteById.get(id);if(!local||remote)if(local||!remote){if(local&&remote)if(objectChecksum(local)===objectChecksum(remote))console.log(chalk.gray(`= same ${id}`)),same++;else{if(console.log(chalk.cyan(`~ changed ${id}`)),options.details){const detailsLimit=Number(options.detailsLimit)>0?Number(options.detailsLimit):30,details=diffCollectionsDetailed(local,remote),show=details.slice(0,detailsLimit);for(const item of show)"added"===item.type?console.log(chalk.yellow(` + ${item.path} (remote-only) = ${formatDiffValue(item.remote)}`)):"removed"===item.type?console.log(chalk.yellow(` - ${item.path} (local-only) = ${formatDiffValue(item.local)}`)):console.log(chalk.cyan(` ~ ${item.path} local=${formatDiffValue(item.local)} remote=${formatDiffValue(item.remote)}`));details.length>show.length&&console.log(chalk.gray(` ... and ${details.length-show.length} more changes`))}changed++}}else console.log(chalk.yellow(`- remote-only ${id}`)),onlyRemote++;else console.log(chalk.yellow(`+ local-only ${id}`)),onlyLocal++}console.log(chalk.blue(`Summary: changed=${changed}, same=${same}, local-only=${onlyLocal}, remote-only=${onlyRemote}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),schemaTypesConvertCommand=new Command("schema:types:convert").description("Convert local TypeScript types file into collections-as-code JSON (review before push)").option("-t, --target-dir <path>","Base target directory for schema artifacts").option("--types-file <path>","Path to TypeScript types file","./buildx/generated/types.ts").option("--collections-file <path>","Output collections JSON path","./buildx/generated/collections.json").option("--base-collections-file <path>","Optional base collections file to merge metadata from").option("--no-allow-lossy","Require base collections metadata file (strict mode)").option("--filter <pattern...>","Filter collection ids by wildcard pattern(s)").option("--dry-run","Preview output content without writing files").action(async options=>{try{const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,typesFilePath=targetDirPath?path.join(targetDirPath,"types.ts"):toAbsolutePath(options.typesFile),outputCollectionsFilePath=targetDirPath?path.join(targetDirPath,"collections.json"):toAbsolutePath(options.collectionsFile),baseCollectionsFilePath=options.baseCollectionsFile?toAbsolutePath(options.baseCollectionsFile):outputCollectionsFilePath,filters=parseFilters(options.filter);if(!await fs.pathExists(typesFilePath))throw new Error(`Types file not found: ${typesFilePath}`);const typeContent=await fs.readFile(typesFilePath,"utf8"),{collections:collections,warnings:warnings}=function buildCollectionsFromTypes(typeContent,filters){var _a,_b;const enumMap=parseCollectionIdEnum(typeContent),typeBlocks=function parseExportedObjectTypes(source){const results=[],regex=/export\s+type\s+([A-Za-z0-9_]+)\s*=\s*{/g;let match;for(;null!==(match=regex.exec(source));){const typeName=match[1];if(typeName.startsWith("Bx"))continue;const braceStart=source.indexOf("{",match.index);if(braceStart<0)continue;let depth=0,end=-1;for(let i=braceStart;i<source.length;i++){const ch=source[i];if("{"===ch&&depth++,"}"===ch&&(depth--,0===depth)){end=i;break}}end<0||(results.push({typeName:typeName,body:source.slice(braceStart+1,end)}),regex.lastIndex=end)}return results}(typeContent),warnings=[],collections=[];for(const block of typeBlocks){const collectionId=resolveCollectionId(block.typeName,enumMap);if(!matchByFilters(collectionId,filters))continue;const members=splitTopLevelMembers(block.body),formSchema={};for(const member of members){const annotations=parseBxFieldAnnotations(member),trimmed=stripCommentsForFieldParse(member);if(!trimmed||trimmed.startsWith("//"))continue;const match=trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\??\s*:\s*([\s\S]+)$/);if(!match)continue;const[,fieldName,typeTextRaw]=match,optional=/\?\s*:/.test(trimmed);if(["_id","__bxstate"].includes(fieldName))continue;if(SYSTEM_MANAGED_FIELD_NAMES$1.has(fieldName))continue;const fieldSchema=convertTypeFieldToSchemaField(typeTextRaw.trim(),optional);"Text"!==fieldSchema.type||/^(string|BxText|BxEmail|BxUrl|BxObjectId|BxAuth|BxUser|BxPhoneNumber|BxSequence)\b/.test(typeTextRaw.trim())||warnings.push(`Field "${collectionId}.${fieldName}" used fallback Text for type "${typeTextRaw.trim()}"`),(null==(_a=fieldSchema.propertiesScheme)?void 0:_a.ref)&&enumMap.has(fieldSchema.propertiesScheme.ref)&&(fieldSchema.propertiesScheme.ref=enumMap.get(fieldSchema.propertiesScheme.ref));const annotatedField=applyFieldAnnotations(fieldSchema,annotations,warnings,`${collectionId}.${fieldName}`);(null==(_b=annotatedField.propertiesScheme)?void 0:_b.ref)&&enumMap.has(annotatedField.propertiesScheme.ref)&&(annotatedField.propertiesScheme.ref=enumMap.get(annotatedField.propertiesScheme.ref)),formSchema[fieldName]=annotatedField}collections.push({collection_id:collectionId,form_schema:formSchema})}return{collections:collections,warnings:warnings}}(typeContent,filters);let finalCollections=collections,hasBaseCollections=!1;if(baseCollectionsFilePath&&await fs.pathExists(baseCollectionsFilePath)){hasBaseCollections=!0;const baseCollections=await fs.readJson(baseCollectionsFilePath);if(Array.isArray(baseCollections)){const baseById=new Map(baseCollections.map(collection=>[collection.collection_id,collection]));finalCollections=collections.map(collection=>{const base=baseById.get(collection.collection_id);return base?normalizeCollectionForCode(function mergeCollectionWithBase(baseCollection,inferredCollection){const baseSchema=(null==baseCollection?void 0:baseCollection.form_schema)&&"object"==typeof baseCollection.form_schema?baseCollection.form_schema:{},inferredSchema=(null==inferredCollection?void 0:inferredCollection.form_schema)&&"object"==typeof inferredCollection.form_schema?inferredCollection.form_schema:{},mergedSchema={},keys=new Set([...Object.keys(baseSchema),...Object.keys(inferredSchema)]);for(const key of keys)mergedSchema[key]=mergeSchemaField(baseSchema[key],inferredSchema[key]);return{...inferredCollection,...baseCollection,form_schema:mergedSchema}}(base,collection)):collection}).filter(Boolean)}}if(!hasBaseCollections&&!1===options.allowLossy)throw new Error([`Base collections file not found: ${baseCollectionsFilePath||"(not specified)"}`,"Conversion without base metadata is lossy and usually produces a large schema:diff.","Run schema:pull first, or pass --base-collections-file <path>, or remove --no-allow-lossy."].join("\n"));if(hasBaseCollections||console.log(chalk.yellow("! Running lossy convert without base metadata (titles/choices/collection metadata may be dropped)")),warnings.length){console.log(chalk.yellow(`Conversion warnings (${warnings.length}):`));for(const warning of warnings)console.log(chalk.yellow(` - ${warning}`))}options.dryRun?(console.log(chalk.cyan(`~ would write converted collections to: ${outputCollectionsFilePath}`)),printDryRunFilePreview$1(outputCollectionsFilePath,JSON.stringify(finalCollections,null,2))):(await fs.ensureDir(path.dirname(outputCollectionsFilePath)),await fs.writeJson(outputCollectionsFilePath,finalCollections,{spaces:2}),console.log(chalk.green("✓ Converted collections written to:"),outputCollectionsFilePath),console.log(chalk.blue("Next step:")),console.log(chalk.cyan(` buildx-cli schema:push --collections-file "${outputCollectionsFilePath}" --project-id <project-id> --dry-run`)))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),syncCommand=schemaSyncCommand,ASYNC_ARROW_FUNCTION_REGEX=/^\s*async\s*\(\s*[A-Za-z_$][\w$]*(?:\s*:[^,]+)?\s*,\s*[A-Za-z_$][\w$]*(?:\s*:[^)]+)?\s*\)\s*=>\s*\{([\s\S]*)\}\s*;?\s*$/,FUNCTION_DECLARATION_REGEX=/^\s*(?:async\s+)?function(?:\s+[A-Za-z_$][\w$]*)?\s*\(\s*[A-Za-z_$][\w$]*(?:\s*:[^,]+)?\s*,\s*[A-Za-z_$][\w$]*(?:\s*:[^)]+)?\s*\)\s*\{[\s\S]*\}\s*;?\s*$/;function applyFunctionPullOptions(command){return command.option("-p, --project-id <project-id>","Project ID to sync functions from (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for function artifacts").option("--context-output <path>","Output path for function context schema","./buildx/generated/function-context.d.ts").option("--functions-dir <path>","Directory to store function source files","./buildx/functions").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only include functions matching wildcard pattern(s)").option("--full-context","Write full context schema from API (default writes compact schema)").option("--module-wrap","Wrap function code into ESM module format (experimental)").option("--no-validate-code","Skip runtime compatibility validation").option("--no-lint","Skip basic syntax lint checks").option("--dry-run","Preview sync result without writing local files").option("-f, --force","Force overwrite existing local files")}function printDryRunFilePreview(filePath,content){console.log(chalk.cyan(`\n--- DRY RUN: ${filePath} ---`)),console.log(content),console.log(chalk.cyan(`--- END DRY RUN: ${filePath} ---\n`))}function ensureConfigured(){apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config:setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1))}function resolveProjectId(projectId){if(projectId)return projectId;const defaultProjectId=configManager.getDefaultProject();if(defaultProjectId)return console.log(chalk.blue("Using project ID:"),defaultProjectId),defaultProjectId;const envConfig=loadEnvConfig();if(envConfig.BUILDX_PROJECT_ID)return console.log(chalk.blue("Using project ID from environment variable:"),envConfig.BUILDX_PROJECT_ID),envConfig.BUILDX_PROJECT_ID;console.error(chalk.red("Error: No project ID specified")),console.log(chalk.yellow("Use --project-id option, set a default project with 'buildx projects:set-default', or set BUILDX_PROJECT_ID environment variable")),process.exit(1)}function toFunctionFilename(functionName){return`${function sanitizeFileName(name){return name.replace(/[^a-zA-Z0-9._-]/g,"_")}(functionName)}.ts`}function getFunctionManifestPath(functionsDirPath){return path.join(functionsDirPath,"functions.manifest.json")}function filterFunctions(functions,filters){return filters.length?functions.filter(fn=>matchByFilters(String(fn.name||""),filters)):functions}function toImportPathWithoutExtension(fromFilePath,toFilePath){const withoutExt=path.relative(path.dirname(fromFilePath),toFilePath).split(path.sep).join("/").replace(/\.[^.]+$/,"");return withoutExt.startsWith(".")?withoutExt:`./${withoutExt}`}function normalizeFunctionSource(code,contextImportPath){const trimmed=code.trim();if(!trimmed)return[`import type { FlowContext, FlowData } from "${contextImportPath}";`,"","const handler = async (data: FlowData, context: FlowContext) => {","\treturn { data, context };","};","","export default handler;",""].join("\n");if(/\bexport\s+default\b/.test(trimmed)||/\bmodule\.exports\b/.test(trimmed))return`${trimmed}\n`;return/^(async\s*)?\([\s\S]*\)\s*=>\s*[\s\S]+$/.test(trimmed)?function wrapArrowFunctionSource(code,contextImportPath){return[`import type { FlowContext, FlowData } from "${contextImportPath}";`,"",`const handler = ${code.trim()};`,"","export default handler;",""].join("\n")}(trimmed,contextImportPath):`${trimmed}\n`}function preserveFunctionSource(code){const trimmed=code.trim();return trimmed?`${trimmed}\n`:""}function compactFunctionMetadata(detail){const metadata={};return detail.group_path&&(metadata.group_path=detail.group_path),Array.isArray(detail.compatible)&&detail.compatible.length>0&&(metadata.compatible=detail.compatible),detail.collection_id&&(metadata.collection_id=detail.collection_id),"boolean"==typeof detail.allow_anonymous&&(metadata.allow_anonymous=detail.allow_anonymous),Array.isArray(detail.allow_method)&&detail.allow_method.length>0&&(metadata.allow_method=detail.allow_method),detail.input_schema&&"{}"!==detail.input_schema&&(metadata.input_schema=detail.input_schema),detail.output_schema&&"{}"!==detail.output_schema&&(metadata.output_schema=detail.output_schema),detail.output_format&&"object"==typeof detail.output_format&&(metadata.output_format=detail.output_format),metadata}function validateFunctionRuntimeCode(code){const trimmed=String(code||"").trim();if(!trimmed)return{valid:!1,reason:"code is empty"};if(FUNCTION_DECLARATION_REGEX.test(trimmed))return{valid:!0};const arrowMatch=trimmed.match(ASYNC_ARROW_FUNCTION_REGEX);if(arrowMatch){const body=(arrowMatch[1]||"").trim();return ASYNC_ARROW_FUNCTION_REGEX.test(body)?{valid:!1,reason:"nested async wrapper detected (double-wrapped function body)"}:{valid:!0}}return{valid:!1,reason:"expected runtime wrapper function, e.g. async (data, context) => { ... }"}}function stripTypeFromParam(param){const withoutDefault=param.trim(),colonIndex=withoutDefault.indexOf(":");return(colonIndex>=0?withoutDefault.slice(0,colonIndex).trim():withoutDefault).replace(/\?/g,"")}function lintFunctionRuntimeCode(code){const trimmed=String(code||"").trim();if(!trimmed)return{valid:!1,reason:"code is empty"};try{const jsLikeCode=function toLintableRuntimeCode(code){const trimmed=String(code||"").trim();if(!trimmed)return trimmed;const arrowSignature=trimmed.match(/^(\s*async\s*)\(([\s\S]*?)\)(\s*=>\s*\{[\s\S]*\}\s*;?\s*)$/);if(arrowSignature){const params=arrowSignature[2].split(",").map(p=>stripTypeFromParam(p)).join(", ");return`${arrowSignature[1]}(${params})${arrowSignature[3]}`}const fnSignature=trimmed.match(/^(\s*(?:async\s+)?function(?:\s+[A-Za-z_$][\w$]*)?\s*)\(([\s\S]*?)\)(\s*\{[\s\S]*\}\s*;?\s*)$/);if(fnSignature){const params=fnSignature[2].split(",").map(p=>stripTypeFromParam(p)).join(", ");return`${fnSignature[1]}(${params})${fnSignature[3]}`}return trimmed}(trimmed);return jsLikeCode.startsWith("async")?new Function(`return (${jsLikeCode});`)():new Function(`${jsLikeCode}; return true;`)(),{valid:!0}}catch(error){return{valid:!1,reason:`syntax check failed (${error instanceof Error?error.message:"unknown error"})`}}}async function runFunctionPull(options){var _a;ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,contextOutputPath=targetDirPath?path.join(targetDirPath,"function-context.d.ts"):toAbsolutePath(options.contextOutput),functionsDirPath=targetDirPath?path.join(targetDirPath,"functions"):toAbsolutePath(options.functionsDir),manifestPath=getFunctionManifestPath(functionsDirPath),previousManifest=await readJsonIfExists(manifestPath),contextSpinner=ora("Fetching function context schema...").start(),contextInfo=await apiService.getFunctionContextSchemaInfo(projectId),contextSchema=options.fullContext?function ensureFlowDataType(schema){return/\btype\s+FlowData\b/.test(schema)||/\binterface\s+FlowData\b/.test(schema)?schema:`${schema.trimEnd()}\n\nexport type FlowData = Record<string, any>;\n`}(contextInfo.schema):function buildCompactContextSchema(rawSchema){const lines=["// Auto-generated by buildx-cli (compact mode).","// Use --full-context to keep the full remote schema.","","export type FlowData = Record<string, any>;","export type FlowContext = Record<string, any>;","","export interface CodeContext {","\tcontext: FlowContext;","\tdata: FlowData;","\t[key: string]: any;","}",""];return rawSchema.includes("type LODASH_TYPE")&&lines.splice(3,0,"type LODASH_TYPE = any;"),rawSchema.includes("type URL_SEARCH_PARAMS_TYPE")&&lines.splice(3,0,"type URL_SEARCH_PARAMS_TYPE = any;"),lines.join("\n")}(contextInfo.schema);if(contextSpinner.succeed("Function context schema fetched"),await fs.ensureDir(path.dirname(contextOutputPath)),await fs.pathExists(contextOutputPath)&&!options.force){if(sha256(await fs.readFile(contextOutputPath,"utf8"))!==sha256(contextSchema))throw new Error(`Context file has local edits: ${contextOutputPath}. Use --force to overwrite.`)}options.dryRun?(console.log(chalk.cyan(`~ would write function context schema: ${contextOutputPath}`)),printDryRunFilePreview(contextOutputPath,contextSchema)):await fs.writeFile(contextOutputPath,contextSchema,"utf8"),await fs.ensureDir(functionsDirPath);const listSpinner=ora("Fetching function list...").start(),filters=parseFilters(options.filter),functions=filterFunctions(await apiService.listFunctions(projectId),filters);listSpinner.succeed(`Fetched ${functions.length} functions`);const entries=[];for(const fn of functions){const name=String(fn.name||"");if(!name)continue;const detail=await apiService.getFunction(projectId,name),filename=toFunctionFilename(name),filePath=path.join(functionsDirPath,filename),contextImportPath=toImportPathWithoutExtension(filePath,contextOutputPath),sourceCode=String(detail.code||"");if(options.validateCode){const validation=validateFunctionRuntimeCode(sourceCode);validation.valid||console.log(chalk.yellow(`⚠ ${name}: runtime validation warning (${validation.reason})`))}if(options.lint){const lintResult=lintFunctionRuntimeCode(sourceCode);lintResult.valid||console.log(chalk.yellow(`⚠ ${name}: lint warning (${lintResult.reason})`))}const code=options.moduleWrap?normalizeFunctionSource(sourceCode,contextImportPath):preserveFunctionSource(sourceCode),localChecksum=sha256(code);if(await fs.pathExists(filePath)&&!options.force){const previousEntry=null==(_a=null==previousManifest?void 0:previousManifest.functions)?void 0:_a.find(entry=>entry.name===name),existingChecksum=sha256(await fs.readFile(filePath,"utf8"));if(previousEntry&&existingChecksum!==previousEntry.localChecksum){console.log(chalk.yellow(`⚠ Skipped ${name}: local file changed (use --force to overwrite)`));continue}}options.dryRun?(console.log(chalk.cyan(`~ would write function source: ${filePath}`)),printDryRunFilePreview(filePath,code)):await fs.writeFile(filePath,code,"utf8"),entries.push({name:name,file:filename,remoteChecksum:detail.checksum,localChecksum:localChecksum,metadata:compactFunctionMetadata(detail)})}const manifest={version:1,projectId:projectId,generatedAt:(new Date).toISOString(),context:{file:path.relative(path.dirname(manifestPath),contextOutputPath),checksum:contextInfo.checksum,version:contextInfo.version},functions:entries.sort((a,b)=>a.name.localeCompare(b.name))};options.dryRun?(console.log(chalk.cyan(`~ would write function manifest: ${manifestPath}`)),console.log(chalk.blue("Functions count:"),entries.length),printDryRunFilePreview(manifestPath,JSON.stringify(manifest,null,2))):(await fs.writeJson(manifestPath,manifest,{spaces:2}),console.log(chalk.green("✓ Function context schema:"),contextOutputPath),console.log(chalk.green("✓ Function sources:"),functionsDirPath),console.log(chalk.green("✓ Function manifest:"),manifestPath))}const functionSyncCommand=applyFunctionPullOptions(new Command("function:sync").description("Deprecated alias of function:pull (kept for compatibility)")).action(async options=>{try{console.log(chalk.yellow("function:sync is deprecated. Use function:pull.")),await runFunctionPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionPullCommand=applyFunctionPullOptions(new Command("function:pull").description("Pull function context type + function source files into local project")).action(async options=>{try{await runFunctionPull(options)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionPushCommand=new Command("function:push").description("Push local function source files back to project").option("-p, --project-id <project-id>","Project ID to push functions to (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for function artifacts").option("--functions-dir <path>","Directory containing function source files","./buildx/functions").option("-n, --name <function-name>","Push only one function by name").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Only push functions matching wildcard pattern(s)").option("--no-validate-code","Skip runtime compatibility validation before push").option("--no-lint","Skip basic syntax lint checks before push").option("--dry-run","Show what would be pushed").option("-f, --force","Force push even when remote drift is detected").action(async options=>{try{ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,functionsDirPath=targetDirPath?path.join(targetDirPath,"functions"):toAbsolutePath(options.functionsDir),manifestPath=getFunctionManifestPath(functionsDirPath),manifest=await readJsonIfExists(manifestPath);if(!manifest)throw new Error(`Function manifest not found: ${manifestPath}. Run function:sync first.`);const filters=parseFilters(options.filter),filteredFromManifest=filterFunctions(manifest.functions,filters),targets=options.name?filteredFromManifest.filter(entry=>entry.name===options.name):filteredFromManifest;if(0===targets.length)throw new Error(options.name?`Function "${options.name}" not found in manifest`:"No functions in manifest");if(options.validateCode){const invalidEntries=[];for(const entry of targets){const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath))continue;const validation=validateFunctionRuntimeCode(await fs.readFile(filePath,"utf8"));validation.valid||invalidEntries.push(`${entry.name}: ${validation.reason}`)}if(invalidEntries.length>0)throw new Error(`Function code validation failed:\n- ${invalidEntries.join("\n- ")}\nUse --no-validate-code to bypass.`)}if(options.lint){const lintErrors=[];for(const entry of targets){const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath))continue;const lintResult=lintFunctionRuntimeCode(await fs.readFile(filePath,"utf8"));lintResult.valid||lintErrors.push(`${entry.name}: ${lintResult.reason}`)}if(lintErrors.length>0)throw new Error(`Function lint failed:\n- ${lintErrors.join("\n- ")}\nUse --no-lint to bypass.`)}let pushed=0,skipped=0;const updatedEntries=[];for(const entry of manifest.functions){if(!targets.find(item=>item.name===entry.name)){updatedEntries.push(entry);continue}const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath)){console.log(chalk.yellow(`⚠ Skipped ${entry.name}: source file missing (${filePath})`)),skipped++,updatedEntries.push(entry);continue}const code=await fs.readFile(filePath,"utf8"),localChecksum=sha256(code),remote=await apiService.getFunction(projectId,entry.name).catch(()=>null),remoteChecksum=null==remote?void 0:remote.checksum;if(!(!entry.remoteChecksum||!remoteChecksum||remoteChecksum===entry.remoteChecksum)&&!options.force){console.log(chalk.yellow(`⚠ Skipped ${entry.name}: remote changed since last sync (use --force to override)`)),skipped++,updatedEntries.push(entry);continue}if(options.dryRun){console.log(chalk.cyan(`~ would push ${entry.name}`)),pushed++,updatedEntries.push({...entry,localChecksum:localChecksum});continue}const payload={...entry.metadata,code:code},saved=await apiService.upsertFunction(projectId,entry.name,payload),nextEntry={...entry,remoteChecksum:(null==saved?void 0:saved.checksum)||remoteChecksum,localChecksum:localChecksum};updatedEntries.push(nextEntry),console.log(chalk.green(`✓ pushed ${entry.name}`)),pushed++}manifest.generatedAt=(new Date).toISOString(),manifest.functions=updatedEntries.sort((a,b)=>a.name.localeCompare(b.name)),await fs.writeJson(manifestPath,manifest,{spaces:2}),console.log(chalk.blue(`Done. pushed=${pushed}, skipped=${skipped}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionListCommand=new Command("function:list").description("List remote functions in project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-u, --api-url <url>","Custom API base URL").option("--filter <pattern...>","Filter function names by wildcard pattern(s)").action(async options=>{try{ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const filters=parseFilters(options.filter),functions=filterFunctions(await apiService.listFunctions(projectId),filters).sort((a,b)=>String(a.name||"").localeCompare(String(b.name||"")));for(const fn of functions)console.log(fn.name);console.log(chalk.blue(`Total: ${functions.length}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),functionDiffCommand=new Command("function:diff").description("Diff local function sources against remote project").option("-p, --project-id <project-id>","Project ID (uses default if not specified)").option("-t, --target-dir <path>","Base target directory for function artifacts").option("--functions-dir <path>","Directory containing function source files","./buildx/functions").option("-u, --api-url <url>","Custom API base URL").option("-n, --name <function-name>","Diff only one function by name").option("--filter <pattern...>","Filter function names by wildcard pattern(s)").action(async options=>{try{ensureConfigured();const projectId=resolveProjectId(options.projectId);options.apiUrl&&apiService.setBaseUrl(options.apiUrl);const targetDirPath=options.targetDir?toAbsolutePath(options.targetDir):null,functionsDirPath=targetDirPath?path.join(targetDirPath,"functions"):toAbsolutePath(options.functionsDir),manifestPath=getFunctionManifestPath(functionsDirPath),manifest=await readJsonIfExists(manifestPath);if(!manifest)throw new Error(`Function manifest not found: ${manifestPath}. Run function:sync first.`);const filters=parseFilters(options.filter);let targets=filterFunctions(manifest.functions,filters);if(options.name&&(targets=targets.filter(entry=>entry.name===options.name)),!targets.length)throw new Error("No functions matched filters/name");let same=0,changed=0,missingLocal=0,missingRemote=0,remoteDrift=0;for(const entry of targets){const filePath=path.join(functionsDirPath,entry.file);if(!await fs.pathExists(filePath)){console.log(chalk.yellow(`+ local-missing ${entry.name}`)),missingLocal++;continue}const localChecksum=sha256(await fs.readFile(filePath,"utf8")),remote=await apiService.getFunction(projectId,entry.name).catch(()=>null);if(!remote){console.log(chalk.yellow(`- remote-missing ${entry.name}`)),missingRemote++;continue}entry.remoteChecksum&&remote.checksum&&entry.remoteChecksum!==remote.checksum&&(console.log(chalk.yellow(`! remote-drift ${entry.name}`)),remoteDrift++);localChecksum===(remote.checksum||sha256(String(remote.code||"")))?(console.log(chalk.gray(`= same ${entry.name}`)),same++):(console.log(chalk.cyan(`~ changed ${entry.name}`)),changed++)}console.log(chalk.blue(`Summary: changed=${changed}, same=${same}, local-missing=${missingLocal}, remote-missing=${missingRemote}, remote-drift=${remoteDrift}`))}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),projectsListCommand=new Command("projects:list").description("List available projects").action(async()=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1));const spinner=ora("Fetching projects...").start();try{const projects=await apiService.getProjects();if(spinner.succeed(`Found ${projects.length} projects`),0===projects.length)return void console.log(chalk.yellow("No projects found"));const defaultProject=configManager.getDefaultProject();console.log("\n"+chalk.blue.bold("Available Projects:")),projects.forEach(project=>{const prefix=project.project_id===defaultProject?chalk.green("★ "):" ";console.log(`${prefix}${chalk.bold(project.name)} (${project.project_id})`),project.apiUrl&&console.log(` API: ${chalk.gray(project.apiUrl)}`)}),defaultProject&&console.log(chalk.green("\n★ Default project"))}catch(error){throw spinner.fail("Failed to fetch projects"),error}}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),projectsSetDefaultCommand=new Command("projects:set-default").description("Set default project").argument("<project-id>","Project ID to set as default").action(async projectId=>{try{apiService.isConfigured()||(console.error(chalk.red("❌ API not configured")),console.log(chalk.yellow("Please configure your API endpoint and API key first:")),console.log(chalk.cyan(" buildx config:setup")),process.exit(1)),configManager.isAuthenticated()||(console.error(chalk.red("Error: Not authenticated")),console.log(chalk.yellow('Run "buildx auth:login" to authenticate first')),process.exit(1));let project=configManager.getProject(projectId);if(!project){console.log(chalk.yellow("Project not found in local config. Fetching from API..."));const found=(await apiService.getProjects()).find(p=>p.project_id===projectId);if(found)configManager.addProject(found),project=found;else{loadEnvConfig().BUILDX_PROJECT_ID===projectId?(project={project_id:projectId,name:projectId},configManager.addProject(project)):(console.error(chalk.red("Error: Project not found in configuration or API")),console.log(chalk.yellow('Run "buildx projects:list" to see available projects')),process.exit(1))}}configManager.setDefaultProject(projectId),console.log(chalk.green("✓ Default project set to:"),project.name),console.log(chalk.blue("Project ID:"),project.project_id)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),projectsCurrentCommand=new Command("projects:current").description("Show current default project").action(()=>{try{const defaultProjectId=configManager.getDefaultProject();if(!defaultProjectId)return console.log(chalk.yellow("No default project set")),void console.log(chalk.blue('Use "buildx projects:set-default <project-id>" to set a default project'));const project=configManager.getProject(defaultProjectId);if(!project)return console.log(chalk.red("Error: Default project not found in configuration")),void console.log(chalk.blue("Project ID:"),defaultProjectId);console.log(chalk.green("Current default project:")),console.log(chalk.blue("Name:"),project.name),console.log(chalk.blue("ID:"),project.project_id),project.apiUrl&&console.log(chalk.blue("API URL:"),project.apiUrl)}catch(error){console.error(chalk.red("Error:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),setupCommand=new Command("config:setup").description("Configure API endpoint and API key").option("-e, --endpoint <endpoint>","API endpoint URL").option("-k, --api-key <apiKey>","API key").action(async options=>{var _a,_b;try{let endpoint=options.endpoint,apiKey=options.apiKey;if(!endpoint||!apiKey){console.log(chalk.blue("🔧 BuildX CLI Setup")),console.log(chalk.gray("Configure your API endpoint and API key to get started.")),console.log(chalk.gray("Supports .env / env aliases: NEXT_PUBLIC_API_ENDPOINT, NEXT_PUBLIC_API_KEY, NEXT_PUBLIC_BUILDX_API_ENDPOINT, NEXT_PUBLIC_BUILDX_API_KEY, BUILDX_API_ENDPOINT, BUILDX_API_KEY.\n"));const currentConfig=configManager.getApiConfig(),envConfig=loadEnvConfig();if(!endpoint&&!apiKey&&envConfig.BUILDX_API_ENDPOINT&&envConfig.BUILDX_API_KEY){const envApiKey=envConfig.BUILDX_API_KEY,slicedApiKey2=envApiKey.substring(0,2),endpointSource=(null==(_a=envConfig._sources)?void 0:_a.endpointKey)||"unknown",apiKeySource=(null==(_b=envConfig._sources)?void 0:_b.apiKeyKey)||"unknown";console.log(chalk.yellow("Detected API config from environment/.env")),console.log(chalk.gray(` Endpoint: ${envConfig.BUILDX_API_ENDPOINT} (${endpointSource})`)),console.log(chalk.gray(` API Key: ${slicedApiKey2}${"*".repeat(Math.min(envApiKey.length-slicedApiKey2.length,8))}... (${apiKeySource})`));const{useEnvConfig:useEnvConfig}=await inquirer.prompt([{type:"confirm",name:"useEnvConfig",message:"Use detected environment values?",default:!0}]);useEnvConfig&&(endpoint=envConfig.BUILDX_API_ENDPOINT,apiKey=envConfig.BUILDX_API_KEY)}if(!endpoint||!apiKey){const answers=await inquirer.prompt([{type:"input",name:"endpoint",message:"Enter your API endpoint URL:",default:endpoint||(null==currentConfig?void 0:currentConfig.endpoint)||envConfig.BUILDX_API_ENDPOINT||"https://api.buildx.com",validate:input=>{if(!input.trim())return"Endpoint URL is required";try{return new URL(input),!0}catch{return"Please enter a valid URL"}}},{type:"password",name:"apiKey",message:"Enter your API key:",default:apiKey||(null==currentConfig?void 0:currentConfig.apiKey)||envConfig.BUILDX_API_KEY||"",validate:input=>!!input.trim()||"API key is required"}]);endpoint=answers.endpoint,apiKey=answers.apiKey}}configManager.setApiConfig({endpoint:endpoint.trim(),apiKey:apiKey.trim()});const slicedApiKey=apiKey.substring(0,2);console.log(chalk.green("✅ Configuration saved successfully!")),console.log(chalk.gray(`Endpoint: ${endpoint}`)),console.log(chalk.gray(`API Key: ${slicedApiKey}${"*".repeat(Math.min(apiKey.length-slicedApiKey.length,8))}...`)),console.log(chalk.blue("\nYou can now use the CLI commands. Start with:")),console.log(chalk.cyan(" buildx auth:login")),console.log(chalk.cyan(" buildx projects:list"))}catch(error){console.error(chalk.red("❌ Setup failed:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),configShowCommand=new Command("config:show").description("Show current configuration").action(()=>{var _a,_b,_c;try{const apiConfig=configManager.getApiConfig(),authConfig=configManager.getAuth(),projectsConfig=configManager.getProjects(),syncConfig=configManager.getSyncConfig(),envConfig=loadEnvConfig();if(console.log(chalk.blue("🔧 BuildX CLI Configuration")),console.log(chalk.gray("=".repeat(50))),console.log(chalk.yellow("\n📡 API Configuration:")),apiConfig){console.log(chalk.green(" ✅ Configured")),console.log(chalk.gray(` Endpoint: ${apiConfig.endpoint}`));const slicedApiKey=apiConfig.apiKey.substring(0,2);console.log(chalk.gray(` API Key: ${slicedApiKey}${"*".repeat(Math.min(apiConfig.apiKey.length-slicedApiKey.length,8))}...`));const storedConfig=configManager.config.get("api");if((null==storedConfig?void 0:storedConfig.endpoint)&&(null==storedConfig?void 0:storedConfig.apiKey))console.log(chalk.gray(" Source: Stored configuration"));else if(envConfig.BUILDX_API_ENDPOINT&&envConfig.BUILDX_API_KEY){if(console.log(chalk.gray(" Source: Environment variables")),envConfig.BUILDX_API_ENDPOINT){const endpointKey=(null==(_a=envConfig._sources)?void 0:_a.endpointKey)||"BUILDX_API_ENDPOINT";console.log(chalk.gray(` Env: ${endpointKey}=${envConfig.BUILDX_API_ENDPOINT}`))}if(envConfig.BUILDX_API_KEY){const slicedApiKey2=envConfig.BUILDX_API_KEY.substring(0,2),apiKeyKey=(null==(_b=envConfig._sources)?void 0:_b.apiKeyKey)||"BUILDX_API_KEY";console.log(chalk.gray(` Env: ${apiKeyKey}=${slicedApiKey2}${"*".repeat(Math.min(envConfig.BUILDX_API_KEY.length-slicedApiKey2.length,8))}...`))}}}else console.log(chalk.red(" ❌ Not configured")),console.log(chalk.gray(' Run "buildx config setup" to configure')),console.log(chalk.gray(" Or set BUILDX_API_ENDPOINT and BUILDX_API_KEY environment variables"));if(console.log(chalk.yellow("\n🔐 Authentication:")),authConfig&&configManager.isAuthenticated()?(console.log(chalk.green(" ✅ Authenticated")),console.log(chalk.gray(` Token: ${authConfig.token.substring(0,20)}...`)),authConfig.expiresAt&&console.log(chalk.gray(` Expires: ${new Date(authConfig.expiresAt).toLocaleString()}`))):(console.log(chalk.red(" ❌ Not authenticated")),console.log(chalk.gray(' Run "buildx auth:login" to authenticate'))),console.log(chalk.yellow("\n📁 Projects:")),(null==projectsConfig?void 0:projectsConfig.list)&&projectsConfig.list.length>0){if(console.log(chalk.green(` ✅ ${projectsConfig.list.length} project(s) available`)),projectsConfig.default){const defaultProject=projectsConfig.list.find(p=>p.project_id===projectsConfig.default);console.log(chalk.gray(` Default: ${(null==defaultProject?void 0:defaultProject.name)||projectsConfig.default}`))}}else if(console.log(chalk.red(" ❌ No projects available")),console.log(chalk.gray(' Run "buildx projects:list" to fetch projects')),envConfig.BUILDX_PROJECT_ID){const projectIdKey=(null==(_c=envConfig._sources)?void 0:_c.projectIdKey)||"BUILDX_PROJECT_ID";console.log(chalk.gray(` Env default candidate: ${projectIdKey}=${envConfig.BUILDX_PROJECT_ID}`))}console.log(chalk.yellow("\n🔄 Sync Configuration:")),syncConfig?console.log(chalk.gray(` Output Path: ${syncConfig.outputPath}`)):console.log(chalk.gray(" Using default sync configuration")),console.log(chalk.yellow("\n📂 Configuration File:")),console.log(chalk.gray(` ${configManager.getConfigPath()}`))}catch(error){console.error(chalk.red("❌ Failed to show configuration:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}}),configClearCommand=new Command("config:clear").description("Clear all CLI configuration (API, auth, projects, sync)").action(()=>{try{configManager.clear(),console.log(chalk.green("✅ All configuration cleared.")),console.log(chalk.yellow('You must run "buildx config setup" before using the CLI again.'))}catch(error){console.error(chalk.red("❌ Failed to clear configuration:"),error instanceof Error?error.message:"Unknown error"),process.exit(1)}});new Command("config").description("Manage CLI configuration").addCommand(setupCommand).addCommand(configShowCommand).addCommand(configClearCommand);const program=new Command,version=JSON.parse(fs$2.readFileSync("./package.json","utf8")).version;program.name("buildx").description("BuildX CLI - API authentication, project management, and schema synchronization tool").version(version,"-v, --version"),program.addCommand(loginCommand),program.addCommand(logoutCommand),program.addCommand(authStatusCommand),program.addCommand(syncCommand),program.addCommand(schemaPullCommand),program.addCommand(schemaPushCommand),program.addCommand(schemaListCommand),program.addCommand(schemaDiffCommand),program.addCommand(schemaTypesConvertCommand),program.addCommand(functionSyncCommand),program.addCommand(functionPullCommand),program.addCommand(functionPushCommand),program.addCommand(functionListCommand),program.addCommand(functionDiffCommand),program.addCommand(projectsListCommand),program.addCommand(projectsSetDefaultCommand),program.addCommand(projectsCurrentCommand),program.addCommand(setupCommand),program.addCommand(configShowCommand),program.addCommand(configClearCommand),program.exitOverride();try{program.parse()}catch(err){err instanceof Error?console.error(chalk.red("Error:"),err.message):console.error(chalk.red("An unexpected error occurred")),process.exit(1)}
|