balda 0.0.35 → 0.0.36

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/lib/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var it=require('path'),Rs=require('pino'),ajv=require('ajv'),Es=require('fast-json-stringify'),child_process=require('child_process'),qr=require('readline'),module$1=require('module'),Xe=require('fs'),ro=require('crypto'),stream=require('stream'),async_hooks=require('async_hooks'),zlib=require('zlib'),http=require('http'),http2=require('http2'),https=require('https'),promises=require('stream/promises');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var it__default=/*#__PURE__*/_interopDefault(it);var Rs__default=/*#__PURE__*/_interopDefault(Rs);var Es__default=/*#__PURE__*/_interopDefault(Es);var qr__namespace=/*#__PURE__*/_interopNamespace(qr);var Xe__default=/*#__PURE__*/_interopDefault(Xe);var ro__default=/*#__PURE__*/_interopDefault(ro);var vs=Object.create;var nt=Object.defineProperty;var Rr=Object.getOwnPropertyDescriptor;var bs=Object.getOwnPropertyNames;var ws=Object.getPrototypeOf,Ss=Object.prototype.hasOwnProperty;var Nt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var xs=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ts=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ps=(n,e)=>{for(var t in e)nt(n,t,{get:e[t],enumerable:true});},Os=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bs(e))!Ss.call(n,s)&&s!==t&&nt(n,s,{get:()=>e[s],enumerable:!(r=Rr(e,s))||r.enumerable});return n};var Cs=(n,e,t)=>(t=n!=null?vs(ws(n)):{},Os(nt(t,"default",{value:n,enumerable:true}),n));var P=(n,e,t,r)=>{for(var s=void 0,o=n.length-1,i;o>=0;o--)(i=n[o])&&(s=(i(e,t,s))||s);return s&&nt(e,t,s),s};var jr={};Ps(jr,{runtime:()=>E});var Lt,E,G=xs(()=>{Lt=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},E=new Lt;});var _r=Ts((pt,zt)=>{(function(e,t){typeof pt=="object"&&typeof zt=="object"?zt.exports=t():typeof define=="function"&&define.amd?define("cronstrue",[],t):typeof pt=="object"?pt.cronstrue=t():e.cronstrue=t();})(globalThis,()=>(()=>{var n={949:((s,o,i)=>{Object.defineProperty(o,"__esModule",{value:true}),o.CronParser=void 0;var a=i(515),c=(function(){function d(l,p,u){p===void 0&&(p=true),u===void 0&&(u=false),this.expression=l,this.dayOfWeekStartIndexZero=p,this.monthStartIndexZero=u;}return d.prototype.parse=function(){var l,p,u=(l=this.expression)!==null&&l!==void 0?l:"";if(u==="@reboot")return p=["@reboot","","","","","",""],p;if(u.startsWith("@")){var m=this.parseSpecial(this.expression);p=this.extractParts(m);}else p=this.extractParts(this.expression);return this.normalize(p),this.validate(p),p},d.prototype.parseSpecial=function(l){var p={"@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"},u=p[l];if(!u)throw new Error("Unknown special expression.");return u},d.prototype.extractParts=function(l){if(!this.expression)throw new Error("cron expression is empty");for(var p=l.trim().split(/[ ]+/),u=0;u<p.length;u++)if(p[u].includes(",")){var m=p[u].split(",").map(function(f){return f.trim()}).filter(function(f){return f!==""}).map(function(f){return isNaN(Number(f))?f:Number(f)}).filter(function(f){return f!==null&&f!==""});m.length===0&&m.push("*"),m.sort(function(f,g){return f!==null&&g!==null?f-g:0}),p[u]=m.map(function(f){return f!==null?f.toString():""}).join(",");}if(p.length<5)throw new Error("Expression has only ".concat(p.length," part").concat(p.length==1?"":"s",". At least 5 parts are required."));if(p.length==5)p.unshift(""),p.push("");else if(p.length==6){var h=/\d{4}$/.test(p[5])||p[4]=="?"||p[2]=="?";h?p.unshift(""):p.push("");}else if(p.length>7)throw new Error("Expression has ".concat(p.length," parts; too many!"));return p},d.prototype.normalize=function(l){var p=this;if(l[3]=l[3].replace("?","*"),l[5]=l[5].replace("?","*"),l[2]=l[2].replace("?","*"),l[0].indexOf("0/")==0&&(l[0]=l[0].replace("0/","*/")),l[1].indexOf("0/")==0&&(l[1]=l[1].replace("0/","*/")),l[2].indexOf("0/")==0&&(l[2]=l[2].replace("0/","*/")),l[3].indexOf("1/")==0&&(l[3]=l[3].replace("1/","*/")),l[4].indexOf("1/")==0&&(l[4]=l[4].replace("1/","*/")),l[6].indexOf("1/")==0&&(l[6]=l[6].replace("1/","*/")),l[5]=l[5].replace(/(^\d)|([^#/\s]\d)/g,function(w){var b=w.replace(/\D/,""),S=b;return p.dayOfWeekStartIndexZero?b=="7"&&(S="0"):S=(parseInt(b)-1).toString(),w.replace(b,S)}),l[5]=="L"&&(l[5]="6"),l[3]=="?"&&(l[3]="*"),l[3].indexOf("W")>-1&&(l[3].indexOf(",")>-1||l[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 u={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var m in u)l[5]=l[5].replace(new RegExp(m,"gi"),u[m].toString());l[4]=l[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(w){var b=w.replace(/\D/,""),S=b;return p.monthStartIndexZero&&(S=(parseInt(b)+1).toString()),w.replace(b,S)});var h={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 f in h)l[4]=l[4].replace(new RegExp(f,"gi"),h[f].toString());l[0]=="0"&&(l[0]=""),!/\*|\-|\,|\//.test(l[2])&&(/\*|\//.test(l[1])||/\*|\//.test(l[0]))&&(l[2]+="-".concat(l[2]));for(var g=0;g<l.length;g++)if(l[g].indexOf(",")!=-1&&(l[g]=l[g].split(",").filter(function(w){return w!==""}).join(",")||"*"),l[g]=="*/1"&&(l[g]="*"),l[g].indexOf("/")>-1&&!/^\*|\-|\,/.test(l[g])){var y=null;switch(g){case 4:y="12";break;case 5:y="6";break;case 6:y="9999";break;default:y=null;break}if(y!==null){var T=l[g].split("/");l[g]="".concat(T[0],"-").concat(y,"/").concat(T[1]);}}},d.prototype.validate=function(l){var p="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(l[0],p),this.validateOnlyExpectedCharactersFound(l[1],p),this.validateOnlyExpectedCharactersFound(l[2],p),this.validateOnlyExpectedCharactersFound(l[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(l[4],p),this.validateOnlyExpectedCharactersFound(l[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(l[6],p),this.validateAnyRanges(l);},d.prototype.validateAnyRanges=function(l){a.default.secondRange(l[0]),a.default.minuteRange(l[1]),a.default.hourRange(l[2]),a.default.dayOfMonthRange(l[3]),a.default.monthRange(l[4],this.monthStartIndexZero),a.default.dayOfWeekRange(l[5],this.dayOfWeekStartIndexZero);},d.prototype.validateOnlyExpectedCharactersFound=function(l,p){var u=l.match(new RegExp("[^".concat(p,"]+"),"gi"));if(u&&u.length)throw new Error("Expression contains invalid values: '".concat(u.toString(),"'"))},d})();o.CronParser=c;}),333:((s,o,i)=>{Object.defineProperty(o,"__esModule",{value:true}),o.ExpressionDescriptor=void 0;var a=i(823),c=i(949),d=(function(){function l(p,u){if(this.expression=p,this.options=u,this.expressionParts=new Array(5),!this.options.locale&&l.defaultLocale&&(this.options.locale=l.defaultLocale),!l.locales[this.options.locale]){var m=Object.keys(l.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(m,"'.")),this.options.locale=m;}this.i18n=l.locales[this.options.locale],u.use24HourTimeFormat===void 0&&(u.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault());}return l.toString=function(p,u){var m=u===void 0?{}:u,h=m.throwExceptionOnParseError,f=h===void 0?true:h,g=m.verbose,y=g===void 0?false:g,T=m.dayOfWeekStartIndexZero,w=T===void 0?true:T,b=m.monthStartIndexZero,S=b===void 0?false:b,R=m.use24HourTimeFormat,M=m.locale,B=M===void 0?null:M,ce=m.logicalAndDayFields,le=ce===void 0?false:ce,Z={throwExceptionOnParseError:f,verbose:y,dayOfWeekStartIndexZero:w,monthStartIndexZero:S,use24HourTimeFormat:R,locale:B,logicalAndDayFields:le};Z.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Bt=new l(p,Z);return Bt.getFullDescription()},l.initialize=function(p,u){u===void 0&&(u="en"),l.specialCharacters=["/","-",",","*"],l.defaultLocale=u,p.load(l.locales);},l.prototype.getFullDescription=function(){var p,u,m="";try{var h=new c.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=h.parse(),this.expressionParts[0]==="@reboot")return ((u=(p=this.i18n).atReboot)===null||u===void 0?void 0:u.call(p))||"Run once, at startup";var f=this.getTimeOfDayDescription(),g=this.getDayOfMonthDescription(),y=this.getMonthDescription(),T=this.getDayOfWeekDescription(),w=this.getYearDescription();m+=f+g+T+y+w,m=this.transformVerbosity(m,!!this.options.verbose),m=m.charAt(0).toLocaleUpperCase()+m.substr(1);}catch(b){if(!this.options.throwExceptionOnParseError)m=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw "".concat(b)}return m},l.prototype.getTimeOfDayDescription=function(){var p=this.expressionParts[0],u=this.expressionParts[1],m=this.expressionParts[2],h="";if(!a.StringUtilities.containsAny(u,l.specialCharacters)&&!a.StringUtilities.containsAny(m,l.specialCharacters)&&!a.StringUtilities.containsAny(p,l.specialCharacters))h+=this.i18n.atSpace()+this.formatTime(m,u,p);else if(!p&&u.indexOf("-")>-1&&!(u.indexOf(",")>-1)&&!(u.indexOf("/")>-1)&&!a.StringUtilities.containsAny(m,l.specialCharacters)){var f=u.split("-");h+=a.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(m,f[0],""),this.formatTime(m,f[1],""));}else if(!p&&m.indexOf(",")>-1&&m.indexOf("-")==-1&&m.indexOf("/")==-1&&!a.StringUtilities.containsAny(u,l.specialCharacters)){var g=m.split(",");h+=this.i18n.at();for(var y=0;y<g.length;y++)h+=" ",h+=this.formatTime(g[y],u,""),y<g.length-2&&(h+=","),y==g.length-2&&(h+=this.i18n.spaceAnd());}else {var T=this.getSecondsDescription(),w=this.getMinutesDescription(),b=this.getHoursDescription();if(h+=T,h&&w&&(h+=", "),h+=w,w===b)return h;h&&b&&(h+=", "),h+=b;}return h},l.prototype.getSecondsDescription=function(){var p=this,u=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(m){return m},function(m){return a.StringUtilities.format(p.i18n.everyX0Seconds(m),m)},function(m){return p.i18n.secondsX0ThroughX1PastTheMinute()},function(m){return m=="0"?"":parseInt(m)<20?p.i18n.atX0SecondsPastTheMinute(m):p.i18n.atX0SecondsPastTheMinuteGt20()||p.i18n.atX0SecondsPastTheMinute(m)});return u},l.prototype.getMinutesDescription=function(){var p=this,u=this.expressionParts[0],m=this.expressionParts[2],h=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(f){return f},function(f){return a.StringUtilities.format(p.i18n.everyX0Minutes(f),f)},function(f){return p.i18n.minutesX0ThroughX1PastTheHour()},function(f){try{return f=="0"&&m.indexOf("/")==-1&&u==""?p.i18n.everyHour():parseInt(f)<20?p.i18n.atX0MinutesPastTheHour(f):p.i18n.atX0MinutesPastTheHourGt20()||p.i18n.atX0MinutesPastTheHour(f)}catch{return p.i18n.atX0MinutesPastTheHour(f)}});return h},l.prototype.getHoursDescription=function(){var p=this,u=this.expressionParts[2],m=0,h=[];u.split("/")[0].split(",").forEach(function(y){var T=y.split("-");T.length===2&&h.push({value:T[1],index:m+1}),m+=T.length;});var f=0,g=this.getSegmentDescription(u,this.i18n.everyHour(),function(y){var T=h.find(function(b){return b.value===y&&b.index===f}),w=T&&p.expressionParts[1]!=="0";return f++,w?p.formatTime(y,"59",""):p.formatTime(y,"0","")},function(y){return a.StringUtilities.format(p.i18n.everyX0Hours(y),y)},function(y){return p.i18n.betweenX0AndX1()},function(y){return p.i18n.atX0()});return g},l.prototype.getDayOfWeekDescription=function(){var p=this,u=this.i18n.daysOfTheWeek(),m=null;return this.expressionParts[5]=="*"?m="":m=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(h,f){var g=h;h.indexOf("#")>-1?g=h.substring(0,h.indexOf("#")):h.indexOf("L")>-1&&(g=g.replace("L",""));var y=parseInt(g),T=p.i18n.daysOfTheWeekInCase?p.i18n.daysOfTheWeekInCase(f)[y]:u[y];if(h.indexOf("#")>-1){var w=null,b=h.substring(h.indexOf("#")+1),S=h.substring(0,h.indexOf("#"));switch(b){case "1":w=p.i18n.first(S);break;case "2":w=p.i18n.second(S);break;case "3":w=p.i18n.third(S);break;case "4":w=p.i18n.fourth(S);break;case "5":w=p.i18n.fifth(S);break}T=w+" "+T;}return T},function(h){return parseInt(h)==1?"":a.StringUtilities.format(p.i18n.commaEveryX0DaysOfTheWeek(h),h)},function(h){var f=h.substring(0,h.indexOf("-")),g=p.expressionParts[3]!="*";return g?p.i18n.commaAndX0ThroughX1(f):p.i18n.commaX0ThroughX1(f)},function(h){var f=null;if(h.indexOf("#")>-1){var g=h.substring(h.indexOf("#")+1),y=h.substring(0,h.indexOf("#"));f=p.i18n.commaOnThe(g,y).trim()+p.i18n.spaceX0OfTheMonth();}else if(h.indexOf("L")>-1)f=p.i18n.commaOnTheLastX0OfTheMonth(h.replace("L",""));else {var T=p.expressionParts[3]!="*";T?p.options.logicalAndDayFields?f=p.i18n.commaOnlyOnX0(h):f=p.i18n.commaAndOnX0():f=p.i18n.commaOnlyOnX0(h);}return f}),m},l.prototype.getMonthDescription=function(){var p=this,u=this.i18n.monthsOfTheYear(),m=this.getSegmentDescription(this.expressionParts[4],"",function(h,f){return f&&p.i18n.monthsOfTheYearInCase?p.i18n.monthsOfTheYearInCase(f)[parseInt(h)-1]:u[parseInt(h)-1]},function(h){return parseInt(h)==1?"":a.StringUtilities.format(p.i18n.commaEveryX0Months(h),h)},function(h){return p.i18n.commaMonthX0ThroughMonthX1()||p.i18n.commaX0ThroughX1()},function(h){return p.i18n.commaOnlyInMonthX0?p.i18n.commaOnlyInMonthX0():p.i18n.commaOnlyInX0()});return m},l.prototype.getDayOfMonthDescription=function(){var p=this,u=null,m=this.expressionParts[3];switch(m){case "L":u=this.i18n.commaOnTheLastDayOfTheMonth();break;case "WL":case "LW":u=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var h=m.match(/(\d{1,2}W)|(W\d{1,2})/);if(h){var f=parseInt(h[0].replace("W","")),g=f==1?this.i18n.firstWeekday():a.StringUtilities.format(this.i18n.weekdayNearestDayX0(),f.toString());u=a.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),g);break}else {var y=m.match(/L-(\d{1,2})/);if(y){var T=y[1];u=a.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(T),T);break}else {if(m=="*"&&this.expressionParts[5]!="*")return "";u=this.getSegmentDescription(m,this.i18n.commaEveryDay(),function(w){return w=="L"?p.i18n.lastDay():p.i18n.dayX0?a.StringUtilities.format(p.i18n.dayX0(),w):w},function(w){return w=="1"?p.i18n.commaEveryDay():p.i18n.commaEveryX0Days(w)},function(w){return p.i18n.commaBetweenDayX0AndX1OfTheMonth(w)},function(w){return p.i18n.commaOnDayX0OfTheMonth(w)});}break}}return u},l.prototype.getYearDescription=function(){var p=this,u=this.getSegmentDescription(this.expressionParts[6],"",function(m){return /^\d+$/.test(m)?new Date(parseInt(m),1).getFullYear().toString():m},function(m){return a.StringUtilities.format(p.i18n.commaEveryX0Years(m),m)},function(m){return p.i18n.commaYearX0ThroughYearX1()||p.i18n.commaX0ThroughX1()},function(m){return p.i18n.commaOnlyInYearX0?p.i18n.commaOnlyInYearX0():p.i18n.commaOnlyInX0()});return u},l.prototype.getSegmentDescription=function(p,u,m,h,f,g){var y=null,T=p.indexOf("/")>-1,w=p.indexOf("-")>-1,b=p.indexOf(",")>-1;if(!p)y="";else if(p==="*")y=u;else if(!T&&!w&&!b)y=a.StringUtilities.format(g(p),m(p));else if(b){for(var S=p.split(","),R="",M=0;M<S.length;M++)if(M>0&&S.length>2&&(R+=",",M<S.length-1&&(R+=" ")),M>0&&S.length>1&&(M==S.length-1||S.length==2)&&(R+="".concat(this.i18n.spaceAnd()," ")),S[M].indexOf("/")>-1||S[M].indexOf("-")>-1){var B=S[M].indexOf("-")>-1&&S[M].indexOf("/")==-1,ce=this.getSegmentDescription(S[M],u,m,h,B?this.i18n.commaX0ThroughX1:f,g);B&&(ce=ce.replace(", ","")),R+=ce;}else T?R+=this.getSegmentDescription(S[M],u,m,h,f,g):R+=m(S[M]);T?y=R:y=a.StringUtilities.format(g(p),R);}else if(T){var S=p.split("/");if(y=a.StringUtilities.format(h(S[1]),S[1]),S[0].indexOf("-")>-1){var le=this.generateRangeSegmentDescription(S[0],f,m);le.indexOf(", ")!=0&&(y+=", "),y+=le;}else if(S[0].indexOf("*")==-1){var Z=a.StringUtilities.format(g(S[0]),m(S[0]));Z=Z.replace(", ",""),y+=a.StringUtilities.format(this.i18n.commaStartingX0(),Z);}}else w&&(y=this.generateRangeSegmentDescription(p,f,m));return y},l.prototype.generateRangeSegmentDescription=function(p,u,m){var h="",f=p.split("-"),g=m(f[0],1),y=m(f[1],2),T=u(p);return h+=a.StringUtilities.format(T,g,y),h},l.prototype.formatTime=function(p,u,m){var h=0,f=0,g=parseInt(p)+h,y=parseInt(u)+f;y>=60?(y-=60,g+=1):y<0&&(y+=60,g-=1),g>=24?g=g-24:g<0&&(g=24+g);var T="",w=false;this.options.use24HourTimeFormat||(w=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),T=w?"".concat(this.getPeriod(g)," "):" ".concat(this.getPeriod(g)),g>12&&(g-=12),g===0&&(g=12));var b="";return m&&(b=":".concat(("00"+m).substring(m.length))),"".concat(w?T:"").concat(("00"+g.toString()).substring(g.toString().length),":").concat(("00"+y.toString()).substring(y.toString().length)).concat(b).concat(w?"":T)},l.prototype.transformVerbosity=function(p,u){if(!u&&(p=p.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),p=p.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),p=p.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),p=p.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var m=0,h=Object.entries(this.i18n.conciseVerbosityReplacements());m<h.length;m++){var f=h[m],g=f[0],y=f[1];p=p.replace(new RegExp(g,"g"),y);}return p},l.prototype.getPeriod=function(p){return p>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},l.locales={},l})();o.ExpressionDescriptor=d;}),747:((s,o,i)=>{Object.defineProperty(o,"__esModule",{value:true}),o.enLocaleLoader=void 0;var a=i(486),c=(function(){function d(){}return d.prototype.load=function(l){l.en=new a.en;},d})();o.enLocaleLoader=c;}),486:((s,o)=>{Object.defineProperty(o,"__esModule",{value:true}),o.en=void 0;var i=(function(){function a(){}return a.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},a.prototype.atX0MinutesPastTheHourGt20=function(){return null},a.prototype.commaMonthX0ThroughMonthX1=function(){return null},a.prototype.commaYearX0ThroughYearX1=function(){return null},a.prototype.use24HourTimeFormatByDefault=function(){return false},a.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return "An error occurred when generating the expression description. Check the cron expression syntax."},a.prototype.everyMinute=function(){return "every minute"},a.prototype.everyHour=function(){return "every hour"},a.prototype.atSpace=function(){return "At "},a.prototype.everyMinuteBetweenX0AndX1=function(){return "Every minute between %s and %s"},a.prototype.at=function(){return "At"},a.prototype.spaceAnd=function(){return " and"},a.prototype.everySecond=function(){return "every second"},a.prototype.everyX0Seconds=function(){return "every %s seconds"},a.prototype.secondsX0ThroughX1PastTheMinute=function(){return "seconds %s through %s past the minute"},a.prototype.atX0SecondsPastTheMinute=function(){return "at %s seconds past the minute"},a.prototype.everyX0Minutes=function(){return "every %s minutes"},a.prototype.minutesX0ThroughX1PastTheHour=function(){return "minutes %s through %s past the hour"},a.prototype.atX0MinutesPastTheHour=function(){return "at %s minutes past the hour"},a.prototype.everyX0Hours=function(){return "every %s hours"},a.prototype.betweenX0AndX1=function(){return "between %s and %s"},a.prototype.atX0=function(){return "at %s"},a.prototype.commaEveryDay=function(){return ", every day"},a.prototype.commaEveryX0DaysOfTheWeek=function(){return ", every %s days of the week"},a.prototype.commaX0ThroughX1=function(){return ", %s through %s"},a.prototype.commaAndX0ThroughX1=function(){return ", %s through %s"},a.prototype.first=function(){return "first"},a.prototype.second=function(){return "second"},a.prototype.third=function(){return "third"},a.prototype.fourth=function(){return "fourth"},a.prototype.fifth=function(){return "fifth"},a.prototype.commaOnThe=function(){return ", on the "},a.prototype.spaceX0OfTheMonth=function(){return " %s of the month"},a.prototype.lastDay=function(){return "the last day"},a.prototype.commaOnTheLastX0OfTheMonth=function(){return ", on the last %s of the month"},a.prototype.commaOnlyOnX0=function(){return ", only on %s"},a.prototype.commaAndOnX0=function(){return ", and on %s"},a.prototype.commaEveryX0Months=function(){return ", every %s months"},a.prototype.commaOnlyInX0=function(){return ", only in %s"},a.prototype.commaOnTheLastDayOfTheMonth=function(){return ", on the last day of the month"},a.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return ", on the last weekday of the month"},a.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return ", %s days before the last day of the month"},a.prototype.firstWeekday=function(){return "first weekday"},a.prototype.weekdayNearestDayX0=function(){return "weekday nearest day %s"},a.prototype.commaOnTheX0OfTheMonth=function(){return ", on the %s of the month"},a.prototype.commaEveryX0Days=function(){return ", every %s days"},a.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return ", between day %s and %s of the month"},a.prototype.commaOnDayX0OfTheMonth=function(){return ", on day %s of the month"},a.prototype.commaEveryHour=function(){return ", every hour"},a.prototype.commaEveryX0Years=function(){return ", every %s years"},a.prototype.commaStartingX0=function(){return ", starting %s"},a.prototype.daysOfTheWeek=function(){return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},a.prototype.monthsOfTheYear=function(){return ["January","February","March","April","May","June","July","August","September","October","November","December"]},a.prototype.atReboot=function(){return "Run once, at startup"},a})();o.en=i;}),515:((s,o)=>{Object.defineProperty(o,"__esModule",{value:true});function i(c,d){if(!c)throw new Error(d)}var a=(function(){function c(){}return c.secondRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=0&&u<=59,"seconds part must be >= 0 and <= 59");}},c.minuteRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=0&&u<=59,"minutes part must be >= 0 and <= 59");}},c.hourRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=0&&u<=23,"hours part must be >= 0 and <= 23");}},c.dayOfMonthRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=1&&u<=31,"DOM part must be >= 1 and <= 31");}},c.monthRange=function(d,l){for(var p=d.split(","),u=0;u<p.length;u++)if(!isNaN(parseInt(p[u],10))){var m=parseInt(p[u],10);i(m>=1&&m<=12,l?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12");}},c.dayOfWeekRange=function(d,l){for(var p=d.split(","),u=0;u<p.length;u++)if(!isNaN(parseInt(p[u],10))){var m=parseInt(p[u],10);i(m>=0&&m<=6,l?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7");}},c})();o.default=a;}),823:((s,o)=>{Object.defineProperty(o,"__esModule",{value:true}),o.StringUtilities=void 0;var i=(function(){function a(){}return a.format=function(c){for(var d=[],l=1;l<arguments.length;l++)d[l-1]=arguments[l];return c.replace(/%s/g,function(p){for(var u=[],m=1;m<arguments.length;m++)u[m-1]=arguments[m];return d.shift()})},a.containsAny=function(c,d){return d.some(function(l){return c.indexOf(l)>-1})},a})();o.StringUtilities=i;})},e={};function t(s){var o=e[s];if(o!==void 0)return o.exports;var i=e[s]={exports:{}};return n[s](i,i.exports,t),i.exports}var r={};return (()=>{var s=r;Object.defineProperty(s,"__esModule",{value:true}),s.toString=void 0;var o=t(333),i=t(747);o.ExpressionDescriptor.initialize(new i.enLocaleLoader),s.default=o.ExpressionDescriptor;var a=o.ExpressionDescriptor.toString;s.toString=a;})(),r})());});G();G();var Ft=class{getCwd(){switch(E.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},N=new Ft;G();var It=class{basename(e){switch(E.type){case "node":case "bun":case "deno":return it__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(E.type){case "node":case "bun":case "deno":return it__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(E.type){case "bun":case "node":case "deno":return it__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(E.type){case "bun":case "node":case "deno":return it__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new It;var Dt=class{async glob(...e){let t=await import('fs/promises'),r=N.getCwd(),s=x.resolve(r,e[1]?.cwd??""),o=[];for await(let i of t.glob(...e)){if(typeof i=="string"){o.push(x.resolve(s,i));continue}i.isFile()&&o.push(x.resolve(s,i.name));}return o}async mkdir(e,t){switch(E.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(E.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(E.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let o=Bun.file(e);return t?.encoding==="utf8"?o.text():new Uint8Array(await o.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}async writeFile(e,t){switch(E.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(E.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let o=await(await import('fs/promises')).stat(e);return {isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async unlink(e){switch(E.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(E.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(E.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},v=new Dt;var O=class extends Error{constructor(e){super(e);}};var js=()=>Rs__default.default({level:"info",formatters:{level:e=>({level:e})}}),q=js();var He=class extends O{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var at=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"?module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))):Nt("module").createRequire?.((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))??__filename)??Nt,pe=async n=>{let e=x.join(process.cwd(),"node_modules");if(!await v.exists(e))return n;let r=[];for(let s of n){let o=x.join(e,s);await v.exists(o)||r.push(s);}return r},U=async()=>await v.exists(x.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await v.exists(x.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await v.exists(x.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await v.exists(x.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await v.exists(x.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],I=async(n,e,t,r,s=true)=>{let o=qr__namespace.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var it=require('path'),Rs=require('pino'),ajv=require('ajv'),Es=require('fast-json-stringify'),child_process=require('child_process'),qr=require('readline'),module$1=require('module'),Xe=require('fs'),ro=require('crypto'),stream=require('stream'),async_hooks=require('async_hooks'),zlib=require('zlib'),http=require('http'),http2=require('http2'),https=require('https'),promises=require('stream/promises');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var it__default=/*#__PURE__*/_interopDefault(it);var Rs__default=/*#__PURE__*/_interopDefault(Rs);var Es__default=/*#__PURE__*/_interopDefault(Es);var qr__namespace=/*#__PURE__*/_interopNamespace(qr);var Xe__default=/*#__PURE__*/_interopDefault(Xe);var ro__default=/*#__PURE__*/_interopDefault(ro);var vs=Object.create;var nt=Object.defineProperty;var Rr=Object.getOwnPropertyDescriptor;var bs=Object.getOwnPropertyNames;var ws=Object.getPrototypeOf,Ss=Object.prototype.hasOwnProperty;var Lt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var xs=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ts=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ps=(n,e)=>{for(var t in e)nt(n,t,{get:e[t],enumerable:true});},Os=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bs(e))!Ss.call(n,s)&&s!==t&&nt(n,s,{get:()=>e[s],enumerable:!(r=Rr(e,s))||r.enumerable});return n};var Cs=(n,e,t)=>(t=n!=null?vs(ws(n)):{},Os(nt(t,"default",{value:n,enumerable:true}),n));var P=(n,e,t,r)=>{for(var s=void 0,o=n.length-1,i;o>=0;o--)(i=n[o])&&(s=(i(e,t,s))||s);return s&&nt(e,t,s),s};var jr={};Ps(jr,{runtime:()=>E});var Ft,E,G=xs(()=>{Ft=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},E=new Ft;});var _r=Ts((pt,Gt)=>{(function(e,t){typeof pt=="object"&&typeof Gt=="object"?Gt.exports=t():typeof define=="function"&&define.amd?define("cronstrue",[],t):typeof pt=="object"?pt.cronstrue=t():e.cronstrue=t();})(globalThis,()=>(()=>{var n={949:((s,o,i)=>{Object.defineProperty(o,"__esModule",{value:true}),o.CronParser=void 0;var a=i(515),c=(function(){function d(l,p,u){p===void 0&&(p=true),u===void 0&&(u=false),this.expression=l,this.dayOfWeekStartIndexZero=p,this.monthStartIndexZero=u;}return d.prototype.parse=function(){var l,p,u=(l=this.expression)!==null&&l!==void 0?l:"";if(u==="@reboot")return p=["@reboot","","","","","",""],p;if(u.startsWith("@")){var m=this.parseSpecial(this.expression);p=this.extractParts(m);}else p=this.extractParts(this.expression);return this.normalize(p),this.validate(p),p},d.prototype.parseSpecial=function(l){var p={"@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"},u=p[l];if(!u)throw new Error("Unknown special expression.");return u},d.prototype.extractParts=function(l){if(!this.expression)throw new Error("cron expression is empty");for(var p=l.trim().split(/[ ]+/),u=0;u<p.length;u++)if(p[u].includes(",")){var m=p[u].split(",").map(function(f){return f.trim()}).filter(function(f){return f!==""}).map(function(f){return isNaN(Number(f))?f:Number(f)}).filter(function(f){return f!==null&&f!==""});m.length===0&&m.push("*"),m.sort(function(f,g){return f!==null&&g!==null?f-g:0}),p[u]=m.map(function(f){return f!==null?f.toString():""}).join(",");}if(p.length<5)throw new Error("Expression has only ".concat(p.length," part").concat(p.length==1?"":"s",". At least 5 parts are required."));if(p.length==5)p.unshift(""),p.push("");else if(p.length==6){var h=/\d{4}$/.test(p[5])||p[4]=="?"||p[2]=="?";h?p.unshift(""):p.push("");}else if(p.length>7)throw new Error("Expression has ".concat(p.length," parts; too many!"));return p},d.prototype.normalize=function(l){var p=this;if(l[3]=l[3].replace("?","*"),l[5]=l[5].replace("?","*"),l[2]=l[2].replace("?","*"),l[0].indexOf("0/")==0&&(l[0]=l[0].replace("0/","*/")),l[1].indexOf("0/")==0&&(l[1]=l[1].replace("0/","*/")),l[2].indexOf("0/")==0&&(l[2]=l[2].replace("0/","*/")),l[3].indexOf("1/")==0&&(l[3]=l[3].replace("1/","*/")),l[4].indexOf("1/")==0&&(l[4]=l[4].replace("1/","*/")),l[6].indexOf("1/")==0&&(l[6]=l[6].replace("1/","*/")),l[5]=l[5].replace(/(^\d)|([^#/\s]\d)/g,function(w){var b=w.replace(/\D/,""),S=b;return p.dayOfWeekStartIndexZero?b=="7"&&(S="0"):S=(parseInt(b)-1).toString(),w.replace(b,S)}),l[5]=="L"&&(l[5]="6"),l[3]=="?"&&(l[3]="*"),l[3].indexOf("W")>-1&&(l[3].indexOf(",")>-1||l[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 u={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var m in u)l[5]=l[5].replace(new RegExp(m,"gi"),u[m].toString());l[4]=l[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(w){var b=w.replace(/\D/,""),S=b;return p.monthStartIndexZero&&(S=(parseInt(b)+1).toString()),w.replace(b,S)});var h={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 f in h)l[4]=l[4].replace(new RegExp(f,"gi"),h[f].toString());l[0]=="0"&&(l[0]=""),!/\*|\-|\,|\//.test(l[2])&&(/\*|\//.test(l[1])||/\*|\//.test(l[0]))&&(l[2]+="-".concat(l[2]));for(var g=0;g<l.length;g++)if(l[g].indexOf(",")!=-1&&(l[g]=l[g].split(",").filter(function(w){return w!==""}).join(",")||"*"),l[g]=="*/1"&&(l[g]="*"),l[g].indexOf("/")>-1&&!/^\*|\-|\,/.test(l[g])){var y=null;switch(g){case 4:y="12";break;case 5:y="6";break;case 6:y="9999";break;default:y=null;break}if(y!==null){var T=l[g].split("/");l[g]="".concat(T[0],"-").concat(y,"/").concat(T[1]);}}},d.prototype.validate=function(l){var p="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(l[0],p),this.validateOnlyExpectedCharactersFound(l[1],p),this.validateOnlyExpectedCharactersFound(l[2],p),this.validateOnlyExpectedCharactersFound(l[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(l[4],p),this.validateOnlyExpectedCharactersFound(l[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(l[6],p),this.validateAnyRanges(l);},d.prototype.validateAnyRanges=function(l){a.default.secondRange(l[0]),a.default.minuteRange(l[1]),a.default.hourRange(l[2]),a.default.dayOfMonthRange(l[3]),a.default.monthRange(l[4],this.monthStartIndexZero),a.default.dayOfWeekRange(l[5],this.dayOfWeekStartIndexZero);},d.prototype.validateOnlyExpectedCharactersFound=function(l,p){var u=l.match(new RegExp("[^".concat(p,"]+"),"gi"));if(u&&u.length)throw new Error("Expression contains invalid values: '".concat(u.toString(),"'"))},d})();o.CronParser=c;}),333:((s,o,i)=>{Object.defineProperty(o,"__esModule",{value:true}),o.ExpressionDescriptor=void 0;var a=i(823),c=i(949),d=(function(){function l(p,u){if(this.expression=p,this.options=u,this.expressionParts=new Array(5),!this.options.locale&&l.defaultLocale&&(this.options.locale=l.defaultLocale),!l.locales[this.options.locale]){var m=Object.keys(l.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(m,"'.")),this.options.locale=m;}this.i18n=l.locales[this.options.locale],u.use24HourTimeFormat===void 0&&(u.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault());}return l.toString=function(p,u){var m=u===void 0?{}:u,h=m.throwExceptionOnParseError,f=h===void 0?true:h,g=m.verbose,y=g===void 0?false:g,T=m.dayOfWeekStartIndexZero,w=T===void 0?true:T,b=m.monthStartIndexZero,S=b===void 0?false:b,R=m.use24HourTimeFormat,M=m.locale,B=M===void 0?null:M,ce=m.logicalAndDayFields,le=ce===void 0?false:ce,Z={throwExceptionOnParseError:f,verbose:y,dayOfWeekStartIndexZero:w,monthStartIndexZero:S,use24HourTimeFormat:R,locale:B,logicalAndDayFields:le};Z.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Ht=new l(p,Z);return Ht.getFullDescription()},l.initialize=function(p,u){u===void 0&&(u="en"),l.specialCharacters=["/","-",",","*"],l.defaultLocale=u,p.load(l.locales);},l.prototype.getFullDescription=function(){var p,u,m="";try{var h=new c.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=h.parse(),this.expressionParts[0]==="@reboot")return ((u=(p=this.i18n).atReboot)===null||u===void 0?void 0:u.call(p))||"Run once, at startup";var f=this.getTimeOfDayDescription(),g=this.getDayOfMonthDescription(),y=this.getMonthDescription(),T=this.getDayOfWeekDescription(),w=this.getYearDescription();m+=f+g+T+y+w,m=this.transformVerbosity(m,!!this.options.verbose),m=m.charAt(0).toLocaleUpperCase()+m.substr(1);}catch(b){if(!this.options.throwExceptionOnParseError)m=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw "".concat(b)}return m},l.prototype.getTimeOfDayDescription=function(){var p=this.expressionParts[0],u=this.expressionParts[1],m=this.expressionParts[2],h="";if(!a.StringUtilities.containsAny(u,l.specialCharacters)&&!a.StringUtilities.containsAny(m,l.specialCharacters)&&!a.StringUtilities.containsAny(p,l.specialCharacters))h+=this.i18n.atSpace()+this.formatTime(m,u,p);else if(!p&&u.indexOf("-")>-1&&!(u.indexOf(",")>-1)&&!(u.indexOf("/")>-1)&&!a.StringUtilities.containsAny(m,l.specialCharacters)){var f=u.split("-");h+=a.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(m,f[0],""),this.formatTime(m,f[1],""));}else if(!p&&m.indexOf(",")>-1&&m.indexOf("-")==-1&&m.indexOf("/")==-1&&!a.StringUtilities.containsAny(u,l.specialCharacters)){var g=m.split(",");h+=this.i18n.at();for(var y=0;y<g.length;y++)h+=" ",h+=this.formatTime(g[y],u,""),y<g.length-2&&(h+=","),y==g.length-2&&(h+=this.i18n.spaceAnd());}else {var T=this.getSecondsDescription(),w=this.getMinutesDescription(),b=this.getHoursDescription();if(h+=T,h&&w&&(h+=", "),h+=w,w===b)return h;h&&b&&(h+=", "),h+=b;}return h},l.prototype.getSecondsDescription=function(){var p=this,u=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(m){return m},function(m){return a.StringUtilities.format(p.i18n.everyX0Seconds(m),m)},function(m){return p.i18n.secondsX0ThroughX1PastTheMinute()},function(m){return m=="0"?"":parseInt(m)<20?p.i18n.atX0SecondsPastTheMinute(m):p.i18n.atX0SecondsPastTheMinuteGt20()||p.i18n.atX0SecondsPastTheMinute(m)});return u},l.prototype.getMinutesDescription=function(){var p=this,u=this.expressionParts[0],m=this.expressionParts[2],h=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(f){return f},function(f){return a.StringUtilities.format(p.i18n.everyX0Minutes(f),f)},function(f){return p.i18n.minutesX0ThroughX1PastTheHour()},function(f){try{return f=="0"&&m.indexOf("/")==-1&&u==""?p.i18n.everyHour():parseInt(f)<20?p.i18n.atX0MinutesPastTheHour(f):p.i18n.atX0MinutesPastTheHourGt20()||p.i18n.atX0MinutesPastTheHour(f)}catch{return p.i18n.atX0MinutesPastTheHour(f)}});return h},l.prototype.getHoursDescription=function(){var p=this,u=this.expressionParts[2],m=0,h=[];u.split("/")[0].split(",").forEach(function(y){var T=y.split("-");T.length===2&&h.push({value:T[1],index:m+1}),m+=T.length;});var f=0,g=this.getSegmentDescription(u,this.i18n.everyHour(),function(y){var T=h.find(function(b){return b.value===y&&b.index===f}),w=T&&p.expressionParts[1]!=="0";return f++,w?p.formatTime(y,"59",""):p.formatTime(y,"0","")},function(y){return a.StringUtilities.format(p.i18n.everyX0Hours(y),y)},function(y){return p.i18n.betweenX0AndX1()},function(y){return p.i18n.atX0()});return g},l.prototype.getDayOfWeekDescription=function(){var p=this,u=this.i18n.daysOfTheWeek(),m=null;return this.expressionParts[5]=="*"?m="":m=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(h,f){var g=h;h.indexOf("#")>-1?g=h.substring(0,h.indexOf("#")):h.indexOf("L")>-1&&(g=g.replace("L",""));var y=parseInt(g),T=p.i18n.daysOfTheWeekInCase?p.i18n.daysOfTheWeekInCase(f)[y]:u[y];if(h.indexOf("#")>-1){var w=null,b=h.substring(h.indexOf("#")+1),S=h.substring(0,h.indexOf("#"));switch(b){case "1":w=p.i18n.first(S);break;case "2":w=p.i18n.second(S);break;case "3":w=p.i18n.third(S);break;case "4":w=p.i18n.fourth(S);break;case "5":w=p.i18n.fifth(S);break}T=w+" "+T;}return T},function(h){return parseInt(h)==1?"":a.StringUtilities.format(p.i18n.commaEveryX0DaysOfTheWeek(h),h)},function(h){var f=h.substring(0,h.indexOf("-")),g=p.expressionParts[3]!="*";return g?p.i18n.commaAndX0ThroughX1(f):p.i18n.commaX0ThroughX1(f)},function(h){var f=null;if(h.indexOf("#")>-1){var g=h.substring(h.indexOf("#")+1),y=h.substring(0,h.indexOf("#"));f=p.i18n.commaOnThe(g,y).trim()+p.i18n.spaceX0OfTheMonth();}else if(h.indexOf("L")>-1)f=p.i18n.commaOnTheLastX0OfTheMonth(h.replace("L",""));else {var T=p.expressionParts[3]!="*";T?p.options.logicalAndDayFields?f=p.i18n.commaOnlyOnX0(h):f=p.i18n.commaAndOnX0():f=p.i18n.commaOnlyOnX0(h);}return f}),m},l.prototype.getMonthDescription=function(){var p=this,u=this.i18n.monthsOfTheYear(),m=this.getSegmentDescription(this.expressionParts[4],"",function(h,f){return f&&p.i18n.monthsOfTheYearInCase?p.i18n.monthsOfTheYearInCase(f)[parseInt(h)-1]:u[parseInt(h)-1]},function(h){return parseInt(h)==1?"":a.StringUtilities.format(p.i18n.commaEveryX0Months(h),h)},function(h){return p.i18n.commaMonthX0ThroughMonthX1()||p.i18n.commaX0ThroughX1()},function(h){return p.i18n.commaOnlyInMonthX0?p.i18n.commaOnlyInMonthX0():p.i18n.commaOnlyInX0()});return m},l.prototype.getDayOfMonthDescription=function(){var p=this,u=null,m=this.expressionParts[3];switch(m){case "L":u=this.i18n.commaOnTheLastDayOfTheMonth();break;case "WL":case "LW":u=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var h=m.match(/(\d{1,2}W)|(W\d{1,2})/);if(h){var f=parseInt(h[0].replace("W","")),g=f==1?this.i18n.firstWeekday():a.StringUtilities.format(this.i18n.weekdayNearestDayX0(),f.toString());u=a.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),g);break}else {var y=m.match(/L-(\d{1,2})/);if(y){var T=y[1];u=a.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(T),T);break}else {if(m=="*"&&this.expressionParts[5]!="*")return "";u=this.getSegmentDescription(m,this.i18n.commaEveryDay(),function(w){return w=="L"?p.i18n.lastDay():p.i18n.dayX0?a.StringUtilities.format(p.i18n.dayX0(),w):w},function(w){return w=="1"?p.i18n.commaEveryDay():p.i18n.commaEveryX0Days(w)},function(w){return p.i18n.commaBetweenDayX0AndX1OfTheMonth(w)},function(w){return p.i18n.commaOnDayX0OfTheMonth(w)});}break}}return u},l.prototype.getYearDescription=function(){var p=this,u=this.getSegmentDescription(this.expressionParts[6],"",function(m){return /^\d+$/.test(m)?new Date(parseInt(m),1).getFullYear().toString():m},function(m){return a.StringUtilities.format(p.i18n.commaEveryX0Years(m),m)},function(m){return p.i18n.commaYearX0ThroughYearX1()||p.i18n.commaX0ThroughX1()},function(m){return p.i18n.commaOnlyInYearX0?p.i18n.commaOnlyInYearX0():p.i18n.commaOnlyInX0()});return u},l.prototype.getSegmentDescription=function(p,u,m,h,f,g){var y=null,T=p.indexOf("/")>-1,w=p.indexOf("-")>-1,b=p.indexOf(",")>-1;if(!p)y="";else if(p==="*")y=u;else if(!T&&!w&&!b)y=a.StringUtilities.format(g(p),m(p));else if(b){for(var S=p.split(","),R="",M=0;M<S.length;M++)if(M>0&&S.length>2&&(R+=",",M<S.length-1&&(R+=" ")),M>0&&S.length>1&&(M==S.length-1||S.length==2)&&(R+="".concat(this.i18n.spaceAnd()," ")),S[M].indexOf("/")>-1||S[M].indexOf("-")>-1){var B=S[M].indexOf("-")>-1&&S[M].indexOf("/")==-1,ce=this.getSegmentDescription(S[M],u,m,h,B?this.i18n.commaX0ThroughX1:f,g);B&&(ce=ce.replace(", ","")),R+=ce;}else T?R+=this.getSegmentDescription(S[M],u,m,h,f,g):R+=m(S[M]);T?y=R:y=a.StringUtilities.format(g(p),R);}else if(T){var S=p.split("/");if(y=a.StringUtilities.format(h(S[1]),S[1]),S[0].indexOf("-")>-1){var le=this.generateRangeSegmentDescription(S[0],f,m);le.indexOf(", ")!=0&&(y+=", "),y+=le;}else if(S[0].indexOf("*")==-1){var Z=a.StringUtilities.format(g(S[0]),m(S[0]));Z=Z.replace(", ",""),y+=a.StringUtilities.format(this.i18n.commaStartingX0(),Z);}}else w&&(y=this.generateRangeSegmentDescription(p,f,m));return y},l.prototype.generateRangeSegmentDescription=function(p,u,m){var h="",f=p.split("-"),g=m(f[0],1),y=m(f[1],2),T=u(p);return h+=a.StringUtilities.format(T,g,y),h},l.prototype.formatTime=function(p,u,m){var h=0,f=0,g=parseInt(p)+h,y=parseInt(u)+f;y>=60?(y-=60,g+=1):y<0&&(y+=60,g-=1),g>=24?g=g-24:g<0&&(g=24+g);var T="",w=false;this.options.use24HourTimeFormat||(w=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),T=w?"".concat(this.getPeriod(g)," "):" ".concat(this.getPeriod(g)),g>12&&(g-=12),g===0&&(g=12));var b="";return m&&(b=":".concat(("00"+m).substring(m.length))),"".concat(w?T:"").concat(("00"+g.toString()).substring(g.toString().length),":").concat(("00"+y.toString()).substring(y.toString().length)).concat(b).concat(w?"":T)},l.prototype.transformVerbosity=function(p,u){if(!u&&(p=p.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),p=p.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),p=p.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),p=p.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var m=0,h=Object.entries(this.i18n.conciseVerbosityReplacements());m<h.length;m++){var f=h[m],g=f[0],y=f[1];p=p.replace(new RegExp(g,"g"),y);}return p},l.prototype.getPeriod=function(p){return p>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},l.locales={},l})();o.ExpressionDescriptor=d;}),747:((s,o,i)=>{Object.defineProperty(o,"__esModule",{value:true}),o.enLocaleLoader=void 0;var a=i(486),c=(function(){function d(){}return d.prototype.load=function(l){l.en=new a.en;},d})();o.enLocaleLoader=c;}),486:((s,o)=>{Object.defineProperty(o,"__esModule",{value:true}),o.en=void 0;var i=(function(){function a(){}return a.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},a.prototype.atX0MinutesPastTheHourGt20=function(){return null},a.prototype.commaMonthX0ThroughMonthX1=function(){return null},a.prototype.commaYearX0ThroughYearX1=function(){return null},a.prototype.use24HourTimeFormatByDefault=function(){return false},a.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return "An error occurred when generating the expression description. Check the cron expression syntax."},a.prototype.everyMinute=function(){return "every minute"},a.prototype.everyHour=function(){return "every hour"},a.prototype.atSpace=function(){return "At "},a.prototype.everyMinuteBetweenX0AndX1=function(){return "Every minute between %s and %s"},a.prototype.at=function(){return "At"},a.prototype.spaceAnd=function(){return " and"},a.prototype.everySecond=function(){return "every second"},a.prototype.everyX0Seconds=function(){return "every %s seconds"},a.prototype.secondsX0ThroughX1PastTheMinute=function(){return "seconds %s through %s past the minute"},a.prototype.atX0SecondsPastTheMinute=function(){return "at %s seconds past the minute"},a.prototype.everyX0Minutes=function(){return "every %s minutes"},a.prototype.minutesX0ThroughX1PastTheHour=function(){return "minutes %s through %s past the hour"},a.prototype.atX0MinutesPastTheHour=function(){return "at %s minutes past the hour"},a.prototype.everyX0Hours=function(){return "every %s hours"},a.prototype.betweenX0AndX1=function(){return "between %s and %s"},a.prototype.atX0=function(){return "at %s"},a.prototype.commaEveryDay=function(){return ", every day"},a.prototype.commaEveryX0DaysOfTheWeek=function(){return ", every %s days of the week"},a.prototype.commaX0ThroughX1=function(){return ", %s through %s"},a.prototype.commaAndX0ThroughX1=function(){return ", %s through %s"},a.prototype.first=function(){return "first"},a.prototype.second=function(){return "second"},a.prototype.third=function(){return "third"},a.prototype.fourth=function(){return "fourth"},a.prototype.fifth=function(){return "fifth"},a.prototype.commaOnThe=function(){return ", on the "},a.prototype.spaceX0OfTheMonth=function(){return " %s of the month"},a.prototype.lastDay=function(){return "the last day"},a.prototype.commaOnTheLastX0OfTheMonth=function(){return ", on the last %s of the month"},a.prototype.commaOnlyOnX0=function(){return ", only on %s"},a.prototype.commaAndOnX0=function(){return ", and on %s"},a.prototype.commaEveryX0Months=function(){return ", every %s months"},a.prototype.commaOnlyInX0=function(){return ", only in %s"},a.prototype.commaOnTheLastDayOfTheMonth=function(){return ", on the last day of the month"},a.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return ", on the last weekday of the month"},a.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return ", %s days before the last day of the month"},a.prototype.firstWeekday=function(){return "first weekday"},a.prototype.weekdayNearestDayX0=function(){return "weekday nearest day %s"},a.prototype.commaOnTheX0OfTheMonth=function(){return ", on the %s of the month"},a.prototype.commaEveryX0Days=function(){return ", every %s days"},a.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return ", between day %s and %s of the month"},a.prototype.commaOnDayX0OfTheMonth=function(){return ", on day %s of the month"},a.prototype.commaEveryHour=function(){return ", every hour"},a.prototype.commaEveryX0Years=function(){return ", every %s years"},a.prototype.commaStartingX0=function(){return ", starting %s"},a.prototype.daysOfTheWeek=function(){return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},a.prototype.monthsOfTheYear=function(){return ["January","February","March","April","May","June","July","August","September","October","November","December"]},a.prototype.atReboot=function(){return "Run once, at startup"},a})();o.en=i;}),515:((s,o)=>{Object.defineProperty(o,"__esModule",{value:true});function i(c,d){if(!c)throw new Error(d)}var a=(function(){function c(){}return c.secondRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=0&&u<=59,"seconds part must be >= 0 and <= 59");}},c.minuteRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=0&&u<=59,"minutes part must be >= 0 and <= 59");}},c.hourRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=0&&u<=23,"hours part must be >= 0 and <= 23");}},c.dayOfMonthRange=function(d){for(var l=d.split(","),p=0;p<l.length;p++)if(!isNaN(parseInt(l[p],10))){var u=parseInt(l[p],10);i(u>=1&&u<=31,"DOM part must be >= 1 and <= 31");}},c.monthRange=function(d,l){for(var p=d.split(","),u=0;u<p.length;u++)if(!isNaN(parseInt(p[u],10))){var m=parseInt(p[u],10);i(m>=1&&m<=12,l?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12");}},c.dayOfWeekRange=function(d,l){for(var p=d.split(","),u=0;u<p.length;u++)if(!isNaN(parseInt(p[u],10))){var m=parseInt(p[u],10);i(m>=0&&m<=6,l?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7");}},c})();o.default=a;}),823:((s,o)=>{Object.defineProperty(o,"__esModule",{value:true}),o.StringUtilities=void 0;var i=(function(){function a(){}return a.format=function(c){for(var d=[],l=1;l<arguments.length;l++)d[l-1]=arguments[l];return c.replace(/%s/g,function(p){for(var u=[],m=1;m<arguments.length;m++)u[m-1]=arguments[m];return d.shift()})},a.containsAny=function(c,d){return d.some(function(l){return c.indexOf(l)>-1})},a})();o.StringUtilities=i;})},e={};function t(s){var o=e[s];if(o!==void 0)return o.exports;var i=e[s]={exports:{}};return n[s](i,i.exports,t),i.exports}var r={};return (()=>{var s=r;Object.defineProperty(s,"__esModule",{value:true}),s.toString=void 0;var o=t(333),i=t(747);o.ExpressionDescriptor.initialize(new i.enLocaleLoader),s.default=o.ExpressionDescriptor;var a=o.ExpressionDescriptor.toString;s.toString=a;})(),r})());});G();G();var It=class{getCwd(){switch(E.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},N=new It;G();var Dt=class{basename(e){switch(E.type){case "node":case "bun":case "deno":return it__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(E.type){case "node":case "bun":case "deno":return it__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(E.type){case "bun":case "node":case "deno":return it__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(E.type){case "bun":case "node":case "deno":return it__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new Dt;var Qt=class{async glob(...e){let t=await import('fs/promises'),r=N.getCwd(),s=x.resolve(r,e[1]?.cwd??""),o=[];for await(let i of t.glob(...e)){if(typeof i=="string"){o.push(x.resolve(s,i));continue}i.isFile()&&o.push(x.resolve(s,i.name));}return o}async mkdir(e,t){switch(E.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(E.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(E.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let o=Bun.file(e);return t?.encoding==="utf8"?o.text():new Uint8Array(await o.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}async writeFile(e,t){switch(E.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(E.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let o=await(await import('fs/promises')).stat(e);return {isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async unlink(e){switch(E.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(E.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(E.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},v=new Qt;var O=class extends Error{constructor(e){super(e);}};var js=()=>Rs__default.default({level:"info",formatters:{level:e=>({level:e})}}),q=js();var He=class extends O{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var at=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"?module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))):Lt("module").createRequire?.((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))??__filename)??Lt,pe=async n=>{let e=x.join(process.cwd(),"node_modules");if(!await v.exists(e))return n;let r=[];for(let s of n){let o=x.join(e,s);await v.exists(o)||r.push(s);}return r},U=async()=>await v.exists(x.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await v.exists(x.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await v.exists(x.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await v.exists(x.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await v.exists(x.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],I=async(n,e,t,r,s=true)=>{let o=qr__namespace.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
2
2
  ${i}
3
3
  (y/n): `;return new Promise(c=>{o.question(a,d=>{if(o.close(),d.toLowerCase()==="y"||d.toLowerCase()==="yes"){child_process.execSync(n,r),c(true);return}c(false);});})};var ct=class extends O{constructor(e){super(`Failed to convert Zod schema to JSON Schema. This usually happens when using Zod v3 schemas with Zod v4. Make sure you're importing from 'zod' (v4) and not 'zod/v3'. Original error: ${e.message}`);}};var _=class{static zodModule=null;static zodSchemaCache=new WeakSet;static load(){if(this.zodModule)return this.zodModule;try{return this.zodModule=at("zod"),this.ensureZodV4(),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
4
- Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new He;if(!("toJSONSchema"in e))throw new He}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new He;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new ct(r):r}}};var lt=class extends O{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var F=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=at("@sinclair/typebox"),this.typeboxModule}catch{throw new lt}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};var A=class{static ajv=new ajv.Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let o=this.ajv.getSchema(r);if(!o)throw new Error(`Failed to compile schema with key: ${r}`);return o}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let o=Es__default.default(e,{ajv:this.ajv.opts});return r.set(t,o),o}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,o]of Object.entries(e)){let i=Number(s),a=null;if(_.isZodSchema(o)){let c=_.toJSONSchema(o);a=this.getOrCreateSerializer(c,"fast_stringify_zod");}else F.isTypeBoxSchema(o)?a=this.getOrCreateSerializer(o,"fast_stringify_typebox"):typeof o=="object"&&o!==null&&(a=this.getOrCreateSerializer(o,"fast_stringify_json"));a&&r.set(i,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new ajv.Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var Qt=n=>{if(_.isZodSchema(n)){try{let t=_.toJSONSchema(n);A.storeJsonSchema(t,"serialize_zod"),A.getOrCompileValidator(t,"serialize_zod");}catch(t){q.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(F.isTypeBoxSchema(n)){try{A.storeJsonSchema(n,"serialize_typebox"),A.getOrCompileValidator(n,"serialize_typebox");}catch(t){q.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof n=="object"&&n!==null){try{A.storeJsonSchema(n,"serialize_json"),A.getOrCompileValidator(n,"serialize_json");}catch(t){q.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(n);try{let t={type:typeof n};A.storeJsonSchema(t,`serialize_primitive_${e}`),A.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){q.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},Er=n=>{if(_.isZodSchema(n)){try{let t=_.toJSONSchema(n);A.storeJsonSchema(t,"zod_schema"),A.getOrCompileValidator(t,"zod_schema");}catch(t){q.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(F.isTypeBoxSchema(n)){try{A.storeJsonSchema(n,"typebox_schema"),A.getOrCompileValidator(n,"typebox_schema");}catch(t){q.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof n=="object"&&n!==null){try{A.storeJsonSchema(n,"json_schema"),A.getOrCompileValidator(n,"json_schema");}catch(t){q.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(n);try{let t={type:typeof n};A.storeJsonSchema(t,`primitive_${e}`),A.getOrCompileValidator(t,`primitive_${e}`);}catch(t){q.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},Ar=(n,e)=>{n&&Er(n),e&&Er(e);},kr=n=>{if(!n||Object.keys(n).length===0)return;let e={};for(let[t,r]of Object.entries(n)){let s=Number(t);if(e[s]=r,Qt(r),_.isZodSchema(r))try{let o=_.toJSONSchema(r);A.getOrCreateSerializer(o,"fast_stringify_zod");}catch{}else F.isTypeBoxSchema(r)?A.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&A.getOrCreateSerializer(r,"fast_stringify_json");}return e};var $r=(n,e)=>async function(t,r,...s){try{let o=[t,r,...s];if(e.body){let i=t.validate(e.body,!0);o.push(i);}if(e.query){let i=t.validateQuery(e.query,!0);o.push(i);}if(e.all){let i=t.validateAll(e.all,!0);o.push(i);}return n(...o)}catch(o){return r.badRequest(o)}};var Ne=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Ut=class n{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,o,i){e=e.toUpperCase();let a=t.split("?")[0];Ar(o?.body,o?.query);let c=kr(i?.responses),d=o&&(o.body||o.query||o.all),l=d?$r(s,o):s,p=d?o:void 0,u=this.trees.get(e);u||(u=new Ne,this.trees.set(e,u));let m=a.replace(/^\/+|\/+$/g,""),h=m.length===0?[]:m.split("/"),f=true,g=[],y=u;for(let w of h){if(w==="*"){f=false,y.wildcardChild||(y.wildcardChild=new Ne),y=y.wildcardChild;break}if(w.startsWith(":")){f=false;let b=w.slice(1);g.push(b),y.paramChild||(y.paramChild={node:new Ne,name:b}),y=y.paramChild.node;continue}y.staticChildren.has(w)||y.staticChildren.set(w,new Ne),y=y.staticChildren.get(w);}if(y.middleware=r,y.handler=l,g.length>0&&(y.paramName=g.join(",")),c&&this.handlerResponseSchemas.set(s,c),f){let w="/"+m,b=`${e}:${w}`;this.staticRouteCache.set(b,{middleware:r,handler:l,params:{},responseSchemas:c});}else {let w="/"+m.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),b=`${e}:${w}`;this.staticRouteCache.delete(b);}let T=this.routes.findIndex(w=>w.method===e&&w.path===t);if(T!==-1){this.routes[T].middleware=r,this.routes[T].handler=l,this.routes[T].swaggerOptions=i,this.routes[T].responseSchemas=c,this.routes[T].validationSchemas=p;return}this.routes.push({method:e,path:t,middleware:r,handler:l,swaggerOptions:i,responseSchemas:c,validationSchemas:p});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let o=`${e}:${r}`,i=this.staticRouteCache.get(o);if(i)return i;let a=this.trees.get(e);if(!a)return null;let c=r.replace(/^\/+|\/+$/g,""),d=c.length===0?[]:c.split("/"),l={},p=a;for(let m=0;m<d.length;m++){let h=d[m];if(p.staticChildren.has(h)){p=p.staticChildren.get(h);continue}if(p.paramChild){l[p.paramChild.name]=h,p=p.paramChild.node;continue}if(p.wildcardChild){l["*"]=d.slice(m).join("/"),p=p.wildcardChild;break}return null}if(!p.handler||!p.middleware)return null;let u=this.handlerResponseSchemas.get(p.handler);return {middleware:p.middleware,handler:p.handler,params:l,responseSchemas:u}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,body:r.body,query:r.query,all:r.all,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("GET",s,p,i,u,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("POST",s,p,i,u,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("PATCH",s,p,i,u,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("PUT",s,p,i,u,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("DELETE",s,p,i,u,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("OPTIONS",s,p,i,u,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("HEAD",s,p,i,u,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],o=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new n(i,[...this.middlewares,...s]);o?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.validationSchemas,c.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}},$=new Ut;var Gt=class n{static cronstrue=null;static async getCronstrue(){return this.cronstrue||(this.cronstrue=await Promise.resolve().then(()=>Cs(_r())).catch(()=>{throw new O("cronstrue not installed as a dependency, it is required in order to consult cron jobs in UI")})),this.cronstrue}async generate(){let e=await n.getCronstrue(),t=J.scheduledJobs,r=new Set,s=new Set,i=t.map(l=>{let p=e.default.toString(l.args[0])||"-",u=l.args[2]?.timezone||"System Default";return r.add(p),s.add(u),{name:l.name,schedule:l.args[0],frequency:p,timezone:u}}).map(l=>`
4
+ Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new He;if(!("toJSONSchema"in e))throw new He}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new He;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new ct(r):r}}};var lt=class extends O{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var F=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=at("@sinclair/typebox"),this.typeboxModule}catch{throw new lt}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};var A=class{static ajv=new ajv.Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let o=this.ajv.getSchema(r);if(!o)throw new Error(`Failed to compile schema with key: ${r}`);return o}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let o=Es__default.default(e,{ajv:this.ajv.opts});return r.set(t,o),o}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,o]of Object.entries(e)){let i=Number(s),a=null;if(_.isZodSchema(o)){let c=_.toJSONSchema(o);a=this.getOrCreateSerializer(c,"fast_stringify_zod");}else F.isTypeBoxSchema(o)?a=this.getOrCreateSerializer(o,"fast_stringify_typebox"):typeof o=="object"&&o!==null&&(a=this.getOrCreateSerializer(o,"fast_stringify_json"));a&&r.set(i,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new ajv.Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var Ut=n=>{if(_.isZodSchema(n)){try{let t=_.toJSONSchema(n);A.storeJsonSchema(t,"serialize_zod"),A.getOrCompileValidator(t,"serialize_zod");}catch(t){q.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(F.isTypeBoxSchema(n)){try{A.storeJsonSchema(n,"serialize_typebox"),A.getOrCompileValidator(n,"serialize_typebox");}catch(t){q.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof n=="object"&&n!==null){try{A.storeJsonSchema(n,"serialize_json"),A.getOrCompileValidator(n,"serialize_json");}catch(t){q.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(n);try{let t={type:typeof n};A.storeJsonSchema(t,`serialize_primitive_${e}`),A.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){q.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},Er=n=>{if(_.isZodSchema(n)){try{let t=_.toJSONSchema(n);A.storeJsonSchema(t,"zod_schema"),A.getOrCompileValidator(t,"zod_schema");}catch(t){q.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(F.isTypeBoxSchema(n)){try{A.storeJsonSchema(n,"typebox_schema"),A.getOrCompileValidator(n,"typebox_schema");}catch(t){q.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof n=="object"&&n!==null){try{A.storeJsonSchema(n,"json_schema"),A.getOrCompileValidator(n,"json_schema");}catch(t){q.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(n);try{let t={type:typeof n};A.storeJsonSchema(t,`primitive_${e}`),A.getOrCompileValidator(t,`primitive_${e}`);}catch(t){q.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},Ar=(n,e)=>{n&&Er(n),e&&Er(e);},kr=n=>{if(!n||Object.keys(n).length===0)return;let e={};for(let[t,r]of Object.entries(n)){let s=Number(t);if(e[s]=r,Ut(r),_.isZodSchema(r))try{let o=_.toJSONSchema(r);A.getOrCreateSerializer(o,"fast_stringify_zod");}catch{}else F.isTypeBoxSchema(r)?A.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&A.getOrCreateSerializer(r,"fast_stringify_json");}return e};var $r=(n,e)=>async function(t,r,...s){try{let o=[t,r,...s];if(e.body){let i=t.validate(e.body,!0);o.push(i);}if(e.query){let i=t.validateQuery(e.query,!0);o.push(i);}if(e.all){let i=t.validateAll(e.all,!0);o.push(i);}return n(...o)}catch(o){return r.badRequest(o)}};var Ne=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},zt=class n{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,o,i){e=e.toUpperCase();let a=t.split("?")[0];Ar(o?.body,o?.query);let c=kr(i?.responses),d=o&&(o.body||o.query||o.all),l=d?$r(s,o):s,p=d?o:void 0,u=this.trees.get(e);u||(u=new Ne,this.trees.set(e,u));let m=a.replace(/^\/+|\/+$/g,""),h=m.length===0?[]:m.split("/"),f=true,g=[],y=u;for(let w of h){if(w==="*"){f=false,y.wildcardChild||(y.wildcardChild=new Ne),y=y.wildcardChild;break}if(w.startsWith(":")){f=false;let b=w.slice(1);g.push(b),y.paramChild||(y.paramChild={node:new Ne,name:b}),y=y.paramChild.node;continue}y.staticChildren.has(w)||y.staticChildren.set(w,new Ne),y=y.staticChildren.get(w);}if(y.middleware=r,y.handler=l,g.length>0&&(y.paramName=g.join(",")),c&&this.handlerResponseSchemas.set(s,c),f){let w="/"+m,b=`${e}:${w}`;this.staticRouteCache.set(b,{middleware:r,handler:l,params:{},responseSchemas:c});}else {let w="/"+m.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),b=`${e}:${w}`;this.staticRouteCache.delete(b);}let T=this.routes.findIndex(w=>w.method===e&&w.path===t);if(T!==-1){this.routes[T].middleware=r,this.routes[T].handler=l,this.routes[T].swaggerOptions=i,this.routes[T].responseSchemas=c,this.routes[T].validationSchemas=p;return}this.routes.push({method:e,path:t,middleware:r,handler:l,swaggerOptions:i,responseSchemas:c,validationSchemas:p});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let o=`${e}:${r}`,i=this.staticRouteCache.get(o);if(i)return i;let a=this.trees.get(e);if(!a)return null;let c=r.replace(/^\/+|\/+$/g,""),d=c.length===0?[]:c.split("/"),l={},p=a;for(let m=0;m<d.length;m++){let h=d[m];if(p.staticChildren.has(h)){p=p.staticChildren.get(h);continue}if(p.paramChild){l[p.paramChild.name]=h,p=p.paramChild.node;continue}if(p.wildcardChild){l["*"]=d.slice(m).join("/"),p=p.wildcardChild;break}return null}if(!p.handler||!p.middleware)return null;let u=this.handlerResponseSchemas.get(p.handler);return {middleware:p.middleware,handler:p.handler,params:l,responseSchemas:u}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,body:r.body,query:r.query,all:r.all,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("GET",s,p,i,u,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("POST",s,p,i,u,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("PATCH",s,p,i,u,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("PUT",s,p,i,u,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("DELETE",s,p,i,u,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("OPTIONS",s,p,i,u,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:o,handler:i,body:a,query:c,all:d,swaggerOptions:l}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...o],u={body:a,query:c,all:d};this.addOrUpdate("HEAD",s,p,i,u,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],o=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new n(i,[...this.middlewares,...s]);o?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.validationSchemas,c.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}},$=new zt;var Jt=class n{static cronstrue=null;static async getCronstrue(){return this.cronstrue||(this.cronstrue=await Promise.resolve().then(()=>Cs(_r())).catch(()=>{throw new O("cronstrue not installed as a dependency, it is required in order to consult cron jobs in UI")})),this.cronstrue}async generate(){let e=await n.getCronstrue(),t=J.scheduledJobs,r=new Set,s=new Set,i=t.map(l=>{let p=e.default.toString(l.args[0])||"-",u=l.args[2]?.timezone||"System Default";return r.add(p),s.add(u),{name:l.name,schedule:l.args[0],frequency:p,timezone:u}}).map(l=>`
5
5
  <tr data-name="${this.escapeHtml(l.name.toLowerCase())}" data-frequency="${this.escapeHtml(l.frequency)}" data-timezone="${this.escapeHtml(l.timezone)}">
6
6
  <td class="name">${this.escapeHtml(l.name)}</td>
7
7
  <td class="schedule"><code>${this.escapeHtml(l.schedule)}</code></td>
@@ -490,7 +490,7 @@ Zod is a peer dependency required when using Zod schemas for validation.`)}}stat
490
490
  })();
491
491
  </script>
492
492
  </body>
493
- </html>`}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}},Br=new Gt;var J=class{static scheduledJobs=[];static logger=q.child({scope:"CronService"});static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new O("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",o=>this.globalErrorHandler(o));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await v.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),q.error(s);});}));}},As=n=>{J.globalErrorHandler=n.bind(J);},Hr=async n=>{if(!n||n.path.length===0)throw new O("Cron UI path is required");let e=await Br.generate();$.addOrUpdate("GET",n.path,[],(t,r)=>{r.html(e);});};var ks=(n,e)=>function(t,r,s){let o=s.value,i=async(...a)=>{let c=new t.constructor;return await o.apply(c,a)};return J.register(`${t.constructor.name}.${r}`,n,i,e),s};G();var Jt=class{getCliArgs(){switch(E.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(E.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let o=t+1;o<e.length;o++)if(!e[o].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[o]))return o;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Wt=new Jt;var dt=n=>n.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),ut=n=>n.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),Nr=n=>n.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var ye=(n,e)=>{if(!n||typeof n!="string")return e;let t=n.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let o=Number.parseFloat(r[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024)}if(s){let o=Number.parseFloat(s[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024*1024)}return e};var $s=n=>{if(!n||n==="-"||n==="--")return null;let e=n.indexOf("=");if(e>0){let t=n.substring(0,e),r=n.substring(e+1);return {name:t,value:Lr(r)}}return {name:n,value:true}},Lr=n=>{if(n.toLowerCase()==="true")return true;if(n.toLowerCase()==="false")return false;let e=Number(n);return !Number.isNaN(e)&&Number.isFinite(e)?e:n},ve=()=>{let n=Wt.getCliArgs(),e=[],t={};if(!n||!n.length)return {args:e,flags:t};for(let r=0;r<n.length;r++){let s=n[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let o=$s(s);if(o){if(o.value===true&&r+1<n.length){let i=n[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(o.value=Lr(i),r++);}if(o.name in t){let i=t[o.name];Array.isArray(i)?i.push(o.value):t[o.name]=[i,o.value];}else t[o.name]=o.value;}continue}e.push(s);}}return {args:e,flags:t}};var mt=()=>Wt.getCliArgs()[0]||null;var j=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var be="VALIDATION_ERROR";var Fr=ve().args.slice(1),H=n=>(e,t)=>{let r=mt();if(!r||r!==e.commandName)return;let s=t;j.set(e,t,{type:"arg",name:s,description:n.description});let o=Fr.length?Fr.shift():n.defaultValue;if(n.required&&!o){let i=j.get(e,be);j.set(e,be,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}n.parse&&o&&(o=n.parse(o)),Object.defineProperty(e,t,{value:o,enumerable:true,configurable:true,writable:true});};var Y=n=>(e,t)=>{let r=mt();if(!r||r!==e.commandName)return;let s=n.name||t,o=ve().flags,i=n.aliases?Array.isArray(n.aliases)?n.aliases:[n.aliases]:[],a=[s,...i],c=n.defaultValue;for(let d of a){let l=[d,`-${d}`,`--${d}`];for(let p of l)if(p in o){let u=o[p];n.type==="list"?c=(Array.isArray(u)?u:[u]).map(h=>{let f=String(h);return n.parse?n.parse(f):f}):(c=u,n.type==="boolean"?c=!!c:n.type==="number"?c=Number(c):n.type==="string"&&(c=String(c)),n.parse&&(c=n.parse(c)));break}if(c!==n.defaultValue)break}if(j.set(e,t,{type:"flag",name:s,aliases:i||[],description:n.description}),n.required&&(n.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=j.get(e,be);j.set(e,be,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};Y.boolean=n=>Y({...n,type:"boolean"});Y.string=n=>Y({...n,type:"string"});Y.number=n=>Y({...n,type:"number"});Y.list=n=>Y({...n,type:"list"});Y.array=n=>Y({...n,type:"list"});var C=Y;var _s=n=>async(e,t,r)=>{for(let s of n)if(!await s.manager.canAccess(s.scope,s.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},Bs=(n,e)=>t=>{let r=j.get(t.prototype,"__class__"),s=r?.middlewares||[],o=r?.policies||[],i=j.getAll(t.prototype),a=new t;if(i){for(let[c,d]of i.entries()){if(!d.route)continue;let l=t.prototype[c].bind(a),p=n?x.join(n,d.route.path):d.route.path,u=[...o,...d.policies||[]],m=u.length>0?[_s(u)]:[],h=[...s,...m,...d.middlewares||[]];$.addOrUpdate(d.route.method,p,h,l,{service:t.name.replace(/Controller$/,""),...e,...d.documentation});}j.clear(t.prototype);}};var Hs=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"DELETE"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"DELETE"},j.set(t,r,o),s};var Ns=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"GET"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"GET"},j.set(t,r,o),s};var Ls=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"PATCH"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"PATCH"},j.set(t,r,o),s};var Fs=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"POST"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"POST"},j.set(t,r,o),s};var Is=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"PUT"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"PUT"},j.set(t,r,o),s};var Ds=n=>(e,t,r)=>{if(typeof t>"u"){let o=j.get(e.prototype,"__class__");if(o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),!n)throw new Error(`Middleware ${String(n)} not found, are you sure you defined it before using it?`);return Array.isArray(n)||(n=[n]),o.middlewares.push(...n),j.set(e.prototype,"__class__",o),e}let s=j.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(n)||(n=[n]),s.middlewares.push(...n),j.set(e,t,s),r};var ht=(n,e,t=false)=>{if(!n(e)){if(t)throw new ajv.ValidationError(n.errors||[]);return e}return e};var Ge=new WeakMap,Ir=new WeakSet,Us=n=>{let{jsonSchema:e,prefix:t}=Dr(n);try{return A.getOrCompileValidator(e,t)}catch{return null}},Dr=n=>_.isZodSchema(n)?{jsonSchema:_.toJSONSchema(n),prefix:"serialize_zod"}:F.isTypeBoxSchema(n)?{jsonSchema:n,prefix:"serialize_typebox"}:typeof n=="object"&&n!==null?{jsonSchema:n,prefix:"serialize_json"}:{jsonSchema:{type:typeof n},prefix:`serialize_primitive_${JSON.stringify(n)}`},zs=(n,e)=>(t,r,s)=>{let o=j.get(t,r)||{middlewares:[],route:{}};o.documentation||(o.documentation={}),o.documentation.responses||(o.documentation.responses={}),o.serializeOptions||(o.serializeOptions={});let i=Number(e?.status??200);o.documentation.responses[i]=n,o.serializeOptions[i]=e?.throwErrorOnValidationFail??false,j.set(t,r,o),Qt(n);let{jsonSchema:a,prefix:c}=Dr(n);A.getOrCreateSerializer(a,c);let d=Ge.get(s.value)||{};if(d[i]={name:r,schema:n,throwErrorOnValidationFail:e?.throwErrorOnValidationFail??false},Ge.set(s.value,d),!Ir.has(s.value)){let l=s.value,p=async function(...m){let h=m[1];await l.apply(this,m);let f=h.responseStatus,g=Ge.get(p),y=g?.[f]?.schema,T=g?.[f]?.throwErrorOnValidationFail??false;if(!y)return;let w=h.getBody();if(T){let b=Us(y);if(b)try{await ht(b,w,T);}catch(S){return q.error({error:S,body:w,statusCode:f,schemaDescription:typeof y=="object"&&y!==null?Object.keys(y).slice(0,5).join(", "):"unknown"},"Response validation failed in @serialize decorator"),h.status(500).json({error:"Internal Server Error",message:"Response validation failed"})}}h.json(w,y);};Ir.add(p);let u=Ge.get(l);u&&Ge.set(p,u),s.value=p;}};var we=n=>(e,t,r)=>{let s=r.value,o=j.get(e,t);return o||(o={middlewares:[],route:{}}),o.documentation||(o.documentation={}),n.body&&(o.documentation.requestBody=n.body),n.query&&(o.documentation.query=n.query),n.all&&(o.documentation.requestBody=n.all,o.documentation.query=n.all),j.set(e,t,o),r.value=async function(...i){let a=i[0],c=i[1];try{let d,l,p,u=n.throwOnValidationFail??!0;n.body&&(d=a.validate(n.body,u)),n.query&&(l=a.validateQuery(n.query,u)),n.all&&(p=a.validateAll(n.all,u));let m=[...i];return d!==void 0&&m.push(d),l!==void 0&&m.push(l),p!==void 0&&m.push(p),s.apply(this,m)}catch(d){return n.customError?c.status(n.customError.status||400).json({received:a.body,schema:n.body,error:d}):c.badRequest(d)}},r};we.query=(n,e)=>we({query:n,...e});we.body=(n,e)=>we({body:n,...e});we.all=(n,e)=>we({all:n,...e});var Gs=we;var Vt=class{logger=q.child({scope:this.constructor.name})};var Js=n=>{if(!Buffer.isBuffer(n))return n;let e=n.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},Le=class n{static subscriptions=[];static client=null;static connectionOptions={};static logger=q.child({scope:"MqttService"});static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new O("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,this.logger.info("Starting MQTT client"),this.subscriptions.length||this.logger.info("No MQTT subscriptions to register");let{host:r=process.env.MQTT_HOST||"localhost",port:s=Number(process.env.MQTT_PORT)||1883,protocol:o="mqtt",...i}=e,a=`${o}://${r}:${s}`;this.client=await t.connectAsync(a,i),this.logger.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,d)=>{this.handleMessage(c,d);}),this.client.on("disconnect",()=>{this.logger.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)this.logger.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){this.logger.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}this.logger.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let o=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${o}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(o){this.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(o);}}static globalErrorHandler(e){this.logger.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await v.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing MQTT handler: ${r}`),this.logger.error(s);});}));}subscribe(e,t){return function(r,s,o){let i=o.value;if(!i)return o;let a=async(c,d)=>{let l=new r.constructor,p=Js(d);if(i.length===1){await i.call(l,p);return}await i.call(l,c,p);};return n.register(`${r.constructor.name}.${s}`,e,a,t),o}}async unsubscribe(e){if(!n.client)throw new O("MQTT client is not connected. Call MqttService.connect() first.");if(!n.client.connected)throw new O("MQTT client is not connected. Call MqttService.connect() first.");try{await n.client.unsubscribeAsync(e),n.subscriptions=n.subscriptions.filter(t=>t.topic!==e),n.logger.debug(`Unsubscribed from topic: ${String(e)}`);}catch(t){throw n.logger.error(`Failed to unsubscribe from topic ${String(e)}: ${t.message}`),t}}async publish(e,t,r){if(!n.client)throw new O("MQTT client is not connected. Call MqttService.connect() first.");if(!n.client.connected)throw new O("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await n.client.publishAsync(e,s,r||{}),q.debug(`Published message to topic: ${String(e)}`);}catch(o){throw q.error(`Failed to publish to topic ${String(e)}: ${o.message}`),o}}static async disconnect(){if(this.client)return new Promise(e=>{let t=this.client;t?.end(false,{},()=>{q.info("MQTT client disconnected gracefully"),t?.emit("disconnect",{cmd:"disconnect"}),this.client=null,e();});})}},Ws=n=>{Le.globalErrorHandler=n.bind(Le);},Vs=new Le;var X=class extends O{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var Kt=class{randomUUID(){return crypto.randomUUID()}},ee=new Kt;var ne=class{static options={connection:{}}},Qr=n=>{ne.options=n??{connection:{}};};var Je=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),o=ee.randomUUID();return await s.add(e,t,{jobId:o,...ne.options?.defaultJobOptions,...r}),{id:o}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=ne.options??{},o=await this.getBullMQClient(),i=new o.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,i);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),r=new t.Queue(e,{...ne.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let o=await this.getQueueWithConfig(e,s),i=ee.randomUUID(),a={jobId:i,...ne.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await o.add(e,t,a),{id:i}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let o=ne.options??{},{errorHandler:i}=o,a=await this.getBullMQClient(),c={...o,...r};delete c.errorHandler,delete c.defaultJobOptions;let d=new a.Worker(e,async l=>{try{await t(l.data);}catch(p){await i?.(l,p)??Promise.reject(p);}},c);this.workers.set(s,d);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),o={...ne.options||{connection:{}},...t},i=new s.Queue(e,o);this.queues.set(r,i);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var We=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=ee.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(o=>{console.error("[MemoryPubSub] Fatal queue processing error:",o);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var te=class{static options={}},Ur=n=>{te.options=n??{};};var Ve=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let o=r||{},i=await s.send(e,t,o);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=te.options;s.errorHandler&&r.on("error",s.errorHandler);let o=await r.work(e,async i=>{let a=Array.isArray(i)?i:[i];for(let c of a)await t(c.data);});this.workers.set(e,o);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:o}=te.options,i=s??o,a=new r(i);return te.options?.errorHandler&&a.on("error",te.options.errorHandler),await a.start(),this.boss=a,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let o=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,o);let i=r||{},a=await o.send(e,t,i);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let o=te.options;o.errorHandler&&s.on("error",o.errorHandler);let i=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async c=>{let d=Array.isArray(c)?c:[c];for(let l of d)await t(l.data);});this.workers.set(i,a);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),o=r.PgBoss.default??r.PgBoss,i=new o(e.connectionString);return te.options?.errorHandler&&i.on("error",te.options.errorHandler),await i.start(),this.bossInstances.set(t,i),i}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var ue=class{static options={}},zr=n=>{ue.options=n??{};};var Ke=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:o}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new o({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:i,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=ue.options,s=await this.getSqsConsumerLib(),o={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let d=JSON.parse(c.Body||"{}");await t(d);}},i=s.Consumer.create(o),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(e,i);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=ue.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new X("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new X("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=ue.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...o}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),d=new a({...o,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await i.send(d)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=ue.options,o=await this.getSqsConsumerLib(),i=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:i,handleMessage:async l=>{let p=JSON.parse(l.Body||"{}");await t(p);}},c=o.Consumer.create(a),d=s.errorHandler;d&&(c.on("error",d),c.on("processing_error",d)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var re=class{static map=new Map;static{this.map.set("bullmq",new Je),this.map.set("sqs",new Ke),this.map.set("pgboss",new Ve),this.map.set("memory",new We);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var W=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=q.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,o){let i=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(i)&&this.logger.warn(`Queue handler for ${i} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(i,{name:e,topic:t,handler:r,provider:s,queueOptions:o});}static registerCustomQueue(e,t,r,s){let o=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(o)&&this.logger.warn(`Custom queue handler for ${o} already registered, overwriting previous handler`),this.customQueueSubscribers.set(o,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:o,provider:i,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let c=re.getProvider(i);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,o,a):await c.subscribe(s,o);}for(let{topic:r,handler:s,pubsub:o}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await o.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let o=await v.glob(s,{cwd:N.getCwd()});this.logger.info(`Pattern "${s}" matched ${o.length} file(s)`),r.push(...o);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(o=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(o),t.throwOnError)throw o});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var ft=new WeakMap,Se=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=re.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}async unsubscribe(){await re.getProvider(this.provider).unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,o,i){let a=i.value,c=async d=>{let l=ft.get(s.constructor);return l||(l=W.instanceFactory(s.constructor),ft.set(s.constructor,l)),a.apply(l,[d])};return W.registerTypedQueue(`${s.constructor.name}.${String(o)}`,e,c,t,r),i}}async subscribeWithCallback(e){let t=re.getProvider(this.provider);if(this.queueOptions){await t.subscribeWithConfig(this.topic,e,this.queueOptions);return}await t.subscribe(this.topic,e);}},gt=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}async unsubscribe(){await this.pubsub.unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,o){let i=o.value,a=async c=>{let d=ft.get(r.constructor);return d||(d=W.instanceFactory(r.constructor),ft.set(r.constructor,d)),i.apply(d,[c])};return W.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),o}}};function Ks(n,e){return new Se(n,"sqs",e)}function Xs(n,e){return new Se(n,"bullmq",e)}function Zs(n,e){return new Se(n,"pgboss",e)}function Xt(n){return new Se(n,"memory")}function Ys(n,e){return new gt(n,e)}var eo=n=>{let e=["bullmq","pgboss","sqs"];n.bullmq&&Qr(n.bullmq),n.pgboss&&Ur(n.pgboss),n.sqs&&zr(n.sqs);for(let t of Object.keys(n)){let r=t;e.includes(r)||re.setProvider(r,n[r]);}};G();var Zt=class{exit(e){switch(E.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${E.type}`)}}},Fe=new Zt;var k=class{static flagsAndArgs={flags:ve().flags,args:ve().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=q.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(d=>t.includes(d)))return;let s=this.commandName,o=this.description||"No description available",i=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:o,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(c),Fe.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:o,options:i,args:a,flags:c}=e,d={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},l=[`${d.title}${r}${d.reset}`,`${d.description}${s}${d.reset}`,"",`${d.subtitle}Usage:${d.reset}`,` ${d.code}${r}${d.reset} [options] [arguments]`,"",`${d.subtitle}Options:${d.reset}`,` ${d.flag}-h, --help${d.reset} Show this help message`,"",`${d.subtitle}Command Options:${d.reset}`,` ${d.flag}keepAlive${d.reset} ${i?.keepAlive??false?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,` ${d.flag}loggerPath${d.reset} ${i?.loggerPath??"src/logger.ts"}`,` ${d.flag}allowUnknownFlags${d.reset} ${i?.allowUnknownFlags??true?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,""];if(o){let h=Array.isArray(o)?o:[o];l.push(`${d.subtitle}Help:${d.reset}`),h.forEach(f=>{l.push(` ${d.description}${f}${d.reset}`);}),l.push("");}let p=j.getAll(t),u=p?Array.from(p.values()).filter(h=>h.type==="arg"):[],m=p?Array.from(p.values()).filter(h=>h.type==="flag"):[];return u.length&&(l.push(`${d.subtitle}Available Arguments:${d.reset}`),u.forEach(h=>{let f=h.required?` ${d.error}(required)${d.reset}`:"",g=h.description?` ${d.description}${h.description}${d.reset}`:"";l.push(` ${d.code}${h.name}${d.reset}${f}${g}`);}),l.push("")),m.length&&(l.push(`${d.subtitle}Available Flags:${d.reset}`),m.forEach(h=>{h.aliases&&!Array.isArray(h.aliases)&&(h.aliases=[h.aliases]);let f=h.aliases.length?` ${d.flag}(${h.aliases.join(", ")})${d.reset}`:"",g=h.required?` ${d.error}(required)${d.reset}`:"",y=h.description?` ${d.description}${h.description}${d.reset}`:"";l.push(` ${d.flag}--${h.name}${f}${d.reset}${g}${y}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${d.subtitle}Current Context:${d.reset}`),a?.length&&l.push(` ${d.info}Provided Arguments:${d.reset} ${d.code}${a.join(" ")}${d.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${d.info}Provided Flags:${d.reset}`),Object.keys(c).forEach(h=>{let f=c[h],g=f!=null?` = ${d.code}${f}${d.reset}`:"";l.push(` ${d.flag}${h}${d.reset}${g}`);})),l.push("")),o&&(Array.isArray(o)?o.some(h=>h.includes("example")):o.includes("example"))&&(l.push(`${d.subtitle}Examples:${d.reset}`),(Array.isArray(o)?o.filter(f=>f.includes("example")):[o.split("example")[1].trim()]).forEach(f=>{l.push(` ${d.code}${f}${d.reset}`);}),l.push("")),l.join(`
493
+ </html>`}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}},Br=new Jt;var J=class{static scheduledJobs=[];static logger=q.child({scope:"CronService"});static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new O("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",o=>this.globalErrorHandler(o));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await v.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),q.error(s);});}));}},As=n=>{J.globalErrorHandler=n.bind(J);},Hr=async n=>{if(!n||n.path.length===0)throw new O("Cron UI path is required");let e=await Br.generate();$.addOrUpdate("GET",n.path,[],(t,r)=>{r.html(e);});};var ks=(n,e)=>function(t,r,s){let o=s.value,i=async(...a)=>{let c=new t.constructor;return await o.apply(c,a)};return J.register(`${t.constructor.name}.${r}`,n,i,e),s};G();var Wt=class{getCliArgs(){switch(E.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(E.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let o=t+1;o<e.length;o++)if(!e[o].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[o]))return o;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Vt=new Wt;var dt=n=>n.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),ut=n=>n.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),Nr=n=>n.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var ye=(n,e)=>{if(!n||typeof n!="string")return e;let t=n.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let o=Number.parseFloat(r[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024)}if(s){let o=Number.parseFloat(s[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024*1024)}return e};var $s=n=>{if(!n||n==="-"||n==="--")return null;let e=n.indexOf("=");if(e>0){let t=n.substring(0,e),r=n.substring(e+1);return {name:t,value:Lr(r)}}return {name:n,value:true}},Lr=n=>{if(n.toLowerCase()==="true")return true;if(n.toLowerCase()==="false")return false;let e=Number(n);return !Number.isNaN(e)&&Number.isFinite(e)?e:n},ve=()=>{let n=Vt.getCliArgs(),e=[],t={};if(!n||!n.length)return {args:e,flags:t};for(let r=0;r<n.length;r++){let s=n[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let o=$s(s);if(o){if(o.value===true&&r+1<n.length){let i=n[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(o.value=Lr(i),r++);}if(o.name in t){let i=t[o.name];Array.isArray(i)?i.push(o.value):t[o.name]=[i,o.value];}else t[o.name]=o.value;}continue}e.push(s);}}return {args:e,flags:t}};var mt=()=>Vt.getCliArgs()[0]||null;var j=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var be="VALIDATION_ERROR";var Fr=ve().args.slice(1),H=n=>(e,t)=>{let r=mt();if(!r||r!==e.commandName)return;let s=t;j.set(e,t,{type:"arg",name:s,description:n.description});let o=Fr.length?Fr.shift():n.defaultValue;if(n.required&&!o){let i=j.get(e,be);j.set(e,be,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}n.parse&&o&&(o=n.parse(o)),Object.defineProperty(e,t,{value:o,enumerable:true,configurable:true,writable:true});};var Y=n=>(e,t)=>{let r=mt();if(!r||r!==e.commandName)return;let s=n.name||t,o=ve().flags,i=n.aliases?Array.isArray(n.aliases)?n.aliases:[n.aliases]:[],a=[s,...i],c=n.defaultValue;for(let d of a){let l=[d,`-${d}`,`--${d}`];for(let p of l)if(p in o){let u=o[p];n.type==="list"?c=(Array.isArray(u)?u:[u]).map(h=>{let f=String(h);return n.parse?n.parse(f):f}):(c=u,n.type==="boolean"?c=!!c:n.type==="number"?c=Number(c):n.type==="string"&&(c=String(c)),n.parse&&(c=n.parse(c)));break}if(c!==n.defaultValue)break}if(j.set(e,t,{type:"flag",name:s,aliases:i||[],description:n.description}),n.required&&(n.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=j.get(e,be);j.set(e,be,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};Y.boolean=n=>Y({...n,type:"boolean"});Y.string=n=>Y({...n,type:"string"});Y.number=n=>Y({...n,type:"number"});Y.list=n=>Y({...n,type:"list"});Y.array=n=>Y({...n,type:"list"});var C=Y;var _s=n=>async(e,t,r)=>{for(let s of n)if(!await s.manager.canAccess(s.scope,s.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},Bs=(n,e)=>t=>{let r=j.get(t.prototype,"__class__"),s=r?.middlewares||[],o=r?.policies||[],i=j.getAll(t.prototype),a=new t;if(i){for(let[c,d]of i.entries()){if(!d.route)continue;let l=t.prototype[c].bind(a),p=n?x.join(n,d.route.path):d.route.path,u=[...o,...d.policies||[]],m=u.length>0?[_s(u)]:[],h=[...s,...m,...d.middlewares||[]];$.addOrUpdate(d.route.method,p,h,l,{service:t.name.replace(/Controller$/,""),...e,...d.documentation});}j.clear(t.prototype);}};var Hs=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"DELETE"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"DELETE"},j.set(t,r,o),s};var Ns=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"GET"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"GET"},j.set(t,r,o),s};var Ls=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"PATCH"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"PATCH"},j.set(t,r,o),s};var Fs=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"POST"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"POST"},j.set(t,r,o),s};var Is=(n,e)=>(t,r,s)=>{let o=j.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"PUT"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"PUT"},j.set(t,r,o),s};var Ds=n=>(e,t,r)=>{if(typeof t>"u"){let o=j.get(e.prototype,"__class__");if(o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),!n)throw new Error(`Middleware ${String(n)} not found, are you sure you defined it before using it?`);return Array.isArray(n)||(n=[n]),o.middlewares.push(...n),j.set(e.prototype,"__class__",o),e}let s=j.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(n)||(n=[n]),s.middlewares.push(...n),j.set(e,t,s),r};var ht=(n,e,t=false)=>{if(!n(e)){if(t)throw new ajv.ValidationError(n.errors||[]);return e}return e};var Ge=new WeakMap,Ir=new WeakSet,Us=n=>{let{jsonSchema:e,prefix:t}=Dr(n);try{return A.getOrCompileValidator(e,t)}catch{return null}},Dr=n=>_.isZodSchema(n)?{jsonSchema:_.toJSONSchema(n),prefix:"serialize_zod"}:F.isTypeBoxSchema(n)?{jsonSchema:n,prefix:"serialize_typebox"}:typeof n=="object"&&n!==null?{jsonSchema:n,prefix:"serialize_json"}:{jsonSchema:{type:typeof n},prefix:`serialize_primitive_${JSON.stringify(n)}`},zs=(n,e)=>(t,r,s)=>{let o=j.get(t,r)||{middlewares:[],route:{}};o.documentation||(o.documentation={}),o.documentation.responses||(o.documentation.responses={}),o.serializeOptions||(o.serializeOptions={});let i=Number(e?.status??200);o.documentation.responses[i]=n,o.serializeOptions[i]=e?.throwErrorOnValidationFail??false,j.set(t,r,o),Ut(n);let{jsonSchema:a,prefix:c}=Dr(n);A.getOrCreateSerializer(a,c);let d=Ge.get(s.value)||{};if(d[i]={name:r,schema:n,throwErrorOnValidationFail:e?.throwErrorOnValidationFail??false},Ge.set(s.value,d),!Ir.has(s.value)){let l=s.value,p=async function(...m){let h=m[1];await l.apply(this,m);let f=h.responseStatus,g=Ge.get(p),y=g?.[f]?.schema,T=g?.[f]?.throwErrorOnValidationFail??false;if(!y)return;let w=h.getBody();if(T){let b=Us(y);if(b)try{await ht(b,w,T);}catch(S){return q.error({error:S,body:w,statusCode:f,schemaDescription:typeof y=="object"&&y!==null?Object.keys(y).slice(0,5).join(", "):"unknown"},"Response validation failed in @serialize decorator"),h.status(500).json({error:"Internal Server Error",message:"Response validation failed"})}}h.json(w,y);};Ir.add(p);let u=Ge.get(l);u&&Ge.set(p,u),s.value=p;}};var we=n=>(e,t,r)=>{let s=r.value,o=j.get(e,t);return o||(o={middlewares:[],route:{}}),o.documentation||(o.documentation={}),n.body&&(o.documentation.requestBody=n.body),n.query&&(o.documentation.query=n.query),n.all&&(o.documentation.requestBody=n.all,o.documentation.query=n.all),j.set(e,t,o),r.value=async function(...i){let a=i[0],c=i[1];try{let d,l,p,u=n.throwOnValidationFail??!0;n.body&&(d=a.validate(n.body,u)),n.query&&(l=a.validateQuery(n.query,u)),n.all&&(p=a.validateAll(n.all,u));let m=[...i];return d!==void 0&&m.push(d),l!==void 0&&m.push(l),p!==void 0&&m.push(p),s.apply(this,m)}catch(d){return n.customError?c.status(n.customError.status||400).json({received:a.body,schema:n.body,error:d}):c.badRequest(d)}},r};we.query=(n,e)=>we({query:n,...e});we.body=(n,e)=>we({body:n,...e});we.all=(n,e)=>we({all:n,...e});var Gs=we;var Kt=class{logger=q.child({scope:this.constructor.name})};var Js=n=>{if(!Buffer.isBuffer(n))return n;let e=n.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},Le=class n{static subscriptions=[];static client=null;static connectionOptions={};static logger=q.child({scope:"MqttService"});static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new O("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,this.logger.info("Starting MQTT client"),this.subscriptions.length||this.logger.info("No MQTT subscriptions to register");let{host:r=process.env.MQTT_HOST||"localhost",port:s=Number(process.env.MQTT_PORT)||1883,protocol:o="mqtt",...i}=e,a=`${o}://${r}:${s}`;this.client=await t.connectAsync(a,i),this.logger.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,d)=>{this.handleMessage(c,d);}),this.client.on("disconnect",()=>{this.logger.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)this.logger.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){this.logger.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}this.logger.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let o=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${o}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(o){this.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(o);}}static globalErrorHandler(e){this.logger.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await v.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing MQTT handler: ${r}`),this.logger.error(s);});}));}subscribe(e,t){return function(r,s,o){let i=o.value;if(!i)return o;let a=async(c,d)=>{let l=new r.constructor,p=Js(d);if(i.length===1){await i.call(l,p);return}await i.call(l,c,p);};return n.register(`${r.constructor.name}.${s}`,e,a,t),o}}async unsubscribe(e){if(!n.client)throw new O("MQTT client is not connected. Call MqttService.connect() first.");if(!n.client.connected)throw new O("MQTT client is not connected. Call MqttService.connect() first.");try{await n.client.unsubscribeAsync(e),n.subscriptions=n.subscriptions.filter(t=>t.topic!==e),n.logger.debug(`Unsubscribed from topic: ${String(e)}`);}catch(t){throw n.logger.error(`Failed to unsubscribe from topic ${String(e)}: ${t.message}`),t}}async publish(e,t,r){if(!n.client)throw new O("MQTT client is not connected. Call MqttService.connect() first.");if(!n.client.connected)throw new O("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await n.client.publishAsync(e,s,r||{}),q.debug(`Published message to topic: ${String(e)}`);}catch(o){throw q.error(`Failed to publish to topic ${String(e)}: ${o.message}`),o}}static async disconnect(){if(this.client)return new Promise(e=>{let t=this.client;t?.end(false,{},()=>{q.info("MQTT client disconnected gracefully"),t?.emit("disconnect",{cmd:"disconnect"}),this.client=null,e();});})}},Ws=n=>{Le.globalErrorHandler=n.bind(Le);},Vs=new Le;var X=class extends O{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var Xt=class{randomUUID(){return crypto.randomUUID()}},ee=new Xt;var ne=class{static options={connection:{}}},Qr=n=>{ne.options=n??{connection:{}};};var Je=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),o=ee.randomUUID();return await s.add(e,t,{jobId:o,...ne.options?.defaultJobOptions,...r}),{id:o}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=ne.options??{},o=await this.getBullMQClient(),i=new o.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,i);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),r=new t.Queue(e,{...ne.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let o=await this.getQueueWithConfig(e,s),i=ee.randomUUID(),a={jobId:i,...ne.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await o.add(e,t,a),{id:i}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let o=ne.options??{},{errorHandler:i}=o,a=await this.getBullMQClient(),c={...o,...r};delete c.errorHandler,delete c.defaultJobOptions;let d=new a.Worker(e,async l=>{try{await t(l.data);}catch(p){await i?.(l,p)??Promise.reject(p);}},c);this.workers.set(s,d);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new X("bullmq","ioredis")}),o={...ne.options||{connection:{}},...t},i=new s.Queue(e,o);this.queues.set(r,i);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var We=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=ee.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(o=>{console.error("[MemoryPubSub] Fatal queue processing error:",o);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var te=class{static options={}},Ur=n=>{te.options=n??{};};var Ve=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let o=r||{},i=await s.send(e,t,o);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=te.options;s.errorHandler&&r.on("error",s.errorHandler);let o=await r.work(e,async i=>{let a=Array.isArray(i)?i:[i];for(let c of a)await t(c.data);});this.workers.set(e,o);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:o}=te.options,i=s??o,a=new r(i);return te.options?.errorHandler&&a.on("error",te.options.errorHandler),await a.start(),this.boss=a,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let o=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,o);let i=r||{},a=await o.send(e,t,i);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let o=te.options;o.errorHandler&&s.on("error",o.errorHandler);let i=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async c=>{let d=Array.isArray(c)?c:[c];for(let l of d)await t(l.data);});this.workers.set(i,a);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new X("pg-boss","pg")}),o=r.PgBoss.default??r.PgBoss,i=new o(e.connectionString);return te.options?.errorHandler&&i.on("error",te.options.errorHandler),await i.start(),this.bossInstances.set(t,i),i}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var ue=class{static options={}},zr=n=>{ue.options=n??{};};var Ke=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:o}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new o({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:i,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=ue.options,s=await this.getSqsConsumerLib(),o={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let d=JSON.parse(c.Body||"{}");await t(d);}},i=s.Consumer.create(o),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(e,i);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=ue.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new X("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new X("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=ue.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...o}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),d=new a({...o,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await i.send(d)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=ue.options,o=await this.getSqsConsumerLib(),i=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:i,handleMessage:async l=>{let p=JSON.parse(l.Body||"{}");await t(p);}},c=o.Consumer.create(a),d=s.errorHandler;d&&(c.on("error",d),c.on("processing_error",d)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var re=class{static map=new Map;static{this.map.set("bullmq",new Je),this.map.set("sqs",new Ke),this.map.set("pgboss",new Ve),this.map.set("memory",new We);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var W=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=q.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,o){let i=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(i)&&this.logger.warn(`Queue handler for ${i} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(i,{name:e,topic:t,handler:r,provider:s,queueOptions:o});}static registerCustomQueue(e,t,r,s){let o=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(o)&&this.logger.warn(`Custom queue handler for ${o} already registered, overwriting previous handler`),this.customQueueSubscribers.set(o,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:o,provider:i,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let c=re.getProvider(i);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,o,a):await c.subscribe(s,o);}for(let{topic:r,handler:s,pubsub:o}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await o.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let o=await v.glob(s,{cwd:N.getCwd()});this.logger.info(`Pattern "${s}" matched ${o.length} file(s)`),r.push(...o);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(o=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(o),t.throwOnError)throw o});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var ft=new WeakMap,Se=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=re.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}async unsubscribe(){await re.getProvider(this.provider).unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,o,i){let a=i.value,c=async d=>{let l=ft.get(s.constructor);return l||(l=W.instanceFactory(s.constructor),ft.set(s.constructor,l)),a.apply(l,[d])};return W.registerTypedQueue(`${s.constructor.name}.${String(o)}`,e,c,t,r),i}}async subscribeWithCallback(e){let t=re.getProvider(this.provider);if(this.queueOptions){await t.subscribeWithConfig(this.topic,e,this.queueOptions);return}await t.subscribe(this.topic,e);}},gt=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}async unsubscribe(){await this.pubsub.unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,o){let i=o.value,a=async c=>{let d=ft.get(r.constructor);return d||(d=W.instanceFactory(r.constructor),ft.set(r.constructor,d)),i.apply(d,[c])};return W.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),o}}};function Ks(n,e){return new Se(n,"sqs",e)}function Xs(n,e){return new Se(n,"bullmq",e)}function Zs(n,e){return new Se(n,"pgboss",e)}function Zt(n){return new Se(n,"memory")}function Ys(n,e){return new gt(n,e)}var eo=n=>{let e=["bullmq","pgboss","sqs"];n.bullmq&&Qr(n.bullmq),n.pgboss&&Ur(n.pgboss),n.sqs&&zr(n.sqs);for(let t of Object.keys(n)){let r=t;e.includes(r)||re.setProvider(r,n[r]);}};G();var Yt=class{exit(e){switch(E.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${E.type}`)}}},Fe=new Yt;var k=class{static flagsAndArgs={flags:ve().flags,args:ve().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=q.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(d=>t.includes(d)))return;let s=this.commandName,o=this.description||"No description available",i=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:o,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(c),Fe.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:o,options:i,args:a,flags:c}=e,d={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},l=[`${d.title}${r}${d.reset}`,`${d.description}${s}${d.reset}`,"",`${d.subtitle}Usage:${d.reset}`,` ${d.code}${r}${d.reset} [options] [arguments]`,"",`${d.subtitle}Options:${d.reset}`,` ${d.flag}-h, --help${d.reset} Show this help message`,"",`${d.subtitle}Command Options:${d.reset}`,` ${d.flag}keepAlive${d.reset} ${i?.keepAlive??false?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,` ${d.flag}loggerPath${d.reset} ${i?.loggerPath??"src/logger.ts"}`,` ${d.flag}allowUnknownFlags${d.reset} ${i?.allowUnknownFlags??true?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,""];if(o){let h=Array.isArray(o)?o:[o];l.push(`${d.subtitle}Help:${d.reset}`),h.forEach(f=>{l.push(` ${d.description}${f}${d.reset}`);}),l.push("");}let p=j.getAll(t),u=p?Array.from(p.values()).filter(h=>h.type==="arg"):[],m=p?Array.from(p.values()).filter(h=>h.type==="flag"):[];return u.length&&(l.push(`${d.subtitle}Available Arguments:${d.reset}`),u.forEach(h=>{let f=h.required?` ${d.error}(required)${d.reset}`:"",g=h.description?` ${d.description}${h.description}${d.reset}`:"";l.push(` ${d.code}${h.name}${d.reset}${f}${g}`);}),l.push("")),m.length&&(l.push(`${d.subtitle}Available Flags:${d.reset}`),m.forEach(h=>{h.aliases&&!Array.isArray(h.aliases)&&(h.aliases=[h.aliases]);let f=h.aliases.length?` ${d.flag}(${h.aliases.join(", ")})${d.reset}`:"",g=h.required?` ${d.error}(required)${d.reset}`:"",y=h.description?` ${d.description}${h.description}${d.reset}`:"";l.push(` ${d.flag}--${h.name}${f}${d.reset}${g}${y}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${d.subtitle}Current Context:${d.reset}`),a?.length&&l.push(` ${d.info}Provided Arguments:${d.reset} ${d.code}${a.join(" ")}${d.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${d.info}Provided Flags:${d.reset}`),Object.keys(c).forEach(h=>{let f=c[h],g=f!=null?` = ${d.code}${f}${d.reset}`:"";l.push(` ${d.flag}${h}${d.reset}${g}`);})),l.push("")),o&&(Array.isArray(o)?o.some(h=>h.includes("example")):o.includes("example"))&&(l.push(`${d.subtitle}Examples:${d.reset}`),(Array.isArray(o)?o.filter(f=>f.includes("example")):[o.split("example")[1].trim()]).forEach(f=>{l.push(` ${d.code}${f}${d.reset}`);}),l.push("")),l.join(`
494
494
  `)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=j.getAll(e);if(s){for(let i of s.values())if(i.type==="flag"&&(r.add(`--${i.name}`),r.add(`-${i.name}`),r.add(i.name),i.aliases)){let a=Array.isArray(i.aliases)?i.aliases:[i.aliases];for(let c of a)r.add(`--${c}`),r.add(`-${c}`),r.add(c);}}let o=Object.keys(e.flags).filter(i=>!t.has(i)&&!r.has(i));if(o.length){let i={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${i.title}\u274C Unknown Flags:${i.reset}`),console.error(""),o.forEach(a=>{console.error(` ${i.error}\u2022${i.reset} ${i.flag}${a}${i.reset}`);}),console.error(""),console.error(`${i.info}\u{1F4A1} Tip: Use --help for available flags${i.reset}`),Fe.exit(1);}};static validateContext=e=>{let t=Array.from(j.get(e,be)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,o)=>{let i=`${r.info}${o+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,c=`${r.code}${s.name}${r.reset}`;console.error(` ${i} ${a} ${c}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Fe.exit(1);}}};var V=class extends k{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,c,d]=await U();await I(`${a} ${c} esbuild ${d}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=it__default.default.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(c=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Xe__default.default.existsSync(r)||Xe__default.default.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Xe__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Xe__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let o=it__default.default.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:o,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});i.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:i.errors},null,2)),process.exit(1)),i.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:i.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${o}`,output:o,assets:!!this.assets},null,2)),process.exit(0);}};P([C({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],V,"clearDist"),P([C({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],V,"entry"),P([C({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],V,"output"),P([C({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],V,"tsconfig"),P([C({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],V,"assets"),P([C({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],V,"format"),P([C({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],V,"packages"),P([C({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],V,"sourcemap");var xe=class extends k{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await J.massiveImportCronJobs(e);let t=J.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),J.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};P([H({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],xe,"pattern"),P([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],xe,"additionalPatterns");var Ie=class extends k{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(Te.getCommand(this.name)){let s=Te.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=x.join(this.path,`${this.name}.ts`),await v.exists(x.join(process.cwd(),this.path))||await v.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
495
495
 
496
496
  export default class extends Command {
@@ -680,8 +680,10 @@ server.listen(({ url }) => {
680
680
  // The GraphQL endpoint is automatically available at /graphql
681
681
  // You can extend the schema using server.graphql.addTypeDef() and server.graphql.addResolver()
682
682
  `}static getLoggerTemplate(){return `import pino from "pino";
683
+ import { CommandRegistry } from "../command_registry.js";
683
684
 
684
685
  export const logger = pino({ level: "info" });
686
+ CommandRegistry.setLogger(logger);
685
687
  `}};P([C.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],ie,"srcPath"),P([C.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],ie,"typescript"),P([C.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],ie,"mqtt"),P([C.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],ie,"cron"),P([C.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],ie,"graphql");var qe=class extends k{static commandName="init-mailer";static description="Initialize mailer configuration with required dependencies";static help=["Initialize a mailer configuration file with basic setup","Automatically installs required packages for nodemailer and optional template engines","Supports Handlebars, EJS, Edge.js, Mustache, or custom adapters","Example: npx balda init-mailer -t handlebars -o src/mailer"];static templateEngine;static outputPath;static mailerDependencies={base:["nodemailer","@types/nodemailer"],handlebars:["handlebars","@types/handlebars"],ejs:["ejs","@types/ejs"],edge:["edge.js"],mustache:["mustache","@types/mustache"]};static async handle(){if(this.logger.info("Initializing mailer configuration..."),!["handlebars","ejs","edge","mustache","custom","none"].includes(this.templateEngine)){this.logger.error(`Invalid template engine: ${this.templateEngine}. Must be one of: handlebars, ejs, edge, mustache, custom, none`);return}let[e,t]=await U();if(["npm","yarn","pnpm"].includes(e)){let i=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],a=await pe(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for mailer`),!await I(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Mailer initialization aborted.");return}a.length===0&&this.logger.info("All mailer dependencies are already installed");}let r=this.getConfigTemplate(),s="mailer.config.ts",o=x.join(this.outputPath,s);await v.exists(this.outputPath)||await v.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await v.writeFile(o,new TextEncoder().encode(r)),this.logger.info(`Mailer configuration initialized successfully at ${o}`),this.logger.info("Remember to update the configuration with your actual SMTP credentials"),this.templateEngine!=="none"&&this.logger.info(`Template engine '${this.templateEngine}' configured and ready to use`);}static getConfigTemplate(){let e=this.templateEngine!=="none";return `import { createTransport } from "nodemailer";
686
688
  import { Mailer${e?`, ${this.getAdapterImport()}`:""} } from "balda";
687
689
 
@@ -1079,16 +1081,16 @@ export const storage = new Storage(
1079
1081
  defaultProvider: "local",
1080
1082
  },
1081
1083
  );
1082
- `}[e]||""}};P([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],ke,"storageType"),P([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],ke,"outputPath");var no=[je,Ie,Oe,Re,me,Pe,Ce,Q,ie,qe,Me,Ze,V,Ae,ke,De,Ee,xe],er=class n{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=q.child({scope:"CommandRegistry"});static setLogger(e){n.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||n.loggerPath;try{let r=await import(x.join(N.getCwd(),t));r.logger&&n.setLogger(r.logger);}catch{n.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new n}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){n.logger.info(`Loading commands from ${e}`);let t=await v.glob(e,{cwd:N.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{n.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let s=await import(r).then(o=>o.default?o.default:o).catch(o=>(n.logger.error(`Error loading command ${r}: ${o}`),null));s&&this.commands.set(s.commandName,s);}for(let r of no)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Te=er.getInstance();G();var Qe=class{get(e){switch(E.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${E.type}`)}}getEnvironment(){switch(E.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var io=new Qe,L=n=>{let e=io.get("NODE_ENV")!=="production";return {code:n.name||"INTERNAL_ERROR",message:n.message,...e&&{stack:n.stack,cause:n.cause}}};var Ue=class extends O{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var z=class extends O{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var se=class{schemaOptions;apolloOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.apolloOptions=t.apolloOptions,this.isEnabled=t.isEnabled;}getSchemaOptions(){return this.schemaOptions}getApolloOptions(){return this.apolloOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},apolloOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),apolloOptions:this.resolveApolloOptions(e.apolloOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveApolloOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var he=async(n,e,t,r)=>{let s=n.length;if(s===0){let a=await e(t,r);return a&&r.send(a),r}let o=0,i=async()=>{if(o>=s){let d=await e(t,r);return d&&r.send(d),r}let a=o++,c=n[a];await c(t,r,i);};return await i(),r},ao=new Set(["post","put","patch"]),ae=n=>n?ao.has(n.toLowerCase()):true,vt=async(n,e,t,r,s)=>{try{let{HeaderMap:o}=await import('@apollo/server'),i=new o;e.headers.forEach((h,f)=>{i.set(f,h);});let c=(e.headers.get("content-type")??"").includes("application/json"),d="";if(t!=="GET"){let h=await e.text();d=c&&h?JSON.parse(h):h;}let l={method:t.toUpperCase(),headers:i,body:d,search:r?`?${r}`:""},p=await n.executeHTTPGraphQLRequest({httpGraphQLRequest:l,context:async()=>s}),u={};for(let[h,f]of p.headers)u[h]=f;if(p.body.kind==="complete")return new globalThis.Response(p.body.string,{status:p.status??200,headers:u});let m=new ReadableStream({async start(h){if(p.body.kind==="chunked")for await(let f of p.body.asyncIterator)h.enqueue(new TextEncoder().encode(f));h.close();}});return new globalThis.Response(m,{status:p.status??200,headers:u})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},Jr=async(n,e,t,r,s,o,i)=>{try{let{HeaderMap:a}=await import('@apollo/server'),c=new a;for(let[f,g]of Object.entries(e))g!==void 0&&c.set(f,Array.isArray(g)?g.join(", "):g);let p=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,u={method:t?.toUpperCase()??"POST",headers:c,body:p,search:s?`?${s}`:""},m=await n.executeHTTPGraphQLRequest({httpGraphQLRequest:u,context:async()=>o}),h=m.status??200;m.body.kind==="complete"?await i(m.headers,h,m.body.string):await i(m.headers,h,m.body.asyncIterator);}catch{await i(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},fe=n=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(o=>setTimeout(o,10));},s=async()=>{try{let{ApolloServer:o}=await import('@apollo/server'),{makeExecutableSchema:i}=await import('@graphql-tools/schema'),a=n.getSchemaOptions(),c=n.getApolloOptions(),d=i({typeDefs:a.typeDefs,resolvers:a.resolvers}),l=new o({schema:d,...c});return await l.start(),{server:l,url:"/graphql"}}catch(o){throw o instanceof Error&&(o.message.includes("Cannot find module")||o.message.includes("Cannot find package"))?new Error("GraphQL is enabled but '@apollo/server' is not installed. Install it with: npm install @apollo/server @graphql-tools/schema graphql"):o}};return async()=>{if(!n.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var oe=class n{static fromRequest(e){let t=Object.assign(new n,{url:e.url,method:e.method,headers:e.headers,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive});return t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#s&&e){let t=stream.Readable.toWeb(this.#s);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive})}static toJSONSchemaWithPrefix(e){return _.isZodSchema(e)?{jsonSchema:_.toJSONSchema(e),prefix:"zod_schema"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"typebox_schema"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"json_schema"}:{jsonSchema:{type:typeof e},prefix:`primitive_${JSON.stringify(e)}`}}static getOrCompileSchema(e){let{jsonSchema:t,prefix:r}=this.toJSONSchemaWithPrefix(e);return A.storeJsonSchema(t,r),A.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return ht(s,t,r)}#t;#s;url="";method="GET";headers=new Headers;signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};#e;#r;#n=false;get query(){if(this.#n)return this.#e;if(!this.#r||this.#r==="")this.#e={};else if(this.#r.length<50&&!this.#r.includes("&")){let e=this.#r.indexOf("=");if(e===-1)this.#e={[this.#r]:""};else {let t=this.#r.slice(0,e),r=decodeURIComponent(this.#r.slice(e+1));this.#e={[t]:r};}}else this.#e=Object.fromEntries(new URLSearchParams(this.#r));return this.#n=true,this.#e}set query(e){this.#e=e,this.#n=true;}setQueryString(e){this.#r=e,this.#n=false,this.#e=void 0;}#o;get id(){return this.#o||(this.#o=ee.randomUUID()),this.#o}set id(e){this.#o=e;}validate(e,t=false){return n.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return n.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return n.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}setNodeRequest(e){this.#s=e;}};G();var tr=class{file(e,t){switch(E.type){case "bun":case "node":return Xe__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},bt=new tr;var Wr=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var rr=(n,e)=>{let{source:t,path:r}=n,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),$.addOrUpdate("GET",`${s}/*`,[],async(o,i)=>po(o,i,t),{},{service:"StaticFiles",...e}),async(o,i,a)=>a()};async function po(n,e,t){if(n.method!=="GET"&&n.method!=="HEAD")return e.status(405).json({...L(new Ue(n.url,n.method))});let r=n.params["*"]||"",s=x.join(t,r),o=x.resolve(N.getCwd(),s),i=x.resolve(N.getCwd(),t);if(!o.startsWith(i))return e.notFound({...L(new z(n.url,n.method))});try{if(!(await v.stat(o)).isFile)return e.notFound({...L(new z(n.url,n.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...L(new z(n.url,n.method))});throw d}let a=sr(x.extName(o));e.setHeader("Content-Type",a);let c=bt.file(o);e.raw(c);}function sr(n){return Wr.get(n)||"application/octet-stream"}var D=class{static toWebResponse(e){let t=e.getBody();return e.headers["Content-Type"]?.toLowerCase()==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:e.headers}):globalThis.Response.json(t,{status:e.responseStatus,headers:e.headers}):new globalThis.Response(t,{status:e.responseStatus,headers:e.headers})}responseStatus;headers;body;#t;#s;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#s=e,this.#e=A.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers["Content-Type"]="text/plain";}json(e,t){if(this.body=e,this.headers["Content-Type"]="application/json",!t&&this.#e){let s=this.#e.get(this.responseStatus);if(s){this.#t=s;return}}let r=t??this.#s?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:o}=this.getJsonSchemaWithPrefix(r);this.#t=A.getOrCreateSerializer(s,o)??void 0;}}getJsonSchemaWithPrefix(e){return _.isZodSchema(e)?{jsonSchema:_.toJSONSchema(e),prefix:"fast_stringify_zod"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"fast_stringify_typebox"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof e},prefix:`fast_stringify_primitive_${JSON.stringify(e)}`}}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=x.extName(e),s=sr(r);this.body=bt.file(e,t),this.headers["Content-Type"]=s;}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.responseStatus=204,this.body="";}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.responseStatus=304,this.body="";}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){if(this.#t&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#t(this.body),this.#t=void 0;}catch(e){q.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#t=void 0;}return this.body}};var de=class{constructor(e){this.response=e;}body(){let e=this.response.getBody();if(typeof e=="string"&&this.response.headers["Content-Type"]?.includes("json"))try{return JSON.parse(e)}catch{return e}return e}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let s in t){let o=r===""?s:`${r}.${s}`,i=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,o);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,o);else if(i!==a)throw new Error(`Expected ${o} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),o=Object.keys(t);if(s.length!==o.length)throw new Error(`Expected ${r} to have ${o.length} keys, but got ${s.length}`);for(let i of o){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let o=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,o);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,o);else if(i!==a)throw new Error(`Expected ${o} to be ${a}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let o=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],o);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var wt=class{server;logger=q.child({scope:"MockServer"});ensureGraphQLHandler;constructor(e){this.server=e,this.ensureGraphQLHandler=fe(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:o={},cookies:i={},ip:a}=r;this.validateOptions(r);let c=this.server.graphql.isEnabled,d=t.startsWith("/graphql");if(c&&d)return this.handleGraphQLRequest(e,t,r);let l=$.find(e.toUpperCase(),t);if(!l){let g=new D(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new de(g)}let p,u="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?p=JSON.stringify(r.body):p=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;u=`multipart/form-data; boundary=${g}`,p=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(u="application/x-www-form-urlencoded",p=new URLSearchParams(r.urlencoded).toString());let m=new URL(`http://${this.server.host}:${this.server.port}${t}`);m.search=new URLSearchParams(o).toString();let h=new globalThis.Request(m.toString(),{method:e.toUpperCase(),body:ae(e)?p:void 0,headers:{"content-type":u,...s}}),f=oe.fromRequest(h);f.query={...Object.fromEntries(m.searchParams.entries()),...o},f.params=l.params,f.cookies=i,f.ip=a;try{let g=await he(l.middleware,l.handler,f,new D);return new de(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let y=new D(500);return y.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new de(y)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,s=[];for(let[c,d]of e.entries()){s.push(r.encode(`--${t}\r
1084
+ `}[e]||""}};P([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],ke,"storageType"),P([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],ke,"outputPath");var no=[je,Ie,Oe,Re,me,Pe,Ce,Q,ie,qe,Me,Ze,V,Ae,ke,De,Ee,xe],vt=class n{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=q.child({scope:"CommandRegistry"});static setLogger(e){n.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||n.loggerPath;try{let r=await import(x.join(N.getCwd(),t));r.logger&&n.setLogger(r.logger);}catch{n.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new n}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return n.logger}setLogger(e){n.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){n.logger.info(`Loading commands from ${e}`);let t=await v.glob(e,{cwd:N.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{n.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let s=await import(r).then(o=>o.default?o.default:o).catch(o=>(n.logger.error(`Error loading command ${r}: ${o}`),null));s&&this.commands.set(s.commandName,s);}for(let r of no)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Te=vt.getInstance();G();var Qe=class{get(e){switch(E.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${E.type}`)}}getEnvironment(){switch(E.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var io=new Qe,L=n=>{let e=io.get("NODE_ENV")!=="production";return {code:n.name||"INTERNAL_ERROR",message:n.message,...e&&{stack:n.stack,cause:n.cause}}};var Ue=class extends O{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var z=class extends O{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var se=class{schemaOptions;apolloOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.apolloOptions=t.apolloOptions,this.isEnabled=t.isEnabled;}getSchemaOptions(){return this.schemaOptions}getApolloOptions(){return this.apolloOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},apolloOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),apolloOptions:this.resolveApolloOptions(e.apolloOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveApolloOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var he=async(n,e,t,r)=>{let s=n.length;if(s===0){let a=await e(t,r);return a&&r.send(a),r}let o=0,i=async()=>{if(o>=s){let d=await e(t,r);return d&&r.send(d),r}let a=o++,c=n[a];await c(t,r,i);};return await i(),r},ao=new Set(["post","put","patch"]),ae=n=>n?ao.has(n.toLowerCase()):true,bt=async(n,e,t,r,s)=>{try{let{HeaderMap:o}=await import('@apollo/server'),i=new o;e.headers.forEach((h,f)=>{i.set(f,h);});let c=(e.headers.get("content-type")??"").includes("application/json"),d="";if(t!=="GET"){let h=await e.text();d=c&&h?JSON.parse(h):h;}let l={method:t.toUpperCase(),headers:i,body:d,search:r?`?${r}`:""},p=await n.executeHTTPGraphQLRequest({httpGraphQLRequest:l,context:async()=>s}),u={};for(let[h,f]of p.headers)u[h]=f;if(p.body.kind==="complete")return new globalThis.Response(p.body.string,{status:p.status??200,headers:u});let m=new ReadableStream({async start(h){if(p.body.kind==="chunked")for await(let f of p.body.asyncIterator)h.enqueue(new TextEncoder().encode(f));h.close();}});return new globalThis.Response(m,{status:p.status??200,headers:u})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},Jr=async(n,e,t,r,s,o,i)=>{try{let{HeaderMap:a}=await import('@apollo/server'),c=new a;for(let[f,g]of Object.entries(e))g!==void 0&&c.set(f,Array.isArray(g)?g.join(", "):g);let p=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,u={method:t?.toUpperCase()??"POST",headers:c,body:p,search:s?`?${s}`:""},m=await n.executeHTTPGraphQLRequest({httpGraphQLRequest:u,context:async()=>o}),h=m.status??200;m.body.kind==="complete"?await i(m.headers,h,m.body.string):await i(m.headers,h,m.body.asyncIterator);}catch{await i(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},fe=n=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(o=>setTimeout(o,10));},s=async()=>{try{let{ApolloServer:o}=await import('@apollo/server'),{makeExecutableSchema:i}=await import('@graphql-tools/schema'),a=n.getSchemaOptions(),c=n.getApolloOptions(),d=i({typeDefs:a.typeDefs,resolvers:a.resolvers}),l=new o({schema:d,...c});return await l.start(),{server:l,url:"/graphql"}}catch(o){throw o instanceof Error&&(o.message.includes("Cannot find module")||o.message.includes("Cannot find package"))?new Error("GraphQL is enabled but '@apollo/server' is not installed. Install it with: npm install @apollo/server @graphql-tools/schema graphql"):o}};return async()=>{if(!n.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var oe=class n{static fromRequest(e){let t=Object.assign(new n,{url:e.url,method:e.method,headers:e.headers,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive});return t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#s&&e){let t=stream.Readable.toWeb(this.#s);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive})}static toJSONSchemaWithPrefix(e){return _.isZodSchema(e)?{jsonSchema:_.toJSONSchema(e),prefix:"zod_schema"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"typebox_schema"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"json_schema"}:{jsonSchema:{type:typeof e},prefix:`primitive_${JSON.stringify(e)}`}}static getOrCompileSchema(e){let{jsonSchema:t,prefix:r}=this.toJSONSchemaWithPrefix(e);return A.storeJsonSchema(t,r),A.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return ht(s,t,r)}#t;#s;url="";method="GET";headers=new Headers;signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};#e;#r;#n=false;get query(){if(this.#n)return this.#e;if(!this.#r||this.#r==="")this.#e={};else if(this.#r.length<50&&!this.#r.includes("&")){let e=this.#r.indexOf("=");if(e===-1)this.#e={[this.#r]:""};else {let t=this.#r.slice(0,e),r=decodeURIComponent(this.#r.slice(e+1));this.#e={[t]:r};}}else this.#e=Object.fromEntries(new URLSearchParams(this.#r));return this.#n=true,this.#e}set query(e){this.#e=e,this.#n=true;}setQueryString(e){this.#r=e,this.#n=false,this.#e=void 0;}#o;get id(){return this.#o||(this.#o=ee.randomUUID()),this.#o}set id(e){this.#o=e;}validate(e,t=false){return n.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return n.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return n.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}setNodeRequest(e){this.#s=e;}};G();var tr=class{file(e,t){switch(E.type){case "bun":case "node":return Xe__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},wt=new tr;var Wr=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var rr=(n,e)=>{let{source:t,path:r}=n,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),$.addOrUpdate("GET",`${s}/*`,[],async(o,i)=>po(o,i,t),{},{service:"StaticFiles",...e}),async(o,i,a)=>a()};async function po(n,e,t){if(n.method!=="GET"&&n.method!=="HEAD")return e.status(405).json({...L(new Ue(n.url,n.method))});let r=n.params["*"]||"",s=x.join(t,r),o=x.resolve(N.getCwd(),s),i=x.resolve(N.getCwd(),t);if(!o.startsWith(i))return e.notFound({...L(new z(n.url,n.method))});try{if(!(await v.stat(o)).isFile)return e.notFound({...L(new z(n.url,n.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...L(new z(n.url,n.method))});throw d}let a=sr(x.extName(o));e.setHeader("Content-Type",a);let c=wt.file(o);e.raw(c);}function sr(n){return Wr.get(n)||"application/octet-stream"}var D=class{static toWebResponse(e){let t=e.getBody();return e.headers["Content-Type"]?.toLowerCase()==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:e.headers}):globalThis.Response.json(t,{status:e.responseStatus,headers:e.headers}):new globalThis.Response(t,{status:e.responseStatus,headers:e.headers})}responseStatus;headers;body;#t;#s;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#s=e,this.#e=A.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers["Content-Type"]="text/plain";}json(e,t){if(this.body=e,this.headers["Content-Type"]="application/json",!t&&this.#e){let s=this.#e.get(this.responseStatus);if(s){this.#t=s;return}}let r=t??this.#s?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:o}=this.getJsonSchemaWithPrefix(r);this.#t=A.getOrCreateSerializer(s,o)??void 0;}}getJsonSchemaWithPrefix(e){return _.isZodSchema(e)?{jsonSchema:_.toJSONSchema(e),prefix:"fast_stringify_zod"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"fast_stringify_typebox"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof e},prefix:`fast_stringify_primitive_${JSON.stringify(e)}`}}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=x.extName(e),s=sr(r);this.body=wt.file(e,t),this.headers["Content-Type"]=s;}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.responseStatus=204,this.body="";}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.responseStatus=304,this.body="";}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){if(this.#t&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#t(this.body),this.#t=void 0;}catch(e){q.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#t=void 0;}return this.body}};var de=class{constructor(e){this.response=e;}body(){let e=this.response.getBody();if(typeof e=="string"&&this.response.headers["Content-Type"]?.includes("json"))try{return JSON.parse(e)}catch{return e}return e}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let s in t){let o=r===""?s:`${r}.${s}`,i=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,o);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,o);else if(i!==a)throw new Error(`Expected ${o} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),o=Object.keys(t);if(s.length!==o.length)throw new Error(`Expected ${r} to have ${o.length} keys, but got ${s.length}`);for(let i of o){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let o=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,o);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,o);else if(i!==a)throw new Error(`Expected ${o} to be ${a}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let o=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],o);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var St=class{server;logger=q.child({scope:"MockServer"});ensureGraphQLHandler;constructor(e){this.server=e,this.ensureGraphQLHandler=fe(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:o={},cookies:i={},ip:a}=r;this.validateOptions(r);let c=this.server.graphql.isEnabled,d=t.startsWith("/graphql");if(c&&d)return this.handleGraphQLRequest(e,t,r);let l=$.find(e.toUpperCase(),t);if(!l){let g=new D(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new de(g)}let p,u="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?p=JSON.stringify(r.body):p=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;u=`multipart/form-data; boundary=${g}`,p=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(u="application/x-www-form-urlencoded",p=new URLSearchParams(r.urlencoded).toString());let m=new URL(`http://${this.server.host}:${this.server.port}${t}`);m.search=new URLSearchParams(o).toString();let h=new globalThis.Request(m.toString(),{method:e.toUpperCase(),body:ae(e)?p:void 0,headers:{"content-type":u,...s}}),f=oe.fromRequest(h);f.query={...Object.fromEntries(m.searchParams.entries()),...o},f.params=l.params,f.cookies=i,f.ip=a;try{let g=await he(l.middleware,l.handler,f,new D);return new de(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let y=new D(500);return y.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new de(y)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,s=[];for(let[c,d]of e.entries()){s.push(r.encode(`--${t}\r
1083
1085
  `));let l=`Content-Disposition: form-data; name="${c}"`,p="";if(d instanceof File&&(l+=`; filename="${d.name}"`,p=`Content-Type: ${d.type||"application/octet-stream"}\r
1084
1086
  `),s.push(r.encode(`${l}\r
1085
1087
  ${p}\r
1086
1088
  `)),d instanceof File){let u=await d.arrayBuffer();s.push(new Uint8Array(u)),s.push(r.encode(`\r
1087
1089
  `));}else s.push(r.encode(`${String(d)}\r
1088
1090
  `));}s.push(r.encode(`--${t}--\r
1089
- `));let o=s.reduce((c,d)=>c+d.byteLength,0),i=new Uint8Array(o),a=0;for(let c of s)i.set(c,a),a+=c.byteLength;return i}async handleGraphQLRequest(e,t,r={}){let s=await this.ensureGraphQLHandler();if(!s){let p=new D(500);return p.json({errors:[{message:"GraphQL handler not initialized"}]}),new de(p)}let{headers:o={},query:i={}}=r,a=new URL(`http://${this.server.host}:${this.server.port}${t}`);a.search=new URLSearchParams(i).toString();let c;r.body!==void 0&&ae(e)&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?c=JSON.stringify(r.body):c=r.body);let d=new globalThis.Request(a.toString(),{method:e.toUpperCase(),body:c,headers:{"content-type":"application/json",...o}}),l=oe.fromRequest(d);l.query={...Object.fromEntries(a.searchParams.entries()),...i};try{let{HeaderMap:p}=await import('@apollo/server'),u=new p;for(let[M,B]of Object.entries(o))B!==void 0&&u.set(M,Array.isArray(B)?B.join(", "):String(B));let h=(u.get("content-type")??"").includes("application/json"),f="";typeof c=="string"?f=c:c instanceof Uint8Array?f=new TextDecoder().decode(c):c&&typeof c=="object"&&(f=new TextDecoder().decode(new Uint8Array(c)));let g=h&&f?JSON.parse(f):f,y={method:e.toUpperCase(),headers:u,body:g,search:a.search},T=this.server.graphql.getApolloOptions(),w=T.context&&typeof T.context=="function"?await T.context({req:l}):{req:l},b=await s.server.executeHTTPGraphQLRequest({httpGraphQLRequest:y,context:async()=>w}),S=b.status??200,R=new D(S);for(let[M,B]of b.headers)R.setHeader(M,B);if(b.body.kind==="complete"){let M=b.body.string;try{R.json(JSON.parse(M));}catch{R.text(M);}}else {let M="";for await(let B of b.body.asyncIterator)M+=B;try{R.json(JSON.parse(M));}catch{R.text(M);}}return new de(R)}catch(p){this.logger.error({error:p},`Error processing GraphQL request ${e} ${t}:`);let u=new D(500);return u.json({errors:[{message:"Internal server error"}]}),new de(u)}}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var ze=new async_hooks.AsyncLocalStorage,or=n=>async(e,t,r)=>{let s={};for(let[o,i]of Object.entries(n))s[o]=i(e);ze.run(s,()=>{e.ctx=new Proxy({},{get(o,i){return ze.getStore()?.[i]},set(o,i,a){let c=ze.getStore();return c?(c[i]=a,true):false},ownKeys(){let o=ze.getStore();return o?Object.keys(o):[]},has(o,i){let a=ze.getStore();return a?i in a:false}}),r();});};var St=class extends O{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};G();var nr=class{async tmpdir(){switch(E.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},Vr=new nr;var Kr=1024*1024,Xr=10*1024*1024,Yr=n=>async(e,t,r)=>{let s=[];try{let o=e.headers.get("content-type")??e.headers.get("Content-Type");if(!o||!o.startsWith("multipart/form-data")||e.body||e.bodyUsed)return r();let i=e.headers.get("content-length"),a=ye(n?.maxFileSize,Xr)??Xr;if(i&&parseInt(i)>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let c=o.match(/boundary=(.*)(;|$)/i);if(!c)return r();let d=c[1].replace(/(^\s*"?|"?\s*$)/g,""),l=new Uint8Array(await e.toWebApi().arrayBuffer());if(l.length>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let p=new TextEncoder().encode(`--${d}`),u=new Uint8Array([13,10,13,10]),m=[],h=(w,b,S=0)=>{e:for(let R=S;R<=w.length-b.length;R++){for(let M=0;M<b.length;M++)if(w[R+M]!==b[M])continue e;return R}return -1},f=h(l,p);for(;f!==-1&&(f+=p.length,!(l[f]===45&&l[f+1]===45));){l[f]===13&&l[f+1]===10&&(f+=2);let w=h(l,u,f);if(w===-1)break;let b=l.subarray(f,w),S=new TextDecoder().decode(b),R=w+u.length,M=h(l,p,R);if(M===-1)break;let B=M-1;l[B]===10&&B--,l[B]===13&&B--;let ce=l.subarray(R,B+1);m.push({headers:S,data:ce}),f=M;}let g=[],y={},T=ye(n?.maxFileSize,Kr)??Kr;for(let w of m){let b=w.headers.split(`\r
1090
- `).find(le=>le.toLowerCase().startsWith("content-disposition:"));if(!b)continue;let S=b.match(/name="([^"]+)"/);if(!S)continue;let R=S[1],M=b.match(/filename="([^"]*)"/),B=M?M[1]:"";if(!!B){if(n?.maxFiles&&g.length>=n.maxFiles)return t.badRequest({...L(new O(`Too many files: Maximum ${n.maxFiles} files allowed`))});if(T&&w.data.length>T)return t.badRequest({...L(new St(B,w.data.length,T))});let le=w.headers.split(`\r
1091
- `).find(ys=>ys.toLowerCase().startsWith("content-type:")),Z=le?le.split(":")[1].trim():"application/octet-stream";if(n?.allowedMimeTypes&&!n.allowedMimeTypes.includes(Z))return t.badRequest({...L(new O(`Invalid file type: "${Z}" is not allowed. Allowed types: ${n.allowedMimeTypes.join(", ")}`))});let Bt=mo(Z),Ht=x.join(await Vr.tmpdir(),`${ee.randomUUID()}${Bt}`);await v.writeFile(Ht,w.data),s.push(Ht),g.push({formName:R,mimeType:Z,size:w.data.length,tmpPath:Ht,originalName:B});}else y[R]=new TextDecoder().decode(w.data);}e.files=g,e.body=y,e.bodyUsed=!0,await r(),await Zr(s);}catch(o){throw await Zr(s),o}},Zr=async n=>{await Promise.allSettled(n.map(e=>v.unlink(e)));};var mo=n=>({"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","application/pdf":".pdf","text/plain":".txt","application/json":".json","text/csv":".csv","application/octet-stream":".bin","application/x-www-form-urlencoded":".urlencoded","application/xml":".xml","application/yaml":".yaml","application/yml":".yml","application/csv":".csv","application/txt":".txt","application/markdown":".markdown"})[n.toLowerCase()]||".bin";var Ye=class extends O{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var es=100*1024,ts=n=>async(e,t,r)=>{if(!ho(e)||!ae(e.method)||e.bodyUsed)return r();let s=ye(n?.sizeLimit,es)??es,o=e.headers.get("content-length");if(o&&Number.parseInt(o)>s){let i={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...n?.customErrorMessage};return t.status(i.status).json({error:i.message})}if(e.body||e.bodyUsed)return r();try{let i=e.toWebApi();e.body=await i.json(),e.bodyUsed=!0;}catch(i){return i instanceof SyntaxError?t.badRequest({...L(new Ye("Invalid JSON syntax"))}):t.badRequest({...L(new Ye("Invalid request body encoding"))})}await r();};function ho(n){let e=fo(n);return e?go(e)==="application/json":false}function fo(n){let e=n.headers.get("content-type")??n.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function go(n){let e=n.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var rs=1024*1024,ss=n=>{let t={limit:ye(n?.limit,rs)??rs,extended:n?.extended??false,charset:n?.charset??"utf8",allowEmpty:n?.allowEmpty??true,parameterLimit:n?.parameterLimit??1e3};return async(r,s,o)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();let a=r.headers.get("content-length");if(a&&parseInt(a)>t.limit){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}try{await yo(r,t),await o();}catch(c){if(c instanceof Error&&c.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw c}}};async function yo(n,e){if(n.body||n.bodyUsed)return;let r=await n.toWebApi().arrayBuffer();if(r.byteLength>e.limit)throw new Error(`Body size ${r.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(r),i=vo(o,e);n.body=i,n.bodyUsed=true;}function vo(n,e){let t={},r=new URLSearchParams(n);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,o]of r.entries())!e.allowEmpty&&o===""||(e.extended?bo(t,s,o):t[s]=o);return t}function bo(n,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(n[e]=t);return}let o=n,i=e.split("[")[0];if(r.includes(i))return;for(let c=0;c<s.length-1;c++){let d=s[c].slice(1,-1);if(r.includes(d))return;if(o[i]||(o[i]={}),d===""){Array.isArray(o[i])||(o[i]=[]),o=o[i];continue}o[i][d]||(o[i][d]={}),o=o[i][d];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t;}}var wo=n=>(n.headers.get("content-type")??n.headers.get("Content-Type"))?.split(";")[0]??null,os=n=>{let e=n.json,t=n.urlencoded,r=n.fileParser;return async(s,o,i)=>{if(!ae(s.method)||s.bodyUsed)return i();let a=wo(s);if(a==="application/json"&&e)return ts(e)(s,o,i);if(a==="multipart/form-data"&&r)return Yr(r)(s,o,i);if(a==="application/x-www-form-urlencoded"&&t)return ss(t)(s,o,i);if(a?.includes("text/")){let c=new TextDecoder,d=s.toWebApi();s.body=c.decode(await d.arrayBuffer()),s.bodyUsed=true;}return !s.body&&!s.bodyUsed&&(s.body=await s.toWebApi().arrayBuffer()),i()}};var xo=1024,To=6,Po=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],ir=n=>{let e=n?.threshold??xo,t=Math.max(0,Math.min(9,n?.level??To)),r=n?.filter??Po;return async(s,o,i)=>{if(!(s.headers.get("accept-encoding")||"").includes("gzip"))return i();let d=o.send.bind(o),l=o.text.bind(o),p=(u,m)=>{if(!Co(u,m,e,r))return u;let h=ns(u);if(!h||h.length<e)return u;let f=zlib.gzipSync(h,{level:t});return o.setHeader("Content-Encoding","gzip"),o.setHeader("Content-Length",f.length.toString()),f};o.send=function(u){let m=o.headers["content-type"],h=p(u,m);return d(h)},o.json=function(u,m){let h=null;if(m){let{jsonSchema:y,prefix:T}=Oo(m);h=A.getOrCreateSerializer(y,T);}let f=h&&typeof u=="object"&&u!==null?h(u):typeof u=="string"?u:JSON.stringify(u),g=p(f,"application/json");return g!==f?(o.setHeader("Content-Type","application/json"),d(g)):d(f)},o.text=function(u){let m=p(u,"text/plain");return m!==u?(o.setHeader("Content-Type","text/plain"),d(m)):l(u)},await i();}},Oo=n=>_.isZodSchema(n)?{jsonSchema:_.toJSONSchema(n),prefix:"fast_stringify_zod"}:F.isTypeBoxSchema(n)?{jsonSchema:n,prefix:"fast_stringify_typebox"}:typeof n=="object"&&n!==null?{jsonSchema:n,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof n},prefix:`fast_stringify_primitive_${JSON.stringify(n)}`},Co=(n,e,t,r)=>{if(!n||!e)return false;let s=ns(n);return !s||s.length<t?false:r.some(o=>o.test(e))},ns=n=>typeof n=="string"?Buffer.from(n,"utf-8"):Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n):typeof n=="object"?Buffer.from(JSON.stringify(n),"utf-8"):null;var ar=n=>{let e={secret:n?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...n?.defaults},parse:n?.parse??true,sign:n?.sign??false};return async(t,r,s)=>{if(e.parse){let o=Ro(t.headers.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(o)){if(e.sign&&e.secret){let c=await Mo(a,e.secret);c!==false&&(t.cookies[i]=c);continue}t.cookies[i]=a;}}r.cookie=(o,i,a)=>{is(r,o,i,{...e.defaults,...a},e);},r.clearCookie=(o,i)=>{jo(r,o,{...e.defaults,...i});},await s();}};function Ro(n){let e={};if(!n)return e;let t=n.split(";");for(let r of t){let[s,o]=r.trim().split("=");s&&o&&(e[decodeURIComponent(s)]=decodeURIComponent(o));}return e}async function is(n,e,t,r,s){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires&&(o+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(o+=`; Max-Age=${r.maxAge}`),r.secure&&(o+="; Secure"),r.httpOnly&&(o+="; HttpOnly"),r.sameSite&&(o+=`; SameSite=${r.sameSite}`),r.priority&&(o+=`; Priority=${r.priority}`),s.sign&&s.secret&&(o=await qo(o,s.secret));let i=n.headers["set-cookie"]||"",a=i?`${i}, ${o}`:o;n.setHeader("Set-Cookie",a);}function jo(n,e,t){let r={...t,expires:new Date(0),maxAge:0};is(n,e,"",r,{secret:"",sign:false});}async function qo(n,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(n),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",o,s),a=new Uint8Array(i),c=Array.from(a).map(d=>d.toString(16).padStart(2,"0")).join("");return `${n}.${c}`}async function Mo(n,e){let t=n.split(".");if(t.length!==2)return false;let[r,s]=t,o=new TextEncoder,i=o.encode(e),a=o.encode(r),c=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(d),p=Array.from(l).map(u=>u.toString(16).padStart(2,"0")).join("");return s===p?r:false}var cr=n=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...n};return async(t,r,s)=>{let o=t.headers.get("origin")||"";if(t.method==="OPTIONS")return Eo(t,r,e,o,s);Ao(t,r,e,o),await s();}};function Eo(n,e,t,r,s){let o=as(t,r);if(!o){e.forbidden("CORS origin not allowed");return}if(cs(e,t,o),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Ao(n,e,t,r){let s=as(t,r);s&&cs(e,t,s);}function as(n,e){if(typeof n.origin=="string")return n.origin;if(Array.isArray(n.origin)){let t=n.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function cs(n,e,t){if(n.setHeader("Access-Control-Allow-Origin",t),e.credentials&&n.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;n.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;n.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;n.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&n.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function ls(n,e=""){let t=new URL(n.url),r=Object.fromEntries(n.headers.entries()),o=n.headers.get("x-forwarded-proto")||t.protocol.replace(":","");return {body:n.body,query:n.query,params:n.params,cookies:n.cookies,session:n.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:n.method,ip:n.ip,headers:r,url:t.pathname,get(a){return n.headers.get(a.toLowerCase())??void 0},header(a){return n.headers.get(a.toLowerCase())??void 0},app:{},res:null,route:null,protocol:o,secure:o==="https",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:a=>n.params[a]??n.query[a],files:n.files,file:n.file,rawBody:n.body}}function ps(n){return {locals:{},headersSent:false,statusCode:n.responseStatus,status(t){return n.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!n.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return n.html(t),this}return n.send(t),this},json(t){return this.headersSent=true,n.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,o=typeof t=="number"?t:302;return n.status(o).setHeader("Location",s),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return n.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,o]of Object.entries(t))n.setHeader(s,o);else r!==void 0&&n.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return n.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,n.send(t??""),this},write(t){return q.warn({method:"write"},"res.write() is not fully supported in Express compatibility layer - responses will be buffered"),true},get(t){return n.headers[t]},getHeader(t){return n.headers[t]},removeHeader(t){return delete n.headers[t],this},append(t,r){let s=n.headers[t],o=Array.isArray(r)?r.join(", "):r;return n.setHeader(t,s?`${s}, ${o}`:o),this},cookie(t,r,s){return n.cookie?.(t,r,s),this},clearCookie(t,r){return n.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){throw new Error("format() is not supported in Express compatibility layer")},attachment(t){return t?n.setHeader("Content-Disposition",`attachment; filename="${t}"`):n.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){n.file(t);},download(t,r,s,o){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),n.file(t);},links(t){let r=Object.entries(t).map(([s,o])=>`<${o}>; rel="${s}"`).join(", ");return n.setHeader("Link",r),this},location(t){return n.setHeader("Location",t),this},vary(t){return n.setHeader("Vary",t),this},app:{},req:null}}function $e(n,e=""){return async(t,r,s)=>{let o=ls(t,e),i=ps(r);o.res=i,i.req=o;let a=false,c=3e4;await Promise.race([new Promise((d,l)=>{let p=u=>{if(a=true,u){l(u);return}d();};try{let u=n(o,i,p);u instanceof Promise&&u.catch(l);}catch(u){l(u);}}),new Promise(d=>{setTimeout(()=>{!a&&!i.headersSent&&q.warn({basePath:e,timeout:c},"Express middleware did not call next() within timeout and did not send response"),d();},c);})]),i.headersSent||await s();}}function ds(n,e=""){return async(t,r)=>{let s=ls(t,e),o=ps(r);s.res=o,o.req=s;let i=()=>{};try{await n(s,o,i);}catch(a){throw q.error({error:a,basePath:e},"Express handler threw an error"),a}}}function et(n,e){let t=lr(n),r=e.stack;if(!r){q.warn({basePath:n},"Express router has no stack - routes may not be registered");return}for(let s of r)us(s,t);}function us(n,e){if(n.route){let t=lr(e+n.route.path),r=Object.keys(n.route.methods).filter(s=>n.route.methods[s]);for(let s of r){let o=n.route.stack.map(i=>i.handle);ko(s.toUpperCase(),t,o,e);}return}if(n.handle&&typeof n.handle=="function"){let t=n.path||"",r=lr(e+t),s=n.handle.stack;if(s&&Array.isArray(s)){for(let c of s)us(c,r);return}let o=r==="/"?"/*":`${r}/*`,i=$e(n.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)$.addOrUpdate(c,o,[i],async()=>{},{},{excludeFromSwagger:true});}}function ko(n,e,t,r){let s=t.slice(0,-1).map(a=>$e(a,r)),o=t[t.length-1],i=ds(o,r);$.addOrUpdate(n,e,s,i,{},{excludeFromSwagger:true});}function lr(n){let e=n.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function pr(n){return {use(e,t){if(typeof e=="string"){let o=e,i=t,a=i.stack;if(a&&Array.isArray(a)){et(o,i);return}n.use($e(i,o));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){et("/",r);return}n.use($e(r));}}}var dr=n=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...n};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let o="SAMEORIGIN";typeof e.frameguard=="object"&&(o=e.frameguard.action),r.setHeader("X-Frame-Options",o);}if(e.hsts){let o={};typeof e.hsts=="object"&&(o=e.hsts);let i=o.maxAge!==void 0?o.maxAge:15552e3,a=o.includeSubDomains!==void 0?o.includeSubDomains:true,c=o.preload!==void 0?o.preload:false,d=`max-age=${i}`;a!==false&&(d+="; includeSubDomains"),c&&(d+="; preload"),r.setHeader("Strict-Transport-Security",d);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await s();}};var ur=n=>{let e=q.child({scope:"LogMiddleware"});return async(t,r,s)=>{try{let o=t.body;(n?.logRequest??!0)&&e.info({type:"request",requestId:t.id,method:n?.requestPayload?.method??!0?t.method:void 0,url:n?.requestPayload?.url??!0?t.url:void 0,ip:n?.requestPayload?.ip??!0?t.ip:void 0,headers:n?.requestPayload?.headers??!0?t.headers:void 0,body:n?.requestPayload?.body??!1?ms(o):void 0});let i=performance.now();await s();let c=performance.now()-i;(n?.logResponse??!0)&&e.info({type:"response",requestId:t.id,status:n?.responsePayload?.status??r.responseStatus,duration:`${c.toFixed(2)}ms`,body:n?.responsePayload?.body??!1?ms(r.getBody()):void 0,headers:n?.responsePayload?.headers??!1?r.headers:void 0});}catch(o){throw e.error(o),o}}};function ms(n){if(typeof n=="string"||n&&typeof n=="object"&&n.constructor===Object)return n}var $o=["POST"],_o="X-HTTP-Method-Override",Bo=["GET","POST","PUT","PATCH","DELETE"],mr=n=>{let e=(n?.methods??$o).map(r=>r.toUpperCase()),t=n?.header??_o;return async(r,s,o)=>{let i=r.method.toUpperCase();if(!e.includes(i))return o();let a=r.headers.get(t);if(!a)return o();let c=a.toUpperCase();if(!Bo.includes(c))return o();r.method=c,await o();}};var xt=class{storage=new Map;timers=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){let r=this.timers.get(e);r&&clearTimeout(r),this.storage.set(e,t);let s=setTimeout(()=>{this.storage.delete(e),this.timers.delete(e);},this.windowMs);this.timers.set(e,s);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){let t=this.timers.get(e);t&&clearTimeout(t),this.storage.delete(e),this.timers.delete(e);}};var hr=(n,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...n},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new xt(r.windowMs):{get:r.get,set:r.set};return async(o,i,a)=>{let c=t.type==="ip"?o.ip:t.key(o),d=await s.get(c);return d>=t.limit?i.status(t.statusCode).json({message:t.message}):(await s.set(c,d+1),a())}};var Tt=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var fr=n=>{let e=n?.name??"sid",t=n?.ttl??3600*24,r=n?.store??new Tt,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...n?.cookie??{}};return async(o,i,a)=>{let d=o.cookies&&o.cookies[e],l=d?await r.get(d):void 0;(!d||!l)&&(d||=ee.randomUUID(),l||={},await r.set(d,l,t),i.cookie?.(e,d,s)),o.session=l,o.saveSession=async()=>r.set(d,l,t),o.destroySession=async()=>{await r.destroy(d),i.clearCookie?.(e,s);},await a(),await r.set(d,l,t);}};var fs=n=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};n&&typeof n!="boolean"&&(e={...e,...n});let t=Ho(e),r=`${e.path}`,s=`${r}/json`,o;e.type==="rapidoc"?o=Lo(s,e):e.type==="scalar"?o=Fo(s,e):e.type==="elements"?o=Io(s,e):e.type==="custom"?o=e.customUIGenerator(s,e):o=No(s,e),$.addOrUpdate("GET",r,[],(i,a)=>{a.html(o);}),$.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);});},ge=n=>n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function _e(n){if(!n||typeof n!="object")return {type:"string"};let e="json_schema";_.isZodSchema(n)?e="zod_schema":F.isTypeBoxSchema(n)&&(e="typebox_schema");let t=A.getJsonSchema(n,e);if(t)return t;if(_.isZodSchema(n))try{let s=_.toJSONSchema(n);return A.storeJsonSchema(s,e),s}catch(s){return q.debug({error:s instanceof Error?s.message:String(s),schemaType:n?.constructor?.name||typeof n},"Failed to convert Zod schema to JSON Schema for Swagger documentation"),{type:"object"}}let r=n;return A.storeJsonSchema(r,e),r}function Ho(n){let e=$.getRoutes(),t={},r;if(n.models)if(Array.isArray(n.models))r=n.models.reduce((o,i,a)=>{let c=_e(i),d=c.$id||c.title||`Model${a}`;return o[d]=c,o},{});else {r={};for(let[o,i]of Object.entries(n.models))r[o]=_e(i);}let s={...n.components,securitySchemes:n.securitySchemes||{},schemas:r?{...n.components?.schemas||{},...r}:n.components?.schemas?{...n.components.schemas}:void 0};for(let o of e){let i=o.swaggerOptions;if(i?.excludeFromSwagger)continue;t[o.path]||(t[o.path]={});let a=o.method.toLowerCase(),c={summary:i?.name||`${a.toUpperCase()} ${o.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},d=[],l=o.validationSchemas?.query;if(l){let u=l;if(u.type==="object"&&u.shape)for(let[m,h]of Object.entries(u.shape))!h||typeof h!="object"||d.push({name:m,in:"query",required:Array.isArray(u.shape[m].required)?u.shape[m].required.includes(m):false,schema:_e(h)});}i&&i.params?d=d.concat(hs(o.path,i.params)):d=d.concat(hs(o.path)),d.length>0&&(c.parameters=d);let p=o.validationSchemas?.body||o.validationSchemas?.all;if(p){let u="application/json";i?.bodyType==="form-data"?u="multipart/form-data":i?.bodyType==="urlencoded"&&(u="application/x-www-form-urlencoded"),c.requestBody={content:{[u]:{schema:_e(p)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(c.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(c.responses={},i?.responses)for(let[u,m]of Object.entries(i.responses))c.responses[u]={description:`Response for ${u}`,content:{"application/json":{schema:_e(m)}}};if(i?.errors)for(let[u,m]of Object.entries(i.errors))c.responses[u]={description:`Error response for ${u}`,content:{"application/json":{schema:_e(m)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let u=[];Array.isArray(i.security)||(i.security=[i.security]);for(let m of i.security)if(m.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:m.bearerFormat||"JWT",description:m.description}),u.push({bearer:[]});else if(m.type==="apiKey")s.securitySchemes[m.name]||(s.securitySchemes[m.name]={type:"apiKey",name:m.name,in:m.in,description:m.description}),u.push({[m.name]:[]});else if(m.type==="oauth2"){let h=m.name||"oauth2";s.securitySchemes[h]||(s.securitySchemes[h]={type:"oauth2",flows:m.flows,description:m.description}),u.push({[h]:[]});}else if(m.type==="openIdConnect"){let h=m.name||"openIdConnect";s.securitySchemes[h]||(s.securitySchemes[h]={type:"openIdConnect",openIdConnectUrl:m.openIdConnectUrl,description:m.description}),u.push({[h]:[]});}u.length&&(c.security=u);}else n.security&&(c.security=n.security);t[o.path][a]=c;}return {openapi:"3.0.0",info:{title:n.title,description:n.description,version:n.version,...n.info},servers:n.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:s,security:n.security||[],tags:n.tags?Object.entries(n.tags).map(([o,i])=>({name:o,...i})):[]}}function No(n,e){return `
1091
+ `));let o=s.reduce((c,d)=>c+d.byteLength,0),i=new Uint8Array(o),a=0;for(let c of s)i.set(c,a),a+=c.byteLength;return i}async handleGraphQLRequest(e,t,r={}){let s=await this.ensureGraphQLHandler();if(!s){let p=new D(500);return p.json({errors:[{message:"GraphQL handler not initialized"}]}),new de(p)}let{headers:o={},query:i={}}=r,a=new URL(`http://${this.server.host}:${this.server.port}${t}`);a.search=new URLSearchParams(i).toString();let c;r.body!==void 0&&ae(e)&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?c=JSON.stringify(r.body):c=r.body);let d=new globalThis.Request(a.toString(),{method:e.toUpperCase(),body:c,headers:{"content-type":"application/json",...o}}),l=oe.fromRequest(d);l.query={...Object.fromEntries(a.searchParams.entries()),...i};try{let{HeaderMap:p}=await import('@apollo/server'),u=new p;for(let[M,B]of Object.entries(o))B!==void 0&&u.set(M,Array.isArray(B)?B.join(", "):String(B));let h=(u.get("content-type")??"").includes("application/json"),f="";typeof c=="string"?f=c:c instanceof Uint8Array?f=new TextDecoder().decode(c):c&&typeof c=="object"&&(f=new TextDecoder().decode(new Uint8Array(c)));let g=h&&f?JSON.parse(f):f,y={method:e.toUpperCase(),headers:u,body:g,search:a.search},T=this.server.graphql.getApolloOptions(),w=T.context&&typeof T.context=="function"?await T.context({req:l}):{req:l},b=await s.server.executeHTTPGraphQLRequest({httpGraphQLRequest:y,context:async()=>w}),S=b.status??200,R=new D(S);for(let[M,B]of b.headers)R.setHeader(M,B);if(b.body.kind==="complete"){let M=b.body.string;try{R.json(JSON.parse(M));}catch{R.text(M);}}else {let M="";for await(let B of b.body.asyncIterator)M+=B;try{R.json(JSON.parse(M));}catch{R.text(M);}}return new de(R)}catch(p){this.logger.error({error:p},`Error processing GraphQL request ${e} ${t}:`);let u=new D(500);return u.json({errors:[{message:"Internal server error"}]}),new de(u)}}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var ze=new async_hooks.AsyncLocalStorage,or=n=>async(e,t,r)=>{let s={};for(let[o,i]of Object.entries(n))s[o]=i(e);ze.run(s,()=>{e.ctx=new Proxy({},{get(o,i){return ze.getStore()?.[i]},set(o,i,a){let c=ze.getStore();return c?(c[i]=a,true):false},ownKeys(){let o=ze.getStore();return o?Object.keys(o):[]},has(o,i){let a=ze.getStore();return a?i in a:false}}),r();});};var xt=class extends O{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};G();var nr=class{async tmpdir(){switch(E.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},Vr=new nr;var Kr=1024*1024,Xr=10*1024*1024,Yr=n=>async(e,t,r)=>{let s=[];try{let o=e.headers.get("content-type")??e.headers.get("Content-Type");if(!o||!o.startsWith("multipart/form-data")||e.body||e.bodyUsed)return r();let i=e.headers.get("content-length"),a=ye(n?.maxFileSize,Xr)??Xr;if(i&&parseInt(i)>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let c=o.match(/boundary=(.*)(;|$)/i);if(!c)return r();let d=c[1].replace(/(^\s*"?|"?\s*$)/g,""),l=new Uint8Array(await e.toWebApi().arrayBuffer());if(l.length>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let p=new TextEncoder().encode(`--${d}`),u=new Uint8Array([13,10,13,10]),m=[],h=(w,b,S=0)=>{e:for(let R=S;R<=w.length-b.length;R++){for(let M=0;M<b.length;M++)if(w[R+M]!==b[M])continue e;return R}return -1},f=h(l,p);for(;f!==-1&&(f+=p.length,!(l[f]===45&&l[f+1]===45));){l[f]===13&&l[f+1]===10&&(f+=2);let w=h(l,u,f);if(w===-1)break;let b=l.subarray(f,w),S=new TextDecoder().decode(b),R=w+u.length,M=h(l,p,R);if(M===-1)break;let B=M-1;l[B]===10&&B--,l[B]===13&&B--;let ce=l.subarray(R,B+1);m.push({headers:S,data:ce}),f=M;}let g=[],y={},T=ye(n?.maxFileSize,Kr)??Kr;for(let w of m){let b=w.headers.split(`\r
1092
+ `).find(le=>le.toLowerCase().startsWith("content-disposition:"));if(!b)continue;let S=b.match(/name="([^"]+)"/);if(!S)continue;let R=S[1],M=b.match(/filename="([^"]*)"/),B=M?M[1]:"";if(!!B){if(n?.maxFiles&&g.length>=n.maxFiles)return t.badRequest({...L(new O(`Too many files: Maximum ${n.maxFiles} files allowed`))});if(T&&w.data.length>T)return t.badRequest({...L(new xt(B,w.data.length,T))});let le=w.headers.split(`\r
1093
+ `).find(ys=>ys.toLowerCase().startsWith("content-type:")),Z=le?le.split(":")[1].trim():"application/octet-stream";if(n?.allowedMimeTypes&&!n.allowedMimeTypes.includes(Z))return t.badRequest({...L(new O(`Invalid file type: "${Z}" is not allowed. Allowed types: ${n.allowedMimeTypes.join(", ")}`))});let Ht=mo(Z),Nt=x.join(await Vr.tmpdir(),`${ee.randomUUID()}${Ht}`);await v.writeFile(Nt,w.data),s.push(Nt),g.push({formName:R,mimeType:Z,size:w.data.length,tmpPath:Nt,originalName:B});}else y[R]=new TextDecoder().decode(w.data);}e.files=g,e.body=y,e.bodyUsed=!0,await r(),await Zr(s);}catch(o){throw await Zr(s),o}},Zr=async n=>{await Promise.allSettled(n.map(e=>v.unlink(e)));};var mo=n=>({"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","application/pdf":".pdf","text/plain":".txt","application/json":".json","text/csv":".csv","application/octet-stream":".bin","application/x-www-form-urlencoded":".urlencoded","application/xml":".xml","application/yaml":".yaml","application/yml":".yml","application/csv":".csv","application/txt":".txt","application/markdown":".markdown"})[n.toLowerCase()]||".bin";var Ye=class extends O{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var es=100*1024,ts=n=>async(e,t,r)=>{if(!ho(e)||!ae(e.method)||e.bodyUsed)return r();let s=ye(n?.sizeLimit,es)??es,o=e.headers.get("content-length");if(o&&Number.parseInt(o)>s){let i={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...n?.customErrorMessage};return t.status(i.status).json({error:i.message})}if(e.body||e.bodyUsed)return r();try{let i=e.toWebApi();e.body=await i.json(),e.bodyUsed=!0;}catch(i){return i instanceof SyntaxError?t.badRequest({...L(new Ye("Invalid JSON syntax"))}):t.badRequest({...L(new Ye("Invalid request body encoding"))})}await r();};function ho(n){let e=fo(n);return e?go(e)==="application/json":false}function fo(n){let e=n.headers.get("content-type")??n.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function go(n){let e=n.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var rs=1024*1024,ss=n=>{let t={limit:ye(n?.limit,rs)??rs,extended:n?.extended??false,charset:n?.charset??"utf8",allowEmpty:n?.allowEmpty??true,parameterLimit:n?.parameterLimit??1e3};return async(r,s,o)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();let a=r.headers.get("content-length");if(a&&parseInt(a)>t.limit){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}try{await yo(r,t),await o();}catch(c){if(c instanceof Error&&c.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw c}}};async function yo(n,e){if(n.body||n.bodyUsed)return;let r=await n.toWebApi().arrayBuffer();if(r.byteLength>e.limit)throw new Error(`Body size ${r.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(r),i=vo(o,e);n.body=i,n.bodyUsed=true;}function vo(n,e){let t={},r=new URLSearchParams(n);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,o]of r.entries())!e.allowEmpty&&o===""||(e.extended?bo(t,s,o):t[s]=o);return t}function bo(n,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(n[e]=t);return}let o=n,i=e.split("[")[0];if(r.includes(i))return;for(let c=0;c<s.length-1;c++){let d=s[c].slice(1,-1);if(r.includes(d))return;if(o[i]||(o[i]={}),d===""){Array.isArray(o[i])||(o[i]=[]),o=o[i];continue}o[i][d]||(o[i][d]={}),o=o[i][d];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t;}}var wo=n=>(n.headers.get("content-type")??n.headers.get("Content-Type"))?.split(";")[0]??null,os=n=>{let e=n.json,t=n.urlencoded,r=n.fileParser;return async(s,o,i)=>{if(!ae(s.method)||s.bodyUsed)return i();let a=wo(s);if(a==="application/json"&&e)return ts(e)(s,o,i);if(a==="multipart/form-data"&&r)return Yr(r)(s,o,i);if(a==="application/x-www-form-urlencoded"&&t)return ss(t)(s,o,i);if(a?.includes("text/")){let c=new TextDecoder,d=s.toWebApi();s.body=c.decode(await d.arrayBuffer()),s.bodyUsed=true;}return !s.body&&!s.bodyUsed&&(s.body=await s.toWebApi().arrayBuffer()),i()}};var xo=1024,To=6,Po=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],ir=n=>{let e=n?.threshold??xo,t=Math.max(0,Math.min(9,n?.level??To)),r=n?.filter??Po;return async(s,o,i)=>{if(!(s.headers.get("accept-encoding")||"").includes("gzip"))return i();let d=o.send.bind(o),l=o.text.bind(o),p=(u,m)=>{if(!Co(u,m,e,r))return u;let h=ns(u);if(!h||h.length<e)return u;let f=zlib.gzipSync(h,{level:t});return o.setHeader("Content-Encoding","gzip"),o.setHeader("Content-Length",f.length.toString()),f};o.send=function(u){let m=o.headers["content-type"],h=p(u,m);return d(h)},o.json=function(u,m){let h=null;if(m){let{jsonSchema:y,prefix:T}=Oo(m);h=A.getOrCreateSerializer(y,T);}let f=h&&typeof u=="object"&&u!==null?h(u):typeof u=="string"?u:JSON.stringify(u),g=p(f,"application/json");return g!==f?(o.setHeader("Content-Type","application/json"),d(g)):d(f)},o.text=function(u){let m=p(u,"text/plain");return m!==u?(o.setHeader("Content-Type","text/plain"),d(m)):l(u)},await i();}},Oo=n=>_.isZodSchema(n)?{jsonSchema:_.toJSONSchema(n),prefix:"fast_stringify_zod"}:F.isTypeBoxSchema(n)?{jsonSchema:n,prefix:"fast_stringify_typebox"}:typeof n=="object"&&n!==null?{jsonSchema:n,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof n},prefix:`fast_stringify_primitive_${JSON.stringify(n)}`},Co=(n,e,t,r)=>{if(!n||!e)return false;let s=ns(n);return !s||s.length<t?false:r.some(o=>o.test(e))},ns=n=>typeof n=="string"?Buffer.from(n,"utf-8"):Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n):typeof n=="object"?Buffer.from(JSON.stringify(n),"utf-8"):null;var ar=n=>{let e={secret:n?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...n?.defaults},parse:n?.parse??true,sign:n?.sign??false};return async(t,r,s)=>{if(e.parse){let o=Ro(t.headers.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(o)){if(e.sign&&e.secret){let c=await Mo(a,e.secret);c!==false&&(t.cookies[i]=c);continue}t.cookies[i]=a;}}r.cookie=(o,i,a)=>{is(r,o,i,{...e.defaults,...a},e);},r.clearCookie=(o,i)=>{jo(r,o,{...e.defaults,...i});},await s();}};function Ro(n){let e={};if(!n)return e;let t=n.split(";");for(let r of t){let[s,o]=r.trim().split("=");s&&o&&(e[decodeURIComponent(s)]=decodeURIComponent(o));}return e}async function is(n,e,t,r,s){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires&&(o+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(o+=`; Max-Age=${r.maxAge}`),r.secure&&(o+="; Secure"),r.httpOnly&&(o+="; HttpOnly"),r.sameSite&&(o+=`; SameSite=${r.sameSite}`),r.priority&&(o+=`; Priority=${r.priority}`),s.sign&&s.secret&&(o=await qo(o,s.secret));let i=n.headers["set-cookie"]||"",a=i?`${i}, ${o}`:o;n.setHeader("Set-Cookie",a);}function jo(n,e,t){let r={...t,expires:new Date(0),maxAge:0};is(n,e,"",r,{secret:"",sign:false});}async function qo(n,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(n),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",o,s),a=new Uint8Array(i),c=Array.from(a).map(d=>d.toString(16).padStart(2,"0")).join("");return `${n}.${c}`}async function Mo(n,e){let t=n.split(".");if(t.length!==2)return false;let[r,s]=t,o=new TextEncoder,i=o.encode(e),a=o.encode(r),c=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(d),p=Array.from(l).map(u=>u.toString(16).padStart(2,"0")).join("");return s===p?r:false}var cr=n=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...n};return async(t,r,s)=>{let o=t.headers.get("origin")||"";if(t.method==="OPTIONS")return Eo(t,r,e,o,s);Ao(t,r,e,o),await s();}};function Eo(n,e,t,r,s){let o=as(t,r);if(!o){e.forbidden("CORS origin not allowed");return}if(cs(e,t,o),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Ao(n,e,t,r){let s=as(t,r);s&&cs(e,t,s);}function as(n,e){if(typeof n.origin=="string")return n.origin;if(Array.isArray(n.origin)){let t=n.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function cs(n,e,t){if(n.setHeader("Access-Control-Allow-Origin",t),e.credentials&&n.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;n.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;n.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;n.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&n.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function ls(n,e=""){let t=new URL(n.url),r=Object.fromEntries(n.headers.entries()),o=n.headers.get("x-forwarded-proto")||t.protocol.replace(":","");return {body:n.body,query:n.query,params:n.params,cookies:n.cookies,session:n.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:n.method,ip:n.ip,headers:r,url:t.pathname,get(a){return n.headers.get(a.toLowerCase())??void 0},header(a){return n.headers.get(a.toLowerCase())??void 0},app:{},res:null,route:null,protocol:o,secure:o==="https",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:a=>n.params[a]??n.query[a],files:n.files,file:n.file,rawBody:n.body}}function ps(n){return {locals:{},headersSent:false,statusCode:n.responseStatus,status(t){return n.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!n.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return n.html(t),this}return n.send(t),this},json(t){return this.headersSent=true,n.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,o=typeof t=="number"?t:302;return n.status(o).setHeader("Location",s),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return n.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,o]of Object.entries(t))n.setHeader(s,o);else r!==void 0&&n.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return n.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,n.send(t??""),this},write(t){return q.warn({method:"write"},"res.write() is not fully supported in Express compatibility layer - responses will be buffered"),true},get(t){return n.headers[t]},getHeader(t){return n.headers[t]},removeHeader(t){return delete n.headers[t],this},append(t,r){let s=n.headers[t],o=Array.isArray(r)?r.join(", "):r;return n.setHeader(t,s?`${s}, ${o}`:o),this},cookie(t,r,s){return n.cookie?.(t,r,s),this},clearCookie(t,r){return n.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){throw new Error("format() is not supported in Express compatibility layer")},attachment(t){return t?n.setHeader("Content-Disposition",`attachment; filename="${t}"`):n.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){n.file(t);},download(t,r,s,o){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),n.file(t);},links(t){let r=Object.entries(t).map(([s,o])=>`<${o}>; rel="${s}"`).join(", ");return n.setHeader("Link",r),this},location(t){return n.setHeader("Location",t),this},vary(t){return n.setHeader("Vary",t),this},app:{},req:null}}function $e(n,e=""){return async(t,r,s)=>{let o=ls(t,e),i=ps(r);o.res=i,i.req=o;let a=false,c=3e4;await Promise.race([new Promise((d,l)=>{let p=u=>{if(a=true,u){l(u);return}d();};try{let u=n(o,i,p);u instanceof Promise&&u.catch(l);}catch(u){l(u);}}),new Promise(d=>{setTimeout(()=>{!a&&!i.headersSent&&q.warn({basePath:e,timeout:c},"Express middleware did not call next() within timeout and did not send response"),d();},c);})]),i.headersSent||await s();}}function ds(n,e=""){return async(t,r)=>{let s=ls(t,e),o=ps(r);s.res=o,o.req=s;let i=()=>{};try{await n(s,o,i);}catch(a){throw q.error({error:a,basePath:e},"Express handler threw an error"),a}}}function et(n,e){let t=lr(n),r=e.stack;if(!r){q.warn({basePath:n},"Express router has no stack - routes may not be registered");return}for(let s of r)us(s,t);}function us(n,e){if(n.route){let t=lr(e+n.route.path),r=Object.keys(n.route.methods).filter(s=>n.route.methods[s]);for(let s of r){let o=n.route.stack.map(i=>i.handle);ko(s.toUpperCase(),t,o,e);}return}if(n.handle&&typeof n.handle=="function"){let t=n.path||"",r=lr(e+t),s=n.handle.stack;if(s&&Array.isArray(s)){for(let c of s)us(c,r);return}let o=r==="/"?"/*":`${r}/*`,i=$e(n.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)$.addOrUpdate(c,o,[i],async()=>{},{},{excludeFromSwagger:true});}}function ko(n,e,t,r){let s=t.slice(0,-1).map(a=>$e(a,r)),o=t[t.length-1],i=ds(o,r);$.addOrUpdate(n,e,s,i,{},{excludeFromSwagger:true});}function lr(n){let e=n.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function pr(n){return {use(e,t){if(typeof e=="string"){let o=e,i=t,a=i.stack;if(a&&Array.isArray(a)){et(o,i);return}n.use($e(i,o));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){et("/",r);return}n.use($e(r));}}}var dr=n=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...n};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let o="SAMEORIGIN";typeof e.frameguard=="object"&&(o=e.frameguard.action),r.setHeader("X-Frame-Options",o);}if(e.hsts){let o={};typeof e.hsts=="object"&&(o=e.hsts);let i=o.maxAge!==void 0?o.maxAge:15552e3,a=o.includeSubDomains!==void 0?o.includeSubDomains:true,c=o.preload!==void 0?o.preload:false,d=`max-age=${i}`;a!==false&&(d+="; includeSubDomains"),c&&(d+="; preload"),r.setHeader("Strict-Transport-Security",d);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await s();}};var ur=n=>{let e=q.child({scope:"LogMiddleware"});return async(t,r,s)=>{try{let o=t.body;(n?.logRequest??!0)&&e.info({type:"request",requestId:t.id,method:n?.requestPayload?.method??!0?t.method:void 0,url:n?.requestPayload?.url??!0?t.url:void 0,ip:n?.requestPayload?.ip??!0?t.ip:void 0,headers:n?.requestPayload?.headers??!0?t.headers:void 0,body:n?.requestPayload?.body??!1?ms(o):void 0});let i=performance.now();await s();let c=performance.now()-i;(n?.logResponse??!0)&&e.info({type:"response",requestId:t.id,status:n?.responsePayload?.status??r.responseStatus,duration:`${c.toFixed(2)}ms`,body:n?.responsePayload?.body??!1?ms(r.getBody()):void 0,headers:n?.responsePayload?.headers??!1?r.headers:void 0});}catch(o){throw e.error(o),o}}};function ms(n){if(typeof n=="string"||n&&typeof n=="object"&&n.constructor===Object)return n}var $o=["POST"],_o="X-HTTP-Method-Override",Bo=["GET","POST","PUT","PATCH","DELETE"],mr=n=>{let e=(n?.methods??$o).map(r=>r.toUpperCase()),t=n?.header??_o;return async(r,s,o)=>{let i=r.method.toUpperCase();if(!e.includes(i))return o();let a=r.headers.get(t);if(!a)return o();let c=a.toUpperCase();if(!Bo.includes(c))return o();r.method=c,await o();}};var Tt=class{storage=new Map;timers=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){let r=this.timers.get(e);r&&clearTimeout(r),this.storage.set(e,t);let s=setTimeout(()=>{this.storage.delete(e),this.timers.delete(e);},this.windowMs);this.timers.set(e,s);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){let t=this.timers.get(e);t&&clearTimeout(t),this.storage.delete(e),this.timers.delete(e);}};var hr=(n,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...n},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new Tt(r.windowMs):{get:r.get,set:r.set};return async(o,i,a)=>{let c=t.type==="ip"?o.ip:t.key(o),d=await s.get(c);return d>=t.limit?i.status(t.statusCode).json({message:t.message}):(await s.set(c,d+1),a())}};var Pt=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var fr=n=>{let e=n?.name??"sid",t=n?.ttl??3600*24,r=n?.store??new Pt,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...n?.cookie??{}};return async(o,i,a)=>{let d=o.cookies&&o.cookies[e],l=d?await r.get(d):void 0;(!d||!l)&&(d||=ee.randomUUID(),l||={},await r.set(d,l,t),i.cookie?.(e,d,s)),o.session=l,o.saveSession=async()=>r.set(d,l,t),o.destroySession=async()=>{await r.destroy(d),i.clearCookie?.(e,s);},await a(),await r.set(d,l,t);}};var fs=n=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};n&&typeof n!="boolean"&&(e={...e,...n});let t=Ho(e),r=`${e.path}`,s=`${r}/json`,o;e.type==="rapidoc"?o=Lo(s,e):e.type==="scalar"?o=Fo(s,e):e.type==="elements"?o=Io(s,e):e.type==="custom"?o=e.customUIGenerator(s,e):o=No(s,e),$.addOrUpdate("GET",r,[],(i,a)=>{a.html(o);}),$.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);});},ge=n=>n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function _e(n){if(!n||typeof n!="object")return {type:"string"};let e="json_schema";_.isZodSchema(n)?e="zod_schema":F.isTypeBoxSchema(n)&&(e="typebox_schema");let t=A.getJsonSchema(n,e);if(t)return t;if(_.isZodSchema(n))try{let s=_.toJSONSchema(n);return A.storeJsonSchema(s,e),s}catch(s){return q.debug({error:s instanceof Error?s.message:String(s),schemaType:n?.constructor?.name||typeof n},"Failed to convert Zod schema to JSON Schema for Swagger documentation"),{type:"object"}}let r=n;return A.storeJsonSchema(r,e),r}function Ho(n){let e=$.getRoutes(),t={},r;if(n.models)if(Array.isArray(n.models))r=n.models.reduce((o,i,a)=>{let c=_e(i),d=c.$id||c.title||`Model${a}`;return o[d]=c,o},{});else {r={};for(let[o,i]of Object.entries(n.models))r[o]=_e(i);}let s={...n.components,securitySchemes:n.securitySchemes||{},schemas:r?{...n.components?.schemas||{},...r}:n.components?.schemas?{...n.components.schemas}:void 0};for(let o of e){let i=o.swaggerOptions;if(i?.excludeFromSwagger)continue;t[o.path]||(t[o.path]={});let a=o.method.toLowerCase(),c={summary:i?.name||`${a.toUpperCase()} ${o.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},d=[],l=o.validationSchemas?.query;if(l){let u=l;if(u.type==="object"&&u.shape)for(let[m,h]of Object.entries(u.shape))!h||typeof h!="object"||d.push({name:m,in:"query",required:Array.isArray(u.shape[m].required)?u.shape[m].required.includes(m):false,schema:_e(h)});}i&&i.params?d=d.concat(hs(o.path,i.params)):d=d.concat(hs(o.path)),d.length>0&&(c.parameters=d);let p=o.validationSchemas?.body||o.validationSchemas?.all;if(p){let u="application/json";i?.bodyType==="form-data"?u="multipart/form-data":i?.bodyType==="urlencoded"&&(u="application/x-www-form-urlencoded"),c.requestBody={content:{[u]:{schema:_e(p)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(c.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(c.responses={},i?.responses)for(let[u,m]of Object.entries(i.responses))c.responses[u]={description:`Response for ${u}`,content:{"application/json":{schema:_e(m)}}};if(i?.errors)for(let[u,m]of Object.entries(i.errors))c.responses[u]={description:`Error response for ${u}`,content:{"application/json":{schema:_e(m)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let u=[];Array.isArray(i.security)||(i.security=[i.security]);for(let m of i.security)if(m.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:m.bearerFormat||"JWT",description:m.description}),u.push({bearer:[]});else if(m.type==="apiKey")s.securitySchemes[m.name]||(s.securitySchemes[m.name]={type:"apiKey",name:m.name,in:m.in,description:m.description}),u.push({[m.name]:[]});else if(m.type==="oauth2"){let h=m.name||"oauth2";s.securitySchemes[h]||(s.securitySchemes[h]={type:"oauth2",flows:m.flows,description:m.description}),u.push({[h]:[]});}else if(m.type==="openIdConnect"){let h=m.name||"openIdConnect";s.securitySchemes[h]||(s.securitySchemes[h]={type:"openIdConnect",openIdConnectUrl:m.openIdConnectUrl,description:m.description}),u.push({[h]:[]});}u.length&&(c.security=u);}else n.security&&(c.security=n.security);t[o.path][a]=c;}return {openapi:"3.0.0",info:{title:n.title,description:n.description,version:n.version,...n.info},servers:n.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:s,security:n.security||[],tags:n.tags?Object.entries(n.tags).map(([o,i])=>({name:o,...i})):[]}}function No(n,e){return `
1092
1094
  <!DOCTYPE html>
1093
1095
  <html lang="en">
1094
1096
  <head>
@@ -1218,6 +1220,6 @@ ${p}\r
1218
1220
  <script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
1219
1221
  </body>
1220
1222
  </html>
1221
- `}function hs(n,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(n))!==null;){let o=s[1],i={type:"string"};e&&e.shape&&e.shape[o]&&(i=_e(e.shape[o])||{type:"string"}),t.push({name:o,in:"path",required:true,schema:i});}return t}var gr=n=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},n.ms);try{await r();}finally{clearTimeout(s);}};var yr=n=>{let e=n?.header??"x-forwarded-for",t=n?.trust??true,r=n?.hop??"first";return async(s,o,i)=>{if(!t)return i();let a=s.headers.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(d=>d.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var vr=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),o=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},o,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),o=e.split(":");if(o.length!==2)throw new Error("Invalid hash format");let[i,a]=o,c=this.decodeBase64(i),d=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),p=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),u=new Uint8Array(p);if(u.length!==d.length)return !1;let m=0;for(let h=0;h<u.length;h++)m|=u[h]^d[h];return m===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let o=0;o<r;o++)s[o]=t.charCodeAt(o);return s}},tt=new vr;var Pt=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},o=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let d=a.url,l=d.indexOf("://")+3,p=d.indexOf("/",l),u=p===-1?"/":d.slice(p),m=u.indexOf("?"),h=m===-1?u:u.slice(0,m),f=m===-1?"":u.slice(m+1),g=$.find(a.method,h),y=oe.fromRequest(a);y.params=g?.params??{},y.setQueryString(f);let T=a.headers.get("x-forwarded-for");if(y.ip=T?T.split(",")[0].trim():c.requestIP(a)?.address,await t?.call(this,y,c),o&&h.startsWith(i)){let S=await this.ensureGraphQLHandler();if(S){let R=y.toWebApi();return vt(S.server,R,a.method,f,{req:y,server:c})}}if(r&&y.headers.get("upgrade")==="websocket"){let S=y.toWebApi();if(c.upgrade(S,{data:{}}))return}let w=new D;return w.setRouteResponseSchemas(g?.responseSchemas),await he(g?.middleware??[],g?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),y,w),D.toWebResponse(w)},...r?{websocket:r}:{},...s}),this.url=this.runtimeServer.url.toString();}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Ot=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,o="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,d=c.indexOf("://")+3,l=c.indexOf("/",d),p=l===-1?"/":c.slice(l),u=p.indexOf("?"),m=u===-1?p:p.slice(0,u),h=u===-1?"":p.slice(u+1),f=$.find(i.method,m),g=oe.fromRequest(i);g.params=f?.params??{},g.setQueryString(h);let y=i.headers.get("x-forwarded-for");if(g.ip=y?y.split(",")[0].trim():a.remoteAddr?.hostname,await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&m.startsWith(o)){let S=await this.ensureGraphQLHandler();if(S){let R=g.toWebApi();return vt(S.server,R,i.method,h,{req:g,info:a})}}if(g.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let S=g.toWebApi(),{socket:R,response:M}=Deno.upgradeWebSocket(S);return this.tapOptions?.deno?.websocket?.open&&(R.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(R)),this.tapOptions?.deno?.websocket?.message&&(R.onmessage=B=>{this.tapOptions?.deno?.websocket?.message?.(R,B.data);}),this.tapOptions?.deno?.websocket?.close&&(R.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(R)),M}let w=new D;return w.setRouteResponseSchemas(f?.responseSchemas),await he(f?.middleware??[],f?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),g,w),D.toWebResponse(w)},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Wo=async(n,e)=>{let t=stream.Readable.fromWeb(n);return promises.pipeline(t,e)},Ct=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure";let r=this.graphql.isEnabled,s="/graphql";this.runtimeServer=this.createServer(async(o,i)=>{if(this.tapOptions&&this.tapOptions.node){let y=this.tapOptions.node;await y?.(o);}let a=o.url,c=a.indexOf("?"),d=c===-1?a:a.slice(0,c),l=c===-1?"":a.slice(c+1);if(r&&d.startsWith(s)){let y=await this.ensureGraphQLHandler();if(y){let T=ae(o.method)?await this.readRequestBody(o):"";await Jr(y.server,o.headers,o.method??"POST",T,l,{req:o},async(w,b,S)=>{for(let[R,M]of w)i.setHeader(R,M);if(i.statusCode=b,typeof S=="string")i.end(S);else {for await(let R of S)i.write(R);i.end();}});return}}let p=$.find(o.method,d),u=this.processHeaders(o.headers),m=new oe;m.url=`${this.url}${a}`,m.method=o.method,ae(o.method)&&m.setNodeRequest(o),m.headers=new Headers(u),m.ip=this.extractClientIp(o),m.setQueryString(l),m.params=p?.params??{};let h=new D;h.nodeResponse=i,h.setRouteResponseSchemas(p?.responseSchemas);let f=await he(p?.middleware??[],p?.handler??((y,T)=>{T.notFound({...L(new z(y.url,y.method))});}),m,h);if(i.headersSent||i.writableEnded)return;let g=f.getBody();if(g instanceof ReadableStream){i.writeHead(f.responseStatus,f.headers),Wo(g,i);return}i.writeHead(f.responseStatus,f.headers),g instanceof Buffer||g instanceof Uint8Array||typeof g=="string"?i.end(g):f.headers["Content-Type"]==="application/json"?i.end(typeof g=="string"?g:JSON.stringify(g)):i.end(g!=null?String(g):void 0);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let o=e[s];o!==void 0&&(t[s]=Array.isArray(o)?o.join(", "):o);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",o=>s.push(Buffer.from(o))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var Rt=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Pt(e);if(e?.runtime==="node")return new Ct(e);if(e?.runtime==="deno")return new Ot(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};G();var jt=class{_brand="BaldaServer";#t=new Qe;serverOptions;router=$;logger;isListening;isProduction;graphql;#s;#e;#r=[];#n=["node_modules"];#o;#i;constructor(e){this.#s=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.#t.get("PORT"))??80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal,cronUI:e?.cronUI},this.logger=(e?.logger??q).child({scope:"Balda"}),e?.ajvInstance&&A.setGlobalInstance(e.ajvInstance),this.#i=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new se(this.serverOptions.graphql),this.#e=new Rt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:E.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#i,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}get host(){return this.#e.host}get routes(){return $.getRoutes()||[]}get fs(){return v}async hash(e){return tt.hash(e)}async compareHash(e,t){return tt.compare(e,t)}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}get(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("GET",e,s,o,l,d);}post(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("POST",e,s,o,l,d);}patch(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PATCH",e,s,o,l,d);}put(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PUT",e,s,o,l,d);}delete(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("DELETE",e,s,o,l,d);}options(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("OPTIONS",e,s,o,l,d);}head(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("HEAD",e,s,o,l,d);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(E.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(E.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(E.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){Fe.exit(e);}on(e,t){switch(E.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}once(e,t){switch(E.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}use(...e){this.#r.push(...e);}useExpress(e,t){pr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){et(e,t);}setErrorHandler(e){this.#r.unshift(async(t,r,s)=>{try{await s();}catch(o){await e?.(t,r,s,o);}});}setNotFoundHandler(e){this.#o=e?.bind(this);}listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let t={port:this.port,host:this.host,url:this.url};this.bootstrap().then(()=>{this.#e.listen(),this.isListening=true,e?.({...t,error:void 0});}).catch(r=>{e?.({...t,error:r});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e();});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}configureHash(e){tt.configure(e);}async getMockServer(e){return await this.bootstrap(e),new wt(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>v.glob(s,{cwd:N.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#n.some(o=>s.includes(o))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(o=>{this.logger.error(`Error importing controller ${s}: ${o}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,body:r.body,query:r.query,all:r.all,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(os(r));break;case "cors":this.use(cr(r));break;case "static":this.use(rr(r));break;case "helmet":this.use(dr(r));break;case "cookie":this.use(ar(r));break;case "methodOverride":this.use(mr(r));break;case "compression":this.use(ir(r));break;case "log":this.use(ur(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:o}=r;this.use(hr(s,o));break;case "trustProxy":this.use(yr(r));break;case "timeout":this.use(gr(r));break;case "session":this.use(fr(r));break;case "asyncLocalStorage":this.use(or(r));break;default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#s||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.cronUI&&await Hr(this.serverOptions.cronUI),this.serverOptions.swagger&&fs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#r.length&&$.applyGlobalMiddlewaresToAllRoutes(this.#r),this.#s=true);}handleNotFound=(e,t)=>{if(this.#o){this.#o(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],o=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=$.find(a,r);c&&c.handler!==this.handleNotFound&&o.push(a);}if(o.length){t.setHeader("Allow",o.join(", "));let a=new Ue(r,e.method);t.methodNotAllowed({...L(a)});return}let i=new z(r,e.method);t.notFound({...L(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)$.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true});}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var gs=()=>{let n=A.getCacheStats(),e=n.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:n.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:n.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Vo=()=>{let n=gs();q.info({validators:n.validators.size,totalSchemaRefs:n.totalSchemaReferences,memoryEstimate:n.memoryEstimate.total},"Schema cache metrics");},Ko=()=>{A.clearAllCaches(),q.debug("All schema caches cleared");};var K=class extends O{constructor(e){super(`File not found: ${e}`);}};var br=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new K(e);let o=t;if(o==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(o){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new O("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new K(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),o=t;await s.upload(o,o.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new O("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new O("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var wr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new O("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await v.exists(r))return [];let o=[];return await this.listFilesRecursively(r,t,o),o}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await v.exists(r))throw new K(e);switch(t){case "raw":return await v.readFile(r);case "text":return await v.readFile(r,{encoding:"utf8"});case "stream":return await v.streamFile(r);default:throw new O("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),o=x.join(s,"..");await v.mkdir(o,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await v.exists(t)&&await v.unlink(t);}async listFilesRecursively(e,t,r){let s=await v.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let o=await this.readDirectory(e);for(let i of o){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(G(),jr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new O("Unsupported runtime")}}async ensureDirectoryExists(){if(await v.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await v.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};G();var Sr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=E.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:o}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:o,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new O("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new K(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new O("Invalid return type")}}catch(s){throw s instanceof K?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new K(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new K(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new O("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new K(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var xr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var qt=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new O("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Mt=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new O("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Et=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new O("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var At=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new O("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var kt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,o)=>{let i=t[s];return i===void 0?r:o&&this.helpers.has(o)?this.helpers.get(o)(i):String(i)})}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var rt=class extends O{constructor(e){super(e),this.name="MailerError";}},st=class extends rt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},$t=class extends rt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},_t=class extends rt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ot=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,o=s.build();return s.hasTemplate()?this.sendWithTemplate(o):this.sendDirect(o)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new $t;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var Tr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new _t(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ot(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new st(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,o=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:o,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=Xt("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let o=s;o.isFilePath?r.templateFile(o.template,o.data):r.template(o.template,o.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new st(String(this.defaultProvider));return e}};var Pr=class{};var Or=n=>(e,t)=>(r,s,o)=>{let i={scope:e,handler:t,manager:n};if(typeof s>"u"){let c=j.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),j.set(r.prototype,"__class__",c),r}let a=j.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),j.set(r,s,a),o};var Cr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Or(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new O(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Zh=$,Yh=jt;
1222
- exports.AzureBlobStorageProvider=br;exports.BaseCron=Vt;exports.BasePlugin=Pr;exports.BullMQPubSub=Je;exports.Command=k;exports.CronService=J;exports.CustomAdapter=kt;exports.EdgeAdapter=Mt;exports.EjsAdapter=At;exports.GraphQL=se;exports.HandlebarsAdapter=qt;exports.LocalStorageProvider=wr;exports.MailOptionsBuilder=Be;exports.MailProvider=ot;exports.Mailer=Tr;exports.MemoryPubSub=We;exports.MqttService=Le;exports.MustacheAdapter=Et;exports.PGBossPubSub=Ve;exports.PolicyManager=Cr;exports.QueueManager=re;exports.QueueService=W;exports.S3StorageProvider=Sr;exports.SQSPubSub=Ke;exports.Server=jt;exports.Storage=xr;exports.arg=H;exports.asyncLocalStorage=or;exports.asyncStorage=ze;exports.bullmqQueue=Xs;exports.clearAllSchemaCaches=Ko;exports.commandRegistry=Te;exports.compression=ir;exports.controller=Bs;exports.cookie=ar;exports.cors=cr;exports.createExpressAdapter=pr;exports.createPolicyDecorator=Or;exports.createQueue=Ys;exports.cron=ks;exports.default=Yh;exports.defineQueueConfiguration=eo;exports.del=Hs;exports.expressHandler=ds;exports.expressMiddleware=$e;exports.flag=C;exports.get=Ns;exports.getSchemaCacheMetrics=gs;exports.hash=tt;exports.helmet=dr;exports.log=ur;exports.logSchemaCacheMetrics=Vo;exports.logger=q;exports.memoryQueue=Xt;exports.methodOverride=mr;exports.middleware=Ds;exports.mountExpressRouter=et;exports.mqtt=Vs;exports.patch=Ls;exports.pgbossQueue=Zs;exports.post=Fs;exports.put=Is;exports.rateLimiter=hr;exports.router=Zh;exports.serialize=zs;exports.serveStatic=rr;exports.session=fr;exports.setCronGlobalErrorHandler=As;exports.setMqttGlobalErrorHandler=Ws;exports.sqsQueue=Ks;exports.timeoutMw=gr;exports.trustProxy=yr;exports.validate=Gs;//# sourceMappingURL=index.cjs.map
1223
+ `}function hs(n,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(n))!==null;){let o=s[1],i={type:"string"};e&&e.shape&&e.shape[o]&&(i=_e(e.shape[o])||{type:"string"}),t.push({name:o,in:"path",required:true,schema:i});}return t}var gr=n=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},n.ms);try{await r();}finally{clearTimeout(s);}};var yr=n=>{let e=n?.header??"x-forwarded-for",t=n?.trust??true,r=n?.hop??"first";return async(s,o,i)=>{if(!t)return i();let a=s.headers.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(d=>d.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var vr=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),o=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},o,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),o=e.split(":");if(o.length!==2)throw new Error("Invalid hash format");let[i,a]=o,c=this.decodeBase64(i),d=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),p=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),u=new Uint8Array(p);if(u.length!==d.length)return !1;let m=0;for(let h=0;h<u.length;h++)m|=u[h]^d[h];return m===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let o=0;o<r;o++)s[o]=t.charCodeAt(o);return s}},tt=new vr;var Ot=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},o=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let d=a.url,l=d.indexOf("://")+3,p=d.indexOf("/",l),u=p===-1?"/":d.slice(p),m=u.indexOf("?"),h=m===-1?u:u.slice(0,m),f=m===-1?"":u.slice(m+1),g=$.find(a.method,h),y=oe.fromRequest(a);y.params=g?.params??{},y.setQueryString(f);let T=a.headers.get("x-forwarded-for");if(y.ip=T?T.split(",")[0].trim():c.requestIP(a)?.address,await t?.call(this,y,c),o&&h.startsWith(i)){let S=await this.ensureGraphQLHandler();if(S){let R=y.toWebApi();return bt(S.server,R,a.method,f,{req:y,server:c})}}if(r&&y.headers.get("upgrade")==="websocket"){let S=y.toWebApi();if(c.upgrade(S,{data:{}}))return}let w=new D;return w.setRouteResponseSchemas(g?.responseSchemas),await he(g?.middleware??[],g?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),y,w),D.toWebResponse(w)},...r?{websocket:r}:{},...s}),this.url=this.runtimeServer.url.toString();}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Ct=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,o="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,d=c.indexOf("://")+3,l=c.indexOf("/",d),p=l===-1?"/":c.slice(l),u=p.indexOf("?"),m=u===-1?p:p.slice(0,u),h=u===-1?"":p.slice(u+1),f=$.find(i.method,m),g=oe.fromRequest(i);g.params=f?.params??{},g.setQueryString(h);let y=i.headers.get("x-forwarded-for");if(g.ip=y?y.split(",")[0].trim():a.remoteAddr?.hostname,await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&m.startsWith(o)){let S=await this.ensureGraphQLHandler();if(S){let R=g.toWebApi();return bt(S.server,R,i.method,h,{req:g,info:a})}}if(g.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let S=g.toWebApi(),{socket:R,response:M}=Deno.upgradeWebSocket(S);return this.tapOptions?.deno?.websocket?.open&&(R.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(R)),this.tapOptions?.deno?.websocket?.message&&(R.onmessage=B=>{this.tapOptions?.deno?.websocket?.message?.(R,B.data);}),this.tapOptions?.deno?.websocket?.close&&(R.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(R)),M}let w=new D;return w.setRouteResponseSchemas(f?.responseSchemas),await he(f?.middleware??[],f?.handler??((S,R)=>{R.notFound({...L(new z(S.url,S.method))});}),g,w),D.toWebResponse(w)},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Wo=async(n,e)=>{let t=stream.Readable.fromWeb(n);return promises.pipeline(t,e)},Rt=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;needsHeaderFiltering;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new se,this.ensureGraphQLHandler=fe(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure";let r=this.graphql.isEnabled,s="/graphql";this.runtimeServer=this.createServer(async(o,i)=>{if(this.tapOptions&&this.tapOptions.node){let y=this.tapOptions.node;await y?.(o);}let a=o.url,c=a.indexOf("?"),d=c===-1?a:a.slice(0,c),l=c===-1?"":a.slice(c+1);if(r&&d.startsWith(s)){let y=await this.ensureGraphQLHandler();if(y){let T=ae(o.method)?await this.readRequestBody(o):"";await Jr(y.server,o.headers,o.method??"POST",T,l,{req:o},async(w,b,S)=>{for(let[R,M]of w)i.setHeader(R,M);if(i.statusCode=b,typeof S=="string")i.end(S);else {for await(let R of S)i.write(R);i.end();}});return}}let p=$.find(o.method,d),u=this.processHeaders(o.headers),m=new oe;m.url=`${this.url}${a}`,m.method=o.method,ae(o.method)&&m.setNodeRequest(o),m.headers=new Headers(u),m.ip=this.extractClientIp(o),m.setQueryString(l),m.params=p?.params??{};let h=new D;h.nodeResponse=i,h.setRouteResponseSchemas(p?.responseSchemas);let f=await he(p?.middleware??[],p?.handler??((y,T)=>{T.notFound({...L(new z(y.url,y.method))});}),m,h);if(i.headersSent||i.writableEnded)return;let g=f.getBody();if(g instanceof ReadableStream){i.writeHead(f.responseStatus,f.headers),Wo(g,i);return}i.writeHead(f.responseStatus,f.headers),g instanceof Buffer||g instanceof Uint8Array||typeof g=="string"?i.end(g):f.headers["Content-Type"]==="application/json"?i.end(typeof g=="string"?g:JSON.stringify(g)):i.end(g!=null?String(g):void 0);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}processHeaders(e){let t={};if(this.needsHeaderFiltering){for(let s in e){if(s.charCodeAt(0)===58)continue;let o=e[s];o!==void 0&&(t[s]=Array.isArray(o)?o.join(", "):o);}return t}for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}return t}extractClientIp(e){let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",o=>s.push(Buffer.from(o))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var jt=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Ot(e);if(e?.runtime==="node")return new Rt(e);if(e?.runtime==="deno")return new Ct(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};G();var qt=class{_brand="BaldaServer";#t=new Qe;serverOptions;router=$;logger;isListening;isProduction;graphql;#s;#e;#r=[];#n=["node_modules"];#o;#i;constructor(e){this.#s=false,this.logger=(e?.logger??q).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.#t.get("PORT"))??80,host:e?.host??this.#t.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,graphql:e?.graphql??void 0,abortSignal:e?.abortSignal,cronUI:e?.cronUI},e?.ajvInstance&&A.setGlobalInstance(e.ajvInstance),this.#i=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#t.get("NODE_ENV")==="production",this.graphql=new se(this.serverOptions.graphql),this.#e=new jt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:E.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#i,graphql:this.graphql}),this.setupAbortSignalHandler();}get protectedKeys(){let e=Object.getOwnPropertyNames(this),t=Object.getPrototypeOf(this),r=t?Object.getOwnPropertyNames(t):[];return Array.from(new Set([...e,...r]))}get url(){return this.#e.url}get port(){return this.#e.port}get host(){return this.#e.host}get routes(){return $.getRoutes()||[]}get fs(){return v}async hash(e){return tt.hash(e)}async compareHash(e,t){return tt.compare(e,t)}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}get(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("GET",e,s,o,l,d);}post(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("POST",e,s,o,l,d);}patch(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PATCH",e,s,o,l,d);}put(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("PUT",e,s,o,l,d);}delete(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("DELETE",e,s,o,l,d);}options(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("OPTIONS",e,s,o,l,d);}head(e,t,r){let{middlewares:s,handler:o,body:i,query:a,all:c,swaggerOptions:d}=this.extractOptionsAndHandlerFromRouteRegistration(t,r),l={body:i,query:a,all:c};$.addOrUpdate("HEAD",e,s,o,l,d);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(E.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#e.getServer("node")}getBunServer(){if(E.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#e.getServer("bun")}getDenoServer(){if(E.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#e.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(this.protectedKeys.includes(e)||e==="constructor")throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){Fe.exit(e);}on(e,t){switch(E.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}once(e,t){switch(E.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${E.type}, only node, bun and deno are supported`)}}use(...e){this.#r.push(...e);}useExpress(e,t){pr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){et(e,t);}setErrorHandler(e){this.#r.unshift(async(t,r,s)=>{try{await s();}catch(o){await e?.(t,r,s,o);}});}setNotFoundHandler(e){this.#o=e?.bind(this);}listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let t={port:this.port,host:this.host,url:this.url};this.bootstrap().then(()=>{this.#e.listen(),this.isListening=true,e?.({...t,error:void 0});}).catch(r=>{e?.({...t,error:r});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e();});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){if(!this.isListening){this.logger.warn("Trying to disconnect the server that is not listening, ignoring");return}try{await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}configureHash(e){tt.configure(e);}async getMockServer(e){return await this.bootstrap(e),new St(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns;if(!(!t||t.length===0))try{let r=await Promise.all(t.map(async s=>v.glob(s,{cwd:N.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#n.some(o=>s.includes(o))),this.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing controller ${s}`),await import(s).catch(o=>{this.logger.error(`Error importing controller ${s}: ${o}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,body:r.body,query:r.query,all:r.all,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(os(r));break;case "cors":this.use(cr(r));break;case "static":this.use(rr(r));break;case "helmet":this.use(dr(r));break;case "cookie":this.use(ar(r));break;case "methodOverride":this.use(mr(r));break;case "compression":this.use(ir(r));break;case "log":this.use(ur(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:o}=r;this.use(hr(s,o));break;case "trustProxy":this.use(yr(r));break;case "timeout":this.use(gr(r));break;case "session":this.use(fr(r));break;case "asyncLocalStorage":this.use(or(r));break;default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#s||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.cronUI&&await Hr(this.serverOptions.cronUI),this.serverOptions.swagger&&fs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#r.length&&$.applyGlobalMiddlewaresToAllRoutes(this.#r),this.#s=true);}handleNotFound=(e,t)=>{if(this.#o){this.#o(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],o=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=$.find(a,r);c&&c.handler!==this.handleNotFound&&o.push(a);}if(o.length){t.setHeader("Allow",o.join(", "));let a=new Ue(r,e.method);t.methodNotAllowed({...L(a)});return}let i=new z(r,e.method);t.notFound({...L(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)$.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true});}setupAbortSignalHandler(){if(!this.serverOptions.abortSignal)return;let e=this.serverOptions.abortSignal;if(e.aborted){this.logger.warn("AbortSignal was already aborted, server will not start");return}e.addEventListener("abort",async()=>{this.logger.info("AbortSignal received, shutting down server gracefully");try{await this.disconnect(),this.logger.info("Server shutdown completed");}catch(t){this.logger.error({error:t},"Error during server shutdown from abort signal");}});}};var gs=()=>{let n=A.getCacheStats(),e=n.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:n.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:n.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Vo=()=>{let n=gs();q.info({validators:n.validators.size,totalSchemaRefs:n.totalSchemaReferences,memoryEstimate:n.memoryEstimate.total},"Schema cache metrics");},Ko=()=>{A.clearAllCaches(),q.debug("All schema caches cleared");};var K=class extends O{constructor(e){super(`File not found: ${e}`);}};var br=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new K(e);let o=t;if(o==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(o){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new O("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new K(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),o=t;await s.upload(o,o.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new O("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new O("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var wr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new O("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.resolve(this.options.directory),r=e?x.join(t,e):t;if(!await v.exists(r))return [];let o=[];return await this.listFilesRecursively(r,t,o),o}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=x.join(this.options.directory,e);if(!await v.exists(r))throw new K(e);switch(t){case "raw":return await v.readFile(r);case "text":return await v.readFile(r,{encoding:"utf8"});case "stream":return await v.streamFile(r);default:throw new O("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),o=x.join(s,"..");await v.mkdir(o,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=x.join(this.options.directory,e);await v.exists(t)&&await v.unlink(t);}async listFilesRecursively(e,t,r){let s=await v.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let o=await this.readDirectory(e);for(let i of o){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(G(),jr));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new O("Unsupported runtime")}}async ensureDirectoryExists(){if(await v.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await v.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};G();var Sr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=E.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:o}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:o,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new O("getDownloadUrl requires CloudFront configuration on Node.js/Deno")}async getUploadUrl(e,t=3600){if(await this.ensureClient(),this.isBun)return this.bunS3Client.file(e).presign({method:"PUT",expiresIn:t});let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureAwsSdk();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){if(await this.ensureClient(),this.isBun)try{let s=this.bunS3Client.file(e);if(!await s.exists())throw new K(e);switch(t){case "raw":{let a=await s.arrayBuffer();return new Uint8Array(a)}case "text":return await s.text();case "stream":return s.stream();default:throw new O("Invalid return type")}}catch(s){throw s instanceof K?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new K(e):s}let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new K(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new O("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new K(e):s}}async putObject(e,t,r){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).write(t,{type:r});return}let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){if(await this.ensureClient(),this.isBun){await this.bunS3Client.file(e).delete();return}let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.clientInitialized||(this.isBun?await this.ensureBunClient():await this.ensureAwsSdk(),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.clientInitialized=true);}async ensureBunClient(){if(this.bunS3Client)return;let e=this.options.s3ClientConfig,t=typeof e.credentials=="function"?await e.credentials():e.credentials,r=typeof e.endpoint=="string"?e.endpoint:e.endpoint?.toString(),s=globalThis.Bun.S3Client;this.bunS3Client=new s({accessKeyId:t?.accessKeyId,secretAccessKey:t?.secretAccessKey,sessionToken:t?.sessionToken,region:e.region,endpoint:r,bucket:e.bucketName});}async ensureAwsSdk(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default??e).catch(()=>{throw new O("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var xr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Mt=class{async render(e,t){return await this.ensureHandlebars(),this.handlebars.compile(e)(t)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}async registerHelper(e,t){await this.ensureHandlebars(),this.handlebars.registerHelper(e,t);}async registerPartial(e,t){await this.ensureHandlebars(),this.handlebars.registerPartial(e,t);}async ensureHandlebars(){if(this.handlebars)return;let t=await import('handlebars').catch(()=>{throw new O("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Et=class{async render(e,t){return await this.ensureEdge(),this.edge.renderRaw(e,t)}async renderFromFile(e,t){return await this.ensureEdge(),this.edge.render(e,t)}async global(e,t){await this.ensureEdge(),this.edge.global(e,t);}async registerTag(e){await this.ensureEdge(),this.edge.registerTag(e);}async ensureEdge(){if(this.edge)return;let e=await import('edge.js').catch(()=>{throw new O("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var At=class{partials={};async render(e,t){return await this.ensureMustache(),this.mustache.render(e,t,this.partials)}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerPartial(e,t){this.partials[e]=t;}async ensureMustache(){if(this.mustache)return;let e=await import('mustache').catch(()=>{throw new O("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var kt=class{options;constructor(e={}){this.options=e;}async render(e,t){return await this.ensureEjs(),this.ejs.render(e,t,this.options)}async renderFromFile(e,t){return await this.ensureEjs(),this.ejs.renderFile(e,t,this.options)}async ensureEjs(){if(this.ejs)return;let e=await import('ejs').catch(()=>{throw new O("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var $t=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,o)=>{let i=t[s];return i===void 0?r:o&&this.helpers.has(o)?this.helpers.get(o)(i):String(i)})}async renderFromFile(e,t){let r=await v.readFile(e,{encoding:"utf8"});return this.render(r,t)}registerHelper(e,t){this.helpers.set(e,t);}};var Be=class{options={};templateOptions;from(e){return this.options.from=e,this}to(e){return this.options.to=e,this}cc(e){return this.options.cc=e,this}bcc(e){return this.options.bcc=e,this}subject(e){return this.options.subject=e,this}text(e){return this.options.text=e,this}html(e){return this.options.html=e,this}template(e,t){return this.templateOptions={template:e,data:t,isFilePath:false},this}templateFile(e,t){return this.templateOptions={template:e,data:t,isFilePath:true},this}attachment(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(e),this}attachments(e){return this.options.attachments||(this.options.attachments=[]),this.options.attachments.push(...e),this}hasTemplate(){return !!this.templateOptions}isTemplateFile(){return !!this.templateOptions?.isFilePath}build(){if(!this.options.to)throw new Error("[MailOptionsBuilder] 'to' field is required");if(!this.options.subject)throw new Error("[MailOptionsBuilder] 'subject' field is required");if(this.templateOptions){let{text:e,html:t,...r}=this.options;return {...r,template:this.templateOptions.template,data:this.templateOptions.data,isFilePath:this.templateOptions.isFilePath}}return this.options}};var rt=class extends O{constructor(e){super(e),this.name="MailerError";}},st=class extends rt{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},_t=class extends rt{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Bt=class extends rt{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ot=class{transporter;templateAdapter;defaultFrom;constructor(e){this.transporter=e.transporter,this.templateAdapter=e.templateAdapter,this.defaultFrom=e.from;}async send(e){let t=new Be,s=e(t)??t,o=s.build();return s.hasTemplate()?this.sendWithTemplate(o):this.sendDirect(o)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new _t;let t=e.isFilePath?await this.templateAdapter.renderFromFile(e.template,e.data):await this.templateAdapter.render(e.template,e.data),r={...e,html:t,from:e.from||this.defaultFrom};await this.sendDirect(r);}async verify(){return this.transporter.verify()}};var Tr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Bt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ot(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new st(String(e));return t}async send(e){return this.getDefaultProvider().send(e)}async later(e){await this.initializeQueue();let t=new Be,s=e(t)??t,o=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:o,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=Zt("mailer-emails"),await this.emailQueue.subscribe(async e=>{await this.processEmail(e);}),this.queueInitialized=true);}async processEmail(e){try{await this.getDefaultProvider().send(r=>{let s=e.options;if(r.to(s.to).subject(s.subject),s.from&&r.from(s.from),s.cc&&r.cc(s.cc),s.bcc&&r.bcc(s.bcc),"text"in s&&s.text&&r.text(s.text),"html"in s&&s.html&&r.html(s.html),s.attachments&&r.attachments(s.attachments),e.isTemplate){let o=s;o.isFilePath?r.templateFile(o.template,o.data):r.template(o.template,o.data);}}),await new Promise(r=>setTimeout(r,1e3));}catch(t){console.error("[Mailer] Failed to send queued email:",t);}}async verify(){return this.getDefaultProvider().verify()}getDefaultProvider(){let e=this.providerMap.get(this.defaultProvider);if(!e)throw new st(String(this.defaultProvider));return e}};var Pr=class{};var Or=n=>(e,t)=>(r,s,o)=>{let i={scope:e,handler:t,manager:n};if(typeof s>"u"){let c=j.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),j.set(r.prototype,"__class__",c),r}let a=j.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),j.set(r,s,a),o};var Cr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Or(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new O(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Zh=$,Yh=qt;
1224
+ exports.AzureBlobStorageProvider=br;exports.BaseCron=Kt;exports.BasePlugin=Pr;exports.BullMQPubSub=Je;exports.Command=k;exports.CommandRegistry=vt;exports.CronService=J;exports.CustomAdapter=$t;exports.EdgeAdapter=Et;exports.EjsAdapter=kt;exports.GraphQL=se;exports.HandlebarsAdapter=Mt;exports.LocalStorageProvider=wr;exports.MailOptionsBuilder=Be;exports.MailProvider=ot;exports.Mailer=Tr;exports.MemoryPubSub=We;exports.MqttService=Le;exports.MustacheAdapter=At;exports.PGBossPubSub=Ve;exports.PolicyManager=Cr;exports.QueueManager=re;exports.QueueService=W;exports.S3StorageProvider=Sr;exports.SQSPubSub=Ke;exports.Server=qt;exports.Storage=xr;exports.arg=H;exports.asyncLocalStorage=or;exports.asyncStorage=ze;exports.bullmqQueue=Xs;exports.clearAllSchemaCaches=Ko;exports.commandRegistry=Te;exports.compression=ir;exports.controller=Bs;exports.cookie=ar;exports.cors=cr;exports.createExpressAdapter=pr;exports.createPolicyDecorator=Or;exports.createQueue=Ys;exports.cron=ks;exports.default=Yh;exports.defineQueueConfiguration=eo;exports.del=Hs;exports.expressHandler=ds;exports.expressMiddleware=$e;exports.flag=C;exports.get=Ns;exports.getSchemaCacheMetrics=gs;exports.hash=tt;exports.helmet=dr;exports.log=ur;exports.logSchemaCacheMetrics=Vo;exports.logger=q;exports.memoryQueue=Zt;exports.methodOverride=mr;exports.middleware=Ds;exports.mountExpressRouter=et;exports.mqtt=Vs;exports.patch=Ls;exports.pgbossQueue=Zs;exports.post=Fs;exports.put=Is;exports.rateLimiter=hr;exports.router=Zh;exports.serialize=zs;exports.serveStatic=rr;exports.session=fr;exports.setCronGlobalErrorHandler=As;exports.setMqttGlobalErrorHandler=Ws;exports.sqsQueue=Ks;exports.timeoutMw=gr;exports.trustProxy=yr;exports.validate=Gs;//# sourceMappingURL=index.cjs.map
1223
1225
  //# sourceMappingURL=index.cjs.map