@sr-connect/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1398 @@
1
+ #!/usr/bin/env node
2
+ import{highlightContent}from"./chunk-7ZX4RISS.js";import{__commonJS,__export,__toESM}from"./chunk-HHBSYJ3E.js";var require_picocolors=__commonJS({"node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports,module){"use strict";var p=process||{},argv2=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv2.includes("--no-color"))&&(!!env.FORCE_COLOR||argv2.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=(open,close,replace=open)=>input=>{let string4=""+input,index=string4.indexOf(close,open.length);return~index?open+replaceClose(string4,close,replace,index)+close:open+string4+close},replaceClose=(string4,close,replace,index)=>{let result="",cursor=0;do result+=string4.substring(cursor,index)+replace,cursor=index+close.length,index=string4.indexOf(close,cursor);while(~index);return result+string4.substring(cursor)},createColors=(enabled6=isColorSupported)=>{let f2=enabled6?formatter:()=>String;return{isColorSupported:enabled6,reset:f2("\x1B[0m","\x1B[0m"),bold:f2("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f2("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f2("\x1B[3m","\x1B[23m"),underline:f2("\x1B[4m","\x1B[24m"),inverse:f2("\x1B[7m","\x1B[27m"),hidden:f2("\x1B[8m","\x1B[28m"),strikethrough:f2("\x1B[9m","\x1B[29m"),black:f2("\x1B[30m","\x1B[39m"),red:f2("\x1B[31m","\x1B[39m"),green:f2("\x1B[32m","\x1B[39m"),yellow:f2("\x1B[33m","\x1B[39m"),blue:f2("\x1B[34m","\x1B[39m"),magenta:f2("\x1B[35m","\x1B[39m"),cyan:f2("\x1B[36m","\x1B[39m"),white:f2("\x1B[37m","\x1B[39m"),gray:f2("\x1B[90m","\x1B[39m"),bgBlack:f2("\x1B[40m","\x1B[49m"),bgRed:f2("\x1B[41m","\x1B[49m"),bgGreen:f2("\x1B[42m","\x1B[49m"),bgYellow:f2("\x1B[43m","\x1B[49m"),bgBlue:f2("\x1B[44m","\x1B[49m"),bgMagenta:f2("\x1B[45m","\x1B[49m"),bgCyan:f2("\x1B[46m","\x1B[49m"),bgWhite:f2("\x1B[47m","\x1B[49m"),blackBright:f2("\x1B[90m","\x1B[39m"),redBright:f2("\x1B[91m","\x1B[39m"),greenBright:f2("\x1B[92m","\x1B[39m"),yellowBright:f2("\x1B[93m","\x1B[39m"),blueBright:f2("\x1B[94m","\x1B[39m"),magentaBright:f2("\x1B[95m","\x1B[39m"),cyanBright:f2("\x1B[96m","\x1B[39m"),whiteBright:f2("\x1B[97m","\x1B[39m"),bgBlackBright:f2("\x1B[100m","\x1B[49m"),bgRedBright:f2("\x1B[101m","\x1B[49m"),bgGreenBright:f2("\x1B[102m","\x1B[49m"),bgYellowBright:f2("\x1B[103m","\x1B[49m"),bgBlueBright:f2("\x1B[104m","\x1B[49m"),bgMagentaBright:f2("\x1B[105m","\x1B[49m"),bgCyanBright:f2("\x1B[106m","\x1B[49m"),bgWhiteBright:f2("\x1B[107m","\x1B[49m")}};module.exports=createColors();module.exports.createColors=createColors}});var require_cronstrue=__commonJS({"node_modules/.pnpm/cronstrue@3.24.0/node_modules/cronstrue/dist/cronstrue.js"(exports,module){"use strict";(function(root,factory2){typeof exports=="object"&&typeof module=="object"?module.exports=factory2():typeof define=="function"&&define.amd?define("cronstrue",[],factory2):typeof exports=="object"?exports.cronstrue=factory2():root.cronstrue=factory2()})(globalThis,()=>(()=>{"use strict";var __webpack_modules__={949(__unused_webpack_module,exports2,__webpack_require__2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.CronParser=void 0;var rangeValidator_1=__webpack_require__2(515),CronParser=(function(){function CronParser2(expression,dayOfWeekStartIndexZero,monthStartIndexZero){dayOfWeekStartIndexZero===void 0&&(dayOfWeekStartIndexZero=!0),monthStartIndexZero===void 0&&(monthStartIndexZero=!1),this.expression=expression,this.dayOfWeekStartIndexZero=dayOfWeekStartIndexZero,this.monthStartIndexZero=monthStartIndexZero}return CronParser2.prototype.parse=function(){var _a3,parsed,expression=(_a3=this.expression)!==null&&_a3!==void 0?_a3:"";if(expression==="@reboot")return parsed=["@reboot","","","","","",""],parsed;if(expression.startsWith("@")){var special=this.parseSpecial(this.expression);parsed=this.extractParts(special)}else parsed=this.extractParts(this.expression);return this.normalize(parsed),this.validate(parsed),parsed},CronParser2.prototype.parseSpecial=function(expression){var specialExpressions={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},special=specialExpressions[expression];if(!special)throw new Error("Unknown special expression.");return special},CronParser2.prototype.extractParts=function(expression){if(!this.expression)throw new Error("cron expression is empty");for(var parsed=expression.trim().split(/[ ]+/),i=0;i<parsed.length;i++)if(parsed[i].includes(",")){var arrayElement=parsed[i].split(",").map(function(item){return item.trim()}).filter(function(item){return item!==""}).map(function(item){return isNaN(Number(item))?item:Number(item)}).filter(function(item){return item!==null&&item!==""});arrayElement.length===0&&arrayElement.push("*"),arrayElement.sort(function(a,b2){return a!==null&&b2!==null?a-b2:0}),parsed[i]=arrayElement.map(function(item){return item!==null?item.toString():""}).join(",")}if(parsed.length<5)throw new Error("Expression has only ".concat(parsed.length," part").concat(parsed.length==1?"":"s",". At least 5 parts are required."));if(parsed.length==5)parsed.unshift(""),parsed.push("");else if(parsed.length==6){var isYearWithNoSecondsPart=/\d{4}$/.test(parsed[5])||parsed[4]=="?"||parsed[2]=="?";isYearWithNoSecondsPart?parsed.unshift(""):parsed.push("")}else if(parsed.length>7)throw new Error("Expression has ".concat(parsed.length," parts; too many!"));return parsed},CronParser2.prototype.normalize=function(expressionParts){var _this=this;if(expressionParts[3]=expressionParts[3].replace("?","*"),expressionParts[5]=expressionParts[5].replace("?","*"),expressionParts[2]=expressionParts[2].replace("?","*"),expressionParts[0].indexOf("0/")==0&&(expressionParts[0]=expressionParts[0].replace("0/","*/")),expressionParts[1].indexOf("0/")==0&&(expressionParts[1]=expressionParts[1].replace("0/","*/")),expressionParts[2].indexOf("0/")==0&&(expressionParts[2]=expressionParts[2].replace("0/","*/")),expressionParts[3].indexOf("1/")==0&&(expressionParts[3]=expressionParts[3].replace("1/","*/")),expressionParts[4].indexOf("1/")==0&&(expressionParts[4]=expressionParts[4].replace("1/","*/")),expressionParts[6].indexOf("1/")==0&&(expressionParts[6]=expressionParts[6].replace("1/","*/")),expressionParts[5]=expressionParts[5].replace(/(^\d)|([^#/\s]\d)/g,function(t){var dowDigits=t.replace(/\D/,""),dowDigitsAdjusted=dowDigits;return _this.dayOfWeekStartIndexZero?dowDigits=="7"&&(dowDigitsAdjusted="0"):dowDigitsAdjusted=(parseInt(dowDigits)-1).toString(),t.replace(dowDigits,dowDigitsAdjusted)}),expressionParts[5]=="L"&&(expressionParts[5]="6"),expressionParts[3]=="?"&&(expressionParts[3]="*"),expressionParts[3].indexOf("W")>-1&&(expressionParts[3].indexOf(",")>-1||expressionParts[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var days={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var day in days)expressionParts[5]=expressionParts[5].replace(new RegExp(day,"gi"),days[day].toString());expressionParts[4]=expressionParts[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(t){var dowDigits=t.replace(/\D/,""),dowDigitsAdjusted=dowDigits;return _this.monthStartIndexZero&&(dowDigitsAdjusted=(parseInt(dowDigits)+1).toString()),t.replace(dowDigits,dowDigitsAdjusted)});var months={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var month in months)expressionParts[4]=expressionParts[4].replace(new RegExp(month,"gi"),months[month].toString());expressionParts[0]=="0"&&(expressionParts[0]=""),!/\*|\-|\,|\//.test(expressionParts[2])&&(/\*|\//.test(expressionParts[1])||/\*|\//.test(expressionParts[0]))&&(expressionParts[2]+="-".concat(expressionParts[2]));for(var i=0;i<expressionParts.length;i++)if(expressionParts[i].indexOf(",")!=-1&&(expressionParts[i]=expressionParts[i].split(",").filter(function(str){return str!==""}).join(",")||"*"),expressionParts[i]=="*/1"&&(expressionParts[i]="*"),expressionParts[i].indexOf("/")>-1&&!/^\*|\-|\,/.test(expressionParts[i])){var stepRangeThrough=null;switch(i){case 4:stepRangeThrough="12";break;case 5:stepRangeThrough="6";break;case 6:stepRangeThrough="9999";break;default:stepRangeThrough=null;break}if(stepRangeThrough!==null){var parts=expressionParts[i].split("/");expressionParts[i]="".concat(parts[0],"-").concat(stepRangeThrough,"/").concat(parts[1])}}},CronParser2.prototype.validate=function(parsed){var standardCronPartCharacters="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(parsed[0],standardCronPartCharacters),this.validateOnlyExpectedCharactersFound(parsed[1],standardCronPartCharacters),this.validateOnlyExpectedCharactersFound(parsed[2],standardCronPartCharacters),this.validateOnlyExpectedCharactersFound(parsed[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(parsed[4],standardCronPartCharacters),this.validateOnlyExpectedCharactersFound(parsed[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(parsed[6],standardCronPartCharacters),this.validateAnyRanges(parsed)},CronParser2.prototype.validateAnyRanges=function(parsed){rangeValidator_1.default.secondRange(parsed[0]),rangeValidator_1.default.minuteRange(parsed[1]),rangeValidator_1.default.hourRange(parsed[2]),rangeValidator_1.default.dayOfMonthRange(parsed[3]),rangeValidator_1.default.monthRange(parsed[4],this.monthStartIndexZero),rangeValidator_1.default.dayOfWeekRange(parsed[5],this.dayOfWeekStartIndexZero)},CronParser2.prototype.validateOnlyExpectedCharactersFound=function(cronPart,allowedCharsExpression){var invalidChars=cronPart.match(new RegExp("[^".concat(allowedCharsExpression,"]+"),"gi"));if(invalidChars&&invalidChars.length)throw new Error("Expression contains invalid values: '".concat(invalidChars.toString(),"'"))},CronParser2})();exports2.CronParser=CronParser},333(__unused_webpack_module,exports2,__webpack_require__2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.ExpressionDescriptor=void 0;var stringUtilities_1=__webpack_require__2(823),cronParser_1=__webpack_require__2(949),ExpressionDescriptor=(function(){function ExpressionDescriptor2(expression,options){if(this.expression=expression,this.options=options,this.expressionParts=new Array(5),!this.options.locale&&ExpressionDescriptor2.defaultLocale&&(this.options.locale=ExpressionDescriptor2.defaultLocale),!ExpressionDescriptor2.locales[this.options.locale]){var fallBackLocale=Object.keys(ExpressionDescriptor2.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(fallBackLocale,"'.")),this.options.locale=fallBackLocale}this.i18n=ExpressionDescriptor2.locales[this.options.locale],options.use24HourTimeFormat===void 0&&(options.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return ExpressionDescriptor2.toString=function(expression,_a3){var _b=_a3===void 0?{}:_a3,_c=_b.throwExceptionOnParseError,throwExceptionOnParseError=_c===void 0?!0:_c,_d=_b.verbose,verbose=_d===void 0?!1:_d,_e2=_b.dayOfWeekStartIndexZero,dayOfWeekStartIndexZero=_e2===void 0?!0:_e2,_f=_b.monthStartIndexZero,monthStartIndexZero=_f===void 0?!1:_f,use24HourTimeFormat=_b.use24HourTimeFormat,_g=_b.trimHoursLeadingZero,trimHoursLeadingZero=_g===void 0?!1:_g,_h=_b.locale,locale=_h===void 0?null:_h,_j=_b.logicalAndDayFields,logicalAndDayFields=_j===void 0?!1:_j,options={throwExceptionOnParseError,verbose,dayOfWeekStartIndexZero,monthStartIndexZero,use24HourTimeFormat,trimHoursLeadingZero,locale,logicalAndDayFields};options.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var descripter=new ExpressionDescriptor2(expression,options);return descripter.getFullDescription()},ExpressionDescriptor2.initialize=function(localesLoader,defaultLocale){defaultLocale===void 0&&(defaultLocale="en"),ExpressionDescriptor2.specialCharacters=["/","-",",","*"],ExpressionDescriptor2.defaultLocale=defaultLocale,localesLoader.load(ExpressionDescriptor2.locales)},ExpressionDescriptor2.prototype.getFullDescription=function(){var _a3,_b,description="";try{var parser=new cronParser_1.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=parser.parse(),this.expressionParts[0]==="@reboot")return((_b=(_a3=this.i18n).atReboot)===null||_b===void 0?void 0:_b.call(_a3))||"Run once, at startup";var timeSegment=this.getTimeOfDayDescription(),dayOfMonthDesc=this.getDayOfMonthDescription(),monthDesc=this.getMonthDescription(),dayOfWeekDesc=this.getDayOfWeekDescription(),yearDesc=this.getYearDescription();description+=timeSegment+dayOfMonthDesc+dayOfWeekDesc+monthDesc+yearDesc,description=this.transformVerbosity(description,!!this.options.verbose),description=description.charAt(0).toLocaleUpperCase()+description.substr(1)}catch(ex){if(!this.options.throwExceptionOnParseError)description=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(ex)}return description},ExpressionDescriptor2.prototype.getTimeOfDayDescription=function(){var secondsExpression=this.expressionParts[0],minuteExpression=this.expressionParts[1],hourExpression=this.expressionParts[2],description="";if(!stringUtilities_1.StringUtilities.containsAny(minuteExpression,ExpressionDescriptor2.specialCharacters)&&!stringUtilities_1.StringUtilities.containsAny(hourExpression,ExpressionDescriptor2.specialCharacters)&&!stringUtilities_1.StringUtilities.containsAny(secondsExpression,ExpressionDescriptor2.specialCharacters))description+=this.i18n.atSpace()+this.formatTime(hourExpression,minuteExpression,secondsExpression);else if(!secondsExpression&&minuteExpression.indexOf("-")>-1&&!(minuteExpression.indexOf(",")>-1)&&!(minuteExpression.indexOf("/")>-1)&&!stringUtilities_1.StringUtilities.containsAny(hourExpression,ExpressionDescriptor2.specialCharacters)){var minuteParts=minuteExpression.split("-");description+=stringUtilities_1.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(hourExpression,minuteParts[0],""),this.formatTime(hourExpression,minuteParts[1],""))}else if(!secondsExpression&&hourExpression.indexOf(",")>-1&&hourExpression.indexOf("-")==-1&&hourExpression.indexOf("/")==-1&&!stringUtilities_1.StringUtilities.containsAny(minuteExpression,ExpressionDescriptor2.specialCharacters)){var hourParts=hourExpression.split(",");description+=this.i18n.at();for(var i=0;i<hourParts.length;i++)description&&(description+=" "),description+=this.formatTime(hourParts[i],minuteExpression,""),i<hourParts.length-2&&(description+=","),i==hourParts.length-2&&(description+=this.i18n.spaceAnd())}else{var secondsDescription=this.getSecondsDescription(),minutesDescription=this.getMinutesDescription(),hoursDescription=this.getHoursDescription();if(description+=secondsDescription,description&&minutesDescription&&(description+=", "),description+=minutesDescription,minutesDescription===hoursDescription)return description;description&&hoursDescription&&(description+=", "),description+=hoursDescription}return description},ExpressionDescriptor2.prototype.getSecondsDescription=function(){var _this=this,description=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(s){return s},function(s){return stringUtilities_1.StringUtilities.format(_this.i18n.everyX0Seconds(s),s)},function(s){return _this.i18n.secondsX0ThroughX1PastTheMinute()},function(s){return s=="0"?"":parseInt(s)<20?_this.i18n.atX0SecondsPastTheMinute(s):_this.i18n.atX0SecondsPastTheMinuteGt20()||_this.i18n.atX0SecondsPastTheMinute(s)});return description},ExpressionDescriptor2.prototype.getMinutesDescription=function(){var _this=this,secondsExpression=this.expressionParts[0],hourExpression=this.expressionParts[2],description=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(s){return s},function(s){return stringUtilities_1.StringUtilities.format(_this.i18n.everyX0Minutes(s),s)},function(s){return _this.i18n.minutesX0ThroughX1PastTheHour()},function(s){var _a3,_b;try{return s=="0"&&hourExpression.indexOf("/")==-1&&secondsExpression==""?_this.i18n.everyHour():s=="0"?((_b=(_a3=_this.i18n).onTheHour)===null||_b===void 0?void 0:_b.call(_a3))||_this.i18n.atX0MinutesPastTheHour(s):parseInt(s)<20?_this.i18n.atX0MinutesPastTheHour(s):_this.i18n.atX0MinutesPastTheHourGt20()||_this.i18n.atX0MinutesPastTheHour(s)}catch{return _this.i18n.atX0MinutesPastTheHour(s)}});return description},ExpressionDescriptor2.prototype.getHoursDescription=function(){var _this=this,expression=this.expressionParts[2],hourIndex=0,rangeEndValues=[];expression.split("/")[0].split(",").forEach(function(range){var rangeParts=range.split("-");rangeParts.length===2&&rangeEndValues.push({value:rangeParts[1],index:hourIndex+1}),hourIndex+=rangeParts.length});var evaluationIndex=0,description=this.getSegmentDescription(expression,this.i18n.everyHour(),function(s){var match=rangeEndValues.find(function(r){return r.value===s&&r.index===evaluationIndex}),isRangeEndWithNonZeroMinute=match&&_this.expressionParts[1]!=="0";return evaluationIndex++,isRangeEndWithNonZeroMinute?_this.formatTime(s,"59",""):_this.formatTime(s,"0","")},function(s){return stringUtilities_1.StringUtilities.format(_this.i18n.everyX0Hours(s),s)},function(s){return _this.i18n.betweenX0AndX1()},function(s){return _this.i18n.atX0()});return description},ExpressionDescriptor2.prototype.getDayOfWeekDescription=function(){var _this=this,daysOfWeekNames=this.i18n.daysOfTheWeek(),description=null;return this.expressionParts[5]=="*"?description="":description=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(s,form){var exp=s;s.indexOf("#")>-1?exp=s.substring(0,s.indexOf("#")):s.indexOf("L")>-1&&(exp=exp.replace("L",""));var parsedExp=parseInt(exp),description2=_this.i18n.daysOfTheWeekInCase?_this.i18n.daysOfTheWeekInCase(form)[parsedExp]:daysOfWeekNames[parsedExp];if(s.indexOf("#")>-1){var dayOfWeekOfMonthDescription=null,dayOfWeekOfMonthNumber=s.substring(s.indexOf("#")+1),dayOfWeekNumber=s.substring(0,s.indexOf("#"));switch(dayOfWeekOfMonthNumber){case"1":dayOfWeekOfMonthDescription=_this.i18n.first(dayOfWeekNumber);break;case"2":dayOfWeekOfMonthDescription=_this.i18n.second(dayOfWeekNumber);break;case"3":dayOfWeekOfMonthDescription=_this.i18n.third(dayOfWeekNumber);break;case"4":dayOfWeekOfMonthDescription=_this.i18n.fourth(dayOfWeekNumber);break;case"5":dayOfWeekOfMonthDescription=_this.i18n.fifth(dayOfWeekNumber);break}description2=dayOfWeekOfMonthDescription+" "+description2}return description2},function(s){return parseInt(s)==1?"":stringUtilities_1.StringUtilities.format(_this.i18n.commaEveryX0DaysOfTheWeek(s),s)},function(s){var beginFrom=s.substring(0,s.indexOf("-")),domSpecified=_this.expressionParts[3]!="*";return domSpecified?_this.i18n.commaAndX0ThroughX1(beginFrom):_this.i18n.commaX0ThroughX1(beginFrom)},function(s){var format=null;if(s.indexOf("#")>-1){var dayOfWeekOfMonthNumber=s.substring(s.indexOf("#")+1),dayOfWeek=s.substring(0,s.indexOf("#"));format=_this.i18n.commaOnThe(dayOfWeekOfMonthNumber,dayOfWeek).trim()+_this.i18n.spaceX0OfTheMonth()}else if(s.indexOf("L")>-1)format=_this.i18n.commaOnTheLastX0OfTheMonth(s.replace("L",""));else{var domSpecified=_this.expressionParts[3]!="*";domSpecified?_this.options.logicalAndDayFields?format=_this.i18n.commaOnlyOnX0(s):format=_this.i18n.commaAndOnX0():format=_this.i18n.commaOnlyOnX0(s)}return format}),description},ExpressionDescriptor2.prototype.getMonthDescription=function(){var _this=this,monthNames=this.i18n.monthsOfTheYear(),description=this.getSegmentDescription(this.expressionParts[4],"",function(s,form){return form&&_this.i18n.monthsOfTheYearInCase?_this.i18n.monthsOfTheYearInCase(form)[parseInt(s)-1]:monthNames[parseInt(s)-1]},function(s){return parseInt(s)==1?"":stringUtilities_1.StringUtilities.format(_this.i18n.commaEveryX0Months(s),s)},function(s){return _this.i18n.commaMonthX0ThroughMonthX1()||_this.i18n.commaX0ThroughX1()},function(s){return _this.i18n.commaOnlyInMonthX0?_this.i18n.commaOnlyInMonthX0():_this.i18n.commaOnlyInX0()});return description},ExpressionDescriptor2.prototype.getDayOfMonthDescription=function(){var _this=this,description=null,expression=this.expressionParts[3];switch(expression){case"L":description=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":description=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var weekDayNumberMatches=expression.match(/(\d{1,2}W)|(W\d{1,2})/);if(weekDayNumberMatches){var dayNumber=parseInt(weekDayNumberMatches[0].replace("W","")),dayString=dayNumber==1?this.i18n.firstWeekday():stringUtilities_1.StringUtilities.format(this.i18n.weekdayNearestDayX0(),dayNumber.toString());description=stringUtilities_1.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),dayString);break}else{var lastDayOffSetMatches=expression.match(/L-(\d{1,2})/);if(lastDayOffSetMatches){var offSetDays=lastDayOffSetMatches[1];description=stringUtilities_1.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(offSetDays),offSetDays);break}else{if(expression=="*"&&this.expressionParts[5]!="*")return"";description=this.getSegmentDescription(expression,this.i18n.commaEveryDay(),function(s){return s=="L"?_this.i18n.lastDay():_this.i18n.dayX0?stringUtilities_1.StringUtilities.format(_this.i18n.dayX0(),s):s},function(s){return s=="1"?_this.i18n.commaEveryDay():_this.i18n.commaEveryX0Days(s)},function(s){return _this.i18n.commaBetweenDayX0AndX1OfTheMonth(s)},function(s){return _this.i18n.commaOnDayX0OfTheMonth(s)})}break}}return description},ExpressionDescriptor2.prototype.getYearDescription=function(){var _this=this,description=this.getSegmentDescription(this.expressionParts[6],"",function(s){return/^\d+$/.test(s)?new Date(parseInt(s),1).getFullYear().toString():s},function(s){return stringUtilities_1.StringUtilities.format(_this.i18n.commaEveryX0Years(s),s)},function(s){return _this.i18n.commaYearX0ThroughYearX1()||_this.i18n.commaX0ThroughX1()},function(s){return _this.i18n.commaOnlyInYearX0?_this.i18n.commaOnlyInYearX0():_this.i18n.commaOnlyInX0()});return description},ExpressionDescriptor2.prototype.getSegmentDescription=function(expression,allDescription,getSingleItemDescription,getIncrementDescriptionFormat,getRangeDescriptionFormat,getDescriptionFormat){var description=null,doesExpressionContainIncrement=expression.indexOf("/")>-1,doesExpressionContainRange=expression.indexOf("-")>-1,doesExpressionContainMultipleValues=expression.indexOf(",")>-1;if(!expression)description="";else if(expression==="*")description=allDescription;else if(!doesExpressionContainIncrement&&!doesExpressionContainRange&&!doesExpressionContainMultipleValues)description=stringUtilities_1.StringUtilities.format(getDescriptionFormat(expression),getSingleItemDescription(expression));else if(doesExpressionContainMultipleValues){for(var segments=expression.split(","),descriptionContent="",conjunction=this.i18n.spaceAnd(),i=0;i<segments.length;i++)if(i>0&&segments.length>2&&(descriptionContent+=",",i<segments.length-1&&(descriptionContent+=" ")),i>0&&segments.length>1&&(i==segments.length-1||segments.length==2)&&(descriptionContent+=conjunction==","&&segments.length>2?" ":"".concat(conjunction," ")),segments[i].indexOf("/")>-1||segments[i].indexOf("-")>-1){var isSegmentRangeWithoutIncrement=segments[i].indexOf("-")>-1&&segments[i].indexOf("/")==-1,currentDescriptionContent=this.getSegmentDescription(segments[i],allDescription,getSingleItemDescription,getIncrementDescriptionFormat,isSegmentRangeWithoutIncrement?this.i18n.commaX0ThroughX1:getRangeDescriptionFormat,getDescriptionFormat);isSegmentRangeWithoutIncrement&&(currentDescriptionContent=currentDescriptionContent.replace(", ","")),descriptionContent+=currentDescriptionContent}else if(!doesExpressionContainIncrement)descriptionContent+=getSingleItemDescription(segments[i]);else{var segmentDescription=this.getSegmentDescription(segments[i],allDescription,getSingleItemDescription,getIncrementDescriptionFormat,getRangeDescriptionFormat,getDescriptionFormat);segmentDescription&&segmentDescription.startsWith(", ")&&(segmentDescription=segmentDescription.substring(2)),descriptionContent+=segmentDescription}doesExpressionContainIncrement?description=descriptionContent:description=stringUtilities_1.StringUtilities.format(getDescriptionFormat(expression),descriptionContent)}else if(doesExpressionContainIncrement){var segments=expression.split("/");if(description=stringUtilities_1.StringUtilities.format(getIncrementDescriptionFormat(segments[1]),segments[1]),segments[0].indexOf("-")>-1){var rangeSegmentDescription=this.generateRangeSegmentDescription(segments[0],getRangeDescriptionFormat,getSingleItemDescription);rangeSegmentDescription.indexOf(", ")!=0&&(description+=", "),description+=rangeSegmentDescription}else if(segments[0].indexOf("*")==-1){var rangeItemDescription=stringUtilities_1.StringUtilities.format(getDescriptionFormat(segments[0]),getSingleItemDescription(segments[0]));rangeItemDescription=rangeItemDescription.replace(", ",""),description+=stringUtilities_1.StringUtilities.format(this.i18n.commaStartingX0(),rangeItemDescription)}}else doesExpressionContainRange&&(description=this.generateRangeSegmentDescription(expression,getRangeDescriptionFormat,getSingleItemDescription));return description},ExpressionDescriptor2.prototype.generateRangeSegmentDescription=function(rangeExpression,getRangeDescriptionFormat,getSingleItemDescription){var description="",rangeSegments=rangeExpression.split("-"),rangeSegment1Description=getSingleItemDescription(rangeSegments[0],1),rangeSegment2Description=getSingleItemDescription(rangeSegments[1],2),rangeDescriptionFormat=getRangeDescriptionFormat(rangeExpression);return description+=stringUtilities_1.StringUtilities.format(rangeDescriptionFormat,rangeSegment1Description,rangeSegment2Description),description},ExpressionDescriptor2.prototype.formatTime=function(hourExpression,minuteExpression,secondExpression){var hourOffset=0,minuteOffset=0,hour=parseInt(hourExpression)+hourOffset,minute=parseInt(minuteExpression)+minuteOffset;minute>=60?(minute-=60,hour+=1):minute<0&&(minute+=60,hour-=1),hour>=24?hour=hour-24:hour<0&&(hour=24+hour);var period="",setPeriodBeforeTime=!1;this.options.use24HourTimeFormat||(setPeriodBeforeTime=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),period=setPeriodBeforeTime?"".concat(this.getPeriod(hour)," "):" ".concat(this.getPeriod(hour)),hour>12&&(hour-=12),hour===0&&(hour=12));var second="";secondExpression&&(second=":".concat(("00"+secondExpression).substring(secondExpression.length)));var hourStr=hour.toString(),paddedHour=("00"+hourStr).substring(hourStr.length),minuteStr=minute.toString(),paddedMinute=("00"+minuteStr).substring(minuteStr.length),displayHour=this.options.trimHoursLeadingZero?hourStr:paddedHour;return"".concat(setPeriodBeforeTime?period:"").concat(displayHour,":").concat(paddedMinute).concat(second).concat(setPeriodBeforeTime?"":period)},ExpressionDescriptor2.prototype.transformVerbosity=function(description,useVerboseFormat){if(!useVerboseFormat&&(description=description.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),description=description.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),description=description.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),description=description.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var _i=0,_a3=Object.entries(this.i18n.conciseVerbosityReplacements());_i<_a3.length;_i++){var _b=_a3[_i],key=_b[0],value=_b[1];description=description.replace(new RegExp(key,"g"),value)}return description},ExpressionDescriptor2.prototype.getPeriod=function(hour){return hour>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},ExpressionDescriptor2.locales={},ExpressionDescriptor2})();exports2.ExpressionDescriptor=ExpressionDescriptor},747(__unused_webpack_module,exports2,__webpack_require__2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.enLocaleLoader=void 0;var en_1=__webpack_require__2(486),enLocaleLoader=(function(){function enLocaleLoader2(){}return enLocaleLoader2.prototype.load=function(availableLocales){availableLocales.en=new en_1.en},enLocaleLoader2})();exports2.enLocaleLoader=enLocaleLoader},486(__unused_webpack_module,exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.en=void 0;var en=(function(){function en2(){}return en2.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},en2.prototype.atX0MinutesPastTheHourGt20=function(){return null},en2.prototype.commaMonthX0ThroughMonthX1=function(){return null},en2.prototype.commaYearX0ThroughYearX1=function(){return null},en2.prototype.use24HourTimeFormatByDefault=function(){return!1},en2.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},en2.prototype.everyMinute=function(){return"every minute"},en2.prototype.everyHour=function(){return"every hour"},en2.prototype.atSpace=function(){return"At "},en2.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},en2.prototype.at=function(){return"At"},en2.prototype.spaceAnd=function(){return" and"},en2.prototype.everySecond=function(){return"every second"},en2.prototype.everyX0Seconds=function(){return"every %s seconds"},en2.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},en2.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},en2.prototype.everyX0Minutes=function(){return"every %s minutes"},en2.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},en2.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},en2.prototype.everyX0Hours=function(){return"every %s hours"},en2.prototype.betweenX0AndX1=function(){return"between %s and %s"},en2.prototype.atX0=function(){return"at %s"},en2.prototype.commaEveryDay=function(){return", every day"},en2.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},en2.prototype.commaX0ThroughX1=function(){return", %s through %s"},en2.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},en2.prototype.first=function(){return"first"},en2.prototype.second=function(){return"second"},en2.prototype.third=function(){return"third"},en2.prototype.fourth=function(){return"fourth"},en2.prototype.fifth=function(){return"fifth"},en2.prototype.commaOnThe=function(){return", on the "},en2.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},en2.prototype.lastDay=function(){return"the last day"},en2.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},en2.prototype.commaOnlyOnX0=function(){return", only on %s"},en2.prototype.commaAndOnX0=function(){return", and on %s"},en2.prototype.commaEveryX0Months=function(){return", every %s months"},en2.prototype.commaOnlyInX0=function(){return", only in %s"},en2.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},en2.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},en2.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},en2.prototype.firstWeekday=function(){return"first weekday"},en2.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},en2.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},en2.prototype.commaEveryX0Days=function(){return", every %s days in a month"},en2.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},en2.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},en2.prototype.commaEveryHour=function(){return", every hour"},en2.prototype.commaEveryX0Years=function(){return", every %s years"},en2.prototype.commaStartingX0=function(){return", starting %s"},en2.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},en2.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},en2.prototype.atReboot=function(){return"Run once, at startup"},en2.prototype.onTheHour=function(){return"on the hour"},en2})();exports2.en=en},515(__unused_webpack_module,exports2){Object.defineProperty(exports2,"__esModule",{value:!0});function assert2(value,message){if(!value)throw new Error(message)}var RangeValidator=(function(){function RangeValidator2(){}return RangeValidator2.secondRange=function(parse4){for(var parsed=parse4.split(","),i=0;i<parsed.length;i++)if(!isNaN(parseInt(parsed[i],10))){var second=parseInt(parsed[i],10);assert2(second>=0&&second<=59,"seconds part must be >= 0 and <= 59")}},RangeValidator2.minuteRange=function(parse4){for(var parsed=parse4.split(","),i=0;i<parsed.length;i++)if(!isNaN(parseInt(parsed[i],10))){var minute=parseInt(parsed[i],10);assert2(minute>=0&&minute<=59,"minutes part must be >= 0 and <= 59")}},RangeValidator2.hourRange=function(parse4){for(var parsed=parse4.split(","),i=0;i<parsed.length;i++)if(!isNaN(parseInt(parsed[i],10))){var hour=parseInt(parsed[i],10);assert2(hour>=0&&hour<=23,"hours part must be >= 0 and <= 23")}},RangeValidator2.dayOfMonthRange=function(parse4){for(var parsed=parse4.split(","),i=0;i<parsed.length;i++)if(!isNaN(parseInt(parsed[i],10))){var dayOfMonth=parseInt(parsed[i],10);assert2(dayOfMonth>=1&&dayOfMonth<=31,"DOM part must be >= 1 and <= 31")}},RangeValidator2.monthRange=function(parse4,monthStartIndexZero){for(var parsed=parse4.split(","),i=0;i<parsed.length;i++)if(!isNaN(parseInt(parsed[i],10))){var month=parseInt(parsed[i],10);assert2(month>=1&&month<=12,monthStartIndexZero?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},RangeValidator2.dayOfWeekRange=function(parse4,dayOfWeekStartIndexZero){for(var parsed=parse4.split(","),i=0;i<parsed.length;i++)if(!isNaN(parseInt(parsed[i],10))){var dayOfWeek=parseInt(parsed[i],10);assert2(dayOfWeek>=0&&dayOfWeek<=6,dayOfWeekStartIndexZero?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},RangeValidator2})();exports2.default=RangeValidator},823(__unused_webpack_module,exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.StringUtilities=void 0;var StringUtilities=(function(){function StringUtilities2(){}return StringUtilities2.format=function(template){for(var values=[],_i=1;_i<arguments.length;_i++)values[_i-1]=arguments[_i];return template.replace(/%s/g,function(substring){for(var args=[],_i2=1;_i2<arguments.length;_i2++)args[_i2-1]=arguments[_i2];return values.shift()})},StringUtilities2.containsAny=function(text,searchStrings){return searchStrings.some(function(c){return text.indexOf(c)>-1})},StringUtilities2})();exports2.StringUtilities=StringUtilities}},__webpack_module_cache__={};function __webpack_require__(moduleId){var cachedModule=__webpack_module_cache__[moduleId];if(cachedModule!==void 0)return cachedModule.exports;var module2=__webpack_module_cache__[moduleId]={exports:{}};return __webpack_modules__[moduleId](module2,module2.exports,__webpack_require__),module2.exports}var __webpack_exports__={};return(()=>{var exports2=__webpack_exports__;Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.toString=void 0;var expressionDescriptor_1=__webpack_require__(333),enLocaleLoader_1=__webpack_require__(747);expressionDescriptor_1.ExpressionDescriptor.initialize(new enLocaleLoader_1.enLocaleLoader),exports2.default=expressionDescriptor_1.ExpressionDescriptor;var cronstrue_toString=expressionDescriptor_1.ExpressionDescriptor.toString;exports2.toString=cronstrue_toString})(),__webpack_exports__})())}});var CommanderError=class extends Error{constructor(exitCode,code,message){super(message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=code,this.exitCode=exitCode,this.nestedError=void 0}},InvalidArgumentError=class extends CommanderError{constructor(message){super(1,"commander.invalidArgument",message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Argument=class{constructor(name,description){switch(this.description=description||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,name[0]){case"<":this.required=!0,this._name=name.slice(1,-1);break;case"[":this.required=!1,this._name=name.slice(1,-1);break;default:this.required=!0,this._name=name;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}argParser(fn){return this.parseArg=fn,this}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function humanReadableArgName(arg){let nameOutput=arg.name()+(arg.variadic===!0?"...":"");return arg.required?"<"+nameOutput+">":"["+nameOutput+"]"}import{EventEmitter}from"events";import childProcess from"child_process";import path from"path";import fs from"fs";import process2 from"process";import{stripVTControlCharacters as stripVTControlCharacters2}from"util";import{stripVTControlCharacters}from"util";var Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(contextOptions){this.helpWidth=this.helpWidth??contextOptions.helpWidth??80}visibleCommands(cmd){let visibleCommands=cmd.commands.filter(cmd2=>!cmd2._hidden),helpCommand=cmd._getHelpCommand();return helpCommand&&!helpCommand._hidden&&visibleCommands.push(helpCommand),this.sortSubcommands&&visibleCommands.sort((a,b2)=>a.name().localeCompare(b2.name())),visibleCommands}compareOptions(a,b2){let getSortKey=option=>option.short?option.short.replace(/^-/,""):option.long.replace(/^--/,"");return getSortKey(a).localeCompare(getSortKey(b2))}visibleOptions(cmd){let visibleOptions=cmd.options.filter(option=>!option.hidden),helpOption=cmd._getHelpOption();if(helpOption&&!helpOption.hidden){let removeShort=helpOption.short&&cmd._findOption(helpOption.short),removeLong=helpOption.long&&cmd._findOption(helpOption.long);!removeShort&&!removeLong?visibleOptions.push(helpOption):helpOption.long&&!removeLong?visibleOptions.push(cmd.createOption(helpOption.long,helpOption.description)):helpOption.short&&!removeShort&&visibleOptions.push(cmd.createOption(helpOption.short,helpOption.description))}return this.sortOptions&&visibleOptions.sort(this.compareOptions),visibleOptions}visibleGlobalOptions(cmd){if(!this.showGlobalOptions)return[];let globalOptions=[];for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent){let visibleOptions=ancestorCmd.options.filter(option=>!option.hidden);globalOptions.push(...visibleOptions)}return this.sortOptions&&globalOptions.sort(this.compareOptions),globalOptions}visibleArguments(cmd){return cmd._argsDescription&&cmd.registeredArguments.forEach(argument=>{argument.description=argument.description||cmd._argsDescription[argument.name()]||""}),cmd.registeredArguments.find(argument=>argument.description)?cmd.registeredArguments:[]}subcommandTerm(cmd){let args=cmd.registeredArguments.map(arg=>humanReadableArgName(arg)).join(" ");return cmd._name+(cmd._aliases[0]?"|"+cmd._aliases[0]:"")+(cmd.options.length?" [options]":"")+(args?" "+args:"")}optionTerm(option){return option.flags}argumentTerm(argument){return argument.name()}longestSubcommandTermLength(cmd,helper){return helper.visibleCommands(cmd).reduce((max,command)=>Math.max(max,this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command)))),0)}longestOptionTermLength(cmd,helper){return helper.visibleOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestGlobalOptionTermLength(cmd,helper){return helper.visibleGlobalOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestArgumentTermLength(cmd,helper){return helper.visibleArguments(cmd).reduce((max,argument)=>Math.max(max,this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument)))),0)}commandUsage(cmd){let cmdName=cmd._name;cmd._aliases[0]&&(cmdName=cmdName+"|"+cmd._aliases[0]);let ancestorCmdNames="";for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent)ancestorCmdNames=ancestorCmd.name()+" "+ancestorCmdNames;return ancestorCmdNames+cmdName+" "+cmd.usage()}commandDescription(cmd){return cmd.description()}subcommandDescription(cmd){return cmd.summary()||cmd.description()}optionDescription(option){let extraInfo=[];if(option.argChoices&&extraInfo.push(`choices: ${option.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),option.defaultValue!==void 0&&(option.required||option.optional||option.isBoolean()&&typeof option.defaultValue=="boolean")&&extraInfo.push(`default: ${option.defaultValueDescription||JSON.stringify(option.defaultValue)}`),option.presetArg!==void 0&&option.optional&&extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`),option.envVar!==void 0&&extraInfo.push(`env: ${option.envVar}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return option.description?`${option.description} ${extraDescription}`:extraDescription}return option.description}argumentDescription(argument){let extraInfo=[];if(argument.argChoices&&extraInfo.push(`choices: ${argument.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),argument.defaultValue!==void 0&&extraInfo.push(`default: ${argument.defaultValueDescription||JSON.stringify(argument.defaultValue)}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return argument.description?`${argument.description} ${extraDescription}`:extraDescription}return argument.description}formatItemList(heading,items,helper){return items.length===0?[]:[helper.styleTitle(heading),...items,""]}groupItems(unsortedItems,visibleItems,getGroup){let result=new Map;return unsortedItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[])}),visibleItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[]),result.get(group).push(item)}),result}formatHelp(cmd,helper){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80;function callFormatItem(term,description){return helper.formatItem(term,termWidth,description,helper)}let output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));if(output=output.concat(this.formatItemList("Arguments:",argumentList,helper)),this.groupItems(cmd.options,helper.visibleOptions(cmd),option=>option.helpGroupHeading??"Options:").forEach((options,group)=>{let optionList=options.map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList(group,optionList,helper))}),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList("Global Options:",globalOptionList,helper))}return this.groupItems(cmd.commands,helper.visibleCommands(cmd),sub=>sub.helpGroup()||"Commands:").forEach((commands,group)=>{let commandList=commands.map(sub=>callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)),helper.styleSubcommandDescription(helper.subcommandDescription(sub))));output=output.concat(this.formatItemList(group,commandList,helper))}),output.join(`
3
+ `)}displayWidth(str){return stripVTControlCharacters(str).length}styleTitle(str){return str}styleUsage(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word==="[command]"?this.styleSubcommandText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleCommandText(word)).join(" ")}styleCommandDescription(str){return this.styleDescriptionText(str)}styleOptionDescription(str){return this.styleDescriptionText(str)}styleSubcommandDescription(str){return this.styleDescriptionText(str)}styleArgumentDescription(str){return this.styleDescriptionText(str)}styleDescriptionText(str){return str}styleOptionTerm(str){return this.styleOptionText(str)}styleSubcommandTerm(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleSubcommandText(word)).join(" ")}styleArgumentTerm(str){return this.styleArgumentText(str)}styleOptionText(str){return str}styleArgumentText(str){return str}styleSubcommandText(str){return str}styleCommandText(str){return str}padWidth(cmd,helper){return Math.max(helper.longestOptionTermLength(cmd,helper),helper.longestGlobalOptionTermLength(cmd,helper),helper.longestSubcommandTermLength(cmd,helper),helper.longestArgumentTermLength(cmd,helper))}preformatted(str){return/\n[^\S\r\n]/.test(str)}formatItem(term,termWidth,description,helper){let itemIndentStr=" ".repeat(2);if(!description)return itemIndentStr+term;let paddedTerm=term.padEnd(termWidth+term.length-helper.displayWidth(term)),spacerWidth=2,remainingWidth=(this.helpWidth??80)-termWidth-spacerWidth-2,formattedDescription;return remainingWidth<this.minWidthToWrap||helper.preformatted(description)?formattedDescription=description:formattedDescription=helper.boxWrap(description,remainingWidth).replace(/\n/g,`
4
+ `+" ".repeat(termWidth+spacerWidth)),itemIndentStr+paddedTerm+" ".repeat(spacerWidth)+formattedDescription.replace(/\n/g,`
5
+ ${itemIndentStr}`)}boxWrap(str,width){if(width<this.minWidthToWrap)return str;let rawLines=str.split(/\r\n|\n/),chunkPattern=/[\s]*[^\s]+/g,wrappedLines=[];return rawLines.forEach(line=>{let chunks=line.match(chunkPattern);if(chunks===null){wrappedLines.push("");return}let sumChunks=[chunks.shift()],sumWidth=this.displayWidth(sumChunks[0]);chunks.forEach(chunk=>{let visibleWidth=this.displayWidth(chunk);if(sumWidth+visibleWidth<=width){sumChunks.push(chunk),sumWidth+=visibleWidth;return}wrappedLines.push(sumChunks.join(""));let nextChunk=chunk.trimStart();sumChunks=[nextChunk],sumWidth=this.displayWidth(nextChunk)}),wrappedLines.push(sumChunks.join(""))}),wrappedLines.join(`
6
+ `)}};var Option=class{constructor(flags,description){this.flags=flags,this.description=description||"",this.required=flags.includes("<"),this.optional=flags.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(flags),this.mandatory=!1;let optionFlags=splitOptionFlags(flags);this.short=optionFlags.shortFlag,this.long=optionFlags.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}preset(arg){return this.presetArg=arg,this}conflicts(names){return this.conflictsWith=this.conflictsWith.concat(names),this}implies(impliedOptionValues){let newImplied=impliedOptionValues;return typeof impliedOptionValues=="string"&&(newImplied={[impliedOptionValues]:!0}),this.implied=Object.assign(this.implied||{},newImplied),this}env(name){return this.envVar=name,this}argParser(fn){return this.parseArg=fn,this}makeOptionMandatory(mandatory=!0){return this.mandatory=!!mandatory,this}hideHelp(hide=!0){return this.hidden=!!hide,this}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?camelcase(this.name().replace(/^no-/,"")):camelcase(this.name())}helpGroup(heading){return this.helpGroupHeading=heading,this}is(arg){return this.short===arg||this.long===arg}isBoolean(){return!this.required&&!this.optional&&!this.negate}},DualOptions=class{constructor(options){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,options.forEach(option=>{option.negate?this.negativeOptions.set(option.attributeName(),option):this.positiveOptions.set(option.attributeName(),option)}),this.negativeOptions.forEach((value,key)=>{this.positiveOptions.has(key)&&this.dualOptions.add(key)})}valueFromOption(value,option){let optionKey=option.attributeName();if(!this.dualOptions.has(optionKey))return!0;let preset=this.negativeOptions.get(optionKey).presetArg,negativeValue=preset!==void 0?preset:!1;return option.negate===(negativeValue===value)}};function camelcase(str){return str.split("-").reduce((str2,word)=>str2+word[0].toUpperCase()+word.slice(1))}function splitOptionFlags(flags){let shortFlag,longFlag,shortFlagExp=/^-[^-]$/,longFlagExp=/^--[^-]/,flagParts=flags.split(/[ |,]+/).concat("guard");if(shortFlagExp.test(flagParts[0])&&(shortFlag=flagParts.shift()),longFlagExp.test(flagParts[0])&&(longFlag=flagParts.shift()),!shortFlag&&shortFlagExp.test(flagParts[0])&&(shortFlag=flagParts.shift()),!shortFlag&&longFlagExp.test(flagParts[0])&&(shortFlag=longFlag,longFlag=flagParts.shift()),flagParts[0].startsWith("-")){let unsupportedFlag=flagParts[0],baseError=`option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;throw/^-[^-][^-]/.test(unsupportedFlag)?new Error(`${baseError}
7
+ - a short flag is a single dash and a single character
8
+ - either use a single dash and a single character (for a short flag)
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):shortFlagExp.test(unsupportedFlag)?new Error(`${baseError}
10
+ - too many short flags`):longFlagExp.test(unsupportedFlag)?new Error(`${baseError}
11
+ - too many long flags`):new Error(`${baseError}
12
+ - unrecognised flag format`)}if(shortFlag===void 0&&longFlag===void 0)throw new Error(`option creation failed due to no flags found in '${flags}'.`);return{shortFlag,longFlag}}function editDistance(a,b2){if(Math.abs(a.length-b2.length)>3)return Math.max(a.length,b2.length);let d=[];for(let i=0;i<=a.length;i++)d[i]=[i];for(let j2=0;j2<=b2.length;j2++)d[0][j2]=j2;for(let j2=1;j2<=b2.length;j2++)for(let i=1;i<=a.length;i++){let cost;a[i-1]===b2[j2-1]?cost=0:cost=1,d[i][j2]=Math.min(d[i-1][j2]+1,d[i][j2-1]+1,d[i-1][j2-1]+cost),i>1&&j2>1&&a[i-1]===b2[j2-2]&&a[i-2]===b2[j2-1]&&(d[i][j2]=Math.min(d[i][j2],d[i-2][j2-2]+1))}return d[a.length][b2.length]}function suggestSimilar(word,candidates){if(!candidates||candidates.length===0)return"";candidates=Array.from(new Set(candidates));let searchingOptions=word.startsWith("--");searchingOptions&&(word=word.slice(2),candidates=candidates.map(candidate=>candidate.slice(2)));let similar=[],bestDistance=3,minSimilarity=.4;return candidates.forEach(candidate=>{if(candidate.length<=1)return;let distance=editDistance(word,candidate),length=Math.max(word.length,candidate.length);(length-distance)/length>minSimilarity&&(distance<bestDistance?(bestDistance=distance,similar=[candidate]):distance===bestDistance&&similar.push(candidate))}),similar.sort((a,b2)=>a.localeCompare(b2)),searchingOptions&&(similar=similar.map(candidate=>`--${candidate}`)),similar.length>1?`
13
+ (Did you mean one of ${similar.join(", ")}?)`:similar.length===1?`
14
+ (Did you mean ${similar[0]}?)`:""}var Command=class _Command extends EventEmitter{constructor(name){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=name||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:str=>process2.stdout.write(str),writeErr:str=>process2.stderr.write(str),outputError:(str,write)=>write(str),getOutHelpWidth:()=>process2.stdout.isTTY?process2.stdout.columns:void 0,getErrHelpWidth:()=>process2.stderr.isTTY?process2.stderr.columns:void 0,getOutHasColors:()=>useColor()??(process2.stdout.isTTY&&process2.stdout.hasColors?.()),getErrHasColors:()=>useColor()??(process2.stderr.isTTY&&process2.stderr.hasColors?.()),stripColor:str=>stripVTControlCharacters2(str)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(sourceCommand){return this._outputConfiguration=sourceCommand._outputConfiguration,this._helpOption=sourceCommand._helpOption,this._helpCommand=sourceCommand._helpCommand,this._helpConfiguration=sourceCommand._helpConfiguration,this._exitCallback=sourceCommand._exitCallback,this._storeOptionsAsProperties=sourceCommand._storeOptionsAsProperties,this._combineFlagAndOptionalValue=sourceCommand._combineFlagAndOptionalValue,this._allowExcessArguments=sourceCommand._allowExcessArguments,this._enablePositionalOptions=sourceCommand._enablePositionalOptions,this._showHelpAfterError=sourceCommand._showHelpAfterError,this._showSuggestionAfterError=sourceCommand._showSuggestionAfterError,this}_getCommandAndAncestors(){let result=[];for(let command=this;command;command=command.parent)result.push(command);return result}command(nameAndArgs,actionOptsOrExecDesc,execOpts){let desc=actionOptsOrExecDesc,opts=execOpts;typeof desc=="object"&&desc!==null&&(opts=desc,desc=null),opts=opts||{};let[,name,args]=nameAndArgs.match(/([^ ]+) *(.*)/),cmd=this.createCommand(name);return desc&&(cmd.description(desc),cmd._executableHandler=!0),opts.isDefault&&(this._defaultCommandName=cmd._name),cmd._hidden=!!(opts.noHelp||opts.hidden),cmd._executableFile=opts.executableFile||null,args&&cmd.arguments(args),this._registerCommand(cmd),cmd.parent=this,cmd.copyInheritedSettings(this),desc?this:cmd}createCommand(name){return new _Command(name)}createHelp(){return Object.assign(new Help,this.configureHelp())}configureHelp(configuration){return configuration===void 0?this._helpConfiguration:(this._helpConfiguration=configuration,this)}configureOutput(configuration){return configuration===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...configuration},this)}showHelpAfterError(displayHelp=!0){return typeof displayHelp!="string"&&(displayHelp=!!displayHelp),this._showHelpAfterError=displayHelp,this}showSuggestionAfterError(displaySuggestion=!0){return this._showSuggestionAfterError=!!displaySuggestion,this}addCommand(cmd,opts){if(!cmd._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);return opts=opts||{},opts.isDefault&&(this._defaultCommandName=cmd._name),(opts.noHelp||opts.hidden)&&(cmd._hidden=!0),this._registerCommand(cmd),cmd.parent=this,cmd._checkForBrokenPassThrough(),this}createArgument(name,description){return new Argument(name,description)}argument(name,description,parseArg,defaultValue){let argument=this.createArgument(name,description);return typeof parseArg=="function"?argument.default(defaultValue).argParser(parseArg):argument.default(parseArg),this.addArgument(argument),this}arguments(names){return names.trim().split(/ +/).forEach(detail=>{this.argument(detail)}),this}addArgument(argument){let previousArgument=this.registeredArguments.slice(-1)[0];if(previousArgument?.variadic)throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);if(argument.required&&argument.defaultValue!==void 0&&argument.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);return this.registeredArguments.push(argument),this}helpCommand(enableOrNameAndArgs,description){if(typeof enableOrNameAndArgs=="boolean")return this._addImplicitHelpCommand=enableOrNameAndArgs,enableOrNameAndArgs&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let nameAndArgs=enableOrNameAndArgs??"help [command]",[,helpName,helpArgs]=nameAndArgs.match(/([^ ]+) *(.*)/),helpDescription=description??"display help for command",helpCommand=this.createCommand(helpName);return helpCommand.helpOption(!1),helpArgs&&helpCommand.arguments(helpArgs),helpDescription&&helpCommand.description(helpDescription),this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,(enableOrNameAndArgs||description)&&this._initCommandGroup(helpCommand),this}addHelpCommand(helpCommand,deprecatedDescription){return typeof helpCommand!="object"?(this.helpCommand(helpCommand,deprecatedDescription),this):(this._addImplicitHelpCommand=!0,this._helpCommand=helpCommand,this._initCommandGroup(helpCommand),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(event,listener){let allowedValues=["preSubcommand","preAction","postAction"];if(!allowedValues.includes(event))throw new Error(`Unexpected value for event passed to hook : '${event}'.
16
+ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[event]?this._lifeCycleHooks[event].push(listener):this._lifeCycleHooks[event]=[listener],this}exitOverride(fn){return fn?this._exitCallback=fn:this._exitCallback=err=>{if(err.code!=="commander.executeSubCommandAsync")throw err},this}_exit(exitCode,code,message){this._exitCallback&&this._exitCallback(new CommanderError(exitCode,code,message)),process2.exit(exitCode)}action(fn){let listener=args=>{let expectedArgsCount=this.registeredArguments.length,actionArgs=args.slice(0,expectedArgsCount);return this._storeOptionsAsProperties?actionArgs[expectedArgsCount]=this:actionArgs[expectedArgsCount]=this.opts(),actionArgs.push(this),fn.apply(this,actionArgs)};return this._actionHandler=listener,this}createOption(flags,description){return new Option(flags,description)}_callParseArg(target,value,previous,invalidArgumentMessage){try{return target.parseArg(value,previous)}catch(err){if(err.code==="commander.invalidArgument"){let message=`${invalidArgumentMessage} ${err.message}`;this.error(message,{exitCode:err.exitCode,code:err.code})}throw err}}_registerOption(option){let matchingOption=option.short&&this._findOption(option.short)||option.long&&this._findOption(option.long);if(matchingOption){let matchingFlag=option.long&&this._findOption(option.long)?option.long:option.short;throw new Error(`Cannot add option '${option.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
17
+ - already used by option '${matchingOption.flags}'`)}this._initOptionGroup(option),this.options.push(option)}_registerCommand(command){let knownBy=cmd=>[cmd.name()].concat(cmd.aliases()),alreadyUsed=knownBy(command).find(name=>this._findCommand(name));if(alreadyUsed){let existingCmd=knownBy(this._findCommand(alreadyUsed)).join("|"),newCmd=knownBy(command).join("|");throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`)}this._initCommandGroup(command),this.commands.push(command)}addOption(option){this._registerOption(option);let oname=option.name(),name=option.attributeName();option.defaultValue!==void 0&&this.setOptionValueWithSource(name,option.defaultValue,"default");let handleOptionValue=(val,invalidValueMessage,valueSource)=>{val==null&&option.presetArg!==void 0&&(val=option.presetArg);let oldValue=this.getOptionValue(name);val!==null&&option.parseArg?val=this._callParseArg(option,val,oldValue,invalidValueMessage):val!==null&&option.variadic&&(val=option._collectValue(val,oldValue)),val==null&&(option.negate?val=!1:option.isBoolean()||option.optional?val=!0:val=""),this.setOptionValueWithSource(name,val,valueSource)};return this.on("option:"+oname,val=>{let invalidValueMessage=`error: option '${option.flags}' argument '${val}' is invalid.`;handleOptionValue(val,invalidValueMessage,"cli")}),option.envVar&&this.on("optionEnv:"+oname,val=>{let invalidValueMessage=`error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;handleOptionValue(val,invalidValueMessage,"env")}),this}_optionEx(config2,flags,description,fn,defaultValue){if(typeof flags=="object"&&flags instanceof Option)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let option=this.createOption(flags,description);if(option.makeOptionMandatory(!!config2.mandatory),typeof fn=="function")option.default(defaultValue).argParser(fn);else if(fn instanceof RegExp){let regex=fn;fn=(val,def)=>{let m2=regex.exec(val);return m2?m2[0]:def},option.default(defaultValue).argParser(fn)}else option.default(fn);return this.addOption(option)}option(flags,description,parseArg,defaultValue){return this._optionEx({},flags,description,parseArg,defaultValue)}requiredOption(flags,description,parseArg,defaultValue){return this._optionEx({mandatory:!0},flags,description,parseArg,defaultValue)}combineFlagAndOptionalValue(combine=!0){return this._combineFlagAndOptionalValue=!!combine,this}allowUnknownOption(allowUnknown=!0){return this._allowUnknownOption=!!allowUnknown,this}allowExcessArguments(allowExcess=!0){return this._allowExcessArguments=!!allowExcess,this}enablePositionalOptions(positional=!0){return this._enablePositionalOptions=!!positional,this}passThroughOptions(passThrough=!0){return this._passThroughOptions=!!passThrough,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(storeAsProperties=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!storeAsProperties,this}getOptionValue(key){return this._storeOptionsAsProperties?this[key]:this._optionValues[key]}setOptionValue(key,value){return this.setOptionValueWithSource(key,value,void 0)}setOptionValueWithSource(key,value,source){return this._storeOptionsAsProperties?this[key]=value:this._optionValues[key]=value,this._optionValueSources[key]=source,this}getOptionValueSource(key){return this._optionValueSources[key]}getOptionValueSourceWithGlobals(key){let source;return this._getCommandAndAncestors().forEach(cmd=>{cmd.getOptionValueSource(key)!==void 0&&(source=cmd.getOptionValueSource(key))}),source}_prepareUserArgs(argv2,parseOptions){if(argv2!==void 0&&!Array.isArray(argv2))throw new Error("first parameter to parse must be array or undefined");if(parseOptions=parseOptions||{},argv2===void 0&&parseOptions.from===void 0){process2.versions?.electron&&(parseOptions.from="electron");let execArgv=process2.execArgv??[];(execArgv.includes("-e")||execArgv.includes("--eval")||execArgv.includes("-p")||execArgv.includes("--print"))&&(parseOptions.from="eval")}argv2===void 0&&(argv2=process2.argv),this.rawArgs=argv2.slice();let userArgs;switch(parseOptions.from){case void 0:case"node":this._scriptPath=argv2[1],userArgs=argv2.slice(2);break;case"electron":process2.defaultApp?(this._scriptPath=argv2[1],userArgs=argv2.slice(2)):userArgs=argv2.slice(1);break;case"user":userArgs=argv2.slice(0);break;case"eval":userArgs=argv2.slice(1);break;default:throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",userArgs}parse(argv2,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv2,parseOptions);return this._parseCommand([],userArgs),this}async parseAsync(argv2,parseOptions){this._prepareForParse();let userArgs=this._prepareUserArgs(argv2,parseOptions);return await this._parseCommand([],userArgs),this}_prepareForParse(){this._savedState===null?(this.options.filter(option=>option.negate&&option.defaultValue===void 0&&this.getOptionValue(option.attributeName())===void 0).forEach(option=>{let positiveLongFlag=option.long.replace(/^--no-/,"--");this._findOption(positiveLongFlag)||this.setOptionValueWithSource(option.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
18
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(executableFile,executableDir,subcommandName){if(fs.existsSync(executableFile))return;let executableDirMessage=executableDir?`searched for local subcommand relative to directory '${executableDir}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",executableMissing=`'${executableFile}' does not exist
19
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
+ - ${executableDirMessage}`;throw new Error(executableMissing)}_executeSubCommand(subcommand,args){args=args.slice();let sourceExt=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(baseDir,baseName){let localBin=path.resolve(baseDir,baseName);if(fs.existsSync(localBin))return localBin;if(sourceExt.includes(path.extname(baseName)))return;let foundExt=sourceExt.find(ext=>fs.existsSync(`${localBin}${ext}`));if(foundExt)return`${localBin}${foundExt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let executableFile=subcommand._executableFile||`${this._name}-${subcommand._name}`,executableDir=this._executableDir||"";if(this._scriptPath){let resolvedScriptPath;try{resolvedScriptPath=fs.realpathSync(this._scriptPath)}catch{resolvedScriptPath=this._scriptPath}executableDir=path.resolve(path.dirname(resolvedScriptPath),executableDir)}if(executableDir){let localFile=findFile(executableDir,executableFile);if(!localFile&&!subcommand._executableFile&&this._scriptPath){let legacyName=path.basename(this._scriptPath,path.extname(this._scriptPath));legacyName!==this._name&&(localFile=findFile(executableDir,`${legacyName}-${subcommand._name}`))}executableFile=localFile||executableFile}let launchWithNode=sourceExt.includes(path.extname(executableFile)),proc;process2.platform!=="win32"?launchWithNode?(args.unshift(executableFile),args=incrementNodeInspectorPort(process2.execArgv).concat(args),proc=childProcess.spawn(process2.argv[0],args,{stdio:"inherit"})):proc=childProcess.spawn(executableFile,args,{stdio:"inherit"}):(this._checkForMissingExecutable(executableFile,executableDir,subcommand._name),args.unshift(executableFile),args=incrementNodeInspectorPort(process2.execArgv).concat(args),proc=childProcess.spawn(process2.execPath,args,{stdio:"inherit"})),proc.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(signal=>{process2.on(signal,()=>{proc.killed===!1&&proc.exitCode===null&&proc.kill(signal)})});let exitCallback=this._exitCallback;proc.on("close",code=>{code=code??1,exitCallback?exitCallback(new CommanderError(code,"commander.executeSubCommandAsync","(close)")):process2.exit(code)}),proc.on("error",err=>{if(err.code==="ENOENT")this._checkForMissingExecutable(executableFile,executableDir,subcommand._name);else if(err.code==="EACCES")throw new Error(`'${executableFile}' not executable`);if(!exitCallback)process2.exit(1);else{let wrappedError=new CommanderError(1,"commander.executeSubCommandAsync","(error)");wrappedError.nestedError=err,exitCallback(wrappedError)}}),this.runningCommand=proc}_dispatchSubcommand(commandName,operands,unknown2){let subCommand=this._findCommand(commandName);subCommand||this.help({error:!0}),subCommand._prepareForParse();let promiseChain;return promiseChain=this._chainOrCallSubCommandHook(promiseChain,subCommand,"preSubcommand"),promiseChain=this._chainOrCall(promiseChain,()=>{if(subCommand._executableHandler)this._executeSubCommand(subCommand,operands.concat(unknown2));else return subCommand._parseCommand(operands,unknown2)}),promiseChain}_dispatchHelpCommand(subcommandName){subcommandName||this.help();let subCommand=this._findCommand(subcommandName);return subCommand&&!subCommand._executableHandler&&subCommand.help(),this._dispatchSubcommand(subcommandName,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((arg,i)=>{arg.required&&this.args[i]==null&&this.missingArgument(arg.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let myParseArg=(argument,value,previous)=>{let parsedValue=value;if(value!==null&&argument.parseArg){let invalidValueMessage=`error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;parsedValue=this._callParseArg(argument,value,previous,invalidValueMessage)}return parsedValue};this._checkNumberOfArguments();let processedArgs=[];this.registeredArguments.forEach((declaredArg,index)=>{let value=declaredArg.defaultValue;declaredArg.variadic?index<this.args.length?(value=this.args.slice(index),declaredArg.parseArg&&(value=value.reduce((processed,v2)=>myParseArg(declaredArg,v2,processed),declaredArg.defaultValue))):value===void 0&&(value=[]):index<this.args.length&&(value=this.args[index],declaredArg.parseArg&&(value=myParseArg(declaredArg,value,declaredArg.defaultValue))),processedArgs[index]=value}),this.processedArgs=processedArgs}_chainOrCall(promise2,fn){return promise2?.then&&typeof promise2.then=="function"?promise2.then(()=>fn()):fn()}_chainOrCallHooks(promise2,event){let result=promise2,hooks=[];return this._getCommandAndAncestors().reverse().filter(cmd=>cmd._lifeCycleHooks[event]!==void 0).forEach(hookedCommand=>{hookedCommand._lifeCycleHooks[event].forEach(callback=>{hooks.push({hookedCommand,callback})})}),event==="postAction"&&hooks.reverse(),hooks.forEach(hookDetail=>{result=this._chainOrCall(result,()=>hookDetail.callback(hookDetail.hookedCommand,this))}),result}_chainOrCallSubCommandHook(promise2,subCommand,event){let result=promise2;return this._lifeCycleHooks[event]!==void 0&&this._lifeCycleHooks[event].forEach(hook=>{result=this._chainOrCall(result,()=>hook(this,subCommand))}),result}_parseCommand(operands,unknown2){let parsed=this.parseOptions(unknown2);if(this._parseOptionsEnv(),this._parseOptionsImplied(),operands=operands.concat(parsed.operands),unknown2=parsed.unknown,this.args=operands.concat(unknown2),operands&&this._findCommand(operands[0]))return this._dispatchSubcommand(operands[0],operands.slice(1),unknown2);if(this._getHelpCommand()&&operands[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(operands[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(unknown2),this._dispatchSubcommand(this._defaultCommandName,operands,unknown2);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(parsed.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let checkForUnknownOptions=()=>{parsed.unknown.length>0&&this.unknownOption(parsed.unknown[0])},commandEvent=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions(),this._processArguments();let promiseChain;return promiseChain=this._chainOrCallHooks(promiseChain,"preAction"),promiseChain=this._chainOrCall(promiseChain,()=>this._actionHandler(this.processedArgs)),this.parent&&(promiseChain=this._chainOrCall(promiseChain,()=>{this.parent.emit(commandEvent,operands,unknown2)})),promiseChain=this._chainOrCallHooks(promiseChain,"postAction"),promiseChain}if(this.parent?.listenerCount(commandEvent))checkForUnknownOptions(),this._processArguments(),this.parent.emit(commandEvent,operands,unknown2);else if(operands.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",operands,unknown2);this.listenerCount("command:*")?this.emit("command:*",operands,unknown2):this.commands.length?this.unknownCommand():(checkForUnknownOptions(),this._processArguments())}else this.commands.length?(checkForUnknownOptions(),this.help({error:!0})):(checkForUnknownOptions(),this._processArguments())}_findCommand(name){if(name)return this.commands.find(cmd=>cmd._name===name||cmd._aliases.includes(name))}_findOption(arg){return this.options.find(option=>option.is(arg))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd.options.forEach(anOption=>{anOption.mandatory&&cmd.getOptionValue(anOption.attributeName())===void 0&&cmd.missingMandatoryOptionValue(anOption)})})}_checkForConflictingLocalOptions(){let definedNonDefaultOptions=this.options.filter(option=>{let optionKey=option.attributeName();return this.getOptionValue(optionKey)===void 0?!1:this.getOptionValueSource(optionKey)!=="default"});definedNonDefaultOptions.filter(option=>option.conflictsWith.length>0).forEach(option=>{let conflictingAndDefined=definedNonDefaultOptions.find(defined=>option.conflictsWith.includes(defined.attributeName()));conflictingAndDefined&&this._conflictingOption(option,conflictingAndDefined)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd._checkForConflictingLocalOptions()})}parseOptions(args){let operands=[],unknown2=[],dest=operands;function maybeOption(arg){return arg.length>1&&arg[0]==="-"}let negativeNumberArg=arg=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)?!this._getCommandAndAncestors().some(cmd=>cmd.options.map(opt=>opt.short).some(short=>/^-\d$/.test(short))):!1,activeVariadicOption=null,activeGroup=null,i=0;for(;i<args.length||activeGroup;){let arg=activeGroup??args[i++];if(activeGroup=null,arg==="--"){dest===unknown2&&dest.push(arg),dest.push(...args.slice(i));break}if(activeVariadicOption&&(!maybeOption(arg)||negativeNumberArg(arg))){this.emit(`option:${activeVariadicOption.name()}`,arg);continue}if(activeVariadicOption=null,maybeOption(arg)){let option=this._findOption(arg);if(option){if(option.required){let value=args[i++];value===void 0&&this.optionMissingArgument(option),this.emit(`option:${option.name()}`,value)}else if(option.optional){let value=null;i<args.length&&(!maybeOption(args[i])||negativeNumberArg(args[i]))&&(value=args[i++]),this.emit(`option:${option.name()}`,value)}else this.emit(`option:${option.name()}`);activeVariadicOption=option.variadic?option:null;continue}}if(arg.length>2&&arg[0]==="-"&&arg[1]!=="-"){let option=this._findOption(`-${arg[1]}`);if(option){option.required||option.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${option.name()}`,arg.slice(2)):(this.emit(`option:${option.name()}`),activeGroup=`-${arg.slice(2)}`);continue}}if(/^--[^=]+=/.test(arg)){let index=arg.indexOf("="),option=this._findOption(arg.slice(0,index));if(option&&(option.required||option.optional)){this.emit(`option:${option.name()}`,arg.slice(index+1));continue}}if(dest===operands&&maybeOption(arg)&&!(this.commands.length===0&&negativeNumberArg(arg))&&(dest=unknown2),(this._enablePositionalOptions||this._passThroughOptions)&&operands.length===0&&unknown2.length===0){if(this._findCommand(arg)){operands.push(arg),unknown2.push(...args.slice(i));break}else if(this._getHelpCommand()&&arg===this._getHelpCommand().name()){operands.push(arg,...args.slice(i));break}else if(this._defaultCommandName){unknown2.push(arg,...args.slice(i));break}}if(this._passThroughOptions){dest.push(arg,...args.slice(i));break}dest.push(arg)}return{operands,unknown:unknown2}}opts(){if(this._storeOptionsAsProperties){let result={},len=this.options.length;for(let i=0;i<len;i++){let key=this.options[i].attributeName();result[key]=key===this._versionOptionName?this._version:this[key]}return result}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((combinedOptions,cmd)=>Object.assign(combinedOptions,cmd.opts()),{})}error(message,errorOptions){this._outputConfiguration.outputError(`${message}
22
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
+ `),this.outputHelp({error:!0}));let config2=errorOptions||{},exitCode=config2.exitCode||1,code=config2.code||"commander.error";this._exit(exitCode,code,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process2.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process2.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey));this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},getErrorMessage=option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag){if(this._allowUnknownOption)return;let suggestion="";if(flag.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag,candidateFlags)}let message=`error: unknown option '${flag}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",received=receivedArgs.length,forSubcommand=this.parent?` for '${this.name()}'`:"",details=receivedArgs.join(", "),message=`error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
25
+ `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases){return aliases===void 0?this._aliases:(aliases.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}helpGroup(heading){return heading===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=heading,this)}commandsGroup(heading){return heading===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=heading,this)}optionsGroup(heading){return heading===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=heading,this)}_initOptionGroup(option){this._defaultOptionGroup&&!option.helpGroupHeading&&option.helpGroup(this._defaultOptionGroup)}_initCommandGroup(cmd){this._defaultCommandGroup&&!cmd.helpGroup()&&cmd.helpGroup(this._defaultCommandGroup)}nameFromFilename(filename){return this._name=path.basename(filename,path.extname(filename)),this}executableDir(path2){return path2===void 0?this._executableDir:(this._executableDir=path2,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text=helper.formatHelp(this,helper);return context.hasColors?text:this._outputConfiguration.stripColor(text)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error51=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error51?(baseWrite=str=>this._outputConfiguration.writeErr(str),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=str=>this._outputConfiguration.writeOut(str),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error:error51,write:str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(flags??"-h, --help",description??"display help for command"),(flags||description)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this._initOptionGroup(option),this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process2.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text=="function"?helpStr=text({error:context.error,command:context.command}):helpStr=text,helpStr&&context.write(`${helpStr}
27
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}function useColor(){if(process2.env.NO_COLOR||process2.env.FORCE_COLOR==="0"||process2.env.FORCE_COLOR==="false")return!1;if(process2.env.FORCE_COLOR||process2.env.CLICOLOR_FORCE!==void 0)return!0}var program=new Command;import{appendFileSync as appendFileSync2,mkdirSync as mkdirSync4,readFileSync as readFileSync5,readdirSync as readdirSync2,renameSync as renameSync3,rmSync as rmSync3,statSync as statSync2}from"fs";import{join as join4}from"path";import{mkdirSync,readFileSync as readFileSync2,writeFileSync}from"fs";import{homedir as homedir2}from"os";import{join}from"path";import{readFileSync}from"fs";var PACKAGE="@sr-connect/cli",CLI=`npx ${PACKAGE}`;function manifestVersion(){let url2=new URL("../package.json",import.meta.url),manifest=JSON.parse(readFileSync(url2,"utf8")),record4=typeof manifest=="object"&&manifest!==null?manifest:{};if(record4.name!==PACKAGE||typeof record4.version!="string")throw new Error(`${url2.pathname} is not the manifest of ${PACKAGE}.`);return record4.version}var VERSION=manifestVersion(),USER_AGENT=`${PACKAGE}@${VERSION}`,APP_DIR="sr-connect";var import_picocolors=__toESM(require_picocolors(),1);import{appendFileSync}from"fs";import{homedir}from"os";import{resolve,sep}from"path";var EXIT={OK:0,API_ERROR:1,USAGE:2,UNAUTHENTICATED:3,NOT_FOUND:4,CANCELLED:130},rawMode=!1;function configureRawMode(opts){let value=process.env.SR_CONNECT_CLI_RAW;rawMode=opts.enabled===!0||value!==void 0&&!/^(0|false|no|off|)$/i.test(value.trim())}function isRaw(){return rawMode}var promptsAllowed=!0;function setPromptsAllowed(allowed){promptsAllowed=allowed}var agentMode=!1;function agentEnvOn(){let value=process.env.SR_CONNECT_CLI_AGENT;return value!==void 0&&!/^(0|false|no|off|)$/i.test(value.trim())}function configureAgentMode(opts){agentMode=opts.enabled===!0||agentEnvOn()}function isAgent(){return agentMode}function promptsDeclined(){return!promptsAllowed||agentMode}function supplyHint(opts={}){let pass=opts.pass??"Pass it",env=opts.env===void 0?"":`, set ${opts.env}`,ask=opts.ask??"pick one";return promptsDeclined()?`${pass}${env}, or ${restorePrompts()} and run on a terminal to ${ask}.`:`${pass}${env}, or run on a terminal to ${ask}.`}function restorePrompts(){return agentMode?agentEnvOn()?"unset SR_CONNECT_CLI_AGENT":"drop --agent":process.env.SR_CONNECT_CLI_NO_PROMPTS?"unset SR_CONNECT_CLI_NO_PROMPTS":"drop --no-prompts"}function canPrompt(){return promptsAllowed&&!agentMode&&!!(process.stdin.isTTY&&process.stderr.isTTY)}var copyPath;function generatedOutputName(){return`output-${Math.floor(Date.now()/1e3)}.${rawMode?"json":"txt"}`}function setOutputCopy(target){if(!target){copyPath=void 0;return}let name=typeof target=="string"&&target.trim()!==""?target.trim():void 0,path2=resolve(name??generatedOutputName());try{appendFileSync(path2,"")}catch(err){fail(EXIT.USAGE,"OUTPUT_FILE_ERROR",`--copy-output-to-file ${path2} is not writable: ${err instanceof Error?err.message:String(err)}`)}return copyPath=path2,path2}function outputCopyPath(){return copyPath}function assertOutputCopyValue(argv2,commandNames){for(let[at2,token]of argv2.entries()){if(token!=="--copy-output-to-file")continue;let value=argv2[at2+1];value===void 0||value.startsWith("-")||!commandNames.includes(value)||fail(EXIT.USAGE,"OUTPUT_FILE_ERROR",`--copy-output-to-file took '${value}' as the file name, which is a command group; the file name is optional and the next word is taken as it.`,{hint:`Put the flag after the command, or name the file: --copy-output-to-file ./${value} if that really is the file.`})}}function assertVersionFlagIsRoot(argv2,commandNames){let rest=argv2.slice(2),flag=rest.find(a=>a==="-V"||a==="--version");if(flag===void 0)return;let group=rest.findIndex(a=>!a.startsWith("-")&&commandNames.includes(a));if(group===-1)return;let verb=rest[group+1],command=verb!==void 0&&!verb.startsWith("-")?`${rest[group]} ${verb}`:rest[group];fail(EXIT.USAGE,"USAGE_ERROR",`${flag} prints this CLI's own version and belongs to the root, so it would have sent nothing and exited 0.`,{hint:`Drop it to run '${command}', or use the flag the verb means: --release-version for a release, --package-version for a package.`})}function reportOutputCopy(){if(copyPath===void 0)return;let line=`Output copied to ${copyPath}`;rawMode?console.error(import_picocolors.default.dim(line)):console.log(import_picocolors.default.green(line))}async function flushOutput(){let drain=stream=>new Promise(done=>{if(stream.writableLength===0){done();return}stream.write("",()=>done())});await Promise.all([drain(process.stdout),drain(process.stderr)])}function ignoreBrokenPipe(){for(let stream of[process.stdout,process.stderr])stream.on("error",err=>{throw(err.code==="EPIPE"||err.code==="ERR_STREAM_DESTROYED")&&process.exit(EXIT.OK),err})}function displayPath(path2,home=safeHomedir()){if(process.platform==="win32")return path2;let base=home.endsWith(sep)?home.slice(0,-sep.length):home;return base===""||base===sep?path2:path2===base?"~":path2.startsWith(base+sep)?`~${path2.slice(base.length)}`:path2}function shellQuote(value){return/^[\w.:@/+-]+$/.test(value)?value:`'${value.replaceAll("'","'\\''")}'`}function safeHomedir(){try{return homedir()}catch{return""}}var ANSI=new RegExp("\x1B\\[[0-9;]*m","g");function stripAnsi(text){return text.replaceAll(ANSI,"")}function emit(text){console.log(text),appendCopy(`${text}
28
+ `)}function appendCopy(text){if(copyPath!==void 0)try{appendFileSync(copyPath,stripAnsi(text))}catch(err){let message=err instanceof Error?err.message:String(err);console.error(import_picocolors.default.yellow(`\u26A0 Could not append to ${copyPath}: ${message}`)),copyPath=void 0}}function describeError(err,depth=0){if(!(err instanceof Error))return String(err);let code=err.code,head=typeof code=="string"&&!err.message.includes(code)?`${err.message} (${code})`:err.message;if(depth>=3)return head;let nested=err instanceof AggregateError&&err.errors.length>0?err.errors[0]:err.cause;if(nested==null)return head;let tail=describeError(nested,depth+1);return head===""?tail:`${head}: ${tail}`}var CliError=class extends Error{exitCode;code;hint;status;tone;banner;expected;constructor(exitCode,code,message,opts){super(message),this.exitCode=exitCode,this.code=code,this.hint=opts?.hint,this.status=opts?.status,this.tone=opts?.tone??"error",this.banner=opts?.banner,this.expected=opts?.expected??!1}};function fail(exitCode,code,message,opts){throw new CliError(exitCode,code,message,opts)}function reportError(err){if(rawMode){let envelope={code:err.code,message:err.message};err.status!==void 0&&(envelope.status=err.status),err.hint!==void 0&&(envelope.hint=err.hint),emit(JSON.stringify({error:envelope}))}else if(err.banner?.length)for(let line of err.banner)console.error(import_picocolors.default.red(line));else console.error(err.tone==="ok"?import_picocolors.default.green(`\u2714 ${err.message}`):import_picocolors.default.red(`\u2716 ${err.message}`)),err.hint&&console.error(import_picocolors.default.dim(` ${err.hint}`));return err.exitCode}function isPrimitive(v2){return v2===null||["string","number","boolean"].includes(typeof v2)}function cell(v2){return v2==null?"":isPrimitive(v2)?String(v2):typeof v2=="object"&&"name"in v2&&isPrimitive(v2.name)?String(v2.name):JSON.stringify(v2)}function humanizeKey(key){return key.replaceAll(/([a-z0-9])([A-Z])/g,"$1_$2").replaceAll(/[\s-]+/g,"_").toUpperCase()}function tableRows(columns,rows2){return rows2.map(row=>Object.fromEntries(columns.map(column=>[column,row[column]??null])))}function renderTable(rows2){if(rows2.length===0)return import_picocolors.default.dim("(no results)");let cols=[];for(let row of rows2)for(let key of Object.keys(row))cols.includes(key)||cols.push(key);let headers=cols.map(humanizeKey),widths=cols.map((c,i)=>Math.max(headers[i]?.length??0,...rows2.map(r=>cell(r[c]).length))),line=vals=>vals.map((v2,i)=>v2.padEnd(widths[i]??0)).join(" ").trimEnd();return[import_picocolors.default.bold(line(headers)),...rows2.map(r=>line(cols.map(c=>cell(r[c]))))].join(`
29
+ `)}function isNamedResource(v2){return typeof v2=="object"&&v2!==null&&!Array.isArray(v2)&&"name"in v2&&typeof v2.name=="string"}function detailValue(v2){if(v2!==void 0){if(v2===null)return"";if(isPrimitive(v2))return String(v2);if(isNamedResource(v2))return v2.id!==void 0?`${v2.name} (${v2.id})`:v2.name;if(Array.isArray(v2))return v2.every(isPrimitive)?v2.map(String).join(", "):v2.every(isNamedResource)?v2.map(item=>detailValue(item)??"").join(", "):JSON.stringify(v2)}}var WARNING_GLYPH="\u26A0";function isWarning(line){return line.trimStart().startsWith(WARNING_GLYPH)}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${trimmedNumber(bytes/1024)} KiB`:`${trimmedNumber(bytes/(1024*1024))} MiB`}function trimmedNumber(value){return String(Number(value.toFixed(1)))}function grouped(bytes){return String(bytes).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function sizesAgainstCap(bytes,cap){let actual=formatBytes(bytes),capped=formatBytes(cap);return actual!==capped?{actual,cap:capped}:{actual:`${grouped(bytes)} bytes`,cap:`${capped} (${grouped(cap)} bytes)`}}function warnLine(line){process.stderr.write(`${import_picocolors.default.yellow(line)}
30
+ `)}function noteLine(line){process.stderr.write(`${line}
31
+ `)}function successLine(line){process.stderr.write(`${import_picocolors.default.green(line)}
32
+ `)}function renderDetail(obj){let entries=[];for(let[key,value]of Object.entries(obj)){let rendered=detailValue(value);if(rendered!==void 0){entries.push([humanizeKey(key),rendered]);continue}for(let[childKey,childValue]of Object.entries(value)){let child=detailValue(childValue)??JSON.stringify(childValue);entries.push([`${humanizeKey(key)}_${humanizeKey(childKey)}`,child])}}if(entries.length===0)return import_picocolors.default.dim("(empty)");let width=Math.max(...entries.map(([label])=>label.length)),continuation=" ".repeat(width+2);return entries.map(([label,value])=>{let aligned2=value.split(`
33
+ `).join(`
34
+ ${continuation}`);return`${import_picocolors.default.dim(label.padEnd(width))} ${aligned2}`}).join(`
35
+ `)}function renderHuman(data){if(typeof data=="string")return data;let rows2=data;if(rows2&&typeof rows2=="object"&&!Array.isArray(rows2)){let arrayProps=Object.entries(rows2).filter(([,v2])=>Array.isArray(v2));arrayProps.length===1&&Object.keys(rows2).length===1&&(rows2=arrayProps[0]?.[1])}return Array.isArray(rows2)?renderTable(rows2):data&&typeof data=="object"?renderDetail(data):JSON.stringify(data,null,2)}function ok(data,opts){emit(rawMode?JSON.stringify(data):renderHuman(opts?.human?opts.human(data):data))}function okText(text){emit(text)}function okFile(bytes){process.stdout.write(bytes),appendCopy(bytes)}function okMutation(message,payload,detail){if(rawMode){emit(JSON.stringify(payload));return}emit(detail===void 0?import_picocolors.default.green(`\u2714 ${message}.`):`${import_picocolors.default.green(`\u2714 ${message}:`)}
36
+ ${renderHuman(detail)}`)}var KNOWN_INSTANCES={eu:{label:"EU",url:"https://api.scriptrunnerconnect.com",appUrl:"https://app.eu.scriptrunnerconnect.com"},us:{label:"US",url:"https://api.us.scriptrunnerconnect.com",appUrl:"https://app.us.scriptrunnerconnect.com"}},INSTANCE_KEYS=Object.keys(KNOWN_INSTANCES);function knownInstance(value){return KNOWN_INSTANCES[value]}var INSTANCE_FORMAT=`${INSTANCE_KEYS.join(", ")}, or an API base URL (e.g. https://api.example.com)`;function parseInstance(raw){let value=raw.trim();if(value==="")return{error:`An instance is required: ${INSTANCE_FORMAT}.`};let lower=value.toLowerCase();if(knownInstance(lower))return{instance:lower};let withScheme=/^[a-z][a-z0-9+.-]*:\/\//i.test(value)?value:`https://${value}`,url2;try{url2=new URL(withScheme)}catch{return{error:`'${value}' is not a valid instance \u2014 use ${INSTANCE_FORMAT}.`}}return url2.protocol!=="https:"&&url2.protocol!=="http:"?{error:`An instance URL must be http:// or https:// \u2014 '${value}' is ${url2.protocol}//.`}:url2.hostname===""?{error:`'${value}' has no host \u2014 use ${INSTANCE_FORMAT}.`}:url2.username!==""||url2.password!==""?{error:`An instance URL must not embed a username or password \u2014 got '${value}'.`}:url2.search!==""||url2.hash!==""?{error:`An instance URL must not carry a query string or fragment \u2014 got '${value}'.`}:{instance:`${url2.protocol}//${url2.host}${url2.pathname.replace(/\/+$/,"")}`}}function instanceError(value){return parseInstance(value).error}function normalizeInstance(value){let{instance:instance4,error:error51}=parseInstance(value);if(!instance4)throw new Error(error51??`not an instance: '${value}'`);return instance4}function assertInstance(value,origin){let{instance:instance4,error:error51}=parseInstance(value);return instance4||fail(EXIT.USAGE,"INVALID_INSTANCE",`${origin}: ${error51}`),instance4}function configDir(){return join(userConfigHome(process.platform,process.env,homedir2()),APP_DIR)}function userConfigHome(platform2,env,home){let xdg=env.XDG_CONFIG_HOME;if(xdg&&xdg!=="")return xdg;if(platform2==="win32"){let appData=env.APPDATA;return appData&&appData!==""?appData:join(home,"AppData","Roaming")}return join(home,".config")}function readConfig(){try{return JSON.parse(readFileSync2(join(configDir(),"config.json"),"utf8"))}catch{return{}}}function writeConfig(config2){mkdirSync(configDir(),{recursive:!0}),writeFileSync(join(configDir(),"config.json"),JSON.stringify(config2,null,2)+`
37
+ `)}function baseUrl(instance4){return knownInstance(instance4)?.url??instance4}function instanceLabel(instance4){let known=knownInstance(instance4);return known?`${known.label} (${known.url})`:instance4}var API_KEYS_PATH="/apiKeys";function apiKeysUrl(instance4){let known=knownInstance(instance4);return known?`${known.appUrl}${API_KEYS_PATH}`:void 0}var LOOPBACK=new Set(["localhost","127.0.0.1","[::1]","::1"]);function insecureInstanceWarning(instance4){let url2=baseUrl(instance4);if(!url2.startsWith("http://"))return;let host;try{host=new URL(url2).hostname}catch{return}if(!LOOPBACK.has(host))return`\u26A0 ${url2} is not HTTPS \u2014 your API credentials are sent unencrypted.`}function explicitInstance(flag){let fromEnv=process.env.SR_CONNECT_CLI_INSTANCE;if(flag!==void 0&&flag!=="")return assertInstance(flag,"--instance");if(fromEnv!==void 0&&fromEnv!=="")return assertInstance(fromEnv,"SR_CONNECT_CLI_INSTANCE")}function resolveInstance(flag){let explicit2=explicitInstance(flag);if(explicit2!==void 0)return explicit2;let stored=readConfig().instance;if(stored!==void 0&&stored!=="")return assertInstance(stored,`the instance in ${join(configDir(),"config.json")}`)}var RUN_ID=`${Date.now().toString(36)}-${process.pid}`;import{createHash}from"crypto";import{fstatSync,mkdirSync as mkdirSync2,readFileSync as readFileSync3,readdirSync,renameSync,rmSync,statSync,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir3}from"os";import{join as join2}from"path";var SESSION_KEYS=["team","workspace","environment"],SESSION_RECORD_VERSION=2,SESSION_TTL_MS=720*60*1e3,PRUNE_MS=10080*60*1e3,LOCK_KEEP_MS=3600*1e3,runtimeInstance,enabled=!0;function configureSession(opts){runtimeInstance=opts.instance,enabled=opts.enabled!==!1}function sessionEnabled(){return enabled}function stateHome(){return userStateHome(process.platform,process.env,homedir3())}function userStateHome(platform2,env,home){let explicit2=env.SR_CONNECT_CLI_STATE_HOME;if(explicit2&&explicit2!=="")return explicit2;let xdg=env.XDG_STATE_HOME;if(xdg&&xdg!=="")return xdg;if(platform2==="win32"){let local=env.LOCALAPPDATA;return local&&local!==""?local:join2(home,"AppData","Local")}return join2(home,".local","state")}function sessionsDir(){return join2(stateHome(),APP_DIR,"sessions")}var sanitize=v2=>v2.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,96);function terminalMarker(){let pair=(a,b2)=>a&&a!==""?`${a}:${b2??""}`:void 0;return[process.env.TERM_SESSION_ID,process.env.ITERM_SESSION_ID,pair(process.env.WEZTERM_UNIX_SOCKET,process.env.WEZTERM_PANE),pair(process.env.KITTY_PID,process.env.KITTY_WINDOW_ID),process.env.ALACRITTY_WINDOW_ID,process.env.WT_SESSION,pair(process.env.TMUX,process.env.TMUX_PANE),process.env.STY].find(c=>c&&c!=="")}function sessionKey(){let explicit2=process.env.SR_CONNECT_CLI_SESSION_ID;if(explicit2&&explicit2!=="")return`id-${sanitize(explicit2)}`;let marker=terminalMarker();if(marker)return`mark-${sanitize(marker)}`;for(let fd of[0,1,2])try{let st2=fstatSync(fd);if(st2.isCharacterDevice()&&st2.rdev)return`tty-${st2.rdev}`}catch{}return process.ppid?`ppid-${process.ppid}`:void 0}function instanceSlug(instance4){return createHash("sha256").update(instance4).digest("hex").slice(0,12)}function sessionFile(){let key=sessionKey();if(!key)return;let instance4=effectiveInstance();return join2(sessionsDir(),instance4?`${key}.${instanceSlug(instance4)}.json`:`${key}.json`)}function hasScope(record4){return!!(record4&&SESSION_KEYS.some(k2=>record4[k2]))}function effectiveInstance(){return resolveInstance(runtimeInstance)}function readSession(){if(!enabled)return;let file2=sessionFile();if(!file2)return;let record4;try{record4=JSON.parse(readFileSync3(file2,"utf8"))}catch{return}if(record4.version!==SESSION_RECORD_VERSION){dropSession(file2);return}let age=Date.now()-Date.parse(record4.updatedAt);if(!Number.isFinite(age)||age>SESSION_TTL_MS){dropSession(file2);return}let instance4=effectiveInstance();if(record4.instance&&instance4&&record4.instance!==instance4){warnStrandedLocks(pruneLocks(record4.locks)),dropSession(file2),hasScope(record4)&&(instanceCleared=instanceLabel(record4.instance));return}return record4}function warnStrandedLocks(locks){if(!locks)return;let kept=keptLocksOf(locks);if(kept.length!==0){warnLine(`${kept.length} workspace lock${kept.length===1?"":"s"} taken against another instance cannot be presented from here and are being forgotten.`);for(let lock of kept)warnLine(` ${lockReleaseCommand(lock)}`)}}var instanceCleared;function takeInstanceClear(){let cleared=instanceCleared;return instanceCleared=void 0,cleared}function readRecord(file2,opts={}){let record4;try{record4=JSON.parse(readFileSync3(file2,"utf8"))}catch{return}if(record4.version!==SESSION_RECORD_VERSION)return;let age=Date.now()-Date.parse(record4.updatedAt);if(!Number.isFinite(age)||age>SESSION_TTL_MS)return;if(opts.anyInstance)return record4;let instance4=effectiveInstance();if(!(record4.instance&&instance4&&record4.instance!==instance4))return record4}function prune(dir){try{for(let name of readdirSync(dir)){if(!name.endsWith(".json"))continue;let path2=join2(dir,name);try{Date.now()-statSync(path2).mtimeMs>PRUNE_MS&&rmSync(path2)}catch{}}}catch{}}function writeSession(record4){let file2=sessionFile();file2||fail(EXIT.USAGE,"NO_SESSION","No shell session detected (no TTY). Set SR_CONNECT_CLI_SESSION_ID, or pass --team/-w/-e explicitly."),persist(file2,record4)}function persist(file2,record4,instance4,options){let dir=sessionsDir();mkdirSync2(dir,{recursive:!0,mode:448}),prune(dir);let existing=options?.replace?void 0:readRecord(file2),carried=record4.serviceInfo??existing?.serviceInfo,locks=pruneLocks("locks"in record4?record4.locks:existing?.locks),update=record4.updateCheck??existing?.updateCheck,payload={...record4,version:SESSION_RECORD_VERSION,...carried===void 0?{}:{serviceInfo:carried},...locks===void 0?{}:{locks},...update===void 0?{}:{updateCheck:update},instance:instance4??effectiveInstance(),updatedAt:new Date().toISOString()},tmp=`${file2}.${process.pid}.tmp`;try{writeFileSync2(tmp,JSON.stringify(payload)+`
38
+ `,{mode:384}),renameSync(tmp,file2)}catch(err){throw rmSync(tmp,{force:!0}),err}}function pruneLocks(locks){if(!locks)return;let kept=Object.fromEntries(Object.entries(locks).filter(([,lock])=>{let expiry=Date.parse(lock.expiresAt);return!Number.isFinite(expiry)||Date.now()-expiry<LOCK_KEEP_MS}));return Object.keys(kept).length>0?kept:void 0}function readWorkspaceLock(workspaceId){let file2=sessionFile();if(file2)return readRecord(file2)?.locks?.[workspaceId]}function storeWorkspaceLock(workspaceId,lock){let file2=sessionFile();if(!file2)return!1;try{let existing=readRecord(file2),{instance:_instance,updatedAt:_updatedAt,locks,...rest}=existing??{};return persist(file2,{...rest,locks:{...locks,[workspaceId]:lock}}),!0}catch{return!1}}function forgetWorkspaceLock(workspaceId){let file2=sessionFile();if(!file2)return;let existing=readRecord(file2);if(existing?.locks?.[workspaceId])try{let{instance:_instance,updatedAt:_updatedAt,locks,...rest}=existing,remaining={...locks};delete remaining[workspaceId],persist(file2,{...rest,locks:remaining})}catch{}}function cachedServiceInfo(){return readSession()?.serviceInfo}function cacheServiceInfo(info){if(!enabled)return;let file2=sessionFile();if(file2)try{let existing=readRecord(file2),{instance:_instance,updatedAt:_updatedAt,...rest}=existing??{};persist(file2,{...rest,serviceInfo:info})}catch{}}function readUpdateCheck(){let file2=sessionFile();if(file2)return readRecord(file2)?.updateCheck}function storeUpdateCheck(check2){let file2=sessionFile();if(file2)try{let existing=readRecord(file2),{instance:_instance,updatedAt:_updatedAt,...rest}=existing??{};persist(file2,{...rest,updateCheck:check2})}catch{}}function forgetScopeValue(key,value,dependents=[]){if(!enabled)return[];let file2=sessionFile();if(!file2)return[];let existing=readRecord(file2);if(!existing||existing[key]!==value)return[];try{let{instance:_instance,updatedAt:_updatedAt,labels,...rest}=existing,removed=[key];delete rest[key];let remaining={...labels};delete remaining[key];for(let dependent of dependents)rest[dependent]!==void 0&&removed.push(dependent),delete rest[dependent],delete remaining[dependent];return persist(file2,{...rest,...Object.keys(remaining).length>0?{labels:remaining}:{}}),removed}catch{return[]}}function lockReleaseCommand(lock){let instance4=lock.instance?` --instance ${shellQuote(lock.instance)}`:"";return`${CLI} workspace-lock release -w ${lock.workspaceId} --lock-id ${lock.lockId}${instance4}`}function dropSession(file2){try{return rmSync(file2),!0}catch{return!1}}function clearSession(){let file2=sessionFile();if(!file2)return{cleared:!1,keptLocks:[]};let existing=readRecord(file2),locks=pruneLocks(existing?.locks);if(!locks)return{cleared:dropSession(file2),keptLocks:[]};let kept=keptLocksOf(locks);try{return persist(file2,{locks},void 0,{replace:!0}),{cleared:!0,keptLocks:kept}}catch{return{cleared:dropSession(file2),keptLocks:kept}}}function clearAllSessions(){let removed=0,keptLocks=[];try{for(let name of readdirSync(sessionsDir())){if(!name.endsWith(".json"))continue;let file2=join2(sessionsDir(),name),record4=readRecord(file2,{anyInstance:!0}),locks=pruneLocks(record4?.locks);try{locks?(persist(file2,{locks},record4?.instance,{replace:!0}),keptLocks.push(...keptLocksOf(locks,record4?.instance))):rmSync(file2),removed+=1}catch{}}}catch{}return{removed,keptLocks}}function keptLocksOf(locks,instance4){let now=Date.now(),foreign=instance4!==void 0&&instance4!==effectiveInstance()?{instance:instance4}:{};return Object.entries(locks).filter(([,lock])=>Date.parse(lock.expiresAt)>now).map(([workspaceId,lock])=>({workspaceId,lockId:lock.lockId,...foreign}))}function describeValue(record4,key){let id=record4[key]??"",label=record4.labels?.[key];return label?`${label} (${id})`:id}import{mkdirSync as mkdirSync3,readFileSync as readFileSync4,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync3}from"fs";import{join as join3}from"path";var SETTING_KEYS=["recordApiCalls","workspaceLock","localSync","crashReports","agenticFeedback"],SETTINGS={recordApiCalls:{label:"Record API calls",hint:"records this CLI's own requests to a local log, readable with `cli list-api-logs` \u2014 recommended to keep on",envVar:"SR_CONNECT_CLI_NO_RECORD_API_CALLS",flag:"--no-record-api-calls"},workspaceLock:{label:"Auto workspace lock",hint:"takes a workspace lock before a write, so nothing else changes the workspace mid-command \u2014 recommended to keep on",envVar:"SR_CONNECT_CLI_NO_LOCK",flag:"--no-lock"},localSync:{label:"Auto local sync",hint:"mirrors a change into the local copy of the workspace, if the local directory is a local workspace clone \u2014 recommended to keep on",envVar:"SR_CONNECT_CLI_NO_LOCAL_SYNC",flag:"--no-local-sync"},crashReports:{label:"Generate crash reports",hint:"writes a report when a run fails unexpectedly, and offers to send it \u2014 recommended to keep on",envVar:"SR_CONNECT_CLI_NO_CRASH_REPORTS",flag:"--no-crash-reports"},agenticFeedback:{label:"Allow agentic feedback",hint:"allows agents to send feedback autonomously for improvements \u2014 recommended to keep on",envVar:"SR_CONNECT_CLI_NO_AGENTIC_FEEDBACK",flag:"--no-agentic-feedback"}},SETTINGS_VERSION=1;function settingsFile(){return join3(stateHome(),APP_DIR,"settings.json")}var cache,warned=!1;function readSettings(){if(cache)return cache;let parsed;try{parsed=JSON.parse(readFileSync4(settingsFile(),"utf8"))}catch{return cache={},cache}let file2=parsed;if(typeof file2?.version=="number"&&file2.version>SETTINGS_VERSION)return warned||(warned=!0,warnLine(`\u26A0 ${settingsFile()} was written by a newer CLI (format ${file2.version}) \u2014 using the defaults. Update the CLI to read it.`)),cache={},cache;let values={},stored=file2?.values;if(stored&&typeof stored=="object")for(let key of SETTING_KEYS){let value=stored[key];typeof value=="boolean"&&(values[key]=value)}return cache=values,values}function envDisabled(key){let value=process.env[SETTINGS[key].envVar];return value===void 0?!1:!["","0","false","no","off"].includes(value.trim().toLowerCase())}function settingEnabled(key){return readSettings()[key]!==!1}function writeSettings(values){let forced=[],stored={};for(let key of SETTING_KEYS){if(envDisabled(key)){forced.push(key),stored[key]=!1;continue}values[key]||(stored[key]=!1)}let file2={version:SETTINGS_VERSION,updatedAt:new Date().toISOString(),values:stored},path2=settingsFile();mkdirSync3(join3(stateHome(),APP_DIR),{recursive:!0,mode:448});let tmp=`${path2}.${process.pid}.tmp`;try{writeFileSync3(tmp,JSON.stringify(file2)+`
39
+ `,{mode:384}),renameSync2(tmp,path2)}catch(err){throw rmSync2(tmp,{force:!0}),err}return cache=stored,forced}function setSetting(key,value){let stored=readSettings(),values=Object.fromEntries(SETTING_KEYS.map(candidate=>[candidate,candidate===key?value:stored[candidate]!==!1]));return writeSettings(values)}function settingStates(flagOff={}){let stored=readSettings();return SETTING_KEYS.map(key=>{let descriptor=SETTINGS[key],flagDisabled=flagOff[key]===!0,env=envDisabled(key),value=stored[key],source=flagDisabled?"flag":env?"env":value===void 0?"default":"stored";return{key,label:descriptor.label,hint:descriptor.hint,enabled:!flagDisabled&&!env&&value!==!1,stored:value??null,envVar:descriptor.envVar,envDisabled:env,flag:descriptor.flag,flagDisabled,source}})}var ENTRY_VERSION=2,MAX_BODY=4*1024,PRUNE_MS2=10080*60*1e3,MAX_SESSION_BYTES=25*1024*1024,ROLLED=".1.jsonl",SECRET_KEY=/password|secret|token|credential|apikey|authorization|lockid/i,SECRET_PARAM=/^(x-amz-signature|x-amz-credential|x-amz-security-token|signature|awsaccesskeyid|googleaccessid|sig|se|sp|sig_key|token|password|apikey)$/i,REDACTED="<redacted>",KEEP_HEADERS=["content-type","content-length","retry-after","x-sr-connect-workspace-lock-expires-at","x-request-id","x-amzn-requestid","x-amzn-trace-id"],enabled2=!1,argv=[],instance,runId="",runSequence=0,runStarted="",runWritten=!1,maintained=!1,SECRET_ARGV_FLAG=/^(--header|--lock-id)(=|$)/;function redactArg(flag,value){if(flag.startsWith("--lock-id"))return REDACTED;let at2=value.indexOf(":");return at2===-1?REDACTED:`${value.slice(0,at2)}: ${REDACTED}`}function sanitizeArgv(tokens){let out=[];for(let i=0;i<tokens.length;i++){let token=tokens[i]??"";if(!SECRET_ARGV_FLAG.test(token)){out.push(token);continue}let eq=token.indexOf("=");if(eq!==-1){out.push(`${token.slice(0,eq)}=${redactArg(token,token.slice(eq+1))}`);continue}out.push(token);let next=tokens[i+1];next!==void 0&&(out.push(redactArg(token,next)),i++)}return out}function configureRecorder(opts){let off=process.env.SR_CONNECT_CLI_NO_RECORD_API_CALLS;enabled2=opts.enabled!==!1&&(off===void 0||/^(0|false|no|off|)$/i.test(off.trim()))&&settingEnabled("recordApiCalls"),instance=opts.instance,argv=sanitizeArgv(process.argv.slice(2)),runStarted=new Date().toISOString(),runSequence+=1,runId=`${RUN_ID}-${runSequence}`,runWritten=!1,maintained=!1}function recordingEnabled(){return enabled2}function apiCallsDir(){return join4(stateHome(),APP_DIR,"api-calls")}function sessionFile2(key){return join4(apiCallsDir(),`${key}.jsonl`)}function sessionOf(name){return name.replace(/(\.1)?\.jsonl$/,"")}function sanitizeBody(text){if(text==="")return"";let bytes=Buffer.byteLength(text),out;try{out=JSON.stringify(redact(JSON.parse(text)))}catch{return`<non-json, ${bytes} bytes>`}return out.length>MAX_BODY?`${out.slice(0,MAX_BODY)}\u2026(truncated, ${bytes} bytes)`:out}function redactHeaders(value){return Array.isArray(value)?value.map(entry2=>entry2&&typeof entry2=="object"&&!Array.isArray(entry2)&&"name"in entry2&&"value"in entry2?{...entry2,value:REDACTED}:redact(entry2)):redact(value)}function redactAttachments(value){return Array.isArray(value)?value.map(entry2=>entry2&&typeof entry2=="object"&&!Array.isArray(entry2)&&"content"in entry2?{...entry2,content:REDACTED}:redact(entry2)):redact(value)}function redact(value){return Array.isArray(value)?value.map(redact):value&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,child])=>[key,SECRET_KEY.test(key)?REDACTED:key==="headers"?redactHeaders(child):key==="attachments"?redactAttachments(child):redact(child)])):typeof value=="string"&&/^https?:\/\//i.test(value)?sanitizeUrl(value):value}function pickHeaders(headers){let picked={};for(let name of KEEP_HEADERS){let value=headers.get(name);value!==null&&(picked[name]=value)}return picked}function instanceBaseUrl(value=instance){let resolved=resolveInstance(value);return resolved?baseUrl(resolved):void 0}function redactLockPath(url2){return url2.replace(/\/lock\/[^/?#]+/i,`/lock/${REDACTED}`)}function sanitizeUrl(url2,base=instanceBaseUrl()){if(url2=redactLockPath(url2),base!==void 0&&url2.startsWith(base))return url2;let cut=url2.indexOf("?");if(cut===-1)return url2;let query=url2.slice(cut+1).split("&").map(pair=>{let eq=pair.indexOf("="),name=eq===-1?pair:pair.slice(0,eq);return SECRET_PARAM.test(name)?`${name}=${REDACTED}`:pair}).join("&");return`${url2.slice(0,cut)}?${query}`}function recordApiCall(call){if(!enabled2)return;let key=sessionKey();if(!key)return;let path2=sessionFile2(key);try{mkdirSync4(apiCallsDir(),{recursive:!0,mode:448}),maintainOnce(path2,key);let lines=[];runWritten||lines.push({v:ENTRY_VERSION,t:"run",runId,ts:runStarted,argv,pid:process.pid,...instance===void 0?{}:{instance}}),lines.push({v:ENTRY_VERSION,t:"call",runId,...call,url:sanitizeUrl(call.url)}),appendFileSync2(path2,lines.map(line=>`${JSON.stringify(line)}
40
+ `).join(""),{mode:384}),runWritten=!0}catch(err){enabled2=!1;let message=err instanceof Error?err.message:String(err);warnLine(`\u26A0 Could not record API calls to ${path2}: ${message}`)}}function maintainOnce(path2,key){maintained||(maintained=!0,prune2(),roll(path2,key))}function prune2(){for(let name of listFiles()){let path2=join4(apiCallsDir(),name);try{Date.now()-statSync2(path2).mtimeMs>PRUNE_MS2&&rmSync3(path2)}catch{}}}function roll(path2,key){try{if(statSync2(path2).size<MAX_SESSION_BYTES)return;renameSync3(path2,join4(apiCallsDir(),`${key}${ROLLED}`))}catch{}}function listFiles(){try{return readdirSync2(apiCallsDir()).filter(name=>name.endsWith(".jsonl")).sort()}catch{return[]}}function filesToRead(opts){if(opts.allSessions)return listFiles();let key=opts.session??sessionKey();if(!key)return[];let present=new Set(listFiles());return[`${key}${ROLLED}`,`${key}.jsonl`].filter(name=>present.has(name))}function parseFile(name){let text;try{text=readFileSync5(join4(apiCallsDir(),name),"utf8")}catch{return[]}let lines=[];for(let line of text.split(`
41
+ `))if(line.trim()!=="")try{let parsed=JSON.parse(line);parsed.v===ENTRY_VERSION&&lines.push(parsed)}catch{}return lines}function readApiCalls(opts){let runs=[],byId=new Map;for(let name of filesToRead(opts)){let session=sessionOf(name),runOf=(id,ts)=>{let runKey=`${session}\0${id}`,known=byId.get(runKey);if(known)return known;let created={runId:id,ts,argv:[],pid:0,session,calls:[],totalCalls:0};return byId.set(runKey,created),runs.push(created),created};for(let line of parseFile(name)){if(line.t==="run"){let run2=runOf(line.runId,line.ts);run2.ts=line.ts,run2.argv=line.argv,run2.pid=line.pid,run2.instance=line.instance;continue}let run=runOf(line.runId,line.ts),{v:_version,t:_type,runId:_runId,...call}=line;run.calls.push(call),run.totalCalls+=1}}return runs.sort((a,b2)=>a.ts.localeCompare(b2.ts))}function listRecordedSessions(){return summarize(listFiles())}function recordedTargets(opts){return summarize(filesToRead(opts))}function summarize(names){let rows2=new Map;for(let name of names){let session=sessionOf(name),row=rows2.get(session)??{session,files:0,runs:0,calls:0,bytes:0},lines=parseFile(name),calls=lines.filter(line=>line.t==="call");row.files+=1,row.runs+=lines.filter(line=>line.t==="run").length,row.calls+=calls.length,row.first??=calls[0]?.ts,row.last=calls.at(-1)?.ts??row.last;try{row.bytes+=statSync2(join4(apiCallsDir(),name)).size}catch{}rows2.set(session,row)}return[...rows2.values()]}function clearApiCalls(opts){let removed=new Set;for(let name of filesToRead(opts))try{rmSync3(join4(apiCallsDir(),name)),removed.add(sessionOf(name))}catch{}return[...removed]}import{closeSync,mkdirSync as mkdirSync6,openSync,readFileSync as readFileSync8,readSync,readdirSync as readdirSync4,rmSync as rmSync5,statSync as statSync4,writeFileSync as writeFileSync5}from"fs";import{arch,platform,release}from"os";import{join as join8}from"path";var PATH_PARAM_RE=/\{[^{}]+\}/g,supportsRequestInitExt=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function randomID(){return Math.random().toString(36).slice(2,11)}function createClient(clientOptions){let{baseUrl:baseUrl2="",Request:CustomRequest=globalThis.Request,fetch:baseFetch=globalThis.fetch,querySerializer:globalQuerySerializer,bodySerializer:globalBodySerializer,pathSerializer:globalPathSerializer,headers:baseHeaders,requestInitExt=void 0,...baseOptions}={...clientOptions};requestInitExt=supportsRequestInitExt()?requestInitExt:void 0,baseUrl2=removeTrailingSlash(baseUrl2);let globalMiddlewares=[];async function coreFetch(schemaPath,fetchOptions){let{baseUrl:localBaseUrl,fetch:fetch2=baseFetch,Request:Request2=CustomRequest,headers,params={},parseAs="json",querySerializer:requestQuerySerializer,bodySerializer=globalBodySerializer??defaultBodySerializer,pathSerializer:requestPathSerializer,body,middleware:requestMiddlewares=[],...init}=fetchOptions||{},finalBaseUrl=baseUrl2;localBaseUrl&&(finalBaseUrl=removeTrailingSlash(localBaseUrl)??baseUrl2);let querySerializer=typeof globalQuerySerializer=="function"?globalQuerySerializer:createQuerySerializer(globalQuerySerializer);requestQuerySerializer&&(querySerializer=typeof requestQuerySerializer=="function"?requestQuerySerializer:createQuerySerializer({...typeof globalQuerySerializer=="object"?globalQuerySerializer:{},...requestQuerySerializer}));let pathSerializer=requestPathSerializer||globalPathSerializer||defaultPathSerializer,serializedBody=body===void 0?void 0:bodySerializer(body,mergeHeaders(baseHeaders,headers,params.header)),finalHeaders=mergeHeaders(serializedBody===void 0||serializedBody instanceof FormData?{}:{"Content-Type":"application/json"},baseHeaders,headers,params.header),finalMiddlewares=[...globalMiddlewares,...requestMiddlewares],requestInit={redirect:"follow",...baseOptions,...init,body:serializedBody,headers:finalHeaders},id,options,request=new Request2(createFinalURL(schemaPath,{baseUrl:finalBaseUrl,params,querySerializer,pathSerializer}),requestInit),response;for(let key in init)key in request||(request[key]=init[key]);if(finalMiddlewares.length){id=randomID(),options=Object.freeze({baseUrl:finalBaseUrl,fetch:fetch2,parseAs,querySerializer,bodySerializer,pathSerializer});for(let m2 of finalMiddlewares)if(m2&&typeof m2=="object"&&typeof m2.onRequest=="function"){let result=await m2.onRequest({request,schemaPath,params,options,id});if(result)if(result instanceof Request2)request=result;else if(result instanceof Response){response=result;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!response){try{response=await fetch2(request,requestInitExt)}catch(error210){let errorAfterMiddleware=error210;if(finalMiddlewares.length)for(let i=finalMiddlewares.length-1;i>=0;i--){let m2=finalMiddlewares[i];if(m2&&typeof m2=="object"&&typeof m2.onError=="function"){let result=await m2.onError({request,error:errorAfterMiddleware,schemaPath,params,options,id});if(result){if(result instanceof Response){errorAfterMiddleware=void 0,response=result;break}if(result instanceof Error){errorAfterMiddleware=result;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(errorAfterMiddleware)throw errorAfterMiddleware}if(finalMiddlewares.length)for(let i=finalMiddlewares.length-1;i>=0;i--){let m2=finalMiddlewares[i];if(m2&&typeof m2=="object"&&typeof m2.onResponse=="function"){let result=await m2.onResponse({request,response,schemaPath,params,options,id});if(result){if(!(result instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");response=result}}}}let contentLength=response.headers.get("Content-Length");if(response.status===204||request.method==="HEAD"||contentLength==="0"&&!response.headers.get("Transfer-Encoding")?.includes("chunked"))return response.ok?{data:void 0,response}:{error:void 0,response};if(response.ok)return{data:await(async()=>{if(parseAs==="stream")return response.body;if(parseAs==="json"&&!contentLength){let raw=await response.text();return raw?JSON.parse(raw):void 0}return await response[parseAs]()})(),response};let error51=await response.text();try{error51=JSON.parse(error51)}catch{}return{error:error51,response}}return{request(method,url2,init){return coreFetch(url2,{...init,method:method.toUpperCase()})},GET(url2,init){return coreFetch(url2,{...init,method:"GET"})},PUT(url2,init){return coreFetch(url2,{...init,method:"PUT"})},POST(url2,init){return coreFetch(url2,{...init,method:"POST"})},DELETE(url2,init){return coreFetch(url2,{...init,method:"DELETE"})},OPTIONS(url2,init){return coreFetch(url2,{...init,method:"OPTIONS"})},HEAD(url2,init){return coreFetch(url2,{...init,method:"HEAD"})},PATCH(url2,init){return coreFetch(url2,{...init,method:"PATCH"})},TRACE(url2,init){return coreFetch(url2,{...init,method:"TRACE"})},use(...middleware){for(let m2 of middleware)if(m2){if(typeof m2!="object"||!("onRequest"in m2||"onResponse"in m2||"onError"in m2))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");globalMiddlewares.push(m2)}},eject(...middleware){for(let m2 of middleware){let i=globalMiddlewares.indexOf(m2);i!==-1&&globalMiddlewares.splice(i,1)}}}}function serializePrimitiveParam(name,value,options){if(value==null)return"";if(typeof value=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${name}=${options?.allowReserved===!0?value:encodeURIComponent(value)}`}function serializeObjectParam(name,value,options){if(!value||typeof value!="object")return"";let values=[],joiner={simple:",",label:".",matrix:";"}[options.style]||"&";if(options.style!=="deepObject"&&options.explode===!1){for(let k2 in value)values.push(k2,options.allowReserved===!0?value[k2]:encodeURIComponent(value[k2]));let final2=values.join(",");switch(options.style){case"form":return`${name}=${final2}`;case"label":return`.${final2}`;case"matrix":return`;${name}=${final2}`;default:return final2}}for(let k2 in value){let finalName=options.style==="deepObject"?`${name}[${k2}]`:k2;values.push(serializePrimitiveParam(finalName,value[k2],options))}let final=values.join(joiner);return options.style==="label"||options.style==="matrix"?`${joiner}${final}`:final}function serializeArrayParam(name,value,options){if(!Array.isArray(value))return"";if(options.explode===!1){let joiner2={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[options.style]||",",final=(options.allowReserved===!0?value:value.map(v2=>encodeURIComponent(v2))).join(joiner2);switch(options.style){case"simple":return final;case"label":return`.${final}`;case"matrix":return`;${name}=${final}`;default:return`${name}=${final}`}}let joiner={simple:",",label:".",matrix:";"}[options.style]||"&",values=[];for(let v2 of value)options.style==="simple"||options.style==="label"?values.push(options.allowReserved===!0?v2:encodeURIComponent(v2)):values.push(serializePrimitiveParam(name,v2,options));return options.style==="label"||options.style==="matrix"?`${joiner}${values.join(joiner)}`:values.join(joiner)}function createQuerySerializer(options){return function(queryParams){let search=[];if(queryParams&&typeof queryParams=="object")for(let name in queryParams){let value=queryParams[name];if(value!=null){if(Array.isArray(value)){if(value.length===0)continue;search.push(serializeArrayParam(name,value,{style:"form",explode:!0,...options?.array,allowReserved:options?.allowReserved||!1}));continue}if(typeof value=="object"){search.push(serializeObjectParam(name,value,{style:"deepObject",explode:!0,...options?.object,allowReserved:options?.allowReserved||!1}));continue}search.push(serializePrimitiveParam(name,value,options))}}return search.join("&")}}function defaultPathSerializer(pathname,pathParams){let nextURL=pathname;for(let match of pathname.match(PATH_PARAM_RE)??[]){let name=match.substring(1,match.length-1),explode=!1,style="simple";if(name.endsWith("*")&&(explode=!0,name=name.substring(0,name.length-1)),name.startsWith(".")?(style="label",name=name.substring(1)):name.startsWith(";")&&(style="matrix",name=name.substring(1)),!pathParams||pathParams[name]===void 0||pathParams[name]===null)continue;let value=pathParams[name];if(Array.isArray(value)){nextURL=nextURL.replace(match,serializeArrayParam(name,value,{style,explode}));continue}if(typeof value=="object"){nextURL=nextURL.replace(match,serializeObjectParam(name,value,{style,explode}));continue}if(style==="matrix"){nextURL=nextURL.replace(match,`;${serializePrimitiveParam(name,value)}`);continue}nextURL=nextURL.replace(match,style==="label"?`.${encodeURIComponent(value)}`:encodeURIComponent(value))}return nextURL}function defaultBodySerializer(body,headers){return body instanceof FormData?body:headers&&(headers.get instanceof Function?headers.get("Content-Type")??headers.get("content-type"):headers["Content-Type"]??headers["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(body).toString():JSON.stringify(body)}function createFinalURL(pathname,options){let finalURL=`${options.baseUrl}${pathname}`;options.params?.path&&(finalURL=options.pathSerializer(finalURL,options.params.path));let search=options.querySerializer(options.params.query??{});return search.startsWith("?")&&(search=search.substring(1)),search&&(finalURL+=`?${search}`),finalURL}function mergeHeaders(...allHeaders){let finalHeaders=new Headers;for(let h of allHeaders){if(!h||typeof h!="object")continue;let iterator=h instanceof Headers?h.entries():Object.entries(h);for(let[k2,v2]of iterator)if(v2===null)finalHeaders.delete(k2);else if(Array.isArray(v2))for(let v22 of v2)finalHeaders.append(k2,v22);else v2!==void 0&&finalHeaders.set(k2,v2)}return finalHeaders}function removeTrailingSlash(url2){return url2.endsWith("/")?url2.substring(0,url2.length-1):url2}var import_picocolors4=__toESM(require_picocolors(),1);import{chmodSync,mkdirSync as mkdirSync5,readFileSync as readFileSync6,rmSync as rmSync4,writeFileSync as writeFileSync4}from"fs";import{join as join5}from"path";var SERVICE=APP_DIR,ACCOUNT="default";async function entry(){if(process.env.SR_CONNECT_CLI_DISABLE_KEYCHAIN)throw new Error("Keychain disabled via SR_CONNECT_CLI_DISABLE_KEYCHAIN.");let{Entry}=await import("@napi-rs/keyring");return new Entry(SERVICE,ACCOUNT)}async function keychainGet(){try{let raw=(await entry()).getPassword();return raw?JSON.parse(raw):null}catch{return null}}async function keychainSet(creds){(await entry()).setPassword(JSON.stringify(creds))}async function keychainDelete(){try{return(await entry()).deletePassword()}catch{return!1}}var CREDENTIALS_FILE=()=>join5(configDir(),"credentials.json");function fileGet(){try{return JSON.parse(readFileSync6(CREDENTIALS_FILE(),"utf8"))}catch{return null}}function fileSet(creds){mkdirSync5(configDir(),{recursive:!0}),writeFileSync4(CREDENTIALS_FILE(),JSON.stringify(creds,null,2)+`
42
+ `,{mode:384}),chmodSync(CREDENTIALS_FILE(),384)}function fileDelete(){rmSync4(CREDENTIALS_FILE(),{force:!0})}async function resolveCredentials(){let creds=await lookupCredentials();return creds&&(resolvedUsername=creds.username),creds}async function lookupCredentials(){let envUser=process.env.SR_CONNECT_CLI_USERNAME,envPass=process.env.SR_CONNECT_CLI_PASSWORD;if(envUser&&envPass)return{username:envUser,password:envPass,source:"env"};let fromKeychain=await keychainGet();if(fromKeychain)return{...fromKeychain,source:"keychain"};let fromFile=fileGet();return fromFile?{...fromFile,source:"file"}:null}var resolvedUsername;function currentUsername(){return resolvedUsername}async function requireCredentials(){let creds=await resolveCredentials();return creds||fail(EXIT.UNAUTHENTICATED,"UNAUTHENTICATED","Not authenticated.",{hint:`Run \`${CLI} auth login\`, or set SR_CONNECT_CLI_USERNAME, SR_CONNECT_CLI_PASSWORD and SR_CONNECT_CLI_INSTANCE.`}),creds}function basicAuthHeader(creds){return"Basic "+Buffer.from(`${creds.username}:${creds.password}`).toString("base64")}var MIN_NODE_MAJOR=22;function runtimeNodeVersion(){return process.versions.node}function nodeMajor(version2=runtimeNodeVersion()){let major=Number.parseInt(version2??"",10);return Number.isFinite(major)?major:void 0}function nodeVersionWarning(version2=runtimeNodeVersion()){let major=Number.parseInt(version2??"",10);if(!(!Number.isFinite(major)||major>=MIN_NODE_MAJOR))return`\u26A0 Node ${version2} is older than the Node ${MIN_NODE_MAJOR} this CLI needs \u2014 live log streaming (--stream-logs) is unavailable and other commands may fail.`}var warned2=!1;function warnIfNodeUnsupported(){if(warned2)return;let warning=nodeVersionWarning();warning&&(warned2=!0,warnLine(warning))}var SEMVER_FORMAT="major.minor.patch",SEMVER=/^\d+\.\d+\.\d+$/;function semverError(version2){let trimmed=version2.trim();if(!SEMVER.test(trimmed))return`Expected a version in ${SEMVER_FORMAT} format, e.g. 1.4.0 \u2014 got "${trimmed}".`}function assertSemver(version2){let error51=semverError(version2);return error51&&fail(EXIT.USAGE,"INVALID_VERSION",error51),version2.trim()}var LOOSE_SEMVER=/^v?(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;function parseVersion(version2){let trimmed=version2.trim(),match=LOOSE_SEMVER.exec(trimmed);if(match)return{major:Number(match[1]??0),minor:Number(match[2]??0),patch:Number(match[3]??0),release:trimmed.includes("-")?0:1}}function compareSemver(a,b2){let left=parseVersion(a),right=parseVersion(b2);return left?right?left.major-right.major||left.minor-right.minor||left.patch-right.patch||left.release-right.release:1:right?-1:0}import{realpathSync}from"fs";import{dirname,join as join6,resolve as resolve2,sep as sep2}from"path";import{fileURLToPath}from"url";var DEFAULT_REGISTRY="https://registry.npmjs.org",LOOKUP_TIMEOUT_MS=5e3,MAX_OFFERED_VERSIONS=30,fetchImpl=(...args)=>fetch(...args);function registryBase(){let configured=process.env.SR_CONNECT_CLI_NPM_REGISTRY;return(configured&&configured.trim()!==""?configured.trim():DEFAULT_REGISTRY).replace(/\/+$/,"")}function isPrerelease(version2){return version2.includes("-")}async function fetchVersions(name){try{let response=await fetchImpl(`${registryBase()}/${encodeURIComponent(name)}`,{headers:{accept:"application/vnd.npm.install-v1+json","user-agent":USER_AGENT},signal:AbortSignal.timeout(LOOKUP_TIMEOUT_MS)});if(response.status===404)return"not-found";if(!response.ok)return;let body=await response.json();if(!body.versions||typeof body.versions!="object"||Array.isArray(body.versions))return;let versions=Object.keys(body.versions).reverse();if(versions.length===0)return;let distTags=body["dist-tags"]&&typeof body["dist-tags"]=="object"&&!Array.isArray(body["dist-tags"])?body["dist-tags"]:{},latest=typeof distTags.latest=="string"?distTags.latest:void 0;return{versions,distTags,...latest?{latest}:{}}}catch{return}}var enabled3=!0;function configureUpdateCheck(opts){let off=process.env.SR_CONNECT_CLI_NO_UPDATE_CHECK;enabled3=opts.enabled&&(off===void 0||/^(0|false|no|off|)$/i.test(off.trim()))}function latestStable(lookup){return lookup.latest&&!isPrerelease(lookup.latest)?lookup.latest:lookup.versions.filter(v2=>!isPrerelease(v2)).sort(compareSemver).at(-1)}function isFresh(checkedAt){let age=Date.now()-Date.parse(checkedAt);return Number.isFinite(age)&&age>=0&&age<SESSION_TTL_MS}function startUpdateCheck(){if(!enabled3)return;let stored=readUpdateCheck();stored&&isFresh(stored.checkedAt)||fetchVersions(PACKAGE).then(lookup=>{if(!lookup||lookup==="not-found")return;let latest=latestStable(lookup);latest&&storeUpdateCheck({checkedAt:new Date().toISOString(),latest})})}function globalRoots(site){let nodeDir=dirname(site.execPath),roots=[{manager:"npm",root:join6(nodeDir,"..","lib","node_modules")},{manager:"npm",root:join6(nodeDir,"node_modules")}],prefix=site.env.npm_config_prefix??site.env.PREFIX;prefix&&roots.push({manager:"npm",root:join6(prefix,"lib","node_modules")});let pnpmHome=site.env.PNPM_HOME;pnpmHome&&roots.push({manager:"pnpm",root:pnpmHome});let bunInstall=site.env.BUN_INSTALL;return bunInstall&&roots.push({manager:"bun",root:join6(bunInstall,"install","global")}),roots}function under(path2,root){let normalized=resolve2(root);return path2===normalized||path2.startsWith(normalized.endsWith(sep2)?normalized:normalized+sep2)}function classifyInstall(site){if(site.entry.includes(`${sep2}_npx${sep2}`)||site.entry.includes(`${sep2}dlx${sep2}`))return{kind:"npx",manager:"npm"};for(let{manager,root}of globalRoots(site))if(under(site.entry,root))return{kind:"global",manager};return{kind:site.entry.includes(`${sep2}node_modules${sep2}`)?"local":"unknown",manager:"npm"}}function updateCommand(kind,manager){let spec=`${PACKAGE}@latest`;return kind==="npx"?`npx ${spec}`:kind!=="global"?`npm install ${spec}`:manager==="pnpm"?`pnpm add -g ${spec}`:manager==="bun"?`bun add -g ${spec}`:`npm install -g ${spec}`}function currentSite(){let file2=fileURLToPath(import.meta.url),entry2=file2;try{entry2=realpathSync(file2)}catch{}return{entry:entry2,env:process.env,execPath:process.execPath}}function updateNotice(latest,current=VERSION,site=currentSite()){if(compareSemver(latest,current)<=0)return;let{kind,manager}=classifyInstall(site);return{command:updateCommand(kind,manager),current,latest}}function renderBanner(body){let width=Math.max(...body.map(line=>Array.from(line).length)),rule="*".repeat(width+6),pad=line=>`* ${line}${" ".repeat(width-Array.from(line).length)} *`;return[rule,pad(""),...body.map(pad),pad(""),rule]}function updateBody(notice){return[`New version of ${PACKAGE} available!`,`${notice.current} \u2192 ${notice.latest}`,"","Update with:",notice.command]}function unsupportedNotice(current=VERSION,site=currentSite()){let{kind,manager}=classifyInstall(site),command=updateCommand(kind,manager);return{message:`${PACKAGE} ${current} is no longer supported by this deployment.`,hint:`Update with: ${command}`,banner:renderBanner([`${PACKAGE} ${current} is no longer supported.`,"","Update with:",command])}}function renderCompact(notice){return[`\u2714 ${PACKAGE} ${notice.latest} is available (you have ${notice.current}).`,` Update with: ${notice.command}`]}var announced=!1;function printUpdateNotice(){if(announced||!enabled3)return;let stored=readUpdateCheck();if(!stored)return;let notice=updateNotice(stored.latest);if(notice){announced=!0;for(let line of isRaw()?renderCompact(notice):renderBanner(updateBody(notice)))successLine(line)}}var flagEnabled=!0;function configureVersionGate(opts){flagEnabled=opts.enabled}function gateEnabled(){return flagEnabled&&!process.env.SR_CONNECT_CLI_NO_VERSION_GATE}var refreshed=!1;async function readServiceInfo(client,opts={}){let cached2=cachedServiceInfo(),refresh=opts.refreshWithoutStreamUrl===!0&&!cached2?.logsStreamUrl&&!refreshed;if(cached2&&!refresh)return cached2;refresh&&cached2&&(refreshed=!0);let answer=await client.GET("/v1/serviceInfo",{}).catch(()=>{});if(!answer)return cached2;let{data,response}=answer;if(response.status===401&&fail(EXIT.UNAUTHENTICATED,"INVALID_CREDENTIALS","The API rejected these credentials.",{hint:`Run \`${CLI} auth login\` and try again.`}),!response.ok||!data)return cached2;let info={readAt:new Date().toISOString(),...data.logsStreamUrl?{logsStreamUrl:data.logsStreamUrl}:{},...data.minimumCliVersion?{minimumCliVersion:data.minimumCliVersion}:{}};return cacheServiceInfo(info),info}async function assertSupportedVersion(client){if(!gateEnabled())return;let minimum=(await readServiceInfo(client))?.minimumCliVersion;if(!minimum||compareSemver(VERSION,minimum)>=0)return;let notice=unsupportedNotice();fail(EXIT.USAGE,"CLI_TOO_OLD",notice.message,{banner:notice.banner,hint:notice.hint})}var import_picocolors3=__toESM(require_picocolors(),1);import crypto from"crypto";var ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=32;var RANDOM_LEN=16,TIME_LEN=10,TIME_MAX=0xffffffffffff;var ULIDErrorCode;(function(ULIDErrorCode2){ULIDErrorCode2.Base32IncorrectEncoding="B32_ENC_INVALID",ULIDErrorCode2.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",ULIDErrorCode2.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",ULIDErrorCode2.EncodeTimeNegative="ENC_TIME_NEG",ULIDErrorCode2.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",ULIDErrorCode2.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",ULIDErrorCode2.PRNGDetectFailure="PRNG_DETECT",ULIDErrorCode2.ULIDInvalid="ULID_INVALID",ULIDErrorCode2.Unexpected="UNEXPECTED",ULIDErrorCode2.UUIDInvalid="UUID_INVALID"})(ULIDErrorCode||(ULIDErrorCode={}));var ULIDError=class extends Error{constructor(errorCode,message){super(`${message} (${errorCode})`),this.name="ULIDError",this.code=errorCode}};function randomChar(prng){let randomPosition=Math.floor(prng()*ENCODING_LEN)%ENCODING_LEN;return ENCODING.charAt(randomPosition)}function detectPRNG(root){let rootLookup=detectRoot(),globalCrypto=rootLookup&&(rootLookup.crypto||rootLookup.msCrypto)||(typeof crypto<"u"?crypto:null);if(typeof globalCrypto?.getRandomValues=="function")return()=>{let buffer=new Uint8Array(1);return globalCrypto.getRandomValues(buffer),buffer[0]/256};if(typeof globalCrypto?.randomBytes=="function")return()=>globalCrypto.randomBytes(1).readUInt8()/256;if(crypto?.randomBytes)return()=>crypto.randomBytes(1).readUInt8()/256;throw new ULIDError(ULIDErrorCode.PRNGDetectFailure,"Failed to find a reliable PRNG")}function detectRoot(){return inWebWorker()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function encodeRandom(len,prng){let str="";for(;len>0;len--)str=randomChar(prng)+str;return str}function encodeTime(now,len=TIME_LEN){if(isNaN(now))throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed,`Time must be a number: ${now}`);if(now>TIME_MAX)throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${TIME_MAX}: ${now}`);if(now<0)throw new ULIDError(ULIDErrorCode.EncodeTimeNegative,`Time must be positive: ${now}`);if(Number.isInteger(now)===!1)throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed,`Time must be an integer: ${now}`);let mod,str="";for(let currentLen=len;currentLen>0;currentLen--)mod=now%ENCODING_LEN,str=ENCODING.charAt(mod)+str,now=(now-mod)/ENCODING_LEN;return str}function inWebWorker(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ulid(seedTime,prng){let currentPRNG=prng||detectPRNG(),seed=!seedTime||isNaN(seedTime)?Date.now():seedTime;return encodeTime(seed,TIME_LEN)+encodeRandom(RANDOM_LEN,currentPRNG)}function personName(person){return[person.firstName,person.lastName].filter(Boolean).join(" ")||person.email||""}function personCell(person){return`${personName(person)||person.id}${person.id?` (${person.id})`:""}`}var import_cronstrue=__toESM(require_cronstrue(),1);var CRON_FIELDS="second minute hour day-of-month month day-of-week",HOURLY_CRON="0 0 * * * *";function everyMinutesCron(minutes){return`0 */${minutes} * * * *`}function dailyCron(hour,minute){return`0 ${minute} ${hour} * * *`}function weeklyCron(day,hour,minute){return`0 ${minute} ${hour} * * ${day}`}function normalizeCron(expression){return expression.trim().split(/\s+/).join(" ")}function errorForNormalized(normalized){let parts=normalized.split(" ").filter(Boolean);if(parts.length!==6)return`CRON expression must have 6 fields (${CRON_FIELDS}) \u2014 got ${parts.length}.`;try{(0,import_cronstrue.toString)(parts.join(" "))}catch(err){return`Invalid CRON expression: ${(err instanceof Error?err.message:String(err)).replace(/^Error:\s*/,"")}`}}function cronError(expression){return errorForNormalized(normalizeCron(expression))}function describeCron(expression){try{return(0,import_cronstrue.toString)(normalizeCron(expression))}catch{return}}var MIN_TRIGGER_INTERVAL_MINUTES=15;function scheduleOf(trigger){return trigger.cronExpressionDescription??trigger.cronExpression??"not scheduled"}function assertCron(expression){let normalized=normalizeCron(expression),message=errorForNormalized(normalized);return message&&fail(EXIT.USAGE,"INVALID_CRON",message,{hint:`Once per hour is ${HOURLY_CRON}`}),normalized}var ResolverFetchError=class extends Error{status;constructor(status,message){super(message),this.status=status}};function listenerAppRegistry(){let app=RESOLVERS.app;return app?{...RESOLVERS,app:{...app,async fetch(client,deps){let payload=await fetchApps(client),withListeners=new Set(payload.apps.filter(a=>connectionTypes(a).some(ct2=>(ct2.eventListenerTypes??[]).length>0)).map(a=>a.id));return(await app.fetch(client,deps)).filter(choice=>withListeners.has(choice.value))}}}:RESOLVERS}function mapResolverError(err,spec){err.status===401&&fail(EXIT.UNAUTHENTICATED,"INVALID_CREDENTIALS",err.message,{status:401}),fail(err.status===404?EXIT.NOT_FOUND:EXIT.API_ERROR,err.status===404?"NOT_FOUND":"API_ERROR",`Fetching ${spec.plural} failed: ${err.message}`,{status:err.status})}function must(deps,key){let v2=deps[key];if(!v2)throw new Error(`resolver dependency '${key}' missing`);return v2}async function unwrap(res){if(!res.response.ok||res.data===void 0){let message=res.error?.errorMessage??`Request failed with HTTP status ${res.response.status}.`;throw new ResolverFetchError(res.response.status,message)}return res.data}var appsCache=new WeakMap,featuresCache=new WeakMap;async function teamFeatures(client,teamId){return await teamFeaturesIfKnown(client,teamId)??{eventQueues:!1,remoteWorkspace:!1}}async function teamFeaturesIfKnown(client,teamId){let perTeam=featuresCache.get(client);perTeam||featuresCache.set(client,perTeam=new Map);let cached2=perTeam.get(teamId);return cached2||(cached2=client.GET("/v1/team/{teamId}",{params:{path:{teamId}}}).then(res=>res.response.ok&&res.data?res.data.features:void 0).catch(()=>{}),perTeam.set(teamId,cached2)),cached2}function connectionTypes(app){return app.connectionTypes??(app.connectionType?[app.connectionType]:[])}async function fetchApps(client){let cached2=appsCache.get(client);return cached2||(cached2=client.GET("/v1/apps").then(unwrap),appsCache.set(client,cached2)),cached2}function findApp(payload,appId){return payload.apps.find(a=>a.id===appId)}function findApiConnectionType(app,apiConnectionTypeId){return connectionTypes(app).flatMap(ct2=>ct2.apiConnectionTypes??[]).find(t=>t.id===apiConnectionTypeId)}async function apiConnectionPackages(client,appId,apiConnectionTypeId){let app=findApp(await fetchApps(client),appId);if(!app)throw new ResolverFetchError(404,`App '${appId}' not found.`);let type=findApiConnectionType(app,apiConnectionTypeId);if(!type)throw new ResolverFetchError(404,`API connection type '${apiConnectionTypeId}' not found.`);return type.packages??[]}var GENERIC_APP="Generic";async function appConnectionTypeName(client,appId){let app=findApp(await fetchApps(client),appId);if(app)return connectionTypes(app)[0]?.name}async function isGenericApp(client,appId){try{return await appConnectionTypeName(client,appId)===GENERIC_APP}catch{return!1}}var environmentsCache=new WeakMap;function fetchEnvironments(client,workspaceId){let perWorkspace=environmentsCache.get(client);perWorkspace||environmentsCache.set(client,perWorkspace=new Map);let cached2=perWorkspace.get(workspaceId);return cached2||(cached2=client.GET("/v1/workspace/{workspaceId}/environments",{params:{path:{workspaceId}}}).then(unwrap),cached2.catch(()=>perWorkspace.delete(workspaceId)),perWorkspace.set(workspaceId,cached2)),cached2}async function environmentRelease(client,workspaceId,environmentId){return(await environmentInfo(client,workspaceId,environmentId))?.release}async function environmentInfo(client,workspaceId,environmentId){return(await fetchEnvironments(client,workspaceId).catch(()=>{}))?.environments.find(e=>e.id===environmentId)}async function environmentBelongsTo(client,workspaceId,environmentId){let data=await fetchEnvironments(client,workspaceId).catch(()=>{});if(data)return data.environments.some(e=>e.id===environmentId)}var packagesCache=new WeakMap;function fetchWorkspacePackages(client,workspaceId){let perWorkspace=packagesCache.get(client);perWorkspace||packagesCache.set(client,perWorkspace=new Map);let cached2=perWorkspace.get(workspaceId);return cached2||(cached2=client.GET("/v1/workspace/{workspaceId}/packages",{params:{path:{workspaceId}}}).then(unwrap),cached2.catch(()=>perWorkspace.delete(workspaceId)),perWorkspace.set(workspaceId,cached2)),cached2}async function packageInfo(client,workspaceId,packageId){return(await fetchWorkspacePackages(client,workspaceId).catch(()=>{}))?.packages.find(p=>p.id===packageId)}var connectorsCache=new WeakMap;function fetchConnectors(client,teamId){let perTeam=connectorsCache.get(client);perTeam||connectorsCache.set(client,perTeam=new Map);let cached2=perTeam.get(teamId);return cached2||(cached2=client.GET("/v1/team/{teamId}/connectors",{params:{path:{teamId}}}).then(unwrap),cached2.catch(()=>perTeam.delete(teamId)),perTeam.set(teamId,cached2)),cached2}async function connectorInfo(client,teamId,connectorId){return(await fetchConnectors(client,teamId).catch(()=>{}))?.connections.find(c=>c.id===connectorId)}var userCache=new WeakMap;async function currentUser(client){let cached2=userCache.get(client);return cached2||(cached2=client.GET("/v1/user/me").then(res=>res.response.ok&&res.data?res.data:void 0).catch(()=>{}),userCache.set(client,cached2)),cached2}async function currentUserId(client){return(await currentUser(client))?.id}var RESOLVERS={team:{key:"team",flag:"--team",label:"Team",plural:"teams",listCommand:`${CLI} team list`,dependsOn:[],async fetch(client){return(await unwrap(await client.GET("/v1/teams"))).teams.map(t=>({value:t.id,label:t.name,hint:t.id}))}},workspace:{key:"workspace",flag:"-w, --workspace",label:"Workspace",plural:"workspaces",listCommand:`${CLI} workspace list`,dependsOn:["team"],async fetch(client,deps){return(await unwrap(await client.GET("/v1/team/{teamId}/workspaces",{params:{path:{teamId:must(deps,"team")}}}))).workspaces.map(w=>({value:w.id,label:w.name,hint:w.id}))}},environment:{key:"environment",flag:"-e, --env",label:"Environment",plural:"environments",listCommand:`${CLI} environment list`,dependsOn:["workspace"],async fetch(client,deps){return(await fetchEnvironments(client,must(deps,"workspace"))).environments.map(e=>({value:e.id??"",label:e.name??e.id??"?",display:`${e.name??e.id??"?"} (${e.release?.version??"HEAD"})`,hint:e.id}))}},release:{key:"release",flag:"<releaseId>",label:"Release",plural:"releases",listCommand:`${CLI} release list`,dependsOn:["workspace"],async fetch(client,deps){return[...(await unwrap(await client.GET("/v1/workspace/{workspaceId}/releases",{params:{path:{workspaceId:must(deps,"workspace")}}}))).releases].reverse().map(r=>({value:r.id,label:r.version,...r.label?{display:`${r.version} \u2014 ${r.label}`}:{},hint:r.created}))}},parameter:{key:"parameter",flag:"<parameterId>",label:"Parameter",plural:"parameters",listCommand:`${CLI} environment-parameter list`,dependsOn:["workspace","environment"],async fetch(client,deps){let data=await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/parameters",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment")}}})),flatten2=(params,prefix="")=>params.flatMap(p=>{let path2=prefix?`${prefix} / ${p.key}`:p.key,self2={value:p.id,label:`${path2} \xB7 ${p.type}`,hint:p.id};return p.children?.length?[self2,...flatten2(p.children,path2)]:[self2]});return flatten2(data.parameters)}},app:{key:"app",flag:"--app-id",label:"App",plural:"apps",listCommand:`${CLI} app list`,dependsOn:[],async fetch(client){return(await fetchApps(client)).apps.map(a=>({value:a.id??"",label:a.name??a.id??"?",hint:a.id}))}},apiConnectionType:{key:"apiConnectionType",flag:"--api-connection-type-id",label:"API connection type",plural:"API connection types",listCommand:`${CLI} app list`,dependsOn:["app"],autoSelectSingle:!0,async fetch(client,deps){let app=findApp(await fetchApps(client),must(deps,"app"));if(!app)throw new ResolverFetchError(404,`App '${deps.app}' not found.`);return connectionTypes(app).flatMap(ct2=>(ct2.apiConnectionTypes??[]).map(t=>({value:t.id??"",label:t.name??t.id??"?",hint:ct2.name})))}},apiConnectionPackage:{key:"apiConnectionPackage",flag:"--package-id",label:"API connection package",plural:"API connection packages",listCommand:`${CLI} app list`,dependsOn:["app","apiConnectionType"],async fetch(client,deps){return(await apiConnectionPackages(client,must(deps,"app"),must(deps,"apiConnectionType"))).map(p=>({value:p.id??"",label:p.name??p.id??"?",hint:p.recommended?"recommended":p.deprecated?"deprecated":void 0}))}},listenerType:{key:"listenerType",flag:"--listener-type-id",label:"Event listener type",plural:"event listener types",listCommand:`${CLI} app list`,dependsOn:["app"],autoSelectSingle:!0,async fetch(client,deps){let app=findApp(await fetchApps(client),must(deps,"app"));if(!app)throw new ResolverFetchError(404,`App '${deps.app}' not found.`);return connectionTypes(app).flatMap(ct2=>(ct2.eventListenerTypes??[]).map(lt2=>({value:lt2.id??"",label:lt2.name??lt2.id??"?",hint:ct2.name})))}},eventType:{key:"eventType",flag:"--event-type-id",label:"Event type",plural:"event types",listCommand:`${CLI} app list`,dependsOn:["app","listenerType"],async fetch(client,deps){let app=findApp(await fetchApps(client),must(deps,"app"));if(!app)throw new ResolverFetchError(404,`App '${deps.app}' not found.`);let listenerType=connectionTypes(app).flatMap(ct2=>ct2.eventListenerTypes??[]).find(lt2=>lt2.id===must(deps,"listenerType"));if(!listenerType)throw new ResolverFetchError(404,`Event listener type '${deps.listenerType}' not found.`);return(listenerType.eventTypes??[]).map(et2=>({value:et2.id??"",label:et2.name??et2.id??"?",hint:et2.category}))}},connector:{key:"connector",flag:"--connector-id",label:"Connector",plural:"connectors",listCommand:`${CLI} connector list`,dependsOn:["team"],async fetch(client,deps){let data=await fetchConnectors(client,must(deps,"team")),me2=await currentUserId(client),allowed,appId=deps.app;if(appId){let app=findApp(await fetchApps(client),appId);if(app){let cts=connectionTypes(app),listenerTypeId=deps.listenerType;if(listenerTypeId){let owning=cts.filter(ct2=>(ct2.eventListenerTypes??[]).some(lt2=>lt2.id===listenerTypeId));owning.length>0&&(cts=owning)}let apiConnectionTypeId=deps.apiConnectionType;if(apiConnectionTypeId){let owning=cts.filter(ct2=>(ct2.apiConnectionTypes??[]).some(t=>t.id===apiConnectionTypeId));owning.length>0&&(cts=owning)}allowed=new Set(cts.map(ct2=>ct2.id??""))}}return data.connections.filter(c=>!allowed||allowed.has(c.connectionType?.id??"")).filter(c=>!appId||c.canUse!==!1).map(c=>{let sharer=me2&&c.owner?.id&&c.owner.id!==me2?personName(c.owner):"",notes=[c.authorized===!1?"unauthorized":void 0,sharer?`explicitly shared with you by ${sharer}`:void 0,c.canUse===!1?"not for use":void 0].filter(note=>note!==void 0),label=c.name??c.id??"?";return{value:c.id??"",label,...notes.length>0?{display:`${label} (${notes.join(", ")})`}:{},hint:c.connectionType?.name}})}},ownedConnector:{key:"ownedConnector",flag:"--connector-id",label:"Connector",plural:"connectors you own",listCommand:`${CLI} connector list`,dependsOn:["team"],async fetch(client,deps){let data=await fetchConnectors(client,must(deps,"team")),me2=await currentUserId(client);return data.connections.filter(c=>!me2||c.owner?.id===me2).map(c=>{let label=c.name??c.id??"?";return{value:c.id??"",label,...c.authorized===!1?{display:`${label} (unauthorized)`}:{},hint:c.connectionType?.name}})}},script:{key:"script",flag:"<scriptId>",label:"Script",plural:"scripts",dependsOn:["workspace","environment"],async fetch(client,deps){return(await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scripts",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment")}}}))).scripts.map(s=>({value:s.id,label:s.name,hint:s.id}))}},eventListener:{key:"eventListener",flag:"<eventListenerId>",label:"Event listener",plural:"event listeners",listCommand:`${CLI} event-listener list`,dependsOn:["workspace","environment"],async fetch(client,deps){return(await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListeners",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment")}}}))).eventListeners.map(el=>({value:el.id,label:el.eventType?`${el.app.name} \xB7 ${el.eventType.name}${el.script?` \u2192 ${el.script.name}`:""}`:`${el.app.name} (setup incomplete)`,hint:el.id}))}},apiConnection:{key:"apiConnection",flag:"<apiConnectionId>",label:"API connection",plural:"API connections",listCommand:`${CLI} api-connection list`,dependsOn:["workspace","environment"],async fetch(client,deps){return(await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnections",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment")}}}))).apiConnections.map(c=>{let label=c.path??c.id;return{value:c.id,label,display:`${label} \xB7 ${c.app.name}${c.connector?` \u2014 ${c.connector.name||c.connector.id}`:" \u2014 no connector here"}`,hint:c.id}})}},eventQueue:{key:"eventQueue",flag:"--event-queue-id",label:"Event queue",plural:"event queues",listCommand:`${CLI} event-queue list`,dependsOn:["workspace","environment"],async fetch(client,deps){return(await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueues",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment")}}}))).eventQueues.map(q2=>({value:q2.id,label:q2.name,...q2.disabled?{display:`${q2.name} (disabled)`}:{},hint:q2.id}))}},testPayload:{key:"testPayload",flag:"<testPayloadId>",label:"Test payload",plural:"test payloads",listCommand:`${CLI} event-listener-test-payload list`,dependsOn:["workspace","environment","eventListener"],async fetch(client,deps){let data=await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment"),eventListenerId:must(deps,"eventListener")}}}));return data.testPayloads.map(p=>({value:p.id,label:p.name,...p.id===data.defaultTestPayloadId?{display:`${p.name} (default)`}:{},hint:p.id}))}},scheduledTrigger:{key:"scheduledTrigger",flag:"<scheduledTriggerId>",label:"Scheduled trigger",plural:"scheduled triggers",listCommand:`${CLI} scheduled-trigger list`,dependsOn:["workspace","environment"],async fetch(client,deps){return(await unwrap(await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTriggers",{params:{path:{workspaceId:must(deps,"workspace"),environmentId:must(deps,"environment")}}}))).scheduledTriggers.map(t=>{let label=t.script?.name??t.id;return{value:t.id,label,display:`${label} \xB7 ${scheduleOf(t)}${t.disabled?" (disabled)":""}`,hint:t.id}})}},workspacePackage:{key:"workspacePackage",flag:"<packageId>",label:"Package",plural:"packages",listCommand:`${CLI} package list`,dependsOn:["workspace"],async fetch(client,deps){return(await fetchWorkspacePackages(client,must(deps,"workspace"))).packages.map(p=>({value:p.id,label:p.name,display:`${p.name}@${p.version} \xB7 ${p.type}${p.required?" \xB7 required":""}`,hint:p.id}))}}};var import_picocolors2=__toESM(require_picocolors(),1);import{existsSync,lstatSync,readdirSync as readdirSync3}from"fs";import{dirname as dirname2,join as join7}from"path";import{PassThrough}from"stream";import{styleText}from"util";function pathOptions(userInput,extensions){if(userInput==="")return[];let allowed=p=>!extensions?.length||extensions.some(ext=>p.toLowerCase().endsWith(ext.toLowerCase())),isDirectory=p=>{try{return lstatSync(p).isDirectory()}catch{return!1}},entriesOf=(dir,prefix)=>readdirSync3(dir).map(name=>join7(dir,name)).filter(full=>full.startsWith(prefix)).filter(full=>isDirectory(full)||allowed(full)).map(full=>isDirectory(full)?`${full}/`:full);try{let insideDir=userInput.length>1&&userInput.endsWith("/"),prefix=insideDir?userInput.slice(0,-1):userInput,values=[];insideDir||values.push(...entriesOf(dirname2(userInput),prefix)),isDirectory(userInput)&&values.push(...entriesOf(userInput,prefix));let options=[...new Set(values)].map(value=>({value}));return existsSync(userInput)&&lstatSync(userInput).isFile()&&!options.some(o=>o.value===userInput)&&options.unshift({value:userInput}),options}catch{return[]}}var AUTOCOMPLETE_THRESHOLD=8;function cancelled(){fail(EXIT.CANCELLED,"CANCELLED","Cancelled.")}var SUBMIT_KEY="Ctrl-S",CTRL_S=19,TAB=9,TAB_SENTINEL_BYTE=28,TAB_SENTINEL="";function detabSentinel(text){return text.replaceAll(TAB_SENTINEL," ")}function rewriteSubmitKeys(chunk){let out=[];for(let byte of chunk)byte===CTRL_S?out.push(TAB):byte===TAB?out.push(TAB_SENTINEL_BYTE):out.push(byte);return Buffer.from(out)}function submitOnCtrlS(source=process.stdin){if(!source.isTTY)return;let proxy=new PassThrough,onData=chunk=>{proxy.write(rewriteSubmitKeys(chunk))};source.on("data",onData),source.resume();let restoreTty=()=>{source.isRaw&&source.setRawMode(!1)};process.once("exit",restoreTty);let input=Object.assign(proxy,{isTTY:!0,setRawMode(mode){return source.setRawMode(mode),input}});return{input,done:()=>{process.off("exit",restoreTty),source.off("data",onData),source.pause(),proxy.end()}}}var clackAdapter={async select(message,choices,opts){let clack=await import("./dist-A3XXQMMP.js"),options=choices.map(c=>({value:c.value,label:c.display??c.label,hint:c.hint,disabled:c.disabled})),initialValue=opts?.initial,result=choices.length>AUTOCOMPLETE_THRESHOLD?await clack.autocomplete({message,options,initialValue,maxItems:10,output:process.stderr}):await clack.select({message,options,initialValue,output:process.stderr});return clack.isCancel(result)&&cancelled(),result},async multiselect(message,choices,opts){let clack=await import("./dist-A3XXQMMP.js"),options=choices.map(c=>({value:c.value,label:c.display??c.label,hint:c.hint,disabled:c.disabled})),initialValues=opts?.initial,result=choices.length>AUTOCOMPLETE_THRESHOLD?await clack.autocompleteMultiselect({message,options,initialValues,required:!1,maxItems:10,output:process.stderr}):await clack.multiselect({message,options,initialValues,required:!1,output:process.stderr});return clack.isCancel(result)&&cancelled(),result},async confirm(message,initial=!1){let clack=await import("./dist-A3XXQMMP.js"),result=await clack.confirm({message,initialValue:initial,output:process.stderr});return clack.isCancel(result)&&cancelled(),result},async text(message,opts){let clack=await import("./dist-A3XXQMMP.js"),result=await clack.text({message,initialValue:opts?.initial,validate:v2=>v2||opts?.allowEmpty?void 0:"Required.",output:process.stderr});return clack.isCancel(result)&&cancelled(),result},async multiline(message,opts){let clack=await import("./dist-A3XXQMMP.js"),core=await import("./dist-UQEAKLYF.js"),{highlightWithCursor,insertCursor}=await import("./highlight-7NU3CBVT.js"),keys=submitOnCtrlS();try{let language=opts?.language,output=process.stderr,style=(format,text)=>styleText(format,text,{stream:output}),result=await new core.MultiLinePrompt({placeholder:opts?.placeholder,initialValue:opts?.initial,showSubmit:!0,validate:()=>{},output,...keys?{input:keys.input}:{},render(){let withGuide=clack.settings.withGuide,title=`${withGuide?`${style("gray",clack.S_BAR)}
43
+ `:""}${clack.symbol(this.state)} ${message}
44
+ `,placeholder=opts?.placeholder&&opts.placeholder.length>0?style("inverse",opts.placeholder[0])+style("dim",opts.placeholder.slice(1)):style(["inverse","hidden"],"_"),userInput=detabSentinel(this.userInput),input=userInput?language?highlightWithCursor(userInput,this.cursor,language):insertCursor(userInput,userInput,this.cursor):placeholder,value=detabSentinel(this.value??""),submit=`
45
+ ${style("dim",`${SUBMIT_KEY} to reach [ submit ], then enter`)}
46
+ ${style(this.focused==="submit"?"cyan":"dim","[ submit ]")}`;switch(this.state){case"error":{let prefix=`${style("yellow",clack.S_BAR)} `,body=withGuide?core.wrapTextWithPrefix(output,input,prefix):input;return`${title}${body}
47
+ ${style("yellow",clack.S_BAR_END)} ${style("yellow",this.error)}${submit}
48
+ `}case"submit":{let prefix=`${style("gray",clack.S_BAR)} `,body=withGuide?core.wrapTextWithPrefix(output,value,prefix,void 0,void 0,line=>style("dim",line)):value?style("dim",value):"";return`${title}${body}`}case"cancel":{let prefix=`${style("gray",clack.S_BAR)} `,body=withGuide?core.wrapTextWithPrefix(output,value,prefix,void 0,void 0,line=>style(["strikethrough","dim"],line)):value?style(["strikethrough","dim"],value):"";return`${title}${body}`}default:{let prefix=withGuide?`${style("cyan",clack.S_BAR)} `:"",end=withGuide?style("cyan",clack.S_BAR_END):"",body=withGuide?core.wrapTextWithPrefix(output,input,prefix):input;return`${title}${body}
49
+ ${end}${submit}
50
+ `}}}}).prompt();return clack.isCancel(result)&&cancelled(),detabSentinel(result??"")}finally{keys?.done()}},async path(message,opts){let clack=await import("./dist-A3XXQMMP.js"),result=await clack.autocomplete({message,maxItems:5,options(){return pathOptions(this.userInput,opts?.extensions)},initialUserInput:"",validate:value=>{if(!Array.isArray(value))return value?opts?.validate?.(String(value)):"Please select a path"},output:process.stderr});return clack.isCancel(result)&&cancelled(),typeof result=="string"?result:""},async password(message,opts){let clack=await import("./dist-A3XXQMMP.js"),result=await clack.password({message,validate:v2=>v2||opts?.allowEmpty?void 0:"Required.",output:process.stderr});return clack.isCancel(result)&&cancelled(),result},async spinner(label,work){let s=(await import("./dist-A3XXQMMP.js")).spinner({output:process.stderr});s.start(label);let previous=activeSpinner;activeSpinner={pause:()=>s.stop(""),resume:()=>s.start(label)};try{let result=await work();return s.stop(label),result}catch(err){throw s.stop(import_picocolors2.default.red(label)),err}finally{activeSpinner=previous}},note(message){console.error(isWarning(message)?import_picocolors2.default.yellow(message):import_picocolors2.default.dim(message))}},activeSpinner;async function suspendSpinner(fn){let spinner=activeSpinner;if(!spinner)return fn();activeSpinner=void 0,spinner.pause();try{return await fn()}finally{spinner.resume(),activeSpinner=spinner}}var adapter=clackAdapter;function prompts(){return adapter}async function withSpinner(label,work){return canPrompt()?adapter.spinner(label,work):work()}var RESOURCE_ID_FORMAT="a 26-character upper-case ULID",RESOURCE_ID_LENGTH=26,RESOURCE_ID_PATTERN=/^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$/;function resourceIdError(value,noun){let trimmed=value.trim();if(!trimmed)return`${noun} is required.`;let shown=noun.includes(`'${trimmed}'`)||noun.includes(`'${value}'`)?"":` \u2014 '${trimmed}'`,subject=shown===""?"it":`'${trimmed}'`;if(trimmed.length!==RESOURCE_ID_LENGTH){let plural5=trimmed.length===1?"character":"characters";return`${noun} is not ${RESOURCE_ID_FORMAT}${shown?`${shown} is`:" \u2014"} ${trimmed.length} ${plural5}.`}if(!RESOURCE_ID_PATTERN.test(trimmed))return/[a-z]/.test(trimmed)?`${noun} is not ${RESOURCE_ID_FORMAT} \u2014 ${subject} has lower-case characters.`:`${noun} is not ${RESOURCE_ID_FORMAT} \u2014 ${subject} has a character a ULID cannot contain.`}function assertResourceId(value,noun){let error51=resourceIdError(value,noun);return error51&&fail(EXIT.USAGE,"INVALID_ID",error51),value.trim()}var LOCK_ID_HEADER="x-sr-connect-workspace-lock-id",LOCK_EXPIRES_HEADER="x-sr-connect-workspace-lock-expires-at",LOCK_SAFETY_MS=6e4,MAX_LOCK_RETRIES=1,LOCKED_OPERATIONS=new Set(["PUT /v1/team/{teamId}/workspace/{workspaceId}","DELETE /v1/team/{teamId}/workspace/{workspaceId}","POST /v1/workspace/{workspaceId}/apiConnection","POST /v1/workspace/{workspaceId}/environment","PUT /v1/workspace/{workspaceId}/environment/{environmentId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}","POST /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}","POST /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}/default","POST /v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}","POST /v1/workspace/{workspaceId}/environment/{environmentId}/parameter","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/parameter/{parameterId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/parameter/{parameterId}","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/readme","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/release","POST /v1/workspace/{workspaceId}/environment/{environmentId}/script","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}","PUT /v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}","DELETE /v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}","POST /v1/workspace/{workspaceId}/package","PUT /v1/workspace/{workspaceId}/package/{packageId}","DELETE /v1/workspace/{workspaceId}/package/{packageId}","POST /v1/workspace/{workspaceId}/release","POST /v1/workspace/{workspaceId}/scheduledTrigger","POST /v1/workspace/{workspaceId}/sftp/temp","DELETE /v1/workspace/{workspaceId}/sftp/temp/{tempSftpAccessId}"]),locking=!0,explicit;function configureWorkspaceLocking(opts){locking=opts.enabled!==!1&&!truthy(process.env.SR_CONNECT_CLI_NO_LOCK)&&settingEnabled("workspaceLock");let fromFlag=opts.lockId!==void 0&&opts.lockId!=="",lockId=opts.lockId??process.env.SR_CONNECT_CLI_LOCK_ID;explicit=lockId&&lockId!==""?assertResourceId(lockId,fromFlag?"--lock-id":"SR_CONNECT_CLI_LOCK_ID"):void 0,notedForeignLock=!1}function truthy(value){return value===void 0?!1:!["","0","false","no","off"].includes(value.trim().toLowerCase())}function explicitLockId(){return explicit}var notedForeignLock=!1;function ownStoredLock(workspaceId,intent="take"){let stored=readWorkspaceLock(workspaceId);if(!stored)return;let me2=currentUsername();if(me2!==void 0&&stored.user!==me2){if(!notedForeignLock){notedForeignLock=!0;let outcome=intent==="take"?"taking a fresh one":"ignoring it";console.error(import_picocolors3.default.dim(`\u2139 The lock this shell recorded for the workspace belongs to ${stored.user} \u2014 ${outcome}.`))}return}return stored}function newLockId(){return ulid()}function lockedWorkspaceOf(method,schemaPath,pathParams){if(!LOCKED_OPERATIONS.has(`${method.toUpperCase()} ${schemaPath}`))return;let workspaceId=pathParams?.workspaceId;return typeof workspaceId=="string"&&workspaceId!==""?workspaceId:void 0}async function readLock(client,workspaceId){let{data,error:error51,response}=await client.GET("/v1/workspace/{workspaceId}/lock",{params:{path:{workspaceId}}});return response.ok&&data?{lock:data,status:response.status}:{status:response.status,error:error51}}async function takeLock(client,workspaceId,opts){let{data,error:error51,response}=await client.POST("/v1/workspace/{workspaceId}/lock",{params:{path:{workspaceId}},body:{lockId:opts.lockId,...opts.force?{force:!0}:{}}});return response.ok&&data?{lock:data,status:response.status}:response.status===409?{conflict:(error51&&"lockedBy"in error51?error51.lockedBy:void 0)??!0,status:409,error:error51}:{status:response.status,error:error51}}async function releaseLock(client,workspaceId,lockId){let{error:error51,response}=await client.DELETE("/v1/workspace/{workspaceId}/lock/{lockId}",{params:{path:{workspaceId,lockId}}});return{ok:response.ok,status:response.status,error:error51}}var freshlyTaken=new Set;function freshKey(workspaceId,lockId){return`${workspaceId}\0${lockId}`}function noteWorkspaceLockUsed(workspaceId,lockId){freshlyTaken.delete(freshKey(workspaceId,lockId))}async function releaseUnusedWorkspaceLock(client,workspaceId,lockId){if(!freshlyTaken.delete(freshKey(workspaceId,lockId)))return;(await releaseLock(client,workspaceId,lockId).catch(()=>({ok:!1}))).ok&&forgetWorkspaceLock(workspaceId)}async function ensureWorkspaceLock(client,workspaceId){if(!locking)return;let stored=ownStoredLock(workspaceId),forced=explicitLockId();if(!forced&&stored&&Date.parse(stored.expiresAt)-Date.now()>LOCK_SAFETY_MS)return stored.lockId;let lockId=forced??stored?.lockId??newLockId();return suspendSpinner(async()=>{let result=await withSpinner("Taking the workspace lock",()=>takeLock(client,workspaceId,{lockId}));if(result.conflict){let holder=result.conflict===!0?void 0:result.conflict;canPrompt()||lockedFail(holder,workspaceId,void 0,await currentUser(client));let answer=await askLockConflict(holder,await currentUser(client));if(answer==="cancel"&&fail(EXIT.CANCELLED,"CANCELLED","Cancelled."),answer==="unlocked")return;result=await withSpinner("Taking the workspace lock",()=>takeLock(client,workspaceId,{lockId,force:!0}))}return result.lock?(forced||storeTaken(workspaceId,lockId,result.lock.expiresAt),!forced&&!stored&&freshlyTaken.add(freshKey(workspaceId,lockId)),lockId):takeFail(result,workspaceId)})}async function recoverLostLock(client,workspaceId,attempt2){attempt2>=MAX_LOCK_RETRIES&&lockLostFail(workspaceId);let previous=ownStoredLock(workspaceId)?.lockId;forgetWorkspaceLock(workspaceId);let lockId=explicitLockId()??previous??newLockId();return suspendSpinner(async()=>{let asked=!1,result=await withSpinner("Taking the workspace lock again",()=>takeLock(client,workspaceId,{lockId}));if(result.conflict){let holder=result.conflict===!0?void 0:result.conflict;canPrompt()||lockedFail(holder,workspaceId,void 0,await currentUser(client)),asked=!0;let answer=await askLockConflict(holder,await currentUser(client),{lost:!0});if(answer==="cancel"&&fail(EXIT.CANCELLED,"CANCELLED","Cancelled."),answer==="unlocked")return{lockId:void 0};result=await withSpinner("Taking the workspace lock",()=>takeLock(client,workspaceId,{lockId,force:!0}))}return result.lock?(explicitLockId()===void 0&&storeTaken(workspaceId,lockId,result.lock.expiresAt),asked||console.error(import_picocolors3.default.dim("The workspace lock had lapsed \u2014 taken again and the change re-sent.")),{lockId}):takeFail(result,workspaceId)})}function takeFail(result,workspaceId){let message=result.error?.errorMessage??`Request failed with HTTP status ${result.status}.`;result.status===401&&fail(EXIT.UNAUTHENTICATED,"INVALID_CREDENTIALS",message,{status:401}),result.status===404&&fail(EXIT.NOT_FOUND,"NOT_FOUND",message,{status:404}),result.status===403&&fail(EXIT.API_ERROR,"FORBIDDEN",message,{status:403,...forbiddenHint(message)}),fail(EXIT.API_ERROR,"WORKSPACE_LOCK_FAILED",`Could not take the workspace lock: ${message}`,{status:result.status,hint:`Check the lock with \`${CLI} workspace-lock check -w ${workspaceId}\`, or pass --no-lock to write without one.`})}function holderLabel(holder){if(!holder)return"another session";let name=personName(holder);return holder.email&&name!==holder.email?`${name} (${holder.email})`:name||"a session"}function sourceLabel(source){return source==="WEBAPP"?"the web application":"the API"}async function askLockConflict(holder,me2,opts={}){let self2=!!(holder?.userId&&me2?.id&&holder.userId===me2.id),webapp=holder?.source==="WEBAPP",evicts=webapp?"loses edit control immediately and is warned about unsaved changes":"stops being able to write to this workspace",lost=opts.lost===!0,stillReady=" Nothing was written \u2014 the change is still ready to send.";self2&&webapp?prompts().note(lost?`The lock this shell held is gone, and you now have this workspace open in the web application.${stillReady}`:"You have this workspace open in the web application, and that session holds the lock."):self2?prompts().note(lost?`The lock this shell held is gone, and another session of yours has taken it through the API. Nothing is unsaved on the API side.${stillReady}`:"Another session of yours holds this workspace, taken through the API. Nothing is unsaved on the API side."):prompts().note(lost?`The lock this shell held is gone and ${holderLabel(holder)} is now editing this workspace through ${sourceLabel(holder?.source)}.${stillReady}`:`${holderLabel(holder)} is editing this workspace through ${sourceLabel(holder?.source)}.`);let take={value:"force",label:lost?"Take the lock and send the change":self2&&webapp?"Take the lock here":"Take the lock",hint:self2&&webapp?`that browser tab ${evicts}`:`${self2?"that session":holderLabel(holder)} ${evicts}`},cancel={value:"cancel",label:self2&&webapp?"Cancel \u2014 the browser tab keeps editing":"Cancel \u2014 leave them to it"},unlocked={value:"unlocked",label:lost?"Send the change without the lock":"Continue without the lock",hint:"the change is applied anyway, and may overwrite theirs"},rest=opts.allowUnlocked===!1?[]:[unlocked],choices=self2&&!webapp?[take,cancel,...rest]:[cancel,take,...rest];return await prompts().select("How would you like to proceed?",choices,choices[0]?{initial:choices[0].value}:{})}function lockedFail(holder,workspaceId,hint,me2){let self2=!!(holder?.userId&&me2?.id&&holder.userId===me2.id),webapp=holder?.source==="WEBAPP",force=`\`${CLI} workspace-lock take -w ${workspaceId} --force\``;self2&&!webapp&&fail(EXIT.API_ERROR,"WORKSPACE_LOCKED","Workspace is locked by another session of yours, taken through the API. Nothing was written.",{status:409,hint:hint??`Nothing is unsaved on the API side, so taking it back costs nobody anything: ${force}.`}),self2&&webapp&&fail(EXIT.API_ERROR,"WORKSPACE_LOCKED","Workspace is locked by your own session in the web application. Nothing was written.",{status:409,hint:hint??`That browser tab loses edit control, and any unsaved changes with it: ${force}.`});let who=holder?`Held by ${holderLabel(holder)} through ${sourceLabel(holder.source)}.`:"Another session holds it.";fail(EXIT.API_ERROR,"WORKSPACE_LOCKED",`Workspace is locked by another session. ${who} Nothing was written.`,{status:409,hint:hint??`Take it anyway with ${force}, or see who holds it with \`${CLI} workspace-lock check -w ${workspaceId}\`.`})}function releaseFail(holder,workspaceId,lockId,me2){let self2=!!(holder?.userId&&me2?.id&&holder.userId===me2.id),check2=`\`${CLI} workspace-lock check -w ${workspaceId}\``;self2&&fail(EXIT.API_ERROR,"WORKSPACE_LOCK_NOT_HELD",`Lock ${lockId} does not hold this workspace: another session of yours does, under a different lock ID. Nothing was released.`,{status:409,hint:`Release it from the session that took it, or take it here with \`${CLI} workspace-lock take -w ${workspaceId} --force\` and release that.`});let who=holder?`${holderLabel(holder)} holds it through ${sourceLabel(holder.source)}`:"another session holds it";fail(EXIT.API_ERROR,"WORKSPACE_LOCK_NOT_HELD",`Lock ${lockId} does not hold this workspace: ${who}. Nothing was released.`,{status:409,hint:`Only the session that took a lock can release it. See who holds it with ${check2}.`})}var LOCK_LOST_MESSAGE="workspace lock is no longer held";async function isLockConflict(response){if(response.status!==409)return!1;try{let body=await response.clone().json();return body.lockedBy!==void 0&&body.lockedBy!==null?!0:typeof body.errorMessage=="string"&&body.errorMessage.toLowerCase().includes(LOCK_LOST_MESSAGE)}catch{return!1}}function lockLostFail(workspaceId){fail(EXIT.API_ERROR,"WORKSPACE_LOCK_LOST","The workspace lock this shell held is gone \u2014 it was taken by another session, or it lapsed. Nothing was written.",{status:409,hint:`Take it again with \`${CLI} workspace-lock take -w ${workspaceId}\` and retry.`})}function storeTaken(workspaceId,lockId,expiresAt){storeWorkspaceLock(workspaceId,{lockId,expiresAt,user:currentUsername()??""})||unstoredLockWarning(workspaceId,lockId)}function unstoredLockWarning(workspaceId,lockId){warnLine(`\u26A0 Workspace lock ${lockId} taken, but this shell has no identity to remember it in.
51
+ Pass --lock-id ${lockId} on later commands to keep using it, or release it with:
52
+ ${CLI} workspace-lock release -w ${workspaceId} --lock-id ${lockId}
53
+ Otherwise it lapses on its own. Set SR_CONNECT_CLI_SESSION_ID to make this shell rememberable.`)}function renewStoredLock(workspaceId,lockId,expiresAt){if(lockId===explicitLockId())return;let stored=ownStoredLock(workspaceId,"read");!stored||stored.lockId!==lockId||stored.expiresAt!==expiresAt&&storeWorkspaceLock(workspaceId,{...stored,expiresAt})}function expiryCell(expiresAt){let ms=Date.parse(expiresAt)-Date.now();if(!Number.isFinite(ms))return expiresAt;if(ms<=0)return`${expiresAt} (lapsed)`;let minutes=Math.round(ms/6e4);return`${expiresAt} (in ${minutes<1?"under a minute":`${minutes} minute${minutes===1?"":"s"}`})`}function holderCell(holder,me2){let mine=me2?.id&&holder.userId===me2.id;return`${holderLabel(holder)}${mine?" \u2014 you":""}`}var MAX_RETRIES=3,RETRYABLE=new Set([429,503]);async function fetchWithRetry(input){let attempt2=0;for(;;){let request=input.clone(),record4=recordingEnabled()?await captureRequest(request,attempt2):void 0,response;try{response=await fetch(request)}catch(err){record4?.failed(err),fail(EXIT.API_ERROR,"NETWORK_ERROR",`Could not reach ${hostOf(request.url)}: ${describeError(err)}`,{hint:`Check the instance is right (--instance, SR_CONNECT_CLI_INSTANCE, or \`${CLI} auth login\`) and reachable from here \u2014 an internal deployment may need a VPN.`})}let retrying=RETRYABLE.has(response.status)&&attempt2<MAX_RETRIES,delayMs=retrying?retryDelay(response,attempt2):void 0;if(record4&&await record4.finished(response,delayMs),!retrying)return response;let cause=response.status===429?"Rate limited by the API":"The API could not reach its database";noteLine(import_picocolors4.default.dim(`${cause} \u2014 retrying in ${Math.round((delayMs??0)/100)/10}s.`)),await new Promise(resolve8=>setTimeout(resolve8,delayMs)),attempt2+=1}}function hostOf(url2){try{return new URL(url2).host}catch{return url2}}function retryDelay(response,attempt2){let retryAfter=Number(response.headers.get("retry-after"));return Number.isFinite(retryAfter)&&retryAfter>0?retryAfter*1e3:1e3*2**attempt2}async function captureRequest(request,attempt2){let started=Date.now(),ts=new Date(started).toISOString(),reqText="";try{reqText=await request.clone().text()}catch{}let base={ts,kind:"api",method:request.method,url:request.url,attempt:attempt2,reqBytes:Buffer.byteLength(reqText),...reqText===""?{}:{reqBody:sanitizeBody(reqText)}};return{async finished(response,retryAfterMs){let resText="";try{resText=await response.clone().text()}catch{}recordApiCall({...base,ms:Date.now()-started,status:response.status,resBytes:Buffer.byteLength(resText),...resText===""?{}:{resBody:sanitizeBody(resText)},...retryAfterMs===void 0?{}:{retryAfterMs},resHeaders:pickHeaders(response.headers)})},failed(err){recordApiCall({...base,ms:Date.now()-started,resBytes:0,error:describeError(err)})}}}function requireInstance(flag){let instance4=resolveInstance(flag);return instance4||fail(EXIT.USAGE,"INSTANCE_REQUIRED",`No instance configured. Pass --instance ${INSTANCE_FORMAT}, set SR_CONNECT_CLI_INSTANCE, or run \`${CLI} auth login\`.`),instance4}var warnedInsecure=!1;function warnIfInsecure(instance4){if(warnedInsecure)return;let warning=insecureInstanceWarning(instance4);warning&&(warnedInsecure=!0,warnLine(warning))}var commandPath="";function setCommandPath(path2){commandPath=path2}function identityHeaders(){let major=nodeMajor();return{"user-agent":USER_AGENT,"x-sr-connect-cli-version":VERSION,"x-sr-connect-cli-interactive":String(canPrompt()),"x-sr-connect-cli-run-id":RUN_ID,...isAgent()?{"x-sr-connect-agent":"true"}:{},...commandPath===""?{}:{"x-sr-connect-cli-command":commandPath},...major===void 0?{}:{"x-sr-connect-cli-node":String(major)}}}async function apiClient(instanceFlag2,opts){let creds=await requireCredentials(),instance4=requireInstance(instanceFlag2);warnIfInsecure(instance4);let client=createClient({baseUrl:baseUrl(instance4),headers:{Authorization:basicAuthHeader(creds),...identityHeaders()},fetch:fetchWithRetry});return opts?.versionGate!==!1&&await assertSupportedVersion(client),client.use({async onRequest({request,schemaPath,params}){let workspaceId=lockedWorkspaceOf(request.method,schemaPath,params.path);if(workspaceId===void 0)return;let lockId=await ensureWorkspaceLock(client,workspaceId);if(lockId!==void 0)return request.headers.set(LOCK_ID_HEADER,lockId),request},async onResponse({request,response,schemaPath,params}){let workspaceId=lockedWorkspaceOf(request.method,schemaPath,params.path),lockId=request.headers.get(LOCK_ID_HEADER);if(workspaceId===void 0||!lockId)return;let renewed=response.headers.get(LOCK_EXPIRES_HEADER);if(renewed&&renewStoredLock(workspaceId,lockId,renewed),response.ok&&noteWorkspaceLockUsed(workspaceId,lockId),response.status!==409){response.status>=400&&response.status<500&&await releaseUnusedWorkspaceLock(client,workspaceId,lockId);return}if(!await isLockConflict(response))return;let current=response;for(let attempt2=0;await isLockConflict(current);attempt2+=1){let recovery=await recoverLostLock(client,workspaceId,attempt2),retry=request.clone();recovery.lockId===void 0?retry.headers.delete(LOCK_ID_HEADER):retry.headers.set(LOCK_ID_HEADER,recovery.lockId),current=await fetchWithRetry(retry);let again=current.headers.get(LOCK_EXPIRES_HEADER);again&&recovery.lockId&&renewStoredLock(workspaceId,recovery.lockId,again)}return current}}),client}var FORBIDDEN_HINTS=[{match:/not allowed to edit workspace/i,hint:`A private workspace is editable by the team's admins alone \u2014 ${CLI} workspace get reports its visibility.`},{match:/not allowed to read workspace/i,hint:`A private workspace is visible to the team's admins alone \u2014 ${CLI} workspace list shows the ones you can see.`}];function forbiddenHint(message){let known=FORBIDDEN_HINTS.find(entry2=>entry2.match.test(message));return known?{hint:known.hint}:void 0}function apiFail(status,body){let error51=body,message=error51?.errorMessage??error51?.message??`Request failed with HTTP status ${status}.`;status===401&&fail(EXIT.UNAUTHENTICATED,"INVALID_CREDENTIALS",message,{status}),status===404&&fail(EXIT.NOT_FOUND,"NOT_FOUND",message,{status}),status===503&&fail(EXIT.API_ERROR,"SERVICE_UNAVAILABLE",message,{status,hint:"The request never ran and nothing changed, so it is safe to send again."});let code=status===403?"FORBIDDEN":status===400?"BAD_REQUEST":status===429?"RATE_LIMITED":"API_ERROR";fail(EXIT.API_ERROR,code,message,{status,...status===403?forbiddenHint(message):void 0})}import{readFileSync as readFileSync7,statSync as statSync3}from"fs";import{basename}from"path";var agentic=!0,offSource;function configureAgenticFeedback(opts){let off=process.env.SR_CONNECT_CLI_NO_AGENTIC_FEEDBACK,flagOff=opts.enabled===!1,envOff=!(off===void 0||/^(0|false|no|off|)$/i.test(off.trim())),storedOn=settingEnabled("agenticFeedback");agentic=!flagOff&&!envOff&&storedOn,offSource=flagOff?"flag":envOff?"env":storedOn?void 0:"stored"}function agenticFeedbackEnabled(){return agentic}function assertAgenticFeedbackAllowed(){agentic||canPrompt()||fail(EXIT.USAGE,"AGENTIC_FEEDBACK_DISABLED","Agentic feedback is turned off, so feedback can only be posted through the interactive flow.",{hint:agenticFeedbackHint()})}function agenticFeedbackHint(){let interactive=`run \`${CLI} feedback post\` on a terminal`;return offSource==="flag"?`Drop --no-agentic-feedback, or ${interactive}.`:offSource==="env"?`Unset SR_CONNECT_CLI_NO_AGENTIC_FEEDBACK, or ${interactive}.`:`Turn the switch back on with \`${CLI} cli settings\`, or ${interactive}.`}var MAX_FEEDBACK_MESSAGE=5e3,MAX_FEEDBACK_EMAIL=100,MAX_ATTACHMENTS=10,MAX_ATTACHMENT_NAME=500,MAX_ATTACHMENT_BYTES=1024*1024,MAX_ATTACHMENTS_BYTES=4*1024*1024,ATTACHMENT_NAME_FORMAT="letters, digits, underscores, spaces, periods, hyphens and parentheses, starting with a letter, digit or underscore",ATTACHMENT_NAME_PATTERN=/^[A-Za-z0-9_][A-Za-z0-9_ .()-]*$/;function attachmentTooLarge(name,bytes){let size=sizesAgainstCap(bytes,MAX_ATTACHMENT_BYTES);return`"${name}" is ${size.actual} \u2014 one attachment can be at most ${size.cap}.`}function normalizeFeedbackMessage(message){return message.trim()}function feedbackMessageError(message){let normalized=normalizeFeedbackMessage(message);if(!normalized)return"A feedback message is required.";if(normalized.length>MAX_FEEDBACK_MESSAGE)return`A feedback message can be at most ${MAX_FEEDBACK_MESSAGE} characters (that one is ${normalized.length}).`}function assertFeedbackMessage(message){let error51=feedbackMessageError(message);return error51&&fail(EXIT.USAGE,"INVALID_FEEDBACK_MESSAGE",error51),normalizeFeedbackMessage(message)}function normalizeFeedbackEmail(email3){return email3.trim()}function feedbackEmailError(email3){let normalized=normalizeFeedbackEmail(email3);if(!normalized)return"A reply address cannot be empty.";if(normalized.length>MAX_FEEDBACK_EMAIL)return`A reply address can be at most ${MAX_FEEDBACK_EMAIL} characters (that one is ${normalized.length}).`;let at2=separatorAt(normalized);if(at2===void 0||at2===0||at2===normalized.length-1)return`A reply address needs a local part and a domain either side of one @ \u2014 '${email3}' does not.`}function separatorAt(value){let quoted=!1,found2;for(let i=0;i<value.length;i+=1){let char=value[i];if(quoted&&char==="\\"){i+=1;continue}if(char==='"'){quoted=!quoted;continue}if(char==="@"&&!quoted){if(found2!==void 0)return;found2=i}}return quoted?void 0:found2}function assertFeedbackEmail(email3){let error51=feedbackEmailError(email3);return error51&&fail(EXIT.USAGE,"INVALID_EMAIL",error51),normalizeFeedbackEmail(email3)}function attachmentNameError(name){let normalized=name.trim();if(!normalized)return"An attachment file name is required.";if(normalized.length>MAX_ATTACHMENT_NAME)return`An attachment file name can be at most ${MAX_ATTACHMENT_NAME} characters (that one is ${normalized.length}).`;if(!ATTACHMENT_NAME_PATTERN.test(normalized))return`An attachment file name can contain ${ATTACHMENT_NAME_FORMAT} \u2014 "${normalized}" cannot be used as it is.`}function assertAttachmentName(name){let error51=attachmentNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_ATTACHMENT_NAME",error51),name.trim()}function suggestAttachmentName(name){let cleaned=name.trim().replaceAll(/[^A-Za-z0-9_ .()-]/g,"_").replace(/^[^A-Za-z0-9_]+/,"");return attachmentNameError(cleaned)?void 0:cleaned}function attachmentSize(path2){let stats=statOrFail(path2);return stats.isFile()||fail(EXIT.USAGE,"INVALID_FILE",`${path2} is not a file.`),stats.size}function statOrFail(path2){try{return statSync3(path2)}catch{fail(EXIT.USAGE,"INVALID_FILE",`${path2} could not be read.`)}}function attachmentFileSize(path2){try{let stats=statSync3(path2);return stats.isFile()?stats.size:void 0}catch{return}}function readAttachment(path2,name){let bytes=attachmentSize(path2);bytes>MAX_ATTACHMENT_BYTES&&fail(EXIT.USAGE,"ATTACHMENT_TOO_LARGE",attachmentTooLarge(name??basename(path2),bytes));let content;try{content=readFileSync7(path2)}catch{fail(EXIT.USAGE,"INVALID_FILE",`${path2} could not be read.`)}return{fileName:(name??basename(path2)).trim(),content:content.toString("base64")}}function base64Bytes(content){let clean=content.replace(/\s/g,"");if(!clean)return 0;let padding2=clean.endsWith("==")?2:clean.endsWith("=")?1:0;return Math.max(0,Math.floor(clean.length*3/4)-padding2)}function assertAttachments(attachments){attachments.length>MAX_ATTACHMENTS&&fail(EXIT.USAGE,"TOO_MANY_ATTACHMENTS",`Up to ${MAX_ATTACHMENTS} files can be attached to one submission (that is ${attachments.length}).`);let seen=new Set,total=0,normalized=[];for(let attachment of attachments){let fileName=assertAttachmentName(attachment.fileName);seen.has(fileName)&&fail(EXIT.USAGE,"DUPLICATE_ATTACHMENT",`Two attachments are named "${fileName}" \u2014 the API refuses a submission with a repeated file name rather than overwriting one of them.`),seen.add(fileName);let bytes=base64Bytes(attachment.content);bytes>MAX_ATTACHMENT_BYTES&&fail(EXIT.USAGE,"ATTACHMENT_TOO_LARGE",attachmentTooLarge(fileName,bytes)),total+=bytes,normalized.push({fileName,content:attachment.content})}if(total>MAX_ATTACHMENTS_BYTES){let totalSize=sizesAgainstCap(total,MAX_ATTACHMENTS_BYTES);fail(EXIT.USAGE,"ATTACHMENTS_TOO_LARGE",`The attachments total ${totalSize.actual} \u2014 one submission can carry at most ${totalSize.cap}.`)}return normalized}function C(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var R=C();function j(l3){R=l3}var z={exec:()=>null};function A(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function k(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let i=typeof r=="string"?r:r.source;return i=i.replace(m.caret,"$1"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Te=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:A(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:A(l3=>new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:A(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:A(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:A(l3=>new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:A(l3=>new RegExp(`^ {0,${l3}}>`))},Oe=/^(?:[ \t]*(?:\n|$))+/,we=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,q=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,U=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=k(oe).replace(/bull/g,U).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Se=k(oe).replace(/bull/g,U).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),K=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,_e=/^[^\n]+/,W=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$e=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",W).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Le=k(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,U).getRegex(),Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",X=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Me=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",X).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=l3=>k(K).replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex(),ze=le(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ee=le(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ce=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ee).getRegex(),J={blockquote:Ce,code:we,def:$e,fences:ye,heading:Pe,hr:q,html:Me,lheading:ae,list:Le,newline:Oe,paragraph:ze,table:z,text:_e},se=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex(),Ae={...J,lheading:Se,table:se,paragraph:k(K).replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex()},Ie={...J,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",X).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:z,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(K).replace("hr",q).replace("heading",` *#{1,6} *[^
54
+ ]`).replace("lheading",ae).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Be=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,De=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,pe=/^( {2,}|\\)\n(?!\s*$)/,qe=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_=/[\p{P}\p{S}]/u,I=/[\s\p{P}\p{S}]/u,v=/[^\s\p{P}\p{S}]/u,ve=k(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,I).getRegex(),He=/[\p{Pi}\p{Ps}"']/u,ue=/(?!~)[\p{P}\p{S}]/u,Ze=/(?!~)[\s\p{P}\p{S}]/u,Ge=/(?:[^\s\p{P}\p{S}]|~)/u,Qe=k(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Te?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ne=k(ce,"u").replace(/punct/g,_).getRegex(),je=k(ce,"u").replace(/punct/g,ue).getRegex(),Fe=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,Ue=k(Fe,"u").replace(/openQuote/g,He).replace(/punct/g,_).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ke=k(he,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,I).replace(/punct/g,_).getRegex(),We=k(he,"gu").replace(/notPunctSpace/g,Ge).replace(/punctSpace/g,Ze).replace(/punct/g,ue).getRegex(),Xe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Je=k(Xe,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,I).replace(/punct/g,_).getRegex(),Ve=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,I).replace(/punct/g,_).getRegex(),Ye="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",et=k(Ye,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,I).replace(/punct/g,_).getRegex(),tt=k(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_).getRegex(),nt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",rt=k(nt,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,I).replace(/punct/g,_).getRegex(),st=k(/\\(punct)/,"gu").replace(/punct/g,_).getRegex(),it=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ot=k(X).replace("(?:-->|$)","-->").getRegex(),at=k("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",ot).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),G=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,lt=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",G).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),de=k(/^!?\[(label)\]\[(ref)\]/).replace("label",G).replace("ref",W).getRegex(),ke=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",W).getRegex(),pt=k("reflink|nolink(?!\\()","g").replace("reflink",de).replace("nolink",ke).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,V={_backpedal:z,anyPunctuation:st,autolink:it,blockSkip:Qe,br:pe,code:De,del:z,delLDelim:z,delRDelim:z,emStrongLDelim:Ne,emStrongRDelimAst:Ke,emStrongRDelimUnd:Ve,escape:Be,link:lt,nolink:ke,punctuation:ve,reflink:de,reflinkSearch:pt,tag:at,text:qe,url:z},ut={...V,emStrongLDelim:Ue,emStrongRDelimAst:Je,emStrongRDelimUnd:et,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",G).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",G).getRegex()},F={...V,emStrongRDelimAst:We,emStrongLDelim:je,delLDelim:tt,delRDelim:rt,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ie).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:k(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ie).getRegex()},ct={...F,br:k(pe).replace("{2,}","*").getRegex(),text:k(F.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},H={normal:J,gfm:Ae,pedantic:Ie},B={normal:V,gfm:F,breaks:ct,pedantic:ut},ht={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ge=l3=>ht[l3];function O(l3,e){if(e){if(m.escapeTest.test(l3))return l3.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l3))return l3.replace(m.escapeReplaceNoEncode,ge);return l3}function Y(l3){try{l3=encodeURI(l3).replace(m.percentDecode,"%")}catch{return null}return l3}function ee(l3,e){let t=l3.replace(m.findPipe,(r,i,o)=>{let p=!1,a=i;for(;--a>=0&&o[a]==="\\";)p=!p;return p?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(m.slashPipe,"|");return n}function $(l3,e,t){let n=l3.length;if(n===0)return"";let s=0;for(;s<n;){let r=l3.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l3.slice(0,n-s)}function te(l3){let e=l3.split(`
55
+ `),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
56
+ `)}function fe(l3,e){if(l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function me(l3,e=0){let t=e,n="";for(let s of l3)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function xe(l3,e,t,n,s){let r=e.href,i=e.title||null,o=l3[1].replace(s.other.outputLinkReplace,"$1");n.state.inLink=!0;let p={type:l3[0].charAt(0)==="!"?"image":"link",raw:t,href:r,title:i,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,p}function dt(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`
57
+ `).map(r=>{let i=r.match(t.other.beginningSpace);if(i===null)return r;let[o]=i;return o.length>=s.length?r.slice(s.length):r}).join(`
58
+ `)}var y=class{options;rules;lexer;constructor(e){this.options=e||R}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:te(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=dt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=$(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:$(t[0],`
59
+ `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:$(t[0],`
60
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=$(t[0],`
61
+ `).split(`
62
+ `),s="",r="",i=[];for(;n.length>0;){let o=!1,p=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))p.push(n[a]),o=!0;else if(!o)p.push(n[a]);else break;n=n.slice(a);let u=p.join(`
63
+ `),c=u.replace(this.rules.other.blockquoteSetextReplace,`
64
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
65
+ ${u}`:u,r=r?`${r}
66
+ ${c}`:c;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=h,n.length===0)break;let d=i.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let T=d,g=n.join(`
67
+ `),w=T.raw+`
68
+ `+g.replace(this.rules.other.blockquoteSetextReplace2,""),M=this.blockquote(w);i[i.length-1]=M,s=`${s}
69
+ ${g}`,r=r.substring(0,r.length-T.text.length)+M.text;break}else if(d?.type==="list"){let T=d,g=T.raw+`
70
+ `+n.join(`
71
+ `),w=this.list(g);i[i.length-1]=w,s=s.substring(0,s.length-d.raw.length)+w.raw,r=r.substring(0,r.length-T.raw.length)+w.raw,n=g.substring(i.at(-1).raw.length).split(`
72
+ `);continue}}return{type:"blockquote",raw:s,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let a=!1,u="",c="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let h=me(t[2].split(`
73
+ `,1)[0],t[1].length),d=e.split(`
74
+ `,1)[0],T=!h.trim(),g=0;if(this.options.pedantic?(g=2,c=h.trimStart()):T?g=t[1].length+1:(g=h.search(this.rules.other.nonSpaceChar),g=g>4?1:g,c=h.slice(g),g+=t[1].length),T&&this.rules.other.blankLine.test(d)&&(u+=d+`
75
+ `,e=e.substring(d.length+1),a=!0),!a){let w=this.rules.other.nextBulletRegex(g),M=this.rules.other.hrRegex(g),ne=this.rules.other.fencesBeginRegex(g),re=this.rules.other.headingBeginRegex(g),be=this.rules.other.htmlBeginRegex(g),Re=this.rules.other.blockquoteBeginRegex(g);for(;e;){let N=e.split(`
76
+ `,1)[0],D;if(d=N,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),D=d):D=d.replace(this.rules.other.tabCharGlobal," "),ne.test(d)||re.test(d)||be.test(d)||Re.test(d)||w.test(d)||M.test(d))break;if(D.search(this.rules.other.nonSpaceChar)>=g||!d.trim())c+=`
77
+ `+D.slice(g);else{if(T||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ne.test(h)||re.test(h)||M.test(h))break;c+=`
78
+ `+d}T=!d.trim(),u+=N+`
79
+ `,e=e.substring(N.length+1),h=D.slice(g)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(o=!0)),r.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),r.raw+=u}let p=r.items.at(-1);if(p)p.raw=p.raw.trimEnd(),p.text=p.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items){this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]);let u=a.tokens[0];if(a.task&&(u?.type==="text"||u?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),u.raw=u.raw.replace(this.rules.other.listReplaceTask,""),u.text=u.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let h={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};a.checked=h.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=h.raw+a.tokens[0].raw,a.tokens[0].text=h.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(h)):a.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):a.tokens.unshift(h)}}else a.task&&(a.task=!1);if(!r.loose){let c=a.tokens.filter(d=>d.type==="space"),h=c.length>0&&c.some(d=>this.rules.other.anyLine.test(d.raw));r.loose=h}}if(r.loose)for(let a of r.items){a.loose=!0;for(let u of a.tokens)u.type==="text"&&(u.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=te(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:$(t[0],`
80
+ `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ee(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
81
+ `):[],i={type:"table",raw:$(t[0],`
82
+ `),header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of r)i.rows.push(ee(o,i.header.length).map((p,a)=>({text:p,tokens:this.lexer.inline(p),header:!1,align:i.align[a]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:$(t[0],`
83
+ `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
84
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=$(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=fe(t[2],"()");if(i===-2)return;if(i>-1){let p=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,p).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),xe(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return xe(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...s[0]].length-1,o,p,a=i,u=0,c=s[0][0],h=n===c,d=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(s=d.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(p=[...o].length,s[3]||s[4]){a+=p;continue}else if(s[5]||s[6]){if(i%3&&!((i+p)%3)){u+=p;continue}if(h)break}if(a-=p,a>0)continue;p=Math.min(p,p+a+u);let T=[...s[0]][0].length,g=e.slice(0,i+s.index+T+p);if(Math.min(i,p)%2){let M=g.slice(1,-1);return{type:"em",raw:g,text:M,tokens:this.lexer.inlineTokens(M)}}let w=g.slice(2,-2);return{type:"strong",raw:g,text:w,tokens:this.lexer.inlineTokens(w)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...s[0]].length-1,o,p,a=i,u=this.rules.inline.delRDelim;for(u.lastIndex=0,t=t.slice(-1*e.length+i);(s=u.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(p=[...o].length,p!==i))continue;if(s[3]||s[4]){a+=p;continue}if(a-=p,a>0)continue;p=Math.min(p,p+a);let c=[...s[0]][0].length,h=e.slice(0,i+s.index+c+p),d=h.slice(i,-i);return{type:"del",raw:h,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||R,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:H.normal,inline:B.normal};this.options.pedantic?(t.block=H.pedantic,t.inline=B.pedantic):this.options.gfm&&(t.block=H.gfm,this.options.breaks?t.inline=B.breaks:t.inline=B.gfm),this.tokenizer.rules=t}static get rules(){return{block:H,inline:B}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,`
85
+ `),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(m.tabCharGlobal," ").replace(m.spaceLine,""));let s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(o=>(r=o.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let o=t.at(-1);r.raw.length===1&&o!==void 0?o.raw+=`
86
+ `:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
87
+ `)?"":`
88
+ `)+r.raw,o.text+=`
89
+ `+r.text,this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
90
+ `)?"":`
91
+ `)+r.raw,o.text+=`
92
+ `+r.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let o=1/0,p=e.slice(1),a;this.options.extensions.startBlock.forEach(u=>{a=u.call({lexer:this},p),typeof a=="number"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(i=e.substring(0,o+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let o=t.at(-1);n&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(`
93
+ `)?"":`
94
+ `)+r.raw,o.text+=`
95
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(`
96
+ `)?"":`
97
+ `)+r.raw,o.text+=`
98
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e;if(this.tokens.links){let o=Object.keys(this.tokens.links);o.length>0&&(n=n.replace(this.tokenizer.rules.inline.reflinkSearch,p=>o.includes(p.slice(p.lastIndexOf("[")+1,-1))?"["+"a".repeat(p.length-2)+"]":p))}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,"++"),n=n.replace(this.tokenizer.rules.inline.blockSkip,(o,p,a)=>{let u=a?a.length:0;return o.slice(0,u)+"["+"a".repeat(o.length-u-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,r="",i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(r=""),s=!1;let o;if(this.options.extensions?.inline?.some(a=>(o=a.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let a=t.at(-1);o.type==="text"&&a?.type==="text"?(a.raw+=o.raw,a.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,r)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e,n,r)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let p=e;if(this.options.extensions?.startInline){let a=1/0,u=e.slice(1),c;this.options.extensions.startInline.forEach(h=>{c=h.call({lexer:this},u),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(p=e.substring(0,a+1))}if(o=this.tokenizer.inlineText(p)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(r=o.raw.slice(-1)),s=!0;let a=t.at(-1);a?.type==="text"?(a.raw+=o.raw,a.text+=o.text):t.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},P=class{options;parser;constructor(e){this.options=e||R}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(m.notSpaceStart)?.[0],r=e.replace(m.endingNewline,"")+`
99
+ `;return s?'<pre><code class="language-'+O(s)+'">'+(n?r:O(r,!0))+`</code></pre>
100
+ `:"<pre><code>"+(n?r:O(r,!0))+`</code></pre>
101
+ `}blockquote({tokens:e}){return`<blockquote>
102
+ ${this.parser.parse(e)}</blockquote>
103
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
104
+ `}hr(e){return`<hr>
105
+ `}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o<e.items.length;o++){let p=e.items[o];s+=this.listitem(p)}let r=t?"ol":"ul",i=t&&n!==1?' start="'+n+'"':"";return"<"+r+i+`>
106
+ `+s+"</"+r+`>
107
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
108
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
109
+ `}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let s="";for(let r=0;r<e.rows.length;r++){let i=e.rows[r];n="";for(let o=0;o<i.length;o++)n+=this.tablecell(i[o]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
110
+ <thead>
111
+ `+t+`</thead>
112
+ `+s+`</table>
113
+ `}tablerow({text:e}){return`<tr>
114
+ ${e}</tr>
115
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
116
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${O(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=Y(e);if(r===null)return s;e=r;let i='<a href="'+e+'"';return t&&(i+=' title="'+O(t)+'"'),i+=">"+s+"</a>",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Y(e);if(r===null)return O(n);e=r;let i=`<img src="${e}" alt="${O(n)}"`;return t&&(i+=` title="${O(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:O(e.text)}},L=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},b=class l2{options;renderer;textRenderer;constructor(e){this.options=e||R,this.options.renderer=this.options.renderer||new P,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(e,t){return new l2(t).parse(e)}static parseInline(e,t){return new l2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.extensions?.renderers?.[s.type]){let i=s,o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(i.type)){t+=o||"";continue}}let r=s;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragraph":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.text(r);break}default:{let i='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let o=this.options.extensions.renderers[r.type].call({parser:this},r);if(o!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){n+=o||"";continue}}let i=r;switch(i.type){case"escape":{n+=t.text(i);break}case"html":{n+=t.html(i);break}case"link":{n+=t.link(i);break}case"image":{n+=t.image(i);break}case"checkbox":{n+=t.checkbox(i);break}case"strong":{n+=t.strong(i);break}case"em":{n+=t.em(i);break}case"codespan":{n+=t.codespan(i);break}case"br":{n+=t.br(i);break}case"del":{n+=t.del(i);break}case"text":{n+=t.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}},S=class{options;block;constructor(e){this.options=e||R}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?x.lex:x.lexInline}provideParser(e=this.block){return e?b.parse:b.parseInline}},Z=class{defaults=C();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b;Renderer=P;TextRenderer=L;Lexer=x;Tokenizer=y;Hooks=S;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of r.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let r=s;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(i=>{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let p=r.renderer.apply(this,o);return p===!1&&(p=i.apply(this,o)),p}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new P(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,p=n.renderer[o],a=r[o];r[o]=(...u)=>{let c=p.apply(r,u);return c===!1&&(c=a.apply(r,u)),c||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new y(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,p=n.tokenizer[o],a=r[o];r[o]=(...u)=>{let c=p.apply(r,u);return c===!1&&(c=a.apply(r,u)),c}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new S;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,p=n.hooks[o],a=r[o];S.passThroughHooks.has(i)?r[o]=u=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await p.call(r,u);return a.call(r,h)})();let c=p.call(r,u);return a.call(r,c)}:r[o]=(...u)=>{if(this.defaults.async)return(async()=>{let h=await p.apply(r,u);return h===!1&&(h=await a.apply(r,u)),h})();let c=p.apply(r,u);return c===!1&&(c=a.apply(r,u)),c}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let p=[];return p.push(i.call(this,o)),r&&(p=p.concat(r.call(this,o))),p}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let p=i.hooks?await i.hooks.preprocess(n):n,u=await(i.hooks?await i.hooks.provideLexer(e):e?x.lex:x.lexInline)(p,i),c=i.hooks?await i.hooks.processAllTokens(u):u;i.walkTokens&&await Promise.all(this.walkTokens(c,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser(e):e?b.parse:b.parseInline)(c,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let a=(i.hooks?i.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?b.parse:b.parseInline)(a,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(p){return o(p)}}}onError(e,t){return n=>{if(n.message+=`
117
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+O(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},E=new Z;function f(l3,e){return E.parse(l3,e)}f.options=f.setOptions=function(l3){return E.setOptions(l3),f.defaults=E.defaults,j(f.defaults),f};f.getDefaults=C;f.defaults=R;function kt(...l3){return E.use(...l3),f.defaults=E.defaults,j(f.defaults),f}f.use=kt;f.walkTokens=function(l3,e){return E.walkTokens(l3,e)};f.parseInline=E.parseInline;f.Parser=b;f.parser=b.parse;f.Renderer=P;f.TextRenderer=L;f.Lexer=x;f.lexer=x.lex;f.Tokenizer=y;f.Hooks=S;f.parse=f;var nn=f.options,rn=f.setOptions,sn=f.walkTokens,on=f.parseInline;var ln=b.parse,pn=x.lex;var import_picocolors5=__toESM(require_picocolors(),1);var MAX_RENDER_WIDTH=100;function renderWidth(){let columns=process.stdout.columns,usable=columns&&columns>20?columns:80;return Math.min(usable,MAX_RENDER_WIDTH)}var CONTROL_PATTERN=new RegExp("[\0-\b\v-\x7F-\x9F]","g");function terminalSafeSource(source){return source.replace(CONTROL_PATTERN,"")}function renderMarkdown(source){let safe=terminalSafeSource(source);try{return renderBlocks(f.lexer(safe),renderWidth()).join(`
118
+
119
+ `)}catch{return safe}}function joinSoftBreaks(text){return text.replace(/[ \t]*\n[ \t]*/g," ")}function unescapeHtml(text){return text.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}var ANSI_PATTERN=new RegExp("\x1B\\[[0-9;]*m","g");function plainLength(text){return text.replace(ANSI_PATTERN,"").length}function wrap(text,width){let lines=[];for(let line of text.split(`
120
+ `)){let current="",currentLength=0;for(let word of line.split(" ")){if(word==="")continue;let wordLength=plainLength(word);currentLength>0&&currentLength+1+wordLength>width?(lines.push(current),current=word,currentLength=wordLength):(current=current?`${current} ${word}`:word,currentLength+=currentLength>0?1+wordLength:wordLength)}lines.push(current)}return lines.join(`
121
+ `)}function indentLines(text,indent){return text.split(`
122
+ `).map(line=>line&&`${indent}${line}`).join(`
123
+ `)}function fenceLanguage(lang){let name=lang?.trim().split(/\s+/)[0]?.toLowerCase();if(name==="ts"||name==="typescript"||name==="js"||name==="javascript")return"typescript";if(name==="json")return"json";if(name==="md"||name==="markdown")return"markdown"}function renderBlocks(tokens,width){let blocks=[];for(let token of tokens){let block=renderBlock(token,width);block!==void 0&&blocks.push(block)}return blocks}function renderBlock(token,width){switch(token.type){case"space":return;case"heading":{let heading=token,text=renderInline(heading.tokens),marks=import_picocolors5.default.dim("#".repeat(heading.depth)),styled=heading.depth===1?import_picocolors5.default.bold(import_picocolors5.default.underline(text)):import_picocolors5.default.bold(text);return`${marks} ${styled}`}case"paragraph":return wrap(renderInline(token.tokens),width);case"text":{let text=token;return wrap(text.tokens?renderInline(text.tokens):joinSoftBreaks(unescapeHtml(text.text)),width)}case"code":{let code=token,language=fenceLanguage(code.lang),body=language?highlightContent(code.text,language):code.text;return indentLines(body," ")}case"blockquote":return renderBlocks(token.tokens,Math.max(width-2,20)).join(`
124
+
125
+ `).split(`
126
+ `).map(line=>`${import_picocolors5.default.dim("\u2502")} ${line}`.trimEnd()).join(`
127
+ `);case"list":return renderList(token,width);case"table":return renderMarkdownTable(token);case"hr":return import_picocolors5.default.dim("\u2500".repeat(Math.min(width,40)));case"html":return token.text.trimEnd();case"def":return;default:return"raw"in token?String(token.raw).trimEnd():void 0}}function renderList(list,width){let start=typeof list.start=="number"?list.start:1,lines=[];return list.items.forEach((item,index)=>{let marker=list.ordered?`${start+index}.`:"\u2022",checkbox=item.task?item.checked?"[x] ":"[ ] ":"",indent=" ".repeat(marker.length+1),tokens=item.tokens.filter(token=>token.type!=="checkbox"),body=renderBlocks(tokens,Math.max(width-indent.length,20)).join(item.loose?`
128
+
129
+ `:`
130
+ `),[first="",...rest]=`${checkbox}${body}`.split(`
131
+ `);lines.push(`${import_picocolors5.default.dim(marker)} ${first}`.trimEnd());for(let line of rest)lines.push(line&&`${indent}${line}`)}),lines.join(`
132
+ `)}function renderMarkdownTable(table2){let header=table2.header.map(cell2=>renderInline(cell2.tokens)),rows2=table2.rows.map(row=>row.map(cell2=>renderInline(cell2.tokens))),widths=header.map((cell2,column)=>Math.max(plainLength(cell2),...rows2.map(row=>plainLength(row[column]??"")))),pad=(cell2,column)=>cell2+" ".repeat(Math.max(0,(widths[column]??0)-plainLength(cell2))),renderRow=cells=>cells.map((cell2,column)=>pad(cell2,column)).join(" ").trimEnd();return[import_picocolors5.default.bold(renderRow(header)),import_picocolors5.default.dim(widths.map(column=>"\u2500".repeat(column)).join("\u2500\u2500")),...rows2.map(row=>renderRow(row))].join(`
133
+ `)}function renderInline(tokens){if(!tokens)return"";let out="";for(let token of tokens)switch(token.type){case"text":{let text=token;out+=text.tokens?renderInline(text.tokens):joinSoftBreaks(unescapeHtml(text.text));break}case"strong":out+=import_picocolors5.default.bold(renderInline(token.tokens));break;case"em":out+=import_picocolors5.default.italic(renderInline(token.tokens));break;case"del":out+=import_picocolors5.default.strikethrough(renderInline(token.tokens));break;case"codespan":out+=import_picocolors5.default.cyan(unescapeHtml(token.text));break;case"link":{let link=token,text=renderInline(link.tokens);out+=text===link.href?import_picocolors5.default.underline(link.href):`${text} (${import_picocolors5.default.underline(link.href)})`;break}case"image":{let image=token;out+=`${image.text||"image"} (${import_picocolors5.default.underline(image.href)})`;break}case"br":out+=`
134
+ `;break;case"escape":out+=unescapeHtml(token.text);break;case"html":out+=token.text;break;default:out+="raw"in token?String(token.raw):""}return out}var CRASH_REPORT_VERSION=1,MAX_CRASH_REPORT_BYTES=512*1024,PRUNE_MS3=10080*60*1e3,MAX_STORED_REPORTS=20,enabled4=!0,instanceFlag;function configureCrashReports(opts){let off=process.env.SR_CONNECT_CLI_NO_CRASH_REPORTS;enabled4=opts.enabled!==!1&&(off===void 0||/^(0|false|no|off|)$/i.test(off.trim()))&&settingEnabled("crashReports"),instanceFlag=opts.instance}function crashKindOf(err){if(err instanceof CliError)return err.expected||err.status===503?void 0:err.status!==void 0&&err.status>=500?"server":void 0;if(!(err instanceof Error&&err.name==="CommanderError"))return"unexpected"}function crashReportsDir(){return join8(stateHome(),APP_DIR,"crash-reports")}var sanitizeId=value=>value.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,96);function reportFile(id){return join8(crashReportsDir(),`${sanitizeId(id)}.md`)}function instanceUrl(){try{let instance4=resolveInstance(instanceFlag);return instance4===void 0?void 0:baseUrl(instance4)}catch{return}}function crashTitle(header){return header.kind==="server"?header.status===void 0?"server-side error":`server-side error (HTTP ${header.status})`:"unexpected CLI error"}function callsThisRun(){try{return readApiCalls({}).filter(run=>run.runId.startsWith(`${RUN_ID}-`)).flatMap(run=>run.calls)}catch{return[]}}function table(rows2,header){let escape=cell2=>cell2.replaceAll("|","\\|");return[`| ${header.join(" | ")} |`,`| ${header.map(()=>"---").join(" | ")} |`,...rows2.map(row=>`| ${row.map(escape).join(" | ")} |`)].join(`
135
+ `)}function fenced(label,body,bytes){if(body===void 0||body==="")return`${label}: _(empty)_`;let shown=Buffer.byteLength(body),size=shown<bytes?`${formatBytes(shown)} of ${formatBytes(bytes)}`:formatBytes(bytes);return`${label} (${size}):
136
+
137
+ \`\`\`
138
+ ${body}
139
+ \`\`\``}function failed(call){return call.error!==void 0||(call.status??0)>=400}function callsSection(calls,budget){if(calls.length===0)return"";let kept=[...calls],omitted=0,render=(list,dropped)=>{let rows2=list.map((call,index)=>[String(index+1+dropped),call.ts.slice(11,23),call.method,`\`${pathOf(call.url)}\``,call.error===void 0?String(call.status??""):"no response",String(call.ms),String(call.attempt)]),blocks=["## API calls this run","",table(rows2,["#","Time","Method","Path","Status","ms","Attempt"])];dropped>0&&blocks.push("",`_${dropped} earlier call${dropped===1?"":"s"} omitted to stay under the attachment limit._`);for(let[index,call]of list.entries()){if(!failed(call))continue;let status=call.error===void 0?String(call.status??""):call.error;blocks.push("",`### Call ${index+1+dropped} \u2014 ${call.method} ${pathOf(call.url)} \u2192 ${status}`,"",fenced("Request body",call.reqBody,call.reqBytes),"",fenced("Response body",call.resBody,call.resBytes))}return blocks.join(`
140
+ `)},text=render(kept,omitted);for(;Buffer.byteLength(text)>budget&&kept.length>1;){let index=kept.findIndex(call=>!failed(call));kept.splice(index===-1?0:index,1),omitted+=1,text=render(kept,omitted)}return text}function pathOf(url2){let base=instanceUrl();if(base!==void 0&&url2.startsWith(base)){let remainder=url2.slice(base.length);if(remainder===""||remainder.startsWith("/")||remainder.startsWith("?"))return remainder||"/"}return sanitizeUrl(url2,base)}function commandOf(argv2){let verbs=[];for(let token of argv2)if(token.startsWith("-")||(verbs.push(token),verbs.length===2))break;return verbs.join(" ")}function buildCrashReport(err,kind,calls=callsThisRun()){let argv2=sanitizeArgv(process.argv.slice(2)),cliError=err instanceof CliError?err:void 0,header={v:CRASH_REPORT_VERSION,id:RUN_ID,kind,createdAt:new Date().toISOString(),command:commandOf(argv2)||"(no command)",code:cliError?.code??"UNEXPECTED_ERROR",exitCode:cliError?.exitCode??1,...cliError?.status===void 0?{}:{status:cliError.status}},install=classifyInstall(currentSite()),message=err instanceof Error?describeError(err):String(err),stack=stackOf(err),minimum=cachedServiceInfo()?.minimumCliVersion,timeZone=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})(),environment=table([["Reported at",timeZone?`${header.createdAt} (${timeZone})`:header.createdAt],["CLI",`${PACKAGE} ${VERSION}`],["Install",`${install.kind} (${install.manager})`],["Run ID",header.id],["Command",`\`${argv2.map(shellQuote).join(" ")}\``],["Instance",instanceUrl()??"(none configured)"],...minimum===void 0?[]:[["Deployment minimum CLI",minimum]],["Node",process.version],["OS",`${platform()} ${release()} (${arch()})`],["Terminal",`interactive: ${canPrompt()} \xB7 raw: ${isRaw()} \xB7 CI: ${!!process.env.CI}`],["Error",`${header.code}${header.status===void 0?"":` \xB7 HTTP ${header.status}`} \xB7 exit ${header.exitCode}`]],["Field","Value"]),head=[`<!-- sr-connect-crash ${JSON.stringify(header)} -->`,`# Crash report \u2014 ${crashTitle(header)}`,"","## Summary","",`\`${header.command}\` failed with **${message}**`,"","## Environment","",environment,"","## Error","","```",stack,"```",""].join(`
141
+ `),section=callsSection(calls,Math.max(0,MAX_CRASH_REPORT_BYTES-Buffer.byteLength(head))),markdown=section===""?head:`${head}
142
+ ${section}
143
+ `;return{...header,markdown}}function stackOf(err,depth=0){if(!(err instanceof Error))return String(err);let head=err.stack??`${err.name}: ${err.message}`;if(depth>=3)return head;let nested=err instanceof AggregateError&&err.errors.length>0?err.errors[0]:err.cause;return nested==null?head:`${head}
144
+
145
+ Caused by: ${stackOf(nested,depth+1)}`}function parseHeader(line){let match=/^<!-- sr-connect-crash (.*) -->$/.exec(line.trim());if(match?.[1])try{let parsed=JSON.parse(match[1]);if(typeof parsed!="object"||parsed===null)return;let candidate=parsed;return candidate.v!==CRASH_REPORT_VERSION||typeof candidate.id!="string"||typeof candidate.createdAt!="string"?void 0:parsed}catch{return}}function readHeader(path2){let fd;try{fd=openSync(path2,"r");let buffer=Buffer.alloc(2048),read=readSync(fd,buffer,0,buffer.length,0),[first=""]=buffer.subarray(0,read).toString("utf8").split(`
146
+ `);return parseHeader(first)}catch{return}finally{fd!==void 0&&closeSync(fd)}}function stripCrashHeader(markdown){let[first="",...rest]=markdown.split(`
147
+ `);return parseHeader(first)?rest.join(`
148
+ `).replace(/^\n+/,""):markdown}function listCrashReports(){let dir=crashReportsDir(),names;try{names=readdirSync4(dir).filter(name=>name.endsWith(".md"))}catch{return[]}let reports=[];for(let name of names){let path2=join8(dir,name),header=readHeader(path2);if(header)try{reports.push({...header,path:path2,bytes:statSync4(path2).size})}catch{}}return reports.sort((a,b2)=>b2.createdAt.localeCompare(a.createdAt))}function readCrashReport(id){let stored=id===void 0?listCrashReports()[0]:listCrashReports().find(r=>r.id===id);if(stored)try{let markdown=readFileSync8(stored.path,"utf8");return{v:stored.v,id:stored.id,kind:stored.kind,createdAt:stored.createdAt,command:stored.command,code:stored.code,exitCode:stored.exitCode,...stored.status===void 0?{}:{status:stored.status},markdown}}catch{return}}function clearCrashReports(id){let removed=[];for(let stored of listCrashReports())if(!(id!==void 0&&stored.id!==id))try{rmSync5(stored.path,{force:!0}),removed.push(stored.id)}catch{}return removed}function writeCrashReport(report){let path2=reportFile(report.id);try{mkdirSync6(crashReportsDir(),{recursive:!0,mode:448}),writeFileSync5(path2,report.markdown,{mode:384})}catch{return}return pruneCrashReports(),path2}function pruneCrashReports(){let reports=listCrashReports(),stale=new Set(reports.filter(r=>Date.now()-Date.parse(r.createdAt)>PRUNE_MS3).map(r=>r.path));for(let report of reports.slice(MAX_STORED_REPORTS))stale.add(report.path);for(let path2 of stale)try{rmSync5(path2)}catch{}}function crashAttachmentName(id){let name=`crash-${sanitizeId(id)}.md`;return attachmentNameError(name)===void 0?name:"crash-report.md"}function crashFeedbackMessage(report){return[`Crash report \u2014 ${crashTitle(report)} in \`${report.command}\`.`,"",`${PACKAGE} ${VERSION} \xB7 Node ${process.version} \xB7 ${platform()} ${arch()}`,`Run ID ${report.id} \xB7 ${report.code}${report.status===void 0?"":` \xB7 HTTP ${report.status}`} \xB7 exit ${report.exitCode}`,"","Sent from the CLI. Metadata, the stack and this run\u2019s HTTP calls are in the attached file."].join(`
149
+ `).slice(0,MAX_FEEDBACK_MESSAGE)}async function resolveCrashReport(id,question){if(id!==void 0){let named=readCrashReport(id);return named||crashNotFound(`No crash report with ID ${id}.`),named}let stored=listCrashReports();if(stored.length===0&&crashNotFound("No crash reports stored."),!canPrompt())return readCrashReport(stored[0]?.id)??crashNotFound("No crash reports stored.");let answer=await prompts().select(question,stored.map(crashChoice));return readCrashReport(answer)??crashNotFound(`No crash report with ID ${answer}.`)}function crashChoice(report,index){return{value:report.id,label:report.id,display:`${report.id} \xB7 ${report.createdAt} \xB7 ${report.command} \xB7 ${crashTitle(report)}${index===0?" (newest)":""}`,hint:formatBytes(report.bytes)}}function crashNotFound(message){fail(EXIT.NOT_FOUND,"NOT_FOUND",message,{hint:`Run \`${CLI} cli list-crash-reports\` to see what is stored.`})}async function sendCrashReport(report,opts={}){let content=Buffer.from(report.markdown,"utf8");content.byteLength>MAX_ATTACHMENT_BYTES&&fail(EXIT.USAGE,"ATTACHMENT_TOO_LARGE",attachmentTooLarge("the crash report",content.byteLength));let client=await apiClient(instanceFlag,{versionGate:!1}),{data,response,error:error51}=await withSpinner("Posting crash report",()=>client.POST("/v1/feedback",{body:{message:opts.message??crashFeedbackMessage(report),...opts.email===void 0?{}:{email:opts.email},...opts.canContact?{canContact:!0}:{},attachments:[{fileName:crashAttachmentName(report.id),content:content.toString("base64")}]}}));return(!response.ok||!data)&&apiFail(response.status,error51),data.id}async function askOffer(report,bytes){let answer=await prompts().select("This looks like our bug. Send a crash report to the ScriptRunner Connect team?",[{value:"yes",label:"Yes",display:"Yes (recommended)",hint:`${formatBytes(bytes)} \xB7 metadata, stack and this run's HTTP calls`},{value:"review",label:"Review first",hint:"print the report here, then decide"},{value:"no",label:"No",hint:"keep it on disk \u2014 you can send it later"}],{initial:"yes"});return answer==="review"||answer==="no"?answer:"yes"}function followUp(report,path2){warnLine(`\u26A0 Crash report saved: ${path2}`),agenticFeedbackEnabled()?warnLine(` Send it with: ${CLI} feedback post-crash-report --report ${report.id}`):warnLine(` Agentic feedback is off \u2014 send it from a terminal, or re-enable it with \`${CLI} cli settings\`.`)}async function offerCrashReport(err){if(!enabled4)return;let path2,report;try{let kind=crashKindOf(err);if(kind===void 0||(report=buildCrashReport(err,kind),report.command==="feedback post-crash-report")||(path2=writeCrashReport(report),path2===void 0))return;if(!canPrompt()){followUp(report,path2);return}if(!await resolveCredentials()){followUp(report,path2),warnLine(` (\`${CLI} auth login\` first \u2014 the API records feedback against your account.)`);return}let answer=await askOffer(report,Buffer.byteLength(report.markdown));if(answer==="review"&&(process.stderr.write(`
150
+ ${renderMarkdown(stripCrashHeader(report.markdown))}
151
+
152
+ `),answer=await prompts().confirm("Send this report?",!0)?"yes":"no"),answer!=="yes"){followUp(report,path2);return}let id=await sendCrashReport(report);clearCrashReports(report.id),successLine(`\u2714 Crash report sent. Reference ${id} \u2014 quote it if you follow this up.`)}catch(offerError){let reason=offerError instanceof Error?offerError.message:String(offerError);path2!==void 0&&report!==void 0&&(warnLine(`\u26A0 Could not send the crash report (${reason}) \u2014 it is kept at ${path2}`),warnLine(` Send it with: ${CLI} feedback post-crash-report --report ${report.id}`))}}var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,config:()=>config,core:()=>core_exports2,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date3,decode:()=>decode2,decodeAsync:()=>decodeAsync2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode2,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,includes:()=>_includes,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,overwrite:()=>_overwrite,parse:()=>parse2,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid3,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var core_exports2={};__export(core_exports2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,JSONSchema:()=>json_schema_exports,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,clone:()=>clone,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,initializeContext:()=>initializeContext,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidJWT:()=>isValidJWT,locales:()=>locales_exports,meta:()=>meta,parse:()=>parse,parseAsync:()=>parseAsync,prettifyError:()=>prettifyError,process:()=>process3,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,treeifyError:()=>treeifyError,util:()=>util_exports,version:()=>version});var _a,NEVER=Object.freeze({status:"aborted"});function $constructor(name,initializer3,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_2,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer3(inst,def);let proto=_2.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k2=keys[i];k2 in inst||(inst[k2]=proto[k2].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _2(def){var _a3;let inst=params?.Parent?new Definition:this;init(inst,def),(_a3=inst._zod).deferred??(_a3.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_2,"init",{value:init}),Object.defineProperty(_2,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_2,"name",{value:name}),_2}var $brand=Symbol("zod_brand"),$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});var globalConfig=globalThis.__zod_globalConfig;function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_2){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v2=>typeof v2=="number");return Object.entries(entries).filter(([k2,_2])=>numericValues.indexOf(+k2)===-1).map(([_2,v2])=>v2)}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_2,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw new Error("cached value already set")}}}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}var EVALUATING=Symbol("evaluating");function defineLazy(object2,key,getter){let value;Object.defineProperty(object2,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v2){Object.defineProperty(object2,key,{value:v2})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path2){return path2?path2.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}var allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F2=Function;return new F2(""),!0}catch{return!1}});function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}var getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_2,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_2,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_2,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_2,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_2){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_2,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_2,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k2=>shape[k2]._zod.optin==="optional"&&shape[k2]._zod.optout==="optional")}var NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(newShape[key]=currDef.shape[key])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function merge(a,b2){if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b2._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b2._zod.def.catchall},checks:b2._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key])}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required(Class2,schema,mask){let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]}))}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema,def)}function aborted(x2,startIndex=0){if(x2.aborted===!0)return!0;for(let i=startIndex;i<x2.issues.length;i++)if(x2.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x2,startIndex=0){if(x2.aborted===!0)return!0;for(let i=startIndex;i<x2.issues.length;i++)if(x2.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path2,issues){return issues.map(iss=>{var _a3;return(_a3=iss).path??(_a3.path=[]),iss.path.unshift(path2),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){let message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??(rest.path=[]),rest.message=message,ctx?.reportInput&&(rest.input=_input),rest}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k2,_2])=>Number.isNaN(Number.parseInt(k2,10))).map(el=>el[1])}function base64ToUint8Array(base643){let binaryString=atob(base643),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url3){let base643=base64url3.replace(/-/g,"+").replace(/_/g,"/"),padding2="=".repeat((4-base643.length%4)%4);return base64ToUint8Array(base643+padding2)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex3){let cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b2=>b2.toString(16).padStart(2,"0")).join("")}var Class=class{constructor(..._args){}};var initializer=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error});function flattenError(error51,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error51.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error51,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error52,path2=[])=>{for(let issue2 of error52.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path2,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path2,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path2,...issue2.path]);else{let fullpath=[...path2,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error51),fieldErrors}function treeifyError(error51,mapper=issue2=>issue2.message){let result={errors:[]},processError=(error52,path2=[])=>{var _a3,_b;for(let issue2 of error52.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path2,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path2,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path2,...issue2.path]);else{let fullpath=[...path2,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result,i=0;for(;i<fullpath.length;){let el=fullpath[i],terminal=i===fullpath.length-1;typeof el=="string"?(curr.properties??(curr.properties={}),(_a3=curr.properties)[el]??(_a3[el]={errors:[]}),curr=curr.properties[el]):(curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el]),terminal&&curr.errors.push(mapper(issue2)),i++}}};return processError(error51),result}function toDotPath(_path){let segs=[],path2=_path.map(seg=>typeof seg=="object"?seg.key:seg);for(let seg of path2)typeof seg=="number"?segs.push(`[${seg}]`):typeof seg=="symbol"?segs.push(`[${JSON.stringify(String(seg))}]`):/[^\w$]/.test(seg)?segs.push(`[${JSON.stringify(seg)}]`):(segs.length&&segs.push("."),segs.push(seg));return segs.join("")}function prettifyError(error51){let lines=[],issues=[...error51.issues].sort((a,b2)=>(a.path??[]).length-(b2.path??[]).length);for(let issue2 of issues)lines.push(`\u2716 ${issue2.message}`),issue2.path?.length&&lines.push(` \u2192 at ${toDotPath(issue2.path)}`);return lines.join(`
153
+ `)}var _parse=_Err=>(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},parse=_parse($ZodRealError),_parseAsync=_Err=>async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},parseAsync=_parseAsync($ZodRealError),_safeParse=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync=_safeParseAsync($ZodRealError),_encode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema,value,ctx)},encode=_encode($ZodRealError),_decode=_Err=>(schema,value,_ctx)=>_parse(_Err)(schema,value,_ctx),decode=_decode($ZodRealError),_encodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)},encodeAsync=_encodeAsync($ZodRealError),_decodeAsync=_Err=>async(schema,value,_ctx)=>_parseAsync(_Err)(schema,value,_ctx),decodeAsync=_decodeAsync($ZodRealError),_safeEncode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},safeEncode=_safeEncode($ZodRealError),_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),safeDecode=_safeDecode($ZodRealError),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},safeEncodeAsync=_safeEncodeAsync($ZodRealError),_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx),safeDecodeAsync=_safeDecodeAsync($ZodRealError);var regexes_exports={};__export(regexes_exports,{base64:()=>base64,base64url:()=>base64url,bigint:()=>bigint,boolean:()=>boolean,browserEmail:()=>browserEmail,cidrv4:()=>cidrv4,cidrv6:()=>cidrv6,cuid:()=>cuid,cuid2:()=>cuid2,date:()=>date,datetime:()=>datetime,domain:()=>domain,duration:()=>duration,e164:()=>e164,email:()=>email,emoji:()=>emoji,extendedDuration:()=>extendedDuration,guid:()=>guid,hex:()=>hex,hostname:()=>hostname,html5Email:()=>html5Email,httpProtocol:()=>httpProtocol,idnEmail:()=>idnEmail,integer:()=>integer,ipv4:()=>ipv4,ipv6:()=>ipv6,ksuid:()=>ksuid,lowercase:()=>lowercase,mac:()=>mac,md5_base64:()=>md5_base64,md5_base64url:()=>md5_base64url,md5_hex:()=>md5_hex,nanoid:()=>nanoid,null:()=>_null,number:()=>number,rfc5322Email:()=>rfc5322Email,sha1_base64:()=>sha1_base64,sha1_base64url:()=>sha1_base64url,sha1_hex:()=>sha1_hex,sha256_base64:()=>sha256_base64,sha256_base64url:()=>sha256_base64url,sha256_hex:()=>sha256_hex,sha384_base64:()=>sha384_base64,sha384_base64url:()=>sha384_base64url,sha384_hex:()=>sha384_hex,sha512_base64:()=>sha512_base64,sha512_base64url:()=>sha512_base64url,sha512_hex:()=>sha512_hex,string:()=>string,time:()=>time,ulid:()=>ulid2,undefined:()=>_undefined,unicodeEmail:()=>unicodeEmail,uppercase:()=>uppercase,uuid:()=>uuid,uuid4:()=>uuid4,uuid6:()=>uuid6,uuid7:()=>uuid7,xid:()=>xid});var cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,uuid4=uuid(4),uuid6=uuid(6),uuid7=uuid(7),email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail=unicodeEmail,browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_emoji="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji,"u")}var ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mac=delimiter=>{let escapedDelim=escapeRegex(delimiter??":");return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`)},cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date=new RegExp(`^${dateSource}$`);function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let time3=timeSource({precision:args.precision}),opts=["Z"];args.local&&opts.push(""),args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var string=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i;var _undefined=/^undefined$/i;var lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,hex=/^[0-9a-fA-F]*$/;function fixedBase64(bodyLength,padding2){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding2}$`)}function fixedBase64url(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var md5_hex=/^[0-9a-fA-F]{32}$/,md5_base64=fixedBase64(22,"=="),md5_base64url=fixedBase64url(22),sha1_hex=/^[0-9a-fA-F]{40}$/,sha1_base64=fixedBase64(27,"="),sha1_base64url=fixedBase64url(27),sha256_hex=/^[0-9a-fA-F]{64}$/,sha256_base64=fixedBase64(43,"="),sha256_base64url=fixedBase64url(43),sha384_hex=/^[0-9a-fA-F]{96}$/,sha384_base64=fixedBase64(64,""),sha384_base64url=fixedBase64url(64),sha512_hex=/^[0-9a-fA-F]{128}$/,sha512_base64=fixedBase64(86,"=="),sha512_base64url=fixedBase64url(86);var $ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={}),inst._zod.def=def,(_a3=inst._zod).onattach??(_a3.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;def.value<curr&&(def.inclusive?bag.maximum=def.value:bag.exclusiveMaximum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;def.value>curr&&(def.inclusive?bag.minimum=def.value:bag.exclusiveMinimum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{var _a3;(_a3=inst2._zod.bag).multipleOf??(_a3.multipleOf=def.value)}),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt&&(bag.pattern=integer)}),inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck.init(inst,def);let[minimum,maximum]=BIGINT_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum}),inst._zod.check=payload=>{let input=payload.value;input<minimum&&payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;input.size<=def.maximum||payload.issues.push({origin:getSizableOrigin(input),code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;input.size>=def.minimum||payload.issues.push({origin:getSizableOrigin(input),code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.size,bag.maximum=def.size,bag.size=def.size}),inst._zod.check=payload=>{let input=payload.value,size=input.size;if(size===def.size)return;let tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def),(_a3=inst._zod.def).when??(_a3.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern))}),def.pattern?(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});function handleCheckPropertyResult(result,payload,property){result.issues.length&&payload.issues.push(...prefixIssues(property,result.issues))}var $ZodCheckProperty=$constructor("$ZodCheckProperty",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{let result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise)return result.then(result2=>handleCheckPropertyResult(result2,payload,def.property));handleCheckPropertyResult(result,payload,def.property)}}),$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(inst,def)=>{$ZodCheck.init(inst,def);let mimeSet=new Set(def.mime);inst._zod.onattach.push(inst2=>{inst2._zod.bag.mime=def.mime}),inst._zod.check=payload=>{mimeSet.has(payload.value.type)||payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}});var Doc=class{constructor(args=[]){this.content=[],this.indent=0,this&&(this.args=args)}indented(fn){this.indent+=1,fn(this),this.indent-=1}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
154
+ `).filter(x2=>x2),minIndent=Math.min(...lines.map(x2=>x2.length-x2.trimStart().length)),dedented=lines.map(x2=>x2.slice(minIndent)).map(x2=>" ".repeat(this.indent*2)+x2);for(let line of dedented)this.content.push(line)}compile(){let F2=Function,args=this?.args,lines=[...(this?.content??[""]).map(x2=>` ${x2}`)];return new F2(...args,lines.join(`
155
+ `))}};var version={major:4,minor:4,patch:3};var $ZodType=$constructor("$ZodType",(inst,def)=>{var _a3;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];inst._zod.traits.has("$ZodCheck")&&checks.unshift(inst);for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_2=ch._zod.check(payload);if(_2 instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_2 instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _2,payload.issues.length!==currLen&&(isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:value=>{try{let r=safeParse(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return safeParseAsync(inst,value).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag),inst._zod.parse=(payload,_2)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v2={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v2===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v2))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}let url2=new URL(trimmed);def.hostname&&(def.hostname.lastIndex=0,def.hostname.test(url2.hostname)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})),def.protocol&&(def.protocol.lastIndex=0,def.protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})),def.normalize?payload.value=url2.href:payload.value=trimmed;return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid2),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv6",inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}}),$ZodMAC=$constructor("$ZodMAC",(inst,def)=>{def.pattern??(def.pattern=mac(def.delimiter)),$ZodStringFormat.init(inst,def),inst._zod.bag.format="mac"}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{let parts=payload.value.split("/");try{if(parts.length!==2)throw new Error;let[address,prefix]=parts;if(!prefix)throw new Error;let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw new Error;if(prefixNum<0||prefixNum>128)throw new Error;new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}var $ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64",inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});function isValidBase64URL(data){if(!base64url.test(data))return!1;let base643=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base643.padEnd(Math.ceil(base643.length/4)*4,"=");return isValidBase64(padded)}var $ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64url",inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}var $ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{def.fn(payload.value)||payload.issues.push({code:"invalid_format",format:def.format,input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=inst._zod.bag.pattern??number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:"Infinity":void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodBigIntFormat=$constructor("$ZodBigIntFormat",(inst,def)=>{$ZodCheckBigIntFormat.init(inst,def),$ZodBigInt.init(inst,def)}),$ZodSymbol=$constructor("$ZodSymbol",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return typeof input=="symbol"||payload.issues.push({expected:"symbol",code:"invalid_type",input,inst}),payload}}),$ZodUndefined=$constructor("$ZodUndefined",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_undefined,inst._zod.values=new Set([void 0]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return typeof input>"u"||payload.issues.push({expected:"undefined",code:"invalid_type",input,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodVoid=$constructor("$ZodVoid",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return typeof input>"u"||payload.issues.push({expected:"void",code:"invalid_type",input,inst}),payload}}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}var $ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>handleArrayResult(result2,payload,i))):handleArrayResult(result,payload,i)}return proms.length?Promise.all(proms).then(()=>payload):payload}});function handlePropertyResult(result,final,key,input,isOptionalIn,isOptionalOut){let isPresent=key in input;if(result.issues.length){if(isOptionalIn&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&!isOptionalIn){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?isPresent&&(final.value[key]=void 0):final.value[key]=result.value}function normalizeDef(def){let keys=Object.keys(def.shape);for(let k2 of keys)if(!def.shape?.[k2]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${k2}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,keys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,isOptionalIn=_catchall.optin==="optional",isOptionalOut=_catchall.optout==="optional";for(let key in input){if(key==="__proto__"||keySet.has(key))continue;if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst}),proms.length?Promise.all(proms).then(()=>payload):payload}var $ZodObject=$constructor("$ZodObject",(inst,def)=>{if($ZodType.init(inst,def),!Object.getOwnPropertyDescriptor(def,"shape")?.get){let sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),newSh}})}let _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{let shape=def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(let v2 of field.values)propValues[key].add(v2)}}return propValues});let isObject2=isObject,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value={};let proms=[],shape=value.shape;for(let key of value.keys){let el=shape[key],isOptionalIn=el._zod.optin==="optional",isOptionalOut=el._zod.optout==="optional",r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),generateFastpass=shape=>{let doc=new Doc(["shape","payload","ctx"]),normalized=_normalized.value,parseStr=key=>{let k2=esc(key);return`shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`};doc.write("const input = payload.value;");let ids=Object.create(null),counter=0;for(let key of normalized.keys)ids[key]=`key_${counter++}`;doc.write("const newResult = {};");for(let key of normalized.keys){let id=ids[key],k2=esc(key),schema=shape[key],isOptionalIn=schema?._zod?.optin==="optional",isOptionalOut=schema?._zod?.optout==="optional";doc.write(`const ${id} = ${parseStr(key)};`),isOptionalIn&&isOptionalOut?doc.write(`
156
+ if (${id}.issues.length) {
157
+ if (${k2} in input) {
158
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
159
+ ...iss,
160
+ path: iss.path ? [${k2}, ...iss.path] : [${k2}]
161
+ })));
162
+ }
163
+ }
164
+
165
+ if (${id}.value === undefined) {
166
+ if (${k2} in input) {
167
+ newResult[${k2}] = undefined;
168
+ }
169
+ } else {
170
+ newResult[${k2}] = ${id}.value;
171
+ }
172
+
173
+ `):isOptionalIn?doc.write(`
174
+ if (${id}.issues.length) {
175
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
176
+ ...iss,
177
+ path: iss.path ? [${k2}, ...iss.path] : [${k2}]
178
+ })));
179
+ }
180
+
181
+ if (${id}.value === undefined) {
182
+ if (${k2} in input) {
183
+ newResult[${k2}] = undefined;
184
+ }
185
+ } else {
186
+ newResult[${k2}] = ${id}.value;
187
+ }
188
+
189
+ `):doc.write(`
190
+ const ${id}_present = ${k2} in input;
191
+ if (${id}.issues.length) {
192
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
193
+ ...iss,
194
+ path: iss.path ? [${k2}, ...iss.path] : [${k2}]
195
+ })));
196
+ }
197
+ if (!${id}_present && !${id}.issues.length) {
198
+ payload.issues.push({
199
+ code: "invalid_type",
200
+ expected: "nonoptional",
201
+ input: undefined,
202
+ path: [${k2}]
203
+ });
204
+ }
205
+
206
+ if (${id}_present) {
207
+ if (${id}.value === undefined) {
208
+ newResult[${k2}] = undefined;
209
+ } else {
210
+ newResult[${k2}] = ${id}.value;
211
+ }
212
+ }
213
+
214
+ `)}doc.write("payload.value = newResult;"),doc.write("return payload;");let fn=doc.compile();return(payload,ctx)=>fn(shape,payload,ctx)},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;return isObject2(input)?jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0?(fastpass||(fastpass=generateFastpass(def.shape)),payload=fastpass(payload,ctx),catchall?handleCatchall([],input,payload,ctx,value,inst):payload):superParse(payload,ctx):(payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload)}});function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}var $ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.options.some(o=>o._zod.optin==="optional")?"optional":void 0),defineLazy(inst._zod,"optout",()=>def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),defineLazy(inst._zod,"values",()=>{if(def.options.every(o=>o._zod.values))return new Set(def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazy(inst._zod,"pattern",()=>{if(def.options.every(o=>o._zod.pattern)){let patterns=def.options.map(o=>o._zod.pattern);return new RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join("|")})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results2=>handleUnionResults(results2,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}});function handleExclusiveUnionResults(results,final,inst,ctx){let successes=results.filter(r=>r.issues.length===0);return successes.length===1?(final.value=successes[0].value,final):(successes.length===0?final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}):final.issues.push({code:"invalid_union",input:final.value,inst,errors:[],inclusive:!1}),final)}var $ZodXor=$constructor("$ZodXor",(inst,def)=>{$ZodUnion.init(inst,def),def.inclusive=!1;let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);result instanceof Promise?(results.push(result),async=!0):results.push(result)}return async?Promise.all(results).then(results2=>handleExclusiveUnionResults(results2,payload,inst,ctx)):handleExclusiveUnionResults(results,payload,inst,ctx)}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k2,v2]of Object.entries(pv)){propValues[k2]||(propValues[k2]=new Set);for(let val of v2)propValues[k2].add(val)}}return propValues});let disc=cached(()=>{let opts=def.options,map2=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v2 of values){if(map2.has(v2))throw new Error(`Duplicate discriminator value "${String(v2)}"`);map2.set(v2,o)}}return map2});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);return opt?opt._zod.run(payload,ctx):def.unionFallback||ctx.direction==="backward"?_super(payload,ctx):(payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()),input,path:[def.discriminator],inst}),payload)}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left2,right2])=>handleIntersectionResults(payload,left2,right2)):handleIntersectionResults(payload,left,right)}});function mergeValues(a,b2){if(a===b2)return{valid:!0,data:a};if(a instanceof Date&&b2 instanceof Date&&+a==+b2)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b2)){let bKeys=Object.keys(b2),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b2};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b2[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b2)){if(a.length!==b2.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b2[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(let k2 of iss.keys)unrecKeys.has(k2)||unrecKeys.set(k2,{}),unrecKeys.get(k2).l=!0}else result.issues.push(iss);for(let iss of right.issues)if(iss.code==="unrecognized_keys")for(let k2 of iss.keys)unrecKeys.has(k2)||unrecKeys.set(k2,{}),unrecKeys.get(k2).r=!0;else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f2])=>f2.l&&f2.r).map(([k2])=>k2);if(bothKeys.length&&unrecIssue&&result.issues.push({...unrecIssue,keys:bothKeys}),aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}var $ZodTuple=$constructor("$ZodTuple",(inst,def)=>{$ZodType.init(inst,def);let items=def.items;inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({input,inst,expected:"tuple",code:"invalid_type"}),payload;payload.value=[];let proms=[],optinStart=getTupleOptStart(items,"optin"),optoutStart=getTupleOptStart(items,"optout");if(!def.rest){if(input.length<optinStart)return payload.issues.push({code:"too_small",minimum:optinStart,inclusive:!0,input,inst,origin:"array"}),payload;input.length>items.length&&payload.issues.push({code:"too_big",maximum:items.length,inclusive:!0,input,inst,origin:"array"})}let itemResults=new Array(items.length);for(let i=0;i<items.length;i++){let r=items[i]._zod.run({value:input[i],issues:[]},ctx);r instanceof Promise?proms.push(r.then(rr=>{itemResults[i]=rr})):itemResults[i]=r}if(def.rest){let i=items.length-1,rest=input.slice(items.length);for(let el of rest){i++;let result=def.rest._zod.run({value:el,issues:[]},ctx);result instanceof Promise?proms.push(result.then(r=>handleTupleResult(r,payload,i))):handleTupleResult(result,payload,i)}}return proms.length?Promise.all(proms).then(()=>handleTupleResults(itemResults,payload,items,input,optoutStart)):handleTupleResults(itemResults,payload,items,input,optoutStart)}});function getTupleOptStart(items,key){for(let i=items.length-1;i>=0;i--)if(items[i]._zod[key]!=="optional")return i+1;return 0}function handleTupleResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handleTupleResults(itemResults,final,items,input,optoutStart){for(let i=0;i<items.length;i++){let r=itemResults[i],isPresent=i<input.length;if(r.issues.length){if(!isPresent&&i>=optoutStart){final.value.length=i;break}final.issues.push(...prefixIssues(i,r.issues))}final.value[i]=r.value}for(let i=final.value.length-1;i>=input.length&&(items[i]._zod.optout==="optional"&&final.value[i]===void 0);i--)final.value.length=i;return final}var $ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values){payload.value={};let recordKeys=new Set;for(let key of values)if(typeof key=="string"||typeof key=="number"||typeof key=="symbol"){recordKeys.add(typeof key=="number"?key.toString():key);let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value,result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}let unrecognized;for(let key in input)recordKeys.has(key)||(unrecognized=unrecognized??[],unrecognized.push(key));unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__"||!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof key=="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");retryResult.issues.length===0&&(keyResult=retryResult)}if(keyResult.issues.length){def.mode==="loose"?payload.value[key]=input[key]:payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[keyResult.value]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[keyResult.value]=result.value)}}return proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodMap=$constructor("$ZodMap",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Map))return payload.issues.push({expected:"map",code:"invalid_type",input,inst}),payload;let proms=[];payload.value=new Map;for(let[key,value]of input){let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx),valueResult=def.valueType._zod.run({value,issues:[]},ctx);keyResult instanceof Promise||valueResult instanceof Promise?proms.push(Promise.all([keyResult,valueResult]).then(([keyResult2,valueResult2])=>{handleMapResult(keyResult2,valueResult2,payload,key,input,inst,ctx)})):handleMapResult(keyResult,valueResult,payload,key,input,inst,ctx)}return proms.length?Promise.all(proms).then(()=>payload):payload}});function handleMapResult(keyResult,valueResult,final,key,input,inst,ctx){keyResult.issues.length&&(propertyKeyTypes.has(typeof key)?final.issues.push(...prefixIssues(key,keyResult.issues)):final.issues.push({code:"invalid_key",origin:"map",input,inst,issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})),valueResult.issues.length&&(propertyKeyTypes.has(typeof key)?final.issues.push(...prefixIssues(key,valueResult.issues)):final.issues.push({origin:"map",code:"invalid_element",input,inst,key,issues:valueResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})),final.value.set(keyResult.value,valueResult.value)}var $ZodSet=$constructor("$ZodSet",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Set))return payload.issues.push({input,inst,expected:"set",code:"invalid_type"}),payload;let proms=[];payload.value=new Set;for(let item of input){let result=def.valueType._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>handleSetResult(result2,payload))):handleSetResult(result,payload)}return proms.length?Promise.all(proms).then(()=>payload):payload}});function handleSetResult(result,final){result.issues.length&&final.issues.push(...result.issues),final.value.add(result.value)}var $ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter(k2=>propertyKeyTypes.has(typeof k2)).map(o=>typeof o=="string"?escapeRegex(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return valuesSet.has(input)||payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{if($ZodType.init(inst,def),def.values.length===0)throw new Error("Cannot create literal schema with no valid values");let values=new Set(def.values);inst._zod.values=values,inst._zod.pattern=new RegExp(`^(${def.values.map(o=>typeof o=="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return values.has(input)||payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodFile=$constructor("$ZodFile",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input instanceof File||payload.issues.push({expected:"file",code:"invalid_type",input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output2=>(payload.value=output2,payload.fallback=!0,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload.fallback=!0,payload}});function handleOptionalResult(result,input){return input===void 0&&(result.issues.length||result.fallback)?{issues:[],value:void 0}:result}var $ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let input=payload.value,result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(r=>handleOptionalResult(r,input)):handleOptionalResult(result,input)}return payload.value===void 0?payload:def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,"values",()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleDefaultResult(result2,def)):handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}var $ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction==="backward"||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>{let v2=def.innerType._zod.values;return v2?new Set([...v2].filter(x2=>x2!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleNonOptionalResult(result2,inst)):handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}var $ZodSuccess=$constructor("$ZodSuccess",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError("ZodSuccess");let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>(payload.value=result2.issues.length===0,payload)):(payload.value=result.issues.length===0,payload)}}),$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>(payload.value=result2.value,result2.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result2.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)):(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)}}),$ZodNaN=$constructor("$ZodNaN",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>((typeof payload.value!="number"||!Number.isNaN(payload.value))&&payload.issues.push({input:payload.value,inst,expected:"nan",code:"invalid_type"}),payload)}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right2=>handlePipeResult(right2,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left2=>handlePipeResult(left2,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){return left.issues.length?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}var $ZodCodec=$constructor("$ZodCodec",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if((ctx.direction||"forward")==="forward"){let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left2=>handleCodecAResult(left2,def,ctx)):handleCodecAResult(left,def,ctx)}else{let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right2=>handleCodecAResult(right2,def,ctx)):handleCodecAResult(right,def,ctx)}}});function handleCodecAResult(result,def,ctx){if(result.issues.length)return result.aborted=!0,result;if((ctx.direction||"forward")==="forward"){let transformed=def.transform(result.value,result);return transformed instanceof Promise?transformed.then(value=>handleCodecTxResult(result,value,def.out,ctx)):handleCodecTxResult(result,transformed,def.out,ctx)}else{let transformed=def.reverseTransform(result.value,result);return transformed instanceof Promise?transformed.then(value=>handleCodecTxResult(result,value,def.in,ctx)):handleCodecTxResult(result,transformed,def.in,ctx)}}function handleCodecTxResult(left,value,nextSchema,ctx){return left.issues.length?(left.aborted=!0,left):nextSchema._zod.run({value,issues:left.issues},ctx)}var $ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)}),$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin),defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}var $ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(inst,def)=>{$ZodType.init(inst,def);let regexParts=[];for(let part of def.parts)if(typeof part=="object"&&part!==null){if(!part._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);let source=part._zod.pattern instanceof RegExp?part._zod.pattern.source:part._zod.pattern;if(!source)throw new Error(`Invalid template literal part: ${part._zod.traits}`);let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;regexParts.push(source.slice(start,end))}else if(part===null||primitiveTypes.has(typeof part))regexParts.push(escapeRegex(`${part}`));else throw new Error(`Invalid template literal part: ${part}`);inst._zod.pattern=new RegExp(`^${regexParts.join("")}$`),inst._zod.parse=(payload,_ctx)=>typeof payload.value!="string"?(payload.issues.push({input:payload.value,inst,expected:"string",code:"invalid_type"}),payload):(inst._zod.pattern.lastIndex=0,inst._zod.pattern.test(payload.value)||payload.issues.push({input:payload.value,inst,code:"invalid_format",format:def.format??"template_literal",pattern:inst._zod.pattern.source}),payload)}),$ZodFunction=$constructor("$ZodFunction",(inst,def)=>($ZodType.init(inst,def),inst._def=def,inst._zod.def=def,inst.implement=func=>{if(typeof func!="function")throw new Error("implement() must be called with a function");return function(...args){let parsedArgs=inst._def.input?parse(inst._def.input,args):args,result=Reflect.apply(func,this,parsedArgs);return inst._def.output?parse(inst._def.output,result):result}},inst.implementAsync=func=>{if(typeof func!="function")throw new Error("implementAsync() must be called with a function");return async function(...args){let parsedArgs=inst._def.input?await parseAsync(inst._def.input,args):args,result=await Reflect.apply(func,this,parsedArgs);return inst._def.output?await parseAsync(inst._def.output,result):result}},inst._zod.parse=(payload,_ctx)=>typeof payload.value!="function"?(payload.issues.push({code:"invalid_type",expected:"function",input:payload.value,inst}),payload):(inst._def.output&&inst._def.output._zod.def.type==="promise"?payload.value=inst.implementAsync(payload.value):payload.value=inst.implement(payload.value),payload),inst.input=(...args)=>{let F2=inst.constructor;return Array.isArray(args[0])?new F2({type:"function",input:new $ZodTuple({type:"tuple",items:args[0],rest:args[1]}),output:inst._def.output}):new F2({type:"function",input:args[0],output:inst._def.output})},inst.output=output=>{let F2=inst.constructor;return new F2({type:"function",input:inst._def.input,output})},inst)),$ZodPromise=$constructor("$ZodPromise",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>Promise.resolve(payload.value).then(inner=>def.innerType._zod.run({value:inner,issues:[]},ctx))}),$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>{let d=def;return d._cachedInner||(d._cachedInner=def.getter()),d._cachedInner}),defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern),defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues),defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0),defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>inst._zod.innerType._zod.run(payload,ctx)}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_2)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r2=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst)}});function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var locales_exports={};__export(locales_exports,{ar:()=>ar_default,az:()=>az_default,be:()=>be_default,bg:()=>bg_default,ca:()=>ca_default,cs:()=>cs_default,da:()=>da_default,de:()=>de_default,el:()=>el_default,en:()=>en_default,eo:()=>eo_default,es:()=>es_default,fa:()=>fa_default,fi:()=>fi_default,fr:()=>fr_default,frCA:()=>fr_CA_default,he:()=>he_default,hr:()=>hr_default,hu:()=>hu_default,hy:()=>hy_default,id:()=>id_default,is:()=>is_default,it:()=>it_default,ja:()=>ja_default,ka:()=>ka_default,kh:()=>kh_default,km:()=>km_default,ko:()=>ko_default,lt:()=>lt_default,mk:()=>mk_default,ms:()=>ms_default,nl:()=>nl_default,no:()=>no_default,ota:()=>ota_default,pl:()=>pl_default,ps:()=>ps_default,pt:()=>pt_default,ro:()=>ro_default,ru:()=>ru_default,sl:()=>sl_default,sv:()=>sv_default,ta:()=>ta_default,th:()=>th_default,tr:()=>tr_default,ua:()=>ua_default,uk:()=>uk_default,ur:()=>ur_default,uz:()=>uz_default,vi:()=>vi_default,yo:()=>yo_default,zhCN:()=>zh_CN_default,zhTW:()=>zh_TW_default});var error=()=>{let Sizable={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`:`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`}case"invalid_value":return issue2.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`:_issue.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`:_issue.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`:_issue.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${issue2.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${issue2.keys.length>1?"\u0629":""}: ${joinValues(issue2.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};function ar_default(){return{localeError:error()}}var error2=()=>{let Sizable={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`:`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`}case"invalid_value":return issue2.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin??"d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin??"d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:_issue.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`:_issue.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`:_issue.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};function az_default(){return{localeError:error2()}}function getBelarusianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;return lastTwoDigits>=11&&lastTwoDigits<=19?many:lastDigit===1?one:lastDigit>=2&&lastDigit<=4?few:many}var error3=()=>{let Sizable={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},TypeDictionary={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`}case"invalid_value":return issue2.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getBelarusianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getBelarusianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`:_issue.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`:_issue.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`:_issue.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};function be_default(){return{localeError:error3()}}var error4=()=>{let Sizable={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},TypeDictionary={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`}case"invalid_value":return issue2.values.length===1?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`;if(_issue.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;let invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return _issue.format==="emoji"&&(invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),_issue.format==="datetime"&&(invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),_issue.format==="date"&&(invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),_issue.format==="time"&&(invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),_issue.format==="duration"&&(invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${invalid_adj} ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${issue2.keys.length>1?"\u043E\u0432\u0435":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};function bg_default(){return{localeError:error4()}}var error5=()=>{let Sizable={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`:`Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`}case"invalid_value":return issue2.values.length===1?`Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values," o ")}`;case"too_big":{let adj=issue2.inclusive?"com a m\xE0xim":"menys de",sizing=getSizing(issue2.origin);return sizing?`Massa gran: s'esperava que ${issue2.origin??"el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elements"}`:`Massa gran: s'esperava que ${issue2.origin??"el valor"} fos ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"com a m\xEDnim":"m\xE9s de",sizing=getSizing(issue2.origin);return sizing?`Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`:`Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`:_issue.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`:_issue.format==="includes"?`Format inv\xE0lid: ha d'incloure "${_issue.includes}"`:_issue.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`:`Format inv\xE0lid per a ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clau${issue2.keys.length>1?"s":""} no reconeguda${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${issue2.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${issue2.origin}`;default:return"Entrada inv\xE0lida"}}};function ca_default(){return{localeError:error5()}}var error6=()=>{let Sizable={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},TypeDictionary={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`:`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`}case"invalid_value":return issue2.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin??"hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin??"hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin??"hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin??"hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`:_issue.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`:_issue.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`:_issue.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`:`Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${issue2.origin}`;default:return"Neplatn\xFD vstup"}}};function cs_default(){return{localeError:error6()}}var error7=()=>{let Sizable={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`:`Ugyldigt input: forventede ${expected}, fik ${received}`}case"invalid_value":return issue2.values.length===1?`Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;return sizing?`For stor: forventede ${origin??"value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elementer"}`:`For stor: forventede ${origin??"value"} havde ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;return sizing?`For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`:`For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Ugyldig streng: skal starte med "${_issue.prefix}"`:_issue.format==="ends_with"?`Ugyldig streng: skal ende med "${_issue.suffix}"`:_issue.format==="includes"?`Ugyldig streng: skal indeholde "${_issue.includes}"`:_issue.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`:`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${issue2.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${issue2.origin}`;default:return"Ugyldigt input"}}};function da_default(){return{localeError:error7()}}var error8=()=>{let Sizable={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},TypeDictionary={nan:"NaN",number:"Zahl",array:"Array"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`:`Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`}case"invalid_value":return issue2.values.length===1?`Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Zu gro\xDF: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ist`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`:`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`:_issue.format==="ends_with"?`Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`:_issue.format==="includes"?`Ung\xFCltiger String: muss "${_issue.includes}" enthalten`:_issue.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`:`Ung\xFCltig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;case"unrecognized_keys":return`${issue2.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${issue2.origin}`;default:return"Ung\xFCltige Eingabe"}}};function de_default(){return{localeError:error8()}}var error9=()=>{let Sizable={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return typeof issue2.expected=="string"&&/^[A-Z]/.test(issue2.expected)?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`}case"invalid_value":return issue2.values.length===1?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`:`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`:_issue.format==="ends_with"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`:_issue.format==="includes"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`:_issue.format==="regex"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};function el_default(){return{localeError:error9()}}var error10=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":return issue2.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`:`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`:`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Invalid string: must start with "${_issue.prefix}"`:_issue.format==="ends_with"?`Invalid string: must end with "${_issue.suffix}"`:_issue.format==="includes"?`Invalid string: must include "${_issue.includes}"`:_issue.format==="regex"?`Invalid string: must match pattern ${_issue.pattern}`:`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0?`Invalid discriminator value. Expected ${issue2.options.map(o=>`'${o}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}};function en_default(){return{localeError:error10()}}var error11=()=>{let Sizable={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},TypeDictionary={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`:`Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`}case"invalid_value":return issue2.values.length===1?`Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Tro granda: atendi\u011Dis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`:_issue.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`:_issue.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`:_issue.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`:`Nevalida ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${issue2.divisor}`;case"unrecognized_keys":return`Nekonata${issue2.keys.length>1?"j":""} \u015Dlosilo${issue2.keys.length>1?"j":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${issue2.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${issue2.origin}`;default:return"Nevalida enigo"}}};function eo_default(){return{localeError:error11()}}var error12=()=>{let Sizable={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`:`Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`}case"invalid_value":return issue2.values.length===1?`Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;return sizing?`Demasiado grande: se esperaba que ${origin??"valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`:`Demasiado grande: se esperaba que ${origin??"valor"} fuera ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;return sizing?`Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`:_issue.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`:_issue.format==="includes"?`Cadena inv\xE1lida: debe incluir "${_issue.includes}"`:_issue.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`:`Inv\xE1lido ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Llave${issue2.keys.length>1?"s":""} desconocida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return"Entrada inv\xE1lida"}}};function es_default(){return{localeError:error12()}}var error13=()=>{let Sizable={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},TypeDictionary={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`:`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":return issue2.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:_issue.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:_issue.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`:_issue.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${FormatDictionary[_issue.format]??issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${issue2.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};function fa_default(){return{localeError:error13()}}var error14=()=>{let Sizable={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`:`Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`}case"invalid_value":return issue2.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`:_issue.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`:_issue.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`:_issue.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`:`Virheellinen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;case"unrecognized_keys":return`${issue2.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};function fi_default(){return{localeError:error14()}}var error15=()=>{let Sizable={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},TypeDictionary={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`:`Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`}case"invalid_value":return issue2.values.length===1?`Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`:`Option invalide : une valeur parmi ${joinValues(issue2.values,"|")} attendue`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Trop grand : ${TypeDictionary[issue2.origin]??"valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${TypeDictionary[issue2.origin]??"valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Trop petit : ${TypeDictionary[issue2.origin]??"valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Trop petit : ${TypeDictionary[issue2.origin]??"valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`:_issue.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`:_issue.format==="includes"?`Cha\xEEne invalide : doit inclure "${_issue.includes}"`:_issue.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Cl\xE9${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${issue2.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entr\xE9e invalide"}}};function fr_default(){return{localeError:error15()}}var error16=()=>{let Sizable={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`:`Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`}case"invalid_value":return issue2.values.length===1?`Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"\u2264":"<",sizing=getSizing(issue2.origin);return sizing?`Trop grand : attendu que ${issue2.origin??"la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`:`Trop grand : attendu que ${issue2.origin??"la valeur"} soit ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"\u2265":">",sizing=getSizing(issue2.origin);return sizing?`Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`:_issue.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`:_issue.format==="includes"?`Cha\xEEne invalide : doit inclure "${_issue.includes}"`:_issue.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Cl\xE9${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${issue2.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entr\xE9e invalide"}}};function fr_CA_default(){return{localeError:error16()}}var error17=()=>{let TypeNames={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},Sizable={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},typeEntry=t=>t?TypeNames[t]:void 0,typeLabel=t=>{let e=typeEntry(t);return e?e.label:t??TypeNames.unknown.label},withDefinite=t=>`\u05D4${typeLabel(t)}`,verbFor=t=>(typeEntry(t)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA",getSizing=origin=>origin?Sizable[origin]??null:null,FormatDictionary={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expectedKey=issue2.expected,expected=TypeDictionary[expectedKey??""]??typeLabel(expectedKey),receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??TypeNames[receivedType]?.label??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`}case"invalid_value":{if(issue2.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`;let stringified=issue2.values.map(v2=>stringifyPrimitive(v2));if(issue2.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;let lastValue=stringified[stringified.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified.slice(0,-1).join(", ")} \u05D0\u05D5 ${lastValue}`}case"too_big":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",comparison=issue2.inclusive?`${issue2.maximum} ${sizing?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim()}let adj=issue2.inclusive?"<=":"<",be=verbFor(issue2.origin??"value");return sizing?.unit?`${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`:`${sizing?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`}case"too_small":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(issue2.minimum===1&&issue2.inclusive){let singularPhrase=(issue2.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`}let comparison=issue2.inclusive?`${issue2.minimum} ${sizing?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim()}let adj=issue2.inclusive?">=":">",be=verbFor(issue2.origin??"value");return sizing?.unit?`${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`${sizing?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;if(_issue.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;let nounEntry=FormatDictionary[_issue.format],noun=nounEntry?.label??_issue.format,adjective=(nounEntry?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${noun} \u05DC\u05D0 ${adjective}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${issue2.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${withDefinite(issue2.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};function he_default(){return{localeError:error17()}}var error18=()=>{let Sizable={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},TypeDictionary={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`:`Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`}case"invalid_value":return issue2.values.length===1?`Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`:`Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;return sizing?`Preveliko: o\u010Dekivano da ${origin??"vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemenata"}`:`Preveliko: o\u010Dekivano da ${origin??"vrijednost"} bude ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;return sizing?`Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`:_issue.format==="ends_with"?`Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`:_issue.format==="includes"?`Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`:_issue.format==="regex"?`Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`:`Neispravna ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznat${issue2.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return"Neispravan unos"}}};function hr_default(){return{localeError:error18()}}var error19=()=>{let Sizable={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},TypeDictionary={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`:`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`}case"invalid_value":return issue2.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`T\xFAl nagy: ${issue2.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:_issue.format==="ends_with"?`\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:_issue.format==="includes"?`\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`:_issue.format==="regex"?`\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${issue2.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};function hu_default(){return{localeError:error19()}}function getArmenianPlural(count,one,many){return Math.abs(count)===1?one:many}function withDefiniteArticle(word){if(!word)return"";let vowels=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],lastChar=word[word.length-1];return word+(vowels.includes(lastChar)?"\u0576":"\u0568")}var error20=()=>{let Sizable={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},TypeDictionary={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`:`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`}case"invalid_value":return issue2.values.length===1?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`:`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getArmenianPlural(maxValue,sizing.unit.one,sizing.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getArmenianPlural(minValue,sizing.unit.one,sizing.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`:_issue.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`:_issue.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`:_issue.format==="regex"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length>1?"\u0576\u0565\u0580":""}. ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};function hy_default(){return{localeError:error20()}}var error21=()=>{let Sizable={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`:`Input tidak valid: diharapkan ${expected}, diterima ${received}`}case"invalid_value":return issue2.values.length===1?`Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Terlalu besar: diharapkan ${issue2.origin??"value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`:`Terlalu besar: diharapkan ${issue2.origin??"value"} menjadi ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`String tidak valid: harus dimulai dengan "${_issue.prefix}"`:_issue.format==="ends_with"?`String tidak valid: harus berakhir dengan "${_issue.suffix}"`:_issue.format==="includes"?`String tidak valid: harus menyertakan "${_issue.includes}"`:_issue.format==="regex"?`String tidak valid: harus sesuai pola ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${issue2.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${issue2.origin}`;default:return"Input tidak valid"}}};function id_default(){return{localeError:error21()}}var error22=()=>{let Sizable={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},TypeDictionary={nan:"NaN",number:"n\xFAmer",array:"fylki"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`:`Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`}case"invalid_value":return issue2.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin??"gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin??"gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`:_issue.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`:_issue.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`:_issue.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`:`Rangt ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${issue2.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${issue2.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${issue2.origin}`;default:return"Rangt gildi"}}};function is_default(){return{localeError:error22()}}var error23=()=>{let Sizable={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"numero",array:"vettore"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`:`Input non valido: atteso ${expected}, ricevuto ${received}`}case"invalid_value":return issue2.values.length===1?`Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`:`Opzione non valida: atteso uno tra ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Troppo grande: ${issue2.origin??"valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementi"}`:`Troppo grande: ${issue2.origin??"valore"} deve essere ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Stringa non valida: deve iniziare con "${_issue.prefix}"`:_issue.format==="ends_with"?`Stringa non valida: deve terminare con "${_issue.suffix}"`:_issue.format==="includes"?`Stringa non valida: deve includere "${_issue.includes}"`:_issue.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`:`Input non valido: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${issue2.divisor}`;case"unrecognized_keys":return`Chiav${issue2.keys.length>1?"i":"e"} non riconosciut${issue2.keys.length>1?"e":"a"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${issue2.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${issue2.origin}`;default:return"Input non valido"}}};function it_default(){return{localeError:error23()}}var error24=()=>{let Sizable={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},TypeDictionary={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":return issue2.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let adj=issue2.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",sizing=getSizing(issue2.origin);return sizing?`\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin??"\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit??"\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin??"\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let adj=issue2.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",sizing=getSizing(issue2.origin);return sizing?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:_issue.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:_issue.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:_issue.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length>1?"\u7FA4":""}: ${joinValues(issue2.keys,"\u3001")}`;case"invalid_key":return`${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};function ja_default(){return{localeError:error24()}}var error25=()=>{let Sizable={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},TypeDictionary={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`}case"invalid_value":return issue2.values.length===1?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`:_issue.format==="ends_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`:_issue.format==="includes"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`:_issue.format==="regex"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};function ka_default(){return{localeError:error25()}}var error26=()=>{let Sizable={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},TypeDictionary={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`:`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`}case"invalid_value":return issue2.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`:_issue.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`:_issue.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`:_issue.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};function km_default(){return{localeError:error26()}}function kh_default(){return km_default()}var error27=()=>{let Sizable={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`}case"invalid_value":return issue2.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let adj=issue2.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",suffix=adj==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",sizing=getSizing(issue2.origin),unit=sizing?.unit??"\uC694\uC18C";return sizing?`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`:`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`}case"too_small":{let adj=issue2.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",suffix=adj==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",sizing=getSizing(issue2.origin),unit=sizing?.unit??"\uC694\uC18C";return sizing?`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`:`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:_issue.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:_issue.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:_issue.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};function ko_default(){return{localeError:error27()}}var capitalizeFirstCharacter=text=>text.charAt(0).toUpperCase()+text.slice(1);function getUnitTypeFromNumber(number4){let abs=Math.abs(number4),last=abs%10,last2=abs%100;return last2>=11&&last2<=19||last===0?"many":last===1?"one":"few"}var error28=()=>{let Sizable={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function getSizing(origin,unitType,inclusive,targetShouldBe){let result=Sizable[origin]??null;return result===null?result:{unit:result.unit[unitType],verb:result.verb[targetShouldBe][inclusive?"inclusive":"notInclusive"]}}let FormatDictionary={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},TypeDictionary={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`:`Gautas tipas ${received}, o tik\u0117tasi - ${expected}`}case"invalid_value":return issue2.values.length===1?`Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values,"|")} pasirinkim\u0173`;case"too_big":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.maximum)),issue2.inclusive??!1,"smaller");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit??"element\u0173"}`;let adj=issue2.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`}case"too_small":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.minimum)),issue2.inclusive??!1,"bigger");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit??"element\u0173"}`;let adj=issue2.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`:_issue.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`:_issue.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`:_issue.format==="regex"?`Eilut\u0117 privalo atitikti ${_issue.pattern}`:`Neteisingas ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${issue2.keys.length>1?"i":"as"} rakt${issue2.keys.length>1?"ai":"as"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let origin=TypeDictionary[issue2.origin]??issue2.origin;return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};function lt_default(){return{localeError:error28()}}var error29=()=>{let Sizable={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},TypeDictionary={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`:`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`}case"invalid_value":return issue2.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`:_issue.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`:_issue.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`:_issue.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`:`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};function mk_default(){return{localeError:error29()}}var error30=()=>{let Sizable={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"nombor"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`:`Input tidak sah: dijangka ${expected}, diterima ${received}`}case"invalid_value":return issue2.values.length===1?`Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Terlalu besar: dijangka ${issue2.origin??"nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`:`Terlalu besar: dijangka ${issue2.origin??"nilai"} adalah ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`String tidak sah: mesti bermula dengan "${_issue.prefix}"`:_issue.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${_issue.suffix}"`:_issue.format==="includes"?`String tidak sah: mesti mengandungi "${_issue.includes}"`:_issue.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${issue2.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${issue2.origin}`;default:return"Input tidak sah"}}};function ms_default(){return{localeError:error30()}}var error31=()=>{let Sizable={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},TypeDictionary={nan:"NaN",number:"getal"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`:`Ongeldige invoer: verwacht ${expected}, ontving ${received}`}case"invalid_value":return issue2.values.length===1?`Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),longName=issue2.origin==="date"?"laat":issue2.origin==="string"?"lang":"groot";return sizing?`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementen"} ${sizing.verb}`:`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} is`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),shortName=issue2.origin==="date"?"vroeg":issue2.origin==="string"?"kort":"klein";return sizing?`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`:`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Ongeldige tekst: moet met "${_issue.prefix}" beginnen`:_issue.format==="ends_with"?`Ongeldige tekst: moet op "${_issue.suffix}" eindigen`:_issue.format==="includes"?`Ongeldige tekst: moet "${_issue.includes}" bevatten`:_issue.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`:`Ongeldig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${issue2.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${issue2.origin}`;default:return"Ongeldige invoer"}}};function nl_default(){return{localeError:error31()}}var error32=()=>{let Sizable={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"tall",array:"liste"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`:`Ugyldig input: forventet ${expected}, fikk ${received}`}case"invalid_value":return issue2.values.length===1?`Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`:`Ugyldig valg: forventet en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`For stor(t): forventet ${issue2.origin??"value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementer"}`:`For stor(t): forventet ${issue2.origin??"value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`:_issue.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`:_issue.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`:_issue.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`:`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${issue2.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${issue2.origin}`;default:return"Ugyldig input"}}};function no_default(){return{localeError:error32()}}var error33=()=>{let Sizable={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},TypeDictionary={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`:`F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`}case"invalid_value":return issue2.values.length===1?`F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Fazla b\xFCy\xFCk: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`:_issue.format==="ends_with"?`F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`:_issue.format==="includes"?`F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`:_issue.format==="regex"?`F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};function ota_default(){return{localeError:error33()}}var error34=()=>{let Sizable={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},TypeDictionary={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`:`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":return issue2.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:_issue.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:_issue.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`:_issue.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${FormatDictionary[_issue.format]??issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${issue2.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};function ps_default(){return{localeError:error34()}}var error35=()=>{let Sizable={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},TypeDictionary={nan:"NaN",number:"liczba",array:"tablica"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`}case"invalid_value":return issue2.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`:_issue.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`:_issue.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`:_issue.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`:`Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${issue2.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};function pl_default(){return{localeError:error35()}}var error36=()=>{let Sizable={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",number:"n\xFAmero",null:"nulo"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`:`Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`}case"invalid_value":return issue2.values.length===1?`Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Muito grande: esperado que ${issue2.origin??"valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`:`Muito grande: esperado que ${issue2.origin??"valor"} fosse ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`:_issue.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`:_issue.format==="includes"?`Texto inv\xE1lido: deve incluir "${_issue.includes}"`:_issue.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Chave${issue2.keys.length>1?"s":""} desconhecida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${issue2.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${issue2.origin}`;default:return"Campo inv\xE1lido"}}};function pt_default(){return{localeError:error36()}}var error37=()=>{let Sizable={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},TypeDictionary={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`}case"invalid_value":return issue2.values.length===1?`Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`:`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Prea mare: a\u0219teptat ca ${issue2.origin??"valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemente"}`:`Prea mare: a\u0219teptat ca ${issue2.origin??"valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`:_issue.format==="ends_with"?`\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`:_issue.format==="includes"?`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`:_issue.format==="regex"?`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`:`Format invalid: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${issue2.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${issue2.origin}`;default:return"Intrare invalid\u0103"}}};function ro_default(){return{localeError:error37()}}function getRussianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;return lastTwoDigits>=11&&lastTwoDigits<=19?many:lastDigit===1?one:lastDigit>=2&&lastDigit<=4?few:many}var error38=()=>{let Sizable={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},TypeDictionary={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`}case"invalid_value":return issue2.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getRussianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getRussianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`:_issue.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`:_issue.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`:_issue.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length>1?"\u0438":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};function ru_default(){return{localeError:error38()}}var error39=()=>{let Sizable={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},TypeDictionary={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`:`Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`}case"invalid_value":return issue2.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Preveliko: pri\u010Dakovano, da bo ${issue2.origin??"vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${issue2.origin??"vrednost"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`:_issue.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`:_issue.format==="includes"?`Neveljaven niz: mora vsebovati "${_issue.includes}"`:_issue.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`:`Neveljaven ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznan${issue2.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${issue2.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${issue2.origin}`;default:return"Neveljaven vnos"}}};function sl_default(){return{localeError:error39()}}var error40=()=>{let Sizable={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},TypeDictionary={nan:"NaN",number:"antal",array:"lista"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`}case"invalid_value":return issue2.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`:_issue.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`:_issue.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`:_issue.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`:`Ogiltig(t) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${issue2.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${issue2.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};function sv_default(){return{localeError:error40()}}var error41=()=>{let Sizable={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`}case"invalid_value":return issue2.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:_issue.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:_issue.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:_issue.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};function ta_default(){return{localeError:error41()}}var error42=()=>{let Sizable={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},TypeDictionary={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`:`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`}case"invalid_value":return issue2.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",sizing=getSizing(issue2.origin);return sizing?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",sizing=getSizing(issue2.origin);return sizing?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`:_issue.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`:_issue.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:_issue.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};function th_default(){return{localeError:error42()}}var error43=()=>{let Sizable={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`:`Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`}case"invalid_value":return issue2.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin??"de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin??"de\u011Fer"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`:_issue.format==="ends_with"?`Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`:_issue.format==="includes"?`Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`:_issue.format==="regex"?`Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};function tr_default(){return{localeError:error43()}}var error44=()=>{let Sizable={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},TypeDictionary={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`}case"invalid_value":return issue2.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`:_issue.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`:_issue.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`:_issue.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length>1?"\u0456":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};function uk_default(){return{localeError:error44()}}function ua_default(){return uk_default()}var error45=()=>{let Sizable={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},TypeDictionary={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`:`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":return issue2.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:_issue.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:_issue.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:_issue.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length>1?"\u0632":""}: ${joinValues(issue2.keys,"\u060C ")}`;case"invalid_key":return`${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};function ur_default(){return{localeError:error45()}}var error46=()=>{let Sizable={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},TypeDictionary={nan:"NaN",number:"raqam",array:"massiv"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`:`Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`}case"invalid_value":return issue2.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`:`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`:`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`:_issue.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`:_issue.format==="includes"?`Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`:_issue.format==="regex"?`Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${issue2.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};function uz_default(){return{localeError:error46()}}var error47=()=>{let Sizable={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},TypeDictionary={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`:`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`}case"invalid_value":return issue2.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin??"gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin??"gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`:_issue.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`:_issue.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`:_issue.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`:`${FormatDictionary[_issue.format]??issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};function vi_default(){return{localeError:error47()}}var error48=()=>{let Sizable={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},TypeDictionary={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`:`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`}case"invalid_value":return issue2.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin??"\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin??"\u503C"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`:_issue.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`:_issue.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`:_issue.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`:`\u65E0\u6548${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};function zh_CN_default(){return{localeError:error48()}}var error49=()=>{let Sizable={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`:`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`}case"invalid_value":return issue2.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin??"\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin??"\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`:_issue.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`:_issue.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`:_issue.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`:`\u7121\u6548\u7684 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length>1?"\u5011":""}\uFF1A${joinValues(issue2.keys,"\u3001")}`;case"invalid_key":return`${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};function zh_TW_default(){return{localeError:error49()}}var error50=()=>{let Sizable={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},TypeDictionary={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return issue2=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return/^[A-Z]/.test(issue2.expected)?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`:`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`}case"invalid_value":return issue2.values.length===1?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin??"iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`:_issue.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`:_issue.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`:_issue.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`:`A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};function yo_default(){return{localeError:error50()}}var _a2,$output=Symbol("ZodOutput"),$input=Symbol("ZodInput"),$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta3=_meta[0];return this._map.set(schema,meta3),meta3&&typeof meta3=="object"&&"id"in meta3&&this._idmap.set(meta3.id,schema),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta3=this._map.get(schema);return meta3&&typeof meta3=="object"&&"id"in meta3&&this._idmap.delete(meta3.id),this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f2={...pm,...this._map.get(schema)};return Object.keys(f2).length?f2:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}};function registry(){return new $ZodRegistry}(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:!0,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:!0,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new Class2({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v2=>[v2,v2])):values;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value,params){return new Class2({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn){return new Class2({type:"transform",transform:fn})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:()=>catchValue})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn,...norm})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}function describe(description){let ch=new $ZodCheck({check:"describe"});return ch._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch._zod.check=()=>{},ch}function meta(metadata){let ch=new $ZodCheck({check:"meta"});return ch._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch._zod.check=()=>{},ch}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];params.case!=="sensitive"&&(truthyArray=truthyArray.map(v2=>typeof v2=="string"?v2.toLowerCase():v2),falsyArray=falsyArray.map(v2=>typeof v2=="string"?v2.toLowerCase():v2));let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,_String=Classes.String??$ZodString,stringSchema=new _String({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec2=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:((input,payload)=>{let data=input;return params.case!=="sensitive"&&(data=data.toLowerCase()),truthySet.has(data)?!0:falsySet.has(data)?!1:(payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec2,continue:!1}),{})}),reverseTransform:((input,_payload)=>input===!0?truthyArray[0]||"true":falsyArray[0]||"false"),error:params.error});return codec2}function _stringFormat(Class2,format,fnOrRegex,_params={}){let params=normalizeParams(_params),def={...normalizeParams(_params),check:"string_format",type:"string",format,fn:typeof fnOrRegex=="function"?fnOrRegex:val=>fnOrRegex.test(val),...params};return fnOrRegex instanceof RegExp&&(def.pattern=fnOrRegex),new Class2(def)}function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process3(schema,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||(result.ref=parent),process3(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta3=ctx.metadataRegistry.get(schema);return meta3&&Object.assign(result.schema,meta3),ctx.io==="input"&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a3=result.schema).default??(_a3.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let idToSchema=new Map;for(let entry2 of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry2[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry2[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry2[0])}}let makeURI=entry2=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry2[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry2[1].defId??entry2[1].schema.id??`schema${ctx.counter++}`;return entry2[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry2[1]===root)return{ref:"#"};let defUriPrefix=`#/${defsSegment}/`,defId=entry2[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=entry2=>{if(entry2[1].schema.$ref)return;let seen=entry2[1],{ref,defId}=makeURI(entry2);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry2 of ctx.seen.entries()){let seen=entry2[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
215
+
216
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry2 of ctx.seen.entries()){let seen=entry2[1];if(schema===entry2[0]){extractToDef(entry2);continue}if(ctx.external){let ext=ctx.external.registry.get(entry2[0])?.id;if(schema!==entry2[0]&&ext){extractToDef(entry2);continue}}if(ctx.metadataRegistry.get(entry2[0])?.id){extractToDef(entry2);continue}if(seen.cycle){extractToDef(entry2);continue}if(seen.count>1&&ctx.reused==="ref"){extractToDef(entry2);continue}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):Object.assign(schema2,refSchema),Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry2 of[...ctx.seen.entries()].reverse())flattenRef(entry2[0]);let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};for(let entry2 of ctx.seen.entries()){let seen=entry2[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,defs[seen.defId]=seen.def)}ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return process3(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process3(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format&&(json2.format=formatMap[format]??format,json2.format===""&&delete json2.format,format==="time"&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let regexes=[...patterns];regexes.length===1?json2.pattern=regexes[0].source:regexes.length>1&&(json2.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,_params)=>{let json2=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;typeof format=="string"&&format.includes("int")?json2.type="integer":json2.type="number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),typeof multipleOf=="number"&&(json2.multipleOf=multipleOf)},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);values.every(v2=>typeof v2=="number")&&(json2.type="number"),values.every(v2=>typeof v2=="string")&&(json2.type="string"),json2.enum=values},literalProcessor=(schema,ctx,json2,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val=="bigint"){if(ctx.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v2=>typeof v2=="number")&&(json2.type="number"),vals.every(v2=>typeof v2=="string")&&(json2.type="string"),vals.every(v2=>typeof v2=="boolean")&&(json2.type="boolean"),vals.every(v2=>v2===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,file2={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;minimum!==void 0&&(file2.minLength=minimum),maximum!==void 0&&(file2.maxLength=maximum),mime?mime.length===1?(file2.contentMediaType=mime[0],Object.assign(_json,file2)):(Object.assign(_json,file2),_json.anyOf=mime.map(m2=>({contentMediaType:m2}))):Object.assign(_json,file2)},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=process3(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object",json2.properties={};let shape=def.shape;for(let key in shape)json2.properties[key]=process3(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter(key=>{let v2=def.shape[key]._zod;return ctx.io==="input"?v2.optin===void 0:v2.optout===void 0}));requiredKeys.size>0&&(json2.required=Array.from(requiredKeys)),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=process3(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x2,i)=>process3(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=process3(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b2=process3(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b2)?b2.allOf:[b2]];json2.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x2,i)=>process3(x2,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process3(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,rest&&(json2.items=rest)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),json2.minItems=prefixItems.length,rest||(json2.maxItems=prefixItems.length)):(json2.items=prefixItems,rest&&(json2.additionalItems=rest));let{minimum,maximum}=schema._zod.bag;typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)},recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process3(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)json2.patternProperties[pattern.source]=valueSchema}else(ctx.target==="draft-07"||ctx.target==="draft-2020-12")&&(json2.propertyNames=process3(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})),json2.additionalProperties=process3(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]});let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter(v2=>typeof v2=="string"||typeof v2=="number");validKeyValues.length>0&&(json2.required=validKeyValues)}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=process3(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,ctx.io==="input"&&(json2._prefault=JSON.parse(JSON.stringify(def.defaultValue)))},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process3(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process3(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process3(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry2 of registry2._idmap.entries()){let[_2,schema]=entry2;process3(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry2 of registry2._idmap.entries()){let[key,schema]=entry2;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process3(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process3(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_2,...plainResult}=result;return plainResult}};var json_schema_exports={};var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date3,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid3,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});function date2(params){return _isoDate(ZodISODate,params)}var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});function time2(params){return _isoTime(ZodISOTime,params)}var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)});function duration2(params){return _isoDuration(ZodISODuration,params)}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue2=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues2=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);var _installedGroups=new WeakMap;function _installLazyMethods(inst,group,methods){let proto=Object.getPrototypeOf(inst),installed=_installedGroups.get(proto);if(installed||(installed=new Set,_installedGroups.set(proto,installed)),!installed.has(group)){installed.add(group);for(let key in methods){let fn=methods[key];Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let bound=fn.bind(this);return Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:bound}),bound},set(v2){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:v2})}})}}}var ZodType=$constructor("ZodType",(inst,def)=>($ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),_installLazyMethods(inst,"ZodType",{check(...chks){let def2=this.def;return this.clone(util_exports.mergeDefs(def2,{checks:[...def2.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def2,params){return clone(this,def2,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}}),Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst)),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,_installLazyMethods(inst,"_ZodString",{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime2(params)),inst.date=params=>inst.check(date2(params)),inst.time=params=>inst.check(time2(params)),inst.duration=params=>inst.check(duration2(params))});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:regexes_exports.httpProtocol,hostname:regexes_exports.domain,...util_exports.normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});function ulid3(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",regexes_exports.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",regexes_exports.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),_installLazyMethods(inst,"ZodNumber",{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}});let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??.5),inst.isFinite=!0,inst.format=bag.format??null});function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=params=>inst.check(_gt(BigInt(0),params)),inst.negative=params=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=params=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=params=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});function date3(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element,_installLazyMethods(inst,"ZodArray",{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.defineLazy(inst,"shape",()=>def.shape),_installLazyMethods(inst,"ZodObject",{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone({...this._zod.def,catchall})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}})});function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params),inst.rest=rest=>inst.clone({...inst._zod.def,rest})});function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k2=clone(keyType);return k2._zod.values=void 0,new ZodRecord({type:"record",keyType:k2,valueType,...util_exports.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v2=>[v2,v2])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload.fallback=!0,payload)):(payload.value=output,payload.fallback=!0,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:()=>catchValue})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn,ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe,meta2=meta;function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var z2={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path2=ref.slice(1).split("/").filter(Boolean);if(path2.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path2[0]===defsKey){let key=path2[1];if(!key||!ctx.defs[key])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z2.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z2.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z2.null();if(enumValues.length===0)return z2.never();if(enumValues.length===1)return z2.literal(enumValues[0]);if(enumValues.every(v2=>typeof v2=="string"))return z2.enum(enumValues);let literalSchemas=enumValues.map(v2=>z2.literal(v2));return literalSchemas.length<2?literalSchemas[0]:z2.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z2.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map(t=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z2.never():typeSchemas.length===1?typeSchemas[0]:z2.union(typeSchemas)}if(!type)return z2.any();let zodSchema;switch(type){case"string":{let stringSchema=z2.string();if(schema.format){let format=schema.format;format==="email"?stringSchema=stringSchema.check(z2.email()):format==="uri"||format==="uri-reference"?stringSchema=stringSchema.check(z2.url()):format==="uuid"||format==="guid"?stringSchema=stringSchema.check(z2.uuid()):format==="date-time"?stringSchema=stringSchema.check(z2.iso.datetime()):format==="date"?stringSchema=stringSchema.check(z2.iso.date()):format==="time"?stringSchema=stringSchema.check(z2.iso.time()):format==="duration"?stringSchema=stringSchema.check(z2.iso.duration()):format==="ipv4"?stringSchema=stringSchema.check(z2.ipv4()):format==="ipv6"?stringSchema=stringSchema.check(z2.ipv6()):format==="mac"?stringSchema=stringSchema.check(z2.mac()):format==="cidr"?stringSchema=stringSchema.check(z2.cidrv4()):format==="cidr-v6"?stringSchema=stringSchema.check(z2.cidrv6()):format==="base64"?stringSchema=stringSchema.check(z2.base64()):format==="base64url"?stringSchema=stringSchema.check(z2.base64url()):format==="e164"?stringSchema=stringSchema.check(z2.e164()):format==="jwt"?stringSchema=stringSchema.check(z2.jwt()):format==="emoji"?stringSchema=stringSchema.check(z2.emoji()):format==="nanoid"?stringSchema=stringSchema.check(z2.nanoid()):format==="cuid"?stringSchema=stringSchema.check(z2.cuid()):format==="cuid2"?stringSchema=stringSchema.check(z2.cuid2()):format==="ulid"?stringSchema=stringSchema.check(z2.ulid()):format==="xid"?stringSchema=stringSchema.check(z2.xid()):format==="ksuid"&&(stringSchema=stringSchema.check(z2.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z2.number().int():z2.number();typeof schema.minimum=="number"&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z2.boolean();break}case"null":{zodSchema=z2.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):z2.any();if(Object.keys(shape).length===0){zodSchema=z2.record(keySchema,valueSchema);break}let objectSchema2=z2.object(shape).passthrough(),recordSchema=z2.looseRecord(keySchema,valueSchema);zodSchema=z2.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z2.string().regex(new RegExp(pattern));looseRecords.push(z2.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0&&schemasToIntersect.push(z2.object(shape).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z2.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z2.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z2.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z2.object(shape);schema.additionalProperties===!1?zodSchema=objectSchema.strict():typeof schema.additionalProperties=="object"?zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx)):zodSchema=objectSchema.passthrough();break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),rest=items&&typeof items=="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;rest?zodSchema=z2.tuple(tupleItems).rest(rest):zodSchema=z2.tuple(tupleItems),typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z2.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z2.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let tupleItems=items.map(item=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems=="object"?convertSchema(schema.additionalItems,ctx):void 0;rest?zodSchema=z2.tuple(tupleItems).rest(rest):zodSchema=z2.tuple(tupleItems),typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z2.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z2.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z2.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z2.array(z2.any());break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z2.any():z2.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s=>convertSchema(s,ctx)),anyOfUnion=z2.union(options);baseSchema=hasExplicitType?z2.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s=>convertSchema(s,ctx)),oneOfUnion=z2.xor(options);baseSchema=hasExplicitType?z2.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z2.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z2.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z2.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z2.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);for(let key of Object.keys(schema))RECOGNIZED_KEYS.has(key)||(extraMeta[key]=schema[key]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z2.any():z2.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version2=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}config(en_default());var API_CONNECTION_PATH_FORMAT="letters, digits, -, _ and /, up to 200 characters, stored lower-cased",MAX_API_CONNECTION_PATH=200,API_IMPORT_PREFIX="./api/";function importSpecifier(path2){return`${API_IMPORT_PREFIX}${path2}`}function normalizeApiConnectionPath(path2){let trimmed=path2.trim().toLowerCase(),withoutPrefix=trimmed.startsWith(API_IMPORT_PREFIX)?trimmed.slice(API_IMPORT_PREFIX.length):trimmed;return collapseSlashes(withoutPrefix)}function collapseSlashes(path2){return path2.replaceAll(/\/+/g,"/").replace(/^\//,"").replace(/\/$/,"")}function apiConnectionPathError(path2){let normalized=normalizeApiConnectionPath(path2);if(!normalized)return"An import path is required.";if(normalized.length>MAX_API_CONNECTION_PATH)return`An import path can be at most ${MAX_API_CONNECTION_PATH} characters (that one is ${normalized.length}).`;if(!/^[a-z0-9_/-]+$/.test(normalized))return`An import path may only contain ${API_CONNECTION_PATH_FORMAT} \u2014 '${normalized}' has a character the API refuses.`}function assertApiConnectionPath(path2){let error51=apiConnectionPathError(path2);return error51&&fail(EXIT.USAGE,"INVALID_API_CONNECTION_PATH",error51),normalizeApiConnectionPath(path2)}var PATH_PROMPT=`Import path \u2014 scripts import it as ${API_IMPORT_PREFIX}<path> (${API_CONNECTION_PATH_FORMAT})`;function suggestPathFromLabel(label){return label.toLowerCase().replaceAll(/[^a-z0-9]+/g,"-").replaceAll(/^-+|-+$/g,"")}import{basename as basename2,extname}from"path";var SCRIPT_NAME_FORMAT="letters, digits, dashes, underscores and / for folders \u2014 no file extension",MAX_SCRIPT_NAME=500,SCRIPT_NAME_RULE=`${SCRIPT_NAME_FORMAT}, up to ${MAX_SCRIPT_NAME} characters, leading and trailing slashes stripped and repeated ones collapsed`,ALLOWED=/^[A-Za-z0-9/_-]+$/;function normalizeScriptName(name){return name.trim().replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}function scriptNameError(name){let normalized=normalizeScriptName(name);if(!normalized)return"A script name is required.";if(normalized.length>MAX_SCRIPT_NAME)return`A script name can be at most ${MAX_SCRIPT_NAME} characters.`;if(normalized.includes("."))return"A script name has no file extension \u2014 drop the dot and anything after it.";if(!ALLOWED.test(normalized))return`Use ${SCRIPT_NAME_FORMAT}. '${name}' has a character the API refuses.`}function assertScriptName(name){let error51=scriptNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_SCRIPT_NAME",error51),normalizeScriptName(name)}function suggestNameFromPath(path2){let base=basename2(path2,extname(path2)),cleaned=normalizeScriptName(base.replace(/[^A-Za-z0-9/_-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""));return scriptNameError(cleaned)?void 0:cleaned}import{join as join12}from"path";import{createHash as createHash2}from"crypto";import{readFileSync as readFileSync9}from"fs";import{join as join9}from"path";var METADATA_FILE="workspace.json",METADATA_VERSION=1;function checksumOf(content){return`sha256:${createHash2("sha256").update(content).digest("hex")}`}function renderMetadata(metadata){return`${JSON.stringify(metadata,null,4)}
217
+ `}function record2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function idAndRequiredName(value){let parsed=record2(value),id=parsed?.id,name=parsed?.name;if(!(typeof id!="string"||id==="")&&!(typeof name!="string"||name===""))return{id,name}}function idAndName(value){let parsed=record2(value),id=parsed?.id;if(typeof id!="string"||id==="")return;let name=parsed?.name;return typeof name=="string"?{id,name}:{id}}function trackedScripts(value){let parsed=record2(value)??{},out={};for(let[name,entry2]of Object.entries(parsed)){let fields=record2(entry2),checksum=fields?.checksum;if(typeof checksum!="string")continue;let id=fields?.id;out[name]=typeof id=="string"&&id!==""?{id,checksum}:{checksum}}return out}function trackedPayloads(value){let parsed=record2(value)??{},out={};for(let[path2,entry2]of Object.entries(parsed)){let fields=record2(entry2),checksum=fields?.checksum,eventListenerId=fields?.eventListenerId;if(typeof checksum!="string"||typeof eventListenerId!="string")continue;let id=fields?.id;out[path2]=typeof id=="string"&&id!==""?{eventListenerId,id,checksum}:{eventListenerId,checksum}}return out}function trackedReadme(value){let checksum=record2(value)?.checksum;return typeof checksum=="string"&&checksum!==""?{checksum}:void 0}function readMetadata(directory){let raw;try{raw=readFileSync9(join9(directory,METADATA_FILE),"utf8")}catch{return{}}let parsed;try{parsed=JSON.parse(raw)}catch{return{problem:`${METADATA_FILE} is not valid JSON.`}}let fields=record2(parsed);if(!fields)return{problem:`${METADATA_FILE} is not an object.`};let version2=fields.version;if(typeof version2!="number")return{problem:`${METADATA_FILE} has no version.`};if(version2>METADATA_VERSION)return{problem:`${METADATA_FILE} was written by a newer version of the CLI (format ${version2}, this build understands ${METADATA_VERSION}).`};let team=idAndRequiredName(fields.team),workspace=idAndName(fields.workspace),environment=idAndName(fields.environment);if(!team||!workspace||!environment)return{problem:`${METADATA_FILE} does not name a team, workspace and environment.`};let instance4=fields.instance,release2=record2(fields.environment)?.release,readme=trackedReadme(fields.readme);return{metadata:{version:version2,cli:typeof fields.cli=="string"?fields.cli:"",instance:typeof instance4=="string"?instance4:"",team,workspace,environment:{...environment,...typeof release2=="string"?{release:release2}:{release:null}},clonedAt:typeof fields.clonedAt=="string"?fields.clonedAt:"",pushedAt:typeof fields.pushedAt=="string"?fields.pushedAt:null,scripts:trackedScripts(fields.scripts),testPayloads:trackedPayloads(fields.testPayloads),...readme?{readme}:{}}}}function writerTag(){return`${PACKAGE}@${VERSION}`}function scriptPath(name){return`scripts/${name}.ts`}function scriptNameFromPath(relativePath){if(!relativePath.startsWith("scripts/")||relativePath.startsWith("scripts/api/")||!relativePath.endsWith(".ts"))return;let name=relativePath.slice(8,-3);return name===""?void 0:name}function listenerIdFromFolder(folder){let id=/\(([^()]+)\)$/.exec(folder.trim())?.[1]?.trim();return id===void 0||id===""?void 0:id}function payloadRefFromPath(relativePath){let parts=relativePath.split("/");if(parts.length!==3||parts[0]!=="test-payloads")return;let folder=parts[1]??"",file2=parts[2]??"";if(!file2.endsWith(".json"))return;let eventListenerId=listenerIdFromFolder(folder);if(!eventListenerId)return;let name=file2.slice(0,-5);return name===""?void 0:{eventListenerId,name}}import{lstatSync as lstatSync3,mkdirSync as mkdirSync8,readFileSync as readFileSync11,readdirSync as readdirSync6,renameSync as renameSync4,rmSync as rmSync7,writeFileSync as writeFileSync7}from"fs";import{dirname as dirname3,join as join11,resolve as resolve4}from"path";var notSettled=Symbol("not-settled"),throttleAll=(limit,tasks)=>{if(!Number.isInteger(limit)||limit<1)throw new TypeError(`Expected \`limit\` to be a finite number > 0, got \`${limit}\` (${typeof limit})`);if(!Array.isArray(tasks)||!tasks.every(task=>typeof task=="function"))throw new TypeError("Expected `tasks` to be a list of functions returning a promise");return new Promise((resolve8,reject)=>{let result=Array(tasks.length).fill(notSettled),entries=tasks.entries(),next=()=>{let{done,value}=entries.next();if(done){!result.includes(notSettled)&&resolve8(result);return}let[index,task]=value,onFulfilled=x2=>{result[index]=x2,next()};task().then(onFulfilled,reject)};Array(limit).fill(0).forEach(next)})};var TSCONFIG_JSON=`{
218
+ "extends": "./tsconfig.base.json",
219
+ "compilerOptions": {
220
+ "types": ["@sr-connect/runtime-types"]
221
+ },
222
+ "include": ["scripts", "ev-params.ts"]
223
+ }
224
+ `,ESLINT_CONFIG_JS=`import prettierPlugin from 'eslint-plugin-prettier';
225
+ import prettierConfig from 'eslint-config-prettier';
226
+ import typescriptParser from '@typescript-eslint/parser';
227
+ import typescriptPlugin from '@typescript-eslint/eslint-plugin';
228
+
229
+ export default [
230
+ {
231
+ files: ['**/*.ts'],
232
+ ignores: ['ev-params.ts', 'scripts/api/**/*'],
233
+ languageOptions: {
234
+ parser: typescriptParser,
235
+ parserOptions: {
236
+ project: ['tsconfig.json', './node/tsconfig.json'],
237
+ },
238
+ },
239
+ plugins: {
240
+ prettier: prettierPlugin,
241
+ '@typescript-eslint': typescriptPlugin,
242
+ },
243
+ rules: {
244
+ ...typescriptPlugin.configs.recommended.rules,
245
+ // Turn off stylistic rules that would conflict with Prettier; formatting is enforced by prettier/prettier below.
246
+ ...prettierConfig.rules,
247
+ 'prettier/prettier': 'warn',
248
+ '@typescript-eslint/no-unused-vars': 'warn',
249
+ '@typescript-eslint/no-explicit-any': 'warn',
250
+ '@typescript-eslint/no-floating-promises': 'warn',
251
+ },
252
+ },
253
+ ];
254
+ `,GITIGNORE=`node_modules/
255
+ .DS_Store
256
+ .vscode/sftp.json
257
+ http_logs_*.json
258
+ `,PRETTIERRC=`{
259
+ "tabWidth": 4,
260
+ "useTabs": true,
261
+ "singleQuote": true,
262
+ "printWidth": 120
263
+ }`,PNPM_WORKSPACE_YAML=`# unrs-resolver (jest-resolve's module-resolution engine since Jest 30) ships a
264
+ # native binary via a postinstall build script, which pnpm blocks unless explicitly allowed.
265
+ allowBuilds:
266
+ unrs-resolver: true
267
+ # pnpm uses a strict node_modules layout where transitive dependencies are not
268
+ # accessible from project code. The auto-generated files in scripts/api/ and
269
+ # node/apiRegistry.ts import @managed-api/commons-core directly (it is a
270
+ # transitive dependency of the *-sr-connect packages), so hoist it to the root.
271
+ publicHoistPattern:
272
+ - '@managed-api/*'
273
+ `,NODE_API_REGISTRY_TS=`import { BaseApiCore } from '@managed-api/commons-core';
274
+
275
+ export abstract class ManagedApiCore extends BaseApiCore {
276
+ constructor(public connectionId: string) {
277
+ super();
278
+ }
279
+ }
280
+
281
+ export type ApiRegistry = Record<string, ManagedApiCore>;
282
+
283
+ /**
284
+ * Declare locally implemented API connections here, keyed by the API Connection name used under
285
+ * scripts/api/. When a script runs locally with runtimeMocks.ts loaded, the mocked fetch routes
286
+ * Managed API calls to the matching entry below.
287
+ *
288
+ * Example \u2014 a local 'slack' implementation that forwards calls to the real Slack API with a test token:
289
+ *
290
+ * import { PlatformImplementation, Response as ApiResponse, Headers as ApiHeaders } from '@managed-api/commons-core';
291
+ * import { SlackApi } from '@managed-api/slack-sr-connect';
292
+ *
293
+ * const SLACK_TEST_TOKEN = ''; // paste a test token here, or read it in node/ and hand it in below
294
+ *
295
+ * slack: new (class extends SlackApi {
296
+ * constructor(private readonly token: string) {
297
+ * super('LOCAL_SLACK');
298
+ * }
299
+ * protected getPlatformImplementation(): PlatformImplementation {
300
+ * return {
301
+ * buffer: {
302
+ * encode: (input) => new TextEncoder().encode(input).buffer as ArrayBuffer,
303
+ * decode: (input) => new TextDecoder().decode(input),
304
+ * },
305
+ * performHttpCall: async (request) => {
306
+ * const url = new URL(request.url, 'https://slack.com/api/');
307
+ * const response = await fetch(url, {
308
+ * method: request.method,
309
+ * headers: {
310
+ * ...Object.fromEntries(request.headers),
311
+ * // This file is compiled with the platform types too, where \`process\` does not
312
+ * // exist: read secrets in node/tests and hand them to the class instead,
313
+ * // which is what the constructor parameter above is for.
314
+ * Authorization: \`Bearer \${this.token}\`,
315
+ * },
316
+ * body: ['GET', 'HEAD'].includes(request.method) ? undefined : await request.arrayBuffer(),
317
+ * });
318
+ * return new ApiResponse(
319
+ * url.toString(),
320
+ * response.status,
321
+ * response.statusText,
322
+ * new ApiHeaders(Object.fromEntries(response.headers)),
323
+ * await response.arrayBuffer(),
324
+ * );
325
+ * },
326
+ * };
327
+ * }
328
+ * })(SLACK_TEST_TOKEN),
329
+ */
330
+ export const API_REGISTRY: ApiRegistry = {
331
+ // Declare here locally implemented API connections
332
+ };
333
+ `,NODE_RUNTIME_MOCKS_TS=`import { API_REGISTRY } from './apiRegistry';
334
+ import { ulid } from 'ulid';
335
+ import { promises as fs } from 'fs';
336
+
337
+ // The fetch init types come from whichever @types/node the project resolves, derived from the
338
+ // global fetch signature so they can never disagree with the globals Headers/FormData/Request
339
+ // used below. Importing them from undici-types pinned a second copy of that package and the two
340
+ // copies' FormData types did not unify, which failed \`tsc -p node/tsconfig.json\` on a fresh clone.
341
+ type FetchInit = NonNullable<Parameters<typeof fetch>[1]>;
342
+ type BodyInit = NonNullable<FetchInit['body']>;
343
+ type HeadersInit = NonNullable<FetchInit['headers']>;
344
+ /**
345
+ * This file provides mocks for Node runtime that otherwise exist in ScriptRunner Connect runtime.
346
+ * In your tests make sure to import this file as following: \`import '../runtimeMocks'\`;
347
+ *
348
+ * What is mocked and how it differs from the platform:
349
+ * - @sr-connect/convert (global _convert): full implementation on top of Buffer.
350
+ * - @sr-connect/record-storage (global _processRecordStorageRequest): in-memory storage matching the
351
+ * platform's key and teamScope validation, case-insensitive key handling, scope partitioning, ttl
352
+ * expiry (including the 20-minute invocation-scope cap) and denyUpdateOverwrite conflicts. The secure
353
+ * option is ignored (values round-trip unencrypted), getAllKeys is not paginated, and every invocation
354
+ * in one test process shares the 'invocation' scope. Payload size limits and rate
355
+ * limiting are not enforced locally, so an oversized value and the package's 429-retry path both
356
+ * go unexercised here \u2014 check the product documentation for the limits a real invocation applies.
357
+ * - @sr-connect/trigger (global _triggerScript): no-op that logs a warning.
358
+ * - ServiceError global: same implementation as the platform's.
359
+ * - fetch: intercepted to route Managed API calls (x-stitch-connection-id + relative URL) to
360
+ * implementations registered in apiRegistry.ts, and to emulate the platform's special headers:
361
+ * x-stitch-store-body, x-stitch-stored-body-id (+ the form-data file name/identifier/additional-fields
362
+ * headers), x-stitch-transform-stored-body ('form-data' and 'embedded-base64') and x-stitch-drop-body.
363
+ * Like on the platform, all x-stitch-* headers are stripped from the outbound request \u2014 both for
364
+ * plain fetch calls and for calls routed to a locally registered API implementation (with one
365
+ * exception: a Request object passed into a routed call is used as-is by the Managed API layer,
366
+ * so headers baked into it are not stripped; Managed APIs always call with string URLs). Requests
367
+ * with a GET/HEAD method and a body are rejected like on the platform. Also like on the platform:
368
+ * the outbound content-type defaults to application/json when none is set (and is dropped again for
369
+ * the form-data stored-body transform so the multipart boundary content type wins), every response
370
+ * carries the x-stitch-time header (actual HTTP call time in milliseconds), and content-encoding and
371
+ * transfer-encoding response headers are removed because the returned body is already decoded.
372
+ * Remaining divergences: the x-stitch-ignore-ssl-check header is ignored, validation errors are
373
+ * thrown as plain Error while the platform throws FetchError/TypeError with the same messages
374
+ * (catch by message, not by type), and stored body ids live in one process-wide map instead of
375
+ * being namespaced per invocation like on the platform.
376
+ *
377
+ * To log out intercepted HTTP calls, set the environment variable SRC_LOG_HTTP_CALLS to true. This will create a file in the current directory called http_logs_<timestamp>.json.
378
+ */
379
+
380
+ /**
381
+ * Mocks for @sr-connect/convert package.
382
+ */
383
+ global._convert = {
384
+ base64ToBuffer: (base64) => Buffer.from(base64, 'base64'),
385
+ base64ToText: (base64, encoding) => Buffer.from(base64, 'base64').toString(encoding ?? 'utf8'),
386
+ bufferToBase64: (buffer) => Buffer.from(buffer).toString('base64'),
387
+ bufferToText: (buffer, encoding) => Buffer.from(buffer).toString(encoding ?? 'utf8'),
388
+ textToBase64: (text, encoding) => Buffer.from(text, encoding ?? 'utf8').toString('base64'),
389
+ textToBuffer: (text, encoding) => Buffer.from(text, encoding ?? 'utf8'),
390
+ textToText: (text, sourceEncoding, targetEncoding) =>
391
+ Buffer.from(text, sourceEncoding ?? 'utf8').toString(targetEncoding ?? 'utf8'),
392
+ };
393
+
394
+ interface StoredRecord {
395
+ value: RecordStorageValue;
396
+ /** Expiry epoch in milliseconds; records past it read as absent everywhere. */
397
+ expires?: number;
398
+ }
399
+
400
+ // One map per scope, the way the platform keeps every scope separate (and every teamScope within
401
+ // the team scope). Locally a single workspace/environment/invocation exists, so the scope name
402
+ // alone addresses the map \u2014 which also means every invocation in one test process
403
+ // shares the 'invocation' scope, unlike on the platform.
404
+ const recordStoragePartitions: Record<string, Record<string, StoredRecord>> = {};
405
+
406
+ /**
407
+ * Computes the record expiry like the platform: the given ttl (seconds) from now, and the
408
+ * invocation scope is always capped at 20 minutes even when no ttl is requested.
409
+ */
410
+ function getRecordExpiry(scope: RecordStorageScope, ttl?: number): number | undefined {
411
+ const MAX_INVOCATION_RECORD_TTL = 20 * 60;
412
+ if (scope === 'invocation' && (!ttl || ttl > MAX_INVOCATION_RECORD_TTL)) {
413
+ return Date.now() + MAX_INVOCATION_RECORD_TTL * 1000;
414
+ }
415
+ if (ttl) {
416
+ return Date.now() + ttl * 1000;
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Returns the stored record, treating expired records as absent (get, exists, getAllKeys and the
422
+ * denyUpdateOverwrite conflict check all go through here). Expired records are deleted lazily on
423
+ * access, so an expired record reads as absent rather than as an error, as it does on the platform.
424
+ */
425
+ function getLiveRecord(partition: Record<string, StoredRecord>, key: string): StoredRecord | undefined {
426
+ const record = partition[key];
427
+ if (record?.expires !== undefined && record.expires <= Date.now()) {
428
+ delete partition[key];
429
+ return undefined;
430
+ }
431
+ return record;
432
+ }
433
+
434
+ /**
435
+ * Mock for @sr-connect/record-storage package.
436
+ * This mock implements a simple in-memory Record Storage; see the file header for what is ignored.
437
+ * If you need special behavior in tests consider mocking it as following: jest.spyOn(global, '_processRecordStorageRequest').mockImplementation((request) => { // Your implementation });
438
+ */
439
+ global._processRecordStorageRequest = async (request) => {
440
+ if (request.kind !== 'RECORD_GET_ALL_KEYS') {
441
+ // Validation mirrors the platform: the key is validated as provided
442
+ // (the character check rejects whitespace) and keys of 1024 bytes or more are rejected.
443
+ if (!request.key || request.key.trim().length === 0) {
444
+ return {
445
+ error: {
446
+ code: 400,
447
+ message: 'Key is required',
448
+ },
449
+ };
450
+ } else if (Buffer.byteLength(request.key.trim(), 'utf8') >= 1024) {
451
+ return {
452
+ error: {
453
+ code: 400,
454
+ message: 'Key size exceeds 1024 bytes. Please use a shorter key.',
455
+ },
456
+ };
457
+ } else if (!/^[A-Za-z0-9_-]*$/.test(request.key)) {
458
+ return {
459
+ error: {
460
+ code: 400,
461
+ message: 'Key can only contain alphanumeric characters, underscores and dashes.',
462
+ },
463
+ };
464
+ }
465
+ }
466
+
467
+ // The platform lowercases every key, so keys are case-insensitive:
468
+ // 'MyKey' and 'mykey' address the same record and getAllKeys returns lowercased keys.
469
+ const key = request.key?.toLowerCase() ?? '';
470
+
471
+ // Only null and undefined are prohibited record values; falsy values like 0, false and '' are valid.
472
+ if (request.kind === 'RECORD_SET' && (request.value === undefined || request.value === null)) {
473
+ return {
474
+ error: {
475
+ code: 400,
476
+ message: \`Record value type is not allowed: \${request.value === null ? 'null' : 'undefined'}\`,
477
+ },
478
+ };
479
+ }
480
+
481
+ // teamScope validation mirrors the platform: teamScope is only valid together
482
+ // with the team scope and is constrained to alphanumeric characters (max 200).
483
+ const scope = request.scope ?? 'environment';
484
+ if (request.teamScope && scope !== 'team') {
485
+ return {
486
+ error: {
487
+ code: 400,
488
+ message: "Team scope can only be used when the scope is set to 'team'.",
489
+ },
490
+ };
491
+ }
492
+ if (request.teamScope && (request.teamScope.length > 200 || !/^[a-zA-Z0-9]+$/.test(request.teamScope))) {
493
+ return {
494
+ error: {
495
+ code: 400,
496
+ message: "Only alphanumeric characters are allowed (max 200 characters) for 'teamScope'.",
497
+ },
498
+ };
499
+ }
500
+
501
+ // Like the platform, scopes are separate, not nested: a workspace-scope write is
502
+ // invisible to an environment-scope read, and each teamScope is its own team namespace.
503
+ const partitionKey = scope === 'team' && request.teamScope ? \`team#\${request.teamScope}\` : scope;
504
+ const partition = (recordStoragePartitions[partitionKey] ??= {});
505
+
506
+ switch (request.kind) {
507
+ case 'RECORD_GET':
508
+ return {
509
+ value: getLiveRecord(partition, key)?.value,
510
+ };
511
+ case 'RECORD_SET':
512
+ if (request.denyUpdateOverwrite && getLiveRecord(partition, key)) {
513
+ return {
514
+ error: {
515
+ code: 400,
516
+ message: \`Record already exists in given scope (\${scope}) with key: \${request.key}\`,
517
+ },
518
+ };
519
+ }
520
+ partition[key] = { value: request.value!, expires: getRecordExpiry(scope, request.ttl) };
521
+ return {};
522
+ case 'RECORD_EXISTS':
523
+ // A record with a falsy value (0, false, '') still exists.
524
+ return {
525
+ value: getLiveRecord(partition, key) !== undefined,
526
+ };
527
+ case 'RECORD_DELETE':
528
+ delete partition[key];
529
+ return {};
530
+ case 'RECORD_GET_ALL_KEYS':
531
+ return {
532
+ value: {
533
+ keys: Object.keys(partition).filter(
534
+ (storedKey) => getLiveRecord(partition, storedKey) !== undefined,
535
+ ),
536
+ },
537
+ };
538
+ }
539
+ };
540
+
541
+ /**
542
+ * Mock for @sr-connect/trigger package.
543
+ */
544
+ global._triggerScript = async () => {
545
+ console.warn(
546
+ 'Function call triggerScript from @sr-connect/trigger package was ignored because it is mocked locally.',
547
+ );
548
+ return {
549
+ result: {
550
+ invocationId: 'MOCK_INVOCATION_ID',
551
+ },
552
+ };
553
+ };
554
+
555
+ /**
556
+ * Error class that ScriptRunner Connect packages use internally.
557
+ * Mirrors the platform's implementation exactly, including the message formatting.
558
+ */
559
+ class ServiceError extends Error {
560
+ public name = 'ServiceError';
561
+
562
+ constructor(
563
+ public errorCode?: number,
564
+ message?: string,
565
+ public service?: string,
566
+ ) {
567
+ super(errorCode ? \`\${message} - ScriptRunner Connect Error code: \${errorCode}\` : \`\${message}\`);
568
+
569
+ if (service) {
570
+ this.setService(service);
571
+ }
572
+ }
573
+
574
+ public set(errorCode: number, message: string): void {
575
+ this.errorCode = errorCode;
576
+ this.message = errorCode ? \`\${message} - ScriptRunner Connect Error code: \${errorCode}\` : \`\${message}\`;
577
+ }
578
+
579
+ public setService(service: string): void {
580
+ this.name = \`ServiceError (\${service})\`;
581
+ }
582
+ }
583
+
584
+ interface StoredBody {
585
+ body: ArrayBuffer;
586
+ contentType: string | null;
587
+ }
588
+
589
+ const STORED_BODY_IDS = new Map<string, StoredBody>();
590
+
591
+ // Statuses that must not carry a body per the Fetch spec \u2014 the Response constructor throws otherwise.
592
+ const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
593
+
594
+ const originalFetch: typeof fetch = globalThis.fetch.bind(globalThis);
595
+ globalThis.fetch = (async (...args: Parameters<typeof fetch>): Promise<Response> => {
596
+ let [input, init] = args;
597
+
598
+ const url = input instanceof Request ? input.url : input.toString();
599
+ // Normalize every HeadersInit shape (Headers, tuple array, plain record) once; Headers matches
600
+ // names case-insensitively, like the platform. Fall back to a Request object's own headers.
601
+ const requestHeaders = init?.headers
602
+ ? new Headers(init.headers as HeadersInit)
603
+ : input instanceof Request
604
+ ? input.headers
605
+ : new Headers();
606
+ const connectionId = requestHeaders.get('x-stitch-connection-id');
607
+ const storeBody = requestHeaders.get('x-stitch-store-body') === 'true';
608
+ const dropBody = requestHeaders.get('x-stitch-drop-body') === 'true';
609
+ const storedBodyId = requestHeaders.get('x-stitch-stored-body-id');
610
+
611
+ // Like the platform, the two response-body treatments are mutually exclusive.
612
+ if (storeBody && dropBody) {
613
+ throw Error('Only one of x-stitch-drop-body & x-stitch-store-body can be true');
614
+ }
615
+
616
+ // The platform rejects every fetch with a GET/HEAD method and a body. Check against the
617
+ // caller's original body, before the stored-body transform below assigns one, to match the
618
+ // order the platform applies the check in.
619
+ const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
620
+ if (init?.body && (method === 'GET' || method === 'HEAD')) {
621
+ throw Error('Request with GET/HEAD method cannot have body');
622
+ }
623
+
624
+ // The platform strips ALL x-stitch-* control headers before the request leaves it \u2014 for
625
+ // plain fetch calls and Managed API (connection-routed) calls alike.
626
+ // Do the same here, before routing, so locally registered implementations never see them
627
+ // and cannot accidentally re-forward them into this mocked fetch (double store-body handling).
628
+ const outboundHeaders = new Headers(requestHeaders);
629
+ let headersChanged = false;
630
+ for (const name of [...outboundHeaders.keys()]) {
631
+ if (name.startsWith('x-stitch-')) {
632
+ outboundHeaders.delete(name);
633
+ headersChanged = true;
634
+ }
635
+ }
636
+
637
+ // Like the platform, every outbound request defaults to a JSON content type when none is set.
638
+ // This runs before the form-data deletion below, in the order the platform applies them: the
639
+ // default is added first and the stored-body path then removes it again.
640
+ if (!outboundHeaders.has('content-type')) {
641
+ outboundHeaders.set('content-type', 'application/json');
642
+ headersChanged = true;
643
+ }
644
+
645
+ if (storedBodyId) {
646
+ const storedBody = STORED_BODY_IDS.get(storedBodyId);
647
+ if (!storedBody) {
648
+ throw Error(\`Stored body ID \${storedBodyId} not found\`);
649
+ }
650
+
651
+ // Do not mutate the caller's init object.
652
+ init = { ...init, body: transformStoredBody(storedBody, requestHeaders, init?.body) };
653
+
654
+ // Like the platform, drop the caller's content type for the form-data transform so the
655
+ // boundary content type generated for the FormData body wins (embedded-base64 keeps the
656
+ // caller's header).
657
+ if ((requestHeaders.get('x-stitch-transform-stored-body') ?? 'form-data') === 'form-data') {
658
+ outboundHeaders.delete('content-type');
659
+ }
660
+ }
661
+
662
+ // Check if the connection ID is present and the URL is relative, which means the request should be forwarded to registered API implementation instead
663
+ if (connectionId && !(url.startsWith('http://') || url.startsWith('https://'))) {
664
+ const apiConnection = Object.values(API_REGISTRY).find((api) => api.connectionId === connectionId);
665
+
666
+ if (!apiConnection) {
667
+ throw Error(
668
+ \`Connection ID \${connectionId} was passed with the fetch headers, but no matching locally registered API was found in node/apiRegistry.ts\`,
669
+ );
670
+ } else {
671
+ // Pass the stripped headers as a plain record: the Managed API's own Headers class
672
+ // silently drops all entries when given a web Headers instance (it iterates with
673
+ // Object.entries), so a Headers object must never be handed to apiConnection.fetch.
674
+ const routedInit = { ...init, headers: Object.fromEntries(outboundHeaders.entries()) };
675
+ const startTime = Date.now();
676
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
677
+ const response = await apiConnection.fetch(input as any, routedInit as any);
678
+ const fetchTime = Date.now() - startTime;
679
+ // No log here: when the local implementation performs a real HTTP call it goes back
680
+ // through this mocked global fetch, which logs the actual outbound request.
681
+
682
+ // Lowercase every name: the Managed API Headers class preserves the handler's casing,
683
+ // but the platform normalizes response header names to lowercase before any
684
+ // of this logic runs (the stored body's content-type lookup below relies on it).
685
+ const headers = Object.entries(response.headers.raw()).reduce<Record<string, string>>(
686
+ (prev, [name, values]) => ({ ...prev, [name.toLowerCase()]: values.join(',') }),
687
+ {},
688
+ );
689
+
690
+ // Like the platform, drop encoding headers (the body handed back is already decoded)
691
+ // and expose the actual HTTP call time.
692
+ delete headers['content-encoding'];
693
+ delete headers['transfer-encoding'];
694
+ headers['x-stitch-time'] = String(fetchTime);
695
+
696
+ // The body can only be read once, so read it here and reuse it below for both storing and the reconstructed response.
697
+ const arrayBuffer = await response.arrayBuffer();
698
+
699
+ if (storeBody) {
700
+ const storeBodyId = ulid();
701
+ STORED_BODY_IDS.set(storeBodyId, { body: arrayBuffer, contentType: headers['content-type'] ?? null });
702
+ headers['x-stitch-stored-body-id'] = storeBodyId;
703
+ }
704
+
705
+ // Like the platform, return the response without a body when it was stored externally or dropped.
706
+ const responseBody =
707
+ !NULL_BODY_STATUSES.has(response.status) && !storeBody && !dropBody ? arrayBuffer : undefined;
708
+
709
+ return new Response(responseBody, {
710
+ headers,
711
+ status: response.status,
712
+ statusText: response.statusText,
713
+ });
714
+ }
715
+ }
716
+
717
+ // Only replace the caller's headers when something actually changed (an x-stitch-* strip, the
718
+ // content-type default, or the form-data content-type deletion), so a plain passthrough
719
+ // request keeps its original init untouched.
720
+ if (headersChanged) {
721
+ init = { ...init, headers: outboundHeaders };
722
+ }
723
+
724
+ const startTime = Date.now();
725
+ const response = await originalFetch(input, init);
726
+ const fetchTime = Date.now() - startTime;
727
+
728
+ // Like the platform, drop encoding headers (fetch has already decoded the body, so a surviving
729
+ // content-encoding would lie about the payload) and expose the actual HTTP call time.
730
+ const responseHeaders = new Headers(response.headers);
731
+ responseHeaders.delete('content-encoding');
732
+ responseHeaders.delete('transfer-encoding');
733
+ responseHeaders.set('x-stitch-time', String(fetchTime));
734
+
735
+ if (storeBody) {
736
+ const storeBodyId = ulid();
737
+ const storedResponseBody = await response.arrayBuffer();
738
+ STORED_BODY_IDS.set(storeBodyId, {
739
+ body: storedResponseBody,
740
+ contentType: response.headers.get('content-type'),
741
+ });
742
+ responseHeaders.append('x-stitch-stored-body-id', storeBodyId);
743
+
744
+ // Log the real response body even though the returned Response carries none \u2014 the body
745
+ // was stored, not dropped, and the HTTP log should show what the endpoint returned.
746
+ await logHTTPCall(response.status, responseHeaders, storedResponseBody, input, init);
747
+
748
+ return new Response(undefined, {
749
+ headers: responseHeaders,
750
+ status: response.status,
751
+ statusText: response.statusText,
752
+ });
753
+ }
754
+
755
+ const responseBody =
756
+ !NULL_BODY_STATUSES.has(response.status) && !dropBody ? await response.arrayBuffer() : undefined;
757
+
758
+ const reconstructedResponse = new Response(responseBody, {
759
+ headers: responseHeaders,
760
+ status: response.status,
761
+ statusText: response.statusText,
762
+ });
763
+
764
+ await logHTTPCall(response.status, responseHeaders, responseBody, input, init);
765
+
766
+ return reconstructedResponse;
767
+ }) as typeof fetch;
768
+
769
+ /**
770
+ * Applies the platform's x-stitch-transform-stored-body behavior to a previously stored body:
771
+ * - 'form-data' (default): wrap the stored body into multipart form data, honoring the
772
+ * x-stitch-stored-body-form-data-file-name/-file-identifier/-additional-fields headers.
773
+ * - 'embedded-base64': replace the single [storedBodyBase64] marker in the request body with the
774
+ * base64-encoded stored body.
775
+ */
776
+ function transformStoredBody(
777
+ storedBody: StoredBody,
778
+ requestHeaders: Headers,
779
+ originalBody: BodyInit | null | undefined,
780
+ ): BodyInit {
781
+ // Like the platform, default to form-data wrapping unless another transform is requested.
782
+ const transformType = requestHeaders.get('x-stitch-transform-stored-body') ?? 'form-data';
783
+
784
+ switch (transformType) {
785
+ case 'form-data': {
786
+ const fileName = requestHeaders.get('x-stitch-stored-body-form-data-file-name') ?? 'file';
787
+ const fileIdentifier = requestHeaders.get('x-stitch-stored-body-form-data-file-identifier') ?? 'file';
788
+ const additionalFields = requestHeaders.get('x-stitch-stored-body-form-data-additional-fields');
789
+
790
+ const formData = new FormData();
791
+ formData.append(
792
+ fileIdentifier,
793
+ new Blob([storedBody.body], { type: storedBody.contentType ?? undefined }),
794
+ fileName,
795
+ );
796
+
797
+ if (additionalFields) {
798
+ // Same validation as the platform: key-value pairs separated by ';', each key and
799
+ // value separated by ':', and the header must end with ';'.
800
+ if (!/^([^\\r\\n]+:[^\\r\\n]+;)$/.test(additionalFields)) {
801
+ throw Error(
802
+ 'Invalid x-stitch-stored-body-form-data-additional-fields passed. ' +
803
+ 'The header must be a string of key-value pairs separated by ";". ' +
804
+ 'Each key and value must be separated by ":". The header should end with ";". ' +
805
+ 'For example: "foo:bar;baz:qux;".',
806
+ );
807
+ }
808
+ additionalFields
809
+ .split(';')
810
+ .filter((field) => !!field)
811
+ .forEach((field) => {
812
+ const [fieldKey, fieldValue] = field.split(':');
813
+ formData.append(fieldKey, String(fieldValue));
814
+ });
815
+ }
816
+
817
+ return formData;
818
+ }
819
+ case 'embedded-base64': {
820
+ const bodyText = typeof originalBody === 'string' ? originalBody : '';
821
+ const bodySplit = bodyText.split('[storedBodyBase64]');
822
+ if (bodySplit.length === 1) {
823
+ throw Error('Body does not contain [storedBodyBase64] marker');
824
+ }
825
+ if (bodySplit.length > 2) {
826
+ throw Error('Body contains multiple [storedBodyBase64] markers, only one is allowed');
827
+ }
828
+ return bodySplit.join(Buffer.from(storedBody.body).toString('base64'));
829
+ }
830
+ default:
831
+ throw Error(\`Unsupported transform type: \${transformType}\`);
832
+ }
833
+ }
834
+
835
+ /**
836
+ * Debug helper for SRC_LOG_HTTP_CALLS logging: normalizes any HeadersInit shape
837
+ * (Headers, tuple array, plain record, or a Request object's headers) into a plain record.
838
+ * Names are lowercased so lookups like headers['content-type'] work for any caller casing.
839
+ */
840
+ function getHeaders(...params: Parameters<typeof fetch>) {
841
+ if (params[1]?.headers) {
842
+ if (params[1].headers instanceof Headers) {
843
+ const result: Record<string, string | string[]> = {};
844
+ for (const [key, value] of params[1].headers.entries()) {
845
+ result[key] = value;
846
+ }
847
+ return result;
848
+ } else if (Array.isArray(params[1].headers)) {
849
+ const result: Record<string, string | string[]> = {};
850
+ for (const [key, value] of params[1].headers) {
851
+ result[key.toLowerCase()] = value;
852
+ }
853
+ return result;
854
+ } else {
855
+ const result: Record<string, string | string[]> = {};
856
+ for (const [key, value] of Object.entries(params[1].headers)) {
857
+ result[key.toLowerCase()] = value as string | string[];
858
+ }
859
+ return result;
860
+ }
861
+ } else if (params[0] instanceof Request) {
862
+ const result: Record<string, string | string[]> = {};
863
+ for (const [key, value] of params[0].headers.entries()) {
864
+ result[key] = value;
865
+ }
866
+ return result;
867
+ }
868
+ return {};
869
+ }
870
+
871
+ /**
872
+ * Debug helper for SRC_LOG_HTTP_CALLS logging: renders a request body into a log-friendly value \u2014
873
+ * parsed JSON or decoded text when the content type allows it, a short placeholder otherwise.
874
+ */
875
+ function formatRequestBody(body: BodyInit | null | undefined, contentType?: string): unknown {
876
+ if (!body) {
877
+ return '';
878
+ }
879
+
880
+ const isJson = contentType?.includes('application/json');
881
+ const isText =
882
+ contentType?.includes('text/') ||
883
+ contentType?.includes('application/xml') ||
884
+ contentType?.includes('application/x-www-form-urlencoded');
885
+
886
+ // Handle different BodyInit types
887
+ if (typeof body === 'string') {
888
+ if (isJson) {
889
+ try {
890
+ return JSON.parse(body);
891
+ } catch {
892
+ return body;
893
+ }
894
+ }
895
+ return body;
896
+ }
897
+
898
+ // TextDecoder accepts any BufferSource, so one branch covers ArrayBuffer and all its views.
899
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
900
+ if (isJson) {
901
+ try {
902
+ return JSON.parse(new TextDecoder().decode(body));
903
+ } catch {
904
+ // Fall through to default handling
905
+ }
906
+ }
907
+ if (isText) {
908
+ try {
909
+ return new TextDecoder().decode(body);
910
+ } catch {
911
+ // Fall through to default handling
912
+ }
913
+ }
914
+ return \`[\${body.constructor.name}: \${body.byteLength} bytes]\`;
915
+ }
916
+
917
+ if (body instanceof Blob) {
918
+ return \`[Blob: \${body.size} bytes, type: \${body.type}]\`;
919
+ }
920
+
921
+ if (body instanceof FormData) {
922
+ const entries: string[] = [];
923
+ for (const [key, value] of body.entries()) {
924
+ if (typeof value === 'string') {
925
+ entries.push(\`\${key}: \${value}\`);
926
+ } else {
927
+ entries.push(\`\${key}: [File: \${value.name}, size: \${value.size}]\`);
928
+ }
929
+ }
930
+ return \`[FormData: \${entries.join(', ')}]\`;
931
+ }
932
+
933
+ if (body instanceof URLSearchParams) {
934
+ return \`[URLSearchParams: \${body.toString()}]\`;
935
+ }
936
+
937
+ if (body instanceof ReadableStream) {
938
+ return '[ReadableStream]';
939
+ }
940
+
941
+ // Fallback for any other type
942
+ return body.toString();
943
+ }
944
+
945
+ let httpLogFile: string | undefined;
946
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
947
+ const HTTP_LOGS: any[] = [];
948
+
949
+ /**
950
+ * Writes the intercepted HTTP call into http_logs_<timestamp>.json when the SRC_LOG_HTTP_CALLS
951
+ * environment variable is set to true; no-op otherwise.
952
+ */
953
+ async function logHTTPCall(
954
+ responseStatus: number,
955
+ responseHeaders: { get: (key: string) => string | null; keys: () => IterableIterator<string> },
956
+ responseBody: ArrayBuffer | undefined,
957
+ ...params: Parameters<typeof fetch>
958
+ ) {
959
+ if (process.env.SRC_LOG_HTTP_CALLS === 'true') {
960
+ const [input, init] = params;
961
+ const headers = getHeaders(input, init);
962
+
963
+ let responseBodyText: string | undefined = undefined;
964
+
965
+ if (responseStatus !== 204 && responseBody) {
966
+ responseBodyText = new TextDecoder().decode(responseBody);
967
+ }
968
+
969
+ const contentType =
970
+ typeof headers['content-type'] === 'string' ? headers['content-type'] : headers['content-type']?.[0];
971
+
972
+ const requestBody = init?.body ?? (input instanceof Request ? input.body : undefined);
973
+
974
+ // Get the request method
975
+ const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
976
+
977
+ // Build response headers object using keys() method
978
+ const responseHeadersObj: Record<string, string | null> = {};
979
+ for (const key of responseHeaders.keys()) {
980
+ responseHeadersObj[key] = responseHeaders.get(key);
981
+ }
982
+
983
+ const logEntry = {
984
+ timestamp: new Date().toISOString(),
985
+ request: {
986
+ method,
987
+ url: input instanceof Request ? input.url : input.toString(),
988
+ headers,
989
+ body: formatRequestBody(requestBody, contentType),
990
+ },
991
+ response: {
992
+ status: responseStatus,
993
+ headers: responseHeadersObj,
994
+ body:
995
+ responseHeaders.get('content-type')?.includes('application/json') && responseBodyText
996
+ ? (() => {
997
+ try {
998
+ return JSON.parse(responseBodyText);
999
+ } catch {
1000
+ return responseBodyText;
1001
+ }
1002
+ })()
1003
+ : responseBodyText,
1004
+ },
1005
+ };
1006
+
1007
+ HTTP_LOGS.push(logEntry);
1008
+
1009
+ // Initialize log file name if not set
1010
+ if (!httpLogFile) {
1011
+ httpLogFile = \`http_logs_\${Date.now()}.json\`;
1012
+ }
1013
+
1014
+ // Write logs to file
1015
+ await fs.writeFile(httpLogFile, JSON.stringify(HTTP_LOGS, null, 4));
1016
+ }
1017
+ }
1018
+
1019
+ // Hook up the ServiceError in global scope.
1020
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1021
+ (global as any).ServiceError = ServiceError;
1022
+ `,NODE_GLOBAL_D_TS=`declare type ConvertLibTextEncoding =
1023
+ 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex';
1024
+
1025
+ declare namespace _convert {
1026
+ export function textToBuffer(text: string, encoding?: ConvertLibTextEncoding): Uint8Array;
1027
+ export function bufferToText(buffer: ArrayBuffer, encoding?: ConvertLibTextEncoding): string;
1028
+ export function textToText(
1029
+ text: string,
1030
+ sourceEncoding: ConvertLibTextEncoding,
1031
+ targetEncoding?: ConvertLibTextEncoding,
1032
+ ): string;
1033
+ export function textToBase64(text: string, encoding?: ConvertLibTextEncoding): string;
1034
+ export function base64ToText(base64: string, encoding?: ConvertLibTextEncoding): string;
1035
+ export function base64ToBuffer(base64: string): Uint8Array;
1036
+ export function bufferToBase64(buffer: ArrayBuffer): string;
1037
+ }
1038
+
1039
+ declare function _processRecordStorageRequest(
1040
+ request: ProcessRecordStorageRequest,
1041
+ ): Promise<ProcessRecordStorageResponse>;
1042
+
1043
+ /**
1044
+ * Error class that ScriptRunner Connect packages use internally.
1045
+ * The Node runtime implementation is installed into the global scope by runtimeMocks.ts.
1046
+ */
1047
+ declare class ServiceError extends Error {
1048
+ public name: string;
1049
+ public errorCode?: number;
1050
+ public service?: string;
1051
+
1052
+ constructor(errorCode?: number, message?: string, service?: string);
1053
+
1054
+ public set(errorCode: number, message: string): void;
1055
+ public setService(service: string): void;
1056
+ }
1057
+
1058
+ declare function _triggerScript(
1059
+ scriptName: string,
1060
+ options: TriggerScriptOptions,
1061
+ ): Promise<TriggerScriptInternalResponse>;
1062
+
1063
+ declare type RecordStorageScope = 'environment' | 'workspace' | 'invocation' | 'team';
1064
+
1065
+ declare interface RecordStorageScopeOption {
1066
+ /**
1067
+ * Scope in which the storage operation will be scoped to. Defaults to 'environment'.
1068
+ */
1069
+ scope?: RecordStorageScope;
1070
+ /**
1071
+ * Additional property for team scope to further limit the scope.
1072
+ */
1073
+ teamScope?: string;
1074
+ }
1075
+
1076
+ declare interface RetryOption {
1077
+ /**
1078
+ * Options for retrying the API call when the request gets rate limited (429 response).
1079
+ *
1080
+ * Default: enabled
1081
+ */
1082
+ retryOn429?: {
1083
+ /**
1084
+ * Whether the API call is automatically retried when the request gets rate limited (429 response).
1085
+ *
1086
+ * Default: true
1087
+ */
1088
+ enabled?: boolean;
1089
+
1090
+ /**
1091
+ * Whether to log every retried request attempt in the console.
1092
+ *
1093
+ * Default: true
1094
+ */
1095
+ verbose?: boolean;
1096
+ };
1097
+ }
1098
+
1099
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1100
+ declare type RecordStorageValue = Record<any, any> | string | number | boolean | Array<any>;
1101
+
1102
+ declare interface ProcessRecordStorageRequest extends RetryOption {
1103
+ kind: 'RECORD_SET' | 'RECORD_GET' | 'RECORD_DELETE' | 'RECORD_EXISTS' | 'RECORD_GET_ALL_KEYS';
1104
+ key?: string;
1105
+ scope?: RecordStorageScope;
1106
+ teamScope?: string;
1107
+ secure?: boolean;
1108
+ ttl?: number;
1109
+ denyUpdateOverwrite?: boolean;
1110
+ value?: RecordStorageValue;
1111
+ lastEvaluatedKey?: string;
1112
+ }
1113
+
1114
+ declare interface ProcessRecordStorageResponse {
1115
+ value?: RecordStorageValue;
1116
+ error?: ProcessRecordStorageResponseError;
1117
+ }
1118
+
1119
+ declare interface ProcessRecordStorageResponseError {
1120
+ code: number;
1121
+ message: string;
1122
+ }
1123
+
1124
+ declare interface TriggerScriptOptions {
1125
+ /**
1126
+ * Name of the function within the given script.
1127
+ * Defaults to the default function within the script
1128
+ */
1129
+ functionName?: string;
1130
+
1131
+ /**
1132
+ * The payload to pass to the given script
1133
+ */
1134
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1135
+ payload?: Record<any, any>;
1136
+
1137
+ /**
1138
+ * Options for retrying the API call when the request gets rate limited (429 response).
1139
+ *
1140
+ * Default: enabled
1141
+ */
1142
+ retryOn429?: {
1143
+ /**
1144
+ * Whether the API call is automatically retried when the request gets rate limited (429 response).
1145
+ *
1146
+ * Default: true
1147
+ */
1148
+ enabled?: boolean;
1149
+
1150
+ /**
1151
+ * Whether to log every retried request attempt in the console.
1152
+ *
1153
+ * Default: true
1154
+ */
1155
+ verbose?: boolean;
1156
+ };
1157
+ }
1158
+
1159
+ declare interface TriggerScriptInternalResponse {
1160
+ result?: TriggerScriptResponse;
1161
+ error?: TriggerScriptError;
1162
+ }
1163
+
1164
+ declare interface TriggerScriptResponse {
1165
+ invocationId: string;
1166
+ }
1167
+
1168
+ declare interface TriggerScriptError {
1169
+ code: number;
1170
+ message: string;
1171
+ }
1172
+ `,NODE_TSCONFIG_JSON=`{
1173
+ "extends": "../tsconfig.base.json",
1174
+ "compilerOptions": {
1175
+ "types": ["@types/jest", "@types/node", "@sr-connect/node-runtime-types"]
1176
+ },
1177
+ "include": ["./", "../ev-params.ts"]
1178
+ }
1179
+ `,NODE_JEST_CONFIG_TS=`import type { Config } from 'jest';
1180
+ import { createDefaultEsmPreset } from 'ts-jest';
1181
+
1182
+ export default {
1183
+ ...createDefaultEsmPreset({
1184
+ tsconfig: 'node/tsconfig.json',
1185
+ }),
1186
+ // Only pick up *.test.ts files, so helper modules and fixtures can live under node/tests/ without being run as suites.
1187
+ testMatch: ['**/node/tests/**/*.test.ts'],
1188
+ } satisfies Config;
1189
+ `,VSCODE_EXTENSIONS_JSON=`{
1190
+ "recommendations": [
1191
+ "dbaeumer.vscode-eslint",
1192
+ "esbenp.prettier-vscode"
1193
+ ]
1194
+ }
1195
+ `,PACKAGE_JSON_TEMPLATE=`{
1196
+ "name": "sr-connect-workspace",
1197
+ "version": "1.0.0",
1198
+ "description": "",
1199
+ "author": "",
1200
+ "license": "UNLICENSED",
1201
+ "type": "module",
1202
+ "scripts": {
1203
+ "lint": "eslint",
1204
+ "lint:fix": "eslint --fix",
1205
+ "typecheck": "tsc -p tsconfig.json && tsc -p node/tsconfig.json",
1206
+ "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest -c=./node/jest.config.ts --no-cache"
1207
+ },
1208
+ "dependencies": {
1209
+ "@managed-api/slack-sr-connect": "2.4.0",
1210
+ "@sr-connect/convert": "1.2.0",
1211
+ "@sr-connect/generic-app": "1.0.0",
1212
+ "@sr-connect/record-storage": "1.1.1",
1213
+ "@sr-connect/trigger": "1.0.1",
1214
+ "@sr-connect/runtime-types": "latest",
1215
+ "@sr-connect/node-runtime-types": "latest"
1216
+ },
1217
+ "devDependencies": {
1218
+ "@jest/globals": "30.4.1",
1219
+ "@types/jest": "30.0.0",
1220
+ "@types/node": "22.20.2",
1221
+ "@typescript-eslint/eslint-plugin": "8.67.0",
1222
+ "@typescript-eslint/parser": "8.67.0",
1223
+ "cross-env": "10.1.0",
1224
+ "eslint": "10.9.0",
1225
+ "eslint-config-prettier": "10.1.8",
1226
+ "eslint-plugin-prettier": "5.5.6",
1227
+ "jest": "30.4.2",
1228
+ "prettier": "3.9.6",
1229
+ "ts-jest": "29.4.12",
1230
+ "ts-node": "10.9.2",
1231
+ "typescript": "6.0.3",
1232
+ "ulid": "3.0.2"
1233
+ }
1234
+ }`,TSCONFIG_BASE_TEMPLATE=`{
1235
+ "compilerOptions": {
1236
+ "target": "ES2020",
1237
+ "module": "ESNext",
1238
+ "noEmit": true,
1239
+ "sourceMap": false,
1240
+ "moduleResolution": "bundler",
1241
+ "lib": [
1242
+ "ES2020"
1243
+ ],
1244
+ "strict": true,
1245
+ "skipLibCheck": true,
1246
+ "esModuleInterop": true
1247
+ }
1248
+ }`;var TYPE_PACKAGES=["@sr-connect/runtime-types","@sr-connect/node-runtime-types"];function escapeTypeLiteral(value){return value.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}function escapeJsDoc(value){return value.replace(/\*\//g,"*\\/")}function choiceUnion(parameter){let union2=parameter.choices?.map(ch=>`'${escapeTypeLiteral(ch.value||ch.label)}'`).join(" | ");return union2||void 0}function parameterType(parameter){switch(parameter.type){case"NUMBER":case"BOOLEAN":return parameter.type.toLowerCase();case"DATE":return"Date";case"PASSWORD":case"TEXT":case"MULTILINE_TEXT":return"string";case"LIST":return"string[]";case"SINGLE_CHOICE":return choiceUnion(parameter)??"string";case"MULTIPLE_CHOICES":{let union2=choiceUnion(parameter);return union2?`(${union2})[] & string[]`:"string[]"}case"MAP":return"Record<string, string>";case"FOLDER":{let children=(parameter.children??[]).map(child=>`${jsDoc(" ",child)}
1249
+ ${child.key}${optionalMark(child)}: ${parameterType(child)};`).join(`
1250
+ `);return parameter.children?.length?`{
1251
+ ${children}
1252
+ }`:"Record<string, any>"}default:return"string"}}function optionalMark(parameter){return parameter.type==="BOOLEAN"||parameter.type==="FOLDER"||parameter.required?"":"?"}function jsDoc(indent,parameter){let type=parameter.type.toLowerCase();return parameter.description?`${indent}/**
1253
+ ${indent} * ${escapeJsDoc(parameter.description)}
1254
+ ${indent} *
1255
+ ${indent} * Type: ${type}
1256
+ ${indent} */`:`${indent}/**
1257
+ ${indent} * Type: ${type}
1258
+ ${indent} */`}function generateEvParams(parameters){return`export {};
1259
+
1260
+ declare global {
1261
+ interface EV {
1262
+ ${parameters.map(parameter=>`${jsDoc(" ",parameter)}
1263
+ ${parameter.key}${optionalMark(parameter)}: ${parameterType(parameter)};
1264
+ `).join(`
1265
+ `)}
1266
+ }
1267
+ }
1268
+ `}function generateApiConnectionFile(input){let depth=input.path.split("/").length,relativePathToRegistry="../".repeat(depth+2)+"node/apiRegistry",guessNote=input.namespaceGuessed?`
1269
+ * The exported class name was guessed from the package name \u2014 if this file does not
1270
+ * compile, fix the two '${input.namespace}' references to the class '${input.packageName}' exports.`:"";return`import { PlatformImplementation } from '@managed-api/commons-core';
1271
+ import { ${input.namespace} } from '${input.packageName}';
1272
+ import { API_REGISTRY } from '${relativePathToRegistry}';
1273
+
1274
+ /**
1275
+ * Do not modify this file, it is auto-generated.${guessNote}
1276
+ */
1277
+ export default (API_REGISTRY['${input.path}'] as ${input.namespace}) ??
1278
+ new (class extends ${input.namespace} {
1279
+ constructor() {
1280
+ super('${input.connectionId}');
1281
+ }
1282
+ protected getPlatformImplementation(): PlatformImplementation {
1283
+ throw new Error(
1284
+ "API Connection '${input.path}' local implementation not found, consider adding the implementation in the \`apiRegistry.ts\` file.",
1285
+ );
1286
+ }
1287
+ })();
1288
+ `}function guessNamespace(packageName){let bare=packageName.replace(/^@[^/]+\//,"").replace(/-sr-connect$/,"").replace(/-v\d+([.-]\d+)*$/,"");return`${pascalCase(bare)}Api`}function pascalCase(text){return text.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join("")}function buildDependencies(packages){let dependencies={};for(let pkg of[...packages].sort((a,b2)=>a.name.localeCompare(b2.name)))dependencies[pkg.name]=pkg.version;for(let name of TYPE_PACKAGES)dependencies[name]="latest";return dependencies}function toJson(value){return JSON.stringify(value,null,4)}function generatePackageJson(workspaceName,packages){let template=JSON.parse(PACKAGE_JSON_TEMPLATE);return template.description=workspaceName,template.dependencies=buildDependencies(packages),toJson(template)}function mergePackageJson(existing,packages){let parsed;try{parsed=JSON.parse(existing)}catch{return}if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))return;let merged=parsed;return merged.dependencies=buildDependencies(packages),toJson(merged)+(existing.endsWith(`
1289
+ `)?`
1290
+ `:"")}function generateTsconfigBase(language){let template=JSON.parse(TSCONFIG_BASE_TEMPLATE);return template.compilerOptions.strict=language==="ts-strict",toJson(template)}var FORBIDDEN_IN_FILE_NAME='<>:"/\\|?*',WINDOWS_RESERVED=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i;function unportableNameReason(name){if(!name.trim())return"it is blank";let forbidden=Array.from(new Set(Array.from(name).filter(ch=>FORBIDDEN_IN_FILE_NAME.includes(ch)||ch<" ")));if(forbidden.length>0){let printable=forbidden.map(ch=>ch<" "?"a control character":`'${ch}'`);return`${printable.length>1?`${printable.slice(0,-1).join(", ")} and ${printable.at(-1)}`:printable[0]} cannot appear in a file name on every platform`}if(/[. ]$/.test(name))return"it ends in a dot or a space, which Windows strips";let base=name.split(".")[0]??name;if(WINDOWS_RESERVED.test(base))return`${base} is a reserved device name on Windows`}function listenerFolderName(listener){let app=pascalCase(listener.app.name)||listener.app.name,event=listener.eventType?pascalCase(listener.eventType.name)||listener.eventType.name:void 0;return`${event?`${app}\u2192${event}`:app} (${listener.id})`}function payloadFileName(payloadName){return`${payloadName}.json`}var CONCURRENCY=5;async function apiConnectionFileInputs(client,connections){let withPath=connections.filter(c=>c.path);return(await throttleAll(CONCURRENCY,withPath.map(connection=>async()=>{let catalogue=await apiConnectionPackages(client,connection.app.id,connection.apiConnectionTypeId).catch(()=>[]),fromCatalogue=connection.package?catalogue.find(p=>p.id===connection.package?.id):catalogue.find(p=>p.recommended&&!p.deprecated)??catalogue.find(p=>!p.deprecated)??catalogue[0],packageName=connection.package?.name??fromCatalogue?.name;if(!packageName){warnLine(`\u26A0 API connection "${connection.path}" has no package and the catalogue offers none \u2014 scripts/api/${connection.path}/index.ts was not generated.`);return}let namespace=fromCatalogue?.namespace;return namespace||warnLine(`\u26A0 The app catalogue records no exported class for ${packageName} \u2014 scripts/api/${connection.path}/index.ts uses the guessed name ${guessNamespace(packageName)}.`),{path:connection.path??"",namespace:namespace??guessNamespace(packageName),packageName,connectionId:connection.id,namespaceGuessed:!namespace}}))).filter(input=>input!==void 0)}function apiConnectionFilePath(connectionPath){return`scripts/api/${connectionPath.replaceAll(/\/+/g,"/").replace(/^\//,"").replace(/\/$/,"")}/index.ts`}async function apiConnectionFiles(client,connections){return(await apiConnectionFileInputs(client,connections)).map(input=>({path:apiConnectionFilePath(input.path),content:generateApiConnectionFile(input)}))}import{lstatSync as lstatSync2,mkdirSync as mkdirSync7,readFileSync as readFileSync10,readdirSync as readdirSync5,rmSync as rmSync6,unlinkSync,writeFileSync as writeFileSync6}from"fs";import{join as join10,resolve as resolve3,sep as sep3}from"path";var MARKER_PACKAGES=[...TYPE_PACKAGES,"@sr-connect/convert","@sr-connect/record-storage"],EMPTINESS_IGNORED=new Set([".git",".DS_Store"]);function mergedDependencies(parsed){if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))return{};let manifest=parsed,merged={};for(let section of[manifest.dependencies,manifest.devDependencies])section!==null&&typeof section=="object"&&!Array.isArray(section)&&Object.assign(merged,section);return merged}function looksLikeClonedWorkspace(directory){try{return lstatSync2(join10(directory,METADATA_FILE)),!0}catch{}let raw;try{raw=readFileSync10(join10(directory,"package.json"),"utf8")}catch{return!1}let parsed;try{parsed=JSON.parse(raw)}catch{return!1}let dependencies=mergedDependencies(parsed);return MARKER_PACKAGES.every(name=>name in dependencies)}function inspectDirectory(directory){let entries;try{entries=readdirSync5(directory)}catch{return"empty"}return entries.every(entry2=>EMPTINESS_IGNORED.has(entry2))?"empty":looksLikeClonedWorkspace(directory)?"cloned-workspace":"non-empty"}var KEPT_IN_UPDATE_MODE=new Set(["tsconfig.json","tsconfig.base.json","eslint.config.js",".gitignore",".prettierrc","pnpm-workspace.yaml",".vscode/extensions.json","node/apiRegistry.ts","node/runtimeMocks.ts","node/global.d.ts","node/tsconfig.json","node/jest.config.ts"]),BARE_DIRECTORIES=["scripts/api","node/tests"];function assertInside(directory,relativePath){let absolute2=resolve3(directory,relativePath),base=resolve3(directory);if(absolute2!==base&&!absolute2.startsWith(base+sep3))throw new Error(`Refusing to write outside the target directory: ${relativePath}`);return absolute2}function entryExists(absolute2){try{return lstatSync2(absolute2),!0}catch{return!1}}function ensureParents(directory,relativePath){let segments=relativePath.split("/").slice(0,-1),current=resolve3(directory);for(let segment of segments){current=join10(current,segment);let stat=entryExists(current)?lstatSync2(current):void 0;stat?.isSymbolicLink()?unlinkSync(current):stat&&!stat.isDirectory()&&rmSync6(current,{force:!0}),mkdirSync7(current,{recursive:!0})}}function writeClone(directory,files,updateMode){let written=[],kept=[];mkdirSync7(resolve3(directory),{recursive:!0});for(let file2 of files){let absolute2=assertInside(directory,file2.path);if(updateMode&&KEPT_IN_UPDATE_MODE.has(file2.path)&&entryExists(absolute2)){kept.push(file2.path);continue}ensureParents(directory,file2.path);let existing=entryExists(absolute2)?lstatSync2(absolute2):void 0;existing?.isSymbolicLink()?unlinkSync(absolute2):existing&&!existing.isFile()&&rmSync6(absolute2,{recursive:!0,force:!0}),writeFileSync6(absolute2,file2.content),written.push(file2.path)}for(let bare of BARE_DIRECTORIES)ensureParents(directory,`${bare}/.`),mkdirSync7(assertInside(directory,bare),{recursive:!0});return{written,kept}}function walkFiles(root,prefix,out){let entries;try{entries=readdirSync5(root)}catch{return}for(let entry2 of entries){let absolute2=join10(root,entry2),relativePath=prefix?`${prefix}/${entry2}`:entry2;lstatSync2(absolute2).isDirectory()?walkFiles(absolute2,relativePath,out):out.push(relativePath)}}var SWEPT_ROOTS=["scripts/api","test-payloads"];function sweepStaleFiles(directory,manifestPaths){return SWEPT_ROOTS.flatMap(root=>sweepRoot(directory,root,manifestPaths))}function sweepRoot(directory,root,keep){let deleted=[],rootPath=resolve3(directory,root),present=[];walkFiles(rootPath,root,present);for(let relativePath of present)keep.has(relativePath)||(rmSync6(assertInside(directory,relativePath),{force:!0}),deleted.push(relativePath));return prune3(rootPath,rootPath),deleted}function prune3(dir,root){let entries;try{entries=readdirSync5(dir)}catch{return}for(let entry2 of entries){let absolute2=join10(dir,entry2);lstatSync2(absolute2).isDirectory()&&prune3(absolute2,root)}resolve3(dir)!==root&&readdirSync5(dir).length===0&&rmSync6(dir,{recursive:!0})}var CONCURRENCY2=5,enabled5=!0,instance2;function configureLocalSync(opts){enabled5=opts.enabled!==!1&&!truthy2(process.env.SR_CONNECT_CLI_NO_LOCAL_SYNC)&&settingEnabled("localSync"),instance2=opts.instance}function truthy2(value){return value===void 0?!1:!["","0","false","no","off"].includes(value.trim().toLowerCase())}var MAX_LEVELS=40,lookedUp=!1,found;function findLocalClone(){if(lookedUp)return found;lookedUp=!0;let directory=resolve4(process.cwd());for(let level=0;level<MAX_LEVELS;level+=1){let read=readMetadata(directory);if(read.metadata)return found={directory,metadata:read.metadata},found;if(read.problem){warnLine(`\u26A0 ${displayPath(join11(directory,METADATA_FILE))}: ${read.problem} Ignoring the local copy.`);return}let parent=dirname3(directory);if(parent===directory)break;directory=parent}}var noted=new Set;function noteOnce(line){noted.has(line)||(noted.add(line),warnLine(line))}function cloneFor(scope2){if(!enabled5)return;let clone2=findLocalClone();if(!clone2)return;let record4=clone2.metadata;if(instance2!==void 0&&record4.instance!==""&&baseUrl(record4.instance)!==baseUrl(instance2)){noteOnce(`\u26A0 The local copy in ${displayPath(clone2.directory)} was cloned from ${record4.instance} \u2014 not updated.`);return}if(record4.workspace.id!==scope2.workspaceId){noteOnce(`\u26A0 The local copy in ${displayPath(clone2.directory)} is workspace ${record4.workspace.name??record4.workspace.id} (${record4.workspace.id}) \u2014 not updated.`);return}if(scope2.environmentId!==void 0&&record4.environment.id!==scope2.environmentId){noteOnce(`\u26A0 The local copy in ${displayPath(clone2.directory)} is environment ${record4.environment.name??record4.environment.id} (${record4.environment.id}) \u2014 not updated.`);return}if(record4.environment.release){noteOnce(`\u26A0 The local copy in ${displayPath(clone2.directory)} is release ${record4.environment.release}'s snapshot \u2014 not updated. Re-clone it to pick up what the environment runs now.`);return}return clone2}function absolute(clone2,relativePath){return assertInside(clone2.directory,relativePath)}function readLocal(clone2,relativePath){try{return readFileSync11(absolute(clone2,relativePath),"utf8")}catch{return}}function noteWritten(relativePath){isRaw()||noteLine(`\u2714 Local copy updated: ${relativePath}`)}function noteRemoved(relativePath){isRaw()||noteLine(`\u2714 Local copy updated: ${relativePath} removed`)}function warnDirty(relativePath){warnLine(`\u26A0 ${relativePath} has local changes \u2014 left alone. It no longer matches the workspace.`)}function warnLeftBehind(scope2,relativePath){cloneFor(scope2)&&warnLine(`\u26A0 ${relativePath??"The local copy"} was not updated \u2014 you chose to edit the version in the workspace. Fetch it with \`${CLI} local-workspace clone\`, which rewrites the whole local copy, so check for other unsynced changes first.`)}function ensureParent(clone2,relativePath){mkdirSync8(dirname3(absolute(clone2,relativePath)),{recursive:!0})}async function attempt(run){try{return await run()}catch{return}}async function readOrSkip(run){let got=await attempt(run);return got?.response.ok?got.data:void 0}function writeOrWarn(relativePath,run){try{return run()}catch(error51){warnLine(`\u26A0 ${relativePath} could not be updated in the local copy (${describeError(error51)}). The workspace has the change; this directory does not.`);return}}function putFile(clone2,relativePath,content){return readLocal(clone2,relativePath)===content||!writeOrWarn(relativePath,()=>(ensureParent(clone2,relativePath),writeFileSync7(absolute(clone2,relativePath),content),!0))?!1:(noteWritten(relativePath),!0)}function dropFile(clone2,relativePath){let target=absolute(clone2,relativePath);try{lstatSync3(target)}catch{return!1}return writeOrWarn(relativePath,()=>(rmSync7(target,{force:!0}),pruneUpwards(clone2,dirname3(relativePath)),!0))?(noteRemoved(relativePath),!0):!1}function pruneUpwards(clone2,relativeDir){let roots=new Set([".","","scripts","scripts/api","test-payloads"]),current=relativeDir;for(;!roots.has(current);){let target=absolute(clone2,current);try{if(readdirSync6(target).length>0)return;rmSync7(target,{recursive:!0,force:!0})}catch{return}current=dirname3(current)}}function saveRecord(clone2,mutate){mutate(clone2.metadata),clone2.metadata.cli=writerTag();try{writeFileSync7(absolute(clone2,METADATA_FILE),renderMetadata(clone2.metadata))}catch{warnLine(`\u26A0 ${METADATA_FILE} could not be updated \u2014 the next \`${CLI} local-workspace push\` may re-send files that are already in the workspace.`)}}function syncScript(scope2,change){if(change.mode==="skip-write"){warnLeftBehind(scope2,scriptPath(change.name));return}let clone2=cloneFor(scope2);if(!clone2)return;let relativePath=scriptPath(change.name),recordedName=change.id===void 0?void 0:Object.entries(clone2.metadata.scripts).find(([,entry2])=>entry2.id===change.id)?.[0],candidate=change.previousName??recordedName,previous=candidate!==void 0&&candidate!==change.name?candidate:void 0;if(previous!==void 0){let from=scriptPath(previous),recorded2=clone2.metadata.scripts[previous];if(readLocal(clone2,from)!==void 0)try{ensureParent(clone2,relativePath),renameSync4(absolute(clone2,from),absolute(clone2,relativePath)),pruneUpwards(clone2,dirname3(from)),noteWritten(`${from} \u2192 ${relativePath}`)}catch{warnLine(`\u26A0 ${from} could not be moved to ${relativePath}.`)}saveRecord(clone2,record4=>{delete record4.scripts[previous],recorded2&&(record4.scripts[change.name]=recorded2)})}let recorded=clone2.metadata.scripts[change.name],onDisk=readLocal(clone2,relativePath);onDisk!==void 0&&recorded?.checksum!==void 0&&recorded.checksum!==""&&checksumOf(onDisk)!==recorded.checksum&&onDisk!==change.content&&change.mode!=="always"?warnDirty(relativePath):putFile(clone2,relativePath,change.content),saveRecord(clone2,record4=>{record4.scripts[change.name]={...change.id===void 0?{}:{id:change.id},checksum:checksumOf(change.content)}})}async function syncScriptFromServer(client,scope2,scriptId){if(!cloneFor(scope2)||scope2.environmentId===void 0)return;let path2={workspaceId:scope2.workspaceId,environmentId:scope2.environmentId},data=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}",{params:{path:{...path2,scriptId}}}));data&&syncScript(scope2,{name:data.name,content:data.content,id:data.id})}function syncScriptDeleted(scope2,ref){let clone2=cloneFor(scope2);if(!clone2)return;let name=ref.name??Object.entries(clone2.metadata.scripts).find(([,entry2])=>entry2.id===ref.id)?.[0];if(name===void 0)return;let relativePath=scriptPath(name),recorded=clone2.metadata.scripts[name],onDisk=readLocal(clone2,relativePath);onDisk!==void 0&&recorded?.checksum&&checksumOf(onDisk)!==recorded.checksum?warnLine(`\u26A0 ${relativePath} has local changes \u2014 left in place, though the script is gone from the workspace.`):dropFile(clone2,relativePath),saveRecord(clone2,record4=>{delete record4.scripts[name]})}var folderCache=new Map;async function folderForListener(clone2,client,scope2,eventListenerId){let cached2=folderCache.get(eventListenerId);if(cached2!==void 0)return cached2;for(let[path2,entry2]of Object.entries(clone2.metadata.testPayloads)){if(entry2.eventListenerId!==eventListenerId)continue;let folder2=path2.split("/")[1];if(folder2)return folderCache.set(eventListenerId,folder2),folder2}let listener=await fetchListener(client,scope2,eventListenerId),folder=listener?listenerFolderName(listener):void 0;if(folder&&unportableNameReason(folder)){folderCache.set(eventListenerId,void 0);return}return folderCache.set(eventListenerId,folder),folder}async function fetchListener(client,scope2,eventListenerId){let environmentId=scope2.environmentId;if(environmentId===void 0)return;let data=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListeners",{params:{path:{workspaceId:scope2.workspaceId,environmentId}}}));if(data)return data.eventListeners.find(listener=>listener.id===eventListenerId)}function payloadPathById(clone2,id){if(id!==void 0)return Object.entries(clone2.metadata.testPayloads).find(([,entry2])=>entry2.id===id)?.[0]}function payloadNameFromPath(path2){let file2=path2.split("/")[2];return file2?.endsWith(".json")?file2.slice(0,-5):void 0}async function syncTestPayload(client,scope2,eventListenerId,change){if(change.mode==="skip-write"){let skipped=cloneFor(scope2),folder2=skipped?await folderForListener(skipped,client,scope2,eventListenerId):void 0;warnLeftBehind(scope2,folder2&&change.name?`test-payloads/${folder2}/${payloadFileName(change.name)}`:void 0);return}let clone2=cloneFor(scope2);if(!clone2)return;let folder=await folderForListener(clone2,client,scope2,eventListenerId);if(!folder)return;let knownPath=payloadPathById(clone2,change.id),recordedName=knownPath===void 0?void 0:payloadNameFromPath(knownPath),name=change.name??recordedName;if(name===void 0)return;let previousName=change.previousName??recordedName,reason=unportableNameReason(payloadFileName(name));if(reason){warnLine(`\u26A0 Test payload "${name}" was not written to the local copy: ${reason}.`);return}let relativePath=`test-payloads/${folder}/${payloadFileName(name)}`;if(previousName!==void 0&&previousName!==name){let from=`test-payloads/${folder}/${payloadFileName(previousName)}`,recorded2=clone2.metadata.testPayloads[from];if(readLocal(clone2,from)!==void 0)try{ensureParent(clone2,relativePath),renameSync4(absolute(clone2,from),absolute(clone2,relativePath)),noteWritten(`${from} \u2192 ${relativePath}`)}catch{warnLine(`\u26A0 ${from} could not be moved to ${relativePath}.`)}saveRecord(clone2,record4=>{delete record4.testPayloads[from],recorded2&&(record4.testPayloads[relativePath]=recorded2)})}let recorded=clone2.metadata.testPayloads[relativePath],onDisk=readLocal(clone2,relativePath);onDisk!==void 0&&recorded?.checksum!==void 0&&recorded.checksum!==""&&checksumOf(onDisk)!==recorded.checksum&&onDisk!==change.content&&change.mode!=="always"?warnDirty(relativePath):putFile(clone2,relativePath,change.content),saveRecord(clone2,record4=>{record4.testPayloads[relativePath]={eventListenerId,...change.id===void 0?{}:{id:change.id},checksum:checksumOf(change.content)}})}async function syncTestPayloadDeleted(client,scope2,eventListenerId,ref){let clone2=cloneFor(scope2);if(!clone2)return;let byId=payloadPathById(clone2,ref.id),folder=byId?void 0:await folderForListener(clone2,client,scope2,eventListenerId),relativePath=byId??(folder&&ref.name!==void 0?`test-payloads/${folder}/${payloadFileName(ref.name)}`:void 0);relativePath!==void 0&&(dropFile(clone2,relativePath),saveRecord(clone2,record4=>{delete record4.testPayloads[relativePath]}))}async function syncTestPayloadRenamed(client,scope2,eventListenerId,change){let clone2=cloneFor(scope2);if(!clone2)return;let from=payloadPathById(clone2,change.id);if(from===void 0)return;let folder=from.split("/")[1];if(!folder||unportableNameReason(payloadFileName(change.name)))return;let to=`test-payloads/${folder}/${payloadFileName(change.name)}`;if(to===from)return;let entry2=clone2.metadata.testPayloads[from];if(readLocal(clone2,from)!==void 0)try{renameSync4(absolute(clone2,from),absolute(clone2,to)),noteWritten(`${from} \u2192 ${to}`)}catch{warnLine(`\u26A0 ${from} could not be moved to ${to}.`);return}saveRecord(clone2,record4=>{delete record4.testPayloads[from],entry2&&(record4.testPayloads[to]=entry2)})}async function syncTestPayloadById(client,scope2,eventListenerId,testPayloadId){let environmentId=scope2.environmentId;if(!cloneFor(scope2)||environmentId===void 0)return;let data=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{workspaceId:scope2.workspaceId,environmentId,eventListenerId,testPayloadId}}}));data&&await syncTestPayload(client,scope2,eventListenerId,{name:data.name,content:data.content,id:data.id})}async function syncNewEventListener(client,scope2,eventListenerId){let clone2=cloneFor(scope2);if(!clone2||scope2.environmentId===void 0||!await folderForListener(clone2,client,scope2,eventListenerId))return;let path2={workspaceId:scope2.workspaceId,environmentId:scope2.environmentId},list=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:{...path2,eventListenerId}}}));if(!list)return;let contents=await throttleAll(CONCURRENCY2,list.testPayloads.map(payload=>async()=>readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{...path2,eventListenerId,testPayloadId:payload.id}}}))));for(let payload of contents)payload&&await syncTestPayload(client,scope2,eventListenerId,{name:payload.name,content:payload.content,id:payload.id})}async function syncEventListenerFolder(client,scope2,eventListenerId,op){let clone2=cloneFor(scope2);if(!clone2)return;let current=folderFromRecord(clone2,eventListenerId);if(!current)return;if(op==="delete"){let removed=Object.keys(clone2.metadata.testPayloads).filter(path2=>path2.startsWith(`test-payloads/${current}/`));try{rmSync7(absolute(clone2,`test-payloads/${current}`),{recursive:!0,force:!0}),noteRemoved(`test-payloads/${current}`)}catch{}saveRecord(clone2,record4=>{for(let path2 of removed)delete record4.testPayloads[path2]});return}folderCache.delete(eventListenerId);let listener=await fetchListener(client,scope2,eventListenerId);if(!listener)return;let next=listenerFolderName(listener);if(!(next===current||unportableNameReason(next))){try{renameSync4(absolute(clone2,`test-payloads/${current}`),absolute(clone2,`test-payloads/${next}`)),noteWritten(`test-payloads/${current} \u2192 test-payloads/${next}`)}catch{return}saveRecord(clone2,record4=>{for(let[path2,entry2]of Object.entries(record4.testPayloads))path2.startsWith(`test-payloads/${current}/`)&&(delete record4.testPayloads[path2],record4.testPayloads[path2.replace(`test-payloads/${current}/`,`test-payloads/${next}/`)]=entry2)}),folderCache.set(eventListenerId,next)}}function folderFromRecord(clone2,eventListenerId){for(let[path2,entry2]of Object.entries(clone2.metadata.testPayloads))if(entry2.eventListenerId===eventListenerId)return path2.split("/")[1]}async function syncParameters(client,scope2){let clone2=cloneFor(scope2),environmentId=scope2.environmentId;if(!clone2||environmentId===void 0)return;let data=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/parameters",{params:{path:{workspaceId:scope2.workspaceId,environmentId}}}));data&&putFile(clone2,"ev-params.ts",generateEvParams(data.parameters))}async function syncPackages(client,workspaceId){let clone2=cloneFor({workspaceId});if(!clone2)return;let existing=readLocal(clone2,"package.json");if(existing===void 0)return;let data=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/packages",{params:{path:{workspaceId}}}));if(!data)return;let merged=mergePackageJson(existing,data.packages);if(merged===void 0)return;let delta=dependencyDelta(existing,merged);putFile(clone2,"package.json",merged)&&delta.length>0&&warnDependenciesChanged(clone2,delta)}function dependencyDelta(before,after){let read=raw=>{try{return JSON.parse(raw).dependencies??{}}catch{return{}}},from=read(before),to=read(after),words=[];for(let[name,version2]of Object.entries(to))from[name]===void 0?words.push(`+${name}@${version2}`):from[name]!==version2&&words.push(`${name} ${from[name]} \u2192 ${version2}`);for(let name of Object.keys(from))to[name]===void 0&&words.push(`-${name}`);return words}function installCommand(clone2){let lockFiles=[["pnpm-lock.yaml","pnpm install"],["yarn.lock","yarn install"],["package-lock.json","npm install"]];for(let[file2,command]of lockFiles)try{return lstatSync3(absolute(clone2,file2)),command}catch{}}function warnDependenciesChanged(clone2,delta){let command=installCommand(clone2);warnLine(`\u26A0 The workspace's dependencies changed (${delta.join(", ")}) and package.json was updated. `+(command?`Install them again: ${command}`:"Install them again with whichever package manager this project uses."))}function syncReadme(scope2,content,mode){if(mode==="skip-write"){warnLeftBehind(scope2,"README.md");return}let clone2=cloneFor(scope2);if(!clone2)return;let recorded=clone2.metadata.readme,onDisk=readLocal(clone2,"README.md");onDisk!==void 0&&recorded?.checksum!==void 0&&recorded.checksum!==""&&checksumOf(onDisk)!==recorded.checksum&&onDisk!==content&&mode!=="always"?warnDirty("README.md"):putFile(clone2,"README.md",content),saveRecord(clone2,record4=>{record4.readme={checksum:checksumOf(content)}})}async function syncWorkspaceSettings(workspaceId,change){let clone2=cloneFor({workspaceId});if(!clone2)return;if(change.language!==void 0){let existing=readLocal(clone2,"tsconfig.base.json"),strictNow=existing!==void 0&&/"strict"\s*:\s*true/.test(existing);change.language==="ts-strict"?existing===void 0?putFile(clone2,"tsconfig.base.json",generateTsconfigBase("ts-strict")):strictNow||putFile(clone2,"tsconfig.base.json",existing.replace(/"strict"(\s*):(\s*)false/,'"strict"$1:$2true')):strictNow&&!isRaw()&&noteLine("\u2714 tsconfig.base.json keeps strict mode \u2014 the local copy is stricter than the workspace, which is allowed.")}let previousName=change.previousName??clone2.metadata.workspace.name;if(change.name!==void 0&&previousName!==void 0){let existing=readLocal(clone2,"package.json");if(existing===void 0)return;let parsed;try{parsed=JSON.parse(existing)}catch{return}if(parsed.description!==previousName)return;parsed.description=change.name;let trailing=existing.endsWith(`
1291
+ `)?`
1292
+ `:"";putFile(clone2,"package.json",`${JSON.stringify(parsed,null,4)}${trailing}`),saveRecord(clone2,record4=>{record4.workspace.name=change.name})}}async function syncApiConnections(client,scope2){let clone2=cloneFor(scope2);if(!clone2)return;let environmentId=scope2.environmentId??clone2.metadata.environment.id,data=await readOrSkip(()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnections",{params:{path:{workspaceId:scope2.workspaceId,environmentId}}}));if(!data)return;let files=await attempt(()=>apiConnectionFiles(client,data.apiConnections));if(!files)return;for(let file2 of files)putFile(clone2,file2.path,file2.content);let swept=sweepRoot(clone2.directory,"scripts/api",new Set(files.map(file2=>file2.path)));for(let path2 of swept)noteRemoved(path2)}function noteRedeployed(scope2,what){let clone2=cloneFor(scope2);clone2&&warnLine(`\u26A0 The local copy in ${displayPath(clone2.directory)} no longer matches this environment (${what}). Re-clone it with \`${CLI} local-workspace clone\`.`)}async function localEditSource(client,scope2,target,serverContent){let clone2=cloneFor(scope2);if(!clone2)return{content:serverContent,mode:"if-clean"};let relativePath=await editPath(clone2,client,scope2,target);if(!relativePath)return{content:serverContent,mode:"if-clean"};let onDisk=readLocal(clone2,relativePath);return onDisk===void 0||onDisk===serverContent?{content:serverContent,mode:"if-clean"}:canPrompt()?(prompts().note(`This ${nounOf(target)} differs from your local copy at ${relativePath}.`),await prompts().select("Which one do you want to edit?",[{value:"local",label:`The local file \u2014 ${relativePath}`,hint:"edited here, then uploaded"},{value:"server",label:"The version in the workspace",hint:"the local file is left alone"}],{initial:"local"})==="local"?{content:onDisk,mode:"always"}:{content:serverContent,mode:"skip-write"}):{content:serverContent,mode:"if-clean"}}function nounOf(target){return target.kind==="script"?"script":target.kind==="payload"?"test payload":"README"}async function editPath(clone2,client,scope2,target){if(target.kind==="script")return scriptPath(target.name);if(target.kind==="readme")return"README.md";let folder=await folderForListener(clone2,client,scope2,target.eventListenerId);return folder?`test-payloads/${folder}/${payloadFileName(target.name)}`:void 0}var flagEnabled2=!0,instance3;function configureLocalWorkspaceScope(opts){flagEnabled2=opts.enabled!==!1,instance3=opts.instance}function truthy3(value){return value===void 0?!1:!["","0","false","no","off"].includes(value.trim().toLowerCase())}function localWorkspaceScopeEnabled(){return flagEnabled2&&!truthy3(process.env.SR_CONNECT_CLI_NO_LOCAL_WORKSPACE)}function localWorkspaceScope(){if(!localWorkspaceScopeEnabled())return;let clone2=findLocalClone();if(!clone2)return;let record4=clone2.metadata;if(instance3!==void 0&&record4.instance!==""&&baseUrl(record4.instance)!==baseUrl(instance3))return;let labels={team:record4.team.name};return record4.workspace.name&&(labels.workspace=record4.workspace.name),record4.environment.name&&(labels.environment=record4.environment.name),{directory:clone2.directory,recordPath:join12(clone2.directory,METADATA_FILE),values:{team:record4.team.id,workspace:record4.workspace.id,environment:record4.environment.id},labels}}var SCOPE_ENV={team:"SR_CONNECT_CLI_TEAM",workspace:"SR_CONNECT_CLI_WORKSPACE",environment:"SR_CONNECT_CLI_ENVIRONMENT"};function scopeEnvVar(key){return Object.hasOwn(SCOPE_ENV,key)?SCOPE_ENV[key]:void 0}var SKIPPED_DEFAULT_HINT={destructive:"A session default and a local workspace record are only borrowed by a destructive verb when someone is there to see the question naming it \u2014 pass the scope with flags or environment variables, or run it on a terminal.","save-flow":"This verb writes the session defaults rather than reading them, so a stored value is never the answer here \u2014 pass all three with flags or environment variables, or run it on a terminal to pick them."},workspaceOrigin,inheritedWorkspaceNoted=!1;function inheritedWorkspaceNote(from,workspaceId){return from===void 0||from==="flag"||from==="picker"?void 0:`\u26A0 Workspace ${workspaceId} came from ${from==="env"?"SR_CONNECT_CLI_WORKSPACE":from==="local"?"a local workspace's workspace.json":"this shell's session defaults"}, not from -w \u2014 ${from==="local"?"the clone may name a workspace that no longer exists.":"check that it is the one the ID belongs to."}`}function warnInheritedWorkspace(from,workspaceId){if(inheritedWorkspaceNoted)return;let origin=from!==void 0&&workspaceId!==void 0?{from,value:workspaceId}:workspaceOrigin;if(origin===void 0)return;let note=inheritedWorkspaceNote(origin.from,origin.value);note!==void 0&&(inheritedWorkspaceNoted=!0,warnLine(note))}function recordWorkspaceOrigin(source,values){let from=source.get("workspace"),value=values.workspace;from===void 0||value===void 0||(workspaceOrigin={from,value})}var sessionAnswers=new Map,announcedKeys=new Set,localAnswers=new Map,announcedLocalKeys=new Set,notedLocalClash=!1;function relevantScope(keys,registry2){let seen=new Set,walk2=key=>{if(!seen.has(key)){seen.add(key);for(let dep of registry2[key]?.dependsOn??[])walk2(dep)}};for(let key of keys)walk2(key);return seen}function describeScope(list,record4,registry2){return list.map(k2=>{let noun=(registry2[k2]?.label??k2).toLowerCase(),label=record4.labels?.[k2];return label?`${noun} "${label}" (${record4[k2]??""})`:`${noun} ${record4[k2]??""}`}).join(", ")}async function resolveParams(keys,provided,ctx){let registry2=ctx.registry??RESOLVERS,values={},userProvided=new Set,source=new Map;for(let[key,value]of Object.entries(provided))value&&(values[key]=value,userProvided.add(key),source.set(key,"flag"));for(let key of SESSION_KEYS){let fromEnv=process.env[SCOPE_ENV[key]];!values[key]&&fromEnv&&fromEnv!==""&&(values[key]=fromEnv,userProvided.add(key),source.set(key,"env"))}let blame=(key,form)=>{let spec=registry2[key],value=values[key]??"",origin=source.get(key)==="env"?scopeEnvVar(key)??key:source.get(key)==="session"?`session default \u2014 ${CLI} cli clear-session to clear`:source.get(key)==="local"?`local workspace record \u2014 ${local?.recordPath??""}`:ctx.blame?.[key]??spec?.flag??key;return form==="long"?`${spec?.label??key} '${value}' (${origin})`:`${origin} '${value}'`},skippedDefault=key=>ctx.useSession!==!1||!SESSION_KEYS.includes(key)?!1:readSession()?.[key]?!0:!!localWorkspaceScope()?.values[key],local=ctx.useSession===!1?void 0:localWorkspaceScope();local&&await applyLocalScope(local);let session=ctx.useSession===!1?void 0:readSession(),instanceCleared2=takeInstanceClear();if(instanceCleared2&&prompts().note(`Session defaults cleared \u2014 they belonged to instance '${instanceCleared2}', which is no longer the active instance.`),session){let applied=[];for(let key of SESSION_KEYS){let value=session[key];value&&!values[key]&&(values[key]=value,userProvided.add(key),source.set(key,"session"),applied.push(key))}let relevant=relevantScope(ctx.needs??keys,registry2),shown=applied.filter(k2=>relevant.has(k2)),describeKeys=list=>describeScope(list,session,registry2),drop=list=>{for(let key of list)delete values[key],userProvided.delete(key),source.delete(key)};if(canPrompt()){let unanswered=shown.filter(k2=>!sessionAnswers.has(k2));if(unanswered.length>0){let use=await prompts().confirm(`Use session defaults: ${describeKeys(unanswered)}?`,!0);for(let key of unanswered)sessionAnswers.set(key,use);use||prompts().note("Not using session defaults \u2014 resolving for this run only.")}let refused=applied.filter(k2=>sessionAnswers.get(k2)===!1);drop(refused),shown=shown.filter(k2=>!refused.includes(k2))}else if(shown.length>0){let fresh=shown.filter(k2=>!announcedKeys.has(k2));if(fresh.length>0){for(let key of fresh)announcedKeys.add(key);prompts().note(`Using session defaults: ${describeKeys(fresh)} (${CLI} cli clear-session to clear)`)}}}async function applyLocalScope(record4){let asRecord={...record4.values,labels:record4.labels},clash=SESSION_KEYS.filter(k2=>values[k2]&&values[k2]!==record4.values[k2]);if(clash.length>0&&!(clash.length===1&&clash[0]==="environment"&&await environmentBelongsTo(ctx.client,record4.values.workspace,values.environment??"")===!0)){if(!notedLocalClash){notedLocalClash=!0;let blamed=clash.map(k2=>blame(k2,"short")).join(", ");prompts().note(`The local workspace in ${displayPath(record4.directory)} is ${describeScope(clash,asRecord,registry2)} \u2014 set aside for this run, because ${blamed} was passed instead; its team and workspace are not used either.`)}return}let missing=SESSION_KEYS.filter(k2=>!values[k2]);if(missing.length===0)return;let relevant=relevantScope(ctx.needs??keys,registry2),shown=missing.filter(k2=>relevant.has(k2));if(canPrompt()){let unanswered=shown.filter(k2=>!localAnswers.has(k2));if(unanswered.length>0){let use=await prompts().confirm(`Use the local workspace in ${displayPath(record4.directory)} \u2014 ${describeScope(unanswered,asRecord,registry2)}?`,!0);for(let key of unanswered)localAnswers.set(key,use);if(!use){for(let key of SESSION_KEYS)localAnswers.set(key,!1);prompts().note("Not using the local workspace \u2014 resolving for this run only.")}}}else{let fresh=shown.filter(k2=>!announcedLocalKeys.has(k2));if(fresh.length>0){for(let key of fresh)announcedLocalKeys.add(key);prompts().note(`Using the local workspace in ${displayPath(record4.directory)}: ${describeScope(fresh,asRecord,registry2)} (--no-local-workspace to ignore)`)}}for(let key of missing)localAnswers.get(key)!==!1&&(values[key]=record4.values[key],userProvided.add(key),source.set(key,"local"))}let resolving=new Set,picked=new Set,labels={};async function need(key){let existing=values[key];if(existing)return existing;if(resolving.has(key))throw new Error(`circular resolver dependency at '${key}'`);resolving.add(key);let spec=registry2[key];if(!spec)throw new Error(`no resolver registered for param '${key}'`);if(!ctx.interactive){let envVar=scopeEnvVar(key);fail(EXIT.USAGE,"USAGE_ERROR",ctx.missing?.[key]??`${ctx.blame?.[key]??spec.flag} is required. ${supplyHint({env:envVar})}`,skippedDefault(key)?{hint:SKIPPED_DEFAULT_HINT[ctx.sessionSkipped??"destructive"]}:void 0)}let deps={};for(let dep of spec.dependsOn)deps[dep]=await need(dep);let providedDeps=spec.dependsOn.filter(d=>userProvided.has(d)),choices;try{choices=await withSpinner(`Fetching ${spec.plural}`,()=>spec.fetch(ctx.client,{...values}))}catch(err){if(err instanceof ResolverFetchError){if(err.status===404&&providedDeps.length>0){let blamed=providedDeps.map(d=>blame(d,"long")).join(", ");fail(EXIT.NOT_FOUND,"INVALID_PARAM",`${blamed} is invalid \u2014 the API returned 404 for it.`,{status:404})}mapResolverError(err,spec)}throw err}if(choices.length===0){if(providedDeps.length>0){let blamed=providedDeps.map(d=>blame(d,"short")).join(", ");fail(EXIT.NOT_FOUND,"NO_RESULTS",`No ${spec.plural} found for ${blamed} \u2014 double-check the value.`,{hint:spec.listCommand?`See what exists with \`${spec.listCommand}\`.`:void 0})}fail(EXIT.NOT_FOUND,"NO_RESULTS",`No ${spec.plural} available.`)}let sole=spec.autoSelectSingle&&choices.length===1?choices[0]:void 0,value,label;return sole?(value=sole.value,label=sole.label,prompts().note(`\u2714 ${spec.label}: ${label} (${value}) \u2014 only one, auto-selected`)):(value=await prompts().select(`${spec.label}:`,choices),label=choices.find(c=>c.value===value)?.label??value,prompts().note(`\u2714 ${spec.label}: ${label} (${value})`)),values[key]=value,labels[key]=label,ctx.labels&&(ctx.labels[key]=label),source.set(key,"picker"),picked.add(key),resolving.delete(key),value}for(let key of Object.keys(values))picked.has(key)||(values[key]=assertResourceId(values[key]??"",blame(key,"short")));recordWorkspaceOrigin(source,values);for(let key of keys)await need(key);if(ctx.sources)for(let[key,from]of source)ctx.sources[key]=from;recordWorkspaceOrigin(source,values);let pickedScope=SESSION_KEYS.some(k2=>picked.has(k2));return ctx.offerSession!==!1&&pickedScope&&keys.includes("environment")&&await maybeOfferSession(values,session,registry2,labels),values}async function maybeOfferSession(values,existing,registry2,labels){if(!sessionEnabled()||!canPrompt()||existing?.declined||hasScope(existing)||!values.environment||!values.workspace)return;let record4={team:values.team,workspace:values.workspace,environment:values.environment,labels:pickLabels(values,labels)},summary=describeScope(SESSION_KEYS.filter(k2=>values[k2]),record4,registry2);if(await prompts().confirm(`Remember these as defaults for this shell session \u2014 ${summary}?`,!0)){writeSession(record4);for(let key of SESSION_KEYS)record4[key]&&sessionAnswers.set(key,!0);prompts().note(`\u2714 Saved. Clear with: ${CLI} cli clear-session (or just open a new shell)`)}else writeSession({declined:!0}),prompts().note(`Not saved. Run ${CLI} cli set-session if you change your mind.`)}function pickLabels(values,labels){if(!labels)return;let out={};for(let key of SESSION_KEYS){let label=labels[key];label&&values[key]&&(out[key]=label)}return Object.keys(out).length>0?out:void 0}async function askVersion(message,allowEmpty=!1){for(;;){let answer=(await prompts().text(message,{allowEmpty})).trim();if(answer===""&&allowEmpty)return;let error51=semverError(answer);if(!error51)return answer;prompts().note(`\u2716 ${error51}`)}}var OTHER_INSTANCE="",INSTANCE_URL_PROMPT="Instance API base URL (usually https://api.<your-domain>)";async function askInstance(current){let known=current!==void 0&&INSTANCE_KEYS.includes(current),choice=await prompts().select("Instance:",[...INSTANCE_KEYS.map(key=>({value:key,label:KNOWN_INSTANCES[key].label,hint:KNOWN_INSTANCES[key].url})),{value:OTHER_INSTANCE,label:"Other\u2026",hint:"enter an API base URL"}],{initial:current===void 0?void 0:known?current:OTHER_INSTANCE});if(choice!==OTHER_INSTANCE)return choice;for(;;){let answer=await prompts().text(INSTANCE_URL_PROMPT,{initial:current!==void 0&&!known?current:"https://"}),error51=instanceError(answer);if(!error51)return normalizeInstance(answer);prompts().note(`\u2716 ${error51}`)}}async function askOutputCopy(){if(outputCopyPath())return outputCopyPath();if(!await prompts().confirm("Also copy the output to a file?",!1))return;let answer=await prompts().text(`File name (empty for ${generatedOutputName()} in the current directory)`,{allowEmpty:!0});return setOutputCopy(answer.trim()||!0)}async function resolverChoices(client,key,deps){let spec=RESOLVERS[key];if(!spec)throw new Error(`no resolver registered for param '${key}'`);try{return await withSpinner(`Fetching ${spec.plural}`,()=>spec.fetch(client,deps))}catch(err){if(!(err instanceof ResolverFetchError))throw err;mapResolverError(err,spec)}}async function pickEnvironments(client,workspaceId,message="Deploy into which environments? (space to pick, enter for none)"){let environments=await resolverChoices(client,"environment",{workspace:workspaceId});if(environments.length===0)return prompts().note("\u26A0 No environments in this workspace \u2014 nothing to deploy into."),{ids:[],labels:{}};let ids=await prompts().multiselect(message,environments),labels=Object.fromEntries(ids.map(id=>[id,environments.find(e=>e.value===id)?.label??id]));return{ids,labels}}async function askScript(opts){let existing={value:"existing",label:"Pick an existing script"},create={value:"new",label:"Create a new script",...opts.recommendCreate?{hint:opts.recommendCreate}:{}};if(await prompts().select(opts.message??"Script to run:",opts.recommendCreate?[create,existing]:[existing,create])==="existing")try{return{scriptId:(await resolveParams(["script"],{workspace:opts.workspace,environment:opts.environment},{client:opts.client,interactive:!0,offerSession:!1})).script}}catch(err){if(!(err instanceof CliError)||err.code!=="NO_RESULTS")throw err;prompts().note("\u26A0 No scripts in this environment yet \u2014 creating a new one instead.")}return{scriptName:await askScriptName(opts.suggestedName)}}async function askScriptName(suggested){for(;;){let answer=await prompts().text("New script name (use / for folders, e.g. handlers/OnIssueCreated)",{...suggested?{initial:suggested}:{},allowEmpty:!0}),error51=scriptNameError(answer);if(!error51)return normalizeScriptName(answer);prompts().note(`\u2716 ${error51}`)}}async function askKeepOrChange(opts){let choices=await resolverChoices(opts.client,opts.key,opts.deps),currentValue=opts.current?.value,marked=choices.map(choice=>choice.value===currentValue?{...choice,display:`${choice.display??choice.label} (current)`}:choice),missing=!!currentValue&&!choices.some(c=>c.value===currentValue);if(currentValue&&missing){let label=opts.current?.label??currentValue;marked.unshift({value:currentValue,label,display:`${label} (${opts.missingCurrentMark??"current"})`,hint:currentValue})}let offered=[...marked,...opts.extra??[]];if(offered.length===0)return;let picked=await prompts().select(opts.message,offered,currentValue?{initial:currentValue}:{});return picked===currentValue?void 0:picked}async function askStatus(current,noun="it"){let disabled=await prompts().select("Status:",[{value:"enabled",label:"Enabled",...current?{}:{hint:`enables ${noun}`}},{value:"disabled",label:"Disabled",...current?{hint:`disables ${noun}`}:{}}].map(choice=>choice.value==="disabled"===current?{...choice,display:`${choice.label} (current)`}:choice),{initial:current?"disabled":"enabled"})==="disabled";return disabled===current?void 0:disabled}var REGISTRY=new Map;function defineCommandDoc(command,doc){return REGISTRY.set(command,doc),doc}function docKeys(schema,hidden=[]){let json2=external_exports.toJSONSchema(schema,{unrepresentable:"any"}),all=Object.keys(json2.properties??{}).filter(key=>!hidden.includes(key)),required2=new Set(json2.required??[]);return{required:all.filter(key=>required2.has(key)).sort(),optional:all.filter(key=>!required2.has(key)).sort()}}function nestedKeysOf(property,key){let properties=[property,...property?.anyOf??[]].find(shape=>shape?.type==="object"&&shape.properties)?.properties;return properties?Object.keys(properties).map(child=>`${key}.${child}`):[]}function flagBlockKeys(schema,order){let json2=external_exports.toJSONSchema(schema,{unrepresentable:"any"});return order.flatMap(key=>[key,...nestedKeysOf(json2.properties?.[key],key)])}function aligned(rows2){let width=Math.max(...rows2.map(row=>row.term.length));return rows2.map(row=>` ${row.term.padEnd(width)} ${row.description}`)}function explainLines(doc,ctx={}){let lines=[],flagFor=ctx.flagFor;if(ctx.arguments&&ctx.arguments.length>0&&(lines.push("Arguments:"),lines.push(...aligned(ctx.arguments))),ctx.scope&&ctx.scope.length>0&&(lines.push("Scope flags:"),lines.push(...aligned(ctx.scope))),doc.schema){let{required:required2,optional:optional2}=docKeys(doc.schema,doc.hidden),conditional=doc.conditional??[];lines.push(`Required: ${required2.length>0?required2.join(", "):"none"}`),optional2.length>0&&lines.push(`Optional: ${optional2.map(key=>conditional.includes(key)?`${key}*`:key).join(", ")}`),conditional.length>0&&lines.push(` * ${conditional.join(" and ")} are optional to the schema; a rule below makes one required.`);let mapped=flagFor?flagBlockKeys(doc.schema,[...required2,...optional2]).map(key=>[key,flagFor(key)]).filter(([,flag])=>flag):[];if(mapped.length>0){lines.push("Keys as flags:");for(let[key,flag]of mapped){let env=credentialEnvFor(key,doc);lines.push(` ${key} = ${flag??""}${env===void 0?"":` + ${env}`}`)}}}if(doc.rules.length>0){lines.push("Rules:");for(let rule of doc.rules)lines.push(` \xB7 ${rule}`)}if(doc.notes&&doc.notes.length>0){lines.push("Notes:");for(let note of doc.notes)lines.push(` \xB7 ${note}`)}return lines}function explained(cmd,doc){return cmd.opts().explain!==!0?!1:(printExplain(doc,explainContext(cmd,doc)),!0)}var SCOPE_FLAGS=["--workspace","--env","--team"];function explainContext(cmd,doc){return{flagFor:flagResolver(cmd,doc),arguments:cmd.registeredArguments.map(argument=>({term:argument.required?`<${argument.name()}>`:`[${argument.name()}]`,description:argument.description})),scope:SCOPE_FLAGS.flatMap(long=>{let option=cmd.options.find(declared=>declared.long===long);return option?[{term:option.flags,description:option.description}]:[]})}}var SCOPE_KEY_FLAGS={teamId:"--team",workspaceId:"--workspace",environmentId:"--env",environmentIds:"--env"};function nestedFlag(key,doc,declared){let rule=doc.rules.find(text=>text.startsWith(`${key}:`)||text.startsWith(`${key} `));if(rule===void 0)return;let mentioned=new Set([...rule.matchAll(/--[a-z][a-z-]*/g)].map(match=>match[0]).filter(long=>declared.has(long)));if(mentioned.size!==1)return;let flag=/(--[a-z][a-z-]*)(?: <[^>]+>)? as a (?:repeatable )?flag/i.exec(rule)?.[1];return flag!==void 0&&mentioned.has(flag)?flag:void 0}function credentialEnvFor(key,doc){let rule=doc.rules.find(text=>text.startsWith(`${key}:`)||text.startsWith(`${key} `));if(rule===void 0||!/never from argv/i.test(rule))return;let named=new Set([...rule.matchAll(/SR_CONNECT_CLI_[A-Z0-9_]+/g)].map(match=>match[0]));return named.size===1?[...named][0]:void 0}function flagResolver(cmd,doc){let declared=new Set(cmd.options.map(option=>option.long).filter(long=>long!==void 0));return key=>{let kebab=`--${key.slice(key.lastIndexOf(".")+1).replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`;if(declared.has(kebab))return kebab;if(key.includes("."))return nestedFlag(key,doc,declared);let scope2=SCOPE_KEY_FLAGS[key];if(scope2!==void 0&&declared.has(scope2))return scope2;let beside=doc.rules.map(text=>new RegExp(`${key} \\((?:spelled )?(?:-[a-z]/)?(--[a-z][a-z-]*) as a flag[^)]*\\)`).exec(text)).find(match=>match!==null);if(beside?.[1]!==void 0&&declared.has(beside[1]))return beside[1];let spelled=doc.rules.find(text=>text.startsWith(`${key}:`)||text.startsWith(`${key} `))?.match(/(?:spelled|it is the) (?:-[a-z]\/)?(--[a-z][a-z-]*)|\((?:-[a-z]\/)?(--[a-z][a-z-]*) as a flag\)/i),flag=spelled?.[1]??spelled?.[2];return flag!==void 0&&declared.has(flag)?flag:void 0}}function printExplain(doc,ctx={}){let body=doc.body??{};if(isRaw())okText(JSON.stringify(body));else{let pretty=JSON.stringify(body,null,2);okText(process.stdout.isTTY?highlightContent(pretty,"json"):pretty)}for(let line of explainLines(doc,ctx))noteLine(line)}import{readFileSync as readFileSync12}from"fs";import{readSync as readSync2}from"fs";var CHUNK_BYTES=65536,IDLE_WAIT_MS=5;function readStdinSync(){let chunks=[],buffer=Buffer.alloc(CHUNK_BYTES),parked=new Int32Array(new SharedArrayBuffer(4));for(;;){let read;try{read=readSync2(0,buffer,0,CHUNK_BYTES,null)}catch(err){let code=err.code;if(code==="EAGAIN"){Atomics.wait(parked,0,0,IDLE_WAIT_MS);continue}if(code==="EOF")break;throw err}if(read===0)break;chunks.push(Buffer.from(buffer.subarray(0,read)))}return Buffer.concat(chunks).toString("utf8")}var SCOPE_ENV_VAR={team:"SR_CONNECT_CLI_TEAM",workspace:"SR_CONNECT_CLI_WORKSPACE",environment:"SR_CONNECT_CLI_ENVIRONMENT"};function scopeDescription(noun,opts={}){let tokens=[opts.required===!1||opts.behindPositional?"optional":"required","interactive",opts.sessionOnTty?"session default on a TTY only":"session default",`env ${SCOPE_ENV_VAR[noun]}`];return opts.behindPositional&&tokens.push("ignored when the positional argument is given"),`${capitalize(opts.prose??`${noun} ID`)} (${tokens.join(", ")})`}function capitalize(prose){return prose.charAt(0).toUpperCase()+prose.slice(1)}var SCOPE_TEAM=scopeDescription("team"),SCOPE_WORKSPACE=scopeDescription("workspace"),SCOPE_ENVIRONMENT=scopeDescription("environment"),SCOPE_ENVIRONMENT_BESIDE_POSITIONAL=scopeDescription("environment",{behindPositional:!0}),SCOPE_ENVIRONMENT_BESIDE_POSITIONAL_DESTRUCTIVE=scopeDescription("environment",{behindPositional:!0,sessionOnTty:!0}),SCOPE_TEAM_FILTER=scopeDescription("team",{prose:"team ID \u2014 filters the interactive workspace picker",required:!1}),SCOPE_TEAM_SEARCHED=scopeDescription("team",{prose:"team ID \u2014 searched for when omitted, every workspace read being keyed by team",required:!1}),SCOPE_TEAM_DESTRUCTIVE=scopeDescription("team",{sessionOnTty:!0}),SCOPE_WORKSPACE_DESTRUCTIVE=scopeDescription("workspace",{sessionOnTty:!0}),SCOPE_ENVIRONMENT_DESTRUCTIVE=scopeDescription("environment",{sessionOnTty:!0}),SCOPE_TEAM_FILTER_DESTRUCTIVE=scopeDescription("team",{prose:"team ID \u2014 filters the interactive workspace picker",required:!1,sessionOnTty:!0}),GATE_PROSE="environment ID \u2014 the change applies to the whole workspace, whatever environment is named",SCOPE_ENVIRONMENT_GATE=scopeDescription("environment",{prose:GATE_PROSE}),SCOPE_ENVIRONMENT_GATE_DESTRUCTIVE=scopeDescription("environment",{prose:GATE_PROSE,sessionOnTty:!0}),SCOPE_ENVIRONMENT_GATE_HEAD=scopeDescription("environment",{prose:"environment ID \u2014 the change applies to the whole workspace, and the environment named must run HEAD"}),INPUT_BODY="Read the full request body as JSON from a file, or - for stdin (optional, supersedes every body flag)",EXPLAIN="Print what the verb takes on stdout and the rules for every parameter on stderr, then exit without sending anything (optional, supersedes every other flag)",CONFIRM_YES="Skip the confirmation prompt (optional on a TTY, required otherwise)";function readInput(input){try{let raw=input==="-"?readStdinSync():readFileSync12(input,"utf8");return JSON.parse(raw)}catch(error51){fail(EXIT.USAGE,"INVALID_INPUT",`--input ${input==="-"?"stdin":input} could not be read or is not valid JSON.`,{hint:describeError(error51)})}}function validate(schema,body){let result=schema.safeParse(body);return result.success||fail(EXIT.USAGE,"INVALID_BODY",formatBodyError(result.error,body),{hint:EXPLAIN_HINT}),normalizeBodyIds(result.data,schema),result.data}function normalizeBodyIds(body,schema){if(body===null||typeof body!="object")return;let shape=objectShape(schema),record4=body;for(let[key,value]of Object.entries(record4)){if(/Ids?$/.test(key)){if(typeof value=="string"&&(record4[key]=assertBodyId(value,key)),Array.isArray(value))for(let[index,item]of value.entries())typeof item=="string"&&(value[index]=assertBodyId(item,key));continue}if(value===null||typeof value!="object"||Array.isArray(value))continue;let declared=shape?.[key];objectShape(declared)&&normalizeBodyIds(value,declared)}}function objectShape(schema){let current=schema;for(;current instanceof external_exports.ZodOptional||current instanceof external_exports.ZodNullable||current instanceof external_exports.ZodDefault||current instanceof external_exports.ZodReadonly;)current=current.unwrap();return current instanceof external_exports.ZodObject?current.shape:void 0}function assertBodyId(value,key){return value.trim()||fail(EXIT.USAGE,"INVALID_ID",`${key} is empty. Pass ${RESOURCE_ID_FORMAT}, null to detach where the key accepts it, or omit the key to leave it as it is.`),assertResourceId(value,key)}function formatBodyError(error51,body){let seen=new Set;for(let issue2 of error51.issues)seen.add(houseSentence(issue2,body));return[...seen].join(" ")}var EXPLAIN_HINT="Run the verb with --explain to see every key it takes and the flag each key is spelled as.";function houseSentence(issue2,body){let path2=issue2.path.map(String).join("."),subject=path2===""?"body":path2;if(issue2.code==="unrecognized_keys"){let keys=issue2.keys.join(", "),verb=issue2.keys.length>1?"are not keys":"is not a key";return`${keys} ${verb} of this body.`}if(issue2.code==="invalid_type"){if(valueAt(body,issue2.path)===void 0)return`${subject} is required.`;let wanted=TYPE_NOUNS[issue2.expected];if(wanted)return`${subject} must be ${wanted}.`}return issue2.code==="too_big"?issue2.origin==="array"?`${subject} takes at most ${issue2.maximum} items.`:isNumeric(issue2.origin)?`${subject} can be at most ${issue2.maximum}.`:`${subject} can be at most ${issue2.maximum} characters.`:issue2.code==="too_small"?issue2.origin==="array"?`${subject} needs at least ${issue2.minimum} items.`:isNumeric(issue2.origin)?`${subject} must be ${issue2.minimum} or more.`:`${subject} needs at least ${plural(Number(issue2.minimum),"character")}.`:path2===""?issue2.message:`${path2}: ${issue2.message}`}var TYPE_NOUNS={int:"a whole number",number:"a number",string:"text",boolean:"true or false",array:"a list",object:"an object"};function isNumeric(origin){return origin==="number"||origin==="int"||origin==="bigint"||origin==="date"}function plural(count,noun){return`${count} ${noun}${count===1?"":"s"}`}function valueAt(body,path2){let cursor=body;for(let key of path2){if(cursor===null||typeof cursor!="object")return;cursor=cursor[key]}return cursor}function failNothingToUpdate(flags){let list=flags.length>1?`${flags.slice(0,-1).join(", ")} or ${flags.at(-1)}`:flags[0]??"--input";fail(EXIT.USAGE,"USAGE_ERROR",`Nothing to update: pass ${list}.`)}function failNeedsYes(target,verb="Deleting"){fail(EXIT.USAGE,"CONFIRMATION_REQUIRED",`${verb} ${target} is irreversible. Re-run with --yes to confirm.`)}function assertChoice(flag,value,allowed){if(value!==void 0)return allowed.includes(value)||fail(EXIT.USAGE,"INVALID_OPTION",`${flag} must be one of: ${allowed.join(", ")}.`),value}function collect(value,previous){return[...previous??[],...value.split(",").map(v2=>v2.trim()).filter(v2=>v2!=="")]}function disabledFromFlags(opts){return switchFromFlags(opts,"disabled","enabled")}function switchFromFlags(opts,on2,off){if(opts[on2]&&opts[off]&&fail(EXIT.USAGE,"USAGE_ERROR",`--${on2} and --${off} cannot be combined.`),opts[on2])return!0;if(opts[off])return!1}function assertExplicitEnvironmentAgrees(envFlag,inBody){let explicit2=envFlag??process.env.SR_CONNECT_CLI_ENVIRONMENT;if(!explicit2||!inBody||explicit2===inBody)return;let source=envFlag===void 0?"SR_CONNECT_CLI_ENVIRONMENT names":"-e/--env names";fail(EXIT.USAGE,"USAGE_ERROR",`${source} ${explicit2} but the --input body's environmentId is ${inBody}; the body is what is sent, so drop one of them or make them agree.`)}async function teamForQuestions(scope2,globals){let known=scope2.team??globals.team;if(known)return known;if(canPrompt()){if(scope2.askedTeam!==void 0)return scope2.askedTeam||void 0;try{let resolved=await resolveParams(["team"],{},{client:scope2.client,interactive:!0,offerSession:!1});scope2.askedTeam=resolved.team??""}catch(err){if(!(err instanceof CliError))throw err;scope2.askedTeam=""}return scope2.askedTeam||void 0}}function stripUndefined(obj){return Object.fromEntries(Object.entries(obj).filter(([,v2])=>v2!==void 0))}function implicitShareMark(owner){let who=owner?personName(owner):"";return who?`current \u2014 implicitly shared via the workspace, owned by ${who}`:"current \u2014 implicitly shared via the workspace"}async function confirmImplicitReplacement(current,replacement,owner){let who=owner?personName(owner):"",contact=owner?.email&&who!==owner.email?` (${owner.email})`:"";return prompts().note([`"${current}" is attached here and reaches this workspace only because the workspace`,"is shared with you. Removing it cannot be undone by you: only",who?`${who}${contact}, who owns it, or someone it is explicitly shared with, can`:"the connector's owner, or someone it is explicitly shared with, can","attach it back."].join(`
1293
+ `)),prompts().confirm(`Replace it with "${replacement}"?`,!1)}var createBodySchema=external_exports.object({appId:external_exports.string().min(1),apiConnectionTypeId:external_exports.string().min(1),path:external_exports.string(),packageId:external_exports.string().optional(),connectorId:external_exports.string().optional(),environmentId:external_exports.string().optional()}).strict(),updateBodySchema=external_exports.object({path:external_exports.string().optional(),connectorId:external_exports.string().min(1).optional(),packageId:external_exports.string().min(1).optional()}).strict().refine(body=>Object.keys(body).length>0,{message:"At least one of path, connectorId or packageId is required."}),LIST_DOC=defineCommandDoc("api-connection list",{rules:["The workspace is -w and the environment -e; there is no positional argument, the verb listing every API connection of the workspace."],notes:["A path and its package belong to the workspace, so every environment lists the same connections. The connector column is the exception: it shows what is attached in the environment -e names, which is per-environment configuration."]}),GET_DOC=defineCommandDoc("api-connection get",{rules:["The API connection is the positional argument; the workspace is -w and the environment -e."],notes:["The one read that names the attached connector's owner, which matters because a connector you cannot use is still reported as attached.","Read through a non-HEAD environment it answers what that release captured."]}),DELETE_DOC=defineCommandDoc("api-connection delete",{rules:["The API connection is the positional argument; the workspace is -w and the environment -e, which gates the write rather than choosing what is deleted.","--yes skips the confirmation, and is required without a terminal."],notes:["Removes the API connection from the whole workspace rather than from one environment, and every script importing ./api/<path> stops working.","Its package leaves the workspace unless another API connection on HEAD still uses it. A release that captured a connection on that package does not keep the package in the workspace's dependency list, and pointing a connection back at it puts the package back.","A non-HEAD environment keeps running the copy its release captured."]}),CREATE_DOC=defineCommandDoc("api-connection create",{schema:createBodySchema,body:{appId:"<appId>",apiConnectionTypeId:"<apiConnectionTypeId>",path:"jira",packageId:"<packageId>",connectorId:"<connectorId>",environmentId:"<environmentId>"},rules:[`appId and apiConnectionTypeId come from ${CLI} app list, and the type must be one of the app's.`,`path: ${API_CONNECTION_PATH_FORMAT}; scripts import the connection as ./api/<path>, a pasted ./api/ prefix is dropped, and uniqueness within the workspace is the API's to refuse.`,"packageId: the vendor API package the connection is built on, one of the app's packages in app list; omitted, the API picks the recommended package, or the first one not deprecated, and refuses to choose at all when every package for the API connection type is deprecated.","connectorId attaches a connector in one environment and needs environmentId in the same body: -e/--env fills it on the flags path only, an --input body superseding every body flag; the connector must be of the same API connection type and usable by you in the team; connector list reports each connector's connectionType, which is the app's, and never its API connection type.","environmentId is required with connectorId, and validated whenever it is sent: it must exist and belong to the workspace, and the attachment is refused when that environment is non-HEAD. Sent without connectorId it attaches nothing, so the flags path drops it. The body is what is sent: an -e or SR_CONNECT_CLI_ENVIRONMENT that names a different environment from the body is exit 2 rather than a tie-break, and the session record and a clone's workspace.json are not consulted for the environment when a body is given.","The workspace is -w and never a body key; path and packageId are shared by every environment."]}),UPDATE_DOC=defineCommandDoc("api-connection update",{schema:updateBodySchema,body:{path:"jira",packageId:"<packageId>",connectorId:"<connectorId>"},rules:["An omitted key keeps the current value, and a body with no keys is refused: at least one of path, connectorId or packageId is required.",`connectorId attaches a connector in the environment named by -e, and there is no way to detach one; the connector must be of the connection's API connection type and usable by you in the team, and connector list reports each connector's connectionType, which is the app's, never its API connection type. Omitted, it is kept from that environment's own record, so an API connection with nothing attached there refuses every update \u2014 a path-only one included \u2014 with 400 "Connector is required." until a connector is sent.`,`path: ${API_CONNECTION_PATH_FORMAT}; a pasted ./api/ prefix is dropped; shared by every environment, and every script importing the old ./api/<path> breaks.`,"packageId: the vendor API package, as reported in package.id by get; shared by every environment.","In a non-HEAD environment only connectorId can change. path and packageId are read-only rather than refused there: echo back what that environment's own get reports, or omit them, and only a differing value is a 400 naming it."]});function withScope(cmd,opts={}){let env=opts.gate?opts.destructive?SCOPE_ENVIRONMENT_GATE_DESTRUCTIVE:SCOPE_ENVIRONMENT_GATE:opts.destructive?SCOPE_ENVIRONMENT_DESTRUCTIVE:SCOPE_ENVIRONMENT;return cmd.option("-w, --workspace <workspaceId>",opts.destructive?SCOPE_WORKSPACE_DESTRUCTIVE:SCOPE_WORKSPACE).option("-e, --env <environmentId>",env).option("--team <teamId>",opts.destructive?SCOPE_TEAM_FILTER_DESTRUCTIVE:SCOPE_TEAM_FILTER)}async function resolveScope(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,workspace:resolved.workspace??"",environment:resolved.environment??"",team:resolved.team}}async function resolveApiConnection(scope2,provided){if(provided)return{id:assertResourceId(provided,"apiConnectionId")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<apiConnectionId> is required. ${supplyHint()}`);let labels={};return{id:(await resolveParams(["apiConnection"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0,labels})).apiConnection??"",label:labels.apiConnection}}function connectorCell(connection,empty="\u2014"){let connector=connection.connector;return connector?`${connector.name||connector.id} (${connector.id})`:empty}function packageCell(pkg,empty="\u2014"){return pkg?pkg.label??pkg.name:empty}function packageDetail(pkg,empty="(none)"){return pkg?pkg.label?`${pkg.label} (${pkg.name})`:pkg.name:empty}async function askPackage(client,appId,apiConnectionTypeId){let packages;try{packages=await withSpinner("Fetching packages",()=>apiConnectionPackages(client,appId,apiConnectionTypeId))}catch{return}if(packages.length===0)return;let auto=packages.find(p=>p.recommended)??packages.find(p=>!p.deprecated);if(auto&&packages.length===1)return;auto||prompts().note("Every package for this API connection type is deprecated \u2014 pick one.");let choices=packages.map(p=>{let label=p.name??p.id??"?",hint=p.deprecated?"deprecated":p.recommended?"recommended":void 0;return{value:p.id??"",label,...p.id===auto?.id?{display:`${label} (default)`,hint:hint??"the API picks this"}:hint?{hint}:{}}}),picked=await prompts().select("Package:",choices,auto?.id?{initial:auto.id}:{});return picked===auto?.id?void 0:picked}async function askPath(initial){for(;;){let answer=await prompts().text(PATH_PROMPT,{...initial?{initial}:{},allowEmpty:!0}),error51=apiConnectionPathError(answer);if(!error51)return normalizeApiConnectionPath(answer);prompts().note(`\u2716 ${error51}`)}}function updateFail(status,body,scope2){let error51=body,message=error51?.errorMessage??error51?.message??"";status===400&&/^connector is required\.?$/i.test(message.trim())&&fail(EXIT.API_ERROR,"BAD_REQUEST",message,{status,hint:`No connector is attached in that environment, and an omitted --connector-id keeps whatever is: send one. \`${CLI} api-connection list -w ${scope2.workspace} -e ${scope2.environment}\` shows what each environment has.`}),apiFail(status,body)}function releasedNote(version2){return`\u26A0 This environment has ${version2?`release ${version2}`:"a release"} deployed. Only the connector can be changed there; the import path and the package belong to the API connection and are shared by every environment.`}async function askConnector(scope2,globals,current){let team=await teamForQuestions(scope2,globals);if(!team)return;let deps={team,app:current.appId,apiConnectionType:current.apiConnectionTypeId,workspace:scope2.workspace,environment:scope2.environment},implicit=!1;if(current.connectorId)try{let absent=!(await resolverChoices(scope2.client,"connector",deps)).some(choice=>choice.value===current.connectorId),me2=await currentUserId(scope2.client),someoneElse=!current.owner||!me2||current.owner.id!==me2;implicit=absent&&someoneElse}catch(err){if(!(err instanceof CliError))throw err}for(;;){let picked;try{picked=await askKeepOrChange({client:scope2.client,key:"connector",deps,message:"Connector:",current:{value:current.connectorId,label:current.label},...implicit?{missingCurrentMark:implicitShareMark(current.owner)}:{}})}catch(err){if(!(err instanceof CliError))throw err;return}if(picked===void 0||!implicit)return picked;let replacement=await connectorName(scope2.client,deps,picked);if(await confirmImplicitReplacement(current.label??current.connectorId??"",replacement,current.owner))return picked}}async function connectorName(client,deps,connectorId){try{return(await resolverChoices(client,"connector",deps)).find(choice=>choice.value===connectorId)?.label??connectorId}catch{return connectorId}}var NO_CONNECTOR="\0no-connector";async function askConnectorOnCreate(client,globals,current,scopeTeam){let scope2={client,workspace:current.workspace,environment:current.environment??"",team:scopeTeam},team=await teamForQuestions(scope2,globals);if(!team)return;let choices;try{choices=await resolverChoices(client,"connector",{team,app:current.appId,apiConnectionType:current.apiConnectionTypeId,workspace:current.workspace,...current.environment?{environment:current.environment}:{}})}catch(err){if(!(err instanceof CliError))throw err;return}if(choices.length===0){prompts().note("\u26A0 No connector of this type exists in the team \u2014 creating the API connection unattached.");return}let picked=await prompts().select("Connector:",[{value:NO_CONNECTOR,label:"No connector",hint:"attach one later; scripts using it fail until then"},...choices],{initial:choices[0]?.value??NO_CONNECTOR});return picked===NO_CONNECTOR?void 0:picked}async function buildCreateBody(client,workspaceId,scope2,opts,interactive){let labels={},resolved=await resolveParams(["app","apiConnectionType"],{team:scope2.team,workspace:workspaceId,environment:opts.env??scope2.environment,app:opts.appId,apiConnectionType:opts.apiConnectionTypeId},{client,interactive,labels,offerSession:!1}),appId=resolved.app??"",apiConnectionTypeId=resolved.apiConnectionType??"",path2=opts.path;path2===void 0&&(interactive||fail(EXIT.USAGE,"USAGE_ERROR","--path is required."),path2=await askPath(suggestPathFromLabel(labels.app??"")));let packageId=opts.packageId??(interactive?await askPackage(client,appId,apiConnectionTypeId):void 0),environmentId=opts.env??scope2.environment,connectorId=opts.connectorId;return!connectorId&&interactive&&(connectorId=await askConnectorOnCreate(client,{team:opts.team},{workspace:workspaceId,...environmentId?{environment:environmentId}:{},appId,apiConnectionTypeId},resolved.team)),connectorId&&!environmentId&&interactive&&(environmentId=(await resolveParams(["environment"],{team:resolved.team,workspace:workspaceId},{client,interactive:!0,offerSession:!1})).environment),stripUndefined({appId,apiConnectionTypeId,path:path2,packageId,connectorId,environmentId:connectorId?environmentId:void 0})}async function buildUpdateBody(scope2,globals,apiConnectionId,opts){if(opts.input)return readInput(opts.input);if(!canPrompt()){let rawBody=stripUndefined({path:opts.path===void 0?void 0:assertApiConnectionPath(opts.path),connectorId:opts.connectorId,packageId:opts.packageId});return Object.keys(rawBody).length===0&&failNothingToUpdate(["--path","--connector-id","--package-id","--input"]),rawBody}let current=await withSpinner("Fetching API connection",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,apiConnectionId}}}));(!current.response.ok||!current.data)&&apiFail(current.response.status,current.error);let release2=await withSpinner("Checking the environment",()=>environmentRelease(scope2.client,scope2.workspace,scope2.environment));if(release2&&prompts().note(releasedNote(release2.version)),release2){let shared=[...opts.path===void 0?[]:["--path"],...opts.packageId===void 0?[]:["--package-id"]];shared.length>0&&fail(EXIT.USAGE,"USAGE_ERROR",`${shared.join(" and ")} cannot be changed in an environment with a release deployed \u2014 the import path and the package belong to the API connection and are shared by every environment. Target a HEAD environment, or pass only --connector-id.`)}let path2=release2?void 0:opts.path===void 0?await askPath(current.data.path):assertApiConnectionPath(opts.path),packageId=release2?void 0:opts.packageId??await askKeepOrChange({client:scope2.client,key:"apiConnectionPackage",deps:{app:current.data.app.id,apiConnectionType:current.data.apiConnectionTypeId},message:"Package:",current:{value:current.data.package?.id,label:packageCell(current.data.package,"")}}),connectorId=opts.connectorId??await askConnector(scope2,globals,{appId:current.data.app.id,apiConnectionTypeId:current.data.apiConnectionTypeId,connectorId:current.data.connector?.id,label:current.data.connector?.name,owner:current.data.connector?.owner});!current.data.connector?.id&&connectorId===void 0&&fail(EXIT.USAGE,"CONNECTOR_REQUIRED",`This API connection has no connector attached in this environment, and the API refuses every update to one that has none. Attach one with --connector-id <id>, from \`${CLI} connector list\`.`);let renamed=path2===void 0||path2===current.data.path?void 0:path2;if(renamed===void 0&&packageId===void 0&&connectorId===void 0){prompts().note("Nothing to update \u2014 the API connection was left as it is.");return}return stripUndefined({path:renamed,connectorId,packageId})}function apiConnectionCommand(){let conn=new Command("api-connection").alias("ac").description("Manage workspace API connections");return conn.command("create").description("Create an API connection in a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--app-id <id>","App ID (required unless --input, interactive)").option("--api-connection-type-id <id>","API connection type ID (required unless --input, interactive)").option("--path <path>",`Import path scripts use to reference the connection as ${importSpecifier("<path>")}, ${API_CONNECTION_PATH_FORMAT} (required unless --input, interactive)`).option("--package-id <id>","Package ID (optional, interactive, API default: the recommended or first non-deprecated package)").option("--connector-id <id>","Connector to authorize the connection with (optional, interactive, requires -e/--env, refused in a non-HEAD environment)").option("-e, --env <environmentId>","Environment ID (required with --connector-id unless --input, interactive, session default, env SR_CONNECT_CLI_ENVIRONMENT, ignored with --input)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),interactive=canPrompt(),scope2=await resolveParams(["workspace"],{team:opts.team??globals.team,workspace:opts.workspace??globals.workspace,environment:opts.env??globals.env},{client,interactive,offerSession:!1,needs:["workspace","environment"]}),workspaceId=scope2.workspace??"",rawBody=opts.input?readInput(opts.input):await buildCreateBody(client,workspaceId,scope2,opts,interactive),parsed=validate(createBodySchema,rawBody),body={...parsed,path:assertApiConnectionPath(parsed.path)};body.connectorId&&!body.environmentId&&fail(EXIT.USAGE,"USAGE_ERROR",opts.input?"connectorId needs environmentId in the same body \u2014 -e/--env does not fill it, an --input body superseding every body flag (a connector is attached per environment).":"--connector-id needs an environment \u2014 pass -e/--env (a connector is attached per environment)."),opts.input&&assertExplicitEnvironmentAgrees(opts.env,body.environmentId);let{data,response,error:error51}=await withSpinner("Creating API connection",()=>client.POST("/v1/workspace/{workspaceId}/apiConnection",{params:{path:{workspaceId}},body}));(!response.ok||!data)&&apiFail(response.status,error51),await syncApiConnections(client,{workspaceId}),await syncPackages(client,workspaceId),okMutation("API connection created",data,{...data,path:body.path,import:importSpecifier(body.path)})}),withScope(conn.command("list").description("List API connections in a workspace")).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope(globals),{data,response,error:error51}=await withSpinner("Fetching API connections",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnections",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({apiConnections:d.apiConnections.map(c=>({id:c.id,path:c.path??"\u2014",app:`${c.app.name} (${c.app.id})`,connector:connectorCell(c),package:packageDetail(c.package,"\u2014")}))})})}),withScope(conn.command("get").description("Get a single API connection as the environment sees it").argument("[apiConnectionId]","API connection ID (required, interactive)")).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,GET_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope(globals),connection=await resolveApiConnection(scope2,idArg),{data,response,error:error51}=await withSpinner("Fetching API connection",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,apiConnectionId:connection.id}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({id:d.id,path:d.path??"(none)",import:d.path?importSpecifier(d.path):"(none)",app:`${d.app.name} (${d.app.id})`,apiConnectionTypeId:d.apiConnectionTypeId,connector:connectorCell(d,"(none)"),...d.connector?.owner?{connectorOwner:personCell(d.connector.owner)}:{},package:packageDetail(d.package)})})}),withScope(conn.command("update").description("Update an API connection").argument("[apiConnectionId]","API connection ID (required, interactive)")).option("--path <path>",`New import path, used by scripts as ${importSpecifier("<path>")}, ${API_CONNECTION_PATH_FORMAT} (optional, interactive on HEAD only, refused when it differs from what a non-HEAD environment reports)`).option("--package-id <id>","Vendor API package to use, as reported in package.id (optional, interactive on HEAD only, refused when it differs from what a non-HEAD environment reports)").option("--connector-id <id>","Connector to attach in the specified environment \u2014 there is no way to detach one (optional, interactive, required when the specified environment has no connector attached)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope(globals),connection=await resolveApiConnection(scope2,idArg),rawBody=await buildUpdateBody(scope2,globals,connection.id,opts);if(rawBody===void 0)return;let parsed=validate(updateBodySchema,rawBody),body=parsed.path===void 0?parsed:{...parsed,path:assertApiConnectionPath(parsed.path)},{response,error:error51}=await withSpinner("Updating API connection",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,apiConnectionId:connection.id}},body}));response.ok||updateFail(response.status,error51,scope2),await syncApiConnections(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment}),await syncPackages(scope2.client,scope2.workspace);let echoed=body.path?{path:body.path,import:importSpecifier(body.path)}:void 0;okMutation("API connection updated",{updated:!0,id:connection.id},echoed)}),withScope(conn.command("delete").description("Delete an API connection from a workspace").argument("[apiConnectionId]","API connection ID (required, interactive)"),{destructive:!0,gate:!0}).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope(globals,{useSession:canPrompt()}),connection=await resolveApiConnection(scope2,idArg);if(!opts.yes){canPrompt()||failNeedsYes(`API connection ${connection.id}`);let current=await withSpinner("Fetching API connection",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,apiConnectionId:connection.id}}}));(!current.response.ok||!current.data)&&apiFail(current.response.status,current.error);let path2=current.data.path,pkg=current.data.package;prompts().note(["Deleting removes the API connection from the whole workspace, not just this environment.",path2?`Scripts importing "${importSpecifier(path2)}" stop working.`:"Scripts importing it stop working.",pkg?`The vendor API package ${packageDetail(pkg)} is removed from the workspace unless another API connection still uses it.`:"The vendor API package it uses is removed from the workspace unless another API connection still uses it.","An environment with a release deployed keeps running the API connection captured in that release until the release is replaced."].join(`
1294
+ `)),await prompts().confirm(`Delete API connection ${path2??connection.id} (${connection.id})? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")}let{response,error:error51}=await withSpinner("Deleting API connection",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnection/{apiConnectionId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,apiConnectionId:connection.id}}}));response.ok||apiFail(response.status,error51),await syncApiConnections(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment}),await syncPackages(scope2.client,scope2.workspace),okMutation("API connection deleted",{deleted:!0,id:connection.id})}),conn}function parseCredentials(raw){if(raw.startsWith("{")){try{let parsed=JSON.parse(raw);if(parsed.username&&parsed.password)return{username:parsed.username,password:parsed.password}}catch{}fail(EXIT.USAGE,"INVALID_CREDENTIALS_INPUT",'JSON credentials must be {"username": "...", "password": "..."}.')}let colon=raw.indexOf(":");return(colon<1||colon===raw.length-1)&&fail(EXIT.USAGE,"INVALID_CREDENTIALS_INPUT","Expected credentials as username:password on stdin."),{username:raw.slice(0,colon),password:raw.slice(colon+1)}}function apiKeyInstructions(instance4){let url2=apiKeysUrl(instance4),profile='click your profile name in the bottom-left corner and select "API Keys"';return["Generate an API key in the ScriptRunner Connect web app:",url2?` 1. Open ${url2}
1295
+ (or ${profile})`:` 1. In the web app, ${profile}`,' 2. Click "Create new", name it \u2014 for example "CLI" \u2014 then "Create new"'," 3. Copy Email into the username below, and API Key into the password"].join(`
1296
+ `)}async function verify(creds,instance4){warnIfInsecure(instance4);let client=createClient({baseUrl:baseUrl(instance4),headers:{Authorization:basicAuthHeader(creds),...identityHeaders()},fetch:fetchWithRetry}),{data,response,error:error51}=await withSpinner("Verifying credentials",()=>client.GET("/v1/user/me"));return(!response.ok||!data)&&apiFail(response.status,error51),data}async function askAgenticFeedback(){let descriptor=SETTINGS.agenticFeedback;if(envDisabled("agenticFeedback")){prompts().note(`Agentic feedback is off in this environment (${descriptor.envVar}) \u2014 not asking.`);return}let current=storedAgenticFeedback(),answer;try{answer=await prompts().confirm("May agents send feedback to the ScriptRunner Connect team on their own, to improve the CLI's agentic capabilities?",current)}catch(err){if(!(err instanceof CliError&&err.code==="CANCELLED")){warnLine(`\u26A0 Could not ask about agentic feedback (${describeError(err)}).`);return}prompts().note(`Agentic feedback left as it is (${current?"on":"off"}).`);return}if(answer!==current)try{setSetting("agenticFeedback",answer)}catch(err){warnLine(`\u26A0 Could not store the setting (${describeError(err)}) \u2014 the login itself is unaffected.`);return}prompts().note(answer?`Agentic feedback: on. Change it any time with \`${CLI} cli settings\`.`:`Agentic feedback: off \u2014 only the interactive flow can post. Change it any time with \`${CLI} cli settings\`.`)}function storedAgenticFeedback(){return settingStates().find(state=>state.key==="agenticFeedback")?.enabled!==!1}var LOGIN_DOC=defineCommandDoc("auth login",{rules:['--credentials-stdin reads username:password from stdin, split on the first colon, or {"username":\u2026,"password":\u2026}. Required without a terminal, a key never riding in argv.',"--insecure-storage writes a credentials.json only you can read instead of using the secure store. Without it, a machine with no reachable secure store cannot log in: exit 2 KEYCHAIN_UNAVAILABLE, with the flag named in the hint."],notes:["The secure store is the macOS Keychain, Windows Credential Manager or Secret Service on Linux.","SR_CONNECT_CLI_USERNAME and SR_CONNECT_CLI_PASSWORD are not read here. They replace a stored login for every other command, so with them set no login is needed at all.","The instance must come from --instance or SR_CONNECT_CLI_INSTANCE when none is stored and nobody can be asked.","The document reports authenticated, source (keychain or file \u2014 the same word auth status answers with), the instance, the agentic-feedback switch and the user."]}),STATUS_DOC=defineCommandDoc("auth status",{rules:["No parameters of its own: it reports on whatever credentials and instance the run resolves to."],notes:["Which credential source is in use \u2014 environment, secure store or file \u2014 and which instance it verifies against.","It sends the same request as login and fails the same way, which is what makes it the first thing to run when something answers 3."]}),LOGOUT_DOC=defineCommandDoc("auth logout",{rules:["No parameters: it removes whatever is stored."],notes:["Removes the stored credentials and every terminal's session defaults. A lock whose lease has not run out is kept in the record and named on stderr with the command that gives it back, because logging out leaves nothing here able to release it; the raw document reports them as keptLocks.","Keeps the configured instance, the API-call recordings, the crash reports and the settings \u2014 none of which is a credential, and all of which you want when authentication is the thing that broke."]});function authCommand(){let auth=new Command("auth").description("Manage CLI authentication");return auth.command("login").description("Verify and store API credentials in the OS keychain").option("--credentials-stdin","Read username:password (or JSON) from stdin instead of prompting (optional on a TTY, required otherwise)").option("--insecure-storage","Store credentials in a plaintext 0600 file instead of the OS keychain (optional)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LOGIN_DOC))return;let globals=cmd.optsWithGlobals();!opts.credentialsStdin&&!canPrompt()&&fail(EXIT.USAGE,"CREDENTIALS_REQUIRED","Not interactive. Pipe credentials with --credentials-stdin, or set SR_CONNECT_CLI_USERNAME and SR_CONNECT_CLI_PASSWORD.");let instance4=explicitInstance(globals.instance);!instance4&&canPrompt()&&(instance4=await askInstance(resolveInstance())),instance4||(instance4=requireInstance(globals.instance));let chosenInstance=instance4,creds;if(opts.credentialsStdin)creds=parseCredentials(readStdinSync().trim());else{prompts().note(apiKeyInstructions(chosenInstance));let username=await prompts().text("ScriptRunner Connect API username:"),password=await prompts().password("ScriptRunner Connect API password:");creds={username,password}}let user=await verify(creds,chosenInstance),source;if(opts.insecureStorage)fileSet(creds),source="file";else try{await keychainSet(creds),source="keychain"}catch(err){fail(EXIT.USAGE,"KEYCHAIN_UNAVAILABLE",`OS keychain unavailable (${err instanceof Error?err.message:String(err)}).`,{hint:"Re-run with --insecure-storage to use a 0600 file, or use SR_CONNECT_CLI_USERNAME/SR_CONNECT_CLI_PASSWORD env vars."})}writeConfig({...readConfig(),instance:chosenInstance}),canPrompt()&&await askAgenticFeedback(),ok({authenticated:!0,source,instance:chosenInstance,agenticFeedback:storedAgenticFeedback(),user},{human:d=>({...d,instance:instanceLabel(d.instance)})})}),auth.command("status").description("Show credential source, instance, and verify against the API").option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,STATUS_DOC))return;let globals=cmd.optsWithGlobals(),creds=await requireCredentials(),instance4=requireInstance(globals.instance),user=await verify(creds,instance4);ok({authenticated:!0,source:creds.source,instance:instance4,username:creds.username,user},{human:d=>({...d,instance:instanceLabel(d.instance)})})}),auth.command("logout").description("Remove stored credentials and every shell session's remembered scope").option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LOGOUT_DOC))return;let removed=[];await keychainDelete()&&removed.push("keychain"),fileGet()&&(fileDelete(),removed.push("file"));let{removed:sessions,keptLocks}=clearAllSessions();if(sessions>0&&removed.push("sessions"),keptLocks.length>0){let lines=keptLocks.map(lock=>` ${lockReleaseCommand(lock)}`);warnLine(`\u26A0 ${keptLocks.length===1?"One workspace lock is":`${keptLocks.length} workspace locks are`} still held, and logging out leaves nothing here able to release ${keptLocks.length===1?"it":"them"}.
1297
+ Log back in and give ${keptLocks.length===1?"it":"them"} back with:
1298
+ ${lines.join(`
1299
+ `)}
1300
+ Otherwise ${keptLocks.length===1?"it lapses on its own":"they lapse on their own"}.`)}okMutation("Logged out",{loggedOut:!0,removed,sessions,keptLocks},{removed:removed.length>0?removed.join(", "):"(nothing stored)",sessions})}),auth}import{createServer}from"http";var import_picocolors8=__toESM(require_picocolors(),1);import{readFileSync as readFileSync13,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join13,parse as parse3}from"path";import{fileURLToPath as fileURLToPath2}from"url";function currentFile(){let file2=fileURLToPath2(import.meta.url);try{return realpathSync2(file2)}catch{return file2}}function packageRoot(from=currentFile()){let dir=dirname4(from),{root}=parse3(dir);for(;;){try{return JSON.parse(readFileSync13(join13(dir,"package.json"),"utf8"))?.name===PACKAGE?dir:void 0}catch{}if(dir===root)return;dir=dirname4(dir)}}function selfReadme(from){let root=packageRoot(from);if(root!==void 0)try{return readFileSync13(join13(root,"README.md"),"utf8")}catch{return}}var import_picocolors6=__toESM(require_picocolors(),1);var INDENT=" ",padding=level=>INDENT.repeat(Math.max(0,level)),isValueType=val=>val.type!==void 0&&val.value!==void 0;function formatStackTrace(level,error51){return(error51.stack??[]).map(frame=>`
1301
+ ${padding(level+1)} at ${frame.methodName} (${frame.file}:${frame.lineNumber}:${frame.column})`).join("")}function prettifyJson(json2,level){return JSON.stringify(JSON.parse(json2),null,padding(level+1))}function convertValueToString(val,first,last,level,isArray){try{if(isValueType(val)){if(val.type==="Error"){let error51=val.value;return`${padding(level)}${error51.name??"Error"}: ${error51.message??"[No Message]"}${formatStackTrace(level,error51)}${last?"":`
1302
+ `}`}if(val.type==="object")return`${first?"":`
1303
+ `}${padding(level)}${prettifyJson(val.value,level)}${last?"":`
1304
+ `}`;let value=isArray&&val.type==="string"?`"${String(val.value)}"`:String(val.value);return`${padding(level)}${value}`}return val.type!==void 0?`${padding(level)}${val.type==="Promise"?"Promise (did you forget to wait on Promise?)":val.type}`:"UNKNOWN_TYPE"}catch{return"UNKNOWN_VALUE"}}function convertArgToString(arg,first,last){if(arg.isArray){let values=arg.values.map((val,index)=>convertValueToString(val,index===0,index===arg.values.length-1,1,!0));return`${first?"":`
1305
+ `}[
1306
+ ${values.join(`,
1307
+ `)}
1308
+ ]${last?"":`
1309
+ `}`}return arg.values.length>0?convertValueToString(arg.values[0],first,last,0,!1):"MISSING_VALUE"}function getMessageForArgs(args){return args.map((arg,index)=>convertArgToString(arg,index===0,index===args.length-1)).join(" ").replace(/\n \n/g,`
1310
+ `).replace(/\n\n/g,`
1311
+ `)}var TIMESTAMP_MODES=["time","iso","relative","off"],MAX_DEPTH=8,LEVEL_WIDTH=5;function largePlaceholder(entry2,opts){let head="\u22EF message too large to display. Re-run with --expand-large";return!opts.invocationId||!opts.workspaceId?`${head}.`:`${head}, or fetch this one on its own:
1312
+ ${CLI} log get-large-log-message ${opts.invocationId} ${entry2.id} -w ${opts.workspaceId}`}var LARGE_FAILED="\u22EF message too large to display, and downloading it failed",SEVERITY_COLOR={error:import_picocolors6.default.red,warn:import_picocolors6.default.yellow,info:import_picocolors6.default.cyan,debug:import_picocolors6.default.dim,log:text=>text};function knownSeverity(severity){return severity!==void 0&&severity in SEVERITY_COLOR?severity:"log"}function formatLogRow(row){let stamp=row.stamp.padEnd(row.stampWidth),gap=row.stampWidth>0?" ":"",indent=padding(Math.max(0,row.depth)),severity=knownSeverity(row.severity),level=severity.toUpperCase().padEnd(LEVEL_WIDTH),plain=`${stamp}${gap}${indent}${level} `,gutter=`${stamp}${gap}${indent}${SEVERITY_COLOR[severity](level)} `,continuation=" ".repeat(plain.length),lines=row.body.split(`
1313
+ `).map((line,index)=>index===0?`${gutter}${line}`:`${continuation}${line}`);return row.system&&(lines[lines.length-1]+=` ${import_picocolors6.default.dim("[system]")}`),lines.join(`
1314
+ `)}function two(value){return String(value).padStart(2,"0")}function localTime(timestamp){let date5=new Date(timestamp);return`${two(date5.getHours())}:${two(date5.getMinutes())}:${two(date5.getSeconds())}.${String(date5.getMilliseconds()).padStart(3,"0")}`}function ordered(entries){return[...entries].sort((a,b2)=>a.seq-b2.seq||a.nanoseconds-b2.nanoseconds)}function flatten(entries){return entries.flatMap(entry2=>[entry2,...flatten(entry2.children??[])])}function entryMessage(entry2,opts){if(entry2.expandFailed)return import_picocolors6.default.dim(LARGE_FAILED);if(entry2.largePayload)return import_picocolors6.default.dim(largePlaceholder(entry2,opts));let message=getMessageForArgs(entry2.args);return entry2.method==="group"||entry2.method==="groupCollapsed"?import_picocolors6.default.bold(`\u25B8 ${message}`):entry2.type==="SYSTEM_LOG"?import_picocolors6.default.bold(message):message}function renderConsoleLogs(file2,opts={}){let mode=opts.timestamps??"time",maxDepth=opts.maxDepth??MAX_DEPTH,roots=ordered(file2.invocationLogs),all=flatten(roots),first=all.length>0?all.reduce((min,entry2)=>Math.min(min,entry2.timestamp),1/0):0,stamps=new Map;for(let entry2 of all)stamps.set(entry2.id,stampOf(entry2.timestamp,mode,first));let stampWidth=0;for(let stamp of stamps.values())stampWidth=Math.max(stampWidth,stamp.length);let lines=[],header=opts.heading??["Console logs",opts.invocationId,`${all.length} ${all.length===1?"entry":"entries"}`].filter(Boolean).join(" \xB7 ");lines.push(import_picocolors6.default.bold(header),"");let render=(entries,depth)=>{for(let entry2 of entries)lines.push(formatLogRow({stamp:stamps.get(entry2.id)??"",stampWidth,depth:Math.min(depth,maxDepth),severity:knownSeverity(entry2.severity),body:entryMessage(entry2,opts),system:entry2.type==="SYSTEM_LOG"})),render(ordered(entry2.children??[]),depth+1)};if(render(roots,0),file2.httpLogsUrl){let suffix=opts.invocationId&&opts.workspaceId?`:
1315
+ ${CLI} log list-http-logs ${opts.invocationId} -w ${opts.workspaceId}`:` \u2014 see ${CLI} log list-http-logs.`;lines.push("",import_picocolors6.default.dim(`HTTP logs were also recorded for this invocation${suffix}`))}return lines.join(`
1316
+ `)}function stampWidthOf(mode){switch(mode){case"off":return 0;case"iso":return 24;case"relative":return 8;default:return 12}}function stampOf(timestamp,mode,first){switch(mode){case"off":return"";case"iso":return new Date(timestamp).toISOString();case"relative":return`+${timestamp-first}ms`;default:return localTime(timestamp)}}function parseConsoleLogs(text){let parsed;try{parsed=JSON.parse(text)}catch{fail(EXIT.API_ERROR,"CONSOLE_LOGS_MALFORMED","The downloaded console logs are not valid JSON.",{hint:"Re-run with --raw to see what was downloaded."})}return(parsed===null||typeof parsed!="object"||!Array.isArray(parsed.invocationLogs))&&fail(EXIT.API_ERROR,"CONSOLE_LOGS_MALFORMED","The downloaded console logs are not in the expected format.",{hint:"Re-run with --raw to see what was downloaded."}),parsed}function parseLargeLogMessage(text){let parsed;try{parsed=JSON.parse(text)}catch{fail(EXIT.API_ERROR,"LARGE_MESSAGE_MALFORMED","The downloaded log message is not valid JSON.",{hint:"Re-run with --raw to see what was downloaded."})}return(parsed===null||typeof parsed!="object"||!Array.isArray(parsed.args))&&fail(EXIT.API_ERROR,"LARGE_MESSAGE_MALFORMED","The downloaded log message is not in the expected format.",{hint:"Re-run with --raw to see what was downloaded."}),parsed}function largeEntries(file2){return flatten(file2.invocationLogs).filter(entry2=>entry2.largePayload)}var import_picocolors7=__toESM(require_picocolors(),1);var INDENT2=" ",COLUMN_GAP=" ",NO_STATUS="\u2014",FAILED_STATUS="ERR";function statusText(entry2){let response=entry2.response;return response?.status!==void 0?String(response.status):response?.error?FAILED_STATUS:NO_STATUS}function statusColor(entry2){let status=entry2.response?.status;return status===void 0?entry2.response?.error?import_picocolors7.default.red:text=>text:status>=500?import_picocolors7.default.red:status>=400?import_picocolors7.default.yellow:import_picocolors7.default.green}function durationText(entry2){return entry2.duration===void 0?NO_STATUS:entry2.duration<1e3?`${entry2.duration} ms`:`${(entry2.duration/1e3).toFixed(1)} s`}function urlText(url2){return url2.replace(/^https?:\/\//,"")}function two2(value){return String(value).padStart(2,"0")}function localTime2(timestamp){let date5=new Date(timestamp);return`${two2(date5.getHours())}:${two2(date5.getMinutes())}:${two2(date5.getSeconds())}.${String(date5.getMilliseconds()).padStart(3,"0")}`}function stampOf2(time3,mode,first){let parsed=Date.parse(time3);switch(mode){case"off":return"";case"iso":return Number.isNaN(parsed)?time3:new Date(parsed).toISOString();case"relative":return Number.isNaN(parsed)?time3:`+${parsed-first}ms`;default:return Number.isNaN(parsed)?time3:localTime2(parsed)}}function headerPairs(headers){return headers?Array.isArray(headers)?headers:typeof headers!="object"?[]:Object.entries(headers):[]}function detailHalf(label,headers,body,error51,indent){let lines=[`${indent}${import_picocolors7.default.dim(label)}`];for(let[key,value]of headerPairs(headers))lines.push(`${indent}${INDENT2}${import_picocolors7.default.dim(`${key}:`)} ${value}`);if(error51&&lines.push(`${indent}${INDENT2}${import_picocolors7.default.red(`\u2716 ${error51}`)}`),body){for(let line of String(body.text??"").split(`
1317
+ `))lines.push(`${indent}${INDENT2}${line}`);body.truncated&&lines.push(`${indent}${INDENT2}${import_picocolors7.default.dim(`(truncated, ${body.size} bytes total)`)}`)}else error51||lines.push(`${indent}${INDENT2}${import_picocolors7.default.dim("(no body)")}`);return lines}function renderHttpLogs(entries,opts={}){let mode=opts.timestamps??"time",calls=[...entries].sort((a,b2)=>a.fetchId-b2.fetchId),lines=[],header=["HTTP calls",opts.invocationId,`${calls.length} ${calls.length===1?"call":"calls"}`].filter(Boolean).join(" \xB7 ");if(lines.push(import_picocolors7.default.bold(header)),calls.length===0)return lines.join(`
1318
+ `);lines.push("");let first=Math.min(...calls.map(entry2=>Date.parse(entry2.request.time)).filter(ms=>!Number.isNaN(ms))),rows2=calls.map(entry2=>({entry:entry2,stamp:stampOf2(entry2.request.time,mode,first),method:entry2.request.method.toUpperCase(),status:statusText(entry2),duration:durationText(entry2)})),stampWidth=Math.max(mode==="off"?0:4,...rows2.map(r=>r.stamp.length)),methodWidth=Math.max(6,...rows2.map(r=>r.method.length)),statusWidth=Math.max(6,...rows2.map(r=>r.status.length)),durationWidth=Math.max(8,...rows2.map(r=>r.duration.length)),headings=[...mode==="off"?[]:["TIME".padEnd(stampWidth)],"METHOD".padEnd(methodWidth),"STATUS".padEnd(statusWidth),"DURATION".padEnd(durationWidth),"URL"];lines.push(import_picocolors7.default.dim(headings.join(COLUMN_GAP)));for(let row of rows2){let line=[...mode==="off"?[]:[row.stamp.padEnd(stampWidth)],row.method.padEnd(methodWidth),statusColor(row.entry)(row.status.padEnd(statusWidth)),row.duration.padEnd(durationWidth),urlText(row.entry.request.url)].join(COLUMN_GAP),error51=row.entry.response?.error;error51&&(line+=` ${import_picocolors7.default.red(`\u2716 ${error51}`)}`),lines.push(line),opts.verbose&&lines.push(...detailHalf("request",row.entry.request.headers,row.entry.request.body,void 0,INDENT2),...detailHalf("response",row.entry.response?.headers,row.entry.response?.body,row.entry.response?.error,INDENT2))}return lines.join(`
1319
+ `)}function parseHttpLogs(text){let parsed;try{parsed=JSON.parse(text)}catch{fail(EXIT.API_ERROR,"HTTP_LOGS_MALFORMED","The downloaded HTTP logs are not valid JSON.",{hint:"Re-run with --raw to see what was downloaded."})}return Array.isArray(parsed)&&parsed.every(entry2=>{if(entry2===null||typeof entry2!="object")return!1;let request=entry2.request;if(request===null||typeof request!="object")return!1;let{url:url2,method}=request;return typeof url2=="string"&&typeof method=="string"})||fail(EXIT.API_ERROR,"HTTP_LOGS_MALFORMED","The downloaded HTTP logs are not in the expected format.",{hint:"Re-run with --raw to see what was downloaded."}),parsed}var MIN_PAGE_SIZE=1,PAGE_SIZE_CLAMP=200,MIN_INVOCATION_PAGE_SIZE=20;function relatedLabel(key){let stripped=key.slice(7);return stripped.charAt(0).toLowerCase()+stripped.slice(1)}function relatedValue(entity){let name=entity.name??entity.path??entity.version??entity.cronExpression??entity.uid;return entity.deleted?`${name} (deleted)`:name}function formatMetadata(metadata){if(!metadata)return"";try{let parsed=JSON.parse(metadata);return parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?Object.entries(parsed).map(([key,value])=>`${key}=${typeof value=="string"?value:JSON.stringify(value)}`).join("; "):String(parsed)}catch{return metadata}}function auditLogRow(entry2){let related=Object.entries(entry2).filter(([key,value])=>key.startsWith("related")&&key!=="relatedOrganization"&&value).map(([key,value])=>`${relatedLabel(key)}: ${relatedValue(value)}`).join(", "),actor=entry2.actor;return{date:entry2.date,action:entry2.action,actor:actor?`${actor.name??actor.uid} (${actor.uid})`:"",related,metadata:formatMetadata(entry2.metadata),actorIp:entry2.actorIp??""}}async function walkPages(walk2,emit2){let token=walk2.start;for(;;){let page=await walk2.fetch(token);if(emit2(page),token=walk2.tokenOf(page),!token)break;if(!walk2.paginate){isRaw()||prompts().note(`More results available \u2014 continue with: ${walk2.continuation(token)}`);break}if(!await prompts().confirm(`Fetched ${walk2.countOf(page)} ${walk2.noun} and more are available. Fetch the next page?`,!0))break}}async function fetchAuditLogs(client,teamId,opts,emit2){await walkPages({fetch:async cursor=>{let{data,response,error:error51}=await withSpinner("Fetching audit logs",()=>client.GET("/v1/team/{teamId}/auditLogs",{params:{path:{teamId},query:{...opts.pageSize!==void 0?{pageSize:opts.pageSize}:{},...cursor?{cursor}:{}}}}));return(!response.ok||!data)&&apiFail(response.status,error51),data},tokenOf:page=>page.cursor,countOf:page=>page.auditLogs.length,noun:"entries",continuation:cursor=>`${CLI} log list-audit-logs --team ${shellQuote(teamId)} --cursor ${cursor}`,paginate:opts.paginate,start:opts.cursor},emit2)}var EXECUTION_STATUSES=["QUEUED","RUNNING","FINISHED","ABORTED","TIMED_OUT","FUNCTION_ERROR","RUNTIME_ERROR","DENIED","DROPPED","MALFORMED_PAYLOAD_ERROR"],TRIGGER_TYPES=["EXTERNAL","MANUAL","SCHEDULED","MANUAL_EVENT_LISTENER","CHAINED"],ORDER_BY=["workspace","environment","duration","consoleLogs","httpLogs","startTime"],ORDER_DIRECTIONS=["asc","desc"],TEXT_COMPARATORS=["equals","contains"],COUNT_COMPARATORS=["gt","lt"],asChoices=values=>values.map(value=>({value,label:value}));function invocationLogRow(invocation){return{startTime:invocation.startTime,invocationId:invocation.invocationId,workspace:invocation.workspace.name,environment:invocation.environment.name,script:invocation.script.name,triggerType:invocation.triggerType,status:invocation.executionStatus,invocationType:invocation.invocationType??"",durationMs:invocation.executionDuration,consoleLogs:invocation.consoleLogsCount,httpLogs:invocation.httpLogsCount,queue:invocation.queueName??"",queuedAt:invocation.queuedAt??"",denialReason:invocation.denialReason??"",dropReason:invocation.dropReason??""}}var QUERY_FLAGS={pageSize:"--page-size",orderBy:"--order-by",orderByDirection:"--order-by-direction",from:"--from",to:"--to",workspaces:"-w",executionStatuses:"--execution-status",triggerTypes:"--trigger-type",invocationId:"--invocation-id",invocationIdComparator:"--invocation-id-comparator",environmentName:"--environment-name",environmentNameComparator:"--environment-name-comparator",scriptName:"--script-name",scriptNameComparator:"--script-name-comparator",duration:"--duration",durationComparator:"--duration-comparator",consoleLogsCount:"--console-logs-count",consoleLogsComparator:"--console-logs-comparator",httpLogsCount:"--http-logs-count",httpLogsComparator:"--http-logs-comparator"};function invocationContinuation(teamId,query){let parts=[`${CLI} log list-invocation-logs`,`--team ${shellQuote(teamId)}`];for(let[key,flag]of Object.entries(QUERY_FLAGS)){let value=query[key];if(value!==void 0)for(let single of Array.isArray(value)?value:[value])parts.push(`${flag} ${shellQuote(String(single))}`)}return parts.join(" ")}async function fetchInvocationLogs(client,teamId,opts,emit2){await walkPages({fetch:async nextToken=>{let{data,response,error:error51}=await withSpinner("Fetching invocation logs",()=>client.GET("/v1/team/{teamId}/invocationLogs",{params:{path:{teamId},query:{...opts.query,...nextToken?{nextToken}:{}}}}));return(!response.ok||!data)&&apiFail(response.status,error51),data},tokenOf:page=>page.nextToken,countOf:page=>page.invocations.length,noun:"invocations",continuation:nextToken=>`${invocationContinuation(teamId,opts.query)} --next-token ${nextToken}`,paginate:opts.paginate,start:opts.nextToken},emit2)}async function askEnvironmentName(client,teamId,workspaceId){let choices=await resolverChoices(client,"environment",{workspace:workspaceId});if(choices.length===0){prompts().note("\u26A0 No environments in this workspace \u2014 not filtering by environment.");return}let labels={},resolved=await resolveParams(["environment"],{team:teamId,workspace:workspaceId},{client,interactive:!0,labels,offerSession:!1}),picked=labels.environment;if(picked)return picked;let environmentId=resolved.environment??"",match=choices.find(c=>c.value===environmentId);if(match)return match.label;prompts().note(`\u2716 Environment '${environmentId}' is not in this workspace.`);let value=await prompts().select("Environment:",choices);return choices.find(c=>c.value===value)?.label??value}async function askInvocationFilters(client,teamId,query){let workspaceForEnvironment;if(query.workspaces===void 0){if(await prompts().confirm("Filter by workspace?",!1)){let workspaceId=(await resolveParams(["workspace"],{team:teamId},{client,interactive:!0,offerSession:!1})).workspace??"";query.workspaces=[workspaceId],workspaceForEnvironment=workspaceId}}else query.workspaces.length===1&&(workspaceForEnvironment=query.workspaces[0]);if(workspaceForEnvironment!==void 0&&query.environmentName===void 0&&await prompts().confirm("Filter by workspace environment?",!1)){let name=await askEnvironmentName(client,teamId,workspaceForEnvironment);name!==void 0&&(query.environmentName=name,query.environmentNameComparator="equals")}if(query.executionStatuses===void 0){let picked=await prompts().multiselect("Execution statuses to filter by: (space to pick, enter for no filter)",asChoices(EXECUTION_STATUSES));picked.length>0&&(query.executionStatuses=picked)}if(query.triggerTypes===void 0){let picked=await prompts().multiselect("Trigger types to filter by: (space to pick, enter for no filter)",asChoices(TRIGGER_TYPES));picked.length>0&&(query.triggerTypes=picked)}}var DOWNLOAD_HINT="Download URLs are short-lived \u2014 try again.",DOWNLOAD_TIMEOUT_MS=6e4;async function fetchFile(url2,spec){let started=Date.now(),ts=new Date(started).toISOString(),record4=extra=>recordApiCall({ts,ms:Date.now()-started,kind:"download",method:"GET",url:url2,attempt:0,reqBytes:0,resBytes:0,...extra}),response;try{response=await fetch(url2,{signal:AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)}),record4({status:response.status,resBytes:Number(response.headers.get("content-length")??0),resHeaders:pickHeaders(response.headers)})}catch(err){let message=err instanceof Error?err.message:String(err);record4({error:message}),fail(EXIT.API_ERROR,spec.code,`Downloading the ${spec.what} failed: ${message}`,{hint:DOWNLOAD_HINT})}return response.ok||(spec.onMissing&&(response.status===404||response.status===403)&&spec.onMissing(response.status),fail(EXIT.API_ERROR,spec.code,`Downloading the ${spec.what} failed with HTTP status ${response.status}.`,{status:response.status,hint:DOWNLOAD_HINT})),response.text()}async function downloadFile(url2,spec){return withSpinner(spec.label,()=>fetchFile(url2,spec))}async function fetchInvocationPayload(client,teamId,invocationId){let{data,response,error:error51}=await withSpinner("Fetching invocation payload URL",()=>client.GET("/v1/team/{teamId}/invocationPayload/{invocationId}",{params:{path:{teamId,invocationId}}}));return(!response.ok||!data)&&apiFail(response.status,error51),downloadFile(data.url,{label:"Downloading invocation payload",what:"invocation payload",code:"PAYLOAD_DOWNLOAD_FAILED"})}function formatPayload(text,raw=isRaw()){let trimmed=text.trim(),parsed;try{parsed=JSON.parse(trimmed)}catch{return raw?JSON.stringify(trimmed):trimmed}return raw?trimmed:JSON.stringify(parsed,null,2)}var PAYLOAD_TRIGGER_TYPES=["EXTERNAL","MANUAL","MANUAL_EVENT_LISTENER","CHAINED"];async function askInvocationId(){let typed=(await prompts().text("Invocation ID:")).trim();return typed||fail(EXIT.USAGE,"USAGE_ERROR","An invocation ID is required."),assertResourceId(typed,"invocationId")}var PICK_QUERY={pageSize:MIN_INVOCATION_PAGE_SIZE,orderBy:"startTime",orderByDirection:"desc"},PAYLOAD_PICK_QUERY={...PICK_QUERY,triggerTypes:[...PAYLOAD_TRIGGER_TYPES]},PICK_RECENT="recent",TYPE_ID="id";async function askInvocation(client,teamId,opts){if(await prompts().select("Which invocation?",[{value:PICK_RECENT,label:"Pick from the most recent invocations",hint:opts.browseHint},{value:TYPE_ID,label:"Enter an invocation ID",hint:"for anything older"}])===TYPE_ID)return{invocationId:await askInvocationId()};let query=opts.browseFilters?{...opts.query,...await opts.browseFilters()}:opts.query,{data,response,error:error51}=await withSpinner("Fetching invocation logs",()=>client.GET("/v1/team/{teamId}/invocationLogs",{params:{path:{teamId},query}}));(!response.ok||!data)&&apiFail(response.status,error51);let invocations=data.invocations;if(invocations.length===0)return prompts().note(`\u2716 ${opts.emptyNote}`),{invocationId:await askInvocationId()};let hint=opts.hint??(i=>`${i.triggerType} \xB7 ${i.executionStatus}`),choices=invocations.map(invocation=>({value:invocation.invocationId,label:`${pickerTime(invocation.startTime)} \xB7 ${invocation.workspace.name} (${invocation.environment.name}) \xB7 ${invocation.script.name}`,hint:hint(invocation)})),invocationId=await prompts().select("Invocation:",choices),picked=invocations.find(i=>i.invocationId===invocationId);return{invocationId,workspaceId:picked?.workspace.id,environmentId:picked?.environment.id,environmentName:picked?.environment.name,scriptId:picked?.script.id,scriptName:picked?.script.name,executionStatus:picked?.executionStatus}}async function fetchConsoleLogs(client,workspaceId,invocationId){let missingConsoleLogs=status=>fail(EXIT.NOT_FOUND,"NO_CONSOLE_LOGS",`No console logs found for invocation ${invocationId}.`,{status,hint:noConsoleLogsHint(invocationId)}),{data,response,error:error51}=await withSpinner("Fetching console logs URL",()=>client.GET("/v1/workspace/{workspaceId}/invocation/{invocationId}/consoleLogs",{params:{path:{workspaceId,invocationId}}}));return response.status===404&&missingConsoleLogs(404),(!response.ok||!data)&&apiFail(response.status,error51),downloadFile(data.url,{label:"Downloading console logs",what:"console logs",code:"CONSOLE_LOGS_DOWNLOAD_FAILED",onMissing:missingConsoleLogs})}function noConsoleLogsHint(invocationId){return`The file is written when the invocation ends, so the script may still be running. It is also never written for an invocation that was denied, dropped or stopped, and the IDs may be wrong or belong to another workspace. Check its status with: ${CLI} log list-invocation-logs --invocation-id ${invocationId}`}async function fetchHttpLogs(client,workspaceId,invocationId){let missingHttpLogs=status=>fail(EXIT.NOT_FOUND,"NO_HTTP_LOGS",`No HTTP logs found for invocation ${invocationId}.`,{status,hint:NO_HTTP_LOGS_HINT}),{data,response,error:error51}=await withSpinner("Fetching HTTP logs URL",()=>client.GET("/v1/workspace/{workspaceId}/invocation/{invocationId}/httpLogs",{params:{path:{workspaceId,invocationId}}}));return response.status===404&&missingHttpLogs(404),(!response.ok||!data)&&apiFail(response.status,error51),downloadFile(data.url,{label:"Downloading HTTP logs",what:"HTTP logs",code:"HTTP_LOGS_DOWNLOAD_FAILED",onMissing:missingHttpLogs})}var NO_HTTP_LOGS_HINT="Not every invocation records HTTP logs, and the file is only written once one ends \u2014 so the script may still be running, or may have recorded none. The IDs may also be wrong or belong to another workspace.",EXPAND_CONCURRENCY=4;async function expandLargeMessages(client,workspaceId,invocationId,file2){let pending=largeEntries(file2);pending.length!==0&&await withSpinner(`Downloading ${pending.length} large message${pending.length===1?"":"s"}`,async()=>{let queue=[...pending],workers=Array.from({length:Math.min(EXPAND_CONCURRENCY,queue.length)},async()=>{for(let entry2=queue.shift();entry2;entry2=queue.shift())await expandOne(client,workspaceId,invocationId,entry2)});await Promise.all(workers)})}async function expandOne(client,workspaceId,invocationId,entry2){try{let{data,response}=await client.GET("/v1/workspace/{workspaceId}/invocation/{invocationId}/largeLogMessage/{logMessageId}",{params:{path:{workspaceId,invocationId,logMessageId:entry2.id}}});if(!response.ok||!data)throw new Error(`HTTP ${response.status}`);let downloaded=await fetchFile(data.url,{label:"",what:"large log message",code:"LARGE_MESSAGE_DOWNLOAD_FAILED"});entry2.args=parseLargeLogMessage(downloaded).args,entry2.largePayload=!1}catch{entry2.expandFailed=!0}}async function fetchLargeLogMessage(client,workspaceId,invocationId,logMessageId){let missingMessage=status=>fail(EXIT.NOT_FOUND,"NO_LARGE_LOG_MESSAGE",`No large log message ${logMessageId} found for invocation ${invocationId}.`,{status,hint:NO_LARGE_MESSAGE_HINT}),{data,response,error:error51}=await withSpinner("Fetching log message URL",()=>client.GET("/v1/workspace/{workspaceId}/invocation/{invocationId}/largeLogMessage/{logMessageId}",{params:{path:{workspaceId,invocationId,logMessageId}}}));return response.status===404&&missingMessage(404),(!response.ok||!data)&&apiFail(response.status,error51),downloadFile(data.url,{label:"Downloading log message",what:"log message",code:"LARGE_MESSAGE_DOWNLOAD_FAILED",onMissing:missingMessage})}var NO_LARGE_MESSAGE_HINT="Only a message held separately has one \u2014 a message small enough to be inlined in the console logs was never stored separately, and the console shows the stored ones as \u201Cmessage too large to display\u201D. The IDs may also be wrong or belong to another workspace.";async function askLogMessageId(){let typed=(await prompts().text("Log message ID:")).trim();return typed||fail(EXIT.USAGE,"USAGE_ERROR","A log message ID is required."),assertResourceId(typed,"logMessageId")}var LOGGED_STATUSES=["FINISHED","ABORTED","TIMED_OUT","FUNCTION_ERROR","MALFORMED_PAYLOAD_ERROR"],CONSOLE_SCOPE={query:{consoleLogsCount:0,consoleLogsComparator:"gt",executionStatuses:[...LOGGED_STATUSES]},browseHint:`newest ${MIN_INVOCATION_PAGE_SIZE} with console output`,emptyNote:"No recent invocations with console output in this team \u2014 enter an invocation ID instead.",hint:invocation=>`${invocation.triggerType} \xB7 ${invocation.executionStatus} \xB7 ${invocation.consoleLogsCount} logs`,what:"console logs"},ABORTABLE_STATUSES=["QUEUED","RUNNING"],ABORT_SCOPE={query:{executionStatuses:[...ABORTABLE_STATUSES]},browseHint:`newest ${MIN_INVOCATION_PAGE_SIZE} that are still queued or running`,emptyNote:"Nothing is queued or running in this team right now \u2014 enter an invocation ID instead.",hint:invocation=>`${invocation.triggerType} \xB7 ${invocation.executionStatus}${invocation.queueName?` \xB7 queue: ${invocation.queueName}`:""}`,what:"the abort",workspaceRequired:"Aborting an invocation needs the workspace it belongs to."},HTTP_SCOPE={query:{httpLogsCount:0,httpLogsComparator:"gt",executionStatuses:[...LOGGED_STATUSES]},browseHint:`newest ${MIN_INVOCATION_PAGE_SIZE} with HTTP calls`,emptyNote:"No recent invocations with HTTP calls in this team \u2014 enter an invocation ID instead.",hint:invocation=>`${invocation.triggerType} \xB7 ${invocation.executionStatus} \xB7 ${invocation.httpLogsCount} HTTP calls`,what:"HTTP logs"};function pickerTime(startTime){let match=/^(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2})\.(\d+)(.*)$/.exec(startTime);if(!match)return startTime;let[,head,fraction,rest]=match;return`${head}.${(fraction??"").slice(0,3).padEnd(3,"0")}${rest??""}`}async function askScopeFilterChoice(what,sessionValue){let choices=[{value:"none",label:`No ${what} filter`,hint:"browse them all"},...sessionValue?[{value:"session",label:`Use the session default: ${sessionValue}`}]:[],{value:"pick",label:`Pick a ${what}`}];return await prompts().select(`Filter the list by ${what}?`,choices)}async function askBrowseScopeFilters(client,teamId,fixedWorkspaceId){let extra={},record4=sessionEnabled()?readSession():void 0,workspaceId=fixedWorkspaceId;if(!workspaceId){let answer2=await askScopeFilterChoice("workspace",record4?.workspace?describeValue(record4,"workspace"):void 0);if(answer2==="session")workspaceId=record4?.workspace;else if(answer2==="pick"){let choices=await resolverChoices(client,"workspace",{team:teamId});choices.length===0?prompts().note("\u26A0 No workspaces in this team \u2014 browsing without a workspace filter."):workspaceId=await prompts().select("Workspace:",choices)}workspaceId&&(extra.workspaces=[workspaceId])}if(!workspaceId)return extra;let answer=await askScopeFilterChoice("environment",record4?.environment?describeValue(record4,"environment"):void 0);if(answer==="session"){let name=await sessionEnvironmentName(client,teamId,record4,workspaceId);name&&(extra.environmentName=name,extra.environmentNameComparator="equals")}else if(answer==="pick"){let environments=await resolverChoices(client,"environment",{team:teamId,workspace:workspaceId});if(environments.length===0)prompts().note("\u26A0 No environments in this workspace \u2014 browsing without an environment filter.");else{let picked=await prompts().select("Environment:",environments);extra.environmentName=environments.find(c=>c.value===picked)?.label??picked,extra.environmentNameComparator="equals"}}return extra}async function sessionEnvironmentName(client,teamId,record4,workspaceId){let label=record4?.labels?.environment;if(label)return label;if(record4?.environment){let match=(await resolverChoices(client,"environment",{team:teamId,workspace:workspaceId})).find(c=>c.value===record4.environment);if(match)return match.label}prompts().note("\u26A0 Could not resolve the session environment's name \u2014 browsing without an environment filter.")}async function findInvocation(client,teamId,invocationId){let{data,response,error:error51}=await withSpinner("Fetching the invocation",()=>client.GET("/v1/team/{teamId}/invocationLogs",{params:{path:{teamId},query:{invocationId,invocationIdComparator:"equals",pageSize:MIN_INVOCATION_PAGE_SIZE}}}));return(!response.ok||!data)&&apiFail(response.status,error51),data.invocations.find(i=>i.invocationId===invocationId)}var INVOCATION_ID_FLAG="Invocation ID, the flag spelling of the positional argument (optional, exclusive with <invocationId>)";function invocationFromArgs(positional,flag){return positional!==void 0&&flag!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","<invocationId> and --invocation-id cannot be combined.",{hint:"They name the same value \u2014 pass one of them."}),positional??flag}async function resolveInvocationScope(client,invocationIdArg,opts,globalTeam,spec){let interactive=canPrompt(),team=opts.team??globalTeam,workspaceSource={},invocationId=invocationIdArg===void 0?void 0:assertResourceId(invocationIdArg,"invocationId"),workspaceId=opts.workspace,row={};if(!invocationId){interactive||fail(EXIT.USAGE,"USAGE_ERROR",`<invocationId> is required. ${supplyHint()}`);let teamId=(await resolveParams(["team"],{team},{client,interactive:!0,offerSession:!1})).team??"",picked=await askInvocation(client,teamId,{query:{...PICK_QUERY,...spec.query,...workspaceId?{workspaces:[workspaceId]}:{}},browseFilters:()=>askBrowseScopeFilters(client,teamId,workspaceId),browseHint:spec.browseHint,emptyNote:spec.emptyNote,hint:spec.hint});invocationId=picked.invocationId,workspaceId??=picked.workspaceId,row={environmentId:picked.environmentId,environmentName:picked.environmentName,scriptId:picked.scriptId,scriptName:picked.scriptName,executionStatus:picked.executionStatus}}return workspaceId||(workspaceId=(await resolveParams(["workspace"],{team},{client,interactive,offerSession:!1,sources:workspaceSource,missing:{workspace:`${spec.workspaceRequired??`A workspace is required to fetch ${spec.what}.`} ${supplyHint({pass:"Pass --workspace <id>"})}`}})).workspace??""),{...row,invocationId,workspaceId,workspaceFrom:workspaceSource.workspace}}async function withInheritedWorkspaceNote(scope2,run){try{return await run()}catch(error51){throw error51 instanceof CliError&&error51.exitCode===EXIT.NOT_FOUND&&warnInheritedWorkspace(scope2.workspaceFrom,scope2.workspaceId),error51}}function parsePageSize(value,min=MIN_PAGE_SIZE){if(value===void 0)return;let pageSize=Number(value);return(!Number.isInteger(pageSize)||pageSize<min)&&fail(EXIT.USAGE,"INVALID_PAGE_SIZE",min===MIN_PAGE_SIZE?"--page-size must be a whole number of at least 1.":`--page-size must be a whole number of at least ${min}.`),pageSize}function assertChoices(flag,values,allowed){if(values!==void 0)return values.map(value=>assertChoice(flag,value,allowed))}function assertInteger(flag,value){if(value===void 0)return;let parsed=Number(value);return Number.isInteger(parsed)||fail(EXIT.USAGE,"INVALID_NUMBER",`${flag} must be a whole number.`),parsed<0&&fail(EXIT.USAGE,"INVALID_NUMBER",`${flag} must be a whole number of 0 or more.`),parsed}function isoExample(hoursAgo){return new Date(Date.now()-hoursAgo*60*60*1e3).toISOString()}var API_TIMESTAMP=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?$/;function normalizeApiTimestamp(value){let match=API_TIMESTAMP.exec(value);if(!match)return value;let[,date5,time3,fraction]=match;return`${date5}T${time3}.${(fraction??"").slice(0,3).padEnd(3,"0")}Z`}function assertIsoTime(flag,value){if(value===void 0)return;let normalized=normalizeApiTimestamp(value.trim());return Number.isNaN(Date.parse(normalized))&&fail(EXIT.USAGE,"INVALID_TIME",`${flag} must be an ISO time (e.g. 2026-07-01T00:00:00.000Z) or a startTime as printed in the results (e.g. 2026-07-01 00:00:00.000000000).`),normalized}function parsedIsoTime(flag,value){let normalized=assertIsoTime(flag,value);return normalized===void 0?void 0:Date.parse(normalized)}var INVOCATION_SCOPE_RULE="Six verbs take an invocation ID and they do not all read it through the same scope: list-console-logs, list-http-logs, get-large-log-message and script abort-invocation address an invocation through its workspace, while get-invocation-payload and script replay-invocation address it through a team.",AUDIT_DOC=defineCommandDoc("log list-audit-logs",{rules:["The team is --team; audit logs are team-scoped and there is no positional argument.","--page-size defaults to 200 and is clamped there: a bigger number is accepted and answered with 200, and anything under 1 is exit 2 before a request is made.","--cursor continues a listing, and is what the previous page reported."],notes:["One page per run. The document carries the cursor for the next page; piped human mode prints the continuation command on stderr.","Under --raw each page is its own document, which is the one case where a run answered by a human emits more than one.","Read this one with --raw. The human table is wider than a terminal once metadata is populated."]}),INVOCATION_DOC=defineCommandDoc("log list-invocation-logs",{rules:["The team is --team; -w narrows a team-scoped listing to one or more workspaces and repeats, or takes a comma-separated list.","--execution-status: QUEUED, RUNNING, FINISHED, ABORTED, TIMED_OUT, FUNCTION_ERROR, RUNTIME_ERROR, DENIED, DROPPED, MALFORMED_PAYLOAD_ERROR. Repeats.","--trigger-type: EXTERNAL, MANUAL, SCHEDULED, MANUAL_EVENT_LISTENER, CHAINED. Repeats.","--environment-name filters by name rather than by ID: send the label the environment list reports, not its ID.","--script-name and --invocation-id are the other two text filters, and each of the three takes a comparator beside it: --environment-name-comparator, --script-name-comparator and --invocation-id-comparator, each equals (the API default) or contains.","--duration is milliseconds, --console-logs-count and --http-logs-count are entry counts, and each takes a comparator beside it: --duration-comparator, --console-logs-comparator and --http-logs-comparator, each gt (the API default) or lt.","--from and --to accept an ISO time or a startTime exactly as printed in the results, which is why the table prints the API's own nine-digit form rather than a tidier one: a cell copied out of it is a value these two flags take back.","--order-by: workspace, environment, duration, consoleLogs, httpLogs, startTime; --order-by-direction is asc (the API default) or desc.","--page-size refuses anything under 20 here, unlike list-audit-logs, and --next-token continues a listing; pair it with the same filters."],notes:["The human table carries why a run did not happen: DENIAL_REASON for one that was refused, DROP_REASON for one an event queue evicted. Both are blank for everything else.","INVOCATION_TYPE is what opened the record and is narrower than the status: it tells a malformed incoming payload (MALFORMED_PAYLOAD_EVENT) from a malformed script response (MALFORMED_RESPONSE_EVENT), which both end as MALFORMED_PAYLOAD_ERROR. The others are QUEUED, DROPPED, INVOCATION_START, INVOCATION_FINISH, INVOCATION_DENIED and INVOCATION_DISABLED. It is blank for a record with no opening event, and a value outside that list is printed as stored rather than refused.","The index is eventually consistent. An invocation that has just finished can be missing from a narrowed query for a few seconds while the unfiltered listing already carries it, so a filter that comes back empty right after a trigger is not proof of anything: widen it, or retry.","This is where a replayable invocation is found: only EXTERNAL, MANUAL_EVENT_LISTENER and CHAINED runs can be replayed, and its environmentId and scriptId are what script replay-invocation must be given.","Read this one with --raw, unlike list-console-logs and list-http-logs. The human table prints the environment and the script by name, and their IDs are what the next call takes."]}),PAYLOAD_DOC=defineCommandDoc("log get-invocation-payload",{rules:["The invocation is the positional argument or --invocation-id, and the team is --team: the payload is read through a team route, not a workspace one. Passing both spellings of the invocation is exit 2.",INVOCATION_SCOPE_RULE],notes:["The incoming event of a single invocation, printed as stored. Under --raw a payload that is not JSON is emitted as a JSON string.","Scheduled runs have no payload."]}),CONSOLE_DOC=defineCommandDoc("log list-console-logs",{rules:["The invocation is the positional argument or --invocation-id, and the workspace is -w. Passing both spellings of the invocation is exit 2.",INVOCATION_SCOPE_RULE,"--timestamps is time, iso, relative or off, and is ignored with --raw, which prints the stored file as it is.","--expand-large fetches the messages stored separately and prints them in place. Refused with --raw (exit 2): the file would no longer be the file."],notes:["The file exists only once the invocation has ended, and never for one that was denied or dropped. Exit 4 NO_CONSOLE_LOGS therefore also means still running, which makes this the way to poll a trigger to completion.","A message too large to be stored inline shows as a placeholder carrying the get-large-log-message command that fetches it.","Worth reading without --raw, and the reason is size rather than taste: the rendering is time, severity and message with objects pretty-printed, around 40% of the stored file, which wraps every argument as {values:[{type,value}]} and costs six lines of JSON for a one-word log line. Reach for --raw to count entries, to read seq, or to keep the file byte-exact."]}),HTTP_DOC=defineCommandDoc("log list-http-logs",{rules:["The invocation is the positional argument or --invocation-id, and the workspace is -w. Passing both spellings of the invocation is exit 2.",INVOCATION_SCOPE_RULE,"--verbose adds headers and bodies per call, and is refused with --raw (exit 2).","--timestamps is time, iso, relative or off, and is ignored with --raw, which prints the stored file as it is."],notes:["Not every invocation records HTTP logs. One that made no calls answers an empty array and exit 0, so this is never a way to tell whether a run has finished.","Exit 4 NO_HTTP_LOGS is the stored file being unreadable, not a run with nothing to report.","Bodies are truncated by the runtime before storage, so a body that reads short may not have been.","Worth reading without --raw for the same reason as list-console-logs: the table is time, method, status, duration and URL, an order of magnitude smaller than the stored file, and --verbose adds the headers and bodies and is smaller still. --raw is the file byte-exact, which is what to redirect."]}),LARGE_MESSAGE_DOC=defineCommandDoc("log get-large-log-message",{rules:["The message ID is the second positional argument, exactly as printed in the console-log placeholder; the invocation is the first, or --invocation-id, and the workspace is -w.",INVOCATION_SCOPE_RULE,"--timestamps is time, iso, relative or off, and is ignored with --raw, which prints the stored bytes as they are."],notes:["A message small enough to be inlined has no separate copy, so only an ID a placeholder named resolves here."]});function logsCommand(){let logs=new Command("log").description("Read logs");return logs.command("list-audit-logs").description("List audit logs (paginated)").option("--team <teamId>",SCOPE_TEAM).option("--page-size <n>",`Results per page, at least ${MIN_PAGE_SIZE} and clamped to ${PAGE_SIZE_CLAMP} above that (optional, API default: 200)`).option("--cursor <cursor>","Continue from the cursor returned by an earlier page (optional)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,AUDIT_DOC))return;let globals=cmd.optsWithGlobals(),pageSize=parsePageSize(opts.pageSize),client=await apiClient(globals.instance),teamId=(await resolveParams(["team"],{team:opts.team??globals.team},{client,interactive:canPrompt()})).team??"",interactive=canPrompt();interactive&&await askOutputCopy(),await fetchAuditLogs(client,teamId,{pageSize,cursor:opts.cursor,paginate:interactive},page=>{ok(page,{human:p=>({auditLogs:p.auditLogs.map(auditLogRow)})})})}),logs.command("list-invocation-logs").description("List script invocation logs (paginated, filterable)").option("--team <teamId>",SCOPE_TEAM).option("-w, --workspace <workspaceId>","Filter by workspace ID, or comma-separated (optional, interactive, session default, env SR_CONNECT_CLI_WORKSPACE, repeatable)",collect).option("--execution-status <status>",`Filter by execution status: ${EXECUTION_STATUSES.join(", ")} (optional, interactive, repeatable)`,collect).option("--trigger-type <type>",`Filter by trigger type: ${TRIGGER_TYPES.join(", ")} (optional, interactive, repeatable)`,collect).option("--environment-name <name>","Filter by environment name (optional, interactive when a workspace filter is in play)").option("--environment-name-comparator <how>",`How to compare the environment name: ${TEXT_COMPARATORS.join(" | ")} (optional, API default: equals, ignored when the environment is picked)`).option("--script-name <name>","Filter by script name (optional)").option("--script-name-comparator <how>",`How to compare the script name: ${TEXT_COMPARATORS.join(" | ")} (optional, API default: equals)`).option("--invocation-id <id>","Filter by invocation ID (optional)").option("--invocation-id-comparator <how>",`How to compare the invocation ID: ${TEXT_COMPARATORS.join(" | ")} (optional, API default: equals)`).option("--from <iso>",`Include invocations from the specified ISO time onwards, e.g. ${isoExample(24)} (optional)`).option("--to <iso>",`Include invocations up to the specified ISO time, e.g. ${isoExample(0)} (optional)`).option("--duration <ms>","Filter by execution duration in milliseconds (optional)").option("--duration-comparator <how>",`How to apply --duration: ${COUNT_COMPARATORS.join(" | ")} (optional, API default: gt)`).option("--console-logs-count <n>","Filter by number of console log entries (optional)").option("--console-logs-comparator <how>",`How to apply --console-logs-count: ${COUNT_COMPARATORS.join(" | ")} (optional, API default: gt)`).option("--http-logs-count <n>","Filter by number of HTTP log entries (optional)").option("--http-logs-comparator <how>",`How to apply --http-logs-count: ${COUNT_COMPARATORS.join(" | ")} (optional, API default: gt)`).option("--order-by <field>",`Order by: ${ORDER_BY.join(" | ")} (optional)`).option("--order-by-direction <dir>",`Order direction: ${ORDER_DIRECTIONS.join(" | ")} (optional, API default: asc)`).option("--page-size <n>",`Results per page, at least ${MIN_INVOCATION_PAGE_SIZE} and clamped to ${PAGE_SIZE_CLAMP} above that (optional, API default: 200)`).option("--next-token <token>","Continue from the nextToken returned by an earlier page; pair it with the same filters (optional)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,INVOCATION_DOC))return;let globals=cmd.optsWithGlobals(),query={pageSize:parsePageSize(opts.pageSize,MIN_INVOCATION_PAGE_SIZE),orderBy:assertChoice("--order-by",opts.orderBy,ORDER_BY),orderByDirection:assertChoice("--order-by-direction",opts.orderByDirection,ORDER_DIRECTIONS),from:assertIsoTime("--from",opts.from),to:assertIsoTime("--to",opts.to),workspaces:(opts.workspace??(globals.workspace?[globals.workspace]:void 0))?.map(id=>assertResourceId(id,"-w, --workspace")),executionStatuses:assertChoices("--execution-status",opts.executionStatus,EXECUTION_STATUSES),triggerTypes:assertChoices("--trigger-type",opts.triggerType,TRIGGER_TYPES),invocationId:opts.invocationId,invocationIdComparator:assertChoice("--invocation-id-comparator",opts.invocationIdComparator,TEXT_COMPARATORS),environmentName:opts.environmentName,environmentNameComparator:assertChoice("--environment-name-comparator",opts.environmentNameComparator,TEXT_COMPARATORS),scriptName:opts.scriptName,scriptNameComparator:assertChoice("--script-name-comparator",opts.scriptNameComparator,TEXT_COMPARATORS),duration:assertInteger("--duration",opts.duration),durationComparator:assertChoice("--duration-comparator",opts.durationComparator,COUNT_COMPARATORS),consoleLogsCount:assertInteger("--console-logs-count",opts.consoleLogsCount),consoleLogsComparator:assertChoice("--console-logs-comparator",opts.consoleLogsComparator,COUNT_COMPARATORS),httpLogsCount:assertInteger("--http-logs-count",opts.httpLogsCount),httpLogsComparator:assertChoice("--http-logs-comparator",opts.httpLogsComparator,COUNT_COMPARATORS)},client=await apiClient(globals.instance),teamId=(await resolveParams(["team"],{team:opts.team??globals.team},{client,interactive:canPrompt(),offerSession:!1})).team??"",interactive=canPrompt();interactive&&await askInvocationFilters(client,teamId,query),interactive&&await askOutputCopy(),await fetchInvocationLogs(client,teamId,{query,nextToken:opts.nextToken,paginate:interactive},page=>{ok(page,{human:p=>({invocations:p.invocations.map(invocationLogRow)})})})}),logs.command("get-invocation-payload").description("Fetch the payload (the incoming event) of a script invocation").argument("[invocationId]","Invocation ID (required unless --invocation-id, interactive)").option("--invocation-id <invocationId>",INVOCATION_ID_FLAG).option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(invocationIdArg,opts,cmd)=>{if(explained(cmd,PAYLOAD_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),typedInvocation=invocationFromArgs(invocationIdArg,opts.invocationId),teamId=(await resolveParams(["team"],{team:opts.team??globals.team},{client,interactive:canPrompt(),offerSession:!1})).team??"",interactive=canPrompt(),invocationId=typedInvocation===void 0?void 0:assertResourceId(typedInvocation,"invocationId");invocationId||(interactive||fail(EXIT.USAGE,"USAGE_ERROR",`<invocationId> is required. ${supplyHint()}`),invocationId=(await askInvocation(client,teamId,{query:PAYLOAD_PICK_QUERY,browseHint:`newest ${MIN_INVOCATION_PAGE_SIZE} with a payload`,emptyNote:"No recent invocations with a payload in this team \u2014 enter an invocation ID instead."})).invocationId),interactive&&await askOutputCopy(),okText(formatPayload(await fetchInvocationPayload(client,teamId,invocationId)))}),logs.command("list-console-logs").description("List the console output (console.log/warn/error) of a script invocation").argument("[invocationId]","Invocation ID (required unless --invocation-id, interactive)").option("--invocation-id <invocationId>",INVOCATION_ID_FLAG).option("-w, --workspace <workspaceId>","Workspace the invocation belongs to (required unless the invocation is browsed, interactive, session default, env SR_CONNECT_CLI_WORKSPACE)").option("--team <teamId>","Team ID \u2014 only needed to browse invocations or pick a workspace (optional, interactive, session default, env SR_CONNECT_CLI_TEAM, ignored when the invocation and workspace are both given)").option("--expand-large","Also download large messages stored separately (optional, refused with --raw)").option("--timestamps <mode>",`Timestamp gutter: ${TIMESTAMP_MODES.join(" | ")} (optional, default: time, ignored with --raw)`).option("--explain",EXPLAIN).action(async(invocationIdArg,opts,cmd)=>{if(explained(cmd,CONSOLE_DOC))return;let globals=cmd.optsWithGlobals(),timestamps=assertChoice("--timestamps",opts.timestamps,TIMESTAMP_MODES)??"time";opts.expandLarge&&isRaw()&&fail(EXIT.USAGE,"USAGE_ERROR","--expand-large cannot be combined with --raw.");let client=await apiClient(globals.instance),{invocationId,workspaceId,workspaceFrom}=await resolveInvocationScope(client,invocationFromArgs(invocationIdArg,opts.invocationId),opts,globals.team,CONSOLE_SCOPE);canPrompt()&&await askOutputCopy();let text=await withInheritedWorkspaceNote({workspaceId,workspaceFrom},()=>fetchConsoleLogs(client,workspaceId,invocationId));if(isRaw()){okFile(text);return}let file2=parseConsoleLogs(text);opts.expandLarge&&await expandLargeMessages(client,workspaceId,invocationId,file2),okText(renderConsoleLogs(file2,{invocationId,workspaceId,timestamps}))}),logs.command("list-http-logs").description("List the HTTP calls a script invocation made").argument("[invocationId]","Invocation ID (required unless --invocation-id, interactive)").option("--invocation-id <invocationId>",INVOCATION_ID_FLAG).option("-w, --workspace <workspaceId>","Workspace the invocation belongs to (required unless the invocation is browsed, interactive, session default, env SR_CONNECT_CLI_WORKSPACE)").option("--team <teamId>","Team ID \u2014 only needed to browse invocations or pick a workspace (optional, interactive, session default, env SR_CONNECT_CLI_TEAM, ignored when the invocation and workspace are both given)").option("--verbose","Also print request/response headers and bodies per call (optional, refused with --raw)").option("--timestamps <mode>",`Timestamp gutter: ${TIMESTAMP_MODES.join(" | ")} (optional, default: time, ignored with --raw)`).option("--explain",EXPLAIN).action(async(invocationIdArg,opts,cmd)=>{if(explained(cmd,HTTP_DOC))return;let globals=cmd.optsWithGlobals(),timestamps=assertChoice("--timestamps",opts.timestamps,TIMESTAMP_MODES)??"time";opts.verbose&&isRaw()&&fail(EXIT.USAGE,"USAGE_ERROR","--verbose cannot be combined with --raw.");let client=await apiClient(globals.instance),{invocationId,workspaceId,workspaceFrom}=await resolveInvocationScope(client,invocationFromArgs(invocationIdArg,opts.invocationId),opts,globals.team,HTTP_SCOPE);canPrompt()&&await askOutputCopy();let text=await withInheritedWorkspaceNote({workspaceId,workspaceFrom},()=>fetchHttpLogs(client,workspaceId,invocationId));if(isRaw()){okFile(text);return}okText(renderHttpLogs(parseHttpLogs(text),{invocationId,timestamps,verbose:opts.verbose}))}),logs.command("get-large-log-message").description("Fetch a single console log too large to be stored with the rest").argument("[invocationId]","Invocation ID (required unless --invocation-id, interactive)").option("--invocation-id <invocationId>",INVOCATION_ID_FLAG).argument("[logMessageId]","Log message ID, as printed by list-console-logs (required, interactive)").option("-w, --workspace <workspaceId>","Workspace the invocation belongs to (required unless the invocation is browsed, interactive, session default, env SR_CONNECT_CLI_WORKSPACE)").option("--team <teamId>","Team ID \u2014 only needed to browse invocations or pick a workspace (optional, interactive, session default, env SR_CONNECT_CLI_TEAM, ignored when the invocation and workspace are both given)").option("--timestamps <mode>",`Timestamp gutter: ${TIMESTAMP_MODES.join(" | ")} (optional, default: time, ignored with --raw)`).option("--explain",EXPLAIN).action(async(invocationIdArg,logMessageIdArg,opts,cmd)=>{if(explained(cmd,LARGE_MESSAGE_DOC))return;let globals=cmd.optsWithGlobals(),timestamps=assertChoice("--timestamps",opts.timestamps,TIMESTAMP_MODES)??"time",client=await apiClient(globals.instance),{invocationId,workspaceId,workspaceFrom}=await resolveInvocationScope(client,invocationFromArgs(invocationIdArg,opts.invocationId),opts,globals.team,CONSOLE_SCOPE),logMessageId=logMessageIdArg===void 0?void 0:assertResourceId(logMessageIdArg,"logMessageId");logMessageId||(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<logMessageId> is required. ${supplyHint()}`),logMessageId=await askLogMessageId()),canPrompt()&&await askOutputCopy();let text=await withInheritedWorkspaceNote({workspaceId,workspaceFrom},()=>fetchLargeLogMessage(client,workspaceId,invocationId,logMessageId));if(isRaw()){okFile(text);return}let entry2=parseLargeLogMessage(text);okText(renderConsoleLogs({invocationLogs:[entry2]},{invocationId,workspaceId,timestamps,heading:`Log message \xB7 ${logMessageId} \xB7 invocation ${invocationId}`}))}),logs}function apiCallRow(call,instanceBase){return{time:call.ts.slice(11,23),method:call.method,path:pathOf2(call.url,instanceBase),status:call.status??"",ms:call.ms,attempt:call.attempt,error:call.error??errorMessageOf(call.resBody)??""}}function pathOf2(url2,instanceBase){if(instanceBase!==void 0&&url2.startsWith(instanceBase)){let remainder=url2.slice(instanceBase.length);if(remainder===""||remainder.startsWith("/")||remainder.startsWith("?"))return remainder||"/"}return url2}function errorMessageOf(body){if(body)try{let message=JSON.parse(body)?.errorMessage;return typeof message=="string"?message:void 0}catch{return}}var DEFAULT_RECORDED_LIMIT=20;function parseLimit(value){if(value===void 0)return DEFAULT_RECORDED_LIMIT;let limit=Number(value);return(!Number.isInteger(limit)||limit<0)&&fail(EXIT.USAGE,"INVALID_LIMIT","--limit must be a whole number (0 for no limit)."),limit}function filterApiCalls(runs,opts){let since=parsedIsoTime("--since",opts.since),to=parsedIsoTime("--to",opts.to),statuses=opts.status?.map(value=>{let status=Number(value);return Number.isInteger(status)||fail(EXIT.USAGE,"INVALID_STATUS","--status must be a whole number, e.g. 404."),status}),method=opts.method?.toUpperCase(),matches=call=>{let at2=Date.parse(call.ts);return!(since!==void 0&&at2<since||to!==void 0&&at2>to||opts.failedOnly&&call.error===void 0&&(call.status??0)<400||statuses&&!statuses.includes(call.status??-1)||method&&call.method.toUpperCase()!==method||opts.path&&!call.url.includes(opts.path))};return runs.map(run=>({...run,calls:run.calls.filter(matches)})).filter(run=>run.calls.length>0)}function runDuration(run){let first=run.calls[0],last=run.calls.at(-1);return!first||!last?"0s":`${((Date.parse(last.ts)+last.ms-Date.parse(first.ts))/1e3).toFixed(1)}s`}function renderApiCallRuns(runs,showSession=!1){return runs.length===0?import_picocolors8.default.dim("(no results)"):runs.map(run=>{let command=run.argv.length>0?run.argv.map(shellQuote).join(" "):"(unknown command)",shown=run.calls.length,counted=shown===run.totalCalls?`${shown} call${shown===1?"":"s"}`:`${shown} of ${run.totalCalls} calls`,failed2=run.calls.filter(call=>call.error!==void 0||(call.status??0)>=400).length,facts=[...showSession&&run.session?[run.session]:[],...run.instance?[run.instance]:[],`pid ${run.pid}`,counted,...failed2>0?[import_picocolors8.default.red(`${failed2} failed`)]:[],runDuration(run)],instanceBase=instanceBaseUrl(run.instance),table2=renderTable(run.calls.map(call=>apiCallRow(call,instanceBase))).split(`
1320
+ `).map(line=>` ${line}`).join(`
1321
+ `);return`${import_picocolors8.default.bold(import_picocolors8.default.cyan(`\u25B8 ${run.ts} ${command}`))}
1322
+ ${import_picocolors8.default.dim(` ${facts.join(" \xB7 ")}`)}
1323
+ ${table2}`}).join(`
1324
+
1325
+ `)}function noteWhyEmpty(opts){let recorded=listRecordedSessions();if(recorded.length===0){prompts().note("No API calls recorded yet \u2014 recording is on unless --no-record-api-calls or SR_CONNECT_CLI_NO_RECORD_API_CALLS turned it off, and a run that reaches no API records nothing.");return}opts.allSessions||filterApiCalls(readApiCalls({allSessions:!0}),opts).length>0&&prompts().note(`Nothing recorded for this shell session, but ${recorded.length} other session${recorded.length===1?" has":"s have"} calls \u2014 try --all-sessions.`)}function crashRow(report){return{id:report.id,created:report.createdAt,command:report.command,kind:crashTitle(report),size:formatBytes(report.bytes)}}function settingRow(state){return{setting:state.label,status:state.enabled?"on":"off",source:sourceLabel2(state),flag:state.flag}}function sourceLabel2(state){return state.source==="env"?`env ${state.envVar}`:state.source==="flag"?`flag ${state.flag}`:state.source}function settingsUnchanged(before,values){let wasOff=before.filter(state=>state.stored===!1).map(state=>state.key),nowOff=SETTING_KEYS.filter(key=>!values[key]||envDisabled(key));return wasOff.length===nowOff.length&&wasOff.every(key=>nowOff.includes(key))}async function askSettings(){let states=settingStates(),choices=states.map(state=>({value:state.key,label:state.label,hint:state.envDisabled?`off \u2014 ${state.envVar} is set in this environment`:state.hint,...state.envDisabled?{disabled:!0}:{}})),initial=states.filter(state=>!state.envDisabled&&state.stored!==!1).map(state=>state.key),picked=await prompts().multiselect("CLI settings:",choices,{initial});return SETTING_KEYS.filter(key=>picked.includes(key))}function noteKeptLocks(keptLocks){if(keptLocks.length===0)return;let lines=keptLocks.map(lock=>` ${lockReleaseCommand(lock)}`);warnLine(`\u26A0 ${keptLocks.length===1?"One workspace lock is":`${keptLocks.length} workspace locks are`} still held and kept in the record \u2014 writes from this shell go on reusing ${keptLocks.length===1?"it":"them"}.
1326
+ Give ${keptLocks.length===1?"it":"them"} back early with:
1327
+ ${lines.join(`
1328
+ `)}`)}var GET_README_DOC=defineCommandDoc("cli get-readme",{rules:["No parameters: it prints the README of the installed package."],notes:["Rendered for the terminal in human mode, the markdown source under --raw.","Needs no credentials and no instance, like every verb in this group but set-session.","It is orientation, not per-verb reference: what a verb takes is --explain on that verb."]}),SETTINGS_DOC=defineCommandDoc("cli settings",{rules:["No parameters: there is no flag that sets a switch, and a scripted run is read-only."],notes:["The five stored switches with their current state and which source decided it: flag, env, stored or default.","On a terminal without --raw, one multiselect changes them. Under --raw the command is read-only \u2014 the one place --raw suppresses a question, because there the table is the answer a scripted run wants.","Only the offs are stored, in a file that survives cli clear-session and auth logout. A switch disabled by its environment variable cannot be toggled and is written as off.","Answers that change nothing make no request at all \u2014 this verb never makes one."]}),SET_SESSION_DOC=defineCommandDoc("cli set-session",{rules:["The team is --team, the workspace -w and the environment -e. They carry no session default here, this verb being the save flow itself, though the scope environment variables still pre-fill."],notes:["Remembers all three as this shell's defaults, for 12 hours and for one instance.","A typed -e is checked against the workspace first, one request, and an environment belonging to another workspace is exit 2 ENVIRONMENT_MISMATCH \u2014 the pair would otherwise be stored and fail every command that read it.",`The document carries the three IDs and a labels object holding each one's name, which the checks above already read; every later command's "Using session defaults: \u2026" line reads those names, so a record written here announces itself the same way a picked one does.`,"Where the shell cannot be identified, in a container step for example, set SR_CONNECT_CLI_SESSION_ID."]}),CLEAR_SESSION_DOC=defineCommandDoc("cli clear-session",{rules:["--all forgets every shell's record rather than this one's."],notes:["A workspace lock rides the same record but is not a default, so clearing the scope keeps it: a clear that leaves one names the lock and the command that gives it back."]}),LIST_API_LOGS_DOC=defineCommandDoc("cli list-api-logs",{rules:["--limit counts runs rather than calls, default 20, 0 for all; a run is never cut in half.","--session reads another shell's recording, --all-sessions reads them all, and --list-sessions lists the recorded shells instead and ignores every filter.","--since and --to take an ISO instant or a startTime exactly as printed in log results.","--status repeats, and filters by the HTTP status the call answered with.","--method filters by HTTP method and --path by a substring of the URL; --failed-only keeps the calls that answered 400 or above and the ones that never answered at all. All three are ignored with --list-sessions, as every filter here is."],notes:["Runs of this shell, newest first, each with its calls. Needs no credentials, which is what makes it readable when authentication is the thing that broke.","Secrets are redacted at record time, so what is stored is what is printed."]}),CLEAR_API_LOGS_DOC=defineCommandDoc("cli clear-api-logs",{rules:["--session names another shell's recording to delete, spelled as cli list-api-logs --list-sessions reports it; omitted, this shell's own is the one cleared.","--all-sessions deletes every shell's recording rather than this one's."],notes:["Recording is on unless --no-record-api-calls or the stored switch turns it off; deleting does not turn it off."]}),LIST_CRASH_REPORTS_DOC=defineCommandDoc("cli list-crash-reports",{rules:["No parameters: it lists what is stored."],notes:["Newest first: the run ID, when, the command, the kind and the size.","The store keeps 7 days and the newest 20, pruned on write."]}),GET_CRASH_REPORT_DOC=defineCommandDoc("cli get-crash-report",{rules:["--report names a report by its run ID; omitted, the newest is read.","--content-only prints the markdown verbatim, identically in both modes."],notes:["A report carries the metadata, the stack and the API calls that run recorded, composed against a 512 KB budget."]}),CLEAR_CRASH_REPORTS_DOC=defineCommandDoc("cli clear-crash-reports",{rules:["--report deletes a single report by its run ID; omitted, every stored report goes."],notes:["A report is deleted on a successful feedback post-crash-report too, unless --keep."]});function cliCommand(){let cli=new Command("cli").description("Operations related to the CLI");return cli.command("get-readme").description("Print the CLI's own README").option("--explain",EXPLAIN).action((_opts,cmd)=>{if(explained(cmd,GET_README_DOC))return;let source=selfReadme();source===void 0&&fail(EXIT.NOT_FOUND,"README_UNAVAILABLE","This build does not carry its README.",{hint:`Read it at https://www.npmjs.com/package/${PACKAGE}.`}),isRaw()?okFile(source):okText(renderMarkdown(source))}),cli.command("settings").description("View or change the CLI's own switches").option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,SETTINGS_DOC))return;let globals=cmd.optsWithGlobals(),flagOff={recordApiCalls:globals.recordApiCalls===!1,workspaceLock:globals.lock===!1,localSync:globals.localSync===!1,crashReports:globals.crashReports===!1,agenticFeedback:globals.agenticFeedback===!1};if(!canPrompt()||isRaw()){let states=settingStates(flagOff);ok(states,{human:rows2=>renderTable(rows2.map(settingRow))});return}let before=settingStates(),chosen=new Set(await askSettings()),values=Object.fromEntries(SETTING_KEYS.map(key=>[key,chosen.has(key)]));if(settingsUnchanged(before,values)){prompts().note("Settings unchanged.");return}let forced;try{forced=writeSettings(values)}catch(err){fail(EXIT.API_ERROR,"SETTINGS_WRITE_FAILED",`Could not store the settings: ${describeError(err)}`,{hint:`The file is ${settingsFile()}.`})}for(let key of forced){let state=before.find(candidate=>candidate.key===key);state&&warnLine(`\u26A0 ${state.label} is off because ${state.envVar} is set \u2014 stored as off too.`)}let after=settingStates();okMutation("Settings updated",after,renderTable(after.map(settingRow)))}),cli.command("set-session").description("Remember team/workspace/environment as defaults for this shell session").option("--team <teamId>","Team ID (required, interactive, env SR_CONNECT_CLI_TEAM)").option("-w, --workspace <workspaceId>","Workspace ID (required, interactive, env SR_CONNECT_CLI_WORKSPACE)").option("-e, --env <environmentId>","Environment ID (required, interactive, env SR_CONNECT_CLI_ENVIRONMENT)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,SET_SESSION_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),labels={},sources={},resolved=await resolveParams(["team","workspace","environment"],{team:opts.team,workspace:opts.workspace,environment:opts.env},{client,interactive:canPrompt(),labels,sources,offerSession:!1,useSession:!1,sessionSkipped:"save-flow"}),teamId=resolved.team??"",workspaceId=resolved.workspace??"",environmentId=resolved.environment??"";if(sources.team!=="picker"||sources.workspace!=="picker"){let{data,response,error:error51}=await withSpinner("Checking the workspace",()=>client.GET("/v1/team/{teamId}/workspace/{workspaceId}",{params:{path:{teamId,workspaceId}}}));response.ok||apiFail(response.status,error51),data?.name&&(labels.workspace=data.name)}if(sources.environment!=="picker"){let{environments}=await withSpinner("Checking the environment",()=>fetchEnvironments(client,workspaceId)),named=environments.find(e=>e.id===environmentId);named?.name&&(labels.environment=named.name),named||fail(EXIT.USAGE,"ENVIRONMENT_MISMATCH",`Environment ${environmentId} is not an environment of workspace ${workspaceId}, so storing the pair would fail every command that read it.`,{hint:`List the workspace's own environments with \`${CLI} environment list -w ${workspaceId}\`.`})}if(sources.team!=="picker"){let{data,response,error:error51}=await withSpinner("Checking the team",()=>client.GET("/v1/team/{teamId}",{params:{path:{teamId}}}));response.ok||apiFail(response.status,error51),data?.name&&(labels.team=data.name)}let record4={team:resolved.team,workspace:workspaceId,environment:environmentId,labels};writeSession(record4);let stored=readSession(),detail=stored?Object.fromEntries(SESSION_KEYS.map(k2=>[k2,describeValue(stored,k2)])):record4;okMutation("Session defaults set",record4,detail)}),cli.command("clear-session").description("Forget the session defaults for this shell session").option("--all","Forget the stored defaults of every shell session, not just this one (optional)").option("--explain",EXPLAIN).action((opts,cmd)=>{if(explained(cmd,CLEAR_SESSION_DOC))return;if(opts.all){let{removed,keptLocks:keptLocks2}=clearAllSessions();noteKeptLocks(keptLocks2),okMutation(removed>0?`Cleared session defaults for ${removed} shell session${removed===1?"":"s"}`:"No session defaults were stored",{cleared:removed>0,sessions:removed,keptLocks:keptLocks2});return}let{cleared,keptLocks}=clearSession();noteKeptLocks(keptLocks),okMutation(cleared?"Session defaults cleared":"No session defaults were set",{cleared,keptLocks})}),cli.command("list-api-logs").description("List the API calls this CLI recorded").option("--session <key>","Read another shell session's recording, see --list-sessions (optional, default: this shell's session, ignored with --all-sessions)").option("--all-sessions","Read every recorded shell session, not just this one (optional)").option("--list-sessions","List the recorded shell sessions instead of the calls (optional)").option("--limit <n>",`Keep the newest N runs, with all their calls; 0 for all (optional, default: ${DEFAULT_RECORDED_LIMIT}, ignored with --list-sessions)`).option("--since <iso>","Only calls at or after the specified ISO time (optional, ignored with --list-sessions)").option("--to <iso>","Only calls at or before the specified ISO time (optional, ignored with --list-sessions)").option("--failed-only","Only calls that returned HTTP >= 400 or never got a response (optional, ignored with --list-sessions)").option("--status <code>","Only calls with this HTTP status (optional, repeatable, ignored with --list-sessions)",collect).option("--method <verb>","Only calls with this HTTP method (optional, ignored with --list-sessions)").option("--path <substring>","Only calls whose URL contains this substring (optional, ignored with --list-sessions)").option("--explain",EXPLAIN).action((opts,cmd)=>{if(explained(cmd,LIST_API_LOGS_DOC))return;if(opts.listSessions){let sessions=listRecordedSessions();ok(sessions,{human:rows2=>rows2.map(row=>({session:row.session,files:row.files,runs:row.runs,calls:row.calls,first:row.first??"",last:row.last??"",size:formatBytes(row.bytes)}))});return}let limit=parseLimit(opts.limit),matched=filterApiCalls(readApiCalls(opts),opts),runs=limit>0?matched.slice(-limit):matched;runs.length===0&&!isRaw()&&noteWhyEmpty(opts);let showSession=!!(opts.allSessions||opts.session);ok(runs,{human:rows2=>renderApiCallRuns(rows2,showSession)})}),cli.command("clear-api-logs").description("Delete recorded API calls").option("--session <key>","Clear another shell session's recording (optional, default: this shell's session, ignored with --all-sessions)").option("--all-sessions","Clear every recorded shell session, not just this one (optional)").option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CLEAR_API_LOGS_DOC))return;let targets=recordedTargets(opts),bytes=targets.reduce((total,summary)=>total+summary.bytes,0),files=targets.reduce((total,summary)=>total+summary.files,0);!opts.yes&&targets.length>0&&(canPrompt()||fail(EXIT.USAGE,"CONFIRMATION_REQUIRED","Deleting recorded API calls is irreversible. Re-run with --yes to confirm."),await prompts().confirm(`Delete the recorded API calls of ${targets.length} shell session${targets.length===1?"":"s"} (${formatBytes(bytes)})? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."));let removed=clearApiCalls(opts);okMutation(removed.length>0?`Cleared recorded API calls for ${removed.length} shell session${removed.length===1?"":"s"}`:"No recorded API calls were stored",{deleted:removed.length>0,files,sessions:removed})}),cli.command("list-crash-reports").description("List the crash reports this CLI stored").option("--explain",EXPLAIN).action((_opts,cmd)=>{if(explained(cmd,LIST_CRASH_REPORTS_DOC))return;let reports=listCrashReports();reports.length===0&&!isRaw()&&prompts().note("No crash reports stored \u2014 one is written when a run fails unexpectedly or the API answers 5xx, unless --no-crash-reports or SR_CONNECT_CLI_NO_CRASH_REPORTS turned that off."),ok(reports,{human:rows2=>renderTable(rows2.map(crashRow))})}),cli.command("get-crash-report").description("Read one stored crash report").option("--report <id>",`The crash report to print, see ${CLI} cli list-crash-reports (optional, interactive, default: the newest one)`).option("--content-only","Print the report as markdown, with no rendering or JSON envelope (optional)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,GET_CRASH_REPORT_DOC))return;let report=await resolveCrashReport(opts.report,"Which crash report do you want to read?");if(opts.contentOnly){okFile(report.markdown);return}ok(report,{human:data=>renderMarkdown(stripCrashHeader(data.markdown))})}),cli.command("clear-crash-reports").description("Delete stored crash reports").option("--report <id>","The crash report to delete (optional, default: every stored report)").option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CLEAR_CRASH_REPORTS_DOC))return;let targets=listCrashReports().filter(report=>opts.report===void 0||report.id===opts.report),bytes=targets.reduce((total,report)=>total+report.bytes,0);!opts.yes&&targets.length>0&&(canPrompt()||fail(EXIT.USAGE,"CONFIRMATION_REQUIRED","Deleting crash reports is irreversible. Re-run with --yes to confirm."),await prompts().confirm(`Delete ${targets.length} crash report${targets.length===1?"":"s"} (${formatBytes(bytes)})? This is irreversible \u2014 nothing has been sent.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."));let removed=clearCrashReports(opts.report);okMutation(removed.length>0?`Deleted ${removed.length} crash report${removed.length===1?"":"s"}`:"No crash reports were stored",{deleted:removed.length>0,reports:removed})}),cli.command("simulate-server-error",{hidden:!0}).description("Make a request that really fails, to exercise the crash-report path").option("--status <code>","HTTP status the simulated API answers with (optional, default: 500)").option("--body <json>",'Response body the simulated API answers with (optional, default: {"message":"Internal server error"})').option("--calls <n>","How many requests to make, the last one failing (optional, default: 1)").action(async opts=>{let status=wholeNumber(opts.status,500,"--status",100,599),calls=wholeNumber(opts.calls,1,"--calls",1,50),body=opts.body??'{"message":"Internal server error"}',seen=0,server=createServer((_request,response)=>{seen+=1;let last=seen>=calls;response.writeHead(last?status:200,{"content-type":"application/json"}),response.end(last?body:"{}")});await new Promise(resolve8=>server.listen(0,"127.0.0.1",resolve8));let address=server.address(),port=typeof address=="object"&&address!==null?address.port:0,client=createClient({baseUrl:`http://127.0.0.1:${port}`,headers:identityHeaders(),fetch:fetchWithRetry});try{let result=await withSpinner("Simulating a server error",async()=>{let last=await client.GET("/v1/serviceInfo",{});for(let call=1;call<calls;call+=1)last=await client.GET("/v1/serviceInfo",{});return last});(!result.response.ok||!result.data)&&apiFail(result.response.status,result.error),okMutation("Simulated server response",{simulated:!0,status:result.response.status,calls})}finally{server.closeAllConnections(),await new Promise(resolve8=>server.close(()=>resolve8()))}}),cli.command("simulate-cli-error",{hidden:!0}).description("Throw an unexpected client-side error, to exercise the crash-report path").option("--message <text>","Message the simulated failure carries (optional, default: Simulated client-side failure)").option("--async","Throw from inside an awaited helper rather than a synchronous one (optional)").action(async opts=>{let message=opts.message??"Simulated client-side failure";opts.async&&await throwLater(message),throwNow(message)}),cli}function wholeNumber(value,fallback,flag,min,max){if(value===void 0)return fallback;let parsed=Number(value);return(!Number.isInteger(parsed)||parsed<min||parsed>max)&&fail(EXIT.USAGE,"INVALID_ARGUMENT",`${flag} must be a whole number between ${min} and ${max}.`),parsed}function throwNow(message){throw new TypeError(message,{cause:Object.assign(new Error("socket hang up"),{code:"ECONNRESET"})})}async function throwLater(message){await Promise.resolve(),throwNow(message)}var shareBodySchema=external_exports.object({edit:external_exports.boolean(),use:external_exports.object({permission:external_exports.boolean(),scope:external_exports.enum(["ALL_TEAMS","SPECIFIC_TEAMS"]).optional(),teamIds:external_exports.array(external_exports.string().min(1)).optional()}).strict().refine(use=>!use.permission||use.scope!==void 0,{message:"use.scope is required when use.permission is true."}).refine(use=>use.permission||use.scope===void 0&&use.teamIds===void 0,{message:"use.scope and use.teamIds are only valid when use.permission is true."}).refine(use=>use.scope!=="SPECIFIC_TEAMS"||use.teamIds!==void 0&&use.teamIds.length>0,{message:"use.teamIds must contain at least one team when use.scope is SPECIFIC_TEAMS."}).refine(use=>use.scope!=="ALL_TEAMS"||use.teamIds===void 0,{message:"use.teamIds cannot be provided when use.scope is ALL_TEAMS."})}).strict().refine(body=>body.edit||body.use.permission,{message:"At least one permission must be granted \u2014 use `connector-sharing remove` to revoke access."}),LIST_DOC2=defineCommandDoc("connector-sharing list",{rules:["The connector is --connector-id and the team is --team; there is no positional argument, the verb listing every share."],notes:["Everyone the connector is shared with, the owner included. A narrowed use permission shows as a count of teams here; get names them."]}),GET_DOC2=defineCommandDoc("connector-sharing get",{rules:["The user is the positional argument; the connector is --connector-id and the team is --team."],notes:["A single user's permissions, with the teams a narrowed use permission covers and every team it could cover.",`Your own user ID is refused here (403 "User cannot share connector with themselves."). The owner's own entry is readable through list alone.`]}),ASSIGNABLE_DOC=defineCommandDoc("connector-sharing list-assignable-users",{rules:["The connector is --connector-id and the team is --team; there is no positional argument."],notes:["The users the connector can still be shared with, each with the teams you have in common. Anyone already holding a permission is excluded, so an empty list means everyone already has some access."]}),REMOVE_DOC=defineCommandDoc("connector-sharing remove",{rules:["The user is the positional argument; the connector is --connector-id and the team is --team.","--dry-run reports what revoking their access would detach and commits nothing, the same flag set takes and the way to see the cost before paying it.","--yes skips the confirmation, and is required without a terminal."],notes:["Revokes all access at once; there is no partial removal here, which is what set is for.","API connections and event listeners the user attached the connector to are detached, in workspaces you are not a member of included, and are listed before the confirmation. Granting access back does not re-attach them.",'The document is {"deleted":true,"id":\u2026,"userId":\u2026,"connectorId":\u2026}: id is the user, the resource the verb acted on, and userId says so. set answers the same three keys under updated.']}),SET_DOC=defineCommandDoc("connector-sharing set",{schema:shareBodySchema,body:{edit:!1,use:{permission:!0,scope:"SPECIFIC_TEAMS",teamIds:["<teamId>"]}},rules:["edit (--edit as a flag): true lets the user rename the connector and replace its credentials, in every team; it never lets them delete it.","use.permission: true lets the user attach the connector to API connections and event listeners; use.scope is then required.","use.scope: ALL_TEAMS covers every team you share with the user, including teams they join later, and use.teamIds must then be absent (--use-all-teams as a flag); SPECIFIC_TEAMS needs use.teamIds naming at least one team both of you are members of (--use-team <teamId>, repeatable). The use block has no flag of its own: which of those two was passed is what implies the scope.","use.scope and use.teamIds are refused when use.permission is false.",`At least one of edit or use.permission must be true; access is revoked with ${CLI} connector-sharing remove.`,"The body is the whole permission set and both keys are required: edit false and use.permission false revoke, rather than being left as they are, and losing or narrowing use detaches the connector from that user's workspaces in the teams it no longer covers.","Only the connector's owner can share it, and never with themselves. The user is the positional argument and the connector is --connector-id; neither is a body key.","--dry-run, a flag rather than a key, reports what the body would detach and commits nothing."],notes:['The document is {"updated":true,"id":\u2026,"userId":\u2026,"connectorId":\u2026}: id is the user here, the resource the verb acted on, and userId says so. remove answers the same three keys under deleted.']});async function resolveScope2(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["team"],{team:globals.team},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,team:resolved.team??""}}async function resolveTarget(scope2,provided){if(provided)return{...scope2,connector:assertResourceId(provided,"--connector-id")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR","--connector-id is required.");let labels={},resolved=await resolveParams(["ownedConnector"],{team:scope2.team},{client:scope2.client,interactive:!0,labels});return{...scope2,connector:resolved.ownedConnector??"",...labels.ownedConnector?{connectorLabel:labels.ownedConnector}:{}}}function shareFail(status,error51){let message=error51?.errorMessage??"";status===404&&/connector not found/i.test(message)&&fail(EXIT.NOT_FOUND,"NOT_FOUND",message,{status,hint:`The connector-sharing verbs are the owner's alone, so a connector you do not own reads as missing here \u2014 ${CLI} connector list shows the ones you can see, with the owner of each.`}),apiFail(status,error51)}var sharesCache=new WeakMap;async function fetchShares(target){let perConnector=sharesCache.get(target.client);perConnector||sharesCache.set(target.client,perConnector=new Map);let key=`${target.team}/${target.connector}`,cached2=perConnector.get(key);return cached2||(cached2=withSpinner("Fetching connector sharing",async()=>{let{data,response,error:error51}=await target.client.GET("/v1/team/{teamId}/connector/{connectorId}/shares",{params:{path:{teamId:target.team,connectorId:target.connector}}});return(!response.ok||!data)&&shareFail(response.status,error51),data.shares}),cached2.catch(()=>perConnector.delete(key)),perConnector.set(key,cached2)),cached2}async function fetchShare(target,userId){let{data,error:error51,response}=await withSpinner("Fetching connector share",()=>target.client.GET("/v1/team/{teamId}/connector/{connectorId}/share/{userId}",{params:{path:{teamId:target.team,connectorId:target.connector,userId}}}));return response.ok&&data?{share:data,status:response.status}:{status:response.status,error:error51}}async function fetchAssignableMembers(target){let{data,response,error:error51}=await withSpinner("Fetching assignable members",()=>target.client.GET("/v1/team/{teamId}/connector/{connectorId}/assignableMembers",{params:{path:{teamId:target.team,connectorId:target.connector}}}));return(!response.ok||!data)&&shareFail(response.status,error51),data.members}function userName(user){return personName(user)||"that user"}function useCell(permissions,teams=[]){let use=permissions.use;if(!use.permission)return"no";if(use.scope==="ALL_TEAMS")return"all teams";if(use.teamIds.length===0)return"no teams";let named=use.teamIds.map(id=>teams.find(t=>t.id===id)?.name).filter(name=>!!name);return named.length===use.teamIds.length?named.join(", "):`${use.teamIds.length} team${use.teamIds.length===1?"":"s"}`}function humanShare(share){return{user:personCell(share.user),email:share.user.email,owner:share.owner?"yes":"no",edit:share.permissions.edit?"yes":"no",use:useCell(share.permissions)}}function reducesAccess(current,next){if(!current)return!1;if(current.edit&&!next.edit)return!0;let had=current.use,gets=next.use;if(!had.permission)return!1;if(!gets.permission)return!0;if(had.scope==="ALL_TEAMS")return gets.scope!=="ALL_TEAMS";let kept=new Set(gets.scope==="ALL_TEAMS"?[]:gets.teamIds??[]);return gets.scope!=="ALL_TEAMS"&&had.teamIds.some(id=>!kept.has(id))}function sameAsCurrent(current,next){if(!current||current.edit!==next.edit||current.use.permission!==next.use.permission)return!1;if(!next.use.permission)return!0;if(current.use.scope!==next.use.scope)return!1;if(next.use.scope==="ALL_TEAMS")return!0;let before=[...current.use.teamIds].sort(),after=[...next.use.teamIds??[]].sort();return before.length===after.length&&before.every((id,i)=>id===after[i])}function detachRows(impact){return impact.detaches.map(entry2=>({workspace:`${entry2.workspace.name} (${entry2.workspace.id})`,team:`${entry2.team.name} (${entry2.team.id})`,apiConnections:entry2.apiConnections,eventListeners:entry2.eventListeners}))}function humanImpact(impact){return{effect:impact.effect,...impact.detaches.length>0?{detaches:detachRows(impact)}:{detaches:"nothing would be detached"}}}function impactNote(impact){let rows2=detachRows(impact).map(row=>` ${row.workspace} \xB7 ${row.team} \xB7 ${row.apiConnections} API connection(s), ${row.eventListeners} event listener(s)`).join(`
1329
+ `);prompts().note(["Reducing access detaches the connector. This change would remove it from:","",rows2,"","Those API connections and event listeners stop working the moment the connector is","detached, and every script importing them fails until somebody attaches a","replacement. Granting the permission back does not re-attach anything.","","These are not your workspaces \u2014 one appears above only when you are not a member of","the team that owns it \u2014 so the repair is someone else's to make."].join(`
1330
+ `))}async function dryRun(target,userId,body){let params={path:{teamId:target.team,connectorId:target.connector,userId},query:{dryRun:"true"}},{data,response,error:error51}=await withSpinner("Checking what would change",()=>body===void 0?target.client.DELETE("/v1/team/{teamId}/connector/{connectorId}/share/{userId}",{params}):target.client.PUT("/v1/team/{teamId}/connector/{connectorId}/share/{userId}",{params,body}));return response.ok||shareFail(response.status,error51),data}async function confirmReduction(target,userId,body,question,opts={}){let impact=await dryRun(target,userId,body),detached=impact?.detaches.length??0;if(detached===0&&!opts.always)return;impact&&detached>0&&impactNote(impact);let suffix=detached>0?` This detaches ${detached} workspace${detached===1?"":"s"}.`:"";await prompts().confirm(`${question}${suffix}`,!1)||fail(EXIT.CANCELLED,"CANCELLED","Change cancelled.")}function permissionsFromFlags(opts){opts.useAllTeams&&(opts.useTeam?.length??0)>0&&fail(EXIT.USAGE,"USAGE_ERROR","--use-all-teams and --use-team cannot be combined.");let use=opts.useAllTeams?{permission:!0,scope:"ALL_TEAMS"}:(opts.useTeam?.length??0)>0?{permission:!0,scope:"SPECIFIC_TEAMS",teamIds:opts.useTeam}:{permission:!1};return{edit:opts.edit===!0,use}}async function askShareUser(target,opts){let shares=(await fetchShares(target)).filter(s=>!s.owner),assignable=opts.includeAssignable?await fetchAssignableMembers(target):[],existing=shares.map(share2=>{let label=userName(share2.user),held=[share2.permissions.edit?"edit":void 0,share2.permissions.use.permission?`use in ${useCell(share2.permissions)}`:void 0].filter(note=>note!==void 0);return{value:share2.user.id,label,display:`${label} (shared: ${held.join(", ")||"nothing"})`,hint:share2.user.email}}),candidates=assignable.map(member2=>({value:member2.id,label:userName(member2),hint:`${member2.email} \xB7 ${member2.teams.length} team${member2.teams.length===1?"":"s"} in common`})),choices=[...existing,...candidates];choices.length===0&&(opts.includeAssignable&&fail(EXIT.NOT_FOUND,"NO_ASSIGNABLE_MEMBERS","There is nobody to share this connector with: it is already shared with everyone you share a team with.",{hint:"Share a team with someone first, or change an existing share."}),fail(EXIT.NOT_FOUND,"NO_SHARES","This connector is not shared with anyone."));let picked=await prompts().select(opts.includeAssignable?"Who should hold access to this connector?":`Whose access should be ${opts.verb}?`,choices),share=shares.find(s=>s.user.id===picked),member=assignable.find(m2=>m2.id===picked);return{userId:picked,...share?{share}:{},...share||member?{name:userName(share?share.user:member)}:{}}}function teamChoices(available,current){let choices=available.map(team=>({value:team.id,label:team.name,hint:team.id}));for(let id of current)available.some(team=>team.id===id)||choices.push({value:id,label:id,display:`${id} (current \u2014 no longer a team you share)`,hint:"keep it to leave that access alone"});return choices}async function askPermissions(current,teams){for(;;){let currentEdit=current?.edit,edit=await prompts().select("Can they rename the connector and replace its credentials?",[{value:"no",label:"No",...currentEdit===!1?{display:"No (current)"}:{},hint:"they can still use it, if you grant that next"},{value:"yes",label:"Yes \u2014 edit permission",...currentEdit===!0?{display:"Yes \u2014 edit permission (current)"}:{},hint:"renaming and replacing credentials, never deleting"}],{initial:currentEdit===!0?"yes":"no"})==="yes",currentUse=current?.use,currentScope=currentUse?.permission?currentUse.scope:"none",scope2=await prompts().select("Where may they use it?",[{value:"ALL_TEAMS",label:"Every team you share with them",...currentScope==="ALL_TEAMS"?{display:"Every team you share with them (current)"}:{},hint:"including teams they join later"},{value:"SPECIFIC_TEAMS",label:"Only teams I pick",...currentScope==="SPECIFIC_TEAMS"?{display:"Only teams I pick (current)"}:{}},...edit?[{value:"none",label:"Nowhere \u2014 no use permission",...currentScope==="none"?{display:"Nowhere \u2014 no use permission (current)"}:{},hint:"they cannot use the connector in any workspace"}]:[]],{initial:current&&(edit||currentScope!=="none")?currentScope:"SPECIFIC_TEAMS"}),teamIds;if(scope2==="SPECIFIC_TEAMS"){let held=currentUse?.permission&&currentUse.scope==="SPECIFIC_TEAMS"?currentUse.teamIds:[],choices=teamChoices(teams,held);if(choices.length===0){prompts().note("\u2716 You share no teams with this user, so there is no team to allow.");continue}let picked=await prompts().multiselect("Which teams may they use it in?",choices,{initial:held.length>0?held:choices.length===1?[choices[0]?.value??""]:[]});if(picked.length===0){prompts().note("\u2716 Pick at least one team, or choose a different answer above.");continue}teamIds=picked}let body={edit,use:scope2==="none"?{permission:!1}:scope2==="ALL_TEAMS"?{permission:!0,scope:"ALL_TEAMS"}:{permission:!0,scope:"SPECIFIC_TEAMS",teamIds}};if(!body.edit&&!body.use.permission){prompts().note("\u2716 That grants nothing. Grant at least one permission, or remove their access with `connector-sharing remove`.");continue}return body}}function sentCells(userId,target,body,teams){return{user:userId,connector:target.connectorLabel?`${target.connectorLabel} (${target.connector})`:target.connector,edit:body.edit?"yes":"no",use:useCell({edit:body.edit,use:body.use.permission?{permission:!0,scope:body.use.scope??"ALL_TEAMS",teamIds:body.use.teamIds??[]}:{permission:!1,scope:"ALL_TEAMS",teamIds:[]}},teams)}}function connectorSharingCommand(){let sharing=new Command("connector-sharing").alias("cs").description("Manage connector sharing"),CONNECTOR_ID="Connector ID (required, interactive)",USER_ID="User ID, see list-assignable-users for users the connector is not yet shared with and list for those it is (required, interactive)",SHARED_USER_ID="User ID, one of those list reports (required, interactive)";return sharing.command("list").description("List everyone a connector is shared with").option("--connector-id <connectorId>",CONNECTOR_ID).option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LIST_DOC2))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope2(globals),target=await resolveTarget(scope2,opts.connectorId),{data,response,error:error51}=await withSpinner("Fetching connector sharing",()=>target.client.GET("/v1/team/{teamId}/connector/{connectorId}/shares",{params:{path:{teamId:target.team,connectorId:target.connector}}}));(!response.ok||!data)&&shareFail(response.status,error51),ok(data,{human:d=>({shares:d.shares.map(humanShare)})})}),sharing.command("get").description("Get a single user's permissions on a connector").argument("[userId]",SHARED_USER_ID).option("--connector-id <connectorId>",CONNECTOR_ID).option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(userArg,opts,cmd)=>{if(explained(cmd,GET_DOC2))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope2(globals),target=await resolveTarget(scope2,opts.connectorId),userId=userArg===void 0?void 0:assertResourceId(userArg,"userId");userId||(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<userId> is required. ${supplyHint()}`),userId=(await askShareUser(target,{includeAssignable:!1,verb:"shown"})).userId);let{data,response,error:error51}=await withSpinner("Fetching connector share",()=>target.client.GET("/v1/team/{teamId}/connector/{connectorId}/share/{userId}",{params:{path:{teamId:target.team,connectorId:target.connector,userId}}}));(!response.ok||!data)&&shareFail(response.status,error51),ok(data,{human:d=>({user:personCell(d.user),email:d.user.email,owner:d.owner?"yes":"no",edit:d.permissions.edit?"yes":"no",use:useCell(d.permissions,d.teams),useTeams:d.permissions.use.teamIds.map(id=>{let team=d.teams.find(t=>t.id===id);return team?`${team.name} (${team.id})`:id}).join(", "),sharedTeams:d.teams.map(t=>`${t.name} (${t.id})`).join(", ")})})}),sharing.command("list-assignable-users").description("List the users a connector can still be shared with").option("--connector-id <connectorId>",CONNECTOR_ID).option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,ASSIGNABLE_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope2(globals),target=await resolveTarget(scope2,opts.connectorId),{data,response,error:error51}=await withSpinner("Fetching assignable members",()=>target.client.GET("/v1/team/{teamId}/connector/{connectorId}/assignableMembers",{params:{path:{teamId:target.team,connectorId:target.connector}}}));(!response.ok||!data)&&shareFail(response.status,error51),ok(data,{human:d=>({members:d.members.map(m2=>({user:personCell(m2),email:m2.email,teams:m2.teams.map(t=>`${t.name} (${t.id})`).join(", ")}))})})}),sharing.command("set").description("Share a connector with a user, or change what they may do with it").argument("[userId]",USER_ID).option("--connector-id <connectorId>",CONNECTOR_ID).option("--team <teamId>",SCOPE_TEAM).option("--edit","Let them rename the connector and replace its credentials, in every team; never lets them delete it. The flags carry the whole permission set, so omitting it revokes the permission from a user who holds it (optional, interactive, default: false)").option("--use-all-teams","Let them use the connector in every team you share with them, including teams they join later. Passing neither this nor --use-team revokes the use permission from a user who holds it (optional, interactive, exclusive with --use-team)").option("--use-team <teamId>","Let them use the connector in the specified team only; you and that user must both be members of every team named. Passing neither this nor --use-all-teams revokes the use permission from a user who holds it (optional, interactive, repeatable, exclusive with --use-all-teams)",(value,previous)=>[...previous??[],value]).option("--dry-run","Report what the request would change, and what it would detach, without committing anything (optional)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(userArg,opts,cmd)=>{if(explained(cmd,SET_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope2(globals),target=await resolveTarget(scope2,opts.connectorId),fromFlags=opts.input!==void 0||opts.edit===!0||opts.useAllTeams===!0||(opts.useTeam?.length??0)>0,userId=userArg===void 0?void 0:assertResourceId(userArg,"userId"),current,readCurrent=!1,teams=[],who;if(!userId){canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<userId> is required. ${supplyHint()}`);let picked=await askShareUser(target,{includeAssignable:!0,verb:"changed"});userId=picked.userId,current=picked.share?.permissions,readCurrent=!0,who=picked.share?userName(picked.share.user):picked.name}let typedUserId=userArg!==void 0,body;if(fromFlags){if(body=opts.input!==void 0?validate(shareBodySchema,readInput(opts.input)):validate(shareBodySchema,permissionsFromFlags(opts)),typedUserId&&canPrompt()){let{share,status,error:error52}=await fetchShare(target,userId);!share&&status!==404&&apiFail(status,error52),readCurrent=!0,share&&(current=share.permissions,teams=share.teams,who??=userName(share.user))}}else{canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR","No permission specified: pass --edit, --use-all-teams, --use-team or --input.");let{share,status,error:error52}=await fetchShare(target,userId);if(!share&&status!==404&&apiFail(status,error52),readCurrent=!0,share?(current=share.permissions,teams=share.teams,who??=userName(share.user)):status===404&&(teams=(await fetchAssignableMembers(target)).find(m2=>m2.id===userId)?.teams??[]),body=await askPermissions(current,teams),sameAsCurrent(current,body)){prompts().note("Nothing to change \u2014 they already hold exactly that.");return}}if(opts.dryRun){let impact=await dryRun(target,userId,body);impact||fail(EXIT.API_ERROR,"NO_IMPACT_REPORTED","The API reported no impact for the change."),ok(impact,{human:humanImpact});return}canPrompt()&&reducesAccess(current,body)&&await confirmReduction(target,userId,body,`Reduce ${who??userId}'s access to this connector?`);let{response,error:error51}=await withSpinner("Sharing connector",()=>target.client.PUT("/v1/team/{teamId}/connector/{connectorId}/share/{userId}",{params:{path:{teamId:target.team,connectorId:target.connector,userId}},body}));response.ok||shareFail(response.status,error51),okMutation(current?"Connector sharing updated":"Connector shared",{updated:!0,id:userId,userId,connectorId:target.connector},sentCells(userId,target,body,teams)),readCurrent&&!current&&prompts().note("They may be emailed about the new access.")}),sharing.command("remove").description("Remove a user's access to a connector").argument("[userId]",USER_ID).option("--connector-id <connectorId>",CONNECTOR_ID).option("--team <teamId>",SCOPE_TEAM_DESTRUCTIVE).option("--dry-run","Report what removing their access would detach, without committing anything (optional)").option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(userArg,opts,cmd)=>{if(explained(cmd,REMOVE_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope2(globals,{useSession:canPrompt()}),target=await resolveTarget(scope2,opts.connectorId),userId=userArg===void 0?void 0:assertResourceId(userArg,"userId"),name;if(!userId){canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<userId> is required. ${supplyHint()}`);let picked=await askShareUser(target,{includeAssignable:!1,verb:"removed"});userId=picked.userId,name=picked.share?userName(picked.share.user):void 0}if(opts.dryRun){let impact=await dryRun(target,userId,void 0);impact||fail(EXIT.API_ERROR,"NO_IMPACT_REPORTED","The API reported no impact for the removal."),ok(impact,{human:humanImpact});return}opts.yes||(canPrompt()||fail(EXIT.USAGE,"CONFIRMATION_REQUIRED","Removing access can detach the connector from workspaces. Re-run with --yes to confirm."),await confirmReduction(target,userId,void 0,`Remove ${name??userId}'s access to this connector?`,{always:!0}));let{response,error:error51}=await withSpinner("Removing access",()=>target.client.DELETE("/v1/team/{teamId}/connector/{connectorId}/share/{userId}",{params:{path:{teamId:target.team,connectorId:target.connector,userId}}}));response.ok||shareFail(response.status,error51),okMutation("Connector sharing removed",{deleted:!0,id:userId,userId,connectorId:target.connector})}),sharing}var CONNECTOR_NAME_FORMAT="up to 100 characters",MAX_CONNECTOR_NAME=100;function normalizeConnectorName(name){return name.trim()}function connectorNameError(name){let normalized=normalizeConnectorName(name);if(!normalized)return"A connector name is required.";if(normalized.length>MAX_CONNECTOR_NAME)return`A connector name can be at most ${MAX_CONNECTOR_NAME} characters (that one is ${normalized.length}).`}function assertConnectorName(name){let error51=connectorNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_CONNECTOR_NAME",error51),normalizeConnectorName(name)}var BASE_URL_FORMAT="must start with https:// or http://",MAX_HEADER_NAME=250,BASIC_AUTH_PASSWORD_ENV="SR_CONNECT_CLI_BASIC_AUTH_PASSWORD";function normalizeBaseUrl(url2){return url2.trim()}function baseUrlError(url2){let normalized=normalizeBaseUrl(url2);if(!normalized)return"A base URL is required.";if(!/^https?:\/\/\S/i.test(normalized))return`A base URL ${BASE_URL_FORMAT}.`}function assertBaseUrl(url2){let error51=baseUrlError(url2);return error51&&fail(EXIT.USAGE,"INVALID_BASE_URL",error51),normalizeBaseUrl(url2)}function parseHeaderFlag(input){let at2=input.indexOf(":");at2===-1&&fail(EXIT.USAGE,"INVALID_HEADER",`--header ${JSON.stringify(input)} is not "name: value".`);let name=input.slice(0,at2).trim();return name||fail(EXIT.USAGE,"INVALID_HEADER","A header name cannot be empty."),{name,value:input.slice(at2+1).replace(/^ /,"")}}function headerNameError(name){let normalized=name.trim();if(!normalized)return"A header name is required.";if(normalized.length>MAX_HEADER_NAME)return`A header name can be at most ${MAX_HEADER_NAME} characters (that one is ${normalized.length}).`}function assertHeaders(headers){let seen=new Set,normalized=[];for(let header of headers){let name=header.name.trim(),error51=headerNameError(name);error51&&fail(EXIT.USAGE,"INVALID_HEADER",error51);let key=name.toLowerCase();seen.has(key)&&fail(EXIT.USAGE,"DUPLICATE_HEADER",`Header "${name}" is given more than once.`),seen.add(key),normalized.push({name,value:header.value})}return normalized}function isAuthorizationHeader(name){return name.trim().toLowerCase()==="authorization"}function assertGenericConfiguration(configuration){return{...configuration,baseUrl:assertBaseUrl(configuration.baseUrl),...configuration.headers===void 0?{}:{headers:assertHeaders(configuration.headers)}}}async function basicAuthPassword(opts){let fromEnv=process.env[BASIC_AUTH_PASSWORD_ENV];return fromEnv||(opts.ask||fail(EXIT.USAGE,"USAGE_ERROR",`--basic-auth-username needs a password: set ${BASIC_AUTH_PASSWORD_ENV}, or run on a terminal without --no-prompts to be asked for it.`),opts.ask())}var genericConfigurationSchema=external_exports.object({baseUrl:external_exports.string().min(1),headers:external_exports.array(external_exports.object({name:external_exports.string().min(1),value:external_exports.string()}).strict()).optional(),basicAuth:external_exports.object({username:external_exports.string().min(1),password:external_exports.string().min(1)}).strict().optional()}).strict(),createBodySchema2=external_exports.object({appId:external_exports.string().min(1),name:external_exports.string().min(1),apiConnectionTypeId:external_exports.string().min(1).optional(),eventListenerTypeId:external_exports.string().min(1).optional(),genericConfiguration:genericConfigurationSchema.optional()}).strict(),updateBodySchema2=external_exports.object({name:external_exports.string().min(1).optional(),genericConfiguration:genericConfigurationSchema.optional()}).strict().refine(body=>body.name!==void 0||body.genericConfiguration!==void 0,{message:"Either a new name or a configuration is required."}),EXAMPLE_CONFIGURATION={baseUrl:"https://api.example.com",headers:[{name:"X-Api-Key",value:"<apiKey>"}],basicAuth:{username:"<username>",password:"<password>"}},LIST_DOC3=defineCommandDoc("connector list",{rules:["The team is --team and there is no positional argument; this group stops at the team, a connector belonging to a user and being looked up through one."],notes:["Your own connectors and those shared with you for use in the team named. connectionType is the app the connector is for, and is what an API connection or an event listener is matched against; it is never the API connection type.","Under --raw the list arrives under the key connections, which is the API's own name for it and not connectors. Responses are passed through as they are sent, so that is the key to read.","The listing does not carry baseUrl, the instance a connector points at. Read a single connector for that."]}),GET_DOC3=defineCommandDoc("connector get",{rules:["The connector is the positional argument and the team is --team."],notes:["Reports the authorization URL, which is where an unauthorized connector is finished and where an expired one is renewed, so it is carried for every connector rather than only for a new one.","Reports baseUrl, the instance the connector points at: the site or host it was authorized against, such as an Atlassian site or a self-managed GitLab. The listing does not carry it. Read it as optional rather than as a field every connector has, since it is absent while a connector is unauthorized, even where a URL was already entered, and absent altogether for an app that has no instance of its own.","baseUrl is reported exactly as it was configured, which may include a trailing slash, so normalize it before joining a path onto it.","For a Generic connector it also reports the configuration: the base URL, which is the same value baseUrl carries, the derived authentication method and the header names. Header values are never reported, by this verb or any other."]}),DELETE_DOC2=defineCommandDoc("connector delete",{rules:["The connector is the positional argument and the team is --team.","--force deletes a connector that is still in use, which is otherwise refused.","--yes skips the confirmation, and is required without a terminal."],notes:["Owner only. The connector goes for everyone it was shared with, and every API connection and event listener on it is detached in every workspace, including other people's. Nobody is notified.","A connector still in use is exit 1 CONNECTOR_IN_USE without --force."]}),CREATE_DOC2=defineCommandDoc("connector create",{schema:createBodySchema2,body:{appId:"<appId>",name:"Internal API (prod)",apiConnectionTypeId:"<apiConnectionTypeId>",eventListenerTypeId:"<eventListenerTypeId>",genericConfiguration:EXAMPLE_CONFIGURATION},rules:[`appId: the app the connector is for, from ${CLI} app list; never reported back as such, but list and get report connectionType, whose id is the app's own connectionType.id in app list.`,`name: ${CONNECTOR_NAME_FORMAT}, trimmed, no charset rule, unique among your own connectors for the same app.`,"apiConnectionTypeId (--api-connection-type-id as a flag): one of the app's API connection types; a connector created without one is refused when it is attached to an API connection.","eventListenerTypeId (--listener-type-id as a flag, as on event-listener create): one of the app's event listener types; it only labels the connector, since event listeners attach by app.","genericConfiguration is accepted for the Generic app only (400 for any other) and creates the connector authorized; any other app's connector is created unauthorized and finished in a browser at the URL the response carries.",`genericConfiguration.baseUrl is required whenever the block is sent and ${BASE_URL_FORMAT}. Spelled --base-url as a flag; the block itself has no flag of its own.`,`genericConfiguration.headers: name and value pairs sent with every request, spelled --header <name:value> as a repeatable flag; names are trimmed and can be at most ${MAX_HEADER_NAME} characters, a name given twice is refused with the two compared without case, values are kept exactly as sent, and nothing ever reports a value back.`,`genericConfiguration.basicAuth: a username and password the API encodes into an Authorization header, replacing one of that name in headers. Spelled --basic-auth-username as a flag, with the password read from ${BASIC_AUTH_PASSWORD_ENV}, never from argv. The authentication method is derived from the configuration the write leaves behind and is never sent.`,"Header values and the password are credentials: keep the file out of version control."],notes:["A header value passed in argv is visible in shell history and in the process list. --input avoids that; recordings blank the values either way.","The authorization URL is reported for every connector, authorized or not, because it is also where an expired authorization is renewed."]}),UPDATE_DOC2=defineCommandDoc("connector update",{schema:updateBodySchema2,body:{name:"Internal API (prod)",genericConfiguration:EXAMPLE_CONFIGURATION},rules:["At least one of name or genericConfiguration is required, and an omitted key keeps the current value.",`name: ${CONNECTOR_NAME_FORMAT}, trimmed, unique among your own connectors for the same app; allowed for the owner and for anyone the connector is shared with for editing.`,"genericConfiguration is accepted for a connector of the Generic app only, replaces the configuration and cannot be removed.",`genericConfiguration.baseUrl is required whenever the block is sent, even when only the headers change, and ${BASE_URL_FORMAT}: send the current one back from get. Spelled --base-url as a flag.`,`genericConfiguration.headers: omit to keep the current header set, [] to clear it (--no-headers as a flag; the encoded Authorization header of basic authentication included), an array to replace it (--header <name:value>, repeatable); names are trimmed and can be at most ${MAX_HEADER_NAME} characters, and a name given twice is refused, the two compared without case.`,`genericConfiguration.basicAuth: re-encoded into the Authorization header, replacing one of that name in headers and surviving headers: []. Spelled --basic-auth-username as a flag, with the password read from ${BASIC_AUTH_PASSWORD_ENV}, never from argv.`]});async function resolveScope3(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["team"],{team:globals.team},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,team:resolved.team??""}}async function resolveConnector(scope2,provided){if(provided)return{id:assertResourceId(provided,"connectorId")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<connectorId> is required. ${supplyHint()}`);let labels={};return{id:(await resolveParams(["connector"],{team:scope2.team},{client:scope2.client,interactive:!0,labels})).connector??"",label:labels.connector}}async function askConnectorName(initial){for(;;){let answer=await prompts().text(`Connector name (${CONNECTOR_NAME_FORMAT})`,{...initial?{initial}:{},allowEmpty:!0}),error51=connectorNameError(answer);if(!error51)return normalizeConnectorName(answer);prompts().note(`\u2716 ${error51}`)}}async function askRename(current,opts={}){let name=await askConnectorName(current);if(current!==void 0&&name===current){opts.quiet||prompts().note(`"${current}" is already the connector's name \u2014 nothing to change.`);return}return name}var NO_TYPE="\0no-type";async function askOptionalType(scope2,key,appId){let optOut=key==="apiConnectionType"?{value:NO_TYPE,label:"Not for API connections",hint:"attaching it to an API connection is then refused"}:{value:NO_TYPE,label:"Not for event listeners",hint:"leaves the connector unlabelled; listeners attach by app"},choices;try{choices=await resolverChoices(scope2.client,key,{team:scope2.team,app:appId})}catch(err){if(!(err instanceof CliError))throw err;return}let noun=key==="apiConnectionType"?"API connection type":"event listener type",first=choices[0];if(!first){prompts().note(`\u26A0 This app publishes no ${noun}s \u2014 creating the connector without one.`);return}if(choices.length===1)return prompts().note(`${noun}: ${first.display??first.label} \u2014 only one, auto-selected.`),first.value;let message=key==="apiConnectionType"?"API connection type:":"Event listener type:",picked=await prompts().select(message,[...choices,optOut],{initial:first.value});return picked===NO_TYPE?void 0:picked}async function fetchConnector(scope2,connectorId){let{data}=await withSpinner("Checking the connector",()=>scope2.client.GET("/v1/team/{teamId}/connector/{connectorId}",{params:{path:{teamId:scope2.team,connectorId}}}));return data}function collectHeader(value,previous){return[...previous??[],value]}function hasConfigurationFlags(opts){return opts.baseUrl!==void 0||(opts.header?.length??0)>0||opts.headers===!1||opts.basicAuthUsername!==void 0}async function configurationFromFlags(opts,verb){if(!hasConfigurationFlags(opts))return;let clearHeaders=opts.headers===!1,headers=assertHeaders((opts.header??[]).map(parseHeaderFlag));clearHeaders&&headers.length>0&&fail(EXIT.USAGE,"USAGE_ERROR","--no-headers cannot be combined with --header."),opts.baseUrl===void 0&&fail(EXIT.USAGE,"USAGE_ERROR",`A base URL is required with any other configuration flag: re-run \`${CLI} connector ${verb}\` with --base-url.`);let basicAuth=opts.basicAuthUsername?{username:opts.basicAuthUsername,password:await basicAuthPassword(canPrompt()?{ask:()=>prompts().password("Password:")}:{})}:void 0;return stripUndefined({baseUrl:assertBaseUrl(opts.baseUrl),headers:clearHeaders?[]:headers.length>0?headers:void 0,basicAuth})}async function askBaseUrl(current){for(;;){let answer=await prompts().text(`Base URL (${BASE_URL_FORMAT})`,{...current?{initial:current}:{},allowEmpty:!0}),error51=baseUrlError(answer);if(!error51)return normalizeBaseUrl(answer);prompts().note(`\u2716 ${error51}`)}}async function askBasicAuth(){let username=await prompts().text("Username:"),password=await prompts().password("Password:");return{username,password}}async function askHeaderEntries(opts){let collected=[],taken=new Set((opts.taken??[]).map(n=>n.trim().toLowerCase()));for(;;){let name=await askHeaderName(taken,opts.hasBasicAuth),value=await prompts().password(`Value for "${name}":`,{allowEmpty:!0});if(collected.push({name,value}),taken.add(name.toLowerCase()),!await prompts().confirm("Add another header?",!1))return collected}}async function askHeaderName(taken,hasBasicAuth){for(;;){let answer=(await prompts().text("Header name:",{allowEmpty:!0})).trim(),error51=headerNameError(answer);if(error51){prompts().note(`\u2716 ${error51}`);continue}if(hasBasicAuth&&isAuthorizationHeader(answer)){prompts().note("\u2716 Basic authentication already sends an Authorization header, and the credentials replace whatever is typed here.");continue}if(taken.has(answer.toLowerCase())){prompts().note(`\u2716 Header "${answer}" was already given.`);continue}return answer}}async function askNewConfiguration(scope2,appId,opts){let fromFlags=await configurationFromFlags(opts,"create");if(fromFlags)return fromFlags;if(!canPrompt()||!await isGenericApp(scope2.client,appId)||await prompts().select("Configure this connector:",[{value:"here",label:"Here, now",hint:"a base URL and the headers it sends"},{value:"web",label:"In the web application",hint:"get a link to finish it there"}],{initial:"here"})==="web")return;let baseUrl2=await askBaseUrl(),basicAuth=await prompts().confirm("Add basic authentication?",!1)?await askBasicAuth():void 0,headers=await prompts().confirm("Add headers?",basicAuth===void 0)?await askHeaderEntries({hasBasicAuth:basicAuth!==void 0}):[];return stripUndefined({baseUrl:baseUrl2,...headers.length>0?{headers}:{},...basicAuth?{basicAuth}:{}})}function describeConfiguration(current){let names=current.headerNames??[];return[current.baseUrl?`Base URL ${current.baseUrl}`:"no base URL",current.authMethod??"no authentication",names.length===1?"1 header":`${names.length} headers`].join(" \xB7 ")}async function askConfigurationChange(current,opts){let fromFlags=await configurationFromFlags(opts,"update");if(fromFlags)return fromFlags;if(!canPrompt()||(current?prompts().note(describeConfiguration(current)):prompts().note("This connector has no configuration yet."),!await prompts().confirm(current?"Change the connector's configuration?":"Configure it now?",!current)))return;let baseUrl2=await askBaseUrl(current?.baseUrl),currentNames=current?.headerNames??[],wasBasic=current?.authMethod==="BASIC",walkable=currentNames.filter(name=>!isAuthorizationHeader(name)),headers,removed=!1;if(currentNames.length>0){let answer=await prompts().select("Headers:",[{value:"keep",label:"Keep the current headers",display:`Keep the current headers (${currentNames.join(", ")})`},{value:"replace",label:"Replace them",hint:"every value has to be given again"},{value:"remove",label:"Remove all headers",...wasBasic?{hint:"basic authentication goes with them"}:{}}],{initial:"keep"});answer==="remove"?(headers=[],removed=!0):answer==="replace"&&(prompts().note("Header values are never reported back, so a replacement asks for every value again."),headers=await askReplacementHeaders(walkable,wasBasic))}else await prompts().confirm("Add headers?",!1)&&(headers=await askHeaderEntries({hasBasicAuth:wasBasic}));let basicAuth=removed?void 0:await askCredentialsOnUpdate({wasBasic,replacingHeaders:headers!==void 0});if(!(baseUrl2===current?.baseUrl&&headers===void 0&&basicAuth===void 0))return stripUndefined({baseUrl:baseUrl2,headers,basicAuth})}async function askReplacementHeaders(currentNames,hasBasicAuth){let kept=[];for(let name of currentNames){let value=await prompts().password(`Value for "${name}" (empty removes the header):`,{allowEmpty:!0});if(value===""){prompts().note(`${name} will be removed.`);continue}kept.push({name,value})}return await prompts().confirm("Add another header?",currentNames.length===0)&&kept.push(...await askHeaderEntries({taken:kept.map(h=>h.name),hasBasicAuth})),kept}async function askCredentialsOnUpdate(opts){return opts.wasBasic&&!opts.replacingHeaders?await prompts().select("Authentication:",[{value:"keep",label:"Keep the current credentials",display:"Keep the current credentials (BASIC)"},{value:"set",label:"Set a username and password"}],{initial:"keep"})==="keep"?void 0:askBasicAuth():opts.wasBasic?(prompts().note("Replacing the headers replaces the encoded Authorization header too, so the username and password have to be given again."),await prompts().confirm("Keep basic authentication?",!0)?askBasicAuth():void 0):await prompts().confirm("Add basic authentication?",!1)?askBasicAuth():void 0}function configurationCells(config2){let names=config2.headerNames??[];return stripUndefined({baseUrl:config2.baseUrl,authMethod:config2.authMethod,headers:names.length>0?names.join(", "):"none"})}function sentConfigurationCells(config2){let names=(config2.headers??[]).map(h=>h.name);return config2.basicAuth&&names.push("Authorization (basic)"),{baseUrl:config2.baseUrl,headers:names.length>0?names.join(", "):config2.headers?"none":"unchanged"}}async function askCreateBody(scope2,opts){let appId=(await resolveParams(["app"],{team:scope2.team,app:opts.appId},{client:scope2.client,interactive:canPrompt()})).app??"",name=opts.name??await askConnectorName();return stripUndefined({appId,name,apiConnectionTypeId:opts.apiConnectionTypeId??await askOptionalType(scope2,"apiConnectionType",appId),eventListenerTypeId:opts.listenerTypeId??await askOptionalType(scope2,"listenerType",appId),genericConfiguration:await askNewConfiguration(scope2,appId,opts)})}function authorizationNote(url2,opts={}){if(isRaw())return;let lines=opts.generic?["This connector holds no credentials yet. A Generic connector is configured with a","base URL and headers rather than an authorization flow \u2014 add them in the web","application, or here with:",` ${CLI} connector update ${opts.connectorId??"<connectorId>"} --base-url \u2026 --header 'Name: value'`]:["A new connector holds no credentials yet: authorizing one needs a browser session,","so the API cannot do it and neither can this CLI."];prompts().note([...lines,url2?opts.generic?`Open ${url2} to configure it there.`:`Open ${url2} and sign in to the app to authorize it.`:"This deployment publishes no web-application URL \u2014 finish it from the Connectors page in the web app."].join(`
1331
+ `))}function conflictMessage(body){let message=body?.errorMessage;return typeof message=="string"&&message.length>0?message:void 0}function describeConnector(id,name){return name&&name!==id?`${name} (${id})`:id}function humanConnector(connector,detail=!1){let owner=connector.owner,{genericConfiguration:configuration,authorizationUrl,owner:_owner,...rest}=connector,connectionType=connector.connectionType;return{...rest,authorized:connector.authorized?"yes":"no",canUse:connector.canUse?"yes":"no",...connectionType&&typeof connectionType=="object"?{connectionType:`${connectionType.name??""} (${connectionType.id??""})`}:{},...owner&&typeof owner=="object"?{owner:personCell(owner)}:{},...detail&&owner&&typeof owner=="object"&&owner.email?{ownerEmail:owner.email}:{},...configuration?configurationCells(configuration):{},...authorizationUrl?{authorizationUrl}:{}}}async function deleteConnector(client,target,force){let{response,error:error51}=await withSpinner("Deleting connector",()=>client.DELETE("/v1/team/{teamId}/connector/{connectorId}",{params:{path:{teamId:target.team,connectorId:target.id},...force?{query:{force:"true"}}:{}}}));return{ok:response.ok,status:response.status,error:error51}}async function deleteConnectorWithConflict(client,target,opts){let forced=opts.force,result=await deleteConnector(client,target,forced),conflict=conflictMessage(result.error);result.status===400&&conflict&&!forced&&opts.interactive&&(prompts().note(`\u2716 ${conflict}`),await prompts().confirm("Delete it anyway? Every API connection and event listener using it is detached.",!1)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."),forced=!0,result=await deleteConnector(client,target,forced)),!result.ok&&(result.status===400&&conflict&&!forced&&fail(EXIT.API_ERROR,"CONNECTOR_IN_USE",conflict,{status:400,hint:"Re-run with --force to delete it anyway; every API connection and event listener using it is detached."}),apiFail(result.status,result.error))}async function confirmDeletion(scope2,target){let name=(await withSpinner("Checking the connector",()=>connectorInfo(scope2.client,scope2.team,target.id)))?.name??target.label;prompts().note(["Deleting removes the connector for everyone it was shared with, and the sharing","permissions with it. Every API connection and event listener that uses it is","detached, in every workspace \u2014 including workspaces belonging to the people it was","shared with, and --force decides only whether this request is refused first, never","how much is detached. Scripts importing those API connections fail until another","connector is attached, and nobody is emailed about any of it.","Only the owner of a connector can delete it, and authorization cannot be restored:","a replacement has to be authorized again in the web application."].join(`
1332
+ `)),await prompts().confirm(`Delete connector ${describeConnector(target.id,name)}? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")}function connectorCommand(){let connector=new Command("connector").alias("con").description("Manage connectors");return connector.command("list").description("List connectors").option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC3))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope3(globals),{data,response,error:error51}=await withSpinner("Fetching connectors",()=>scope2.client.GET("/v1/team/{teamId}/connectors",{params:{path:{teamId:scope2.team}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({connections:d.connections.map(c=>{let{authorizationUrl:_url2,...rest}=c;return humanConnector(rest)})})})}),connector.command("get").description("Get a single connector").argument("[connectorId]","Connector ID (required, interactive)").option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,GET_DOC3))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope3(globals),target=await resolveConnector(scope2,idArg),{data,response,error:error51}=await withSpinner("Fetching connector",()=>scope2.client.GET("/v1/team/{teamId}/connector/{connectorId}",{params:{path:{teamId:scope2.team,connectorId:target.id}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>humanConnector(d,!0)})}),connector.command("create").description("Create a connector").option("--team <teamId>",SCOPE_TEAM).option("--app-id <appId>",`App the connector is for, from ${CLI} app list (required unless --input, interactive)`).option("--name <name>",`Connector name, ${CONNECTOR_NAME_FORMAT}, unique among your own connectors for the same app (required unless --input, interactive)`).option("--api-connection-type-id <id>","API connection type the connector is for; a connector created without one is refused when it is attached to an API connection (optional, interactive)").option("--listener-type-id <id>","Event listener type the connector is for; event listeners attach by app, so this only labels the connector (optional, interactive)").option("--base-url <url>",`Base URL every request through the connector is sent to, ${BASE_URL_FORMAT}; only a connector of the Generic app takes a configuration (optional, interactive, required with any other configuration flag, refused for any other app)`).option("--header <name:value>","Header sent with every request, as name:value; the value is visible in your shell history and process list, so use --input to keep it out of both (optional, interactive, repeatable, requires --base-url, refused for any other app)",collectHeader).option("--basic-auth-username <username>",`Username for an Authorization: Basic header the API encodes, replacing any Authorization header passed with --header; the password is read from ${BASIC_AUTH_PASSWORD_ENV} or a masked prompt, never from a flag (optional, interactive, requires --base-url, refused for any other app)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC2))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope3(globals),rawBody;opts.input?rawBody=readInput(opts.input):opts.appId!==void 0&&opts.name!==void 0?rawBody=stripUndefined({appId:opts.appId,name:opts.name,apiConnectionTypeId:opts.apiConnectionTypeId,eventListenerTypeId:opts.listenerTypeId,genericConfiguration:await configurationFromFlags(opts,"create")}):(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",opts.appId===void 0?"--app-id is required.":"--name is required."),rawBody=await askCreateBody(scope2,opts));let parsed=validate(createBodySchema2,rawBody),body={...parsed,name:assertConnectorName(parsed.name),...parsed.genericConfiguration?{genericConfiguration:assertGenericConfiguration(parsed.genericConfiguration)}:{}},{data,response,error:error51}=await withSpinner("Creating connector",()=>scope2.client.POST("/v1/team/{teamId}/connector",{params:{path:{teamId:scope2.team}},body}));if((!response.ok||!data)&&apiFail(response.status,error51),okMutation("Connector created",data,{connectorId:data.connectorId,name:body.name,authorized:data.authorized?"yes":"no",...body.genericConfiguration?sentConfigurationCells(body.genericConfiguration):{},...data.authorizationUrl?{authorizationUrl:data.authorizationUrl}:{}}),!data.authorized){let generic=canPrompt()&&await isGenericApp(scope2.client,body.appId);authorizationNote(data.authorizationUrl,{generic,connectorId:data.connectorId})}}),connector.command("update").description("Rename a connector, or replace a Generic connector's configuration").argument("[connectorId]","Connector ID (required, interactive)").option("--team <teamId>",SCOPE_TEAM).option("--name <name>",`New connector name, ${CONNECTOR_NAME_FORMAT}, unique among your own connectors for the same app (optional, interactive, default: the current name)`).option("--base-url <url>",`Base URL every request through the connector is sent to, ${BASE_URL_FORMAT}; only a connector of the Generic app has a configuration (optional, interactive, required with any other configuration flag, refused for a connector of any other app)`).option("--header <name:value>","Header sent with every request, as name:value; replaces the whole header set, so every header the connector keeps must be given again, and the value is visible in your shell history and process list (optional, interactive, repeatable, exclusive with --no-headers, requires --base-url, refused for a connector of any other app)",collectHeader).option("--no-headers","Remove every header the connector sends, the encoded Authorization header of basic authentication included (optional, interactive, exclusive with --header, requires --base-url, refused for a connector of any other app)").option("--basic-auth-username <username>",`Username for an Authorization: Basic header the API encodes, replacing any Authorization header passed with --header and surviving --no-headers; the password is read from ${BASIC_AUTH_PASSWORD_ENV} or a masked prompt, never from a flag (optional, interactive, requires --base-url, refused for a connector of any other app)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC2))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope3(globals),target=await resolveConnector(scope2,idArg),name,configuration,previous;if(opts.input){let parsed=validate(updateBodySchema2,readInput(opts.input));name=parsed.name===void 0?void 0:assertConnectorName(parsed.name),configuration=parsed.genericConfiguration===void 0?void 0:assertGenericConfiguration(parsed.genericConfiguration)}else if(opts.name!==void 0||hasConfigurationFlags(opts)){configuration=await configurationFromFlags(opts,"update");let parsed=validate(updateBodySchema2,stripUndefined({name:opts.name,genericConfiguration:configuration}));name=parsed.name===void 0?void 0:assertConnectorName(parsed.name)}else{canPrompt()||failNothingToUpdate(["--name","--base-url with --header/--no-headers/--basic-auth-username","--input"]);let current=await fetchConnector(scope2,target.id);previous=current?.name??target.label;let generic=current?.connectionType.name===GENERIC_APP;if(name=await askRename(previous,{quiet:generic}),generic&&(configuration=await askConfigurationChange(current.genericConfiguration,opts)),name===void 0&&configuration===void 0){generic&&prompts().note("Nothing to change \u2014 the name and configuration are as they are.");return}}let body=stripUndefined({name,genericConfiguration:configuration}),{response,error:error51}=await withSpinner("Updating connector",()=>scope2.client.PUT("/v1/team/{teamId}/connector/{connectorId}",{params:{path:{teamId:scope2.team,connectorId:target.id}},body}));response.ok||apiFail(response.status,error51),okMutation("Connector updated",{updated:!0,id:target.id},{id:target.id,...name?{name}:{},...previous&&name?{previous}:{},...configuration?sentConfigurationCells(configuration):{}})}),connector.command("delete").description("Delete a connector").argument("[connectorId]","Connector ID (required, interactive)").option("--team <teamId>",SCOPE_TEAM_DESTRUCTIVE).option("--force","Delete the connector even when workspaces still use it, detaching every API connection and event listener on it (optional, interactive, API default: false)").option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC2))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope3(globals,{useSession:canPrompt()}),target=await resolveConnector(scope2,idArg);opts.yes||(canPrompt()||failNeedsYes(`connector ${target.label??target.id}`),await confirmDeletion(scope2,target)),await deleteConnectorWithConflict(scope2.client,{...target,team:scope2.team},{force:opts.force===!0,interactive:canPrompt()}),okMutation("Connector deleted",{deleted:!0,id:target.id})}),connector}var APP_LIST_DOC=defineCommandDoc("app list",{rules:["No parameters: the catalogue is the same for everyone and resolves no scope at all."],notes:["Every app with its API connection types, event listener types, event types and packages. Every ID the event-listener, api-connection and connector verbs take comes from here.","Everything is nested under connectionType rather than sitting on the app: connectionType.id is what connector list reports as a connector's type, and the rest hangs off it at connectionType.apiConnectionTypes[] and connectionType.eventListenerTypes[].eventTypes[].","The human table is the ID, the name and a count of API connection types, listener types and event types; --raw keeps everything.","The catalogue almost never changes and its IDs are needed constantly, so fetch it once per session and cache the response."]}),APP_GET_DOC=defineCommandDoc("app get",{rules:["The app is the positional argument, by ID or by name, matched without case."],notes:["The same catalogue filtered to one app, for when you want three IDs rather than thirty. There is no single-app route in the API, so this fetches the catalogue and filters locally \u2014 what it saves is reading, not a request.","Human mode lists the API connection types with their packages, and each event listener type with its own packages and its event types.","Under --raw the document is the catalogue entry untouched, and every ID is nested: the event listener types and their event types are at connectionType.eventListenerTypes[].eventTypes[], and the API connection types with their packages at connectionType.apiConnectionTypes[]. A deployment answering connectionTypes[] instead is read the same way.","A name held by two apps is refused with both IDs named; a name held by none is exit 4."]}),TEAM_LIST_DOC=defineCommandDoc("team list",{rules:["No parameters: it lists the teams you are a member of."],notes:["The one read that needs nothing resolved first, which makes it the way to find the ID every other scope chain starts from."]}),TEAM_GET_DOC=defineCommandDoc("team get",{rules:["The team is the positional argument; SR_CONNECT_CLI_TEAM and the session default still supply it."],notes:["Reports the features the team can use: features.eventQueues, which is the plan, and features.remoteWorkspace, which can also be granted per account and so answers whether you may use temporary remote workspaces in the team.","Those two fields are the only way to tell a plan refusal from a bug before making the call that gets refused."]}),TEMPLATE_LIST_DOC=defineCommandDoc("template list",{rules:["No parameters: like app list it resolves no scope at all."],notes:["The published workspace templates, most used first, with a preview URL each. The human table leaves the description out for width; --raw carries it, and the preview URL is the long form.","There is no single-template read, and no get here, the API having no endpoint for one.","A template ID goes to workspace create --source-template-id."]});function appRequired(){return`<app> is required. ${supplyHint({pass:"Pass an app ID or name"})}`}function appCommand(){let apps=new Command("app").description("Discover apps and their event listener/event types");return apps.command("list").description("List apps with their connection types, API connection types, event listener types, event types and packages").option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,APP_LIST_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),{data,response,error:error51}=await withSpinner("Fetching apps",()=>client.GET("/v1/apps"));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({apps:d.apps.map(app=>{let{connectionType:_ct,connectionTypes:_cts,...rest}=app,types=connectionTypes(app),apiConnectionTypes=types.flatMap(t=>t.apiConnectionTypes??[]),listenerTypes=types.flatMap(t=>t.eventListenerTypes??[]);return{...rest,apiConnectionTypes:apiConnectionTypes.length,listenerTypes:listenerTypes.length,eventTypes:listenerTypes.flatMap(t=>t.eventTypes??[]).length}})})})}),apps.command("get").description("Get a single app with every ID the other groups take").argument("[app]","App ID, or its name (required, interactive)").option("--explain",EXPLAIN).action(async(appArg,_opts,cmd)=>{if(explained(cmd,APP_GET_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance);appArg===void 0&&!canPrompt()&&fail(EXIT.USAGE,"USAGE_ERROR",appRequired());let{data,response,error:error51}=await withSpinner("Fetching apps",()=>client.GET("/v1/apps"));(!response.ok||!data)&&apiFail(response.status,error51);let app=await resolveApp(data.apps,appArg);ok(app,{human:()=>renderApp(app)})}),apps}async function resolveApp(apps,provided){if(provided===void 0){canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",appRequired());let choice=await prompts().select("App:",apps.map(app=>({label:app.name,value:app.id})));return apps.find(app=>app.id===choice)}let wanted=provided.trim(),byId=apps.find(app=>app.id===wanted);if(byId)return byId;let wantedName=wanted.toLowerCase(),byName=apps.filter(app=>app.name.toLowerCase()===wantedName);if(byName.length>1&&fail(EXIT.USAGE,"AMBIGUOUS_APP",`More than one app is called "${provided}".`,{hint:`Pass the ID instead: ${byName.map(app=>app.id).join(", ")}.`}),byName[0])return byName[0];fail(EXIT.NOT_FOUND,"NOT_FOUND",`No app called "${provided}".`,{hint:`List them with \`${CLI} app list\`.`})}function renderApp(app){let types=connectionTypes(app),apiConnectionTypes=types.flatMap(t=>t.apiConnectionTypes??[]),listenerTypes=types.flatMap(t=>t.eventListenerTypes??[]),sections=[renderDetail({id:app.id,name:app.name,connectionType:types[0]?`${types[0].name??""} (${types[0].id??""})`:"\u2014"})];apiConnectionTypes.length>0&&sections.push(`
1333
+ API CONNECTION TYPES`,renderTable(apiConnectionTypes.map(t=>({id:t.id,name:t.name,packages:(t.packages??[]).map(pkg=>`${pkg.name} (${pkg.id})`).join(", ")}))));for(let listener of listenerTypes){let packages=(listener.packages??[]).map(pkg=>`${pkg.name} (${pkg.id})`).join(", ");sections.push(`
1334
+ EVENT LISTENER TYPE ${listener.name} (${listener.id})`,...packages?[`PACKAGES ${packages}`]:[],renderTable((listener.eventTypes??[]).map(e=>({eventTypeId:e.id,name:e.name}))))}return sections.join(`
1335
+ `)}function teamCommand(){let teams=new Command("team").description("Discover teams you are a member of");return teams.command("list").description("List teams").option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,TEAM_LIST_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),{data,response,error:error51}=await withSpinner("Fetching teams",()=>client.GET("/v1/teams"));(!response.ok||!data)&&apiFail(response.status,error51),ok(data)}),teams.command("get").description("Get a single team").argument("[teamId]",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,TEAM_GET_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["team"],{team:idArg},{client,interactive:canPrompt(),missing:{team:`<teamId> is required. ${supplyHint({env:"SR_CONNECT_CLI_TEAM"})}`},...idArg===void 0?{}:{blame:{team:"<teamId>"}}}),{data,response,error:error51}=await withSpinner("Fetching team",()=>client.GET("/v1/team/{teamId}",{params:{path:{teamId:resolved.team??""}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data)}),teams}function templateCommand(){let templates=new Command("template").description("Discover published workspace templates");return templates.command("list").description("List published templates, most frequently used first").option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,TEMPLATE_LIST_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),{data,response,error:error51}=await withSpinner("Fetching templates",()=>client.GET("/v1/templates"));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({templates:d.templates.map(t=>({templateId:t.templateId,title:t.title,complexity:t.complexity,useCases:t.useCases.join(", "),templatePreviewUrl:t.templatePreviewUrl}))})})}),templates}var ENVIRONMENT_NAME_FORMAT="up to 30 characters, letters, digits and spaces only",MAX_ENVIRONMENT_NAME=30,ENVIRONMENT_NAME_PATTERN=/^[A-Za-z0-9 ]+$/;function normalizeEnvironmentName(name){return name.trim()}function environmentNameError(name){let normalized=normalizeEnvironmentName(name);if(!normalized)return"An environment name is required.";if(normalized.length>MAX_ENVIRONMENT_NAME)return`An environment name can be at most ${MAX_ENVIRONMENT_NAME} characters (that one is ${normalized.length}).`;if(!ENVIRONMENT_NAME_PATTERN.test(normalized))return"An environment name may contain letters, digits and spaces only."}function assertEnvironmentName(name){let error51=environmentNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_ENVIRONMENT_NAME",error51),normalizeEnvironmentName(name)}var createBodySchema3=external_exports.object({name:external_exports.string()}).strict(),updateBodySchema3=external_exports.object({name:external_exports.string()}).strict(),LIST_DOC4=defineCommandDoc("environment list",{rules:["The workspace is -w; there is no positional argument, the verb listing every environment of it."],notes:["Reports the release each environment runs, or HEAD where it follows the workspace's current state."]}),GET_DOC4=defineCommandDoc("environment get",{rules:["The environment is the positional argument, and -e names it too; the positional wins, and -e is ignored when both are given. The workspace is -w."],notes:["One environment with the release it runs. There is no per-environment field a read of the workspace would not also carry."]}),DELETE_DOC3=defineCommandDoc("environment delete",{rules:["The environment is the positional argument, and -e names it too; the positional wins. The workspace is -w.","--yes skips the confirmation, and is required without a terminal."],notes:["The workspace's default environment cannot be deleted, and which one is the default cannot be changed.","Releases that captured the environment are not altered.","The deleted environment is dropped from this shell's session defaults, along with the workspace where the record named both."]}),RELEASE_POSITIONAL_HINT="The positional argument is the release being deployed; the environment is -e.",TARGET_RELEASE_DOC=defineCommandDoc("environment target-release",{rules:["The positional argument is a release, not the environment: the environment is -e, and the release is what it is being moved to. It takes no session default of its own.","--head moves the environment back to the workspace's current state, which then follows every later edit; it and a release ID are alternatives."],notes:["There is no --yes: a terminal confirms and a script does not.",`The environment is read first, so an ask that changes nothing sends no write \u2014 --head on an environment already on HEAD, and a release ID naming the release it already runs, both answer {"updated":false,"id":"<environmentId>","reason":"already-current"} and exit 0, with a stderr note in the document's place in human mode. It is the one verb that reaches that state on the flags path as well.`,"Run inside a local copy of that environment, a note says to re-clone it: the copy now describes a state the environment no longer runs."]}),CREATE_DOC3=defineCommandDoc("environment create",{schema:createBodySchema3,body:{name:"Staging"},rules:[`name: ${ENVIRONMENT_NAME_FORMAT}; trimmed; unique within the workspace.`,"The new environment runs HEAD and starts with the default environment's parameters, each holding its default value as its value and unset where there is none; the default environment's values, and every other environment's parameters, are not copied. The workspace is -w and never a body key."]}),UPDATE_DOC3=defineCommandDoc("environment update",{schema:updateBodySchema3,body:{name:"Staging"},rules:[`name: ${ENVIRONMENT_NAME_FORMAT}; trimmed; unique within the workspace.`,"Allowed in a non-HEAD environment: the name belongs to the environment, not to what the release captured. The release itself is changed with target-release."]}),NAME_PROMPT=`Environment name (${ENVIRONMENT_NAME_FORMAT})`;async function askEnvironmentName2(initial){for(;;){let answer=await prompts().text(NAME_PROMPT,{initial}),error51=environmentNameError(answer);if(!error51)return normalizeEnvironmentName(answer);prompts().note(`\u2716 ${error51}`)}}async function resolveEnvironmentScope(globals,opts,idArg,scopeOpts={}){let client=await apiClient(globals.instance),labels={},resolved=await resolveParams(["workspace","environment"],{workspace:opts.workspace??globals.workspace,environment:idArg??opts.env??globals.env,team:opts.team??globals.team},{client,interactive:canPrompt(),useSession:scopeOpts.useSession,labels,missing:{environment:`<environmentId> is required. ${supplyHint({env:"SR_CONNECT_CLI_ENVIRONMENT"})}`},...idArg===void 0?{}:{blame:{environment:"<environmentId>"}}});return{client,workspace:resolved.workspace??"",environment:resolved.environment??"",label:labels.environment}}function describeEnvironment(id,name){return name&&name!==id?`${name} (${id})`:id}async function askRename2(current){let name=await askEnvironmentName2(current);if(current!==void 0&&name===current){prompts().note(`"${current}" is already the environment's name \u2014 nothing to change.`);return}return name}async function confirmDeletion2(scope2){let current=await withSpinner("Fetching environment",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!current.response.ok||!current.data)&&apiFail(current.response.status,current.error);let name=current.data.name;current.data.default&&fail(EXIT.USAGE,"DEFAULT_ENVIRONMENT",`"${name}" is the workspace's default environment and cannot be deleted.`,{hint:"Which environment is the default cannot be changed either \u2014 delete another environment, or the workspace."}),prompts().note(["Deleting removes the environment from the whole workspace.","Its parameters, event listener and event queue settings, scheduled trigger schedules",`and stored records stop being addressable, and it disappears from ${CLI} environment list.`,"Releases that captured it are not altered \u2014 each still runs its own snapshot.","Scripts, event listeners and event queues themselves belong to the workspace and stay."].join(`
1336
+ `)),await prompts().confirm(`Delete environment ${describeEnvironment(scope2.environment,name)}? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")}var targetBodySchema=external_exports.object({releaseId:external_exports.string().min(1).optional()}).strict(),HEAD="";function releaseName(release2){return release2?.version??"HEAD"}function releaseCell(release2){if(!release2)return"HEAD";let version2=release2.version??release2.id??"?",named=release2.label?`${version2} \u2014 ${release2.label}`:version2;return release2.id&&release2.version?`${named} (${release2.id})`:named}async function askTargetRelease(client,workspaceId,environmentName,current){let releases=await resolverChoices(client,"release",{workspace:workspaceId});if(releases.length===0){prompts().note(`\u2716 No releases in this workspace yet \u2014 nothing to target. Create one with ${CLI} release create.`);return}let currentValue=current?.id??HEAD,offered=[{value:HEAD,label:"HEAD",hint:"no release \u2014 the workspace's current configuration"},...releases].map(choice=>choice.value===currentValue?{...choice,display:`${choice.display??choice.label} (current)`}:choice),picked=await prompts().select(`Release to run in ${environmentName}:`,offered,{initial:currentValue});if(picked===currentValue){prompts().note(`${environmentName} already runs ${releaseName(current)} \u2014 nothing to change.`);return}let target=offered.find(c=>c.value===picked)?.label??picked,question=picked===HEAD?`Stop running release ${releaseName(current)} in "${environmentName}" environment and run the workspace's current configuration instead?`:current?`Target "${environmentName}" environment to run release ${target} instead of ${releaseName(current)}?`:`Target "${environmentName}" environment to run release ${target}?`;return await prompts().confirm(question,!1)||fail(EXIT.CANCELLED,"CANCELLED","Cancelled."),picked===HEAD?{body:{},label:"HEAD"}:{body:{releaseId:picked},label:target}}function environmentCommand(){let env=new Command("environment").alias("env").description("Manage workspace environments");return env.command("list").description("List environments in a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LIST_DOC4))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["workspace"],{workspace:opts.workspace??globals.workspace,team:opts.team??globals.team},{client,interactive:canPrompt()}),{data,response,error:error51}=await withSpinner("Fetching environments",()=>client.GET("/v1/workspace/{workspaceId}/environments",{params:{path:{workspaceId:resolved.workspace??""}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({environments:d.environments.map(e=>({...e,release:releaseCell(e.release)}))})})}),env.command("create").description("Create an environment in a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--name <name>",`Environment name, ${ENVIRONMENT_NAME_FORMAT}, unique within the workspace (required unless --input, interactive)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC3))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),workspaceId=(await resolveParams(["workspace"],{workspace:opts.workspace??globals.workspace,team:opts.team??globals.team},{client,interactive:canPrompt()})).workspace??"",rawBody;opts.input?rawBody=readInput(opts.input):(opts.name===void 0&&!canPrompt()&&fail(EXIT.USAGE,"USAGE_ERROR","--name is required."),rawBody={name:opts.name??await askEnvironmentName2()});let body={name:assertEnvironmentName(validate(createBodySchema3,rawBody).name)},{data,response,error:error51}=await withSpinner("Creating environment",()=>client.POST("/v1/workspace/{workspaceId}/environment",{params:{path:{workspaceId}},body}));(!response.ok||!data)&&apiFail(response.status,error51),okMutation("Environment created",data,data)}),env.command("get").description("Get a single environment of a workspace").argument("[environmentId]",SCOPE_ENVIRONMENT).option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT_BESIDE_POSITIONAL).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,GET_DOC4))return;let globals=cmd.optsWithGlobals(),scope2=await resolveEnvironmentScope(globals,opts,idArg),{data,response,error:error51}=await withSpinner("Fetching environment",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({...d,default:d.default?"yes":"no",release:releaseCell(d.release)})})}),env.command("update").description("Rename an environment").argument("[environmentId]",SCOPE_ENVIRONMENT).option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT_BESIDE_POSITIONAL).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--name <name>",`New environment name, ${ENVIRONMENT_NAME_FORMAT}, unique within the workspace (required unless --input, interactive)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC3))return;let globals=cmd.optsWithGlobals(),scope2=await resolveEnvironmentScope(globals,opts,idArg),name,previous;if(opts.input)name=assertEnvironmentName(validate(updateBodySchema3,readInput(opts.input)).name);else if(opts.name!==void 0)name=assertEnvironmentName(validate(updateBodySchema3,{name:opts.name}).name);else{canPrompt()||failNothingToUpdate(["--name","--input"]);let info=scope2.label?void 0:await withSpinner("Checking the environment",()=>environmentInfo(scope2.client,scope2.workspace,scope2.environment));previous=scope2.label??info?.name;let answer=await askRename2(previous);if(answer===void 0)return;name=answer}let{response,error:error51}=await withSpinner("Renaming environment",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}},body:{name}}));response.ok||apiFail(response.status,error51),okMutation("Environment updated",{updated:!0,id:scope2.environment},{id:scope2.environment,name,...previous?{previous}:{}})}),env.command("delete").description("Delete an environment from the workspace").argument("[environmentId]",SCOPE_ENVIRONMENT_DESTRUCTIVE).option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE_DESTRUCTIVE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT_BESIDE_POSITIONAL_DESTRUCTIVE).option("--team <teamId>",SCOPE_TEAM_FILTER_DESTRUCTIVE).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC3))return;let globals=cmd.optsWithGlobals(),scope2=await resolveEnvironmentScope(globals,opts,idArg,{useSession:canPrompt()});opts.yes||(canPrompt()||failNeedsYes(`environment ${scope2.environment}`),await confirmDeletion2(scope2));let{response,error:error51}=await withSpinner("Deleting environment",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));response.ok||apiFail(response.status,error51),forgetScopeValue("environment",scope2.environment).length>0&&prompts().note(`Removed the deleted environment from this shell's session defaults (${CLI} cli set-session to store another).`),okMutation("Environment deleted",{deleted:!0,id:scope2.environment})}),env.command("target-release").description("Change which release an environment runs, or move it back to HEAD").argument("[releaseId]","Release to run in the environment; it must already exist in the specified workspace (required unless --head, interactive, exclusive with --head)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--head","Run the workspace's current configuration, deploying no release (optional, interactive, exclusive with releaseId)").option("--explain",EXPLAIN).action(async(releaseId,opts,cmd)=>{if(explained(cmd,TARGET_RELEASE_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance);releaseId&&opts.head&&fail(EXIT.USAGE,"USAGE_ERROR","A release ID and --head cannot be combined.",{hint:RELEASE_POSITIONAL_HINT});let labels={},resolved=await resolveParams(["workspace","environment"],{workspace:opts.workspace??globals.workspace,environment:opts.env??globals.env,team:opts.team??globals.team},{client,interactive:canPrompt(),labels}),workspaceId=resolved.workspace??"",environmentId=resolved.environment??"";releaseId!==void 0&&releaseId===environmentId&&fail(EXIT.USAGE,"USAGE_ERROR","That is the environment's own ID, not a release.",{hint:`${RELEASE_POSITIONAL_HINT} \`${CLI} release list -w ${workspaceId}\` names them.`});let body,environmentName=labels.environment??environmentId,previous,targetLabel;if(releaseId||opts.head){let info=await withSpinner("Checking the environment",()=>environmentInfo(client,workspaceId,environmentId)),current=info?.release?.id;if(info&&(opts.head?current===void 0:current===releaseId)){let named=labels.environment??info.name??environmentId,message=opts.head?`${named} already runs HEAD \u2014 nothing to change.`:`${named} already runs release ${releaseName(info.release)} \u2014 nothing to change.`;ok({updated:!1,id:environmentId,reason:"already-current"},{human:()=>message});return}body=validate(targetBodySchema,stripUndefined({releaseId}))}else{canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR","<releaseId> is required. Pass a release ID, or --head to run the workspace's current configuration.");let info=await withSpinner("Checking the environment",()=>environmentInfo(client,workspaceId,environmentId));environmentName=labels.environment??info?.name??environmentId;let answer=await askTargetRelease(client,workspaceId,environmentName,info?.release);if(!answer)return;body=answer.body,targetLabel=answer.label,previous=releaseName(info?.release)}let{response,error:error51}=await withSpinner("Setting the environment's release",()=>client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/release",{params:{path:{workspaceId,environmentId}},body}));response.ok||apiFail(response.status,error51),noteRedeployed({workspaceId,environmentId},body.releaseId?`it now runs release ${targetLabel??body.releaseId}`:"it now runs HEAD"),okMutation("Environment release set",{updated:!0,id:environmentId},{environment:environmentName===environmentId?environmentId:`${environmentName} (${environmentId})`,release:body.releaseId?targetLabel?`${targetLabel} (${body.releaseId})`:body.releaseId:"HEAD \u2014 no release deployed",...previous?{previous}:{}})}),env}var PARAM_TYPES=["TEXT","PASSWORD","NUMBER","BOOLEAN","DATE","MULTILINE_TEXT","SINGLE_CHOICE","MULTIPLE_CHOICES","LIST","MAP","FOLDER"],TYPE_CHOICES=PARAM_TYPES.map(t=>({value:t,label:t})),COLLECTION_TYPES=new Set(["SINGLE_CHOICE","MULTIPLE_CHOICES","LIST","MAP"]),paramValue=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.array(external_exports.string()),external_exports.record(external_exports.string(),external_exports.string())]),choiceSchema=external_exports.object({label:external_exports.string().min(1),value:external_exports.string().optional()}).strict(),editShape={key:external_exports.string().min(1),required:external_exports.boolean().optional(),description:external_exports.string().optional(),defaultValue:paramValue.optional(),value:paramValue.optional(),parentId:external_exports.string().optional(),position:external_exports.number().int().min(0).optional(),masked:external_exports.boolean().optional(),choices:external_exports.array(choiceSchema).optional()},createBodySchema4=external_exports.object({...editShape,type:external_exports.enum(PARAM_TYPES)}).strict(),updateBodySchema4=external_exports.object(editShape).strict(),MAX_PARAMETER_KEY=50,PARAMETER_KEY_CHARSET=/^[A-Za-z0-9_]+$/,PARAMETER_KEY_FORMAT=`letters, digits and underscores only, no spaces, up to ${MAX_PARAMETER_KEY} characters, and unique among its siblings`,MAX_PARAMETER_DESCRIPTION=2e3;function assertParameterKey(key){let trimmed=key.trim();return trimmed||fail(EXIT.USAGE,"INVALID_PARAMETER_KEY","A parameter key is required."),trimmed.length>MAX_PARAMETER_KEY&&fail(EXIT.USAGE,"INVALID_PARAMETER_KEY",`A parameter key can be at most ${MAX_PARAMETER_KEY} characters (that one is ${trimmed.length}).`),PARAMETER_KEY_CHARSET.test(trimmed)||fail(EXIT.USAGE,"INVALID_PARAMETER_KEY",`Use letters, digits and underscores only, no spaces \u2014 '${key}' has a character the API refuses.`),trimmed}function assertParameterBody(body){return body.key!==void 0&&(body.key=assertParameterKey(body.key)),body.description!==void 0&&body.description.length>MAX_PARAMETER_DESCRIPTION&&fail(EXIT.USAGE,"INVALID_PARAMETER_DESCRIPTION",`A parameter description can be at most ${MAX_PARAMETER_DESCRIPTION} characters (that one is ${body.description.length}).`),body}var VALUE_SHAPES_RULE='value and defaultValue (--default-value as a flag) follow the type: a string for TEXT, PASSWORD, DATE and MULTILINE_TEXT, a number for NUMBER, a boolean for BOOLEAN, one of the choice values for SINGLE_CHOICE, an array of strings for MULTIPLE_CHOICES and LIST, an object of string keys and string values for MAP; a FOLDER takes neither. The flags carry strings only, so a SINGLE_CHOICE, MULTIPLE_CHOICES, LIST or MAP value is reachable through --input alone. "" is sent as written rather than omitted, where --value "" and --default-value "" instead drop the key from the body, and are exit 2 VALUE_REQUIRED on a required parameter or a BOOLEAN.',DEFAULT_VALUE_PURPOSE="the value the parameter starts with in a new environment and in a copy of the workspace",DEFAULT_VALUE_NOTE="A default value is what the parameter starts with when a new environment is created and when the workspace is copied; the value itself is not carried over to either, and a parameter with no default starts unset, required or not. Both copy from the default environment alone, so a parameter created in any other environment is carried nowhere and its default value is never used. It is not read at runtime: an unset value stays unset.",CHOICES_RULE='choices: [{label, value}] for SINGLE_CHOICE and MULTIPLE_CHOICES only, and reachable through --input alone, there being no flag for it; label is required and is what is shown, value is optional and is what a selection stores, the label being used when it is left out, and value and defaultValue must name choices that exist. A required choice parameter must end up holding at least one choice, nothing being selectable from an empty set: an absent or empty list is refused with 400 "choices are required for a required SINGLE_CHOICE parameter, for key: <key>." \u2014 the type name being the one sent, and the sentence ending " (folder <folderKey>)." for a parameter inside a folder. A choice parameter that is not required is accepted with no choices at all. An unknown key inside a choice is refused rather than dropped.',DESCRIPTION_RULE=`description: free text, up to ${MAX_PARAMETER_DESCRIPTION} characters.`,CREATE_REQUIRED_RULE="required: a required parameter of a choice, LIST or MAP type must carry a non-empty value (VALUE_REQUIRED, exit 2); ignored for BOOLEAN and FOLDER, which are always stored not required.",UPDATE_REQUIRED_RULE="required (--required and --optional as flags): omitted, the current value is kept rather than cleared. A required parameter of a choice, LIST or MAP type is refused without a non-empty value when the update comes from flags (VALUE_REQUIRED, exit 2), while a body given here is sent as written and the API stores a required parameter with no value; ignored for BOOLEAN and FOLDER, which are always stored not required.",MASKED_RULE="masked applies to TEXT only and is ignored for every other type.",UPDATE_MASKED_RULE="masked applies to TEXT only and is ignored for every other type; omitted, the current value is kept rather than cleared. --masked and --unmasked as flags.",POSITION_RULE="position: index among the siblings, a whole number from 0, where 0 = top; the siblings after it shift down.",LIST_DOC5=defineCommandDoc("environment-parameter list",{rules:["The workspace is -w and the environment -e; there is no positional argument."],notes:["The whole tree, indented in human mode. A PASSWORD value shows as [REDACTED] and is never reported in either mode.","The POSITION column is the position among siblings, which is what --position on create and update refers to."]}),DELETE_DOC4=defineCommandDoc("environment-parameter delete",{rules:["The parameter is the positional argument; the workspace is -w and the environment -e, which is the environment the parameter belongs to.","--yes skips the confirmation, and is required without a terminal."],notes:["Deleting a FOLDER deletes everything inside it.","Nothing else is renumbered: the gap the parameter leaves in its sibling positions stays."]}),CREATE_DOC4=defineCommandDoc("environment-parameter create",{schema:createBodySchema4,body:{key:"JIRA_PROJECT",type:"SINGLE_CHOICE",value:"OPS",defaultValue:"OPS",description:"Project key the scripts write to",required:!0,masked:!1,parentId:"<parameterId>",position:0,choices:[{label:"Operations",value:"OPS"},{label:"Development",value:"DEV"}]},rules:[`key: the name scripts read the parameter by; ${PARAMETER_KEY_FORMAT}.`,`type: ${PARAM_TYPES.join(", ")}; immutable once created.`,VALUE_SHAPES_RULE,CHOICES_RULE,CREATE_REQUIRED_RULE,MASKED_RULE,'parentId (--parent-id as a flag): the FOLDER parameter to create it under. It must name a parameter of type FOLDER in the same environment \u2014 an unknown ID is exit 4 "Parent parameter not found." and any other type is exit 1 BAD_REQUEST "Parent parameter must be a folder." \u2014 and a FOLDER cannot be given one, folders not nesting ("Nested folders are not supported.").',`${POSITION_RULE} Omitted, the parameter is appended to its sibling group.`,DESCRIPTION_RULE],notes:[DEFAULT_VALUE_NOTE]}),UPDATE_DOC4=defineCommandDoc("environment-parameter update",{schema:updateBodySchema4,body:{key:"JIRA_PROJECT",value:"OPS",defaultValue:"OPS",description:"Project key the scripts write to",required:!0,masked:!1,parentId:"<parameterId>",position:0,choices:[{label:"Operations",value:"OPS"},{label:"Development",value:"DEV"}]},rules:["The body replaces the parameter: key is required, and every other key that is omitted is cleared, bar four that are kept \u2014 position, required, masked, and a PASSWORD value; send back everything else that should stay. A parameter belongs to the environment in the path alone, so a non-HEAD environment accepts the edit like any other.",`key: ${PARAMETER_KEY_FORMAT}.`,"type cannot be changed and is not a key here.",VALUE_SHAPES_RULE,`${CHOICES_RULE} Replacing them must keep every choice the current value and defaultValue select, or the API refuses the update. The list is replaced rather than merged, so omitting choices on a parameter whose required stays true empties the set and is refused the same way \u2014 send the choices back to keep them.`,'A PASSWORD value is never read back and never cleared: omitting it keeps the stored secret, and so does "". Send a new one to replace it; there is no way to empty one.',UPDATE_REQUIRED_RULE,UPDATE_MASKED_RULE,'parentId (--parent-id as a flag) moves the parameter under another FOLDER parameter, and omitting it moves the parameter to the root. The same two checks the create makes, and both are made before the parameter in the path is looked up: an unknown ID is exit 4 "Parent parameter not found.", any other type exit 1 BAD_REQUEST "Parent parameter must be a folder.". A FOLDER cannot be moved under anything ("Nested folders are not supported."). Left out of a body it is cleared like the rest; left out as a flag the current folder is kept, the flags path carrying every omitted field forward.',`${POSITION_RULE} Omitted, the current position is kept.`,DESCRIPTION_RULE],notes:[DEFAULT_VALUE_NOTE]});function withScope2(cmd,opts={}){return cmd.option("-w, --workspace <workspaceId>",opts.destructive?SCOPE_WORKSPACE_DESTRUCTIVE:SCOPE_WORKSPACE).option("-e, --env <environmentId>",opts.destructive?SCOPE_ENVIRONMENT_DESTRUCTIVE:SCOPE_ENVIRONMENT).option("--team <teamId>",opts.destructive?SCOPE_TEAM_FILTER_DESTRUCTIVE:SCOPE_TEAM_FILTER)}async function resolveScope4(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,workspace:resolved.workspace??"",environment:resolved.environment??""}}async function resolveParameterId(scope2,provided){return provided?assertResourceId(provided,"parameterId"):(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<parameterId> is required. ${supplyHint()}`),(await resolveParams(["parameter"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0})).parameter??"")}function decodeNewlines(type,v2){return type==="MULTILINE_TEXT"&&v2!==void 0?v2.replaceAll("\\n",`
1337
+ `):v2}function findParam(params,id){for(let p of params){if(p.id===id)return p;if(p.children?.length){let hit=findParam(p.children,id);if(hit)return hit}}}function findParentId(params,id,parent){for(let p of params){if(p.id===id)return parent;if(p.children?.length){let hit=findParentId(p.children,id,p.id);if(hit!==void 0)return hit}}}async function fetchParameters(scope2){let{data,response,error:error51}=await withSpinner("Fetching parameters",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/parameters",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));return(!response.ok||!data)&&apiFail(response.status,error51),data.parameters}function collectFolderChoices(params,prefix=""){return params.flatMap(p=>{if(p.type!=="FOLDER")return[];let path2=prefix?`${prefix} / ${p.key}`:p.key;return[{value:p.id,label:path2,hint:p.id},...collectFolderChoices(p.children??[],path2)]})}var emptyToUndefined=v2=>v2===""?void 0:v2;function unsettable(type,required2){return!required2&&type!=="BOOLEAN"}var noSelection=v2=>v2==null||v2===""?!0:Array.isArray(v2)?v2.length===0:typeof v2=="object"?Object.keys(v2).length===0:!1,collectionNoun=type=>type==="LIST"?"item":type==="MAP"?"key-value pair":"selection";function assertRequiredValue(type,required2,value){!type||!COLLECTION_TYPES.has(type)||!required2||!noSelection(value)||fail(EXIT.USAGE,"VALUE_REQUIRED",`A required ${type} parameter needs at least one ${collectionNoun(type)} \u2014 pass a value via --input.`)}async function editUntilNonEmpty(edit,type){for(;;){let next=await edit();if(!noSelection(next))return next;prompts().note(`\u2716 A required ${type} parameter needs at least one ${collectionNoun(type)}.`)}}function assertCollectionValueFlags(type,value,defaultValue){if(!type||!COLLECTION_TYPES.has(type))return;let flag=value!==void 0&&value!==""?"--value":defaultValue!==void 0&&defaultValue!==""?"--default-value":void 0;flag&&fail(EXIT.USAGE,"VALUE_NEEDS_INPUT",`${flag} cannot carry a ${type} value: the flags hold strings only, and a SINGLE_CHOICE, MULTIPLE_CHOICES, LIST or MAP parameter (its choices included) is created through --input.`,{hint:"Run the verb with --explain to see the body."})}function clearEmptyFlag(v2,type,required2,flag){if(v2!=="")return v2;unsettable(type,required2)||fail(EXIT.USAGE,"VALUE_REQUIRED",type==="BOOLEAN"?`${flag} cannot be empty for a BOOLEAN parameter \u2014 pass true or false.`:`${flag} cannot be empty for a required parameter.`)}function noteDefaultValuePurpose(){prompts().note(`\u2139 A default value is ${DEFAULT_VALUE_PURPOSE}, both seeded from the default environment; it is not read at runtime.`)}async function promptTypedValue(type,label,allowEmpty=!1){let hints=(...extra)=>{let all=allowEmpty?[...extra,"empty to unset"]:extra;return all.length>0?`${label} (${all.join(", ")})`:label};return type==="PASSWORD"?emptyToUndefined(await prompts().password(hints(),{allowEmpty})):type==="BOOLEAN"?prompts().select(label,[{value:"true",label:"true"},{value:"false",label:"false"}]):type==="MULTILINE_TEXT"?decodeNewlines(type,emptyToUndefined(await prompts().text(hints("use \\n for a new line"),{allowEmpty}))):emptyToUndefined(await prompts().text(type==="DATE"?hints("YYYY-MM-DD"):hints(),{allowEmpty}))}function parseChoice(raw){let idx=raw.indexOf("|"),label=(idx===-1?raw:raw.slice(0,idx)).trim(),value=idx===-1?"":raw.slice(idx+1).trim();return label?stripUndefined({label,value:value||void 0}):null}function parseMapEntry(raw){let idx=raw.indexOf("|");return idx<=0||idx===raw.length-1?null:[raw.slice(0,idx).trim(),raw.slice(idx+1).trim()]}var asStringArray=v2=>Array.isArray(v2)?v2.map(String):[],asMapRecord=v2=>v2&&typeof v2=="object"&&!Array.isArray(v2)?{...v2}:{};async function addChoices(out){for(;;){let parsed=parseChoice(await prompts().text('Choice ("label|value" \u2014 value optional)'));if(parsed?out.push(parsed):prompts().note("\u2716 A label is required \u2014 skipped."),!await prompts().confirm("Add another choice?",!1))break}}async function addMapEntries(map2,d=""){for(;;){let parsed=parseMapEntry(await prompts().text('Entry ("key|value")'));if(parsed?map2[parsed[0]]=parsed[1]:prompts().note('\u2716 Expected "key|value" with both parts \u2014 skipped.'),!await prompts().confirm(`Add another ${d}pair?`,!1))break}}async function collectChoices(){if(!await prompts().confirm("Add a choice?",!1))return;let out=[];return await addChoices(out),out.length>0?out:void 0}async function collectMapValue(forDefault=!1){let d=forDefault?"default ":"";if(!await prompts().confirm(`Add a ${d}key-value pair?`,!1))return;let map2={};return await addMapEntries(map2,d),Object.keys(map2).length>0?map2:void 0}async function addListItems(items,d=""){for(;items.push(await prompts().text("List item")),!!await prompts().confirm(`Add another ${d}item?`,!1););}async function collectListItems(forDefault=!1){let d=forDefault?"default ":"";if(!await prompts().confirm(`Add a ${d}list item?`,!1))return;let items=[];return await addListItems(items,d),items.length>0?items:void 0}async function pickRemovals(noun,items,label,warning){if(items.length===0||!await prompts().confirm(`Remove any ${noun}?`,!1))return items;warning&&prompts().note(`\u26A0 ${warning}`);let picked=await prompts().multiselect(`Remove which ${noun}? (space to pick, enter to keep all)`,items.map((item,i)=>({value:String(i),label:label(item)}))),removed=new Set(picked.map(Number));return items.filter((_2,i)=>!removed.has(i))}async function editChoices(current,removalWarning){let list=(current??[]).map(c=>stripUndefined({label:c.label,value:c.value})),kept=await pickRemovals("choices",list,c=>c.value?`${c.label} (${c.value})`:c.label,removalWarning);return await prompts().confirm("Add choices?",!1)&&await addChoices(kept),kept.length>0?kept:void 0}async function editListItems(current){let kept=await pickRemovals("items",asStringArray(current),item=>item);return await prompts().confirm("Add items?",!1)&&await addListItems(kept),kept.length>0?kept:void 0}async function editMapEntries(current){let kept=await pickRemovals("pairs",Object.entries(asMapRecord(current)),([key,value])=>`[${key}, ${value}]`),map2=Object.fromEntries(kept);return await prompts().confirm("Add key-value pairs?",!1)&&await addMapEntries(map2),Object.keys(map2).length>0?map2:void 0}var UNSET_PICK="\0unset-pick";function choiceValue(c){return c.value??c.label}function pruneSelection(value,choices){if(value==null)return{value:void 0,dropped:[]};let allowed=new Set((choices??[]).map(choiceValue));if(Array.isArray(value)){let all=value.map(String),kept=all.filter(v2=>allowed.has(v2));return{value:kept.length>0?kept:void 0,dropped:all.filter(v2=>!allowed.has(v2))}}let single=String(value);return allowed.has(single)?{value,dropped:[]}:{value:void 0,dropped:[single]}}async function pickChoiceSelection(multiple,choices,label,allowEmpty=!1,current){let options=choices.map(c=>({value:choiceValue(c),label:c.label,hint:c.value}));if(!multiple){let unset={value:UNSET_PICK,label:"(unset)"},picked=await prompts().select(label,allowEmpty?[...options,unset]:options);return picked===UNSET_PICK?void 0:picked}let known=new Set(options.map(o=>o.value)),initial=asStringArray(current).filter(v2=>known.has(v2));for(;;){let picked=await prompts().multiselect(`${label} (space to pick, enter to confirm${allowEmpty?" \u2014 none unsets it":""})`,options,{initial});if(picked.length>0)return picked;if(allowEmpty)return;prompts().note("\u2716 Pick at least one \u2014 this parameter must hold a value.")}}async function fillCreateBody(scope2,opts){let key=opts.key??await prompts().text("Parameter key"),type=opts.type??await prompts().select("Parameter type",TYPE_CHOICES),isFolder=type==="FOLDER",scalarish=!isFolder&&!COLLECTION_TYPES.has(type),required2=isFolder?void 0:opts.required??await prompts().confirm("Required?",!1),description=opts.description;description===void 0&&await prompts().confirm("Add a description?",!1)&&(description=await prompts().text("Description"));let allowEmpty=unsettable(type,required2===!0),value=decodeNewlines(type,clearEmptyFlag(opts.value,type,required2===!0,"--value")),choices;if(value===void 0&&!isFolder)if(type==="SINGLE_CHOICE"||type==="MULTIPLE_CHOICES"){for(choices=await collectChoices();required2===!0&&!(choices&&choices.length>0);)prompts().note(`\u2716 A required ${type} parameter needs at least one choice.`),choices=await collectChoices();choices&&choices.length>0&&(required2===!0?(prompts().note("\u2139 A required choice parameter needs a selected value."),value=await pickChoiceSelection(type==="MULTIPLE_CHOICES",choices,"Value")):await prompts().confirm("Set a value now?",!1)&&(value=await pickChoiceSelection(type==="MULTIPLE_CHOICES",choices,"Value")))}else if(type==="MAP"||type==="LIST"){let collect4=()=>type==="MAP"?collectMapValue():collectListItems();value=required2===!0?await editUntilNonEmpty(collect4,type):await collect4()}else await prompts().confirm("Set a value now?",!1)&&(value=await promptTypedValue(type,"Value",allowEmpty));let masked=opts.masked;masked===void 0&&type==="TEXT"&&(masked=await prompts().confirm("Mask the value?",!1));let defaultValue=decodeNewlines(type,clearEmptyFlag(opts.defaultValue,type,required2===!0,"--default-value"));defaultValue===void 0&&!isFolder&&(type==="SINGLE_CHOICE"||type==="MULTIPLE_CHOICES"?choices&&choices.length>0&&(noteDefaultValuePurpose(),await prompts().confirm("Set a default value?",!1)&&(defaultValue=await pickChoiceSelection(type==="MULTIPLE_CHOICES",choices,"Default value"))):type==="MAP"?(noteDefaultValuePurpose(),defaultValue=await collectMapValue(!0)):type==="LIST"?(noteDefaultValuePurpose(),defaultValue=await collectListItems(!0)):scalarish&&(noteDefaultValuePurpose(),await prompts().confirm("Set a default value now?",!1)&&(defaultValue=await promptTypedValue(type,"Default value",allowEmpty))));let parentId=opts.parentId;if(parentId===void 0&&!isFolder){let folders=collectFolderChoices(await fetchParameters(scope2));folders.length>0&&await prompts().confirm("Place this parameter inside a folder?",!1)&&(parentId=await prompts().select("Folder",folders))}return stripUndefined({key,type,required:required2,description,value,defaultValue,choices,parentId,position:opts.position===void 0?void 0:Number(opts.position),masked})}function requiredFromFlags(opts){return switchFromFlags(opts,"required","optional")}function stripChoiceIds(choices){return choices?.map(c=>stripUndefined({label:c.label,value:c.value}))}function currentHint(v2){let s=formatParamCell(v2);return s===""?"(currently unset)":`(currently ${s})`}async function fillUpdateBody(current,folders,currentParentId){let type=current.type,isFolder=type==="FOLDER",body={key:current.key},changeValue=(base,v2)=>prompts().confirm(type==="PASSWORD"?`${base}?`:`${base}? ${currentHint(v2)}`,!1);if(await prompts().confirm(`Change the key? (currently "${current.key}")`,!1)&&(body.key=await prompts().text("New key")),isFolder||(body.required=current.required,await prompts().confirm(`Change "required"? (currently ${current.required})`,!1)&&(body.required=await prompts().confirm("Required?",current.required))),body.description=current.description,await prompts().confirm(`Change the description? ${currentHint(current.description)}`,!1)&&(body.description=await prompts().text("Description")),isFolder)return{body:stripUndefined(body)};let allowEmpty=unsettable(type,body.required===!0),mustHaveValue=body.required===!0&&COLLECTION_TYPES.has(type);if(type==="TEXT"?body.masked=await prompts().confirm(`Mask the value? (currently ${!!current.masked})`,!!current.masked):body.masked=current.masked,body.value=current.value,body.defaultValue=current.defaultValue,type==="SINGLE_CHOICE"||type==="MULTIPLE_CHOICES"){let multiple=type==="MULTIPLE_CHOICES",choices=stripChoiceIds(current.choices),value=current.value,defaultValue=current.defaultValue;if(await prompts().confirm("Change the choices?",!1)){let hasSelection=!noSelection(value)||!noSelection(defaultValue);choices=await editChoices(current.choices,hasSelection?"A removed choice is dropped from the value and the default value automatically.":void 0);let prunedValue=pruneSelection(value,choices),prunedDefault=pruneSelection(defaultValue,choices);value=prunedValue.value,defaultValue=prunedDefault.value,prunedValue.dropped.length>0&&prompts().note(`\u26A0 Dropped from the value: ${prunedValue.dropped.join(", ")}.`),prunedDefault.dropped.length>0&&prompts().note(`\u26A0 Dropped from the default value: ${prunedDefault.dropped.join(", ")}.`)}for(;mustHaveValue&&!(choices&&choices.length>0);)prompts().note(`\u2716 A required ${type} parameter needs at least one choice.`),choices=await editChoices(current.choices);body.choices=choices,body.value=value,body.defaultValue=defaultValue,choices&&choices.length>0?(mustHaveValue&&noSelection(body.value)?(prompts().note("\u2139 A required choice parameter needs a selected value."),body.value=await pickChoiceSelection(multiple,choices,"Value",!1,value)):await changeValue("Change the value",value)&&(body.value=await pickChoiceSelection(multiple,choices,"Value",allowEmpty,value)),noteDefaultValuePurpose(),await changeValue("Change the default value",defaultValue)&&(body.defaultValue=await pickChoiceSelection(multiple,choices,"Default value",allowEmpty,defaultValue))):(body.value=void 0,body.defaultValue=void 0)}else if(type==="LIST"||type==="MAP"){let edit=v2=>type==="LIST"?editListItems(v2):editMapEntries(v2);mustHaveValue&&noSelection(body.value)?(prompts().note(`\u2139 A required ${type} parameter needs at least one ${collectionNoun(type)}.`),body.value=await editUntilNonEmpty(()=>edit(current.value),type)):await changeValue("Change the value",current.value)&&(body.value=mustHaveValue?await editUntilNonEmpty(()=>edit(current.value),type):await edit(current.value)),noteDefaultValuePurpose(),await changeValue("Change the default value",current.defaultValue)&&(body.defaultValue=await edit(current.defaultValue))}else await changeValue("Change the value",current.value)&&(body.value=await promptTypedValue(type,"Value",allowEmpty)),noteDefaultValuePurpose(),await changeValue("Change the default value",current.defaultValue)&&(body.defaultValue=await promptTypedValue(type,"Default value",allowEmpty));if(!currentParentId)folders.length>0&&await prompts().confirm("Move into a folder?",!1)&&(body.parentId=await prompts().select("Folder",folders));else if(body.parentId=currentParentId,await prompts().confirm("Move out of the folder?",!1))body.parentId=void 0;else{let others=folders.filter(f2=>f2.value!==currentParentId);others.length>0&&await prompts().confirm("Move to another folder?",!1)&&(body.parentId=await prompts().select("Folder",others))}return{body:stripUndefined(body)}}function buildUpdateBody2(current,opts,currentParentId){let required2=requiredFromFlags(opts)??current.required,overlay=(flag,passed,carriedValue)=>passed===void 0?carriedValue:clearEmptyFlag(passed,current.type,required2,flag);return stripUndefined({key:opts.key??current.key,required:required2,description:opts.description??current.description,defaultValue:overlay("--default-value",opts.defaultValue,current.defaultValue),value:overlay("--value",opts.value,current.value),masked:switchFromFlags(opts,"masked","unmasked")??current.masked,choices:current.choices?.length?stripChoiceIds(current.choices):void 0,parentId:opts.parentId??currentParentId,position:opts.position===void 0?void 0:Number(opts.position)})}function sameBody(a,b2){let stable=o=>JSON.stringify(Object.fromEntries(Object.entries(o).sort(([x2],[y2])=>x2.localeCompare(y2))));return stable(a)===stable(b2)}function environmentParameterCommand(){let param=new Command("environment-parameter").alias("ep").description("Manage workspace environment parameters");return withScope2(param.command("list").description("List parameters in a workspace environment")).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC5))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope4(globals),{data,response,error:error51}=await withSpinner("Fetching parameters",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/parameters",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({parameters:flattenForHuman(d.parameters)})})}),withScope2(param.command("create").description("Create an environment parameter")).option("--key <key>","Parameter key (required unless --input, interactive)").option("--type <type>",`Parameter type: ${PARAM_TYPES.join(", ")} (required unless --input, interactive)`).option("--value <value>","Parameter value as a string; a SINGLE_CHOICE, MULTIPLE_CHOICES, LIST or MAP value goes through --input (required for a required parameter and for BOOLEAN, optional otherwise, interactive)").option("--default-value <value>",`Default value, ${DEFAULT_VALUE_PURPOSE}; use --input for complex types (optional, interactive)`).option("--description <text>","Parameter description (optional, interactive)").option("--required","Mark the parameter required (optional, interactive, API default: false, ignored for BOOLEAN and FOLDER)").option("--masked","Mask the value (optional, interactive for TEXT only, ignored for other types)").option("--parent-id <id>","Parent FOLDER parameter ID (optional, interactive when the environment has folders, refused for FOLDER)").option("--position <n>","Position among the parameter's siblings, 0 = top; inserting shifts the siblings after it (optional, API default: last in the sibling group)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC4))return;let globals=cmd.optsWithGlobals();opts.input||assertCollectionValueFlags(opts.type,opts.value,opts.defaultValue);let scope2=await resolveScope4(globals),rawBody=opts.input?readInput(opts.input):!opts.key&&canPrompt()?await fillCreateBody(scope2,opts):stripUndefined({key:opts.key,type:assertChoice("--type",opts.type,PARAM_TYPES),value:decodeNewlines(opts.type,clearEmptyFlag(opts.value,opts.type,opts.required===!0,"--value")),defaultValue:decodeNewlines(opts.type,clearEmptyFlag(opts.defaultValue,opts.type,opts.required===!0,"--default-value")),description:opts.description,required:opts.required,masked:opts.masked,parentId:opts.parentId,position:opts.position===void 0?void 0:Number(opts.position)}),body=assertParameterBody(validate(createBodySchema4,rawBody));assertRequiredValue(body.type,body.required===!0,body.value);let{data,response,error:error51}=await withSpinner("Creating parameter",()=>scope2.client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/parameter",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}},body}));(!response.ok||!data)&&apiFail(response.status,error51),await syncParameters(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment}),okMutation("Environment parameter created",data,data)}),withScope2(param.command("update").description("Update an environment parameter").argument("[parameterId]","Parameter ID (required, interactive)")).option("--key <key>","New parameter key (optional, interactive, default: the current key)").option("--value <value>","Parameter value; use --input for LIST/MAP/choice types (optional, interactive, default: the current value)").option("--default-value <value>",`Default value, ${DEFAULT_VALUE_PURPOSE}; use --input for complex types (optional, interactive, default: the current default value)`).option("--description <text>","Parameter description (optional, interactive, default: the current description)").option("--required","Mark the parameter required (optional, interactive, exclusive with --optional, default: the current value)").option("--optional","Mark the parameter optional (optional, interactive, exclusive with --required, default: the current value)").option("--masked","Mask the value (optional, interactive for TEXT only, exclusive with --unmasked, default: the current value, ignored for other types)").option("--unmasked","Unmask the value (optional, interactive for TEXT only, exclusive with --masked, default: the current value, ignored for other types)").option("--parent-id <id>","Move under the specified FOLDER parameter (optional, interactive, default: the current folder, refused for FOLDER)").option("--position <n>","Position among the parameter's siblings, 0 = top; inserting shifts the siblings after it (optional, API default: the current position)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC4))return;let globals=cmd.optsWithGlobals();requiredFromFlags(opts),switchFromFlags(opts,"masked","unmasked");let scope2=await resolveScope4(globals),parameterId=await resolveParameterId(scope2,idArg),body;if(opts.input)body=assertParameterBody(validate(updateBodySchema4,readInput(opts.input)));else{let params=await fetchParameters(scope2),current=findParam(params,parameterId);current||fail(EXIT.NOT_FOUND,"NOT_FOUND",`Parameter '${parameterId}' not found.`,{status:404});let currentParentId=findParentId(params,parameterId),noFlags=[opts.key,opts.value,opts.defaultValue,opts.description,opts.required,opts.optional,opts.masked,opts.unmasked,opts.parentId,opts.position].every(v2=>v2===void 0),interactive=noFlags&&canPrompt();noFlags&&!interactive&&failNothingToUpdate(["--key","--value","--default-value","--description","--required/--optional","--masked/--unmasked","--parent-id","--position","--input"]);let flags=current.type==="PASSWORD"&&current.valueSet&&opts.value===""?{...opts,value:void 0}:opts,draft=(interactive?await fillUpdateBody(current,collectFolderChoices(params),currentParentId):{body:buildUpdateBody2(current,flags,currentParentId)}).body;if(interactive&&sameBody(draft,buildUpdateBody2(current,{},currentParentId))){prompts().note("Nothing to update \u2014 the parameter was left as it is.");return}current.type==="PASSWORD"&&current.valueSet&&opts.value===""&&warnLine("\u26A0 A PASSWORD value cannot be cleared \u2014 the stored secret is kept."),assertRequiredValue(current.type,draft.required===!0,draft.value),body=assertParameterBody(validate(updateBodySchema4,draft))}let{response,error:error51}=await withSpinner("Updating parameter",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/parameter/{parameterId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,parameterId}},body}));response.ok||apiFail(response.status,error51),await syncParameters(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment}),okMutation("Environment parameter updated",{updated:!0,id:parameterId})}),withScope2(param.command("delete").description("Delete an environment parameter").argument("[parameterId]","Parameter ID (required, interactive)"),{destructive:!0}).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC4))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope4(globals,{useSession:canPrompt()}),parameterId=await resolveParameterId(scope2,idArg);opts.yes||(canPrompt()||failNeedsYes(`parameter ${parameterId}`),await prompts().confirm(`Delete parameter ${parameterId}? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."));let{response,error:error51}=await withSpinner("Deleting parameter",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/parameter/{parameterId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,parameterId}}}));response.ok||apiFail(response.status,error51),await syncParameters(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment}),okMutation("Environment parameter deleted",{deleted:!0,id:parameterId})}),param}function formatParamCell(v2){return v2==null?"":Array.isArray(v2)?v2.map(String).join(", "):typeof v2=="object"?Object.entries(v2).map(([k2,val])=>`${k2}=${String(val).replaceAll(`
1338
+ `,"\\n")}`).join(", "):String(v2).replaceAll(`
1339
+ `,"\\n")}function formatSecretCell(v2,isSet){return isSet?"[REDACTED]":formatParamCell(v2)===""?"":"[REDACTED]"}function formatChoicesCell(p){return p.type!=="SINGLE_CHOICE"&&p.type!=="MULTIPLE_CHOICES"?"":(p.choices??[]).map(c=>c.value?`${c.label} (${c.value})`:c.label).join(", ")}function flattenForHuman(params,depth=0){return params.flatMap(p=>{let{children,choices:_choices,defaultValue,description,id,key:_key,position,required:required2,type:_type,value,valueSet:_valueSet,masked:_masked,...rest}=p,secret=p.type==="PASSWORD",row={id,key:`${" ".repeat(depth)}${p.key}`,type:p.masked?`${p.type} (MASKED)`:p.type,required:required2,position,value:secret?formatSecretCell(value,p.valueSet):formatParamCell(value),defaultValue:secret?formatSecretCell(defaultValue,!1):formatParamCell(defaultValue),choices:formatChoicesCell(p),description,...rest};return children?.length?[row,...flattenForHuman(children,depth+1)]:[row]})}import{basename as basename3}from"path";import{readFileSync as readFileSync14,statSync as statSync5}from"fs";import{resolve as resolve5}from"path";var MAX_CONTENT_BYTES=5*1024*1024;function assertSize(bytes,kind){if(bytes>MAX_CONTENT_BYTES){let size=sizesAgainstCap(bytes,MAX_CONTENT_BYTES);fail(EXIT.USAGE,kind.tooLargeCode,`${kind.noun} is ${size.actual} \u2014 the API accepts up to ${size.cap}.`)}}function readContentFile(path2,kind){if(path2==="-")return readStdin(kind);let stats=statOrFail2(path2);stats.isFile()||fail(EXIT.USAGE,"INVALID_FILE",`${path2} is not a file.`),assertSize(stats.size,kind);try{return readFileSync14(path2,"utf8")}catch(error51){fail(EXIT.USAGE,"INVALID_FILE",unreadable(path2,error51))}}function statOrFail2(path2){try{return statSync5(path2)}catch(error51){fail(EXIT.USAGE,"INVALID_FILE",unreadable(path2,error51))}}function unreadable(path2,error51){let code=error51?.code,resolved=resolve5(path2),detail=[];return code&&detail.push(code),resolved!==path2&&detail.push(`looked in ${resolved}`),detail.length>0?`${path2} could not be read (${detail.join(", ")}).`:`${path2} could not be read.`}function readStdin(kind){let content;try{content=readStdinSync()}catch{fail(EXIT.USAGE,"INVALID_FILE","stdin could not be read.")}return assertSize(Buffer.byteLength(content,"utf8"),kind),content}function extensionHint(extensions){return extensions?.length?`; suggesting ${extensions.length===1?extensions[0]:`${extensions.slice(0,-1).join(", ")} or ${extensions.at(-1)}`} \u2014 type the full path to use another`:""}async function askInlineContent(kind,opts={}){let initial=opts.initial;for(;;){let content=await prompts().multiline(`${kind.noun} content (${SUBMIT_KEY} to reach [ submit ], then enter)`,{...opts.placeholder?{placeholder:opts.placeholder}:{},...initial===void 0?{}:{initial},...kind.language?{language:kind.language}:{}});if(content.trim())return assertSize(Buffer.byteLength(content,"utf8"),kind),content;if(opts.emptyConfirm&&await prompts().confirm(opts.emptyConfirm,!1))return"";opts.emptyConfirm||prompts().note(`\u2716 The ${kind.noun.toLowerCase()} cannot be empty.`),initial=content||initial}}async function askContentSource(opts){let choices=[...opts.omitChoice?[{value:"omit",label:opts.omitChoice.label,...opts.omitChoice.hint?{hint:opts.omitChoice.hint}:{}}]:[],{value:"inline",label:opts.inlineLabel??"Write it here",hint:"multi-line editor"},{value:"file",label:"Upload from a file",hint:"path to a local file"}],mode=await prompts().select(opts.message,choices);if(mode==="omit")return{};if(mode==="file"){let path2=await prompts().path(`${opts.pathMessage??"Path to the file"} (relative or absolute${extensionHint(opts.extensions)})`,{...opts.extensions?{extensions:opts.extensions}:{},validate:value=>{if(!value.trim())return"A path is required.";try{return statSync5(value).isFile()?void 0:"That path is not a file."}catch{return"No such file."}}});return{content:readContentFile(path2,opts.kind),path:path2}}let initial=opts.currentContent?await opts.currentContent():void 0;return{content:await askInlineContent(opts.kind,{...initial===void 0?{}:{initial},...opts.placeholder?{placeholder:opts.placeholder}:{},...opts.emptyConfirm?{emptyConfirm:opts.emptyConfirm}:{}})}}var MESSAGE_KIND={noun:"Feedback message",tooLargeCode:"FEEDBACK_MESSAGE_TOO_LARGE"},attachmentSchema=external_exports.object({fileName:external_exports.string(),content:external_exports.string()}).strict(),postBodySchema=external_exports.object({message:external_exports.string(),email:external_exports.string().optional(),canContact:external_exports.boolean().optional(),attachments:external_exports.array(attachmentSchema).optional()}).strict(),POST_DOC=defineCommandDoc("feedback post",{schema:postBodySchema,body:{message:"The script picker lists a deleted script in an environment with a release deployed.",email:"you@example.com",canContact:!0,attachments:[{fileName:"trace.log",content:"aGVsbG8="}]},rules:[`message: up to ${MAX_FEEDBACK_MESSAGE} characters, not empty. Spelled --message or --message-file <path> as a flag.`,`email: the address a reply goes to, up to ${MAX_FEEDBACK_EMAIL} characters; omitted, the API uses the address of the user the API key belongs to.`,"canContact (--can-contact as a flag): whether the ScriptRunner Connect team may contact you about it; API default false.",`attachments: up to ${MAX_ATTACHMENTS}, spelled --attachment <path> as a repeatable flag which reads and encodes the file for you; fileName is ${ATTACHMENT_NAME_FORMAT}, up to ${MAX_ATTACHMENT_NAME} characters and unique; content is the file base64-encoded, up to ${MAX_ATTACHMENT_BYTES/1024/1024} MiB decoded per file and ${MAX_ATTACHMENTS_BYTES/1024/1024} MiB in total.`,"Nothing reads feedback back; the returned ID is the only handle. Refused with exit 2 when the agentic-feedback switch is off and nobody can be asked."]});function collectPath(value,previous){return[...previous??[],value]}async function askFeedbackMessage(){let initial;for(;;){let answer=await prompts().multiline(`Feedback message (${SUBMIT_KEY} to reach [ submit ], then enter)`,{placeholder:"What happened, and what you expected instead",...initial===void 0?{}:{initial}}),error51=feedbackMessageError(answer);if(!error51)return assertFeedbackMessage(answer);prompts().note(`\u2716 ${error51}`),initial=answer||initial}}async function askReplyAddress(client){let me2=await withSpinner("Checking your account",()=>currentUser(client)),fallback=me2?.email?me2.email:"your account's address";for(;;){let answer=await prompts().text(`Reply address (empty to use ${fallback})`,{allowEmpty:!0});if(!answer.trim())return;let error51=feedbackEmailError(answer);if(!error51)return normalizeFeedbackEmail(answer);prompts().note(`\u2716 ${error51}`)}}async function askAttachmentName(suggested){for(;;){let answer=await prompts().text("Send it under a different name",{...suggested?{initial:suggested}:{},allowEmpty:!0}),error51=attachmentNameError(answer);if(!error51)return answer.trim();prompts().note(`\u2716 ${error51}`)}}async function askAttachments(){if(!await prompts().confirm("Attach files?",!1))return[];let attachments=[],names=new Set,total=0;for(;;){let path2=await prompts().path("Path to the file (relative or absolute)",{validate:value=>value.trim()?void 0:"A path is required."}),bytes=attachmentFileSize(path2);if(bytes===void 0)prompts().note(`\u2716 ${path2} is not a readable file.`);else if(bytes>MAX_ATTACHMENT_BYTES)prompts().note(`\u2716 ${attachmentTooLarge(basename3(path2),bytes)}`);else if(total+bytes>MAX_ATTACHMENTS_BYTES){let totals=sizesAgainstCap(total+bytes,MAX_ATTACHMENTS_BYTES);prompts().note(`\u2716 Adding that file would take the submission to ${totals.actual} \u2014 one submission can carry at most ${totals.cap} (${formatBytes(total)} attached so far).`)}else{let fileName=basename3(path2).trim(),nameError=attachmentNameError(fileName);for(nameError&&(prompts().note(`\u2716 ${nameError}`),fileName=await askAttachmentName(suggestAttachmentName(fileName)));names.has(fileName);)prompts().note(`\u2716 Something is already attached as "${fileName}".`),fileName=await askAttachmentName(suggestAttachmentName(fileName));attachments.push(readAttachment(path2,fileName)),names.add(fileName),total+=bytes}if(attachments.length>=MAX_ATTACHMENTS)return prompts().note(`${MAX_ATTACHMENTS} files attached \u2014 that is the most one submission takes.`),attachments;if(total>=MAX_ATTACHMENTS_BYTES||!await prompts().confirm(`Attach another file? (${attachments.length} attached, ${formatBytes(total)} of ${formatBytes(MAX_ATTACHMENTS_BYTES)})`,!1))return attachments}}function postDetail(id,attachments){let detail={id};return attachments.length&&(detail.attachments=attachments.map(a=>`${a.fileName} (${formatBytes(base64Bytes(a.content))})`).join(`
1340
+ `)),detail}var POST_CRASH_DOC=defineCommandDoc("feedback post-crash-report",{rules:["--report names a stored report by its run ID; omitted, the newest is sent.","--keep leaves the report on disk, which is otherwise deleted after a successful send.","--message replaces the default message, which is a summary of the report.","--email is the address a reply should go to, up to 100 characters; omitted, the API uses the address the API key belongs to. --can-contact is what permits a reply at all, and the API defaults it to false, so an address sent without it is stored and not written to."],notes:["Sends a report this CLI stored earlier, with its metadata, the stack and the API calls that run recorded, secrets redacted.","Nothing reads feedback back; the returned ID is the only handle.","Refused with exit 2 AGENTIC_FEEDBACK_DISABLED when the agentic-feedback switch is off and nobody can be asked."]});function feedbackCommand(){let feedback=new Command("feedback").description("Send feedback about ScriptRunner Connect");return feedback.command("post").description("Post feedback, optionally with files attached").option("--message <text>",`Feedback message; up to ${MAX_FEEDBACK_MESSAGE} characters (required unless --message-file or --input, interactive, exclusive with --message-file)`).option("--message-file <path>","Read the feedback message from a file, or - for stdin (required unless --message or --input, interactive, exclusive with --message)").option("--email <address>",`Address a reply should be sent to; up to ${MAX_FEEDBACK_EMAIL} characters (optional, interactive, API default: the address of the user the API key belongs to)`).option("--can-contact","Allow the ScriptRunner Connect team to contact you about what you send (optional, interactive, API default: false)").option("--attachment <path>",`File to attach, sent under its own file name; up to ${MAX_ATTACHMENTS} files, ${formatBytes(MAX_ATTACHMENT_BYTES)} each and ${formatBytes(MAX_ATTACHMENTS_BYTES)} in total (optional, interactive, repeatable)`,collectPath).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,POST_DOC))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt();assertAgenticFeedbackAllowed();let client=await apiClient(globals.instance);opts.message!==void 0&&opts.messageFile!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--message and --message-file cannot be combined.");let rawBody;if(opts.input)rawBody=readInput(opts.input);else{let message=opts.message;message===void 0&&opts.messageFile!==void 0&&(message=readContentFile(opts.messageFile,MESSAGE_KIND)),message===void 0&&interactive&&(message=await askFeedbackMessage()),message===void 0&&fail(EXIT.USAGE,"USAGE_ERROR","Nothing to post: pass --message or --message-file with the feedback (or --input).");let canContact=opts.canContact?!0:interactive?await askContact():void 0,email3=opts.email??(interactive&&canContact?await askReplyAddress(client):void 0),attachments2=opts.attachment?opts.attachment.map(path2=>readAttachment(path2)):interactive?await askAttachments():[];rawBody=stripUndefined({message,email:email3,canContact:canContact?!0:void 0,attachments:attachments2.length?attachments2:void 0})}let parsed=validate(postBodySchema,rawBody),attachments=parsed.attachments===void 0?void 0:assertAttachments(parsed.attachments),body={message:assertFeedbackMessage(parsed.message),...parsed.email===void 0?{}:{email:assertFeedbackEmail(parsed.email)},...parsed.canContact===void 0?{}:{canContact:parsed.canContact},...attachments===void 0?{}:{attachments}},{data,response,error:error51}=await withSpinner("Posting feedback",()=>client.POST("/v1/feedback",{body}));(!response.ok||!data)&&apiFail(response.status,error51),okMutation("Feedback posted",data,postDetail(data.id,attachments??[])),isRaw()||prompts().note("Nothing reads feedback back \u2014 keep that ID if you follow this up in a support conversation.")}),feedback.command("post-crash-report").description("Post a crash report this CLI stored earlier").option("--report <id>",`The crash report to post, see ${CLI} cli list-crash-reports (optional, interactive, default: the newest one)`).option("--message <text>",`Message to send with the report; up to ${MAX_FEEDBACK_MESSAGE} characters (optional, default: a summary composed from the report)`).option("--email <address>",`Address a reply should be sent to; up to ${MAX_FEEDBACK_EMAIL} characters (optional, API default: the address of the user the API key belongs to)`).option("--can-contact","Allow the ScriptRunner Connect team to contact you about the report (optional, API default: false)").option("--keep","Keep the report on disk after posting it (optional, default: it is deleted once posted)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,POST_CRASH_DOC))return;assertAgenticFeedbackAllowed();let report=await resolveCrashReport(opts.report,"Which crash report do you want to send?"),id=await sendCrashReport(report,{...opts.message===void 0?{}:{message:assertFeedbackMessage(opts.message)},...opts.email===void 0?{}:{email:assertFeedbackEmail(opts.email)},...opts.canContact?{canContact:!0}:{}}),removed=opts.keep?!1:clearCrashReports(report.id).includes(report.id);!opts.keep&&!removed&&warnLine(`\u26A0 Could not delete the crash report \u2014 it is still in ${crashReportsDir()}`),okMutation("Crash report posted",{id,report:report.id},{id,report:report.id,kind:crashTitle(report),command:report.command,size:formatBytes(Buffer.byteLength(report.markdown)),keptOnDisk:removed?"no":"yes"}),isRaw()||prompts().note("Nothing reads feedback back \u2014 keep that ID if you follow this up in a support conversation.")}),feedback}async function askContact(){return prompts().confirm("May the ScriptRunner Connect team contact you about this feedback?",!1)}var import_picocolors11=__toESM(require_picocolors(),1);var import_picocolors9=__toESM(require_picocolors(),1);var RUNTIME_EVENTS="@avst-stitch/runtime-events",EVENT={log:`${RUNTIME_EVENTS}/Log`,executionFinished:`${RUNTIME_EVENTS}/ExecutionFinished`,malformedResponse:`${RUNTIME_EVENTS}/MalformedResponseEvent`,invocationScheduled:`${RUNTIME_EVENTS}/InvocationScheduled`,invocationQueued:`${RUNTIME_EVENTS}/InvocationQueued`,invocationDenied:`${RUNTIME_EVENTS}/InvocationDenied`,invocationDisabled:`${RUNTIME_EVENTS}/InvocationDisabled`,queuedInvocationDropped:`${RUNTIME_EVENTS}/QueuedInvocationDropped`,malformedPayload:`${RUNTIME_EVENTS}/MalformedPayloadEvent`};function isControlFrame(frame){return typeof frame.messageType=="string"}function parseFrame(data){let parsed;try{parsed=JSON.parse(data)}catch{return}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return;let frame=parsed;if(typeof frame.messageType=="string"||typeof frame.type=="string")return frame}var REFUSALS={[EVENT.invocationDenied]:"DENIED",[EVENT.invocationDisabled]:"DISABLED",[EVENT.queuedInvocationDropped]:"DROPPED",[EVENT.malformedPayload]:"MALFORMED_PAYLOAD_ERROR"},FINISH_EVENTS=[EVENT.executionFinished,EVENT.malformedResponse],OUTCOME_FAILURES={ABORTED:{code:"INVOCATION_ABORTED",sentence:"The invocation was aborted before it finished",status:409},TIMED_OUT:{code:"SCRIPT_TIMEOUT",sentence:"The script hit the invocation time limit",status:504},FUNCTION_ERROR:{code:"SCRIPT_ERROR",sentence:"The script threw",status:422},RUNTIME_ERROR:{code:"RUNTIME_ERROR",sentence:"The platform failed while running the script \u2014 this is not the script's fault"},MALFORMED_PAYLOAD_ERROR:{code:"MALFORMED_PAYLOAD",sentence:"The event payload could not be used"},DENIED:{code:"INVOCATION_NOT_RUN"},DISABLED:{code:"INVOCATION_NOT_RUN"},DROPPED:{code:"INVOCATION_NOT_RUN"},NOT_RUN:{code:"INVOCATION_NOT_RUN",sentence:"The invocation never ran"}};function resolveOutcome(endOutcome,endReason,detail){let notRun=endReason==="NOT_RUN"||detail?.notRun===!0,status=endOutcome??detail?.status??(notRun?"NOT_RUN":void 0);if(status!==void 0)return{...detail??{hasHttpLogs:!1,notRun},status,notRun}}function outcomeOf(event){let payload=event.payload??{};if(FINISH_EVENTS.includes(event.type))return{status:payload.executionFinishedType??"UNKNOWN",...event.message===void 0?{}:{message:event.message},...typeof payload.time=="number"?{durationMs:payload.time}:{},...typeof payload.logs=="number"?{logs:payload.logs}:{},...typeof payload.httpLogs=="number"?{httpLogs:payload.httpLogs}:{},hasHttpLogs:!!payload.httpLogsUrl,notRun:!1};let refusal=REFUSALS[event.type];if(refusal)return{status:refusal,...event.message===void 0?{}:{message:event.message},hasHttpLogs:!1,notRun:!0}}var METHOD_SEVERITY={log:"log",info:"info",warn:"warn",error:"error",debug:"debug"},LEVEL_SEVERITY={INFO:"info",WARN:"warn",ERROR:"error",DEBUG:"debug",SUCCESS:"info"};function severityOf(event){let method=event.payload?.method;if(method!==void 0&&method in METHOD_SEVERITY)return METHOD_SEVERITY[method];let level=event.level??event.payload?.level;return level!==void 0&&level in LEVEL_SEVERITY?LEVEL_SEVERITY[level]:"log"}function messageOf(event){let raw=event.message??"";if(!event.needsProcessing)return raw;try{let values=JSON.parse(raw);return Array.isArray(values)?getMessageForArgs(values):raw}catch{return raw}}var MAX_DEPTH2=8;function largePlaceholder2(entryId,opts){let head="\u22EF message too large to display";return!entryId||!opts.invocationId||!opts.workspaceId?`${head}.`:`${head}. Fetch this one on its own:
1341
+ ${CLI} log get-large-log-message ${opts.invocationId} ${entryId} -w ${opts.workspaceId}`}function createFeedbackRenderer(opts={}){let mode=opts.timestamps??"time",stampWidth=stampWidthOf(mode),maxDepth=opts.maxDepth??MAX_DEPTH2,depths=new Map,first;return{render(event){if(FINISH_EVENTS.includes(event.type))return;let payload=event.payload??{},timestamp=event.time??payload.timestamp??Date.now();first??=timestamp;let parent=payload.parentId,depth=parent!==void 0?(depths.get(parent)??0)+1:0;payload.entryId!==void 0&&depths.set(payload.entryId,depth);let body=rowBody(event,payload,opts);if(body!==void 0)return formatLogRow({stamp:stampOf(timestamp,mode,first),stampWidth,depth:Math.min(depth,maxDepth),severity:severityOf(event),body,system:payload.type==="SYSTEM_LOG"})}}}function rowBody(event,payload,opts){if(payload.payloadUrl)return import_picocolors9.default.dim(largePlaceholder2(payload.entryId,opts));let message=messageOf(event);if(message!=="")return payload.method==="group"||payload.method==="groupCollapsed"?import_picocolors9.default.bold(`\u25B8 ${message}`):REFUSALS[event.type]?import_picocolors9.default.red(message):payload.type==="SYSTEM_LOG"?import_picocolors9.default.bold(message):message}function renderOutcome(outcome){if(!outcome)return import_picocolors9.default.dim("The stream ended without reporting an outcome.");let ok2=outcome.status==="FINISHED",head=ok2?import_picocolors9.default.green(`\u2714 ${outcome.status}`):import_picocolors9.default.red(`\u2716 ${outcome.status}`);if(outcome.notRun)return`${head} ${import_picocolors9.default.dim("\u2014 the invocation never ran")}`;let parts=[];return outcome.durationMs!==void 0&&parts.push(`${ok2?"in":"after"} ${formatDuration(outcome.durationMs)}`),outcome.logs!==void 0&&parts.push(`${outcome.logs} log ${outcome.logs===1?"entry":"entries"}`),outcome.httpLogs&&parts.push(`${outcome.httpLogs} HTTP ${outcome.httpLogs===1?"call":"calls"}`),parts.length>0?`${head} ${import_picocolors9.default.dim(parts.join(" \xB7 "))}`:head}function formatDuration(ms){return ms<1e3?`${ms} ms`:`${(ms/1e3).toFixed(1)} s`}var import_picocolors10=__toESM(require_picocolors(),1);var TICK_MS=30*1e3,MAX_SESSION_MS=960*1e3,CONNECT_TIMEOUT_MS=15*1e3,READY_TIMEOUT_MS=15*1e3,MAX_AUTH_ATTEMPTS=4,DEFAULT_RETRY_MS=1e3,MAX_RETRY_MS=10*1e3,MAX_RESUME_ATTEMPTS=2,REORDER_HOLD_MS=1e3,TAIL_GRACE_MS=8e3,FATAL_AUTH_REASONS=["UNAUTHORIZED","MALFORMED"],factory;function createSocket(url2){return factory?factory(url2):(typeof WebSocket>"u"&&fail(EXIT.API_ERROR,"STREAMING_UNSUPPORTED",`Live log streaming needs a runtime with a built-in WebSocket (Node ${MIN_NODE_MAJOR} or newer, running ${process.versions.node}).`,{hint:`Read the logs after the run instead: ${CLI} log list-console-logs <invocationId> -w <workspaceId>`}),new WebSocket(url2))}async function logsStreamUrl(client){return(await readServiceInfo(client,{refreshWithoutStreamUrl:!0}))?.logsStreamUrl}var warnedInsecure2=!1;function warnIfInsecure2(url2){if(warnedInsecure2||!url2.startsWith("ws://"))return;let host="";try{host=new URL(url2).hostname}catch{host=""}["localhost","127.0.0.1","::1","[::1]"].includes(host)||(warnedInsecure2=!0,console.error(import_picocolors10.default.yellow(`\u26A0 ${url2} is not encrypted \u2014 your credentials would be sent over a plaintext WebSocket.`)))}async function openLogStream(client,opts={}){return withSpinner("Connecting to the log stream",async()=>{let url2=await logsStreamUrl(client);if(!url2)return;warnIfInsecure2(url2);let authorization=basicAuthHeader(await requireCredentials());return startSession(url2,authorization,opts)})}async function startSession(url2,authorization,opts){let subscriptionId=ulid(),listeners=new Set,socket,closed=!1,ended=!1,resumeAttempts=0,ids,workspaceId,started=!1,onIdentified,pending=[],drainTimer,renderer,result={receivedLogs:0,grouped:!1,incomplete:!1,reconnected:!1},terminated=!1,finishSeen=!1,endOutcome,detail,tailTimer,settle,finished=new Promise(resolve8=>{settle=resolve8}),write=line=>{console.error(line)},emit2=event=>{pending.push({event,at:Date.now()}),scheduleDrain()},drain=(force=!1)=>{if(!renderer||pending.length===0)return;let first=pending[0];if(!force&&first!==void 0&&Date.now()-first.at<REORDER_HOLD_MS){scheduleDrain();return}let batch=pending.splice(0).map(held=>held.event).sort(byTime);for(let event of batch){let row=renderer.render(event);row!==void 0&&!opts.rawFrames&&write(row)}},scheduleDrain=()=>{if(drainTimer||!renderer||pending.length===0)return;let first=pending[0];if(first===void 0)return;let wait=Math.max(0,first.at+REORDER_HOLD_MS-Date.now());drainTimer=setTimeout(()=>{drainTimer=void 0,drain()},wait)},onFrame=frame=>{if(isControlFrame(frame)){frame.messageType==="STREAM_END"&&(frame.reason!==void 0&&(result.endReason=frame.reason),frame.outcome!==void 0&&(endOutcome=frame.outcome),typeof frame.expectedLogs=="number"&&(result.expectedLogs=frame.expectedLogs),terminated=!0,awaitTail());return}let carried=outcomeOf(frame);if(carried&&(detail=carried,finishSeen=!0),frame.type===EVENT.log&&(result.receivedLogs+=1,frame.payload?.parentId!==void 0&&(result.grouped=!0),severityOf(frame)==="error")){let text=messageOf(frame).split(`
1342
+ `)[0]?.trim();text&&(result.lastError=text)}frame.invocationId!==void 0&&identify(frame.invocationId),emit2(frame),(terminated||finishSeen)&&awaitTail()},awaitTail=()=>{if(!ended){if(result.expectedLogs!==void 0&&result.receivedLogs>=result.expectedLogs){finish();return}tailTimer??=setTimeout(finish,TAIL_GRACE_MS)}},identify=invocationId=>{!started||renderer||workspaceId===void 0||(ids={invocationId,workspaceId},renderer=createFeedbackRenderer({...opts.timestamps?{timestamps:opts.timestamps}:{},invocationId,workspaceId}),onIdentified?.(invocationId),opts.rawFrames||(write(""),write(`${import_picocolors10.default.bold(`Streaming console logs \xB7 ${invocationId}`)} ${import_picocolors10.default.dim("\xB7 Ctrl-C stops watching, not the script")}`),write("")),drain(),scheduleDrain())},timers=[],finish=()=>{if(!ended){ended=!0;for(let timer of timers)clearInterval(timer);timers.length=0,tailTimer&&clearTimeout(tailTimer),drainTimer&&clearTimeout(drainTimer),process.removeListener("SIGINT",onSigint),closeSocket(),drain(!0),result.outcome=resolveOutcome(endOutcome,result.endReason,detail),result.expectedLogs!==void 0&&result.receivedLogs<result.expectedLogs&&(result.incomplete=!0),opts.rawFrames||writeTail(),settle?.(result)}},closeSocket=()=>{closed=!0;try{socket?.close()}catch{}},writeTail=()=>{if(!renderer||(write(""),write(renderOutcome(result.outcome)),!ids))return;result.outcome?.hasHttpLogs&&write(import_picocolors10.default.dim(`HTTP logs were also recorded for this invocation:
1343
+ ${CLI} log list-http-logs ${ids.invocationId} -w ${ids.workspaceId}`));let verdict=completenessNote(result);if(verdict){let command=`${CLI} log list-console-logs ${ids.invocationId} -w ${ids.workspaceId}`;write(verdict.certain?import_picocolors10.default.yellow(`${verdict.text}
1344
+ ${command}`):import_picocolors10.default.dim(`${verdict.text}
1345
+ ${command}`))}},onSigint=()=>{drain(!0),!opts.rawFrames&&ids&&(write(""),write(import_picocolors10.default.dim(`Stopped watching. The script keeps running \u2014 read its output with:
1346
+ ${CLI} log list-console-logs ${ids.invocationId} -w ${ids.workspaceId}`))),closeSocket(),process.exit(EXIT.CANCELLED)},attach=next=>{socket=next,next.addEventListener("message",event=>{let raw=String(event.data??"");opts.rawFrames&&write(raw.trim());let frame=parseFrame(raw);if(frame)for(let listener of Array.from(listeners))listener(frame)}),next.addEventListener("close",()=>{if(!(ended||closed)){if(terminated){finish();return}resume()}}),next.addEventListener("error",()=>{})},sendAuth=()=>{socket?.send(JSON.stringify({messageType:"API_AUTH",authorization,subscriptionId}))},waitForFrame=(predicate,timeoutMs,what)=>new Promise((resolve8,reject)=>{let timer=setTimeout(()=>{listeners.delete(listener),reject(new Error(`Timed out after ${timeoutMs}ms waiting for ${what}.`))},timeoutMs),listener=frame=>{predicate(frame)&&(clearTimeout(timer),listeners.delete(listener),resolve8(frame))};listeners.add(listener)}),authenticate=async()=>{for(let attempt2=1;;attempt2+=1){sendAuth();let frame;try{frame=await waitForFrame(f2=>isControlFrame(f2)&&(f2.messageType==="STREAM_READY"||f2.messageType==="API_AUTH_ERROR"),READY_TIMEOUT_MS,"STREAM_READY")}catch(err){closeSocket(),fail(EXIT.API_ERROR,"STREAM_CONNECT_FAILED",`The log stream did not confirm the subscription: ${err instanceof Error?err.message:String(err)}`,{hint:"Re-run without --stream-logs to trigger without watching the output."})}let control=frame;if(control.messageType==="STREAM_READY")return;let reason=control.reason??"UNKNOWN";if(FATAL_AUTH_REASONS.includes(reason)&&(closeSocket(),reason==="UNAUTHORIZED"&&fail(EXIT.UNAUTHENTICATED,"INVALID_CREDENTIALS","The log stream rejected these credentials.",{hint:`Run \`${CLI} auth login\` and try again.`}),fail(EXIT.API_ERROR,"STREAM_REJECTED",`The log stream rejected the subscription: ${reason}.`)),attempt2>=MAX_AUTH_ATTEMPTS){closeSocket();let code=reason==="TOO_MANY_STREAMS"?"TOO_MANY_STREAMS":"STREAM_CONNECT_FAILED";fail(EXIT.API_ERROR,code,`The log stream could not be opened after ${attempt2} attempts: ${reason}.`,{hint:reason==="TOO_MANY_STREAMS"?"Close another log tail and retry.":"Re-run without --stream-logs to trigger without watching the output."})}await delay(Math.min(control.retryAfterMs??DEFAULT_RETRY_MS,MAX_RETRY_MS))}},resume=async()=>{if(ended||resumeAttempts>=MAX_RESUME_ATTEMPTS){result.incomplete=!0,finish();return}resumeAttempts+=1,result.reconnected=!0,opts.rawFrames||write(import_picocolors10.default.dim(`Reconnecting to the log stream (attempt ${resumeAttempts} of ${MAX_RESUME_ATTEMPTS})\u2026`));try{let next=createSocket(url2);attach(next),await waitForOpen(next,CONNECT_TIMEOUT_MS),sendAuth(),await waitForFrame(f2=>isControlFrame(f2)&&f2.messageType==="STREAM_READY",READY_TIMEOUT_MS,"STREAM_READY")}catch{result.incomplete=!0,opts.rawFrames||write(import_picocolors10.default.yellow("\u26A0 Reconnecting failed \u2014 stopped watching.")),finish()}};attach(createSocket(url2)),await waitForOpen(socket,CONNECT_TIMEOUT_MS).catch(err=>{closeSocket(),fail(EXIT.API_ERROR,"STREAM_CONNECT_FAILED",`Could not open the log stream at ${url2}: ${err instanceof Error?err.message:String(err)}`,{hint:"Re-run without --stream-logs to trigger without watching the output."})}),listeners.add(onFrame),await authenticate();let sessionStart=Date.now();return timers.push(setInterval(()=>{Date.now()-sessionStart<MAX_SESSION_MS||(result.incomplete=!0,opts.rawFrames||write(import_picocolors10.default.yellow(endOutcome!==void 0||detail!==void 0?"\u26A0 Stopped watching after 16 minutes. The invocation reported its outcome; the log stream was never closed.":"\u26A0 Stopped watching after 16 minutes. The script was not stopped \u2014 it may still be running.")),finish())},TICK_MS)),{subscriptionId,start(nextWorkspaceId,next){if(started)return;started=!0,workspaceId=nextWorkspaceId,onIdentified=next,process.once("SIGINT",onSigint);let known=pending.find(held=>held.event.invocationId!==void 0)?.event.invocationId;known!==void 0&&identify(known)},identify,done:()=>finished,close:finish}}function completenessNote(result){let{expectedLogs,receivedLogs,grouped:grouped2,incomplete,reconnected}=result;if(expectedLogs!==void 0&&receivedLogs<expectedLogs)return{text:`\u26A0 Received ${receivedLogs} of ${expectedLogs} log messages \u2014 output is incomplete. Read the stored output:`,certain:!0};if(incomplete)return{text:"\u26A0 Output was lost. Read the stored output:",certain:!0};if(!(expectedLogs!==void 0&&!grouped2))return reconnected?{text:"The connection dropped and was re-established during the run, so some messages may not have reached this terminal. Stored output:",certain:!1}:expectedLogs===void 0?{text:"The stream reported no message count, so completeness cannot be confirmed. Stored output:",certain:!1}:{text:"This run used console.group, and the message count only covers top-level messages \u2014 it cannot confirm the output is complete. Stored output:",certain:!1}}function byTime(a,b2){let at2=a.time??a.payload?.timestamp??0,bt=b2.time??b2.payload?.timestamp??0;return at2-bt||(a.payload?.seq??0)-(b2.payload?.seq??0)||(a.payload?.nanoseconds??0)-(b2.payload?.nanoseconds??0)}function waitForOpen(socket,timeoutMs){return new Promise((resolve8,reject)=>{let timer=setTimeout(()=>reject(new Error(`the socket did not open within ${timeoutMs}ms`)),timeoutMs);socket.addEventListener("open",()=>{clearTimeout(timer),resolve8()}),socket.addEventListener("error",()=>{clearTimeout(timer),reject(new Error("the socket failed to open"))})})}function delay(ms){return new Promise(resolve8=>setTimeout(resolve8,ms))}var SCRIPT_KIND={noun:"Script",tooLargeCode:"SCRIPT_TOO_LARGE",language:"typescript"},createBodySchema5=external_exports.object({name:external_exports.string().min(1),content:external_exports.string()}).strict(),updateBodySchema5=external_exports.object({content:external_exports.string(),name:external_exports.string().min(1).optional()}).strict(),CONTENT_CAP=`${MAX_CONTENT_BYTES/1024/1024} MiB`,EXAMPLE_SOURCE=`export default async function (event: unknown) {
1347
+ console.log(event)
1348
+ }
1349
+ `,BUNDLE_RULE="Refused in a non-HEAD environment. The whole workspace is bundled before saving: an import that does not resolve is a 400 and nothing is saved, while ordinary type errors are saved and reported back in compilationErrors.",LIST_DOC6=defineCommandDoc("script list",{rules:["The workspace is -w and the environment -e; there is no positional argument."],notes:["Read through a non-HEAD environment it answers what that release captured, so a script added since is not listed there."]}),GET_DOC5=defineCommandDoc("script get",{rules:["The script is the positional argument; the workspace is -w and the environment -e.","--content-only prints the source verbatim, for `> handler.ts`; --raw changes nothing there, the bytes being identical in both modes."],notes:["The content field of the ordinary document is what an --input body for update has to carry, and --content-only is the same bytes as a file.","Read through a non-HEAD environment it answers the copy that release captured; a script added since is exit 4 there."]}),DELETE_DOC5=defineCommandDoc("script delete",{rules:["The script is the positional argument; the workspace is -w and the environment -e.","--force deletes a script an event listener or scheduled trigger still uses, which is otherwise refused.","--yes skips the confirmation, and is required without a terminal."],notes:["Removes the script from the whole workspace; a non-HEAD environment keeps running the copy its release captured. Allowed through any environment, unlike creating or updating one \u2014 though a script added after that environment's release was cut is not part of it and is exit 4 there, as it is on a read.","A script still in use is exit 1 SCRIPT_IN_USE without --force.","--force detaches it from every event listener and scheduled trigger and leaves each one incomplete: it has no script to run and stops running, but it is not disabled \u2014 disabled is a state you set, and both still report false afterwards.","The reads say so: event-listener get and list, and scheduled-trigger get and list, all leave the script out once it is gone rather than naming an ID that resolves nowhere, so an absent script means the listener or trigger has nothing to run. Point each one at a script, or delete it.","Triggering a deleted script is exit 1 BAD_REQUEST, `Cannot run deleted script <name>`, rather than the exit 4 a read gives."]}),ABORT_DOC=defineCommandDoc("script abort-invocation",{rules:["The invocation is the positional argument or --invocation-id, and passing both is exit 2. The workspace is -w, required without a terminal unless the ordinary scope chain supplies it, as on the workspace-scoped log verbs; an inherited workspace that answers not found carries a \u26A0 naming where it came from.",INVOCATION_SCOPE_RULE],notes:["Requests that a queued or running invocation be aborted. Acceptance means the request was registered, not that the run stopped: a short run may finish first. `log list-invocation-logs --invocation-id \u2026` reports ABORTED when it took.","A queued invocation is stopped after it starts rather than prevented from starting, and the request eventually lapses \u2014 one still waiting by then runs to completion.","An invocation that has already finished cannot be aborted.","There is no --yes: a terminal confirms and a script does not."]}),CREATE_DOC5=defineCommandDoc("script create",{schema:createBodySchema5,body:{name:"handlers/OnIssueCreated",content:EXAMPLE_SOURCE},rules:[`name: ${SCRIPT_NAME_RULE}.`,`content: the whole TypeScript source, spelled --content or --file <path> as a flag, up to ${CONTENT_CAP}; "" is refused.`,BUNDLE_RULE,"--silent is about the run offered after saving, not about the save: it marks that run silenced and withholds its live console stream from everything but --stream-logs, the invocation still being recorded and its logs still readable. A run is only offered on a terminal, so without one the flag would do nothing and is refused (exit 2) rather than ignored."],notes:["Diagnostics come back in the document, and in human mode as a yellow block per script: a change can break a script that imports this one, so they cover the whole workspace rather than the file just written.","Inside a local copy of the workspace the new script file is written into it."]}),UPDATE_DOC5=defineCommandDoc("script update",{schema:updateBodySchema5,body:{content:EXAMPLE_SOURCE,name:"handlers/OnIssueCreated"},rules:[`content is what the API requires on every update, a plain rename included, but only an --input body has to carry it: a rename on its own reads the current source and sends it back. Spelled --content or --file <path> as a flag. Up to ${CONTENT_CAP}; "" is refused.`,`name renames the script and is optional; omitted keeps the current name. ${SCRIPT_NAME_RULE}.`,BUNDLE_RULE,"--silent is about the run offered after saving, not about the save: it marks that run silenced and withholds its live console stream from everything but --stream-logs, the invocation still being recorded and its logs still readable. A run is only offered on a terminal, so without one the flag would do nothing and is refused (exit 2) rather than ignored."],notes:["Diagnostics come back in the document, and in human mode as a yellow block per script, covering every script in the workspace rather than the one written.","Inside a local copy of the workspace the local file is updated, and a rename moves it."]}),SCRIPT_NAME_PROMPT="Script name (use / for folders, e.g. handlers/OnIssueCreated)";function readScriptFile(path2){return readContentFile(path2,SCRIPT_KIND)}async function askScriptName2(suggested){for(;;){let answer=await prompts().text(SCRIPT_NAME_PROMPT,{...suggested?{initial:suggested}:{},allowEmpty:!0}),error51=scriptNameError(answer);if(!error51)return assertScriptName(answer);prompts().note(`\u2716 ${error51}`)}}async function askSource(opts={}){return askContentSource({kind:SCRIPT_KIND,message:"How do you want to provide the script?",pathMessage:"Path to the script file",extensions:[".ts"],placeholder:"export default async function (event: unknown) { \u2026 }",...opts.inlineLabel?{inlineLabel:opts.inlineLabel}:{},...opts.currentContent?{currentContent:opts.currentContent}:{}})}async function fetchScript(client,path2){let{data,response,error:error51}=await withSpinner("Fetching script",()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}",{params:{path:path2}}));return(!response.ok||!data)&&apiFail(response.status,error51),data}function plural2(n,noun){return`${n} ${noun}${n===1?"":"s"}`}function renderCompilationErrors(groups){let total=groups.reduce((n,g)=>n+g.errors.length,0),heading=import_picocolors11.default.yellow(`\u26A0 TypeScript reported ${plural2(total,"problem")} in ${plural2(groups.length,"script")}. Nothing was blocked \u2014 the change was saved and the workspace bundled.`),blocks=groups.map(g=>`${import_picocolors11.default.bold(g.scriptName)}
1350
+ ${g.errors.map(e=>` ${e}`).join(`
1351
+ `)}`);return[heading,...blocks].join(`
1352
+ `)}var SCRIPT_NAME_BUNDLE_REPORT="Creating a script re-bundles the workspace and the response says how that went: compilationErrors carries TypeScript diagnostics for a bundle that was written anyway, one entry per script and covering every script in the workspace, and bundlingError says no bundle was written, in which case the script exists and answers 404 on a trigger until any script in the workspace is saved. Neither is a failure.";function renderBundlingError(message){return import_picocolors11.default.yellow(`\u26A0 The workspace could not be bundled: ${message}
1353
+ The script was created and cannot run yet \u2014 ${CLI} script trigger answers 404 naming it. Saving any script in the workspace (${CLI} script update <scriptId> with its own content) rebuilds the bundle.`)}function bundleReportDetail(detail,report){let blocks=[];report.compilationErrors&&report.compilationErrors.length>0&&blocks.push(renderCompilationErrors(report.compilationErrors)),report.bundlingError&&blocks.push(renderBundlingError(report.bundlingError));let rest=Object.fromEntries(Object.entries(detail).filter(([key])=>key!=="compilationErrors"&&key!=="bundlingError"));return blocks.length===0?rest:[renderDetail(rest),...blocks].join(`
1354
+
1355
+ `)}function renderScriptMutation(data){let detail=renderDetail({id:data.id,name:data.name}),errors=data.compilationErrors;return errors&&errors.length>0?`${detail}
1356
+
1357
+ ${renderCompilationErrors(errors)}`:detail}function renderScript(script){return`${renderDetail({id:script.id,name:script.name})}
1358
+ SOURCE
1359
+ ${script.content}`}async function deleteScript(client,path2,force){let{response,error:error51}=await withSpinner(force?"Deleting script (forced)":"Deleting script",()=>client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}",{params:{path:path2,...force?{query:{force:"true"}}:{}}}));return{ok:response.ok,status:response.status,error:error51}}function conflictMessage2(error51){return error51?.errorMessage??"The script is still used by event listeners or scheduled triggers."}async function deleteScriptWithConflict(client,path2,opts){let forced=opts.force,result=await deleteScript(client,path2,forced);result.status===409&&!forced&&opts.interactive&&(prompts().note(`\u2716 ${conflictMessage2(result.error)}`),await prompts().confirm("Delete it anyway? Anything using it will be deactivated.",!1)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."),forced=!0,result=await deleteScript(client,path2,forced)),result.status===409&&fail(EXIT.API_ERROR,"SCRIPT_IN_USE",conflictMessage2(result.error),{status:409,hint:"Re-run with --force to delete it anyway; the event listeners and scheduled triggers using it will be deactivated."}),result.ok||apiFail(result.status,result.error)}function failBundleTimeout(status){fail(EXIT.API_ERROR,"BUNDLE_TIMEOUT",`The API did not return a usable response (HTTP ${status}). The workspace bundle most likely exceeded the request timeout.`,{status,hint:"The whole workspace is compiled and bundled on every create and update \u2014 a large dependency tree can exceed the limit. Nothing was saved."})}var PAYLOAD_KIND={noun:"Event payload",tooLargeCode:"PAYLOAD_TOO_LARGE",language:"json"},PAYLOAD_PLACEHOLDER='{ "issue": { "key": "TEST-1" } }',triggerBodySchema=external_exports.object({functionName:external_exports.string().min(1).optional(),payload:external_exports.record(external_exports.string(),external_exports.unknown()).optional(),testPayloadId:external_exports.string().min(1).optional(),waitForResponse:external_exports.boolean().optional(),silent:external_exports.boolean().optional(),streamSubscriptionId:external_exports.string().min(1).optional()}).strict().refine(body=>body.payload===void 0||body.testPayloadId===void 0,{error:"payload and testPayloadId cannot be combined.",path:["payload"]}),TRIGGER_DOC=defineCommandDoc("script trigger",{schema:triggerBodySchema,body:{functionName:"handleEvent",payload:{issue:{key:"TEST-1"}},testPayloadId:"<testPayloadId>",waitForResponse:!0,silent:!1},hidden:["streamSubscriptionId"],rules:["functionName: a named export of the script to invoke; omitted, the default export runs.",`payload: the event as a JSON object, never a string or an array, up to ${CONTENT_CAP}, spelled --payload or --payload-file <path> as a flag; testPayloadId (--test-payload-id as a flag) instead runs a test payload of an event listener targeting the script. The two cannot be combined, and omitting both invokes the function with {}.`,"waitForResponse: true waits for the return value and caps the wait at 20 seconds, after which the invocation is ended as timed out rather than left to finish; omitted or false, the request answers 202 as soon as the run is accepted and the value is never returned. Spelled --wait as a flag, which a body given here supersedes like every body flag: with --input this key is what counts, and --response-only needs it to be true.","silent: true withholds the live console stream from everything except a socket the caller is already holding open for the run (--stream-logs), and marks the run as silenced in the audit trail; the invocation is still recorded and its logs readable either way. A run started through the API is addressed to its caller and to nobody else, so it never reaches the web application whichever value this carries."],notes:["--stream-logs watches the console output live until the run ends, on stderr in both modes so stdout stays one document. The exit code then follows the run: every outcome other than FINISHED is exit 1, with the code naming it. Watching stops after 16 minutes, and Ctrl-C stops watching rather than the script, exiting 130.","--raw-stream prints the raw frames one per line instead of the rendered console, on stderr either way, with no header and no outcome summary: a machine reads the outcome off the STREAM_END frame. --timestamps is time, iso, relative or off.","The stream is opened before the run, so a stream that cannot be opened means nothing ran: exit 1 STREAM_CONNECT_FAILED, no invocation, and a hint to re-run without the flag. Retrying is safe.","Streamed rows print in the order the frames arrive, and the order they are sent in is not guaranteed: a row can print after one stamped later than it. The stored file is ordered, so where the order of two lines carries meaning read log list-console-logs once the run has ended rather than the live view.","The outcomes map to codes: FUNCTION_ERROR is SCRIPT_ERROR (HTTP 422 with --wait), TIMED_OUT is SCRIPT_TIMEOUT (504, and the invocation is ended), ABORTED is INVOCATION_ABORTED, RUNTIME_ERROR is RUNTIME_ERROR, MALFORMED_PAYLOAD_ERROR is MALFORMED_PAYLOAD, DENIED and DISABLED are INVOCATION_NOT_RUN, and anything else is INVOCATION_FAILED naming the status. The first three reach a waited run too; the rest need --stream-logs to be seen at all.",`--response-only prints only the returned value, compact under --raw and null when the function returned nothing. It needs a waited run, and what is checked is the body actually sent: --wait on the flags path, and the body's own waitForResponse with --input, so --input {"waitForResponse":true} --response-only works without --wait and an --input body lacking the key is exit 2 with --wait beside it.`,"Without --wait or --stream-logs the request is accepted with 202 and exit 0 says only that the run started. The message carries the invocation ID and the hint carries the log list-console-logs command that reads its output, on stderr in both modes.",'A test payload must belong to an event listener targeting this script; any other is refused with "Test payload does not belong to an event listener that targets this script." Its content has to parse as a JSON object too, and neither is checked when the payload is written, so a payload saved with anything else only fails here.',"The request also carries the environment's exposed parameter values, against a larger ceiling than the payload cap, so a payload under 5 MiB can still be refused in a workspace with big parameters. The API's message says so when it happens.","Triggering a script that has been deleted is exit 1 BAD_REQUEST, `Cannot run deleted script <name>`, rather than the exit 4 a read gives."]});function parseEventPayload(text,allow="object"){let parsed;try{parsed=JSON.parse(text)}catch{return{error:"is not valid JSON."}}return allow!=="any"&&(parsed===null||typeof parsed!="object"||Array.isArray(parsed))?{error:`has to be a JSON object, e.g. ${PAYLOAD_PLACEHOLDER}.`}:{payload:parsed}}function eventPayloadError(text,allow="object"){let result=parseEventPayload(text,allow);return"error"in result?result.error:void 0}function assertEventPayload(text,label,allow="object"){assertSize(Buffer.byteLength(text,"utf8"),PAYLOAD_KIND);let result=parseEventPayload(text,allow);return"error"in result&&fail(EXIT.USAGE,"INVALID_PAYLOAD",`${label} ${result.error}`),result.payload}function assertPayloadSize(payload){payload!==void 0&&assertSize(Buffer.byteLength(JSON.stringify(payload),"utf8"),PAYLOAD_KIND)}var PAYLOAD_FETCH_CONCURRENCY=4;async function findScriptTestPayloads(client,path2){return withSpinner("Looking for test payloads",async()=>{let listeners=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListeners",{params:{path:{workspaceId:path2.workspaceId,environmentId:path2.environmentId}}});(!listeners.response.ok||!listeners.data)&&apiFail(listeners.response.status,listeners.error);let matching=listeners.data.eventListeners.filter(el=>el.script?.id===path2.scriptId),groups=[];for(let i=0;i<matching.length;i+=PAYLOAD_FETCH_CONCURRENCY){let chunk=matching.slice(i,i+PAYLOAD_FETCH_CONCURRENCY);groups.push(...await Promise.all(chunk.map(async el=>{let res=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:{workspaceId:path2.workspaceId,environmentId:path2.environmentId,eventListenerId:el.id}}});return(!res.response.ok||!res.data)&&apiFail(res.response.status,res.error),{listener:el,payloads:res.data.testPayloads}})))}let several=groups.filter(g=>g.payloads.length>0).length>1;return groups.flatMap(({listener,payloads})=>payloads.map(p=>({value:p.id,label:p.name,...several?{display:`${p.name} \xB7 ${listener.eventType?.name??listener.app.name}`}:{},hint:p.id})))})}async function askPayloadObject(opts){let previous;for(;;){let source=await askContentSource({kind:PAYLOAD_KIND,message:opts.message,pathMessage:"Path to the payload file",extensions:[".json"],placeholder:PAYLOAD_PLACEHOLDER,...opts.inlineLabel?{inlineLabel:opts.inlineLabel}:{},...opts.omitChoice?{omitChoice:opts.omitChoice}:{},...previous===void 0?{}:{currentContent:async()=>previous}});if(source.content===void 0)return{omitted:!0};let error51=eventPayloadError(source.content,opts.allow??"object");if(!error51)return assertSize(Buffer.byteLength(source.content,"utf8"),PAYLOAD_KIND),{payload:JSON.parse(source.content),omitted:!1};prompts().note(`\u2716 The event payload ${error51}`),previous=source.path?void 0:source.content}}async function askEventPayload(client,path2){if(!await prompts().confirm("Specify an event payload?",!1))return{};let testPayloads=path2?await findScriptTestPayloads(client,path2):[],answer=await askPayloadObject({message:"How do you want to provide the event payload?",...testPayloads.length>0?{omitChoice:{label:"Use an event listener test payload",hint:"from an event listener that runs this script"}}:{}});return answer.omitted?{testPayloadId:await prompts().select("Test payload",testPayloads)}:{payload:answer.payload}}async function askReplayPayload(){return(await askPayloadObject({allow:"any",message:"Replay with the original payload?",omitChoice:{label:"Use the original invocation's payload",hint:"recommended \u2014 the event exactly as it arrived"},inlineLabel:"Write a payload here"})).payload}function renderTrigger(data,waited){let detail=renderDetail({invocationId:data.invocationId});return waited?`${detail}
1360
+ ${renderResponse(data)}`:detail}function renderResponse(data){return data.response===void 0?"The function returned nothing.":`RESPONSE
1361
+ ${JSON.stringify(data.response,null,2)}`}function consoleLogsHint(invocationId,workspaceId,finished=!1){return`Read console logs with${finished?"":" (once the script has finished executing)"}: ${CLI} log list-console-logs ${invocationId} -w ${workspaceId}`}function printConsoleLogsHint(invocationId,workspaceId,finished=!1){let hint=consoleLogsHint(invocationId,workspaceId,finished);isRaw()?noteLine(hint):prompts().note(hint)}function failInvocation(status,error51,workspaceId){let body=error51,reason=body?.errorMessage??`Request failed with HTTP status ${status}.`,invocationId=body?.invocationId,suffix=invocationId?` (invocation ${invocationId})`:"",[code,message]=status===422?["SCRIPT_ERROR",`The script threw: ${reason}${suffix}`]:status===504?["SCRIPT_TIMEOUT",`The script was still running when the 20 second cap on waiting expired, and the invocation was ended as timed out: ${reason}${suffix}`]:["INVOCATION_ABORTED",`The invocation was aborted before it finished: ${reason}${suffix}`];fail(EXIT.API_ERROR,code,message,{status,expected:!0,...invocationId?{hint:consoleLogsHint(invocationId,workspaceId)}:{}})}async function askStreamLogs(){return prompts().confirm("Stream console logs back to this terminal while the script runs?",!0)}async function startLogStream(client,opts,explicit2){let stream=await openLogStream(client,{timestamps:assertChoice("--timestamps",opts.timestamps,TIMESTAMP_MODES)??"time",...opts.rawStream?{rawFrames:!0}:{}});if(stream)return stream;explicit2&&fail(EXIT.API_ERROR,"STREAMING_UNAVAILABLE","Live log streaming is not available in this deployment.",{hint:`Read the output after the run instead: ${CLI} log list-console-logs <invocationId> -w <workspaceId>`}),prompts().note("\u26A0 Live log streaming is not available in this deployment \u2014 continuing without it.")}var STREAM_DRAIN_MS=5e3;async function drainLogStream(stream,invocationId){stream.identify(invocationId),await Promise.race([stream.done(),new Promise(resolve8=>setTimeout(resolve8,STREAM_DRAIN_MS))]),stream.close()}function failStreamOutcome(result,invocationId,workspaceId){let hint=consoleLogsHint(invocationId,workspaceId),outcome=result.outcome;if(!outcome||outcome.status==="FINISHED")return;let known=outcome.status in OUTCOME_FAILURES,failure=OUTCOME_FAILURES[outcome.status],sentence=known?failure?.sentence:`The invocation ended as ${outcome.status}`,reason=outcome.message??result.lastError??"no detail was reported";fail(EXIT.API_ERROR,failure?.code??"INVOCATION_FAILED",`${sentence?`${sentence}: `:""}${reason} (invocation ${invocationId})`,{hint,...failure?.status===void 0?{}:{status:failure.status}})}var REPLAYABLE_TRIGGER_TYPES=["EXTERNAL","MANUAL_EVENT_LISTENER","CHAINED"];async function resolveReplayTarget(client,teamId,invocationIdArg,opts,interactive){if(!invocationIdArg){interactive||fail(EXIT.USAGE,"USAGE_ERROR",`<invocationId> is required. ${supplyHint()}`);let picked=await askInvocation(client,teamId,{query:{...opts.workspace?{workspaces:[opts.workspace]}:{},triggerTypes:[...REPLAYABLE_TRIGGER_TYPES]},browseFilters:()=>askBrowseScopeFilters(client,teamId,opts.workspace),browseHint:`newest ${MIN_INVOCATION_PAGE_SIZE} that can be replayed`,emptyNote:"No recent replayable invocations in this team \u2014 enter an invocation ID instead.",hint:invocation2=>`${invocation2.triggerType} \xB7 ${invocation2.executionStatus}`});if(picked.workspaceId&&picked.environmentId&&picked.scriptId)return{invocationId:picked.invocationId,workspaceId:picked.workspaceId,environmentName:picked.environmentName??picked.environmentId,environmentId:picked.environmentId,scriptId:picked.scriptId,scriptName:picked.scriptName??picked.scriptId};invocationIdArg=picked.invocationId}invocationIdArg=assertResourceId(invocationIdArg,"invocationId");let invocation=await findInvocation(client,teamId,invocationIdArg);return invocation||fail(EXIT.NOT_FOUND,"INVOCATION_NOT_FOUND",`No invocation ${invocationIdArg} in this team.`,{hint:`List what is there with: ${CLI} log list-invocation-logs --invocation-id ${invocationIdArg}`}),replayTarget(invocation)}function replayTarget(invocation){return{invocationId:invocation.invocationId,workspaceId:invocation.workspace.id,environmentId:invocation.environment.id,environmentName:invocation.environment.name,scriptId:invocation.script.id,scriptName:invocation.script.name}}var replayBodySchema=external_exports.object({environmentId:external_exports.string().min(1),scriptId:external_exports.string().min(1),eventPayload:external_exports.unknown().optional(),silent:external_exports.boolean().optional(),streamSubscriptionId:external_exports.string().min(1).optional()}).strict(),REPLAY_DOC=defineCommandDoc("script replay-invocation",{schema:replayBodySchema,body:{environmentId:"<environmentId>",scriptId:"<scriptId>",eventPayload:{issue:{key:"TEST-1"}},silent:!1},hidden:["streamSubscriptionId"],rules:["environmentId and scriptId must be the invocation's own, as reported by log list-invocation-logs; any other value is a 400. Without --input they are filled from the invocation record and there is nothing to pass, so they are required only in an --input body.",`eventPayload: any JSON value replacing the original event \u2014 an object, but an array or a scalar too, handed to the function as it is sent, up to ${CONTENT_CAP}. Spelled --payload or --payload-file <path> as a flag; omitted, the original event is delivered again.`,"silent: true withholds the live console stream from everything except a socket the caller is already holding open for the replay (--stream-logs); the replay is still recorded and its logs readable either way. A replay asked for through the API is addressed to its caller alone, so it never reaches the web application whichever value this carries.","Parameter values come from the environment as they are now, and the release deployed there is what runs. The workspace is the invocation's; --team is where the invocation is looked up.","The invocation is the positional argument or --invocation-id, and passing both is exit 2.",INVOCATION_SCOPE_RULE],notes:["Only an invocation triggered by a stored event can be replayed: EXTERNAL, MANUAL_EVENT_LISTENER and CHAINED. script trigger produces MANUAL, which is none of them, so nothing this CLI starts can be replayed afterwards \u2014 the invocation has to have arrived from outside.","There is no --wait here: --stream-logs is the way to see the outcome in one command. Beside it, --raw-stream prints every received frame verbatim as one JSON document per line instead of a rendered console, and --timestamps is time, iso, relative or off. Both are ignored without --stream-logs.","Streamed rows print in the order the frames arrive, and the order they are sent in is not guaranteed: a row can print after one stamped later than it. The stored file is ordered, so where the order of two lines carries meaning read log list-console-logs once the run has ended rather than the live view.","There is no --yes either: a terminal confirms and a script does not. -w only narrows the list the invocation is looked up in."]});function queuedAbortWarning(){return"This invocation is QUEUED, so aborting it is best effort: the request eventually lapses, and an invocation still waiting by then runs to completion. Even before it lapses it starts and is then stopped, rather than being prevented from starting."}function abortQuestion(target){return`Request that ${target.scriptName?`${target.scriptName} (${target.invocationId})`:target.invocationId} be aborted?`}function abortHint(invocationId,workspaceId){return`Aborting is a request, not a command \u2014 the invocation may still finish on its own. Confirm what it did with: ${CLI} log list-invocation-logs --invocation-id ${invocationId}
1362
+ ${consoleLogsHint(invocationId,workspaceId)}`}function failInvocationMissing(invocationId,workspaceId){fail(EXIT.NOT_FOUND,"INVOCATION_NOT_FOUND",`No invocation ${invocationId} in workspace ${workspaceId}.`,{hint:"An invocation triggered moments ago may not be recorded yet \u2014 retry briefly before treating this as a wrong ID."})}function failNotAbortable(invocationId,error51){let message=error51?.errorMessage??"The invocation has already finished.";fail(EXIT.API_ERROR,"INVOCATION_NOT_ABORTABLE",message,{hint:`Read what it did with: ${CLI} log list-invocation-logs --invocation-id ${invocationId}`})}async function abortInvocation(client,target){target.executionStatus==="QUEUED"&&prompts().note(`\u26A0 ${queuedAbortWarning()}`),canPrompt()&&!await prompts().confirm(abortQuestion(target),!1)&&fail(EXIT.CANCELLED,"CANCELLED","Abort not requested.");let{data,response,error:error51}=await withSpinner("Requesting the abort",()=>client.POST("/v1/workspace/{workspaceId}/invocation/{invocationId}/abort",{params:{path:{workspaceId:target.workspaceId,invocationId:target.invocationId}}}));response.status===404&&(warnInheritedWorkspace(target.workspaceFrom,target.workspaceId),failInvocationMissing(target.invocationId,target.workspaceId)),response.status===409&&failNotAbortable(target.invocationId,error51),(!response.ok||!data)&&apiFail(response.status,error51),okMutation("Abort requested",data,renderDetail({invocationId:data.invocationId})),isRaw()?noteLine(abortHint(data.invocationId,target.workspaceId)):prompts().note(abortHint(data.invocationId,target.workspaceId))}async function resolveScriptScope(globals,opts){let client=await apiClient(globals.instance),labels={},keys=opts.script?["workspace","environment","script"]:["workspace","environment"],resolved=await resolveParams(keys,{team:opts.team??globals.team,workspace:opts.workspace??globals.workspace,environment:opts.env??globals.env,...opts.script?{script:opts.scriptId}:{}},{client,interactive:canPrompt(),offerSession:opts.offerSession??!0,useSession:opts.useSession,labels});return{client,workspaceId:resolved.workspace??"",environmentId:resolved.environment??"",scriptId:resolved.script??"",labels}}async function askRunAfterSave(when){return prompts().confirm(`Run the script once ${when}?`,!1)}var SILENT_AFTER_SAVE="Mark the run offered after saving as silenced and withhold its live console stream from everything but --stream-logs; the invocation is still recorded, and its logs still readable (optional, refused without a TTY)";function assertSilentIsUsable(silent,interactive){!silent||interactive||fail(EXIT.USAGE,"USAGE_ERROR","--silent applies to the run offered after saving, which is only offered interactively \u2014 it does not quieten this command's own output.")}async function askTriggerRequest(client,path2,opts,interactive){let rawBody,wantStream=opts.streamLogs===!0;if(opts.input)rawBody=readInput(opts.input);else{let source={};opts.payload!==void 0?source={payload:assertEventPayload(opts.payload,"--payload")}:opts.payloadFile!==void 0?source={payload:assertEventPayload(readContentFile(opts.payloadFile,PAYLOAD_KIND),opts.payloadFile)}:opts.testPayloadId!==void 0?source={testPayloadId:opts.testPayloadId}:interactive&&(source=await askEventPayload(client,path2));let wait=opts.wait||interactive&&await prompts().confirm("Wait for the response? The wait is capped at 20 seconds and the return value is shown.",!1);!wantStream&&interactive&&(wantStream=await askStreamLogs()),rawBody=stripUndefined({functionName:opts.functionName,...source,waitForResponse:wait||void 0,silent:opts.silent||void 0})}let body=validate(triggerBodySchema,rawBody);return assertPayloadSize(body.payload),{body,wantStream}}async function runTrigger(client,path2,request,opts){let{body,wantStream}=request,waited=body.waitForResponse===!0,stream;wantStream&&(stream=await startLogStream(client,opts,opts.streamLogs===!0),stream&&(body.streamSubscriptionId=stream.subscriptionId)),stream?.start(path2.workspaceId,invocationId=>{!isRaw()&&!opts.responseOnly&&okText(`Script triggered:
1363
+ ${renderDetail({invocationId})}`)});let send2=()=>client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}/trigger",{params:{path:path2},body}),{data,response,error:error51}=stream?await send2():await withSpinner(waited?"Running the script (waiting up to 20 seconds)":"Triggering the script",send2);if(response.status===409||response.status===422||response.status===504){let failed2=error51?.invocationId;stream&&failed2?await drainLogStream(stream,failed2):stream?.close(),failInvocation(response.status,error51,path2.workspaceId)}(!response.ok||!data)&&(stream?.close(),apiFail(response.status,error51));let result=data;if(stream){stream.identify(result.invocationId);let streamed=await stream.done();failStreamOutcome(streamed,result.invocationId,path2.workspaceId),opts.responseOnly?okText(isRaw()?JSON.stringify(result.response??null):JSON.stringify(result.response??null,null,2)):isRaw()?okMutation("Script triggered",result):waited&&okText(renderResponse(result));return}opts.responseOnly?okText(isRaw()?JSON.stringify(result.response??null):JSON.stringify(result.response??null,null,2)):okMutation("Script triggered",result,renderTrigger(result,waited)),printConsoleLogsHint(result.invocationId,path2.workspaceId,waited)}function scriptCommand(){let script=new Command("script").description("Manage workspace scripts");return script.command("create").description("Create a script in a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--name <name>",`Script name, ${SCRIPT_NAME_FORMAT} (required unless --input, interactive)`).option("--file <path>","Read the script source from a file, or - for stdin (required unless --content or --input, interactive, exclusive with --content)").option("--content <source>","Script source inline (required unless --file or --input, interactive, exclusive with --file)").option("--silent",SILENT_AFTER_SAVE).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC5))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt();opts.file!==void 0&&opts.content!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--file and --content cannot be combined."),assertSilentIsUsable(opts.silent,interactive);let{client,workspaceId,environmentId}=await resolveScriptScope(globals,{...opts,offerSession:!opts.input}),rawBody;if(opts.input)rawBody=readInput(opts.input);else{let content=opts.content,sourcePath=opts.file;if(content===void 0&&sourcePath!==void 0&&(content=readScriptFile(sourcePath)),content===void 0){interactive||fail(EXIT.USAGE,"USAGE_ERROR","--file or --content is required.");let source=await askSource();content=source.content,sourcePath=source.path}let name=opts.name;name===void 0&&(interactive||fail(EXIT.USAGE,"USAGE_ERROR","--name is required."),name=await askScriptName2(sourcePath?suggestNameFromPath(sourcePath):void 0)),rawBody={name,content}}let body=validate(createBodySchema5,rawBody);body.name=assertScriptName(body.name),body.content||fail(EXIT.USAGE,"INVALID_BODY","Script content cannot be empty."),assertSize(Buffer.byteLength(body.content,"utf8"),SCRIPT_KIND);let run;interactive&&await askRunAfterSave("it is saved")&&(run=await askTriggerRequest(client,void 0,{silent:opts.silent},!0));let{data,response,error:error51}=await withSpinner("Creating script (the workspace is compiled and bundled)",()=>client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/script",{params:{path:{workspaceId,environmentId}},body}));(response.status===502||response.status===504)&&failBundleTimeout(response.status),(!response.ok||!data)&&apiFail(response.status,error51),syncScript({workspaceId,environmentId},{name:data.name,content:body.content,id:data.id}),okMutation("Script created",data,renderScriptMutation(data)),run&&await runTrigger(client,{workspaceId,environmentId,scriptId:data.id},run,{silent:opts.silent})}),script.command("update").description("Update a script").argument("[scriptId]","Script to update (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--name <name>",`Rename the script, ${SCRIPT_NAME_FORMAT} (optional, interactive)`).option("--file <path>","Read the new source from a file, or - for stdin (optional, interactive, exclusive with --content)").option("--content <source>","New source inline (optional, interactive, exclusive with --file)").option("--silent",SILENT_AFTER_SAVE).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(scriptIdArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC5))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt();opts.file!==void 0&&opts.content!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--file and --content cannot be combined."),assertSilentIsUsable(opts.silent,interactive);let{client,labels,...ids}=await resolveScriptScope(globals,{...opts,script:!0,scriptId:scriptIdArg,offerSession:!opts.input}),path2=ids,rawBody,editSource;if(opts.input)rawBody=readInput(opts.input);else{let name=opts.name,content=opts.content;content===void 0&&opts.file!==void 0&&(content=readScriptFile(opts.file));let fetched,currentScript=()=>fetched??=fetchScript(client,path2);if(interactive&&(name===void 0&&await prompts().confirm("Rename the script?",!1)&&(name=await askScriptName2(labels.script??(await currentScript()).name)),content===void 0&&await prompts().confirm("Edit the script content?",!0)&&({content}=await askSource({inlineLabel:"Edit it here",currentContent:async()=>{let fetchedScript=await currentScript();return editSource=await localEditSource(client,{workspaceId:path2.workspaceId,environmentId:path2.environmentId},{kind:"script",name:fetchedScript.name},fetchedScript.content),editSource.content}}))),name===void 0&&content===void 0){if(interactive){prompts().note("Nothing to update \u2014 neither the name nor the content changed.");return}failNothingToUpdate(["--name to rename","--file/--content to replace the source","--input"])}content??=(await currentScript()).content,rawBody=stripUndefined({name,content})}let body=validate(updateBodySchema5,rawBody);body.name!==void 0&&(body.name=assertScriptName(body.name)),body.content||fail(EXIT.USAGE,"INVALID_BODY","Script content cannot be empty."),assertSize(Buffer.byteLength(body.content,"utf8"),SCRIPT_KIND);let run;interactive&&await askRunAfterSave("the change is saved")&&(run=await askTriggerRequest(client,path2,{silent:opts.silent},!0));let{data,response,error:error51}=await withSpinner("Updating script (the workspace is compiled and bundled)",()=>client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}",{params:{path:path2},body}));(response.status===502||response.status===504)&&failBundleTimeout(response.status),(!response.ok||!data)&&apiFail(response.status,error51),syncScript({workspaceId:path2.workspaceId,environmentId:path2.environmentId},{name:data.name,content:body.content,id:data.id,...editSource===void 0?{}:{mode:editSource.mode}}),okMutation("Script updated",data,renderScriptMutation(data)),run&&await runTrigger(client,path2,run,{silent:opts.silent})}),script.command("list").description("List scripts in a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LIST_DOC6))return;let globals=cmd.optsWithGlobals(),{client,workspaceId,environmentId}=await resolveScriptScope(globals,opts),{data,response,error:error51}=await withSpinner("Fetching scripts",()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scripts",{params:{path:{workspaceId,environmentId}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({scripts:d.scripts.map(s=>({id:s.id,name:s.name}))})})}),script.command("get").description("Get a single script as the environment sees it").argument("[scriptId]","Script to get (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--content-only","Print just the script source, verbatim, for redirecting it into a file; the same bytes with or without --raw (optional)").option("--explain",EXPLAIN).action(async(scriptIdArg,opts,cmd)=>{if(explained(cmd,GET_DOC5))return;let globals=cmd.optsWithGlobals(),{client,labels:_labels,...path2}=await resolveScriptScope(globals,{...opts,script:!0,scriptId:scriptIdArg}),found2=await fetchScript(client,path2);if(opts.contentOnly){okFile(found2.content);return}ok(found2,{human:renderScript})}),script.command("delete").description("Delete a script from a workspace").argument("[scriptId]","Script to delete (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE_DESTRUCTIVE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT_GATE_DESTRUCTIVE).option("--team <teamId>",SCOPE_TEAM_FILTER_DESTRUCTIVE).option("--yes",CONFIRM_YES).option("--force","Delete even when event listeners or scheduled triggers still use the script, which are then deactivated (optional, interactive)").option("--explain",EXPLAIN).action(async(scriptIdArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC5))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt(),{client,labels,...path2}=await resolveScriptScope(globals,{...opts,script:!0,scriptId:scriptIdArg,useSession:interactive}),named=labels.script??path2.scriptId;opts.yes||(interactive||failNeedsYes(`script ${named}`),await prompts().confirm(`Delete ${named}? It is removed from the whole workspace, not just this environment. This is irreversible.`,!1)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")),await deleteScriptWithConflict(client,path2,{force:!!opts.force,interactive}),syncScriptDeleted({workspaceId:path2.workspaceId,environmentId:path2.environmentId},{id:path2.scriptId,...labels.script?{name:labels.script}:{}}),okMutation("Script deleted",{deleted:!0,id:path2.scriptId})}),script.command("trigger").description("Run a script in a workspace").argument("[scriptId]","Script to run (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--function-name <name>","Function to invoke (optional, default: the script's default export)").option("--payload <json>","Event payload as a JSON object (optional, interactive, exclusive with --payload-file and --test-payload-id)").option("--payload-file <path>","Read the event payload from a JSON file, or - for stdin (optional, interactive, exclusive with --payload and --test-payload-id)").option("--test-payload-id <testPayloadId>","Run an event listener test payload as the event; offered only when a listener targeting the script has one (optional, interactive, exclusive with --payload and --payload-file)").option("--wait","Wait for the script to return \u2014 the wait is capped at 20 seconds, and a script still running then is ended as timed out (optional, interactive, ignored with --input)").option("--response-only","Print just the value the script returned, verbatim; null when it returned nothing (optional, requires --wait or waitForResponse: true in the --input body)").option("--silent","Withhold the live console stream from everything except --stream-logs, and mark the run as silenced in the audit trail; the invocation is still recorded, and its logs still readable. A run started here is addressed to you and to nobody else regardless, so this changes nothing the web application would have seen (optional)").option("--stream-logs","Watch the script's console output live over a WebSocket until it finishes; printed on stderr, and the exit code then reflects the script's own outcome (optional, interactive)").option("--raw-stream","Print every received frame verbatim as JSON, one per line, instead of a rendered console (optional, requires --stream-logs)").option("--timestamps <mode>",`Timestamp gutter for the streamed console: ${TIMESTAMP_MODES.join(" | ")} (optional, default: time, ignored without --stream-logs)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(scriptIdArg,opts,cmd)=>{if(explained(cmd,TRIGGER_DOC))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt();[opts.payload,opts.payloadFile,opts.testPayloadId].filter(v2=>v2!==void 0).length>1&&fail(EXIT.USAGE,"USAGE_ERROR","--payload, --payload-file and --test-payload-id cannot be combined."),opts.responseOnly&&!opts.wait&&!opts.input&&fail(EXIT.USAGE,"USAGE_ERROR","--response-only requires --wait."),opts.rawStream&&!opts.streamLogs&&fail(EXIT.USAGE,"USAGE_ERROR","--raw-stream requires --stream-logs.");let{client,labels:_labels,...path2}=await resolveScriptScope(globals,{...opts,script:!0,scriptId:scriptIdArg,offerSession:!opts.input}),request=await askTriggerRequest(client,path2,opts,interactive);opts.responseOnly&&request.body.waitForResponse!==!0&&fail(EXIT.USAGE,"USAGE_ERROR","--response-only needs a waited run: the --input body must carry waitForResponse: true (--wait is a body flag, and the body supersedes it)."),await runTrigger(client,path2,request,opts)}),script.command("replay-invocation").description("Replay a past invocation through its own script, optionally with another payload").argument("[invocationId]","Invocation to replay (required unless --invocation-id, interactive)").option("--invocation-id <invocationId>",INVOCATION_ID_FLAG).option("--team <teamId>","Team ID \u2014 the invocation is looked up in it (required, interactive, session default, env SR_CONNECT_CLI_TEAM)").option("-w, --workspace <workspaceId>","Narrow the interactive invocation list (optional, ignored when the invocation is given)").option("--payload <json>","Replace the event payload with any JSON value, an array or a scalar included (optional, interactive, exclusive with --payload-file)").option("--payload-file <path>","Read the replacement event payload from a JSON file, or - for stdin (optional, interactive, exclusive with --payload)").option("--silent","Withhold the live console stream from everything except --stream-logs; the replay is still recorded, and its logs still readable. A replay asked for here is addressed to you and to nobody else regardless, so this changes nothing the web application would have seen (optional)").option("--stream-logs","Watch the replayed invocation's console output live over a WebSocket until it finishes; printed on stderr, and the exit code then reflects the script's own outcome (optional, interactive)").option("--raw-stream","Print every received frame verbatim as JSON, one per line, instead of a rendered console (optional, requires --stream-logs)").option("--timestamps <mode>",`Timestamp gutter for the streamed console: ${TIMESTAMP_MODES.join(" | ")} (optional, default: time, ignored without --stream-logs)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(invocationIdArg,opts,cmd)=>{if(explained(cmd,REPLAY_DOC))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt();opts.payload!==void 0&&opts.payloadFile!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--payload and --payload-file cannot be combined."),opts.rawStream&&!opts.streamLogs&&fail(EXIT.USAGE,"USAGE_ERROR","--raw-stream requires --stream-logs.");let flagPayload,payloadChoice="the original invocation's payload";opts.payload!==void 0?(flagPayload=assertEventPayload(opts.payload,"--payload","any"),payloadChoice="a replacement payload from --payload"):opts.payloadFile!==void 0&&(flagPayload=assertEventPayload(readContentFile(opts.payloadFile,PAYLOAD_KIND),opts.payloadFile,"any"),payloadChoice=`a replacement payload from ${opts.payloadFile}`);let client=await apiClient(globals.instance),typedInvocation=invocationFromArgs(invocationIdArg,opts.invocationId),teamId=(await resolveParams(["team"],{team:opts.team??globals.team},{client,interactive,offerSession:!1})).team??"",target=await resolveReplayTarget(client,teamId,typedInvocation,opts,interactive),rawBody,wantStream=opts.streamLogs===!0;if(opts.input)rawBody=readInput(opts.input),payloadChoice="the payload in --input";else{let eventPayload=flagPayload;eventPayload===void 0&&interactive&&(eventPayload=await askReplayPayload(),eventPayload!==void 0&&(payloadChoice="a replacement payload")),!wantStream&&interactive&&(wantStream=await askStreamLogs()),rawBody=stripUndefined({environmentId:target.environmentId,scriptId:target.scriptId,eventPayload,silent:opts.silent||void 0})}let body=validate(replayBodySchema,rawBody);if(assertPayloadSize(body.eventPayload),interactive){let namedEnvironment=body.environmentId===target.environmentId?target.environmentName:body.environmentId,namedScript=body.scriptId===target.scriptId?target.scriptName:body.scriptId;await prompts().confirm(`Replay in ${namedEnvironment} environment, through ${namedScript} script, with ${payloadChoice}? The original event is delivered again, and parameter values come from that environment as they are now.`,!0)||fail(EXIT.CANCELLED,"CANCELLED","Replay cancelled.")}let stream;wantStream&&(stream=await startLogStream(client,opts,opts.streamLogs===!0),stream&&(body.streamSubscriptionId=stream.subscriptionId)),stream?.start(target.workspaceId,invocationId=>{isRaw()||okText(`Invocation replayed:
1364
+ ${renderDetail({invocationId})}`)});let send2=()=>client.POST("/v1/workspace/{workspaceId}/invocation/{invocationId}/replay",{params:{path:{workspaceId:target.workspaceId,invocationId:target.invocationId}},body}),{data,response,error:error51}=stream?await send2():await withSpinner("Replaying the invocation",send2);if((!response.ok||!data)&&(stream?.close(),apiFail(response.status,error51)),stream){stream.identify(data.invocationId);let streamed=await stream.done();failStreamOutcome(streamed,data.invocationId,target.workspaceId),isRaw()&&okMutation("Invocation replayed",data);return}okMutation("Invocation replayed",data,renderDetail({invocationId:data.invocationId})),printConsoleLogsHint(data.invocationId,target.workspaceId)}),script.command("abort-invocation").description("Request that a queued or running invocation be aborted").argument("[invocationId]","Invocation to abort (required unless --invocation-id, interactive)").option("--invocation-id <invocationId>",INVOCATION_ID_FLAG).option("--team <teamId>","Team ID \u2014 only needed to browse invocations or pick a workspace (optional, interactive, session default, env SR_CONNECT_CLI_TEAM, ignored when the invocation and workspace are both given)").option("-w, --workspace <workspaceId>","Workspace the invocation belongs to (required unless the invocation is browsed, interactive, session default, env SR_CONNECT_CLI_WORKSPACE)").option("--explain",EXPLAIN).action(async(invocationIdArg,opts,cmd)=>{if(explained(cmd,ABORT_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),target=await resolveInvocationScope(client,invocationFromArgs(invocationIdArg,opts.invocationId),opts,globals.team,ABORT_SCOPE);await abortInvocation(client,target)}),script}var HTTP_ENDPOINT="HTTP_ENDPOINT";function withScope3(cmd,opts={}){let env=opts.gate?opts.destructive?SCOPE_ENVIRONMENT_GATE_DESTRUCTIVE:SCOPE_ENVIRONMENT_GATE:opts.destructive?SCOPE_ENVIRONMENT_DESTRUCTIVE:SCOPE_ENVIRONMENT;return cmd.option("-w, --workspace <workspaceId>",opts.destructive?SCOPE_WORKSPACE_DESTRUCTIVE:SCOPE_WORKSPACE).option("-e, --env <environmentId>",env).option("--team <teamId>",opts.destructive?SCOPE_TEAM_FILTER_DESTRUCTIVE:SCOPE_TEAM_FILTER)}async function resolveScope5(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,workspace:resolved.workspace??"",environment:resolved.environment??"",team:resolved.team}}async function resolveListenerId(scope2,provided){return provided?assertResourceId(provided,"eventListenerId"):(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<eventListenerId> is required. ${supplyHint()}`),(await resolveParams(["eventListener"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0})).eventListener??"")}var MAX_QUEUE_GROUPINGS=10,createBodySchema6=external_exports.object({appId:external_exports.string().min(1),eventListenerTypeId:external_exports.string().min(1),eventTypeId:external_exports.string().min(1),scriptId:external_exports.string().min(1).optional(),scriptName:external_exports.string().min(1).optional(),connectorId:external_exports.string().optional(),urlPath:external_exports.string().optional(),disabled:external_exports.boolean().optional(),eventQueueId:external_exports.string().optional(),eventQueueGroupings:external_exports.array(external_exports.string()).max(MAX_QUEUE_GROUPINGS).optional()}).strict().refine(body=>!(body.scriptId&&body.scriptName),{error:"scriptId and scriptName cannot be combined.",path:["scriptId"]}).refine(body=>!!(body.scriptId??body.scriptName),{error:"Either scriptId or scriptName is required.",path:["scriptId"]}),updateBodySchema6=external_exports.object({eventTypeId:external_exports.string().min(1).optional(),connectorId:external_exports.string().optional(),scriptId:external_exports.string().min(1).optional(),scriptName:external_exports.string().min(1).optional(),urlPath:external_exports.string().optional(),disabled:external_exports.boolean().optional(),eventQueueId:external_exports.string().nullable().optional(),eventQueueGroupings:external_exports.array(external_exports.string()).max(MAX_QUEUE_GROUPINGS).optional()}).strict().refine(body=>!(body.scriptId&&body.scriptName),{error:"scriptId and scriptName cannot be combined.",path:["scriptId"]}).refine(body=>Object.keys(body).length>0,{error:"At least one of eventTypeId, scriptId, scriptName, connectorId, urlPath, disabled, eventQueueId or eventQueueGroupings is required."}),SCRIPT_KEYS_RULE=`scriptId names an existing script; scriptName makes the API create one (${SCRIPT_NAME_RULE}) and attach it.`,CONNECTOR_RULE="connectorId: a connector of the same app that you may use in the team. Some listener types need one and app list does not mark which; event-listener get reports connectionRequired for a listener that already exists. A connector fits when its connectionType, as connector list reports it, is the app's connectionType in app list.",MAX_URL_PATH=200,URL_PATH_CHARSET=/^[A-Za-z0-9_-]+$/,URL_PATH_FORMAT=`letters, digits, underscores and dashes, up to ${MAX_URL_PATH} characters, stored lower-cased and unique across the deployment`;function assertUrlPath(path2){let normalized=path2.trim().toLowerCase();return normalized||fail(EXIT.USAGE,"INVALID_URL_PATH","A URL path is required."),normalized.length>MAX_URL_PATH&&fail(EXIT.USAGE,"INVALID_URL_PATH",`A URL path can be at most ${MAX_URL_PATH} characters (that one is ${normalized.length}).`),URL_PATH_CHARSET.test(normalized)||fail(EXIT.USAGE,"INVALID_URL_PATH",`Use letters, digits, underscores and dashes \u2014 '${path2}' has a character the API refuses.`),normalized}var LIST_DOC7=defineCommandDoc("event-listener list",{rules:["The workspace is -w and the environment -e; there is no positional argument."],notes:["A listener reads through the environment named: its URL path, connector and enabled state are per-environment, and the event type and script it triggers are the workspace's."]}),GET_DOC6=defineCommandDoc("event-listener get",{rules:["The event listener is the positional argument; the workspace is -w and the environment -e."],notes:["Reports the URL path, the webhook URL to register in the external application, and the setup URL, when the listener has a path in the environment named.",'It also reports connectionRequired, which is the only place the CLI can tell you whether a listener type needs a connector at all \u2014 app list does not mark which do. It reads as "a connector must be attached", never as "a connector may not be": a false there makes one optional, and such a listener still accepts a connectorId on create and update and reports it afterwards.',"In a non-HEAD environment the read reports what that release captured and nothing else: the script and the event type are absent when the release captured none, rather than borrowing the workspace's current ones. So what get shows there is safe to send straight back to update.","An absent script means the listener has nothing to run, in either kind of environment: it was never given one, or the one it had was deleted with script delete --force. The read never names a script that is gone, so what it reports is what the listener would run."]}),DELETE_DOC6=defineCommandDoc("event-listener delete",{rules:["The event listener is the positional argument; the workspace is -w and the environment -e, which gates the write rather than choosing what is deleted.","--yes skips the confirmation, and is required without a terminal."],notes:["Deletes the listener from the whole workspace. The script it triggered is left in place, as are its test payloads' only reason to exist."]}),CREATE_DOC6=defineCommandDoc("event-listener create",{schema:createBodySchema6,conditional:["scriptId","scriptName"],body:{appId:"<appId>",eventListenerTypeId:"<eventListenerTypeId>",eventTypeId:"<eventTypeId>",scriptId:"<scriptId>",scriptName:"OnIssueCreated",connectorId:"<connectorId>",urlPath:"jira-issues",disabled:!1,eventQueueId:"<eventQueueId>",eventQueueGroupings:["issue.key"]},rules:[`appId, eventListenerTypeId (spelled --listener-type-id as a flag) and eventTypeId come from ${CLI} app list: the listener type must be one of the app's and the event type one of the listener type's.`,`Exactly one of scriptId or scriptName is required. ${SCRIPT_KEYS_RULE}`,CONNECTOR_RULE,`urlPath: the path an HTTP_ENDPOINT listener answers on: ${URL_PATH_FORMAT}; omitted, the API generates one, and every other listener type gets a generated one whatever is sent. The full address comes back as webhookUrl.`,"disabled: true creates the listener disabled in the environment -e names; omitted means enabled.","eventQueueId: an event queue of the workspace; the team's plan must include event queues, which team get reports as features.eventQueues.",`eventQueueGroupings: up to ${MAX_QUEUE_GROUPINGS} field paths into the event, spelled --event-queue-grouping as a repeatable flag; events sharing the values at those paths are handed to the script in arrival order. Ignored without eventQueueId: the API answers 201 and the listener comes back with no grouping at all.`,"A new listener arrives with a seeded Default test payload, sampling the event type it was created for.","Refused in a non-HEAD environment: create in a HEAD one."],notes:[SCRIPT_NAME_BUNDLE_REPORT]}),UPDATE_DOC6=defineCommandDoc("event-listener update",{schema:updateBodySchema6,body:{eventTypeId:"<eventTypeId>",scriptId:"<scriptId>",scriptName:"OnIssueCreated",connectorId:"<connectorId>",urlPath:"jira-issues",disabled:!1,eventQueueId:"<eventQueueId>",eventQueueGroupings:["issue.key"]},rules:["An omitted key keeps the current value.",'eventTypeId moves the listener to a different event type; omitted, the current one is kept. Only a listener that has never been configured with one requires it, and a body naming neither it nor a current value is refused with 400 "Event type is required." there.',`${SCRIPT_KEYS_RULE} The two cannot be combined, and omitting both keeps the script the listener already triggers. In a non-HEAD environment the script cannot change at all, so a scriptId sent there must be the one that environment reports.`,CONNECTOR_RULE,`urlPath moves the endpoint an HTTP_ENDPOINT listener answers on, and whatever was registered with the old path stops arriving: ${URL_PATH_FORMAT}. Omitted, the path is kept where the environment has one of its own, and a non-HEAD environment that has never had one gets a generated path from the first update that touches the listener, as the notes below set out. On every other listener type it is ignored: the listener keeps the path it has.`,"disabled: true stops the listener in the environment named by -e, false starts it there (--disabled and --enabled as flags), omitted keeps the current state.","eventQueueId: an ID attaches that queue, null detaches the listener and drops the grouping with it (--no-event-queue as a flag), omitted keeps the queue as it is; attaching needs the team's plan to include event queues.",`eventQueueGroupings applies to the queue the listener is on, up to ${MAX_QUEUE_GROUPINGS} paths, spelled --event-queue-grouping as a repeatable flag; [] clears the grouping and leaves the listener queued (--no-event-queue-grouping as a flag), and on a listener with no queue it is ignored the way it is on create.`,"In a non-HEAD environment only connectorId, urlPath and disabled can change. eventTypeId, scriptId, eventQueueId and eventQueueGroupings are read-only rather than refused there: omit them, or echo back what that environment's own get reports, and only a differing value is a 400 naming it. Omitting eventTypeId is the only way to write that environment's own fields when its release captured the listener before an event type was chosen, there being nothing to echo. scriptName is refused whenever it is sent, creating a script being a shared change by definition.","Changing eventTypeId leaves the existing test payloads sampling the old event; --replace-test-payloads, a flag rather than a key, replaces them."],notes:["The URL path is per environment, and an environment that has never had one of its own gets a generated path from the first update that touches the listener there \u2014 --disabled alone included. Its webhookUrl then differs from HEAD's, and get through that environment reports no urlPath until that has happened.","--replace-test-payloads deletes the payloads that still sample the old event and seeds one from the new type; a run that passes neither it nor --no-replace-test-payloads gets a warning. An update not carrying eventTypeId cannot have moved the type, so it costs nothing; one that does could be echoing the current value, so the listener is read first to tell a move from an echo \u2014 a read --no-replace-test-payloads skips, neither outcome being possible there. In a local copy the payload files follow.",SCRIPT_NAME_BUNDLE_REPORT]});async function askUrlPath(ask){if(ask.provided!==void 0)return ask.provided;if(!ask.interactive||ask.listenerType!==HTTP_ENDPOINT)return;let typed=(await prompts().text("URL path (must be unique; edit or keep the suggestion)",{initial:ask.current??ulid(),allowEmpty:!0})).trim()||void 0;return typed===ask.current?void 0:typed}async function listenerTypeName(client,appId,listenerTypeId,known){return known||(!appId||!listenerTypeId?void 0:(await resolverChoices(client,"listenerType",{app:appId})).find(choice=>choice.value===listenerTypeId)?.label)}function suggestScriptName(eventTypeName){let pascal=(eventTypeName??"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join("");return pascal?`On${pascal}`.slice(0,MAX_SCRIPT_NAME):void 0}async function askQueueGroupings(current){let paths=[];for(let existing of current??[]){if(!await prompts().confirm(`Change field path "${existing}"?`,!1)){paths.push(existing);continue}let answer=(await prompts().text(`Field path (empty to remove "${existing}")`,{allowEmpty:!0,initial:existing})).trim();answer&&paths.push(answer)}for(;;){if(paths.length>=MAX_QUEUE_GROUPINGS){prompts().note(`\u2714 ${MAX_QUEUE_GROUPINGS} field paths \u2014 that is the maximum.`);break}let opening=paths.length===0&&!current?.length;if(!opening&&!await prompts().confirm("Add another field path?",!1))break;let answer=(await prompts().text(opening?"Field path to group events by (empty for no grouping)":"Field path",{allowEmpty:!0})).trim();if(!answer){opening||prompts().note("\u2716 A field path cannot be empty \u2014 skipping it.");break}paths.push(answer)}return paths}async function askGroupingChoice(current){return await prompts().confirm(`Group queued events by a field? (events sharing a value are processed in order, max ${MAX_QUEUE_GROUPINGS} paths)`,!1)?askQueueGroupings(current):current?.length?[]:void 0}async function askQueueAttachment(scope2,current){let eventQueueId;try{eventQueueId=(await resolveParams(["eventQueue"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0})).eventQueue}catch(err){if(!(err instanceof CliError)||err.code!=="NO_RESULTS")throw err;return prompts().note(`\u26A0 No event queues in this environment \u2014 continuing unqueued. Create one with '${CLI} event-queue create'.`),{}}return stripUndefined({eventQueueId,eventQueueGroupings:await askGroupingChoice(current?.groupings)})}function queueCell(listener){if(!listener.eventQueueId)return"\u2014";let name=listener.eventQueueName??listener.eventQueueId,groupings=listener.eventQueueGroupings;return groupings?.length?`${name} \xB7 ${groupings.join(", ")}`:name}function connectorCell2(id,name){return id?name&&name!==id?`${name} (${id})`:id:name??"\u2014"}async function askQueueOnUpdate(scope2,globals,current){let teamId=await teamForQuestions(scope2,globals);if(!teamId)return{};if(!(await withSpinner("Checking plan features",()=>teamFeatures(scope2.client,teamId))).eventQueues)return{};if(!current.eventQueueId)return await prompts().select("Event queue: not queued",[{value:"keep",label:"Leave it unqueued (current)"},{value:"attach",label:"Queue incoming events",hint:"events are held in an event queue and processed one at a time"}],{initial:"keep"})==="attach"?askQueueAttachment(scope2):{};let grouped2=current.eventQueueGroupings?.length?` \u2014 grouped by ${current.eventQueueGroupings.join(", ")}`:"",answer=await prompts().select(`Event queue: ${current.eventQueueName??current.eventQueueId}${grouped2}`,[{value:"keep",label:"Keep it as it is"},{value:"move",label:"Use a different event queue"},{value:"regroup",label:"Change what the events are grouped by"},{value:"detach",label:"Detach",hint:"deliver events straight to the script"}],{initial:"keep"});return answer==="keep"?{}:answer==="move"?askQueueAttachment(scope2,{groupings:current.eventQueueGroupings}):answer==="detach"?{eventQueueId:null}:{eventQueueGroupings:await askQueueGroupings(current.eventQueueGroupings)}}async function askQueueOnCreate(scope2,globals,opts){if(opts.eventQueueId)return stripUndefined({eventQueueId:opts.eventQueueId,eventQueueGroupings:opts.eventQueueGrouping});let teamId=await teamForQuestions(scope2,globals);return teamId?(await withSpinner("Checking plan features",()=>teamFeatures(scope2.client,teamId))).eventQueues?await prompts().confirm("Queue incoming events? (events are held in an event queue and processed one at a time)",!1)?askQueueAttachment(scope2):{}:{}:{}}var CREATE_SCRIPT="\0create-script",ENVIRONMENT_OWNED="the connector, the URL path and the enabled state";function releasedNote2(version2,environmentName){return[`${environmentName} has ${version2?`release ${version2}`:"a release"} deployed.`,`Only ${ENVIRONMENT_OWNED} can be changed there; the event type, the script and the`,"event queue belong to the event listener and are shared by every environment."].join(" ")}async function askConnectorOnUpdate(scope2,globals,current){let team=await teamForQuestions(scope2,globals);if(!team)return;let choices;try{choices=await resolverChoices(scope2.client,"connector",{team,app:current.appId,listenerType:current.listenerTypeId,workspace:scope2.workspace,environment:scope2.environment})}catch(err){if(!(err instanceof CliError))throw err;return}if(choices.length===0)return;let currentId=current.connectorId,listed=currentId?choices.some(choice=>choice.value===currentId):!1,me2=current.connectorOwner?await currentUserId(scope2.client):void 0,someoneElse=!current.connectorOwner||!me2||current.connectorOwner.id!==me2,implicit=!!currentId&&!listed&&someoneElse,KEEP="\0keep-connector",keepLabel=current.connectionName??currentId,offered=listed?choices.map(choice=>choice.value===currentId?{...choice,display:`${choice.display??choice.label} (current)`}:choice):[currentId&&keepLabel?{value:KEEP,label:keepLabel,display:`${keepLabel} (${implicit?implicitShareMark(current.connectorOwner):"current"})`}:{value:KEEP,label:"No connector",display:"No connector (current)"},...choices],initial=listed?currentId:KEEP;for(;;){let picked=await prompts().select("Connector:",offered,initial?{initial}:{});if(picked===KEEP||listed&&picked===currentId)return;if(!implicit)return picked;let replacement=choices.find(choice=>choice.value===picked)?.label??picked;if(await confirmImplicitReplacement(keepLabel??"",replacement,current.connectorOwner))return picked}}async function askScriptOnUpdate(scope2,current,suggestedName){let picked=await askKeepOrChange({client:scope2.client,key:"script",deps:{workspace:scope2.workspace,environment:scope2.environment},message:"Script:",current:{value:current.id,label:current.name},extra:[{value:CREATE_SCRIPT,label:"Create a new script\u2026"}]});return picked===CREATE_SCRIPT?{scriptName:await askScriptName(suggestedName)}:picked===void 0?{}:{scriptId:picked}}var NO_CONNECTOR2="\0no-connector";async function askConnectorOnCreate2(scope2,globals,current){let team=await teamForQuestions(scope2,globals);if(!team)return;let choices;try{choices=await resolverChoices(scope2.client,"connector",{team,app:current.appId,listenerType:current.listenerTypeId,workspace:scope2.workspace,environment:scope2.environment})}catch(err){if(!(err instanceof CliError))throw err;return}if(choices.length===0){prompts().note("\u26A0 No connector compatible with the selected app exists in the team \u2014 continuing without one.");return}let picked=await prompts().select("Connector:",[{value:NO_CONNECTOR2,label:"No connector",hint:"required by some listener types; attach one later"},...choices],{initial:choices[0]?.value??NO_CONNECTOR2});return picked===NO_CONNECTOR2?void 0:picked}var RECOMMEND_CREATE="recommended \u2014 the entry function is generated for the event type";async function fillCreateBody2(scope2,globals,opts){let labels={},resolved=await resolveParams(["app","listenerType","eventType"],{app:opts.appId,listenerType:opts.listenerTypeId,eventType:opts.eventTypeId,workspace:scope2.workspace,environment:scope2.environment,team:globals.team},{client:scope2.client,interactive:!0,labels,registry:listenerAppRegistry()}),script=opts.scriptId??opts.scriptName?{scriptId:opts.scriptId,scriptName:opts.scriptName}:await askScript({client:scope2.client,workspace:scope2.workspace,environment:scope2.environment,message:"Script to handle the event:",suggestedName:suggestScriptName(labels.eventType),recommendCreate:RECOMMEND_CREATE}),urlPath=await askUrlPath({provided:opts.urlPath,listenerType:opts.urlPath===void 0?await listenerTypeName(scope2.client,resolved.app,resolved.listenerType,labels.listenerType):void 0,interactive:!0}),connectorId=opts.connectorId??await askConnectorOnCreate2(scope2,globals,{appId:resolved.app??"",listenerTypeId:resolved.listenerType??""}),queue=await askQueueOnCreate(scope2,globals,opts);return stripUndefined({appId:resolved.app,eventListenerTypeId:resolved.listenerType,eventTypeId:resolved.eventType,scriptId:script.scriptId,scriptName:script.scriptName,connectorId,urlPath,disabled:opts.disabled,...queue})}var DEFAULT_PAYLOAD_NAME="Default",PAYLOAD_CONCURRENCY=5;function plural3(count,noun){return`${count} ${noun}${count===1?"":"s"}`}function eventTypeMoved(plan){return plan.eventTypeChanged??!1}async function refreshTestPayloads(scope2,eventListenerId){let path2={workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId},list=await withSpinner("Fetching test payloads",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:path2}}));(!list.response.ok||!list.data)&&apiFail(list.response.status,list.error);let existing=list.data.testPayloads;if(existing.length===0)return{deleted:[]};let taken=new Set(existing.map(payload=>payload.name)),name=DEFAULT_PAYLOAD_NAME;for(let n=2;taken.has(name);n+=1)name=`${DEFAULT_PAYLOAD_NAME} ${n}`;let created=await withSpinner("Creating test payload for the new event type",()=>scope2.client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload",{params:{path:path2},body:{name}}));(!created.response.ok||!created.data)&&apiFail(created.response.status,created.error),await withSpinner(`Deleting ${plural3(existing.length,"old test payload")}`,()=>throttleAll(PAYLOAD_CONCURRENCY,existing.map(payload=>async()=>{let{response,error:error51}=await scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{...path2,testPayloadId:payload.id}}});response.ok||apiFail(response.status,error51)})));let final=created.data;if(final.name!==DEFAULT_PAYLOAD_NAME){let renamed=await withSpinner("Renaming the new test payload",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{...path2,testPayloadId:created.data.id}},body:{name:DEFAULT_PAYLOAD_NAME}}));renamed.response.ok&&renamed.data&&(final=renamed.data)}return{created:final,deleted:existing}}async function buildUpdateBody3(scope2,globals,eventListenerId,opts,plan={}){let interactive=!opts.input&&canPrompt();opts.eventQueue===!1&&opts.eventQueueId&&fail(EXIT.USAGE,"USAGE_ERROR","--no-event-queue cannot be combined with --event-queue-id.");let listenerType,currentUrlPath,currentQueue={},eventTypeId=opts.eventTypeId,scriptId=opts.scriptId,scriptName=opts.scriptName,connectorId=opts.connectorId,disabled=disabledFromFlags(opts),queue={},releasedEnvironment=!1;if(interactive){let current=await withSpinner("Fetching event listener",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}}}));(!current.response.ok||!current.data)&&apiFail(current.response.status,current.error),listenerType=current.data.eventListenerType.name,currentUrlPath=current.data.urlPath,currentQueue={eventQueueId:current.data.eventQueueId,eventQueueName:current.data.eventQueueName,eventQueueGroupings:current.data.eventQueueGroupings};let release2=await withSpinner("Checking the environment",()=>environmentRelease(scope2.client,scope2.workspace,scope2.environment));if(releasedEnvironment=!!release2,release2?prompts().note(`\u26A0 ${releasedNote2(release2.version,"This environment")}`):eventTypeId||(eventTypeId=await askKeepOrChange({client:scope2.client,key:"eventType",deps:{app:current.data.app.id,listenerType:current.data.eventListenerType.id},message:"Event type:",current:{value:current.data.eventType?.id,label:current.data.eventType?.name}})),plan.eventTypeChanged=eventTypeId!==void 0&&eventTypeId!==current.data.eventType?.id,plan.eventTypeChanged&&(plan.replace=opts.replaceTestPayloads??await prompts().confirm("The event type changed. Replace the test payloads with a fresh sample of the new event? Existing payloads are deleted, edits included.",!1)),!release2&&!scriptId&&!scriptName){let picked=await askScriptOnUpdate(scope2,{id:current.data.script?.id,name:current.data.script?.name},suggestScriptName(current.data.eventType?.name));scriptId=picked.scriptId,scriptName=picked.scriptName}connectorId??=await askConnectorOnUpdate(scope2,globals,{connectorId:current.data.connectorId,connectionName:current.data.connectionName,connectorOwner:current.data.connectorOwner,appId:current.data.app.id,listenerTypeId:current.data.eventListenerType.id}),disabled??=await askStatus(current.data.disabled,"the event listener")}let urlPath=await askUrlPath({provided:opts.urlPath,listenerType,current:currentUrlPath,interactive}),groupingFlag=opts.eventQueueGrouping===!1?[]:opts.eventQueueGrouping??void 0;return opts.eventQueue===!1?queue={eventQueueId:null}:opts.eventQueueId||groupingFlag?queue=stripUndefined({eventQueueId:opts.eventQueueId,eventQueueGroupings:groupingFlag}):interactive&&!releasedEnvironment&&(queue=await askQueueOnUpdate(scope2,globals,currentQueue)),opts.input?readInput(opts.input):{...stripUndefined({eventTypeId,connectorId,scriptId,scriptName,urlPath,disabled}),...queue}}async function recordEventTypeMove(scope2,eventListenerId,body,opts,plan){if(plan.eventTypeChanged!==void 0||opts.replaceTestPayloads===!1||body.eventTypeId===void 0)return;let current=await withSpinner("Fetching event listener",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}}}));current.response.ok&&current.data&&(plan.eventTypeChanged=body.eventTypeId!==current.data.eventType?.id)}function eventListenerCommand(){let el=new Command("event-listener").alias("el").description("Manage workspace event listeners");return withScope3(el.command("list").description("List event listeners in a workspace")).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC7))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope5(globals),{data,response,error:error51}=await withSpinner("Fetching event listeners",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListeners",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({eventListeners:tableRows(["id","app","eventListenerType","disabled","script","eventType","connector","urlPath","queue"],d.eventListeners.map(listener=>({...listener,connector:listener.connectionName??"\u2014",urlPath:listener.urlPath??"\u2014",queue:queueCell(listener)})))})})}),withScope3(el.command("get").description("Get a single event listener as the environment sees it").argument("[eventListenerId]","Event listener ID (required, interactive)")).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,GET_DOC6))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope5(globals),eventListenerId=await resolveListenerId(scope2,idArg),{data,response,error:error51}=await withSpinner("Fetching event listener",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:({eventQueueId:_id,eventQueueName:_name,eventQueueGroupings:_g,connectorId,connectionName,connectorOwner,...rest})=>({...rest,...connectorId||connectionName?{connector:connectorCell2(connectorId,connectionName)}:{},...connectorOwner?{connectorOwner:personCell(connectorOwner)}:{},queue:queueCell(data)})})}),withScope3(el.command("create").description("Create an event listener in a workspace")).option("--app-id <id>",`App ID, see ${CLI} app list (required unless --input, interactive)`).option("--listener-type-id <id>","Event listener type ID for the app (required unless --input, interactive)").option("--event-type-id <id>","Event type ID for the listener type (required unless --input, interactive)").option("--script-id <id>","Existing script ID to attach (required unless --script-name or --input, interactive, exclusive with --script-name)").option("--script-name <name>","Script name to create and attach (required unless --script-id or --input, interactive, exclusive with --script-id)").option("--connector-id <id>","Connector ID, required by some listener types, which app list does not mark (optional, interactive)").option("--url-path <path>","Custom URL path an HTTP_ENDPOINT listener answers on (optional, interactive for HTTP_ENDPOINT only, API default: a generated path, ignored on every other listener type)").option("--disabled","Create the listener disabled (optional, API default: enabled)").option("--event-queue-id <id>","Event queue ID to attach (optional, interactive on a plan with event queues)").option("--event-queue-grouping <fieldPath>",`Event queue grouping field path, max ${MAX_QUEUE_GROUPINGS}; repeat the flag or comma-separate (optional, interactive, repeatable, ignored without --event-queue-id)`,collect).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC6))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope5(globals),interactive=!opts.input&&canPrompt(),hasAllRequired=opts.appId&&opts.listenerTypeId&&opts.eventTypeId&&(opts.scriptId??opts.scriptName),rawBody;if(opts.input)rawBody=readInput(opts.input);else if(interactive&&!hasAllRequired)rawBody=await fillCreateBody2(scope2,globals,opts);else{let urlPath=await askUrlPath({provided:opts.urlPath,listenerType:interactive&&opts.urlPath===void 0?await listenerTypeName(scope2.client,opts.appId,opts.listenerTypeId):void 0,interactive});rawBody=stripUndefined({appId:opts.appId,eventListenerTypeId:opts.listenerTypeId,eventTypeId:opts.eventTypeId,scriptId:opts.scriptId,scriptName:opts.scriptName,connectorId:opts.connectorId,urlPath,disabled:opts.disabled,eventQueueId:opts.eventQueueId,eventQueueGroupings:opts.eventQueueGrouping})}let parsed=validate(createBodySchema6,rawBody),body={...parsed,...parsed.scriptName===void 0?{}:{scriptName:assertScriptName(parsed.scriptName)},...parsed.urlPath===void 0?{}:{urlPath:assertUrlPath(parsed.urlPath)}},{data,response,error:error51}=await withSpinner("Creating event listener",()=>scope2.client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}},body}));(!response.ok||!data)&&apiFail(response.status,error51),await syncNewEventListener(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},data.eventListenerId),await syncPackages(scope2.client,scope2.workspace),body.scriptName!==void 0&&await syncScriptFromServer(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},data.scriptId),okMutation("Event listener created",data,bundleReportDetail(data,data))}),withScope3(el.command("update").description("Update an event listener").argument("[eventListenerId]","Event listener ID (required, interactive)")).option("--event-type-id <id>","Event type ID for the listener type (optional, interactive on HEAD only, default: the current event type, refused when it differs from what a non-HEAD environment reports)").option("--connector-id <id>","Connector ID, required by some listener types, which app list does not mark (optional, interactive)").option("--script-id <id>","Existing script ID to attach (optional, interactive on HEAD only, exclusive with --script-name, refused when it differs from what a non-HEAD environment reports)").option("--script-name <name>","Script name to create and attach (optional, interactive on HEAD only, exclusive with --script-id, refused in a non-HEAD environment)").option("--url-path <path>","Custom URL path an HTTP_ENDPOINT listener answers on (optional, interactive for HTTP_ENDPOINT only, default: the current path, ignored on every other listener type)").option("--disabled","Disable the listener (optional, interactive, exclusive with --enabled)").option("--enabled","Enable the listener (optional, interactive, exclusive with --disabled)").option("--event-queue-id <id>","Event queue ID to attach; omitting it keeps the current queue (optional, interactive on HEAD only, exclusive with --no-event-queue, refused when it differs from what a non-HEAD environment reports)").option("--no-event-queue","Detach the event queue so events go straight to the script, also dropping the grouping (optional, interactive on HEAD only, exclusive with --event-queue-id, refused when it differs from what a non-HEAD environment reports)").option("--event-queue-grouping <fieldPath>",`Event queue grouping field path, max ${MAX_QUEUE_GROUPINGS}; repeat the flag or comma-separate, applies to the queue the listener is on (optional, interactive on HEAD only, repeatable, refused when it differs from what a non-HEAD environment reports)`,collect).option("--no-event-queue-grouping","Clear the grouping, leaving the listener queued (optional, interactive on HEAD only, refused when it differs from what a non-HEAD environment reports)").option("--replace-test-payloads","When the event type changes, delete the existing test payloads and create one seeded from the new event (optional, interactive, exclusive with --no-replace-test-payloads, ignored when the event type does not change)").option("--no-replace-test-payloads","Keep the existing test payloads even though they sample the old event (optional, interactive, exclusive with --replace-test-payloads, ignored when the event type does not change)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC6))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope5(globals),eventListenerId=await resolveListenerId(scope2,idArg),payloads={},rawBody=await buildUpdateBody3(scope2,globals,eventListenerId,opts,payloads),empty=typeof rawBody=="object"&&Object.keys(rawBody??{}).length===0;if(canPrompt()&&!opts.input&&empty){prompts().note("Nothing to update \u2014 the event listener was left as it is.");return}empty&&!opts.input&&failNothingToUpdate(["--event-type-id","--script-id/--script-name","--connector-id","--url-path","--disabled/--enabled","a queue flag","--input"]);let parsed=validate(updateBodySchema6,rawBody),body={...parsed,...parsed.scriptName===void 0?{}:{scriptName:assertScriptName(parsed.scriptName)},...parsed.urlPath===void 0?{}:{urlPath:assertUrlPath(parsed.urlPath)}};await recordEventTypeMove(scope2,eventListenerId,body,opts,payloads);let{data,response,error:error51}=await withSpinner("Updating event listener",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}},body}));(!response.ok||!data)&&apiFail(response.status,error51),await syncEventListenerFolder(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},eventListenerId,"rename"),await syncPackages(scope2.client,scope2.workspace),body.scriptName!==void 0&&data.scriptId!==void 0&&await syncScriptFromServer(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},data.scriptId);let syncScope={workspaceId:scope2.workspace,environmentId:scope2.environment},typeChanged=eventTypeMoved(payloads);if(payloads.replace??(typeChanged&&opts.replaceTestPayloads)){let refreshed2=await refreshTestPayloads(scope2,eventListenerId);for(let gone of refreshed2.deleted)await syncTestPayloadDeleted(scope2.client,syncScope,eventListenerId,{id:gone.id});refreshed2.created&&await syncTestPayloadById(scope2.client,syncScope,eventListenerId,refreshed2.created.id)}else if(typeChanged&&opts.replaceTestPayloads!==!1){let movedTo=body.eventTypeId??"<eventTypeId>";warnLine(`\u26A0 The event listener's test payloads still sample the previous event type. Replace them with \`${CLI} event-listener update ${eventListenerId} --event-type-id ${movedTo} --replace-test-payloads\`.`)}okMutation("Event listener updated",{updated:!0,id:eventListenerId,...data},bundleReportDetail({id:eventListenerId,...data},data))}),withScope3(el.command("delete").description("Delete an event listener from a workspace").argument("[eventListenerId]","Event listener ID (required, interactive)"),{destructive:!0,gate:!0}).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC6))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope5(globals,{useSession:canPrompt()}),eventListenerId=await resolveListenerId(scope2,idArg);opts.yes||(canPrompt()||failNeedsYes(`event listener ${eventListenerId}`),await prompts().confirm(`Delete event listener ${eventListenerId}? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."));let{response,error:error51}=await withSpinner("Deleting event listener",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}}}));response.ok||apiFail(response.status,error51),await syncEventListenerFolder(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},eventListenerId,"delete"),await syncPackages(scope2.client,scope2.workspace),okMutation("Event listener deleted",{deleted:!0,id:eventListenerId})}),el}import{basename as basename4,extname as extname2}from"path";var TEST_PAYLOAD_NAME_FORMAT="up to 50 characters",MAX_TEST_PAYLOAD_NAME=50;function normalizeTestPayloadName(name){return name.trim()}function testPayloadNameError(name){let normalized=normalizeTestPayloadName(name);if(!normalized)return"A test payload name is required.";if(normalized.length>MAX_TEST_PAYLOAD_NAME)return`A test payload name can be at most ${MAX_TEST_PAYLOAD_NAME} characters (that one is ${normalized.length}).`}function assertTestPayloadName(name){let error51=testPayloadNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_TEST_PAYLOAD_NAME",error51),normalizeTestPayloadName(name)}function suggestPayloadNameFromPath(path2){let cleaned=normalizeTestPayloadName(basename4(path2,extname2(path2)));return testPayloadNameError(cleaned)?void 0:cleaned}var PAYLOAD_KIND2={noun:"Test payload",tooLargeCode:"TEST_PAYLOAD_TOO_LARGE",language:"json"},NAME_PROMPT2=`Test payload name (${TEST_PAYLOAD_NAME_FORMAT})`,SOURCE_PROMPT="How do you want to provide the payload content?",SEED_CHOICE={label:"Edit the sample event here",hint:"recommended \u2014 seeded from the event type, opens in the editor"};function withScope4(cmd,opts={}){return cmd.option("-w, --workspace <workspaceId>",opts.destructive?SCOPE_WORKSPACE_DESTRUCTIVE:SCOPE_WORKSPACE).option("-e, --env <environmentId>",opts.destructive?SCOPE_ENVIRONMENT_DESTRUCTIVE:SCOPE_ENVIRONMENT).option("--team <teamId>",opts.destructive?SCOPE_TEAM_FILTER_DESTRUCTIVE:SCOPE_TEAM_FILTER).option("--event-listener-id <eventListenerId>","Event listener ID (required, interactive)")}async function resolveScope6(globals,opts,extra={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:opts.team??globals.team,workspace:opts.workspace??globals.workspace,environment:opts.env??globals.env},{client,interactive:canPrompt(),useSession:extra.useSession});return{client,workspace:resolved.workspace??"",environment:resolved.environment??""}}async function resolveListener(scope2,provided){return provided?assertResourceId(provided,"eventListenerId"):(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR","--event-listener-id is required."),(await resolveParams(["eventListener"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0})).eventListener??"")}async function resolvePayload(scope2,eventListenerId,provided){if(provided)return{id:assertResourceId(provided,"testPayloadId")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<testPayloadId> is required. ${supplyHint()}`);let labels={};return{id:(await resolveParams(["testPayload"],{workspace:scope2.workspace,environment:scope2.environment,eventListener:eventListenerId},{client:scope2.client,interactive:!0,labels})).testPayload??"",label:labels.testPayload}}var createBodySchema7=external_exports.object({name:external_exports.string().min(1),content:external_exports.string().optional(),default:external_exports.boolean().optional()}).strict(),updateBodySchema7=external_exports.object({content:external_exports.string().optional(),name:external_exports.string().min(1).optional()}).strict().refine(body=>body.content!==void 0||body.name!==void 0,{error:"Either content or name is required.",path:["name"]}),CONTENT_CAP2=`${MAX_CONTENT_BYTES/1024/1024} MiB`,LIST_DOC8=defineCommandDoc("event-listener-test-payload list",{rules:["The listener is --event-listener-id; the workspace is -w and the environment -e. There is no positional argument."],notes:["A listener's payloads are the same in every environment. Which one is the default is user-specific and environment-specific, so the default column is yours and not a colleague's."]}),GET_DOC7=defineCommandDoc("event-listener-test-payload get",{rules:["The payload is the positional argument and the listener is --event-listener-id; the workspace is -w and the environment -e.","--content-only prints the stored bytes alone, identically with or without --raw, so `\u2026 --content-only > payload.json` writes the file."],notes:["The content is stored verbatim and never parsed, so a payload saved as something other than a JSON object reads back unchanged and only fails when a trigger runs it."]}),SET_DEFAULT_DOC=defineCommandDoc("event-listener-test-payload set-default",{rules:["The payload is the positional argument and the listener is --event-listener-id; the workspace is -w and the environment -e, which is the environment the choice is made in."],notes:["User-specific and environment-specific: a colleague's manual trigger still runs whatever they picked."]}),DELETE_DOC7=defineCommandDoc("event-listener-test-payload delete",{rules:["The payload is the positional argument and the listener is --event-listener-id; the workspace is -w and the environment -e.","--yes skips the confirmation, and is required without a terminal."],notes:["The last remaining payload of a listener cannot be deleted.","Anyone who had chosen this one falls back to the payload named Default."]}),CREATE_DOC7=defineCommandDoc("event-listener-test-payload create",{schema:createBodySchema7,body:{name:"Issue created",content:'{ "issue": { "key": "TEST-1" } }',default:!0},rules:[`name: ${TEST_PAYLOAD_NAME_FORMAT}, trimmed, no charset rule, unique within the listener.`,`content: the event as text, spelled --content or --file <path> as a flag, up to ${CONTENT_CAP2}, stored verbatim and never parsed; omitted, the API seeds the payload with the sample event for the listener's event type; "" is refused.`,"default: true also makes it the payload a manual trigger runs, for your user in the environment -e names.","The listener is --event-listener-id, not a body key; a listener's payloads are shared by every environment of the workspace."]}),UPDATE_DOC7=defineCommandDoc("event-listener-test-payload update",{schema:updateBodySchema7,body:{name:"Issue created",content:'{ "issue": { "key": "TEST-1" } }'},rules:["At least one of content or name is required; an omitted key keeps the current value, and a rename travels without content.",`name: ${TEST_PAYLOAD_NAME_FORMAT}, trimmed, unique within the listener.`,`content: the whole new event as text, spelled --content or --file <path> as a flag, up to ${CONTENT_CAP2}, stored verbatim; "" is refused.`,"The listener is --event-listener-id and the payload the positional argument; neither is a body key."]});async function askPayloadName(suggested){for(;;){let answer=await prompts().text(NAME_PROMPT2,{...suggested?{initial:suggested}:{},allowEmpty:!0}),error51=testPayloadNameError(answer);if(!error51)return normalizeTestPayloadName(answer);prompts().note(`\u2716 ${error51}`)}}function askPayloadSource(opts){return askContentSource({kind:PAYLOAD_KIND2,message:SOURCE_PROMPT,pathMessage:"Path to the payload file",extensions:[".json"],placeholder:PAYLOAD_PLACEHOLDER2,...opts.allowSeed?{omitChoice:SEED_CHOICE}:{},...opts.inlineLabel?{inlineLabel:opts.inlineLabel}:{},...opts.currentContent?{currentContent:opts.currentContent}:{}})}var PAYLOAD_PLACEHOLDER2='{ "issue": { "key": "TEST-1" } }';async function fetchPayload(client,path2,label="Fetching test payload"){let{data,response,error:error51}=await withSpinner(label,()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:path2}}));return(!response.ok||!data)&&apiFail(response.status,error51),data}async function setDefaultPayload(client,path2){let{response,error:error51}=await withSpinner("Setting default test payload",()=>client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}/default",{params:{path:path2}}));response.ok||apiFail(response.status,error51)}async function editSeededContent(client,path2){let seeded=await fetchPayload(client,path2,"Fetching the seeded sample event"),edited=await askInlineContent(PAYLOAD_KIND2,{initial:seeded.content,placeholder:PAYLOAD_PLACEHOLDER2});if(edited===seeded.content)return{changed:!1};assertSize(Buffer.byteLength(edited,"utf8"),PAYLOAD_KIND2);let{response,error:error51}=await withSpinner("Saving the edited sample event",()=>client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:path2},body:{content:edited}}));return response.ok||apiFail(response.status,error51),{changed:!0}}function formatContent(content){try{return JSON.stringify(JSON.parse(content),null,2)}catch{return content}}function renderPayload(payload){return`${renderDetail({id:payload.id,name:payload.name})}
1365
+ CONTENT
1366
+ ${formatContent(payload.content)}`}function assertOneSource(opts){opts.file!==void 0&&opts.content!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--file and --content cannot be combined.")}function eventListenerTestPayloadCommand(){let tp=new Command("event-listener-test-payload").alias("tp").description("Manage the test payloads a manual event listener trigger runs");return withScope4(tp.command("list").description("List an event listener's test payloads")).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LIST_DOC8))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope6(globals,opts),eventListenerId=await resolveListener(scope2,opts.eventListenerId),{data,response,error:error51}=await withSpinner("Fetching test payloads",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({testPayloads:d.testPayloads.map(p=>({id:p.id,name:p.name,default:p.id===d.defaultTestPayloadId?"\u2714":""}))})})}),withScope4(tp.command("get").description("Get a single test payload with its content").argument("[testPayloadId]","Test payload ID (required, interactive)")).option("--content-only","Print just the payload content, verbatim, for redirecting it into a file; the same bytes with or without --raw (optional)").option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,GET_DOC7))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope6(globals,opts),eventListenerId=await resolveListener(scope2,opts.eventListenerId),picked=await resolvePayload(scope2,eventListenerId,idArg),payload=await fetchPayload(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId,testPayloadId:picked.id});if(opts.contentOnly){okFile(payload.content);return}ok(payload,{human:renderPayload})}),withScope4(tp.command("create").description("Create a test payload for an event listener")).option("--name <name>",`Test payload name, ${TEST_PAYLOAD_NAME_FORMAT} (required unless --input, interactive)`).option("--file <path>","Read the payload content from a file, or - for stdin (optional, interactive, exclusive with --content, API default: the sample event for the event type)").option("--content <json>","Payload content inline (optional, interactive, exclusive with --file, API default: the sample event for the event type)").option("--default","Also make it the payload a manual trigger runs (optional, interactive)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC7))return;let globals=cmd.optsWithGlobals();assertOneSource(opts);let scope2=await resolveScope6(globals,opts),eventListenerId=await resolveListener(scope2,opts.eventListenerId),seedThenEdit=!1,rawBody;if(opts.input)rawBody=readInput(opts.input);else{let content=opts.content,sourcePath=opts.file;if(content===void 0&&sourcePath!==void 0&&(content=readContentFile(sourcePath,PAYLOAD_KIND2)),opts.name===void 0&&canPrompt()){if(content===void 0){let source=await askPayloadSource({allowSeed:!0});content=source.content,sourcePath=source.path,seedThenEdit=content===void 0}let name=await askPayloadName(sourcePath?suggestPayloadNameFromPath(sourcePath):void 0),asDefault=seedThenEdit?opts.default:opts.default??await prompts().confirm("Make this the payload a manual trigger runs?",!1);rawBody=stripUndefined({name,content,default:asDefault||void 0})}else opts.name===void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--name is required."),rawBody=stripUndefined({name:opts.name,content,default:opts.default})}let body=validate(createBodySchema7,rawBody);body.name=assertTestPayloadName(body.name),body.content!==void 0&&(body.content||fail(EXIT.USAGE,"INVALID_BODY","Test payload content cannot be empty \u2014 omit it to seed the sample event instead."),assertSize(Buffer.byteLength(body.content,"utf8"),PAYLOAD_KIND2));let{data,response,error:error51}=await withSpinner("Creating test payload",()=>scope2.client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId}},body}));if((!response.ok||!data)&&apiFail(response.status,error51),seedThenEdit){let path2={workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId,testPayloadId:data.id};await editSeededContent(scope2.client,path2),opts.default===void 0&&await prompts().confirm("Make this the payload a manual trigger runs?",!1)&&await setDefaultPayload(scope2.client,path2)}let payloadScope={workspaceId:scope2.workspace,environmentId:scope2.environment};body.content===void 0?await syncTestPayloadById(scope2.client,payloadScope,eventListenerId,data.id):await syncTestPayload(scope2.client,payloadScope,eventListenerId,{name:data.name,content:body.content,id:data.id}),okMutation("Test payload created",data,data),body.content===void 0&&!seedThenEdit&&canPrompt()&&prompts().note(`Seeded with the sample event \u2014 read it with \`get ${data.id}\`.`)}),withScope4(tp.command("update").description("Replace a test payload's content and/or rename it").argument("[testPayloadId]","Test payload ID (required, interactive)")).option("--name <name>",`Rename the test payload, ${TEST_PAYLOAD_NAME_FORMAT} (optional, interactive)`).option("--file <path>","Read the new content from a file, or - for stdin (optional, interactive, exclusive with --content)").option("--content <json>","New content inline (optional, interactive, exclusive with --file)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC7))return;let globals=cmd.optsWithGlobals(),interactive=!opts.input&&canPrompt();assertOneSource(opts);let scope2=await resolveScope6(globals,opts),eventListenerId=await resolveListener(scope2,opts.eventListenerId),picked=await resolvePayload(scope2,eventListenerId,idArg),path2={workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId,testPayloadId:picked.id},editSource,rawBody;if(opts.input)rawBody=readInput(opts.input);else{let name=opts.name,content=opts.content;if(content===void 0&&opts.file!==void 0&&(content=readContentFile(opts.file,PAYLOAD_KIND2)),interactive&&(name===void 0&&await prompts().confirm("Rename the test payload?",!1)&&(name=await askPayloadName(picked.label)),content===void 0&&await prompts().confirm("Replace the payload content?",!0)&&({content}=await askPayloadSource({inlineLabel:"Edit it here",currentContent:async()=>{let current=await fetchPayload(scope2.client,path2);return editSource=await localEditSource(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},{kind:"payload",eventListenerId,name:current.name},current.content),editSource.content}}))),name===void 0&&content===void 0){if(interactive){prompts().note("Nothing to update \u2014 neither the name nor the content changed.");return}failNothingToUpdate(["--name to rename","--file/--content to replace the content","--input"])}rawBody=stripUndefined({name,content})}let body=validate(updateBodySchema7,rawBody);body.name!==void 0&&(body.name=assertTestPayloadName(body.name)),body.content!==void 0&&(body.content||fail(EXIT.USAGE,"INVALID_BODY","Test payload content cannot be empty."),assertSize(Buffer.byteLength(body.content,"utf8"),PAYLOAD_KIND2));let{data,response,error:error51}=await withSpinner("Updating test payload",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:path2},body}));(!response.ok||!data)&&apiFail(response.status,error51);let payloadScope={workspaceId:scope2.workspace,environmentId:scope2.environment};body.content===void 0?await syncTestPayloadRenamed(scope2.client,payloadScope,eventListenerId,{id:data.id,name:data.name}):await syncTestPayload(scope2.client,payloadScope,eventListenerId,{name:data.name,content:body.content,id:data.id,...editSource===void 0?{}:{mode:editSource.mode}}),okMutation("Test payload updated",data,data)}),withScope4(tp.command("set-default").description("Make a test payload the one a manual trigger runs").argument("[testPayloadId]","Test payload ID (required, interactive)")).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,SET_DEFAULT_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope6(globals,opts),eventListenerId=await resolveListener(scope2,opts.eventListenerId),picked=await resolvePayload(scope2,eventListenerId,idArg);await setDefaultPayload(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId,testPayloadId:picked.id}),okMutation("Default test payload set for your user in this environment",{updated:!0,id:picked.id})}),withScope4(tp.command("delete").description("Delete a test payload").argument("[testPayloadId]","Test payload ID (required, interactive)"),{destructive:!0}).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC7))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope6(globals,opts,{useSession:canPrompt()}),eventListenerId=await resolveListener(scope2,opts.eventListenerId),picked=await resolvePayload(scope2,eventListenerId,idArg),named=picked.label??picked.id;opts.yes||(canPrompt()||failNeedsYes(`test payload ${named}`),await prompts().confirm(`Delete ${named}? It is removed from the whole workspace, along with every user's choice of it as the payload a manual trigger runs. This is irreversible.`,!1)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."));let{response,error:error51}=await withSpinner("Deleting test payload",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventListenerId,testPayloadId:picked.id}}}));response.ok||apiFail(response.status,error51),await syncTestPayloadDeleted(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment},eventListenerId,{id:picked.id,...picked.label?{name:picked.label}:{}}),okMutation("Test payload deleted",{deleted:!0,id:picked.id})}),tp}var EVENT_QUEUE_NAME_FORMAT="up to 100 characters",MAX_EVENT_QUEUE_NAME=100;function normalizeEventQueueName(name){return name.trim()}function eventQueueNameError(name){let normalized=normalizeEventQueueName(name);if(!normalized)return"An event queue name is required.";if(normalized.length>MAX_EVENT_QUEUE_NAME)return`An event queue name can be at most ${MAX_EVENT_QUEUE_NAME} characters (that one is ${normalized.length}).`}function assertEventQueueName(name){let error51=eventQueueNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_EVENT_QUEUE_NAME",error51),normalizeEventQueueName(name)}function evictionThresholdError(minutes){if(!Number.isInteger(minutes)||minutes<=0)return"The eviction threshold must be a whole number of minutes greater than zero."}function assertEvictionThreshold(minutes){let error51=evictionThresholdError(minutes);return error51&&fail(EXIT.USAGE,"INVALID_EVICTION_THRESHOLD",error51),minutes}var DEFAULT_EVICTION_THRESHOLD=30;var EVICTION_ACTIONS=["PROCESS_EVENT","DROP_EVENT"],NAME_PROMPT3=`Event queue name (${EVENT_QUEUE_NAME_FORMAT})`;function withScope5(cmd,opts={}){let env=opts.gate?opts.destructive?SCOPE_ENVIRONMENT_GATE_DESTRUCTIVE:SCOPE_ENVIRONMENT_GATE_HEAD:opts.destructive?SCOPE_ENVIRONMENT_DESTRUCTIVE:SCOPE_ENVIRONMENT;return cmd.option("-w, --workspace <workspaceId>",opts.destructive?SCOPE_WORKSPACE_DESTRUCTIVE:SCOPE_WORKSPACE).option("-e, --env <environmentId>",env).option("--team <teamId>",opts.destructive?SCOPE_TEAM_FILTER_DESTRUCTIVE:SCOPE_TEAM_FILTER)}async function resolveScope7(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,workspace:resolved.workspace??"",environment:resolved.environment??"",...resolved.team===void 0?{}:{team:resolved.team}}}async function resolveQueue(scope2,provided){if(provided)return{id:assertResourceId(provided,"eventQueueId")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<eventQueueId> is required. ${supplyHint()}`);let labels={};return{id:(await resolveParams(["eventQueue"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0,labels})).eventQueue??"",label:labels.eventQueue}}var PLAN_GATE_SENTENCE="Event queues are not available on this team plan.";function queueFail(status,body,team){let message=body?.errorMessage;if(status===403&&message===PLAN_GATE_SENTENCE){let hint=team===void 0?`Whether the plan includes them is features.eventQueues on \`${CLI} team get <teamId>\`, for a team from \`${CLI} team list\`.`:`Whether the plan includes them is features.eventQueues on \`${CLI} team get ${team}\`.`;fail(EXIT.API_ERROR,"FORBIDDEN",message,{status,hint})}apiFail(status,body)}async function assertQueuesAvailable(scope2){if(!scope2.team)return;let team=scope2.team;(await withSpinner("Checking plan features",()=>teamFeaturesIfKnown(scope2.client,team)))?.eventQueues===!1&&queueFail(403,{errorMessage:PLAN_GATE_SENTENCE},team)}var evictionPolicySchema=external_exports.object({evictionAction:external_exports.enum(EVICTION_ACTIONS),evictionThresholdInMinutes:external_exports.number().optional()}).strict(),createBodySchema8=external_exports.object({name:external_exports.string().min(1),evictionPolicy:evictionPolicySchema.optional()}).strict(),updateBodySchema8=external_exports.object({name:external_exports.string().min(1).optional(),disabled:external_exports.boolean().optional(),evictionPolicy:evictionPolicySchema.nullable().optional()}).strict().refine(body=>Object.keys(body).length>0,{message:"At least one of name, disabled or evictionPolicy is required."});function assertQueueRules(body){body.name!==void 0&&(body.name=assertEventQueueName(body.name));let threshold=body.evictionPolicy?.evictionThresholdInMinutes;return threshold!==void 0&&assertEvictionThreshold(threshold),body}var EVICTION_ACTION_EFFECT={PROCESS_EVENT:"hands it to the script regardless",DROP_EVENT:"discards it"},EVICTION_ACTION_EFFECTS=EVICTION_ACTIONS.map(a=>`${a} ${EVICTION_ACTION_EFFECT[a]}`).join(", "),EXAMPLE_POLICY={evictionAction:"PROCESS_EVENT",evictionThresholdInMinutes:DEFAULT_EVICTION_THRESHOLD},LIST_DOC9=defineCommandDoc("event-queue list",{rules:["The workspace is -w and the environment -e, which decides only which enabled state is reported; there is no positional argument."],notes:["A queue belongs to the whole workspace, so every environment lists the same queues. Only the enabled state is per-environment. Event queues need the team's plan to include them; without it every verb in this group is refused."]}),GET_DOC8=defineCommandDoc("event-queue get",{rules:["The event queue is the positional argument; the workspace is -w and the environment -e."],notes:["Reports the listeners attached to the queue beside its own fields.","Event queues need the team's plan to include them; without it every verb in this group is refused."]}),DELETE_DOC8=defineCommandDoc("event-queue delete",{rules:["The event queue is the positional argument; the workspace is -w and the environment -e, which gates the write rather than choosing what is deleted.","--yes skips the confirmation, and is required without a terminal."],notes:["Deleting detaches every listener on the queue, which then runs unqueued and loses its grouping. Nothing refuses it; the confirmation is the only warning.","A listener that loses its queue reads the same way whichever route it took, a queue delete and event-listener update --no-event-queue alike: event-listener get reports no eventQueueId key at all, and no eventQueueGroupings beside it. Absence is the whole signal, and there is no null to branch on.","Event queues need the team's plan to include them; without it every verb in this group is refused."]}),CREATE_DOC8=defineCommandDoc("event-queue create",{schema:createBodySchema8,body:{name:"Orders",evictionPolicy:EXAMPLE_POLICY},rules:[`name: ${EVENT_QUEUE_NAME_FORMAT}, trimmed, unique within the workspace.`,`evictionPolicy: what happens to an event that has waited longer than evictionThresholdInMinutes: ${EVICTION_ACTION_EFFECTS}; omitted, events wait indefinitely. The block has no flag of its own.`,"evictionPolicy.evictionAction is required whenever the block is sent, spelled --eviction-action as a flag.",`evictionPolicy.evictionThresholdInMinutes: a positive integer, spelled --eviction-threshold as a flag; API default ${DEFAULT_EVICTION_THRESHOLD}.`,"The queue is created for the whole workspace and enabled in every environment; refused in a non-HEAD environment. Event queues need the team's plan to include them."]}),UPDATE_DOC8=defineCommandDoc("event-queue update",{schema:updateBodySchema8,body:{name:"Orders",disabled:!1,evictionPolicy:EXAMPLE_POLICY},rules:["An omitted key keeps the current value, and a body with no keys is refused: at least one of name, disabled or evictionPolicy is required.","disabled: true disables the queue in the environment named by -e and false enables it there (--disabled and --enabled as flags), omitted keeps the current state; name and evictionPolicy apply to every environment.","evictionPolicy: an object replaces the policy, null removes it so events wait indefinitely (--no-eviction-policy as a flag), omitted keeps it. The block itself has no flag for setting one.",`evictionPolicy.evictionAction is required whenever an object is sent, spelled --eviction-action as a flag: ${EVICTION_ACTION_EFFECTS}.`,`evictionPolicy.evictionThresholdInMinutes: a positive integer, spelled --eviction-threshold as a flag; API default ${DEFAULT_EVICTION_THRESHOLD}.`,"In a non-HEAD environment only disabled can change. name and evictionPolicy are read-only rather than refused there: echo back what that environment's own get reports, or omit them, and only a differing value is a 400 naming it. null counts as differing when there is a policy to remove, and is accepted when there is not, removing nothing.","Event queues need the team's plan to include them; without it every verb in this group is refused."]});function evictionCell(policy){if(!policy)return"\u2014";let minutes=policy.evictionThresholdInMinutes;return minutes===void 0?policy.evictionAction:`${policy.evictionAction} after ${minutes} min`}function policyFromFlags(opts){if(opts.evictionThreshold!==void 0&&!opts.evictionAction&&fail(EXIT.USAGE,"USAGE_ERROR","--eviction-threshold needs --eviction-action (PROCESS_EVENT or DROP_EVENT)."),!opts.evictionAction)return;let action=opts.evictionAction.toUpperCase();return EVICTION_ACTIONS.includes(action)||fail(EXIT.USAGE,"INVALID_EVICTION_ACTION",`--eviction-action must be one of: ${EVICTION_ACTIONS.join(", ")}.`),{evictionAction:action,...opts.evictionThreshold===void 0?{}:{evictionThresholdInMinutes:assertEvictionThreshold(opts.evictionThreshold)}}}async function askQueueName(initial){for(;;){let answer=await prompts().text(NAME_PROMPT3,{initial}),error51=eventQueueNameError(answer);if(!error51)return normalizeEventQueueName(answer);prompts().note(`\u2716 ${error51}`)}}async function askEvictionPolicy(current){let choices=[{value:"PROCESS_EVENT",label:"Process it anyway",hint:"PROCESS_EVENT"},{value:"DROP_EVENT",label:"Drop it",hint:"DROP_EVENT"}],evictionAction=await prompts().select("When an event has waited too long:",choices,{initial:current?.evictionAction});for(;;){let answer=await prompts().text("Wait limit in minutes",{initial:String(current?.evictionThresholdInMinutes??DEFAULT_EVICTION_THRESHOLD)}),minutes=Number(answer.trim()),error51=evictionThresholdError(minutes);if(!error51)return{evictionAction,evictionThresholdInMinutes:minutes};prompts().note(`\u2716 ${error51}`)}}function eventQueueCommand(){let eq=new Command("event-queue").alias("eq").description("Manage workspace event queues");return withScope5(eq.command("list").description("List event queues in a workspace")).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC9))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope7(globals),{data,response,error:error51}=await withSpinner("Fetching event queues",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueues",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!response.ok||!data)&&queueFail(response.status,error51,scope2.team),ok(data,{human:d=>({eventQueues:d.eventQueues.map(q2=>({id:q2.id,name:q2.name,disabled:q2.disabled,eviction:evictionCell(q2.evictionPolicy)}))})})}),withScope5(eq.command("get").description("Get a single event queue").argument("[eventQueueId]","Event queue ID (required, interactive)")).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,GET_DOC8))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope7(globals),queue=await resolveQueue(scope2,idArg),{data,response,error:error51}=await withSpinner("Fetching event queue",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventQueueId:queue.id}}}));(!response.ok||!data)&&queueFail(response.status,error51,scope2.team),ok(data,{human:d=>({id:d.id,name:d.name,disabled:d.disabled,eviction:evictionCell(d.evictionPolicy),eventListeners:d.eventListeners.length===0?"(none)":d.eventListeners.map(el=>`${el.name} (${el.id})`).join(`
1367
+ `)})})}),withScope5(eq.command("create").description("Create an event queue in a workspace"),{gate:!0}).option("--name <name>",`Event queue name, ${EVENT_QUEUE_NAME_FORMAT} (required unless --input, interactive)`).option("--eviction-action <action>",`What happens to an event that waited too long: ${EVICTION_ACTIONS.join(" | ")} (optional, interactive)`).option("--eviction-threshold <minutes>",`How long an event may wait before that applies (optional, interactive, API default: ${DEFAULT_EVICTION_THRESHOLD}, requires --eviction-action)`,v2=>Number(v2)).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC8))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope7(globals);await assertQueuesAvailable(scope2);let rawBody;if(opts.input)rawBody=readInput(opts.input);else if(!opts.name&&canPrompt()){let name=await askQueueName(),policy=opts.evictionAction!==void 0||opts.evictionThreshold!==void 0?policyFromFlags(opts):await prompts().confirm("Add an eviction policy? (without one, events wait indefinitely)",!1)?await askEvictionPolicy():void 0;rawBody=stripUndefined({name,evictionPolicy:policy})}else rawBody=stripUndefined({name:opts.name===void 0?void 0:assertEventQueueName(opts.name),evictionPolicy:policyFromFlags(opts)});let body=assertQueueRules(validate(createBodySchema8,rawBody)),{data,response,error:error51}=await withSpinner("Creating event queue",()=>scope2.client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}},body}));(!response.ok||!data)&&queueFail(response.status,error51,scope2.team),okMutation("Event queue created",data,{...data,availability:"every environment of this workspace, enabled"})}),withScope5(eq.command("update").description("Update an event queue").argument("[eventQueueId]","Event queue ID (required, interactive)")).option("--name <name>","New name, applies to every environment (optional, interactive on HEAD only, refused when it differs from what a non-HEAD environment reports)").option("--disabled","Disable the queue in the specified environment (optional, interactive, exclusive with --enabled)").option("--enabled","Enable the queue in the specified environment (optional, interactive, exclusive with --disabled)").option("--eviction-action <action>",`Eviction action: ${EVICTION_ACTIONS.join(" | ")} (optional, interactive on HEAD only, refused when it differs from what a non-HEAD environment reports)`).option("--eviction-threshold <minutes>","Eviction threshold in minutes (optional, interactive on HEAD only, requires --eviction-action, refused when it differs from what a non-HEAD environment reports)",v2=>Number(v2)).option("--no-eviction-policy","Remove the eviction policy so events wait indefinitely (optional, interactive on HEAD only, exclusive with --eviction-action and --eviction-threshold, refused when it differs from what a non-HEAD environment reports)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC8))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope7(globals),queue=await resolveQueue(scope2,idArg),interactive=!opts.input&&canPrompt(),removePolicy=opts.evictionPolicy===!1;removePolicy&&(opts.evictionAction||opts.evictionThreshold!==void 0)&&fail(EXIT.USAGE,"USAGE_ERROR","--no-eviction-policy cannot be combined with --eviction-action or --eviction-threshold.");let rawBody;if(opts.input)rawBody=readInput(opts.input);else if(interactive){let current=await withSpinner("Fetching event queue",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventQueueId:queue.id}}}));(!current.response.ok||!current.data)&&queueFail(current.response.status,current.error,scope2.team);let release2=await withSpinner("Checking the environment",()=>environmentRelease(scope2.client,scope2.workspace,scope2.environment));release2&&(opts.name!==void 0||removePolicy||opts.evictionAction!==void 0||opts.evictionThreshold!==void 0)&&fail(EXIT.USAGE,"USAGE_ERROR","The name and the eviction policy belong to the event queue and are shared by every environment, so they cannot be changed in an environment with a release deployed. Target a HEAD environment, or pass only --disabled/--enabled."),release2&&prompts().note(`\u26A0 This environment has ${release2.version?`release ${release2.version}`:"a release"} deployed. Only the enabled state can be changed there; the name and the eviction policy belong to the event queue and are shared by every environment.`);let name=release2?void 0:opts.name??await askQueueName(current.data.name),disabled=disabledFromFlags(opts)??await askStatus(current.data.disabled,"the event queue"),evictionPolicy;if(release2)evictionPolicy=void 0;else if(removePolicy)evictionPolicy=null;else if(opts.evictionAction||opts.evictionThreshold!==void 0)evictionPolicy=policyFromFlags(opts);else{let choices=[{value:"keep",label:evictionCell(current.data.evictionPolicy),display:`${evictionCell(current.data.evictionPolicy)} (current)`},{value:"set",label:current.data.evictionPolicy?"Change the eviction policy":"Add an eviction policy"},...current.data.evictionPolicy?[{value:"remove",label:"Remove it",hint:"events then wait indefinitely"}]:[]],answer=await prompts().select("Eviction policy:",choices,{initial:"keep"});answer==="set"?evictionPolicy=await askEvictionPolicy(current.data.evictionPolicy):answer==="remove"&&(evictionPolicy=null)}let renamed=name===void 0||name===current.data.name?void 0:name;if(renamed===void 0&&disabled===void 0&&evictionPolicy===void 0){prompts().note("Nothing to update \u2014 the event queue was left as it is.");return}rawBody=stripUndefined({name:renamed,disabled,evictionPolicy})}else rawBody=stripUndefined({name:opts.name===void 0?void 0:assertEventQueueName(opts.name),disabled:disabledFromFlags(opts),evictionPolicy:removePolicy?null:policyFromFlags(opts)}),Object.keys(rawBody).length===0&&failNothingToUpdate(["--name","--disabled/--enabled","an eviction policy","--input"]);let body=assertQueueRules(validate(updateBodySchema8,rawBody)),{data,response,error:error51}=await withSpinner("Updating event queue",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventQueueId:queue.id}},body}));(!response.ok||!data)&&queueFail(response.status,error51,scope2.team);let{evictionPolicy:_policy,...detail}=data;okMutation("Event queue updated",data,{...detail,eviction:evictionCell(data.evictionPolicy)})}),withScope5(eq.command("delete").description("Delete an event queue from a workspace").argument("[eventQueueId]","Event queue ID (required, interactive)"),{destructive:!0,gate:!0}).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC8))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope7(globals,{useSession:canPrompt()}),queue=await resolveQueue(scope2,idArg);if(!opts.yes){canPrompt()||failNeedsYes(`event queue ${queue.id}`);let current=await withSpinner("Fetching event queue",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventQueueId:queue.id}}}));(!current.response.ok||!current.data)&&queueFail(current.response.status,current.error,scope2.team);let attached=current.data.eventListeners;prompts().note(["Deleting removes the event queue from the whole workspace, not just this environment.",attached.length===0?"No event listeners are attached to it.":`${attached.length} event listener${attached.length===1?"":"s"} ${attached.length===1?"is":"are"} attached and will be detached, losing ${attached.length===1?"its":"their"} grouping, and will then run unqueued:
1368
+ ${attached.map(el=>` ${el.name} (${el.id})`).join(`
1369
+ `)}`].join(`
1370
+ `)),await prompts().confirm(`Delete event queue ${current.data.name} (${queue.id})? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")}let{response,error:error51}=await withSpinner("Deleting event queue",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/eventQueue/{eventQueueId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,eventQueueId:queue.id}}}));response.ok||queueFail(response.status,error51,scope2.team),okMutation("Event queue deleted",{deleted:!0,id:queue.id})}),eq}import{readFileSync as readFileSync16,writeFileSync as writeFileSync8}from"fs";import{join as join15,resolve as resolve7}from"path";async function bulkContext(client,instanceFlag2,workspaceId,environmentId,lockId){let creds=await requireCredentials(),instance4=requireInstance(instanceFlag2);return{baseUrl:baseUrl(instance4),headers:{Authorization:basicAuthHeader(creds),...identityHeaders(),...lockId===void 0?{}:{[LOCK_ID_HEADER]:lockId}},workspaceId,environmentId,client}}async function withLockRecovery(ctx,sendRequest){let result=await sendRequest();for(let attempt2=0;lockRefused(result);attempt2+=1){let recovery=await recoverLostLock(ctx.client,ctx.workspaceId,attempt2);recovery.lockId===void 0?delete ctx.headers[LOCK_ID_HEADER]:ctx.headers[LOCK_ID_HEADER]=recovery.lockId,result=await sendRequest()}return result}function lockRefused(result){return result.response.status===409&&!messageOf2(result.body)?.includes("already in progress")}var bulkFetch=fetchWithRetry;var MAX_POLL_MS=960*1e3,DEFAULT_POLL_MS=2e3,UPLOAD_TIMEOUT_MS=300*1e3,UPLOAD_ATTEMPTS=2;function record3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function stringField(source,key){let value=source?.[key];return typeof value=="string"&&value!==""?value:void 0}function numberField(source,key){let value=source?.[key];return typeof value=="number"&&Number.isFinite(value)?value:void 0}function rows(value){return Array.isArray(value)?value.flatMap(entry2=>{let fields=record3(entry2),id=stringField(fields,"id"),name=stringField(fields,"name");return id&&name?[{id,name}]:[]}):[]}function compilationErrors(value){return Array.isArray(value)?value.flatMap(entry2=>{let fields=record3(entry2),scriptName=stringField(fields,"scriptName"),errors=fields?.errors;return!scriptName||!Array.isArray(errors)?[]:[{scriptName,errors:errors.filter(e=>typeof e=="string")}]}):[]}function bulkResult(body){let fields=record3(body);return{created:rows(fields?.created),updated:rows(fields?.updated),deleted:rows(fields?.deleted),compilationErrors:compilationErrors(fields?.compilationErrors)}}function messageOf2(body){let fields=record3(body);return stringField(fields,"errorMessage")??stringField(fields,"message")}async function readJson(response){try{return await response.json()}catch{return}}async function send(ctx,method,path2,body){let request=new Request(`${ctx.baseUrl}${path2}`,{method,headers:{...ctx.headers,...body===void 0?{}:{"content-type":"application/json"}},...body===void 0?{}:{body:JSON.stringify(body)}}),response=await bulkFetch(request);return{response,body:await readJson(response)}}function scope(ctx){return`/v1/workspace/${encodeURIComponent(ctx.workspaceId)}/environment/${encodeURIComponent(ctx.environmentId)}`}async function requestUpload(ctx){let{response,body}=await withLockRecovery(ctx,()=>send(ctx,"POST",`${scope(ctx)}/scripts/bulk/upload`));response.ok||grantFail(response.status,body,ctx);let fields=record3(body),upload=record3(fields?.upload),uploadId=stringField(fields,"uploadId"),url2=stringField(upload,"url"),policy=record3(upload?.fields);(!uploadId||!url2||!policy)&&fail(EXIT.API_ERROR,"BULK_UPLOAD_UNSUPPORTED","The API did not return an upload credential for this workspace.",{status:response.status,hint:`Push the scripts one at a time with \`${CLI} script update\` instead.`});let flat={};for(let[key,value]of Object.entries(policy))typeof value=="string"&&(flat[key]=value);return{uploadId,...stringField(fields,"expiresAt")===void 0?{}:{expiresAt:stringField(fields,"expiresAt")},url:url2,fields:flat,...numberField(upload,"maxFileBytes")===void 0?{}:{maxFileBytes:numberField(upload,"maxFileBytes")},...numberField(upload,"maxFiles")===void 0?{}:{maxFiles:numberField(upload,"maxFiles")}}}function grantFail(status,body,ctx){let message=messageOf2(body);status===400&&message?.includes("deployed release")&&fail(EXIT.API_ERROR,"RELEASED_ENVIRONMENT",message,{status,hint:`Scripts can only be pushed to a HEAD environment \u2014 see \`${CLI} environment target-release --help\`.`}),status===400&&message?.includes("already in progress")&&fail(EXIT.API_ERROR,"TOO_MANY_UPLOADS",message,{status,hint:"Unused upload grants expire on their own \u2014 wait for one to lapse rather than retrying."}),status===409&&lockLostFail(ctx.workspaceId),apiFail(status,body)}function uploadKey(uploadId,scriptName){return`uploads/${uploadId}/scripts/${scriptName}.ts`}async function uploadScript(grant,script){let key=uploadKey(grant.uploadId,script.name),lastError;for(let attempt2=0;attempt2<UPLOAD_ATTEMPTS;attempt2+=1){let form=new FormData;for(let[field,value]of Object.entries(grant.fields))form.append(field,field==="key"?key:value.replace("${filename}",key));form.append("file",new Blob([script.content]),key.split("/").pop()??"script.ts");try{let response=await bulkFetch(new Request(grant.url,{method:"POST",body:form,signal:AbortSignal.timeout(UPLOAD_TIMEOUT_MS)}));if(response.ok)return;if(lastError=`HTTP ${response.status}${await storageReason(response)}`,response.status<500)break}catch(err){lastError=describeError(err)}}fail(EXIT.API_ERROR,"SCRIPT_UPLOAD_FAILED",`Could not upload ${script.name}: ${lastError??"the upload host did not answer"}.`,{hint:"The upload goes to a second host rather than to the API, so a proxy or a network without egress to it will refuse this \u2014 the per-script commands remain available."})}async function storageReason(response){let text;try{text=await response.text()}catch{return""}let message=/<Message>([^<]{0,200})<\/Message>/.exec(text)?.[1];return message?` \u2014 ${message}`:""}async function applyUpload(ctx,req){let{response,body}=await withLockRecovery(ctx,()=>send(ctx,"POST",`${scope(ctx)}/scripts/bulk`,{uploadId:req.uploadId,expectedFileCount:req.expectedFileCount,deleteMissing:req.deleteMissing,...req.manifest.length>0?{manifest:req.manifest}:{},mode:req.mode}));if(response.status===202){let fields=record3(body),jobId=stringField(fields,"jobId");jobId||fail(EXIT.API_ERROR,"BULK_PUSH_FAILED","The API accepted the push but named no job.",{status:202});let pollAfterMs=numberField(fields,"pollAfterMs");return{kind:"job",jobId,...pollAfterMs===void 0?{}:{pollAfterMs}}}return response.ok?{kind:"result",result:bulkResult(body)}:applyFail(response.status,body,ctx)}function applyFail(status,body,ctx){let message=messageOf2(body);if(isGatewayTimeout(status)&&syncTimeoutFail(status),status===409){if(message?.includes("already in progress"))return{kind:"in-progress"};lockLostFail(ctx.workspaceId)}status===404&&fail(EXIT.NOT_FOUND,"UPLOAD_NOT_FOUND",message??"Upload not found or expired.",{status,hint:"An upload credential is short-lived, and a successful push spends it \u2014 run the push again."}),status===400&&message?.includes("deployed release")&&fail(EXIT.API_ERROR,"RELEASED_ENVIRONMENT",message,{status}),status===400&&message?.includes("were expected")&&fail(EXIT.API_ERROR,"UPLOAD_INCOMPLETE",message,{status,hint:"Some script bodies did not arrive. Run the push again."}),apiFail(status,body)}async function pollJob(ctx,jobId,opts={}){let now=opts.now??Date.now,sleep=opts.sleep??(ms=>new Promise(resolve8=>setTimeout(resolve8,ms))),deadline=now()+MAX_POLL_MS,delay2=opts.firstDelayMs??DEFAULT_POLL_MS;for(;;){now()>=deadline&&fail(EXIT.API_ERROR,"BULK_PUSH_TIMEOUT",`The push was accepted but had not finished after ${Math.round(MAX_POLL_MS/6e4)} minutes.`,{hint:`It may still land. Re-read the workspace with \`${CLI} script list\` before pushing again.`}),await sleep(delay2);let{response,body}=await send(ctx,"GET",`${scope(ctx)}/scripts/bulk/job/${encodeURIComponent(jobId)}`);response.ok||apiFail(response.status,body);let fields=record3(body),status=stringField(fields,"status");if(status==="SUCCEEDED")return{kind:"result",result:bulkResult(body)};if(status==="FAILED"){let failure=stringField(fields,"failure");return{kind:"failed",failure:failure==="TRANSIENT"||failure==="REJECTED"?failure:void 0,message:messageOf2(record3(fields?.error))??"The push failed."}}delay2=numberField(fields,"pollAfterMs")??DEFAULT_POLL_MS}}function syncTimeoutFail(status){fail(EXIT.API_ERROR,"PUSH_OUTCOME_UNKNOWN",`The push did not answer in time (HTTP ${status}). It may still have been applied.`,{status,expected:!0,hint:`Re-read the workspace with \`${CLI} script list\`, and use --async for a workspace this size.`})}function isGatewayTimeout(status){return status===504||status===502||status===503}import{lstatSync as lstatSync4,readFileSync as readFileSync15,readdirSync as readdirSync7}from"fs";import{join as join14,resolve as resolve6}from"path";function walk(root,prefix,out){let entries;try{entries=readdirSync7(root)}catch{return}for(let entry2 of entries.sort()){let absolute2=join14(root,entry2),relativePath=prefix?`${prefix}/${entry2}`:entry2,directory;try{directory=lstatSync4(absolute2).isDirectory()}catch{continue}directory?walk(absolute2,relativePath,out):out.push(relativePath)}}function scanWorkspace(directory,opts){let base=resolve6(directory),scripts=[],payloads=[],skipped=[],scriptFiles=[];walk(join14(base,"scripts"),"scripts",scriptFiles);for(let path2 of scriptFiles){let name=scriptNameFromPath(path2);if(name===void 0)continue;let content=readFileSync15(join14(base,path2),"utf8");scripts.push({name,path:path2,content,bytes:Buffer.byteLength(content),checksum:checksumOf(content)})}if(opts.withTestPayloads){let payloadFiles=[];walk(join14(base,"test-payloads"),"test-payloads",payloadFiles);for(let path2 of payloadFiles){let ref=payloadRefFromPath(path2);if(!ref){let parts=path2.split("/");parts.length===3&&path2.endsWith(".json")&&skipped.push({path:path2,reason:listenerIdFromFolder(parts[1]??"")?"its file name is empty":"its folder name does not end in an event listener ID in parentheses"});continue}let content=readFileSync15(join14(base,path2),"utf8");payloads.push({path:path2,...ref,content,bytes:Buffer.byteLength(content),checksum:checksumOf(content)})}}let readme;if(opts.withReadme!==!1)try{let content=readFileSync15(join14(base,"README.md"),"utf8");readme={path:"README.md",content,bytes:Buffer.byteLength(content),checksum:checksumOf(content)}}catch{}return{scripts,payloads,skipped,...readme?{readme}:{}}}function planPush(scan,metadata,opts){let recordedScripts=metadata?.scripts??{},localNames=new Set(scan.scripts.map(script=>script.name)),changed=[],unchangedScripts=0;for(let script of scan.scripts){let recorded=recordedScripts[script.name];!opts.force&&recorded?.checksum===script.checksum?unchangedScripts+=1:changed.push(script.name)}let missingScripts=Object.keys(recordedScripts).filter(name=>!localNames.has(name)).sort(),{renames,unattributed}=detectRenames(scan.scripts.filter(script=>recordedScripts[script.name]===void 0),missingScripts,recordedScripts),scripts={upload:changed.length>0||opts.force||opts.deleteMissing&&missingScripts.length>0?scan.scripts:[],changed,unchanged:unchangedScripts,manifest:renames.map(rename=>({name:rename.to,id:rename.id})),renames,unattributed,missingLocally:missingScripts},recordedPayloads=metadata?.testPayloads??{},create=[],update=[],unchangedPayloads=0;for(let payload of scan.payloads){let recorded=recordedPayloads[payload.path];if(!opts.force&&recorded?.checksum===payload.checksum){unchangedPayloads+=1;continue}recorded?.id?update.push({...payload,id:recorded.id}):create.push(payload)}let localPayloadPaths=new Set(scan.payloads.map(payload=>payload.path)),payloads={create,update,unchanged:unchangedPayloads,missingLocally:Object.keys(recordedPayloads).filter(path2=>!localPayloadPaths.has(path2)).sort()},readmeChanged=scan.readme!==void 0&&(opts.force||metadata?.readme?.checksum!==scan.readme.checksum);return{scripts,payloads,...readmeChanged&&scan.readme?{readme:scan.readme}:{},readmeUnchanged:scan.readme!==void 0&&!readmeChanged,anyWork:scripts.upload.length>0||create.length>0||update.length>0||readmeChanged}}function detectRenames(newScripts,missingNames,recorded){let renames=[],unattributed=[],claimed=new Set;for(let script of newScripts){let candidates=missingNames.filter(name=>recorded[name]?.checksum===script.checksum&&!claimed.has(name)),twins=newScripts.filter(other=>other.checksum===script.checksum),candidate=candidates.length===1&&twins.length===1?candidates[0]:void 0,id=candidate===void 0?void 0:recorded[candidate]?.id;if(candidate===void 0||id===void 0){candidates.length>0&&unattributed.push(script.name);continue}claimed.add(candidate),renames.push({from:candidate,to:script.name,id})}return{renames,unattributed:unattributed.sort()}}function assertPushable(scripts,maxFiles,readme,payloads=[]){readme&&readme.bytes>MAX_CONTENT_BYTES&&fail(EXIT.USAGE,"README_TOO_LARGE",`${readme.path} is ${Math.round(readme.bytes/1024)} KiB \u2014 the API accepts up to ${MAX_CONTENT_BYTES/1024/1024} MiB.`);for(let script of scripts){let error51=scriptNameError(script.name);error51&&fail(EXIT.USAGE,"INVALID_SCRIPT_NAME",`${script.path} is not a valid script: ${error51}`,{hint:"Rename the file so its path spells a legal script name."}),script.bytes>MAX_CONTENT_BYTES&&fail(EXIT.USAGE,"SCRIPT_TOO_LARGE",`${script.path} is ${Math.round(script.bytes/1024)} KiB \u2014 the API accepts up to ${MAX_CONTENT_BYTES/1024/1024} MiB per script.`)}for(let payload of payloads){let error51=testPayloadNameError(payload.name);error51&&fail(EXIT.USAGE,"INVALID_TEST_PAYLOAD_NAME",`${payload.path} is not a valid test payload: ${error51}`,{hint:"Rename the file so its name is a legal test payload name."})}maxFiles!==void 0&&scripts.length>maxFiles&&fail(EXIT.USAGE,"TOO_MANY_SCRIPTS",`This directory holds ${scripts.length} scripts and one push accepts at most ${maxFiles}.`)}var WORKSPACE_CONCURRENCY=5;async function fetchTeamName(client,teamId){let{data,response,error:error51}=await client.GET("/v1/team/{teamId}",{params:{path:{teamId}}});return(!response.ok||!data)&&apiFail(response.status,error51),data.name}async function fetchEverything(client,teamId,workspaceId,environmentId,withTestPayloads){let scope2={workspaceId,environmentId},[teamName,workspace,scriptList,apiConnections,parameters,packages,readme,environment,eventListeners]=await throttleAll(WORKSPACE_CONCURRENCY,[()=>fetchTeamName(client,teamId),async()=>{let{data,response,error:error51}=await client.GET("/v1/team/{teamId}/workspace/{workspaceId}",{params:{path:{teamId,workspaceId}}});return(!response.ok||!data)&&apiFail(response.status,error51),data},async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scripts",{params:{path:scope2}});return(!response.ok||!data)&&apiFail(response.status,error51),data.scripts},async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/apiConnections",{params:{path:scope2}});return(!response.ok||!data)&&apiFail(response.status,error51),data.apiConnections},async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/parameters",{params:{path:scope2}});return(!response.ok||!data)&&apiFail(response.status,error51),data.parameters},async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/packages",{params:{path:{workspaceId}}});return(!response.ok||!data)&&apiFail(response.status,error51),data.packages},async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/readme",{params:{path:scope2}});if(response.status!==404)return(!response.ok||!data)&&apiFail(response.status,error51),data.content},()=>environmentInfo(client,workspaceId,environmentId),async()=>{if(!withTestPayloads)return[];let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListeners",{params:{path:scope2}});return(!response.ok||!data)&&apiFail(response.status,error51),data.eventListeners}]),secondWave=await throttleAll(WORKSPACE_CONCURRENCY,[...scriptList.map(script=>async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/script/{scriptId}",{params:{path:{...scope2,scriptId:script.id}}});return(!response.ok||!data)&&apiFail(response.status,error51),{kind:"script",id:data.id,name:data.name,content:data.content}}),...eventListeners.map(listener=>async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:{...scope2,eventListenerId:listener.id}}});return(!response.ok||!data)&&apiFail(response.status,error51),{kind:"payloadList",listener,payloads:data.testPayloads}})]),scripts=secondWave.filter(result=>result.kind==="script").map(({id,name,content})=>({id,name,content})),payloadLists=secondWave.filter(result=>result.kind==="payloadList"),contents=await throttleAll(WORKSPACE_CONCURRENCY,payloadLists.flatMap(({listener,payloads})=>payloads.map(payload=>async()=>{let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{...scope2,eventListenerId:listener.id,testPayloadId:payload.id}}});return(!response.ok||!data)&&apiFail(response.status,error51),{listenerId:listener.id,id:data.id,name:data.name,content:data.content}}))),testPayloads=payloadLists.map(({listener})=>({listener,payloads:contents.filter(payload=>payload.listenerId===listener.id).map(({id,name,content})=>({id,name,content}))})).filter(({payloads})=>payloads.length>0);return{workspace,team:{id:teamId,name:teamName},scripts,apiConnections,parameters,packages,readme,testPayloads,environment}}async function confirmTarget(directory,state,force){if(state==="empty"||force)return;let warning=state==="cloned-workspace"?"This directory already looks like a local copy of a workspace \u2014 your local changes may be overwritten.":"This directory is not empty \u2014 existing files may be overwritten.";canPrompt()||fail(EXIT.USAGE,"DIRECTORY_NOT_EMPTY",warning,{hint:"Pass --force to clone into it anyway."}),prompts().note(warning),await prompts().confirm(`Clone into ${displayPath(directory)} anyway?`,!1)||fail(EXIT.CANCELLED,"CANCELLED","Clone cancelled.")}function testPayloadFiles(listeners){let files=[],skipped=[],tracked={};for(let{listener,payloads}of listeners){let folder=listenerFolderName(listener),folderReason=unportableNameReason(folder);if(folderReason){for(let payload of payloads)skipped.push({eventListenerId:listener.id,name:payload.name,reason:folderReason});continue}for(let payload of payloads){let file2=payloadFileName(payload.name),reason=unportableNameReason(file2);if(reason){skipped.push({eventListenerId:listener.id,name:payload.name,reason});continue}let path2=`test-payloads/${folder}/${file2}`;files.push({path:path2,content:payload.content}),tracked[path2]={eventListenerId:listener.id,id:payload.id,checksum:checksumOf(payload.content)}}}return{files,skipped,tracked}}function buildMetadata(fetched,scope2,payloads){let scripts={};for(let script of fetched.scripts)scripts[script.name]={id:script.id,checksum:checksumOf(script.content)};let release2=fetched.environment?.release;return{version:METADATA_VERSION,cli:writerTag(),instance:scope2.instance,team:fetched.team,workspace:{id:scope2.workspaceId,name:fetched.workspace.name},environment:{id:scope2.environmentId,...fetched.environment?{name:fetched.environment.name}:{},release:release2?release2.version:null},clonedAt:new Date().toISOString(),pushedAt:null,scripts,testPayloads:payloads,...fetched.readme===void 0?{}:{readme:{checksum:checksumOf(fetched.readme)}}}}function buildManifest(fetched,apiFiles,existingPackageJson,scope2){let files=[{path:"package.json",content:(existingPackageJson!==void 0?mergePackageJson(existingPackageJson,fetched.packages):void 0)??generatePackageJson(fetched.workspace.name,fetched.packages)},{path:"pnpm-workspace.yaml",content:PNPM_WORKSPACE_YAML},{path:"tsconfig.json",content:TSCONFIG_JSON},{path:"tsconfig.base.json",content:generateTsconfigBase(fetched.workspace.language)},{path:"eslint.config.js",content:ESLINT_CONFIG_JS},{path:".gitignore",content:GITIGNORE},{path:".prettierrc",content:PRETTIERRC},{path:".vscode/extensions.json",content:VSCODE_EXTENSIONS_JSON},{path:"node/apiRegistry.ts",content:NODE_API_REGISTRY_TS},{path:"node/runtimeMocks.ts",content:NODE_RUNTIME_MOCKS_TS},{path:"node/global.d.ts",content:NODE_GLOBAL_D_TS},{path:"node/tsconfig.json",content:NODE_TSCONFIG_JSON},{path:"node/jest.config.ts",content:NODE_JEST_CONFIG_TS},{path:"ev-params.ts",content:generateEvParams(fetched.parameters)}];fetched.readme!==void 0&&files.push({path:"README.md",content:fetched.readme});for(let script of fetched.scripts)files.push({path:`scripts/${script.name}.ts`,content:script.content});for(let input of apiFiles)files.push({path:`scripts/api/${input.path}/index.ts`,content:generateApiConnectionFile(input)});let payloads=testPayloadFiles(fetched.testPayloads);return files.push(...payloads.files),files.push({path:METADATA_FILE,content:renderMetadata(buildMetadata(fetched,scope2,payloads.tracked))}),{files,skipped:payloads.skipped}}function plural4(count,noun){return`${count} ${noun}${count===1?"":"s"}`}async function resolvePushTarget(directory,globals){let read=readMetadata(directory);read.problem&&fail(EXIT.USAGE,"INVALID_WORKSPACE_METADATA",read.problem,{hint:`Re-clone the directory with \`${CLI} local-workspace clone\`, or pass --team, -w and -e to push without the record.`});let client=await apiClient(globals.instance),previous=read.metadata,force=globals.force===!0,instance4=requireInstance(globals.instance);if(previous){let sameInstance=previous.instance===""||baseUrl(previous.instance)===baseUrl(instance4);!sameInstance&&!force&&fail(EXIT.USAGE,"INSTANCE_MISMATCH",`${METADATA_FILE} was cloned from ${previous.instance} and this run is aimed at ${instance4}.`,{hint:"Aim at the recorded instance, or pass --force to push to this one anyway."});let workspaceId2=globals.workspace??previous.workspace.id,environmentId2=globals.env??previous.environment.id;workspaceId2!==previous.workspace.id&&!force&&fail(EXIT.USAGE,"WORKSPACE_MISMATCH",`${METADATA_FILE} describes workspace ${previous.workspace.id} and -w names ${workspaceId2}.`,{hint:"Drop -w to push where the directory came from, or pass --force."}),environmentId2!==previous.environment.id&&!force&&fail(EXIT.USAGE,"ENVIRONMENT_MISMATCH",`${METADATA_FILE} describes environment ${previous.environment.id} and -e names ${environmentId2}.`,{hint:"Drop -e to push where the directory came from, or pass --force \u2014 the checksums do not describe another environment, so everything is sent."});let redirected=!sameInstance||workspaceId2!==previous.workspace.id||environmentId2!==previous.environment.id,team=!sameInstance||workspaceId2!==previous.workspace.id?await resolveTargetTeam(client,globals):{id:previous.team.id,name:previous.team.name};return{client,instance:instance4,teamId:team.id,teamName:team.name,workspaceId:workspaceId2,environmentId:environmentId2,metadata:redirected?void 0:previous,previous,label:{workspace:previous.workspace.name?`${previous.workspace.name} (${workspaceId2})`:workspaceId2,environment:!redirected&&previous.environment.name?`${previous.environment.name} (${environmentId2})`:environmentId2}}}let labels={},resolved=await resolveParams(["team","workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt(),labels}),workspaceId=resolved.workspace??"",environmentId=resolved.environment??"",teamId=resolved.team??"";return{client,instance:instance4,teamId,teamName:await teamNameFor(client,teamId,labels.team),workspaceId,environmentId,metadata:void 0,previous:void 0,label:{workspace:labels.workspace?`${labels.workspace} (${workspaceId})`:workspaceId,environment:labels.environment?`${labels.environment} (${environmentId})`:environmentId}}}async function remoteScripts(client,workspaceId,environmentId){let{data,response,error:error51}=await withSpinner("Reading the workspace's scripts",()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scripts",{params:{path:{workspaceId,environmentId}}}));return(!response.ok||!data)&&apiFail(response.status,error51),data.scripts}async function remotePayloads(client,workspaceId,environmentId,eventListenerId){let{data,response,error:error51}=await client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayloads",{params:{path:{workspaceId,environmentId,eventListenerId}}});return(!response.ok||!data)&&apiFail(response.status,error51),data.testPayloads}async function fillMissingIds(target,plan,deleteMissing){let unknownScripts=plan.scripts.changed.filter(name=>target.metadata?.scripts[name]===void 0),unknownPayloads=plan.payloads.create,needScripts=deleteMissing||unknownScripts.length>0||target.metadata===void 0;if(!needScripts&&unknownPayloads.length===0)return{metadata:target.metadata,remote:[],unresolvable:[]};let remote=needScripts?await remoteScripts(target.client,target.workspaceId,target.environmentId):[],listeners=[...new Set(unknownPayloads.map(payload=>payload.eventListenerId))],lists=await withSpinner("Reading the event listeners' test payloads",()=>throttleAll(WORKSPACE_CONCURRENCY,listeners.map(eventListenerId=>async()=>{try{return{eventListenerId,payloads:await remotePayloads(target.client,target.workspaceId,target.environmentId,eventListenerId)}}catch(err){return{eventListenerId,payloads:void 0,message:describeError(err)}}}))),unresolvable=[],metadata=target.metadata?{...target.metadata,scripts:{...target.metadata.scripts},testPayloads:{...target.metadata.testPayloads}}:freshMetadata(target);for(let row of remote){let existing=metadata.scripts[row.name];metadata.scripts[row.name]={id:row.id,checksum:existing?.checksum??""}}for(let{eventListenerId,payloads,message}of lists){if(payloads===void 0){for(let local of unknownPayloads.filter(p=>p.eventListenerId===eventListenerId))unresolvable.push({path:local.path,message});continue}for(let local of unknownPayloads.filter(p=>p.eventListenerId===eventListenerId)){let match=payloads.find(row=>row.name===local.name);match&&(metadata.testPayloads[local.path]={eventListenerId,id:match.id,checksum:metadata.testPayloads[local.path]?.checksum??""})}}return{metadata,remote,unresolvable}}async function resolveTargetTeam(client,globals){let labels={},id=(await resolveParams(["team"],{team:globals.team},{client,interactive:canPrompt(),labels})).team??"";return{id,name:await teamNameFor(client,id,labels.team)}}async function teamNameFor(client,teamId,label){return label??await withSpinner("Fetching the team",()=>fetchTeamName(client,teamId))}function freshMetadata(target){return{version:METADATA_VERSION,cli:writerTag(),instance:target.instance,team:{id:target.teamId,name:target.teamName},workspace:{id:target.workspaceId},environment:{id:target.environmentId,release:null},clonedAt:new Date().toISOString(),pushedAt:null,scripts:{},testPayloads:{}}}async function confirmDeleteMissing(names,yes){if(names.length===0||yes)return;let heading=`${plural4(names.length,"script")} in the workspace ${names.length===1?"is":"are"} not in this directory and would be deleted:`;canPrompt()||fail(EXIT.USAGE,"CONFIRMATION_REQUIRED",`${heading} ${names.join(", ")}.`,{hint:"Pass --yes to confirm, or drop --delete-missing."}),prompts().note(`${heading}
1371
+ ${names.join(`
1372
+ `)}`),await prompts().confirm("Delete them as part of this push?",!1)||fail(EXIT.CANCELLED,"CANCELLED","Push cancelled.")}async function settleApply(ctx,request,outcome,retried=!1){if(outcome.kind==="result")return outcome.result;outcome.kind==="in-progress"&&fail(EXIT.API_ERROR,"PUSH_IN_PROGRESS","Another push of this upload is already being applied.",{status:409,hint:"Wait for it to finish, then push again."});let job=await withSpinner("Compiling and bundling",()=>pollJob(ctx,outcome.jobId,outcome.pollAfterMs===void 0?{}:{firstDelayMs:outcome.pollAfterMs}));if(job.kind==="result")return job.result;job.failure==="REJECTED"&&fail(EXIT.API_ERROR,"PUSH_REJECTED",job.message,{hint:"Re-submitting the same push changes nothing \u2014 fix what it reports first."});let canRetry=job.failure==="TRANSIENT"&&!retried;if(canRetry&&canPrompt()&&await prompts().confirm("Send the same push again?",!0)){let again=await withSpinner("Re-sending the push",()=>applyUpload(ctx,request));return settleApply(ctx,request,again,!0)}fail(EXIT.API_ERROR,"PUSH_FAILED",job.message,canRetry?{hint:"The failure was transient \u2014 the same push can be sent again by running it."}:{})}async function pushScripts(target,plan,opts){let ctx=await bulkContext(target.client,opts.instance,target.workspaceId,target.environmentId,opts.lockId),grant=await withSpinner("Requesting an upload credential",()=>requestUpload(ctx));assertPushable(plan.scripts.upload,grant.maxFiles);let cap=grant.maxFileBytes,tooBig=cap===void 0?void 0:plan.scripts.upload.find(s=>s.bytes>cap);tooBig&&cap!==void 0&&fail(EXIT.USAGE,"SCRIPT_TOO_LARGE",`${tooBig.path} is ${Math.round(tooBig.bytes/1024)} KiB and this upload accepts up to ${Math.round(cap/1024)} KiB per file.`),await withSpinner(`Uploading ${plural4(plan.scripts.upload.length,"script")}`,()=>throttleAll(WORKSPACE_CONCURRENCY,plan.scripts.upload.map(script=>()=>uploadScript(grant,script))));let request={uploadId:grant.uploadId,expectedFileCount:plan.scripts.upload.length,deleteMissing:opts.deleteMissing,manifest:plan.scripts.manifest,mode:opts.mode},outcome=await withSpinner(opts.mode==="SYNC"?"Compiling and bundling":"Initiating compilation",()=>applyUpload(ctx,request));return settleApply(ctx,request,outcome)}async function pushReadme(target,readme){let{response,error:error51}=await withSpinner("Pushing the README",()=>target.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/readme",{params:{path:{workspaceId:target.workspaceId,environmentId:target.environmentId}},body:{content:readme.content}}));if(!response.ok){let message=`Request failed with HTTP status ${response.status}.`;try{apiFail(response.status,error51)}catch(err){message=err instanceof Error?err.message:String(err)}return warnLine(`\u26A0 ${readme.path} was not pushed: ${message}`),{pushed:!1,error:message}}return{pushed:!0}}async function pushTestPayloads(target,plan){let outcome={created:[],updated:[],failed:[]},path2={workspaceId:target.workspaceId,environmentId:target.environmentId},tasks=[...plan.payloads.create.map(payload=>async()=>{let{data,response,error:error51}=await target.client.POST("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload",{params:{path:{...path2,eventListenerId:payload.eventListenerId}},body:{name:payload.name,content:payload.content}});(!response.ok||!data)&&apiFail(response.status,error51),outcome.created.push({id:data.id,eventListenerId:payload.eventListenerId,name:payload.name,path:payload.path})}),...plan.payloads.update.map(payload=>async()=>{let{response,error:error51}=await target.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/eventListener/{eventListenerId}/testPayload/{testPayloadId}",{params:{path:{...path2,eventListenerId:payload.eventListenerId,testPayloadId:payload.id}},body:{name:payload.name,content:payload.content}});response.ok||apiFail(response.status,error51),outcome.updated.push({id:payload.id,eventListenerId:payload.eventListenerId,name:payload.name,path:payload.path})})],guarded=tasks.map((task,index)=>async()=>{try{await task()}catch(err){let file2=plan.payloads.create[index]?.path??plan.payloads.update[index-plan.payloads.create.length]?.path??"";outcome.failed.push({path:file2,message:err instanceof Error?err.message:String(err)})}});return await withSpinner(`Pushing ${plural4(tasks.length,"test payload")}`,()=>throttleAll(WORKSPACE_CONCURRENCY,guarded)),outcome}function nextMetadata(target,plan,scriptResult,payloads,readme,deleteMissing){let base=target.metadata??target.previous??freshMetadata(target),scripts={...base.scripts},testPayloads={...base.testPayloads};if(scriptResult){let byName=new Map;for(let row of[...scriptResult.created,...scriptResult.updated])byName.set(row.name,row.id);let renamedFrom=new Map(plan.scripts.renames.map(r=>[r.to,r]));for(let name of plan.scripts.renames.map(r=>r.from))delete scripts[name];if(deleteMissing)for(let name of plan.scripts.missingLocally)delete scripts[name];for(let script of plan.scripts.upload){let id=byName.get(script.name)??renamedFrom.get(script.name)?.id??scripts[script.name]?.id;scripts[script.name]={...id===void 0?{}:{id},checksum:script.checksum}}}let local=new Map([...plan.payloads.create,...plan.payloads.update].map(payload=>[payload.path,payload]));for(let row of[...payloads.created,...payloads.updated]){let checksum=local.get(row.path)?.checksum;checksum!==void 0&&(testPayloads[row.path]={eventListenerId:row.eventListenerId,id:row.id,checksum})}return{...base,version:METADATA_VERSION,cli:writerTag(),instance:base.instance===""?target.instance:base.instance,workspace:{...base.workspace,id:target.workspaceId},environment:{...base.environment,id:target.environmentId},pushedAt:new Date().toISOString(),scripts,testPayloads,...readme.pushed&&plan.readme?{readme:{checksum:plan.readme.checksum}}:{}}}function seconds(ms){return`${(ms/1e3).toFixed(1)}s`}var CLONE_DOC=defineCommandDoc("local-workspace clone",{rules:["The directory is the positional argument, default the current one, and is created when missing.","--team is required here even with -w: the team read supplies the project description and its strictness, which workspace.json carries.","--force gets past a non-empty directory without a terminal. Getting past that refusal on a directory that is already a clone is what update mode is, so re-cloning is `clone --force`.","--no-test-payloads skips the payload fetch entirely."],notes:["Writes package.json with the workspace dependencies, tsconfig.json and tsconfig.base.json, pnpm-workspace.yaml, linter and formatter configs, .gitignore, .vscode/extensions.json, a node/ folder with API mocks for local tests, ev-params.ts with the parameter types, README.md, scripts/<name>.ts, scripts/api/<path>/index.ts, test-payloads/<App\u2192Event (listenerId)>/<name>.json, and workspace.json.","ev-params.ts carries no values, but a parameter's type can include ones you recognise: a choice parameter's options are its type ('OPS' | 'DEV'), and a MAP is Record<string, string> \u2014 deliberately not typed from the keys the environment happens to hold today, a clone's environment not being the one the script runs in.","A directory that already looks like a clone is updated rather than replaced: workspace content is rewritten, the static scaffolding and node/apiRegistry.ts are kept, package.json is merged with only dependencies replaced, and stale scripts/api/** and test-payloads/** files are removed. A scripts/<name>.ts whose script is gone remotely is kept.","A non-empty directory needs a confirmation, or --force without a terminal, whether or not it is already a clone. The two refusals differ only in wording; DIRECTORY_NOT_EMPTY is the code either way.","A non-HEAD environment clones the release's snapshot, except package.json dependencies and test payloads, which come from HEAD; a note says so.","A payload whose name cannot be a file name is skipped with a warning and listed in the document. The rules applied are Windows' on every platform, so a clone is portable.","workspace.json then answers the scope questions for every command run at or below the directory."]}),PUSH_DOC=defineCommandDoc("local-workspace push",{rules:["The directory is the positional argument, default the current one.","workspace.json is the scope, and a -w or -e that disagrees with it is exit 2. --force is the way through, and it also skips the checksum comparison, so everything is re-sent.","--team is required in a directory with no record and no terminal: the record it writes carries the team name.","--delete-missing deletes scripts the directory no longer has, and only scripts \u2014 never payloads or the README. --yes skips the confirmation that names each one.","--async moves compiling and bundling to a background job and polls for the result, for a workspace too large to compile inside one request.","--skip-test-payloads and --skip-readme leave those out of the push."],notes:["Pushes scripts/**/*.ts (not scripts/api/**), test-payloads/**/*.json and README.md. Nothing else in the directory is read; parameters, API connections, listeners and packages have their own verbs.","Checksums decide what is sent. Once one script differs the whole scripts/ tree is uploaded, so the workspace ends up as the directory describes; test payloads and the README are compared one at a time. A locally new script whose content matches a vanished one is a rename.","scripts.sent is every script the workspace rewrote, which is the whole tree once one of them differs; scripts.updated is the subset whose content actually changed, and scripts.unchanged counts the rest. A caller reconciling against the workspace reads sent, one reporting what it edited reads updated.","Scripts push to a HEAD environment only: a non-HEAD one is exit 1 RELEASED_ENVIRONMENT before anything is written, with a hint pointing at environment target-release.","The README is the exception: a non-HEAD environment refuses it, the push warns, reports readme.pushed:false with the reason, and still succeeds.","A payload file whose folder does not end in a listener ID is warned about and skipped; one whose folder names a listener the API does not know is reported with the other payload failures as PUSH_INCOMPLETE, after everything else has been pushed. An illegal payload or script name is refused before anything is uploaded.","A default-mode request that times out is exit 1 PUSH_OUTCOME_UNKNOWN with checksums left alone; re-run with --async. Polling gives up after 16 minutes.","TypeScript diagnostics are reported and are not a failure. A failed test payload ends the run as exit 1 PUSH_INCOMPLETE after workspace.json has been updated for everything that landed, so a re-run sends only what is left.",'Nothing to send reports pushed:false and makes no request. --skip-readme reports readme.skipped:true beside pushed:false, so a caller can tell "not sent because you said not to" from "not sent because it had not changed".',"A push infers a rename from content. For a rename or a deletion by ID use script update --name and script delete instead."]});function localWorkspaceCommand(){let group=new Command("local-workspace").alias("lw").description("Manage a local copy of a workspace");return group.command("clone").description("Clone the workspace into a local directory").argument("[directory]","Directory to clone into, created when missing (optional, default: the current directory)").option("--team <teamId>",SCOPE_TEAM).option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--force","Clone into a non-empty directory without asking (optional on a TTY, required to overwrite a non-empty directory otherwise)").option("--no-test-payloads","Skip the test-payloads directory (optional, default: test payloads are cloned)").option("--explain",EXPLAIN).action(async(directoryArg,_opts,cmd)=>{if(explained(cmd,CLONE_DOC))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["team","workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt()}),teamId=resolved.team??"",workspaceId=resolved.workspace??"",environmentId=resolved.environment??"",directory=resolve7(directoryArg??"."),state=inspectDirectory(directory);await confirmTarget(directory,state,globals.force===!0);let updateMode=state==="cloned-workspace",withPayloads=globals.testPayloads!==!1,{fetched,apiFiles}=await withSpinner("Fetching workspace contents",async()=>{let everything=await fetchEverything(client,teamId,workspaceId,environmentId,withPayloads),connectionFiles=await apiConnectionFileInputs(client,everything.apiConnections);return{fetched:everything,apiFiles:connectionFiles}}),existingPackageJson=updateMode?(()=>{try{return readFileSync16(resolve7(directory,"package.json"),"utf8")}catch{return}})():void 0,{files,skipped}=buildManifest(fetched,apiFiles,existingPackageJson,{instance:requireInstance(globals.instance),teamId,workspaceId,environmentId}),result=writeClone(directory,files,updateMode),swept=sweepStaleFiles(directory,new Set(files.map(f2=>f2.path)));fetched.readme===void 0&&warnLine("\u26A0 No README available through this environment \u2014 README.md was not written.");for(let payload2 of skipped)warnLine(`\u26A0 Test payload "${payload2.name}" of event listener ${payload2.eventListenerId} was not cloned: ${payload2.reason}.`);isRaw()||(result.kept.length>0&&noteLine(`\u2714 Kept (already present): ${result.kept.join(", ")}${updateMode?" \u2014 package.json merged (dependencies replaced, the rest kept)":""}`),swept.length>0&&noteLine(`\u2714 Removed stale auto-generated files: ${swept.join(", ")}`));let payload={cloned:!0,directory,workspaceId,environmentId,files:result.written,kept:result.kept,skippedTestPayloads:skipped},release2=fetched.environment?.release;if(okMutation(`Workspace cloned into ${displayPath(directory)}`,payload,{workspace:`${fetched.workspace.name} (${workspaceId})`,environment:fetched.environment?`${fetched.environment.name} (${environmentId})`:environmentId,...fetched.environment?{version:release2?release2.version:"HEAD"}:{},scripts:fetched.scripts.length,apiConnections:apiFiles.length,testPayloads:fetched.testPayloads.reduce((total,l3)=>total+l3.payloads.length,0),filesWritten:result.written.length,filesKept:result.kept.length}),release2){let tail=withPayloads?", and test payloads are the ones stored today rather than the ones that release was cut with.":".";warnLine(`\u26A0 package.json dependencies come from the workspace's current configuration (HEAD), not from release ${release2.version}. The versions here can differ from the ones that release runs${tail} Everything else in the clone is that release's own snapshot.`)}}),group.command("push").description("Push local scripts, a README and test payloads back to the workspace").argument("[directory]","Directory holding the local copy (optional, default: the current directory)").option("--async","Compile and bundle in the background, polling until it finishes, which gives that work far longer to run at the cost of a slower answer once it is done (optional, default: the push is compiled inside the request and must finish within its timeout)").option("--skip-test-payloads","Push scripts only (optional, default: changed test payloads are pushed too)").option("--skip-readme","Leave the README alone (optional, default: a changed README.md is pushed too)").option("--force","Push every script and test payload without comparing checksums, and allow a target that workspace.json does not describe (optional)").option("--delete-missing","Delete workspace scripts this directory does not contain (optional, requires --yes without a TTY)").option("--yes","Skip the deletion confirmation (optional, required with --delete-missing without a TTY, ignored otherwise)").option("--team <teamId>","Team ID, which a fresh workspace.json has to name (required unless workspace.json describes the target, interactive when it does not, session default, env SR_CONNECT_CLI_TEAM, ignored when workspace.json describes the target)").option("-w, --workspace <workspaceId>","Workspace ID (required unless workspace.json describes the target, interactive when it does not, session default, env SR_CONNECT_CLI_WORKSPACE, default: the workspace recorded in workspace.json, refused when it names another workspace unless --force)").option("-e, --env <environmentId>","Environment ID (required unless workspace.json describes the target, interactive when it does not, session default, env SR_CONNECT_CLI_ENVIRONMENT, default: the environment recorded in workspace.json, refused when it names another environment unless --force)").option("--explain",EXPLAIN).action(async(directoryArg,_opts,cmd)=>{if(explained(cmd,PUSH_DOC))return;let globals=cmd.optsWithGlobals(),startedAt=Date.now(),directory=resolve7(directoryArg??"."),deleteMissing=globals.deleteMissing===!0,force=globals.force===!0,mode=globals.async===!0?"ASYNC":"SYNC",scan=scanWorkspace(directory,{withTestPayloads:globals.skipTestPayloads!==!0,withReadme:globals.skipReadme!==!0});scan.scripts.length===0&&scan.payloads.length===0&&fail(EXIT.USAGE,"NOT_A_LOCAL_WORKSPACE",`No scripts or test payloads found in ${directory}.`,{hint:`Clone a workspace into it first with \`${CLI} local-workspace clone\`.`}),assertPushable(scan.scripts,void 0,scan.readme,scan.payloads);for(let skipped of scan.skipped)warnLine(`\u26A0 ${skipped.path} was not pushed: ${skipped.reason}.`);let target=await resolvePushTarget(directory,globals),first=planPush(scan,target.metadata,{force,deleteMissing}),filled=await fillMissingIds(target,first,deleteMissing),replanned=filled.metadata===target.metadata?first:planPush(scan,filled.metadata,{force,deleteMissing}),unresolvable=new Set(filled.unresolvable.map(entry2=>entry2.path)),plan=unresolvable.size===0?replanned:{...replanned,payloads:{...replanned.payloads,create:replanned.payloads.create.filter(payload=>!unresolvable.has(payload.path))}},aimed={...target,metadata:filled.metadata},localNames=new Set(scan.scripts.map(script=>script.name)),renamedAway=new Set(plan.scripts.renames.map(rename=>rename.from)),wouldDelete=(filled.remote.length>0?filled.remote.map(row=>row.name):plan.scripts.missingLocally).filter(name=>!localNames.has(name)&&!renamedAway.has(name)).sort();if(deleteMissing&&await confirmDeleteMissing(wouldDelete,globals.yes===!0),!plan.anyWork){let totalMs2=Date.now()-startedAt;okMutation(`Nothing to push \u2014 every file matches ${METADATA_FILE}, pass --force to push anyway`,{pushed:!1,directory,workspaceId:aimed.workspaceId,environmentId:aimed.environmentId,mode,scripts:{uploaded:0,changed:[],unchanged:plan.scripts.unchanged,created:[],updated:[],deleted:[],renamed:[],compilationErrors:[]},testPayloads:{created:[],updated:[],unchanged:plan.payloads.unchanged,failed:[]},readme:{pushed:!1,unchanged:plan.readmeUnchanged,...globals.skipReadme===!0?{skipped:!0}:{}},durationMs:{total:totalMs2,scripts:0,testPayloads:0}},{workspace:aimed.label.workspace,environment:aimed.label.environment,scripts:`0 changed of ${plural4(scan.scripts.length,"script")}`,testPayloads:`0 changed of ${plural4(scan.payloads.length,"test payload")}`,timing:`total ${seconds(totalMs2)}`});return}if(!isRaw()){let scriptsPart=plan.scripts.upload.length>0?`${plural4(plan.scripts.upload.length,"script")} (${plan.scripts.changed.length} changed)`:"no scripts",payloadsPart=plural4(plan.payloads.create.length+plan.payloads.update.length,"test payload"),parts=[scriptsPart,payloadsPart,...plan.readme?["the README"]:[]];noteLine(`\u2714 Pushing ${parts.slice(0,-1).join(", ")} and ${parts.at(-1)} to ${aimed.label.workspace} \xB7 ${aimed.label.environment}`)}let lockId=await ensureWorkspaceLock(aimed.client,aimed.workspaceId),scriptsStarted=Date.now(),scriptResult=plan.scripts.upload.length>0?await pushScripts(aimed,plan,{mode,deleteMissing,lockId,...globals.instance===void 0?{}:{instance:globals.instance}}):void 0,scriptsMs=Date.now()-scriptsStarted,payloadsStarted=Date.now(),payloads=plan.payloads.create.length+plan.payloads.update.length>0?await pushTestPayloads(aimed,plan):{created:[],updated:[],failed:[]};payloads.failed.unshift(...filled.unresolvable);let payloadsMs=Date.now()-payloadsStarted,readme=plan.readme?await pushReadme(aimed,plan.readme):{pushed:!1};try{writeFileSync8(join15(directory,METADATA_FILE),renderMetadata(nextMetadata(aimed,plan,scriptResult,payloads,readme,deleteMissing)))}catch(err){warnLine(`\u26A0 ${METADATA_FILE} could not be updated: ${describeError(err)} \u2014 the next push will send everything again.`)}let totalMs=Date.now()-startedAt,editedRemotely=(scriptResult?.updated??[]).filter(row=>plan.scripts.changed.includes(row.name)),scriptsCell=scriptResult?`${plural4(plan.scripts.upload.length,"script")} uploaded, ${plan.scripts.changed.length} changed locally \u2014 ${scriptResult.created.length} created, ${editedRemotely.length} updated${scriptResult.deleted.length>0?`, ${scriptResult.deleted.length} deleted`:""}`:"unchanged, nothing uploaded";for(let name of plan.scripts.unattributed)warnLine(`\u26A0 ${name} looks like a script that was renamed and edited in the same push, which cannot be told apart from a new one \u2014 it was created and the old script is still in the workspace.`);if(!isRaw()){let withheld=[...plan.scripts.upload.length===0&&plan.scripts.unchanged>0?[plural4(plan.scripts.unchanged,"script")]:[],...plan.payloads.unchanged>0?[plural4(plan.payloads.unchanged,"test payload")]:[],...plan.readmeUnchanged?["the README"]:[]];withheld.length>0&&noteLine(`\u2714 Unchanged, not pushed: ${withheld.join(" and ")} \u2014 pass --force to push ${withheld.length===1?"it":"them"} anyway.`),!deleteMissing&&wouldDelete.length>0&&noteLine(`\u2714 In the workspace but not in this directory, left alone: ${wouldDelete.join(", ")} \u2014 pass --delete-missing to remove them.`),plan.payloads.missingLocally.length>0&&noteLine(`\u2714 Test payloads missing locally are never deleted remotely: ${plan.payloads.missingLocally.join(", ")}`)}payloads.failed.length>0&&fail(EXIT.API_ERROR,"PUSH_INCOMPLETE",`Scripts: ${scriptsCell}. ${plural4(payloads.failed.length,"test payload")} could not be pushed: ${payloads.failed.map(failure=>`${failure.path} \u2014 ${failure.message}`).join("; ")}`,{hint:`${METADATA_FILE} was updated for everything that landed \u2014 run the push again to retry the rest.`});let detailRows={workspace:aimed.label.workspace,environment:aimed.label.environment,mode,scripts:scriptsCell,...plan.scripts.renames.length>0?{renamed:plan.scripts.renames.map(rename=>`${rename.from} \u2192 ${rename.to}`).join(", ")}:{},testPayloads:`${payloads.created.length} created, ${payloads.updated.length} updated`,readme:readme.pushed?"updated":readme.error!==void 0?`not pushed \u2014 ${readme.error}`:globals.skipReadme===!0?"skipped (--skip-readme)":plan.readmeUnchanged?"unchanged, not pushed":"none in this directory",timing:`scripts ${seconds(scriptsMs)} \xB7 test payloads ${seconds(payloadsMs)} \xB7 total ${seconds(totalMs)}`},compilation=scriptResult?.compilationErrors??[];okMutation("Workspace pushed",{pushed:!0,directory,workspaceId:aimed.workspaceId,environmentId:aimed.environmentId,mode,scripts:{uploaded:plan.scripts.upload.length,changed:plan.scripts.changed,unchanged:plan.scripts.unchanged,created:scriptResult?.created??[],sent:scriptResult?.updated??[],updated:editedRemotely,deleted:scriptResult?.deleted??[],renamed:plan.scripts.renames,compilationErrors:compilation},testPayloads:{created:payloads.created,updated:payloads.updated,unchanged:plan.payloads.unchanged,failed:payloads.failed},readme:{pushed:readme.pushed,unchanged:plan.readmeUnchanged,...globals.skipReadme===!0?{skipped:!0}:{},...readme.error===void 0?{}:{error:readme.error}},durationMs:{total:totalMs,scripts:scriptsMs,testPayloads:payloadsMs}},compilation.length>0?`${renderDetail(detailRows)}
1373
+
1374
+ ${renderCompilationErrors(compilation)}`:detailRows)}),group}var PACKAGE_NAME_FORMAT="up to 100 characters, as published on the public NPM registry",PACKAGE_VERSION_FORMAT="an exact published version, up to 50 characters",MAX_PACKAGE_NAME=100,MAX_PACKAGE_VERSION=50;function normalizePackageName(name){return name.trim()}function normalizePackageVersion(version2){return version2.trim()}function packageNameError(name){let normalized=normalizePackageName(name);if(!normalized)return"A package name is required.";if(normalized.length>MAX_PACKAGE_NAME)return`A package name can be at most ${MAX_PACKAGE_NAME} characters (that one is ${normalized.length}).`}function packageVersionError(version2){let normalized=normalizePackageVersion(version2);if(!normalized)return"A package version is required.";if(normalized.length>MAX_PACKAGE_VERSION)return`A package version can be at most ${MAX_PACKAGE_VERSION} characters (that one is ${normalized.length}).`}function assertPackageName(name){let error51=packageNameError(name);return error51&&fail(EXIT.USAGE,"INVALID_PACKAGE_NAME",error51),normalizePackageName(name)}function assertPackageVersion(version2){let error51=packageVersionError(version2);return error51&&fail(EXIT.USAGE,"INVALID_PACKAGE_VERSION",error51),normalizePackageVersion(version2)}var createBodySchema9=external_exports.object({name:external_exports.string().min(1),version:external_exports.string().min(1).optional()}).strict(),updateBodySchema9=external_exports.object({version:external_exports.string().min(1)}).strict(),LIST_DOC10=defineCommandDoc("package list",{rules:["The workspace is -w; there is no environment anywhere in this group and no positional argument."],notes:["A non-HEAD environment keeps the dependencies its release captured, and nothing here reports those: the list is the workspace's current one."]}),GET_DOC9=defineCommandDoc("package get",{rules:["The package is the positional argument and the workspace is -w."],notes:["Reports the version the workspace depends on and whether the package is required, which is what remove refuses on."]}),REMOVE_DOC2=defineCommandDoc("package remove",{rules:["The package is the positional argument and the workspace is -w.","--yes skips the confirmation, and is required without a terminal."],notes:["Workspace-wide. Scripts importing the package stop building the next time they are saved; non-HEAD environments are unaffected.","A package the workspace requires cannot be removed: the runtime's own, or one an event listener or API connection uses as its library \u2014 the listener or connection has to go first."]}),NPM_VERSIONS_DOC=defineCommandDoc("package list-npm-versions",{rules:["The package name is the positional argument, as published on the public NPM registry. There is no workspace and no scope: this reads the registry, not the API.","--limit keeps the newest N versions; omitted, every published version is answered.","--stable-only drops prereleases but keeps whatever the latest dist-tag points at, even when that is one."],notes:["Newest first, with the dist-tags. Needs no credentials and touches no instance, so it answers when authentication is the thing that broke.","SR_CONNECT_CLI_NPM_REGISTRY points the lookup at a mirror. It is the one environment variable naming a host that is not the API."]}),ADD_DOC=defineCommandDoc("package add",{schema:createBodySchema9,body:{name:"lodash",version:"4.17.21"},rules:[`name: ${PACKAGE_NAME_FORMAT}. Spelled --name as a flag, or given as the positional argument, the way package list-npm-versions takes it; --name wins where both are given.`,`version: ${PACKAGE_VERSION_FORMAT}, spelled --package-version as a flag; omitted, the API takes the registry's latest version at the time of the call.`,"Whether the name and the version exist is the API's answer rather than a local check.","A package belongs to the workspace: no environment anywhere, and nothing is recompiled until a script is saved."]}),UPDATE_DOC9=defineCommandDoc("package update",{schema:updateBodySchema9,body:{version:"4.17.21"},rules:[`version: ${PACKAGE_VERSION_FORMAT}, spelled --package-version as a flag.`,"name and type cannot change; remove the package and add another instead. A required package can still change version.","Nothing is recompiled until a script is saved."]});async function resolveScope8(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace"],{workspace:globals.workspace,team:globals.team},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,workspace:resolved.workspace??""}}async function resolvePackage(scope2,provided){if(provided)return{id:assertResourceId(provided,"packageId")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<packageId> is required. ${supplyHint()}`);let labels={};return{id:(await resolveParams(["workspacePackage"],{workspace:scope2.workspace},{client:scope2.client,interactive:!0,labels})).workspacePackage??"",label:labels.workspacePackage}}var TYPE_VERSION="\0type",API_LATEST="\0latest";async function askPackageName(initial){for(;;){let answer=await prompts().text(`NPM package name (${PACKAGE_NAME_FORMAT})`,{...initial?{initial}:{},allowEmpty:!0}),error51=packageNameError(answer);if(!error51)return normalizePackageName(answer);prompts().note(`\u2716 ${error51}`)}}async function askVersionText(message,opts={}){for(;;){let answer=await prompts().text(message,{...opts.initial?{initial:opts.initial}:{},allowEmpty:!0});if(opts.allowEmpty&&answer.trim()==="")return;let error51=packageVersionError(answer);if(!error51)return normalizePackageVersion(answer);prompts().note(`\u2716 ${error51}`)}}function versionChoices(published,opts){let offered=published.versions.slice(0,MAX_OFFERED_VERSIONS);opts.current&&!offered.includes(opts.current)&&offered.unshift(opts.current);let choices=offered.map(version2=>{let marks=[];return version2===opts.current&&marks.push("current"),version2===published.latest&&marks.push("latest"),isPrerelease(version2)&&marks.push("prerelease"),{value:version2,label:version2,...marks.length>0?{display:`${version2} (${marks.join(", ")})`}:{}}});return choices.push({value:TYPE_VERSION,label:"Type a version\u2026",hint:"one the list does not show"}),opts.omitAnswer&&choices.push({value:API_LATEST,label:"Let the API resolve the latest version",hint:"sends no version"}),choices}async function askCreateBody2(providedVersion){for(;;){let name=await askPackageName();if(providedVersion!==void 0)return{name,version:providedVersion};let published=await withSpinner("Looking up versions on the NPM registry",()=>fetchVersions(name));if(published==="not-found"){prompts().note(`\u2716 The NPM registry does not publish a package called "${name}".`);continue}let message=`Version of ${name}`;if(!published)return prompts().note("\u2716 Could not reach the NPM registry \u2014 type a version, or leave it empty for its latest."),withVersion(name,await askVersionText(`${message}, ${PACKAGE_VERSION_FORMAT} (empty for the registry's latest)`,{allowEmpty:!0}));let picked=await prompts().select(`${message}:`,versionChoices(published,{omitAnswer:!0}),published.latest?{initial:published.latest}:{});return picked===API_LATEST?{name}:picked===TYPE_VERSION?withVersion(name,await askVersionText(`${message}, ${PACKAGE_VERSION_FORMAT}`)):{name,version:picked}}}function withVersion(name,version2){return version2===void 0?{name}:{name,version:version2}}async function askVersionChange(name,current){let published=await withSpinner("Looking up versions on the NPM registry",()=>fetchVersions(name)),message=`New version for ${name}`,textOpts=current?{initial:current}:{},answer;if(!published||published==="not-found")prompts().note(published==="not-found"?`\u2716 The NPM registry does not publish "${name}" \u2014 type the version to move to.`:"\u2716 Could not reach the NPM registry \u2014 type the version to move to."),answer=await askVersionText(`${message}, ${PACKAGE_VERSION_FORMAT}`,textOpts);else{let picked=await prompts().select(`${message}:`,versionChoices(published,current?{current}:{}),current?{initial:current}:{});answer=picked===TYPE_VERSION?await askVersionText(`${message}, ${PACKAGE_VERSION_FORMAT}`,textOpts):picked}if(answer!==void 0&&current!==void 0&&answer===current){prompts().note(`\u2716 ${name} is already on ${current} \u2014 nothing to change.`);return}return answer}async function confirmDeletion3(scope2,pkg){let current=await withSpinner("Checking the package",()=>packageInfo(scope2.client,scope2.workspace,pkg.id)),name=current?.name??pkg.label??pkg.id;current?.required&&fail(EXIT.USAGE,"REQUIRED_PACKAGE",`"${name}" is required by this workspace and cannot be removed.`,{hint:`The runtime provides it, or an event listener or API connection uses it as its library \u2014 delete that event listener or API connection first. Its version can still be changed with ${CLI} package update ${pkg.id}.`}),prompts().note(["Removing takes the package out of the whole workspace.","Scripts that import it stop building the next time they are updated.","Environments already running a deployed release are not affected."].join(`
1375
+ `));let described=current?`${name}@${current.version} (${pkg.id})`:name;return await prompts().confirm(`Remove package ${described}?`)||fail(EXIT.CANCELLED,"CANCELLED","Removal cancelled."),name}function bundleNote(name){isRaw()||prompts().note(`Update the scripts that import ${name} to pick the change up \u2014 saving a script rebuilds the workspace (${CLI} script update).`)}function humanPackage(pkg){return{...pkg,required:pkg.required?"yes":"no"}}function parseLimit2(value){if(value===void 0)return;let parsed=Number(value);return(!Number.isInteger(parsed)||parsed<1)&&fail(EXIT.USAGE,"INVALID_LIMIT",`--limit must be a whole number of 1 or more (got ${value}).`),parsed}function tagsOf(distTags,version2){let tags=Object.entries(distTags).filter(([,target])=>target===version2).map(([tag])=>tag);return tags.length>0?tags.join(", "):"\u2014"}function packageCommand(){let pkg=new Command("package").description("Manage the NPM packages a workspace depends on");return pkg.command("list").description("List the packages a workspace depends on").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC10))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope8(globals),{data,response,error:error51}=await withSpinner("Fetching packages",()=>scope2.client.GET("/v1/workspace/{workspaceId}/packages",{params:{path:{workspaceId:scope2.workspace}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({packages:d.packages.map(humanPackage)})})}),pkg.command("get").description("Get a single package of a workspace").argument("[packageId]","Package ID (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,GET_DOC9))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope8(globals),target=await resolvePackage(scope2,idArg),{data,response,error:error51}=await withSpinner("Fetching package",()=>scope2.client.GET("/v1/workspace/{workspaceId}/package/{packageId}",{params:{path:{workspaceId:scope2.workspace,packageId:target.id}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:humanPackage})}),pkg.command("add").description("Add an NPM package to a workspace").argument("[name]",`NPM package name, ${PACKAGE_NAME_FORMAT} (required unless --input or --name, interactive, ignored with --input)`).option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--name <name>",`NPM package name, ${PACKAGE_NAME_FORMAT} (required unless --input or the positional argument is given, interactive, supersedes the positional argument)`).option("--package-version <version>",`Package version, ${PACKAGE_VERSION_FORMAT} (optional, interactive, API default: the registry's latest version at the time of the call)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(nameArg,opts,cmd)=>{if(explained(cmd,ADD_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope8(globals),name=opts.name??nameArg,rawBody;opts.input?rawBody=readInput(opts.input):name!==void 0?rawBody=stripUndefined({name,version:opts.packageVersion}):(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR","--name is required. Pass it, or name the package as the argument."),rawBody=await askCreateBody2(opts.packageVersion));let parsed=validate(createBodySchema9,rawBody),body={name:assertPackageName(parsed.name),...parsed.version!==void 0?{version:assertPackageVersion(parsed.version)}:{}},{data,response,error:error51}=await withSpinner("Adding package",()=>scope2.client.POST("/v1/workspace/{workspaceId}/package",{params:{path:{workspaceId:scope2.workspace}},body}));(!response.ok||!data)&&apiFail(response.status,error51),await syncPackages(scope2.client,scope2.workspace),okMutation("Package added",data,humanPackage(data)),bundleNote(data.name)}),pkg.command("update").description("Change the version of a package on a workspace").argument("[packageId]","Package ID (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--package-version <version>",`New version, ${PACKAGE_VERSION_FORMAT} (required unless --input, interactive)`).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC9))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope8(globals),target=await resolvePackage(scope2,idArg),version2;if(opts.input)version2=assertPackageVersion(validate(updateBodySchema9,readInput(opts.input)).version);else if(opts.packageVersion!==void 0)version2=assertPackageVersion(validate(updateBodySchema9,{version:opts.packageVersion}).version);else{canPrompt()||failNothingToUpdate(["--package-version","--input"]);let current=await withSpinner("Checking the package",()=>packageInfo(scope2.client,scope2.workspace,target.id)),name=current?.name??target.label??target.id,answer=await askVersionChange(name,current?.version);if(answer===void 0)return;version2=answer}let{data,response,error:error51}=await withSpinner("Updating package",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/package/{packageId}",{params:{path:{workspaceId:scope2.workspace,packageId:target.id}},body:{version:version2}}));(!response.ok||!data)&&apiFail(response.status,error51),await syncPackages(scope2.client,scope2.workspace),okMutation("Package updated",data,humanPackage(data)),bundleNote(data.name)}),pkg.command("remove").description("Remove a package from a workspace").argument("[packageId]","Package ID (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE_DESTRUCTIVE).option("--team <teamId>",SCOPE_TEAM_FILTER_DESTRUCTIVE).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,REMOVE_DOC2))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope8(globals,{useSession:canPrompt()}),target=await resolvePackage(scope2,idArg),name=target.label;opts.yes||(canPrompt()||failNeedsYes(`package ${target.label??target.id}`,"Removing"),name=await confirmDeletion3(scope2,target)),name??=(await withSpinner("Checking the package",()=>packageInfo(scope2.client,scope2.workspace,target.id)))?.name;let{response,error:error51}=await withSpinner("Removing package",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/package/{packageId}",{params:{path:{workspaceId:scope2.workspace,packageId:target.id}}}));response.ok||apiFail(response.status,error51),await syncPackages(scope2.client,scope2.workspace),okMutation("Package removed",{deleted:!0,id:target.id}),bundleNote(name??target.id)}),pkg.command("list-npm-versions").description("List the versions the NPM registry publishes for a package").argument("[name]","NPM package name to look up on the registry (required, interactive)").option("--limit <count>","How many versions to return, newest first (optional, default: every published version)").option("--stable-only","Exclude prereleases (optional)").option("--explain",EXPLAIN).action(async(nameArg,opts,cmd)=>{if(explained(cmd,NPM_VERSIONS_DOC))return;let limit=parseLimit2(opts.limit),typed=nameArg;typed===void 0&&(canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<name> is required. ${supplyHint()}`),typed=await askPackageName());let name=assertPackageName(typed),published=await withSpinner("Looking up versions on the NPM registry",()=>fetchVersions(name));published==="not-found"&&fail(EXIT.NOT_FOUND,"NPM_PACKAGE_NOT_FOUND",`The NPM registry does not publish a package called "${name}".`,{hint:"Check the spelling, including the @scope/ prefix if the package has one."}),published||fail(EXIT.API_ERROR,"NPM_LOOKUP_FAILED",`Could not read ${registryBase()}.`,{hint:"Check the network and any proxy; SR_CONNECT_CLI_NPM_REGISTRY points the lookup at another registry."});let kept=published.versions.filter(version2=>!opts.stableOnly||!isPrerelease(version2)||version2===published.latest),versions=limit===void 0?kept:kept.slice(0,limit),payload={name,...published.latest?{latest:published.latest}:{},distTags:published.distTags,versions};ok(payload,{human:d=>[renderDetail({name:d.name,latest:d.latest??"\u2014"}),"",renderTable(d.versions.map(version2=>({version:version2,tag:tagsOf(d.distTags,version2),prerelease:isPrerelease(version2)?"yes":"no"})))].join(`
1376
+ `)})}),pkg}var HELP_OPTION_DESCRIPTION="Display help for command",HELP_COMMAND_DESCRIPTION="Display help for command",VERSION_DESCRIPTION="Print the CLI version",MIN_WIDTH_TO_WRAP=24;function rootHelpFooter(){return["",`The full manual, with the exit codes and the raw-output contract: ${CLI} cli get-readme (needs no credentials).`,"Per verb: <verb> -h for the flags it has, <verb> --explain for what each one takes and when it is refused. Neither sends anything.","Agents: pass --agent --raw on every call, or set SR_CONNECT_CLI_AGENT=1 and SR_CONNECT_CLI_RAW=1 once."].join(`
1377
+ `)}function applyHelpConventions(cmd){cmd.helpOption("-h, --help",HELP_OPTION_DESCRIPTION),cmd.commands.length>0&&cmd.helpCommand("help [command]",HELP_COMMAND_DESCRIPTION),cmd.configureHelp({minWidthToWrap:MIN_WIDTH_TO_WRAP});for(let sub of cmd.commands)applyHelpConventions(sub)}function addGlobalOptions(program3){return program3.version(VERSION,"-V, --version",VERSION_DESCRIPTION).option("--instance <instance>","Instance to talk to: eu, us, or a URL; overrides the stored config (optional, interactive at 'auth login', env SR_CONNECT_CLI_INSTANCE)").option("--raw","Compact JSON output; not an agent switch \u2014 prompts still work on a TTY, rendering on stderr (optional, env SR_CONNECT_CLI_RAW=1)").option("--no-session","Ignore the session defaults set by 'cli set-session' (optional)").option("--no-prompts","Never prompt: missing params and confirmations become usage errors (optional, env SR_CONNECT_CLI_NO_PROMPTS=1)").option("--agent","Identifies you as an agent, disables interactive prompts (optional, env SR_CONNECT_CLI_AGENT=1)").option("--copy-output-to-file [file]","Also append stdout to a file; the name is optional and the next word is taken as it, so put the flag after the command or name the file (optional, interactive in the 'log' commands, default: output-<unix-ts>.json in the current directory \u2014 .txt without --raw, refused when the value names a command group)").option("--no-record-api-calls","Do not record this run's API requests for troubleshooting (optional, env SR_CONNECT_CLI_NO_RECORD_API_CALLS=1)").option("--no-lock","Do not take or present a workspace lock on writes (optional, env SR_CONNECT_CLI_NO_LOCK=1)").option("--lock-id <lockId>","Present the specified workspace lock ID on writes instead of the one this shell holds (optional, env SR_CONNECT_CLI_LOCK_ID, default: the lock this shell took or a new one)").option("--no-local-sync","Do not update a local copy of the workspace this command changes (optional, env SR_CONNECT_CLI_NO_LOCAL_SYNC=1)").option("--no-local-workspace","Do not take the team, workspace and environment from a local copy of a workspace at or above the working directory (optional, env SR_CONNECT_CLI_NO_LOCAL_WORKSPACE=1)").option("--no-update-check","Do not check NPM for a newer version of the CLI (optional, env SR_CONNECT_CLI_NO_UPDATE_CHECK=1)").option("--no-version-gate","Run even when the deployment reports this CLI version as unsupported (optional, env SR_CONNECT_CLI_NO_VERSION_GATE=1)").option("--no-crash-reports","Do not write or offer a crash report when this run fails unexpectedly (optional, env SR_CONNECT_CLI_NO_CRASH_REPORTS=1)").option("--no-agentic-feedback","Do not post feedback unless a human is answering the prompts (optional, env SR_CONNECT_CLI_NO_AGENTIC_FEEDBACK=1)")}var createBodySchema10=external_exports.object({environmentId:external_exports.string().min(1),scriptId:external_exports.string().min(1).optional(),scriptName:external_exports.string().min(1).optional(),cronExpression:external_exports.string().min(1),disabled:external_exports.boolean().optional()}).strict().refine(body=>!(body.scriptId&&body.scriptName),{error:"scriptId and scriptName cannot be combined.",path:["scriptId"]}).refine(body=>!!(body.scriptId??body.scriptName),{error:"Either scriptId or scriptName must be specified.",path:["scriptId"]}),updateBodySchema10=external_exports.object({cronExpression:external_exports.string().min(1).optional(),disabled:external_exports.boolean().optional(),scriptId:external_exports.string().min(1).optional()}).strict().refine(body=>Object.keys(body).length>0,{message:"At least one of cronExpression, disabled or scriptId is required."}),CRON_RULE=`cronExpression: six fields, second minute hour day-of-month month day-of-week; ${HOURLY_CRON} runs once per hour. Firings closer than ${MIN_TRIGGER_INTERVAL_MINUTES} minutes apart are accepted and spaced out to that floor.`,LIST_DOC11=defineCommandDoc("scheduled-trigger list",{rules:["The workspace is -w and the environment -e; there is no positional argument."],notes:["The schedule and the enabled state are per-environment, so the same trigger reads differently through two environments. A trigger with no schedule in the environment named is a real state and is listed as not scheduled \u2014 it comes from an environment the schedule was never set in."]}),GET_DOC10=defineCommandDoc("scheduled-trigger get",{rules:["The scheduled trigger is the positional argument; the workspace is -w and the environment -e."],notes:["Reports the expression, its description in words, the next and last firing, the upcoming firings and any warnings.","The warnings are where a schedule the API spaced out to the 15-minute floor becomes visible: create cannot report it, and get and update can."]}),DELETE_DOC9=defineCommandDoc("scheduled-trigger delete",{rules:["The scheduled trigger is the positional argument; the workspace is -w and the environment -e, which gates the write rather than choosing what is deleted.","--yes skips the confirmation, and is required without a terminal."],notes:["Deletes the trigger from the whole workspace rather than from one environment. The script it ran is left alone."]}),CREATE_DOC9=defineCommandDoc("scheduled-trigger create",{schema:createBodySchema10,conditional:["scriptId","scriptName"],body:{environmentId:"<environmentId>",cronExpression:HOURLY_CRON,scriptId:"<scriptId>",scriptName:"NightlySync",disabled:!1},rules:["environmentId is required in the body and names the environment the schedule is created in: -e/--env fills it on the flags path only, an --input body superseding every body flag, and with --input the flag is not needed at all. An -e or SR_CONNECT_CLI_ENVIRONMENT that names a different environment from the body is exit 2 rather than a tie-break; the session record and a clone's workspace.json are not consulted for the environment when a body is given. The workspace is -w.",`${CRON_RULE} A body has to state it: it is the --cron flag, not the key, that falls back to ${HOURLY_CRON} when it is left out.`,`Exactly one of scriptId (an existing script) or scriptName (a script the API creates, ${SCRIPT_NAME_RULE}) is required.`,"disabled: true creates the trigger disabled in that environment; omitted means enabled."],notes:["A trigger with no schedule cannot be created here, though list reports one as a real state: the --cron flag falls back to hourly, and a body without cronExpression is refused. That state comes from an environment the schedule was never set in \u2014 a trigger scheduled in one environment reads as not scheduled in every other.","Firings closer than 15 minutes apart are accepted and spaced out to the floor. create cannot report that; get and update show it under warnings.",SCRIPT_NAME_BUNDLE_REPORT]}),UPDATE_DOC10=defineCommandDoc("scheduled-trigger update",{schema:updateBodySchema10,body:{cronExpression:HOURLY_CRON,disabled:!1,scriptId:"<scriptId>"},rules:["An omitted key keeps the current value, and a body with no keys is refused: at least one of cronExpression, disabled or scriptId is required. disabled is --disabled and --enabled as flags.",`${CRON_RULE} Spelled --cron as a flag, which unlike on create has no fallback here. It and disabled apply to the environment named by -e only.`,"A trigger with no schedule in the environment -e names must be given cronExpression before disabled can change there.","scriptId: the script the trigger runs, shared by every environment; there is no scriptName, since update cannot create a script. Neither the schedule nor the script can be removed.","In a non-HEAD environment scriptId is refused unless it equals the current one; cronExpression and disabled are accepted."]}),WEEKDAYS=[{value:"MON",label:"Monday"},{value:"TUE",label:"Tuesday"},{value:"WED",label:"Wednesday"},{value:"THU",label:"Thursday"},{value:"FRI",label:"Friday"},{value:"SAT",label:"Saturday"},{value:"SUN",label:"Sunday"}];async function askUntil(message,initial,parse4){for(;;){let answer=await prompts().text(message,{initial}),parsed=parse4(answer);if(typeof parsed!="string")return parsed;prompts().note(`\u2716 ${parsed}`)}}async function askInterval(){return askUntil(`Interval in minutes (1-59, spaced out to ${MIN_TRIGGER_INTERVAL_MINUTES} if closer)`,String(MIN_TRIGGER_INTERVAL_MINUTES),answer=>{let minutes=Number(answer.trim());return!Number.isInteger(minutes)||minutes<1||minutes>59?"Enter a whole number of minutes between 1 and 59.":minutes})}async function askTime(){return askUntil("Time of day (HH:MM)","09:00",answer=>{let match=/^(\d{1,2}):(\d{2})$/.exec(answer.trim()),hour=Number(match?.[1]),minute=Number(match?.[2]);return!match||hour>23||minute>59?"Enter a time as HH:MM, e.g. 09:30.":{hour,minute}})}async function buildCron(){let preset=await prompts().select("Schedule:",[{value:"hourly",label:"Every hour",hint:HOURLY_CRON},{value:"minutes",label:"Every N minutes"},{value:"daily",label:"Every day at a set time"},{value:"weekly",label:"Every week on a set day and time"},{value:"custom",label:"Custom CRON expression"}]);if(preset==="minutes")return everyMinutesCron(await askInterval());if(preset==="daily"){let{hour,minute}=await askTime();return dailyCron(hour,minute)}if(preset==="weekly"){let day=await prompts().select("Day of week:",WEEKDAYS),{hour,minute}=await askTime();return weeklyCron(day,hour,minute)}return preset==="custom"?(await askUntil(`CRON expression (${CRON_FIELDS})`,HOURLY_CRON,answer=>cronError(answer)??{expression:answer.trim()})).expression:HOURLY_CRON}function withScope6(cmd,opts={}){let env=opts.gate?opts.destructive?SCOPE_ENVIRONMENT_GATE_DESTRUCTIVE:SCOPE_ENVIRONMENT_GATE:opts.destructive?SCOPE_ENVIRONMENT_DESTRUCTIVE:SCOPE_ENVIRONMENT;return cmd.option("-w, --workspace <workspaceId>",opts.destructive?SCOPE_WORKSPACE_DESTRUCTIVE:SCOPE_WORKSPACE).option("-e, --env <environmentId>",env).option("--team <teamId>",opts.destructive?SCOPE_TEAM_FILTER_DESTRUCTIVE:SCOPE_TEAM_FILTER)}async function resolveScope9(globals,opts={}){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt(),useSession:opts.useSession});return{client,workspace:resolved.workspace??"",environment:resolved.environment??""}}async function resolveTrigger(scope2,provided){if(provided)return{id:assertResourceId(provided,"scheduledTriggerId")};canPrompt()||fail(EXIT.USAGE,"USAGE_ERROR",`<scheduledTriggerId> is required. ${supplyHint()}`);let labels={};return{id:(await resolveParams(["scheduledTrigger"],{workspace:scope2.workspace,environment:scope2.environment},{client:scope2.client,interactive:!0,labels})).scheduledTrigger??"",label:labels.scheduledTrigger}}function scriptCell(script){return script?`${script.name} (${script.id})`:"\u2014"}function triggerDetail(t){return{id:t.id,script:scriptCell(t.script),cronExpression:t.cronExpression??"\u2014",schedule:scheduleOf(t),disabled:t.disabled,nextTriggerDate:t.nextTriggerDate??"\u2014",lastTriggerDate:t.lastTriggerDate??"\u2014",nextScheduledDates:t.nextScheduledDates.length===0?"\u2014":t.nextScheduledDates.join(`
1378
+ `)}}function reportWarnings(t){if(!isRaw())for(let warning of t.warnings)warnLine(`\u26A0 ${warning}`)}async function askSchedule(current,opts={}){let scheduled=current.cronExpression!==void 0;if(!scheduled&&opts.required)return prompts().note("\u26A0 This trigger has no schedule in this environment, and the only other thing an environment owns is the enabled state \u2014 which cannot be set until there is a schedule to set it on. Set one now, or press Ctrl-C to leave the trigger alone."),buildCron();let kept=scheduleOf(current),choices=[{value:"keep",label:kept,display:`${kept} (current)`,...scheduled?{hint:current.cronExpression}:{}},{value:"set",label:scheduled?"Change the schedule":"Set a schedule"}];return await prompts().select("Schedule:",choices,{initial:"keep"})==="keep"?void 0:buildCron()}async function buildUpdateBody4(scope2,triggerId,opts){let current=await withSpinner("Fetching scheduled trigger",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,scheduledTriggerId:triggerId}}}));(!current.response.ok||!current.data)&&apiFail(current.response.status,current.error);let release2=await withSpinner("Checking the environment",()=>environmentRelease(scope2.client,scope2.workspace,scope2.environment));release2&&opts.scriptId!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","The script belongs to the scheduled trigger and is shared by every environment, so it cannot be changed in an environment with a release deployed. Target a HEAD environment, or pass only --cron / --disabled / --enabled."),release2&&prompts().note(`\u26A0 This environment has ${release2.version?`release ${release2.version}`:"a release"} deployed. Only the schedule and the enabled state can be changed there; the script belongs to the scheduled trigger and is shared by every environment.`);let scriptId=release2?void 0:opts.scriptId??await askKeepOrChange({client:scope2.client,key:"script",deps:{workspace:scope2.workspace,environment:scope2.environment},message:"Script:",current:{value:current.data.script?.id,label:current.data.script?.name}}),scheduleRequired=release2!==void 0&&current.data.cronExpression===void 0,cronExpression=opts.cron===void 0?await askSchedule(current.data,{required:scheduleRequired}):assertCron(opts.cron),disabled=disabledFromFlags(opts)??await askStatus(current.data.disabled,"the scheduled trigger"),schedule=current.data.cronExpression===void 0&&cronExpression===void 0&&disabled!==void 0?await askSchedule(current.data,{required:!0}):cronExpression;if(scriptId===void 0&&schedule===void 0&&disabled===void 0){prompts().note("Nothing to update \u2014 the scheduled trigger was left as it is.");return}return stripUndefined({scriptId,cronExpression:schedule,disabled})}function scheduledTriggerCommand(){let st2=new Command("scheduled-trigger").alias("st").description("Manage workspace scheduled triggers");return st2.command("create").description("Create a scheduled trigger in a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>","Environment ID, sent as environmentId in the body (required unless --input, interactive, session default, env SR_CONNECT_CLI_ENVIRONMENT)").option("--team <teamId>",SCOPE_TEAM_FILTER).option("--script-id <id>","Existing script ID to trigger (required unless --script-name or --input, interactive, exclusive with --script-name)").option("--script-name <name>","Name of a new script to create and trigger (required unless --script-id or --input, interactive, exclusive with --script-id)").option("--cron <expression>",`6-field CRON expression, ${CRON_FIELDS} (optional, interactive, default: '${HOURLY_CRON}' \u2014 once per hour)`).option("--disabled","Create the trigger disabled (optional, API default: enabled)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC9))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),interactive=canPrompt(),scope2=await resolveParams(opts.input?["workspace"]:["workspace","environment"],{team:opts.team??globals.team,workspace:opts.workspace??globals.workspace,environment:opts.env??globals.env},{client,interactive,offerSession:!opts.input}),workspaceId=scope2.workspace??"",rawBody;if(opts.input)rawBody=readInput(opts.input);else{let scriptId=opts.scriptId,scriptName=opts.scriptName;!scriptId&&!scriptName&&(interactive||fail(EXIT.USAGE,"USAGE_ERROR","--script-id or --script-name is required."),{scriptId,scriptName}=await askScript({client,workspace:workspaceId,environment:scope2.environment??""}));let cronExpression=opts.cron??(interactive?await buildCron():HOURLY_CRON);rawBody=stripUndefined({environmentId:scope2.environment,scriptId,scriptName,cronExpression,disabled:opts.disabled})}let body=validate(createBodySchema10,rawBody);opts.input&&assertExplicitEnvironmentAgrees(opts.env,body.environmentId),body.cronExpression=assertCron(body.cronExpression),body.scriptName!==void 0&&(body.scriptName=assertScriptName(body.scriptName));let schedule=describeCron(body.cronExpression);interactive&&schedule&&prompts().note(`\u2714 Schedule: ${schedule} (${body.cronExpression})`);let{data,response,error:error51}=await withSpinner("Creating scheduled trigger",()=>client.POST("/v1/workspace/{workspaceId}/scheduledTrigger",{params:{path:{workspaceId}},body:{disabled:!1,...body}}));(!response.ok||!data)&&apiFail(response.status,error51),okMutation("Scheduled trigger created",data,bundleReportDetail({...data,cronExpression:body.cronExpression,...schedule?{schedule}:{}},data))}),withScope6(st2.command("list").description("List scheduled triggers in a workspace")).option("--explain",EXPLAIN).action(async(_opts,cmd)=>{if(explained(cmd,LIST_DOC11))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope9(globals),{data,response,error:error51}=await withSpinner("Fetching scheduled triggers",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTriggers",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({scheduledTriggers:d.scheduledTriggers.map(t=>({id:t.id,script:scriptCell(t.script),schedule:scheduleOf(t),disabled:t.disabled,next:t.nextTriggerDate??"\u2014"}))})})}),withScope6(st2.command("get").description("Get a single scheduled trigger as the environment sees it").argument("[scheduledTriggerId]","Scheduled trigger ID (required, interactive)")).option("--explain",EXPLAIN).action(async(idArg,_opts,cmd)=>{if(explained(cmd,GET_DOC10))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope9(globals),trigger=await resolveTrigger(scope2,idArg),{data,response,error:error51}=await withSpinner("Fetching scheduled trigger",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,scheduledTriggerId:trigger.id}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:triggerDetail}),reportWarnings(data)}),withScope6(st2.command("update").description("Update a scheduled trigger").argument("[scheduledTriggerId]","Scheduled trigger ID (required, interactive)")).option("--cron <expression>",`6-field CRON expression for the specified environment, ${CRON_FIELDS} (optional, interactive)`).option("--disabled","Disable the trigger in the specified environment (optional, interactive, exclusive with --enabled)").option("--enabled","Enable the trigger in the specified environment (optional, interactive, exclusive with --disabled)").option("--script-id <id>","Script the trigger runs, shared by every environment (optional, interactive on HEAD only, refused when it differs from what a non-HEAD environment reports)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC10))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope9(globals),trigger=await resolveTrigger(scope2,idArg),interactive=!opts.input&&canPrompt(),rawBody;if(opts.input)rawBody=readInput(opts.input);else if(interactive){let built=await buildUpdateBody4(scope2,trigger.id,opts);if(!built)return;rawBody=built}else rawBody=stripUndefined({cronExpression:opts.cron===void 0?void 0:assertCron(opts.cron),disabled:disabledFromFlags(opts),scriptId:opts.scriptId}),Object.keys(rawBody).length===0&&failNothingToUpdate(["--cron","--disabled/--enabled","--script-id","--input"]);let body=validate(updateBodySchema10,rawBody);body.cronExpression!==void 0&&(body.cronExpression=assertCron(body.cronExpression));let{data,response,error:error51}=await withSpinner("Updating scheduled trigger",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,scheduledTriggerId:trigger.id}},body}));(!response.ok||!data)&&apiFail(response.status,error51),okMutation("Scheduled trigger updated",data,triggerDetail(data)),reportWarnings(data)}),withScope6(st2.command("delete").description("Delete a scheduled trigger from a workspace").argument("[scheduledTriggerId]","Scheduled trigger ID (required, interactive)"),{destructive:!0,gate:!0}).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC9))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope9(globals,{useSession:canPrompt()}),trigger=await resolveTrigger(scope2,idArg);if(!opts.yes){canPrompt()||failNeedsYes(`scheduled trigger ${trigger.id}`);let current=await withSpinner("Fetching scheduled trigger",()=>scope2.client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,scheduledTriggerId:trigger.id}}}));(!current.response.ok||!current.data)&&apiFail(current.response.status,current.error),prompts().note(["Deleting removes the scheduled trigger from the whole workspace, not just this environment.",`It runs ${scriptCell(current.data.script)} on the schedule "${scheduleOf(current.data)}"; the script itself is left alone.`,"Any release that captured this trigger keeps running its own snapshot of it until that release is replaced."].join(`
1379
+ `)),await prompts().confirm(`Delete scheduled trigger ${trigger.id}? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")}let{response,error:error51}=await withSpinner("Deleting scheduled trigger",()=>scope2.client.DELETE("/v1/workspace/{workspaceId}/environment/{environmentId}/scheduledTrigger/{scheduledTriggerId}",{params:{path:{workspaceId:scope2.workspace,environmentId:scope2.environment,scheduledTriggerId:trigger.id}}}));response.ok||apiFail(response.status,error51),okMutation("Scheduled trigger deleted",{deleted:!0,id:trigger.id})}),st2}var createBodySchema11=external_exports.object({version:external_exports.string().min(1).optional(),label:external_exports.string().min(1).optional(),environmentIds:external_exports.array(external_exports.string().min(1)).min(1).optional()}).strict(),MAX_RELEASE_LABEL=30,RELEASE_LABEL_FORMAT=`free text, up to ${MAX_RELEASE_LABEL} characters`;function assertReleaseLabel(label){let trimmed=label.trim();return trimmed.length>MAX_RELEASE_LABEL&&fail(EXIT.USAGE,"INVALID_RELEASE_LABEL",`A release label can be at most ${MAX_RELEASE_LABEL} characters (that one is ${trimmed.length}).`),trimmed||void 0}var LIST_DOC12=defineCommandDoc("release list",{rules:["The workspace is -w; there is no positional argument."],notes:["Oldest first. Releases cannot be edited or deleted; which release an environment runs is environment target-release."]}),CREATE_DOC10=defineCommandDoc("release create",{schema:createBodySchema11,body:{version:"1.4.0",label:"Sprint 12",environmentIds:["<environmentId>"]},rules:["{} cuts the next minor version and deploys it nowhere.",`version: ${SEMVER_FORMAT}, spelled --release-version as a flag (--version prints the CLI's own version), and it must be greater than the workspace's latest release or the API answers 400 naming both; omitted, the API increments the latest release's minor version, or uses 1.0.0 when there are no releases yet.`,`label: ${RELEASE_LABEL_FORMAT}, shown beside the version.`,"environmentIds: environments to deploy the release into in the same call, at least one when present. Spelled -e/--env as a repeatable flag, which is a deploy target here rather than the scope every other verb reads it as."],notes:["Standing in a local copy of one of the environments deployed into, re-clone it afterwards; a note says so."]});function collect2(value,previous){return[...previous??[],value]}async function fillCreateBody3(client,workspaceId){let version2=await askVersion(`Release version, ${SEMVER_FORMAT} (empty for the next minor version)`,!0),label=await prompts().text("Release label, optional (empty for none)",{allowEmpty:!0}),{ids,labels}=await pickEnvironments(client,workspaceId);return{body:stripUndefined({version:version2,label:label||void 0,environmentIds:ids.length>0?ids:void 0}),labels}}function workspaceReleaseCommand(){let rel=new Command("release").description("Manage workspace releases");return rel.command("list").description("List releases of a workspace").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LIST_DOC12))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["workspace"],{workspace:opts.workspace??globals.workspace,team:opts.team??globals.team},{client,interactive:canPrompt()}),{data,response,error:error51}=await withSpinner("Fetching releases",()=>client.GET("/v1/workspace/{workspaceId}/releases",{params:{path:{workspaceId:resolved.workspace??""}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data)}),rel.command("create").description("Create a workspace release and optionally deploy it").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--release-version <version>",`Release version in Semantic Versioning format, ${SEMVER_FORMAT} (optional, interactive, API default: the next minor version)`).option("--label <text>","Release label (optional, interactive)").option("-e, --env <environmentId>","Environment to deploy the release into; none deploys nowhere (optional, interactive, repeatable)",collect2).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC10))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),interactive=canPrompt(),workspaceId=(await resolveParams(["workspace"],{workspace:opts.workspace??globals.workspace,team:opts.team??globals.team},{client,interactive})).workspace??"",deployTargets=opts.env??[],noFlags=!opts.releaseVersion&&!opts.label&&deployTargets.length===0,deployLabels={},rawBody;opts.input?rawBody=readInput(opts.input):noFlags&&interactive?{body:rawBody,labels:deployLabels}=await fillCreateBody3(client,workspaceId):rawBody=stripUndefined({version:opts.releaseVersion,label:opts.label,environmentIds:deployTargets.length>0?deployTargets:void 0});let body=validate(createBodySchema11,rawBody);if(body.label!==void 0){let label=assertReleaseLabel(body.label);label===void 0?delete body.label:body.label=label}body.version&&(body.version=assertSemver(body.version));let{data,response,error:error51}=await withSpinner("Creating workspace release",()=>client.POST("/v1/workspace/{workspaceId}/release",{params:{path:{workspaceId}},body}));(!response.ok||!data)&&apiFail(response.status,error51);let deployed=(body.environmentIds??[]).map(id=>deployLabels[id]??id);for(let environmentId of body.environmentIds??[])noteRedeployed({workspaceId,environmentId},`release ${data.releaseVersion} was deployed`);okMutation("Workspace release created",data,{...data,...deployed.length>0?{deployedTo:deployed}:{}})}),rel}var VERSION_PARTS=["major","minor","patch"],PART_CHOICES=[{value:"major",label:"Major",hint:"1.4.2 \u2192 2.0.0"},{value:"minor",label:"Minor",hint:"1.4.2 \u2192 1.5.0"},{value:"patch",label:"Patch",hint:"1.4.2 \u2192 1.4.3"}],generateVersionSchema=external_exports.object({incrementMajor:external_exports.boolean().optional(),incrementMinor:external_exports.boolean().optional(),incrementPatch:external_exports.boolean().optional()}).strict().refine(g=>g.incrementMajor===!0||g.incrementMinor===!0||g.incrementPatch===!0,{error:"generateVersion must increment at least one of major, minor or patch."}),createReleaseSchema=external_exports.object({version:external_exports.string().min(1).optional(),generateVersion:generateVersionSchema.optional(),label:external_exports.string().min(1).optional()}).strict().refine(r=>!!r.version!=!!r.generateVersion,{error:"Specify either a release version or a generated one, not both (and not neither).",path:["version"]}),deleteBodySchema=external_exports.object({createRelease:createReleaseSchema.optional(),deployRelease:external_exports.array(external_exports.string().min(1)).min(1).optional()}).strict().refine(b2=>!b2.deployRelease||b2.createRelease,{error:"deployRelease needs a release to deploy \u2014 add createRelease (or drop the environments).",path:["deployRelease"]}),CREATE_DOC11=defineCommandDoc("temp-remote-workspace create",{rules:["The workspace is -w; there is no positional argument and no body."],notes:["Returns the hostname, port, username, private key and expiry. The private key is returned once and never again: store it before discarding the output.","Credentials expire 24 hours after creation. There is no list: the ID comes from this document, and delete takes it as its positional argument.","Two switches gate it and they fail differently. The team's is features.remoteWorkspace on team get; false there answers 403 with a hint naming the field.","The workspace's own is remoteWorkspaceEnabled on workspace get; false there answers exit 1 BAD_REQUEST, 'SFTP server is not enabled for the workspace', and no route in this API turns it on \u2014 only the web application does. Check both before planning around either."]}),DELETE_DOC10=defineCommandDoc("temp-remote-workspace delete",{schema:deleteBodySchema,body:{createRelease:{version:"1.4.0",generateVersion:{incrementMajor:!1,incrementMinor:!0,incrementPatch:!1},label:"Sprint 12"},deployRelease:["<environmentId>"]},rules:["An empty body {} deletes the temporary access and discards its unreleased work.",`createRelease cuts a release from that work first: exactly one of version (${SEMVER_FORMAT}, and greater than the workspace's latest release) or generateVersion, an object with at least one of incrementMajor, incrementMinor or incrementPatch true, applied to the latest release; label is optional, ${RELEASE_LABEL_FORMAT}. The block has no flag of its own: version is --release-version, generateVersion is --increment <major|minor|patch> repeated, and label is --label.`,"deployRelease: environment IDs to deploy the new release into, spelled -e/--env as a repeatable flag; requires createRelease.","The temporary access ID is the positional argument and the workspace is -w; the deletion cannot be undone, and --yes is a flag rather than a key."]});function collect3(value,previous){return[...previous??[],value]}function generateVersionFrom(parts){if(parts.length===0)return;let unknown2=parts.filter(p=>!VERSION_PARTS.includes(p));return unknown2.length>0&&fail(EXIT.USAGE,"USAGE_ERROR",`--increment takes ${VERSION_PARTS.join(", ")} \u2014 got ${unknown2.join(", ")}.`),stripUndefined({incrementMajor:parts.includes("major")||void 0,incrementMinor:parts.includes("minor")||void 0,incrementPatch:parts.includes("patch")||void 0})}async function confirmRelease(){return await prompts().confirm("Create a release from the temporary remote workspace?",!0)?!0:(prompts().note("\u26A0 Without a release, every change made in the temporary remote workspace is discarded when it is deleted. This cannot be undone."),!await prompts().confirm("Delete it anyway and discard those changes?",!1))}async function askReleaseVersion(){if(await prompts().select("Release version:",[{value:"auto",label:"Increment the latest version automatically"},{value:"specify",label:"Specify the version"}])==="specify")return{version:await askVersion(`Release version (${SEMVER_FORMAT})`)};for(;;){let parts=await prompts().multiselect("Which version numbers to increment? (space to pick)",PART_CHOICES),generateVersion=generateVersionFrom(parts);if(generateVersion)return{generateVersion};prompts().note("\u2716 Pick at least one version number to increment.")}}async function fillDeleteBody(client,workspaceId){if(!await confirmRelease())return{body:{},labels:{}};let{version:version2,generateVersion}=await askReleaseVersion(),label=await prompts().text("Release label, optional (empty for none)",{allowEmpty:!0}),deployRelease,labels={};if(await prompts().confirm("Deploy the new release into any environments?",!1)){let picked=await pickEnvironments(client,workspaceId);deployRelease=picked.ids.length>0?picked.ids:void 0,labels=picked.labels}return{body:stripUndefined({createRelease:stripUndefined({version:version2,generateVersion,label:label||void 0}),deployRelease}),labels}}function describeRelease(body,labels){if(!body.createRelease)return"no release created";let{version:version2,generateVersion,label}=body.createRelease,versioning=version2?`version ${version2}`:`incrementing ${VERSION_PARTS.filter(p=>generateVersion?.[`increment${p[0]?.toUpperCase()}${p.slice(1)}`]).join(" + ")}`,deployed=(body.deployRelease??[]).map(id=>labels[id]??id);return[`release created (${versioning}${label?`, label "${label}"`:""})`,deployed.length>0?`deployed into ${deployed.join(", ")}`:"not deployed"].join(", ")}function tempRemoteWorkspaceCommand(){let trw=new Command("temp-remote-workspace").alias("trw").description("Manage temporary remote workspace (SFTP) access");return trw.command("create").description("Open a temporary remote workspace and retrieve its SFTP credentials").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC11))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),workspaceId=(await resolveParams(["workspace"],{workspace:opts.workspace??globals.workspace,team:opts.team??globals.team},{client,interactive:canPrompt()})).workspace??"",{data,response,error:error51}=await withSpinner("Creating temporary remote workspace",()=>client.POST("/v1/workspace/{workspaceId}/sftp/temp",{params:{path:{workspaceId}}}));(!response.ok||!data)&&accessFail(response.status,error51,workspaceId),okMutation("Temporary remote workspace created",data,data)}),trw.command("delete").description("Dispose a temporary remote workspace, optionally releasing and deploying its work").argument("[tempSftpAccessId]","Temporary access ID; there is no endpoint listing these, so it is typed rather than picked (required, interactive)").option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE_DESTRUCTIVE).option("--team <teamId>",SCOPE_TEAM_FILTER_DESTRUCTIVE).option("--release-version <version>",`Create a release with this version, in Semantic Versioning format ${SEMVER_FORMAT} (optional, interactive, exclusive with --increment)`).option("--increment <part>","Create a release incrementing this part of the latest version: major, minor or patch (optional, interactive, repeatable, exclusive with --release-version)",collect3).option("--label <text>","Label for the created release (optional, interactive)").option("-e, --env <environmentId>","Environment to deploy the created release into (optional, interactive, repeatable, requires a created release)",collect3).option("--yes",CONFIRM_YES).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC10))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),interactive=canPrompt(),workspaceId=(await resolveParams(["workspace"],{workspace:opts.workspace??globals.workspace,team:opts.team??globals.team},{client,interactive,useSession:interactive})).workspace??"",tempSftpAccessId=idArg===void 0?void 0:assertResourceId(idArg,"tempSftpAccessId");tempSftpAccessId||(interactive||fail(EXIT.USAGE,"USAGE_ERROR",`<tempSftpAccessId> is required. ${supplyHint({ask:"type it"})}`),tempSftpAccessId=assertResourceId(await prompts().text("Temporary access ID"),"tempSftpAccessId"));let increment=opts.increment??[],deployTargets=opts.env??[],releaseFlags=!!opts.releaseVersion||increment.length>0||!!opts.label,deployLabels={},rawBody;opts.input?rawBody=readInput(opts.input):!releaseFlags&&deployTargets.length===0&&interactive?{body:rawBody,labels:deployLabels}=await fillDeleteBody(client,workspaceId):rawBody=stripUndefined({createRelease:releaseFlags?stripUndefined({version:opts.releaseVersion,generateVersion:generateVersionFrom(increment),label:opts.label}):void 0,deployRelease:deployTargets.length>0?deployTargets:void 0});let body=validate(deleteBodySchema,rawBody);if(body.createRelease?.label!==void 0){let label=assertReleaseLabel(body.createRelease.label);label===void 0?delete body.createRelease.label:body.createRelease.label=label}body.createRelease?.version&&(body.createRelease.version=assertSemver(body.createRelease.version)),opts.yes||(interactive||fail(EXIT.USAGE,"CONFIRMATION_REQUIRED","Deleting a temporary remote workspace is irreversible. Re-run with --yes to confirm."),await prompts().confirm(`Delete temporary remote workspace ${tempSftpAccessId}? (${describeRelease(body,deployLabels)})`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled."));let{response,error:error51}=await withSpinner("Deleting temporary remote workspace",()=>client.DELETE("/v1/workspace/{workspaceId}/sftp/temp/{tempSftpAccessId}",{params:{path:{workspaceId,tempSftpAccessId}},body}));response.ok||failDeletion(response.status,error51,tempSftpAccessId),okMutation("Temporary remote workspace deleted",{deleted:!0,id:tempSftpAccessId})}),trw}function accessFail(status,body,workspaceId){let message=body?.errorMessage??`Request failed with HTTP status ${status}.`;if(status===403&&(/does not own/i.test(message)&&fail(EXIT.API_ERROR,"FORBIDDEN",message,{status,hint:"Only the user who created a set of temporary credentials can delete them, and no route in this API lists them \u2014 the ID has to be one this account created."}),fail(EXIT.API_ERROR,"FORBIDDEN",message,{status,hint:`Whether you may use them in this team is features.remoteWorkspace on \`${CLI} team get <teamId>\`.`})),status===400&&/sftp server is not enabled for the workspace/i.test(message)){let read=workspaceId===void 0?"":` \`${CLI} workspace get ${workspaceId} --team <teamId>\` reports it.`;fail(EXIT.API_ERROR,"BAD_REQUEST",message,{status,hint:`The workspace's own remote file system switch is off (\`remoteWorkspaceEnabled\`), and no route in this API turns it on \u2014 enable it in the web application.${read}`})}apiFail(status,body)}function failDeletion(status,error51,tempSftpAccessId){let message=error51?.errorMessage;status>=500&&fail(EXIT.API_ERROR,"SFTP_ACCESS_NOT_REMOVED",message??"The temporary remote workspace was not removed.",{status,hint:`The credentials may still be active. Run \`${CLI} temp-remote-workspace delete ${tempSftpAccessId} -w <workspaceId>\` again, and contact support if it keeps failing.`}),status===404&&fail(EXIT.NOT_FOUND,"NOT_FOUND",message??"SFTP credentials not found.",{status,hint:"No credentials with that ID exist on the selected workspace \u2014 either they were revoked earlier, or the ID belongs to another workspace. Check both the ID and -w before treating this as proof that the credentials are inactive: this route looks only inside the workspace it was given."}),accessFail(status,error51)}var README_KIND={noun:"README",tooLargeCode:"README_TOO_LARGE",language:"markdown"},updateBodySchema11=external_exports.object({content:external_exports.string()}).strict(),GET_DOC11=defineCommandDoc("readme get",{rules:["The workspace is -w and the environment -e; there is no positional argument, a workspace having one README.","--content-only prints the markdown alone: rendered for the terminal in human mode, the stored source verbatim under --raw, so `readme get --content-only --raw > README.md` reproduces the file byte for byte."],notes:["Without --content-only, the stored document with its name and last-modified time.","A non-HEAD environment answers the README its release captured and reports no lastModified for it. What it shows is what update there will accept back.","A release cut while the README was empty captured nothing, and that environment then answers exit 4 for both get and update: read and edit it through a HEAD environment instead."]}),UPDATE_DOC11=defineCommandDoc("readme update",{schema:updateBodySchema11,body:{content:`# Order sync
1380
+
1381
+ What this workspace does, and how to run it.
1382
+ `},rules:[`content: the whole README as markdown, spelled --content or --file <path> as a flag, up to ${MAX_CONTENT_BYTES/1024/1024} MiB; "" empties it.`,"The workspace is -w and the environment -e; neither is a body key. One README per workspace, shared by every environment, so the environment in the path decides only which README a read sees and whether the write is allowed.","In a non-HEAD environment content is read-only rather than refused: that environment reports the README its release captured (with no lastModified), takes exactly that value back, and answers 400 for a differing one. Echo what its own get reports, or edit through an environment with no release deployed into it (HEAD)."],notes:["The echo that works: `readme get -e <released> --content-only --raw > README.md` and that file straight back is accepted, a differing one being exit 1 naming content as read-only."]});function withScope7(cmd){return cmd.option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("-e, --env <environmentId>",SCOPE_ENVIRONMENT).option("--team <teamId>",SCOPE_TEAM_FILTER)}async function resolveScope10(globals){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace","environment"],{team:globals.team,workspace:globals.workspace,environment:globals.env},{client,interactive:canPrompt()});return{client,workspace:resolved.workspace??"",environment:resolved.environment??""}}function readmeFail(status,error51){if(status===404){let body=error51,message=body?.errorMessage??body?.message??"README not found.";/readme/i.test(message)||apiFail(status,error51),fail(EXIT.NOT_FOUND,"NOT_FOUND",message,{status,hint:"A released environment shows only the README its release captured \u2014 one written after the release was cut, and one that was empty when it was cut, are both readable through a HEAD (non-deployed) environment instead."})}apiFail(status,error51)}async function fetchReadme(client,path2){let{data,response,error:error51}=await withSpinner("Fetching README",()=>client.GET("/v1/workspace/{workspaceId}/environment/{environmentId}/readme",{params:{path:path2}}));return(!response.ok||!data)&&readmeFail(response.status,error51),data}function renderReadme(readme){let detail={name:readme.name};return readme.lastModified!==void 0&&(detail.lastModified=readme.lastModified),`${renderDetail(detail)}
1383
+ CONTENT
1384
+ ${readme.content}`}function sizeCell(content){if(content==="")return"empty";let bytes=Buffer.byteLength(content,"utf8"),size=bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`,lines=content.replace(/\n$/,"").split(`
1385
+ `).length;return`${size} (${lines} line${lines===1?"":"s"})`}async function askReadmeContent(client,path2){let release2=await withSpinner("Checking the environment",()=>environmentRelease(client,path2.workspaceId,path2.environmentId));release2&&fail(EXIT.USAGE,"RELEASED_ENVIRONMENT",`This environment runs ${release2.version?`release ${release2.version}`:"a release"} \u2014 the README is shared by every environment and can only be replaced through a HEAD (non-deployed) environment.`);let fetched,current=()=>fetched??=fetchReadme(client,path2),editSource;return{content:(await askContentSource({kind:README_KIND,message:"How do you want to provide the README?",pathMessage:"Path to the markdown file",inlineLabel:"Edit it here",extensions:[".md",".markdown"],placeholder:"# My workspace",currentContent:async()=>{let server=(await current()).content;return editSource=await localEditSource(client,{workspaceId:path2.workspaceId,environmentId:path2.environmentId},{kind:"readme"},server),editSource.content},emptyConfirm:"Save an empty README? This clears the stored one."})).content??"",...editSource?{mode:editSource.mode}:{}}}function workspaceReadmeCommand(){let readme=new Command("readme").description("Manage workspace READMEs");return withScope7(readme.command("get").description("Get the workspace's README")).option("--content-only","Print just the markdown, rendered for the terminal; with --raw, the stored source verbatim (optional)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,GET_DOC11))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope10(globals),stored=await fetchReadme(scope2.client,{workspaceId:scope2.workspace,environmentId:scope2.environment});if(opts.contentOnly){isRaw()?okFile(stored.content):okText(renderMarkdown(stored.content));return}ok(stored,{human:renderReadme})}),withScope7(readme.command("update").description("Update the workspace's README")).option("--file <path>","Read the new README from a file, or - for stdin (optional, interactive, exclusive with --content)").option("--content <markdown>",'New README markdown inline; "" empties the README (optional, interactive, exclusive with --file)').option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,UPDATE_DOC11))return;let globals=cmd.optsWithGlobals(),interactive=canPrompt();opts.file!==void 0&&opts.content!==void 0&&fail(EXIT.USAGE,"USAGE_ERROR","--file and --content cannot be combined.");let scope2=await resolveScope10(globals),path2={workspaceId:scope2.workspace,environmentId:scope2.environment},rawBody,editMode;if(opts.input)rawBody=readInput(opts.input);else{let content=opts.content;content===void 0&&opts.file!==void 0&&(content=readContentFile(opts.file,README_KIND)),content===void 0&&interactive&&({content,mode:editMode}=await askReadmeContent(scope2.client,path2)),content===void 0&&failNothingToUpdate(["--file","--content","--input"]),rawBody={content}}let body=validate(updateBodySchema11,rawBody);assertSize(Buffer.byteLength(body.content,"utf8"),README_KIND);let{data,response,error:error51}=await withSpinner("Updating README",()=>scope2.client.PUT("/v1/workspace/{workspaceId}/environment/{environmentId}/readme",{params:{path:path2},body}));(!response.ok||!data)&&apiFail(response.status,error51),syncReadme({workspaceId:path2.workspaceId,environmentId:path2.environmentId},data.content,editMode),okMutation("README updated",data,{name:data.name,size:sizeCell(data.content)})}),readme}var LANGUAGES=["js","ts","ts-strict"],VISIBILITIES=["public","private"],LANGUAGE_CHOICES=[{value:"ts",label:"TypeScript"},{value:"ts-strict",label:"TypeScript (strict)"},{value:"js",label:"JavaScript"}],VISIBILITY_CHOICES=[{value:"private",label:"Private \u2014 admins of the team and you"},{value:"public",label:"Public \u2014 all members of the team"}],VISIBILITY_MEANING={public:"every member of the team",private:"the team's admins and you"},VISIBILITY_MEANINGS=VISIBILITIES.map(v2=>`${v2} (${VISIBILITY_MEANING[v2]})`).join(" or "),MAX_WORKSPACE_NAME=200,WORKSPACE_NAME_CHARSET=/^[A-Za-z0-9 .-]+$/,WORKSPACE_NAME_FORMAT=`letters, digits, spaces, hyphens and periods, up to ${MAX_WORKSPACE_NAME} characters, and unique within the team`,MAX_WORKSPACE_DESCRIPTION=1e3;function assertWorkspaceName(name){let trimmed=name.trim();return trimmed||fail(EXIT.USAGE,"INVALID_WORKSPACE_NAME","A workspace name is required."),trimmed.length>MAX_WORKSPACE_NAME&&fail(EXIT.USAGE,"INVALID_WORKSPACE_NAME",`A workspace name can be at most ${MAX_WORKSPACE_NAME} characters (that one is ${trimmed.length}).`),WORKSPACE_NAME_CHARSET.test(trimmed)||fail(EXIT.USAGE,"INVALID_WORKSPACE_NAME",`Use letters, digits, spaces, hyphens and periods \u2014 '${name}' has a character the API refuses. No underscores or slashes, unlike a script name.`),trimmed}function assertWorkspaceDescription(description){return description.length>MAX_WORKSPACE_DESCRIPTION&&fail(EXIT.USAGE,"INVALID_WORKSPACE_DESCRIPTION",`A workspace description can be at most ${MAX_WORKSPACE_DESCRIPTION} characters (that one is ${description.length}).`),description}function assertWorkspaceBody(body){return body.name!==void 0&&(body.name=assertWorkspaceName(body.name)),body.description!==void 0&&assertWorkspaceDescription(body.description),body}var createBodySchema12=external_exports.object({name:external_exports.string(),description:external_exports.string().optional(),sourceWorkspaceId:external_exports.string().optional(),sourceTemplateId:external_exports.string().optional(),language:external_exports.enum(LANGUAGES).optional(),visibility:external_exports.enum(VISIBILITIES).optional()}).strict().refine(body=>!(body.sourceWorkspaceId&&body.sourceTemplateId),{message:"sourceWorkspaceId and sourceTemplateId cannot both be set.",path:["sourceTemplateId"]}),updateBodySchema12=external_exports.object({name:external_exports.string(),description:external_exports.string().optional(),language:external_exports.enum(LANGUAGES).optional(),visibility:external_exports.enum(VISIBILITIES).optional()}).strict(),MISSING_WORKSPACE={workspace:`<workspaceId> is required. ${supplyHint({env:"SR_CONNECT_CLI_WORKSPACE"})}`},BLAME_WORKSPACE={workspace:"<workspaceId>"},CONFIRM_MOVE_YES="Confirm moving the workspace when --team names another team, the one change here that clears connector attachments and remote file system access (optional on a TTY, required for a move otherwise, ignored when no move is involved)";function teamLabel(moving){return moving.teamName?`${moving.teamName} (${moving.teamId})`:moving.teamId}async function confirmMove(moving,teamId,yes){let from=teamLabel(moving);noteLine(`\u2139 Workspace "${moving.workspace.name}" is in team ${from}. This update moves it to ${teamId}.`),warnLine(`\u26A0 Moving clears every connector attachment in every environment \u2014 each event listener
1386
+ and API connection has to be pointed at a connector in the new team.
1387
+ Remote file system access is turned off with it, and any temporary credentials stop working.`),!yes&&(canPrompt()||fail(EXIT.USAGE,"CONFIRMATION_REQUIRED",`Moving workspace "${moving.workspace.name}" from team ${from} to ${teamId} clears every connector attachment in every environment and turns remote file system access off, and moving it back undoes neither. Re-run with --yes to confirm.`,{hint:`Pass --team ${moving.teamId} to update it where it is instead.`}),await prompts().confirm("Move it to that team?",!1)||fail(EXIT.CANCELLED,"CANCELLED","Cancelled."))}var LIST_DOC13=defineCommandDoc("workspace list",{rules:["The team is --team; the workspace is this group's resource, so there is no -w here and no positional argument."],notes:["Every workspace of the team, yours and the public ones you are not a member of alike."]}),GET_DOC12=defineCommandDoc("workspace get",{rules:["The workspace is the positional argument and there is no -w here, the workspace being what this verb reads rather than where it looks. --team is optional: every workspace read is keyed by team, and a team that was not given is found by searching the ones you are a member of, which is one request per team until the workspace turns up."],notes:["Reports the language, which is worth reading after creating from a template or another workspace: either brings its own, and ts-strict is the one to prefer.","Also reports remoteWorkspaceEnabled, which a move between teams turns off."]}),DELETE_DOC11=defineCommandDoc("workspace delete",{rules:["The workspace is the positional argument and the team is --team.","--yes skips the confirmation, and is required without a terminal."],notes:["Deletes the workspace with its environments, scripts, API connections, event listeners, scheduled triggers and releases; anything running from a release stops.","The lock this shell holds is presented and never stands in the way. Another holder is exit 1 WORKSPACE_LOCKED naming them, with workspace-lock check and workspace-lock take --force in the hint.","Dropped from this shell's session defaults afterwards, along with the environment the record named."]}),CREATE_DOC12=defineCommandDoc("workspace create",{schema:createBodySchema12,body:{name:"Order sync",description:"Keeps Jira and the order system in step.",sourceWorkspaceId:"<workspaceId>",sourceTemplateId:"<templateId>",language:"ts-strict",visibility:"private"},rules:[`name: ${WORKSPACE_NAME_FORMAT}.`,`description: free text, up to ${MAX_WORKSPACE_DESCRIPTION} characters.`,`sourceWorkspaceId (--source-workspace-id as a flag) copies another workspace; sourceTemplateId (--source-template-id) creates from a published template, as listed by ${CLI} template list; at most one of the two. Either brings its own language, and language is then ignored: read the language back with ${CLI} workspace get and upgrade it with update. A copy has one environment, the default one, holding the source's default environment's parameters with each default value as the value; parameter values, other environments and releases are not copied.`,`language: ${LANGUAGES.join(", ")}; API default ts; ts-strict is the one to prefer.`,`visibility: ${VISIBILITY_MEANINGS}; API default private. Creating a public one needs you to be an admin of the team, and a member who is not gets exit 1 "User is not in any of the required roles: ADMIN,SUPER_ADMIN"; seeing one needs nothing, which is what public means.`,"The team is --team, never a body key."]}),UPDATE_DOC12=defineCommandDoc("workspace update",{schema:updateBodySchema12,body:{name:"Order sync",description:"Keeps Jira and the order system in step.",language:"ts-strict",visibility:"private"},rules:[`name is required even when it does not change: send the current one back. ${WORKSPACE_NAME_FORMAT}.`,`description is cleared when the body omits it, so send the current one back to keep it; "" clears it too. Up to ${MAX_WORKSPACE_DESCRIPTION} characters. The flags path reads the workspace and carries it forward, so only a body given here has to.`,`language: ${LANGUAGES.join(", ")}; omitted, the current one is kept.`,`visibility: ${VISIBILITIES.join(" or ")}; omitted, the current one is kept, except when --team moves the workspace to another team, where a body that does not name one makes it private. Changing it needs you to be an admin of the team.`,"The sources a workspace was created from cannot change. --team names the workspace's team, or a new team to move it to; it is not a body key.","A --team that names another team moves the workspace, which clears every connector attachment in every environment and turns remote file system access off \u2014 neither undone by moving it back. So it takes --yes without a terminal (exit 2 CONFIRMATION_REQUIRED otherwise) and a confirmation with one, and only a typed flag can move at all: a team from an environment variable, a clone or the session record is exit 2 TEAM_MISMATCH. An --input body is held to both, the team being resolved outside it."],notes:["--yes is for the move alone: an ordinary update never needs it, and passing it to one is accepted and ignored.","The workspace is found by looking through your teams for the one holding it, which is named on stderr. Only a move pays for that search \u2014 an ordinary update reads the workspace once. An ID in none of your teams is exit 4.","A workspace published as a template stays one: the template flag is not part of this request, and editing such a workspace needs permission to author templates, which the API answers 403 for when you do not have it."]});function assertOneSource2(opts){opts.sourceWorkspaceId&&opts.sourceTemplateId&&fail(EXIT.USAGE,"USAGE_ERROR","--source-workspace-id and --source-template-id cannot be combined.")}async function fillCreateBody4(client,teamId,opts){let sourceWorkspaceId=opts.sourceWorkspaceId;!sourceWorkspaceId&&!opts.sourceTemplateId&&await prompts().confirm("Clone from an existing workspace?",!1)&&(sourceWorkspaceId=(await resolveParams(["workspace"],{team:teamId},{client,interactive:!0})).workspace);let name=opts.name??await prompts().text("Workspace name"),description=opts.description;description===void 0&&(description=await prompts().text("Workspace description, optional (empty for none)",{allowEmpty:!0})||void 0);let language=opts.language??(sourceWorkspaceId||opts.sourceTemplateId?void 0:await prompts().select("Scripting language",LANGUAGE_CHOICES)),visibility=opts.visibility??await prompts().select("Visibility",VISIBILITY_CHOICES);return stripUndefined({name,description,sourceWorkspaceId,sourceTemplateId:opts.sourceTemplateId,language,visibility})}async function locateWorkspace(client,teamId,workspaceId){let direct=teamId===void 0?void 0:await withSpinner("Fetching workspace",()=>client.GET("/v1/team/{teamId}/workspace/{workspaceId}",{params:{path:{teamId,workspaceId}}}));return direct?.response.ok&&direct.data?{workspace:direct.data,teamId:teamId??""}:(direct&&direct.response.status!==404&&apiFail(direct.response.status,direct.error),withSpinner("Looking for the workspace in your other teams",async()=>{let teams=await client.GET("/v1/teams");(!teams.response.ok||!teams.data)&&apiFail(teams.response.status,teams.error);for(let team of teams.data.teams){if(!team.id||team.id===teamId)continue;let list=await client.GET("/v1/team/{teamId}/workspaces",{params:{path:{teamId:team.id}}});(!list.response.ok||!list.data)&&apiFail(list.response.status,list.error);let found2=list.data.workspaces.find(w=>w.id===workspaceId);if(found2)return{workspace:found2,teamId:team.id,...team.name?{teamName:team.name}:{}}}}))}async function fetchWorkspace(client,teamId,workspaceId){let{data,response,error:error51}=await withSpinner("Fetching workspace",()=>client.GET("/v1/team/{teamId}/workspace/{workspaceId}",{params:{path:{teamId,workspaceId}}}));return(!response.ok||!data)&&apiFail(response.status,error51),data}async function fillUpdateBody2(current,moving){let name=await prompts().text("Workspace name",{initial:current.name}),description=current.description,currently=current.description?`(currently "${current.description}")`:"(currently unset)";await prompts().confirm(`Change the description? ${currently}`,!1)&&(description=await prompts().text("Description",{allowEmpty:!0}));let language;await prompts().confirm("Change the scripting language?",!1)&&(language=await prompts().select("Scripting language",LANGUAGE_CHOICES));let visibility;return moving?visibility=await prompts().select("Visibility",VISIBILITY_CHOICES,{initial:current.visibility}):await prompts().confirm("Change the visibility?",!1)&&(visibility=await prompts().select("Visibility",VISIBILITY_CHOICES)),{name,...description===void 0?{}:{description},...language===void 0?{}:{language},...visibility===void 0?{}:{visibility}}}async function confirmDeletion4(client,teamId,workspaceId){let current=await fetchWorkspace(client,teamId,workspaceId);prompts().note(["Deleting removes the workspace from the whole team, and everything in it goes with it:","environments, scripts, API connections, event listeners, scheduled triggers \u2014 and releases,","so anything still running from one stops immediately.",`It disappears from ${CLI} workspace list, and every later request naming it is a 404.`].join(`
1388
+ `)),await prompts().confirm(`Delete workspace "${current.name}" (${workspaceId})? This is irreversible.`)||fail(EXIT.CANCELLED,"CANCELLED","Deletion cancelled.")}async function failDeletion2(client,status,error51,workspaceId){if(status===409){let holder=error51?.lockedBy;lockedFail(holder,workspaceId,`See who holds it with \`${CLI} workspace-lock check -w ${workspaceId}\`, then take it with \`${CLI} workspace-lock take -w ${workspaceId} --force\` and delete again.`,await currentUser(client))}apiFail(status,error51)}function workspaceCommand(){let ws=new Command("workspace").description("Manage workspaces");return ws.command("list").description("List workspaces").option("--team <teamId>",SCOPE_TEAM).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,LIST_DOC13))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["team"],{team:opts.team},{client,interactive:canPrompt()}),{data,response,error:error51}=await withSpinner("Fetching workspaces",()=>client.GET("/v1/team/{teamId}/workspaces",{params:{path:{teamId:resolved.team??""}}}));(!response.ok||!data)&&apiFail(response.status,error51),ok(data,{human:d=>({workspaces:tableRows(["id","name","description","language","remoteWorkspaceEnabled","visibility","incomingApps","outgoingApps","createdFromTemplate"],d.workspaces.map(w=>({...w,incomingApps:w.incomingApps.join(", "),outgoingApps:w.outgoingApps.join(", ")})))})})}),ws.command("create").description("Create a workspace, optionally from another workspace or a published template").option("--team <teamId>",SCOPE_TEAM).option("--name <name>","Workspace name (required unless --input, interactive)").option("--description <text>","Workspace description (optional, interactive)").option("--source-workspace-id <id>","Clone from the specified workspace, whose language is used (optional, interactive, exclusive with --source-template-id)").option("--source-template-id <id>",`Create from the specified published template, whose language is used, as listed by ${CLI} template list (optional, exclusive with --source-workspace-id)`).option("--language <lang>","Scripting language: js, ts, or ts-strict (optional, interactive, API default: ts, ignored with --source-workspace-id or --source-template-id)").option("--visibility <mode>","Sharing mode: public or private (optional, interactive, API default: private)").option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CREATE_DOC12))return;let globals=cmd.optsWithGlobals();assertOneSource2(opts);let client=await apiClient(globals.instance),teamId=(await resolveParams(["team"],{team:opts.team??globals.team},{client,interactive:canPrompt()})).team??"",rawBody=opts.input?readInput(opts.input):!opts.name&&canPrompt()?await fillCreateBody4(client,teamId,opts):stripUndefined({name:opts.name,description:opts.description,sourceWorkspaceId:opts.sourceWorkspaceId,sourceTemplateId:opts.sourceTemplateId,language:assertChoice("--language",opts.language,LANGUAGES),visibility:assertChoice("--visibility",opts.visibility,VISIBILITIES)}),body=assertWorkspaceBody(validate(createBodySchema12,rawBody)),{data,response,error:error51}=await withSpinner("Creating workspace",()=>client.POST("/v1/team/{teamId}/workspace",{params:{path:{teamId}},body}));(!response.ok||!data)&&apiFail(response.status,error51),okMutation("Workspace created",data,data)}),ws.command("get").description("Get a single workspace").argument("[workspaceId]",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_SEARCHED).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,GET_DOC12))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["workspace"],{team:opts.team??globals.team,workspace:idArg??globals.workspace},{client,interactive:canPrompt(),missing:MISSING_WORKSPACE,...idArg===void 0?{}:{blame:BLAME_WORKSPACE}}),workspaceId=resolved.workspace??"",teamId=resolved.team,located=teamId===void 0?await locateWorkspace(client,void 0,workspaceId):void 0;teamId===void 0&&!located&&fail(EXIT.NOT_FOUND,"NOT_FOUND",`No workspace ${workspaceId} in any of your teams.`,{status:404});let data=located?located.workspace:await fetchWorkspace(client,teamId??"",workspaceId);ok(data,{human:d=>({...d,incomingApps:d.incomingApps.join(", "),outgoingApps:d.outgoingApps.join(", ")})})}),ws.command("update").description("Update a workspace").argument("[workspaceId]","Workspace ID (required, interactive, session default, env SR_CONNECT_CLI_WORKSPACE)").option("--team <teamId>","Team ID \u2014 the workspace's team, or a new team to move it to; only the flag itself can move, a session default or environment variable never does (required, interactive, session default, env SR_CONNECT_CLI_TEAM)").option("--name <name>","New workspace name (optional, interactive, default: the current name)").option("--description <text>",'New workspace description; "" clears it (optional, interactive, default: the current description)').option("--language <lang>","Scripting language: js, ts, or ts-strict (optional, interactive, default: the current language)").option("--visibility <mode>","Sharing mode: public or private; a move to another team makes the workspace private unless this says otherwise (optional, interactive, default: the current mode)").option("--yes",CONFIRM_MOVE_YES).option("--input <file>",INPUT_BODY).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,UPDATE_DOC12))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["team","workspace"],{team:opts.team??globals.team,workspace:idArg??globals.workspace},{client,interactive:canPrompt(),missing:MISSING_WORKSPACE,...idArg===void 0?{}:{blame:BLAME_WORKSPACE}}),teamId=resolved.team??"",workspaceId=resolved.workspace??"",{name,description,language,visibility}=opts,interactive=[name,description,language,visibility].every(v2=>v2===void 0)&&opts.input===void 0&&canPrompt(),located=await locateWorkspace(client,teamId,workspaceId);located||fail(EXIT.NOT_FOUND,"NOT_FOUND",`Workspace '${workspaceId}' is not in team '${teamId}', or in any other team you are a member of.`,{status:404});let current=located.workspace,moving=located.teamId!==teamId?located:void 0;moving&&(opts.team===void 0&&fail(EXIT.USAGE,"TEAM_MISMATCH",`Workspace "${moving.workspace.name}" is in team ${teamLabel(moving)}, but this run took --team ${teamId} from a default rather than the flag, and only the flag can move a workspace.`,{hint:`Pass --team ${moving.teamId} to update it where it is, or --team ${teamId} to move it there.`}),await confirmMove(moving,teamId,opts.yes===!0));let body;if(opts.input)body=assertWorkspaceBody(validate(updateBodySchema12,readInput(opts.input)));else{if(interactive){let walked=await fillUpdateBody2(current,!!moving);name=walked.name,description=walked.description,language=walked.language,visibility=walked.visibility}else!moving&&!name&&description===void 0&&!language&&!visibility&&failNothingToUpdate(["--name","--description","--language","--visibility","--input"]),name||(name=current.name),description??=current.description;body=assertWorkspaceBody(validate(updateBodySchema12,stripUndefined({name,description,language,visibility})))}moving&&current.visibility==="public"&&body.visibility===void 0&&warnLine(`\u26A0 Moving a workspace makes it private unless the update names a visibility.
1389
+ Pass --visibility public to keep it public.`);let{response,error:error51}=await withSpinner("Updating workspace",()=>client.PUT("/v1/team/{teamId}/workspace/{workspaceId}",{params:{path:{teamId,workspaceId}},body}));response.ok||apiFail(response.status,error51);let sent=body;await syncWorkspaceSettings(workspaceId,{...sent.name===void 0?{}:{name:sent.name},...sent.language===void 0?{}:{language:sent.language}}),okMutation("Workspace updated",{updated:!0,id:workspaceId})}),ws.command("delete").description("Delete a workspace").argument("[workspaceId]",SCOPE_WORKSPACE_DESTRUCTIVE).option("--team <teamId>",SCOPE_TEAM_DESTRUCTIVE).option("--yes",CONFIRM_YES).option("--explain",EXPLAIN).action(async(idArg,opts,cmd)=>{if(explained(cmd,DELETE_DOC11))return;let globals=cmd.optsWithGlobals(),client=await apiClient(globals.instance),resolved=await resolveParams(["team","workspace"],{team:opts.team??globals.team,workspace:idArg??globals.workspace},{client,interactive:canPrompt(),useSession:canPrompt(),missing:MISSING_WORKSPACE,...idArg===void 0?{}:{blame:BLAME_WORKSPACE}}),teamId=resolved.team??"",workspaceId=resolved.workspace??"";opts.yes||(canPrompt()||failNeedsYes(`workspace ${workspaceId}`),await confirmDeletion4(client,teamId,workspaceId));let{response,error:error51}=await withSpinner("Deleting workspace",()=>client.DELETE("/v1/team/{teamId}/workspace/{workspaceId}",{params:{path:{teamId,workspaceId}}}));response.ok||await failDeletion2(client,response.status,error51,workspaceId),forgetWorkspaceLock(workspaceId);let removed=forgetScopeValue("workspace",workspaceId,["environment"]);if(removed.length>0){let what=removed.includes("environment")?"workspace and its environment":"workspace";prompts().note(`Removed the deleted ${what} from this shell's session defaults (${CLI} cli set-session to store another).`)}okMutation("Workspace deleted",{deleted:!0,id:workspaceId})}),ws}var CHECK_DOC=defineCommandDoc("workspace-lock check",{rules:["The workspace is -w and there is no positional argument: a workspace holds at most one lock, so there is nothing to name."],notes:["Reports who holds the lock, how they took it, and when the lease lapses. A held lock is exit 0 \u2014 the read succeeded \u2014 and leads with a neutral `\u2139 Workspace lock is taken.` above the rows.","Nobody holding it is exit 4 NO_WORKSPACE_LOCK, printed green with a \u2714: for a script polling for a free workspace that is the good answer, and the code is what to branch on."]}),TAKE_DOC=defineCommandDoc("workspace-lock take",{rules:["--force takes the lock even though another session holds it, which makes a browser tab lose edit control at once. Never pass it on your own when the holder is somebody else: stop and ask. A refusal naming you as the holder is the exception, and its hint says so.","--lock-id names the ID to take or renew rather than generating one, and it is the one place an explicit ID is stored for the rest of the shell session; every other command presents it and stores nothing."],notes:["Takes the lock and keeps it for the rest of the shell session, so the writes that follow renew it rather than taking their own. Re-running renews rather than replaces.","The document adds lockId, which no read reports, for --lock-id elsewhere.","Another holder is exit 1 WORKSPACE_LOCKED without --force.","A lock renews only through writes and lapses without them. Trust the lapse time the command prints over any number written down elsewhere."]}),RELEASE_DOC=defineCommandDoc("workspace-lock release",{rules:["--lock-id releases the lock of that ID rather than the one this shell took; the same flag every command accepts, read here whichever side of the verb it is on. Required when this shell holds none."],notes:["Only the session that took a lock can release it. A workspace nobody holds is exit 4; an ID that is not what holds the workspace is exit 1 WORKSPACE_LOCK_NOT_HELD, which means either another session of yours has it under a different ID or another user does \u2014 the refusal says which. Nothing is released either way.","Releasing early is the polite thing to do: the alternative is leaving somebody locked out until the lease lapses."]});function withScope8(cmd){return cmd.option("-w, --workspace <workspaceId>",SCOPE_WORKSPACE).option("--team <teamId>",SCOPE_TEAM_FILTER)}async function resolveScope11(globals){let client=await apiClient(globals.instance),resolved=await resolveParams(["workspace"],{workspace:globals.workspace,team:globals.team},{client,interactive:canPrompt()});return{client,workspace:resolved.workspace??""}}function lockReadFail(status,error51,workspaceId){let message=error51?.errorMessage??"";status===404&&/lock not found/i.test(message)&&fail(EXIT.NOT_FOUND,"NO_WORKSPACE_LOCK","Nobody holds the lock on this workspace.",{status,tone:"ok",hint:`Take it with \`${CLI} workspace-lock take -w ${workspaceId}\`.`}),apiFail(status,error51)}function renderLock(lock,me2,extra={}){return renderDetail({workspaceId:lock.workspaceId,source:lock.source,acquiredAt:lock.acquiredAt,expiresAt:expiryCell(lock.expiresAt),holder:holderCell(lock.holder,me2),...extra})}function workspaceLockCommand(){let lock=new Command("workspace-lock").alias("wl").description("Manage workspace locks");return withScope8(lock.command("check").description("Check who holds the workspace lock (exit 4 when nobody does)")).option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,CHECK_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope11(globals),result=await withSpinner("Reading the workspace lock",()=>readLock(scope2.client,scope2.workspace));result.lock||lockReadFail(result.status,result.error,scope2.workspace);let me2=isRaw()?void 0:await currentUser(scope2.client),lockDoc=result.lock;isRaw()||console.error("\u2139 Workspace lock is taken."),ok(lockDoc,{human:()=>renderLock(lockDoc,me2)})}),withScope8(lock.command("take").description("Take the workspace lock, or renew one this shell already holds; kept for the rest of the shell session")).option("--force","Take the lock even though another session holds it \u2014 a web application session loses edit control and is warned about unsaved changes (optional, interactive)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,TAKE_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope11(globals),lockId=explicitLockId()??ownStoredLock(scope2.workspace)?.lockId??newLockId(),result=await withSpinner("Taking the workspace lock",()=>takeLock(scope2.client,scope2.workspace,{lockId,force:opts.force}));if(result.conflict){let holder=result.conflict===!0?void 0:result.conflict;canPrompt()||lockedFail(holder,scope2.workspace,void 0,await currentUser(scope2.client)),await askLockConflict(holder,await currentUser(scope2.client),{allowUnlocked:!1})!=="force"&&fail(EXIT.CANCELLED,"CANCELLED","Cancelled."),result=await withSpinner("Taking the workspace lock",()=>takeLock(scope2.client,scope2.workspace,{lockId,force:!0}))}result.lock||apiFail(result.status,result.error),storeTaken(scope2.workspace,lockId,result.lock.expiresAt);let human=isRaw()?"":renderLock(result.lock,await currentUser(scope2.client),{lockId});okMutation("Workspace lock taken",{...result.lock,lockId},human),isRaw()||console.error(`Held for this shell session. Release it with \`${CLI} workspace-lock release -w ${scope2.workspace}\`.`)}),withScope8(lock.command("release").description("Release the workspace lock, rather than waiting for the lease to lapse")).option("--lock-id <lockId>","Lock ID to release; the same flag every command accepts, read here whichever side of the verb it is on (required unless this shell holds one, env SR_CONNECT_CLI_LOCK_ID, default: the lock this shell took)").option("--explain",EXPLAIN).action(async(opts,cmd)=>{if(explained(cmd,RELEASE_DOC))return;let globals=cmd.optsWithGlobals(),scope2=await resolveScope11(globals),stored=ownStoredLock(scope2.workspace,"read")?.lockId,lockId=opts.lockId??explicitLockId()??stored;lockId||fail(EXIT.USAGE,"USAGE_ERROR","No workspace lock to release: this shell holds none. Pass --lock-id, or set SR_CONNECT_CLI_LOCK_ID.");let result=await withSpinner("Releasing the workspace lock",()=>releaseLock(scope2.client,scope2.workspace,lockId));if(lockId===stored&&(result.ok||result.status===404)&&forgetWorkspaceLock(scope2.workspace),result.status===409){let holder=result.error?.lockedBy;releaseFail(holder,scope2.workspace,lockId,await currentUser(scope2.client))}result.ok||apiFail(result.status,result.error),okMutation("Workspace lock released",{deleted:!0,id:lockId,workspaceId:scope2.workspace},renderDetail({workspaceId:scope2.workspace}))}),lock}var refusedBy;function positionalNamed(cmd,flag){let named=cmd?.registeredArguments.find(argument=>`--${argument.name().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`===flag)?.name();if(named!==void 0)return named;let asPositional=SCOPE_POSITIONALS[flag];return asPositional!==void 0&&cmd?.registeredArguments.some(argument=>argument.name()===asPositional)?asPositional:void 0}var SCOPE_POSITIONALS={"-w":"workspaceId","--workspace":"workspaceId","-e":"environmentId","--env":"environmentId","--environment":"environmentId","--team":"teamId"};function scopeNamed(cmd,flag){if(SCOPE_POSITIONALS[flag]===void 0)return;let declared=(cmd?.options??[]).flatMap(option=>option.long!==void 0&&SCOPE_POSITIONALS[option.long]!==void 0?[option.long]:[]);return declared.length>0?declared:void 0}var MIN_SUFFIX_STEM=4;function suffixNamed(cmd,flag){let stem=flag.replace(/^--/,"");if(stem.length<MIN_SUFFIX_STEM)return;let matches=(cmd?.options??[]).map(option=>option.long).filter(long=>long!==void 0&&long!==flag&&long.endsWith(`-${stem}`));return matches.length===1?matches[0]:void 0}function nounOf2(name){return name.replace(/Id$/,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase()}function valuedOptions(cmd){return(cmd?.options??[]).filter(option=>(option.required||option.optional)&&option.long!==void 0).map(option=>option.long??"")}function usageErrorOf(err,cmd=refusedBy){let raw=err.message.replace(/^error: /,""),quoted=/'([^']+)'/.exec(raw)?.[1],flag=quoted===void 0?void 0:/--[a-z][a-z-]*/.exec(quoted)?.[0]??quoted,path2=cmd===void 0?void 0:commandPath2(cmd);switch(err.code){case"commander.missingMandatoryOptionValue":return new CliError(EXIT.USAGE,"USAGE_ERROR",`${flag??"An option"} is required.`,{hint:supplyHint({ask:"be asked for it"})});case"commander.optionMissingArgument":{let value=quoted===void 0?void 0:/<[^>]+>/.exec(quoted)?.[0];return new CliError(EXIT.USAGE,"USAGE_ERROR",`${flag??"The option"} needs a value${value?` (${value})`:""}.`)}case"commander.unknownOption":{let suggestion=/\(Did you mean ([^?]+)\?\)/.exec(raw)?.[1],options="Add --help to the command to list its options.",positional=quoted===void 0?void 0:positionalNamed(cmd,quoted),suffix=quoted===void 0?void 0:suffixNamed(cmd,quoted),scope2=quoted===void 0?void 0:scopeNamed(cmd,quoted),lead=positional!==void 0&&path2!==void 0?`The ${nounOf2(positional)} is the positional argument: ${path2} <${positional}>.`:scope2!==void 0?`This verb's scope ${scope2.length===1?"flag is":"flags are"} ${scope2.join(" and ")}.`:(suffix??suggestion)!==void 0?`Did you mean ${suffix??suggestion}?`:void 0;return new CliError(EXIT.USAGE,"USAGE_ERROR",`'${quoted??""}' is not an option here.`,{hint:lead===void 0?options:`${lead} ${options}`})}case"commander.excessArguments":{let options="Add --help to the command to list its options.";if(cmd!==void 0&&cmd.registeredArguments.length===0){let valued=valuedOptions(cmd),named=valued.length>0?`Name it with ${valued.join(" or ")}. `:"";return new CliError(EXIT.USAGE,"USAGE_ERROR",`'${path2??"The command"}' takes no positional arguments.`,{hint:`${named}${options}`})}return new CliError(EXIT.USAGE,"USAGE_ERROR",raw.charAt(0).toUpperCase()+raw.slice(1),{hint:options})}case"commander.unknownCommand":{let suggestion=/\(Did you mean ([^?]+)\?\)/.exec(raw)?.[1],groups=`\`${CLI}\` lists the groups, and a group run alone lists its verbs.`;return new CliError(EXIT.USAGE,"USAGE_ERROR",`'${quoted??""}' is not a command.`,{hint:suggestion?`Did you mean ${suggestion}? ${groups}`:groups})}case"commander.missingArgument":return new CliError(EXIT.USAGE,"USAGE_ERROR",`<${quoted??"argument"}> is required.`,{hint:supplyHint()});default:return new CliError(EXIT.USAGE,"USAGE_ERROR",raw.charAt(0).toUpperCase()+raw.slice(1))}}var program2=addGlobalOptions(new Command(CLI).description("CLI for ScriptRunner Connect")).exitOverride();program2.addCommand(apiConnectionCommand());program2.addCommand(appCommand());program2.addCommand(authCommand());program2.addCommand(cliCommand());program2.addCommand(connectorCommand());program2.addCommand(connectorSharingCommand());program2.addCommand(environmentCommand());program2.addCommand(environmentParameterCommand());program2.addCommand(eventListenerCommand());program2.addCommand(eventListenerTestPayloadCommand());program2.addCommand(eventQueueCommand());program2.addCommand(feedbackCommand());program2.addCommand(localWorkspaceCommand());program2.addCommand(logsCommand());program2.addCommand(packageCommand());program2.addCommand(workspaceReadmeCommand());program2.addCommand(workspaceReleaseCommand());program2.addCommand(scheduledTriggerCommand());program2.addCommand(scriptCommand());program2.addCommand(teamCommand());program2.addCommand(tempRemoteWorkspaceCommand());program2.addCommand(templateCommand());program2.addCommand(workspaceCommand());program2.addCommand(workspaceLockCommand());function overrideExits(cmd){cmd.exitOverride(err=>{throw refusedBy=cmd,err}),cmd.configureOutput({outputError:()=>{},writeErr:str=>{process.stdout.write(str)}});for(let sub of cmd.commands)overrideExits(sub)}overrideExits(program2);applyHelpConventions(program2);program2.addHelpText("after",rootHelpFooter());function commandPath2(cmd){let names=[];for(let c=cmd;c.parent;c=c.parent)names.unshift(c.name());return names.join(" ")}program2.hook("preAction",(thisCommand,actionCommand)=>{let globals=thisCommand.optsWithGlobals();configureRawMode({enabled:!!globals.raw}),setCommandPath(commandPath2(actionCommand)),configureAgentMode({enabled:!!globals.agent}),setPromptsAllowed(globals.prompts!==!1&&!process.env.SR_CONNECT_CLI_NO_PROMPTS),setOutputCopy(globals.copyOutputToFile),configureSession({instance:globals.instance,enabled:globals.session!==!1}),configureRecorder({enabled:globals.recordApiCalls!==!1,instance:globals.instance}),configureWorkspaceLocking({enabled:globals.lock!==!1,lockId:globals.lockId}),configureLocalSync({enabled:globals.localSync!==!1,instance:globals.instance}),configureLocalWorkspaceScope({enabled:globals.localWorkspace!==!1,instance:globals.instance}),configureVersionGate({enabled:globals.versionGate!==!1}),configureCrashReports({enabled:globals.crashReports!==!1,instance:globals.instance}),configureAgenticFeedback({enabled:globals.agenticFeedback!==!1})});try{ignoreBrokenPipe(),warnIfNodeUnsupported(),configureRawMode({enabled:process.argv.includes("--raw")});let commandNames=program2.commands.flatMap(c=>[c.name(),...c.aliases()]);assertOutputCopyValue(process.argv,commandNames),assertVersionFlagIsRoot(process.argv,commandNames),configureUpdateCheck({enabled:!process.argv.includes("--no-update-check")}),configureCrashReports({enabled:!process.argv.includes("--no-crash-reports")}),printUpdateNotice(),startUpdateCheck(),await program2.parseAsync(process.argv),reportOutputCopy(),await flushOutput(),process.exit(EXIT.OK)}catch(err){if(err instanceof CliError){err.exitCode===EXIT.NOT_FOUND&&warnInheritedWorkspace();let code2=reportError(err);reportOutputCopy(),await offerCrashReport(err),await flushOutput(),process.exit(code2)}if(err instanceof CommanderError){(err.code==="commander.helpDisplayed"||err.code==="commander.version"||err.code==="commander.help")&&(await flushOutput(),process.exit(err.exitCode===1?0:err.exitCode));let code2=reportError(usageErrorOf(err));reportOutputCopy(),await flushOutput(),process.exit(code2)}let message=err instanceof Error?err.message:String(err),code=reportError(new CliError(EXIT.API_ERROR,"UNEXPECTED_ERROR",message));reportOutputCopy(),await offerCrashReport(err),await flushOutput(),process.exit(code)}
1390
+ /*! Bundled license information:
1391
+
1392
+ promise-throttle-all/dist/index.mjs:
1393
+ (*!
1394
+ * promise-throttle-all v1.1.1
1395
+ * (c) Robin Pokorny
1396
+ * Released under the MIT License.
1397
+ *)
1398
+ */