balda 0.0.63 → 0.0.65
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/cli.js +27 -27
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +56 -54
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +365 -162
- package/lib/index.d.ts +365 -162
- package/lib/index.js +56 -54
- package/lib/index.js.map +1 -1
- package/package.json +3 -2
package/lib/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var gt=require('path'),ao=require('pino'),ajv=require('ajv'),uo=require('fast-json-stringify'),child_process=require('child_process'),Yr=require('readline'),module$1=require('module'),Jo=require('crypto'),util=require('util'),zlib=require('zlib'),nt=require('fs'),stream=require('stream'),async_hooks=require('async_hooks'),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 gt__default=/*#__PURE__*/_interopDefault(gt);var ao__default=/*#__PURE__*/_interopDefault(ao);var uo__default=/*#__PURE__*/_interopDefault(uo);var Yr__namespace=/*#__PURE__*/_interopNamespace(Yr);var Jo__default=/*#__PURE__*/_interopDefault(Jo);var nt__default=/*#__PURE__*/_interopDefault(nt);var Xs=Object.create;var ft=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Zs=Object.getOwnPropertyNames;var Ys=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty;var Yt=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var to=(o,e)=>()=>(o&&(e=o(o=0)),e);var ro=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),so=(o,e)=>{for(var t in e)ft(o,t,{get:e[t],enumerable:true});},oo=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zs(e))!eo.call(o,s)&&s!==t&&ft(o,s,{get:()=>e[s],enumerable:!(r=Xr(e,s))||r.enumerable});return o};var no=(o,e,t)=>(t=o!=null?Xs(Ys(o)):{},oo(ft(t,"default",{value:o,enumerable:true}),o));var T=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,i;n>=0;n--)(i=o[n])&&(s=(i(e,t,s))||s);return s&&ft(e,t,s),s};var Zr={};so(Zr,{runtime:()=>E});var er,E,V=to(()=>{er=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 er;});var fs=ro((Rt,ur)=>{(function(e,t){typeof Rt=="object"&&typeof ur=="object"?ur.exports=t():typeof define=="function"&&define.amd?define("cronstrue",[],t):typeof Rt=="object"?Rt.cronstrue=t():e.cronstrue=t();})(globalThis,()=>(()=>{var o={949:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.CronParser=void 0;var a=i(515),l=(function(){function p(c,d,u){d===void 0&&(d=true),u===void 0&&(u=false),this.expression=c,this.dayOfWeekStartIndexZero=d,this.monthStartIndexZero=u;}return p.prototype.parse=function(){var c,d,u=(c=this.expression)!==null&&c!==void 0?c:"";if(u==="@reboot")return d=["@reboot","","","","","",""],d;if(u.startsWith("@")){var h=this.parseSpecial(this.expression);d=this.extractParts(h);}else d=this.extractParts(this.expression);return this.normalize(d),this.validate(d),d},p.prototype.parseSpecial=function(c){var d={"@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=d[c];if(!u)throw new Error("Unknown special expression.");return u},p.prototype.extractParts=function(c){if(!this.expression)throw new Error("cron expression is empty");for(var d=c.trim().split(/[ ]+/),u=0;u<d.length;u++)if(d[u].includes(",")){var h=d[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!==""});h.length===0&&h.push("*"),h.sort(function(f,g){return f!==null&&g!==null?f-g:0}),d[u]=h.map(function(f){return f!==null?f.toString():""}).join(",");}if(d.length<5)throw new Error("Expression has only ".concat(d.length," part").concat(d.length==1?"":"s",". At least 5 parts are required."));if(d.length==5)d.unshift(""),d.push("");else if(d.length==6){var m=/\d{4}$/.test(d[5])||d[4]=="?"||d[2]=="?";m?d.unshift(""):d.push("");}else if(d.length>7)throw new Error("Expression has ".concat(d.length," parts; too many!"));return d},p.prototype.normalize=function(c){var d=this;if(c[3]=c[3].replace("?","*"),c[5]=c[5].replace("?","*"),c[2]=c[2].replace("?","*"),c[0].indexOf("0/")==0&&(c[0]=c[0].replace("0/","*/")),c[1].indexOf("0/")==0&&(c[1]=c[1].replace("0/","*/")),c[2].indexOf("0/")==0&&(c[2]=c[2].replace("0/","*/")),c[3].indexOf("1/")==0&&(c[3]=c[3].replace("1/","*/")),c[4].indexOf("1/")==0&&(c[4]=c[4].replace("1/","*/")),c[6].indexOf("1/")==0&&(c[6]=c[6].replace("1/","*/")),c[5]=c[5].replace(/(^\d)|([^#/\s]\d)/g,function(S){var b=S.replace(/\D/,""),w=b;return d.dayOfWeekStartIndexZero?b=="7"&&(w="0"):w=(parseInt(b)-1).toString(),S.replace(b,w)}),c[5]=="L"&&(c[5]="6"),c[3]=="?"&&(c[3]="*"),c[3].indexOf("W")>-1&&(c[3].indexOf(",")>-1||c[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 h in u)c[5]=c[5].replace(new RegExp(h,"gi"),u[h].toString());c[4]=c[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(S){var b=S.replace(/\D/,""),w=b;return d.monthStartIndexZero&&(w=(parseInt(b)+1).toString()),S.replace(b,w)});var m={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 m)c[4]=c[4].replace(new RegExp(f,"gi"),m[f].toString());c[0]=="0"&&(c[0]=""),!/\*|\-|\,|\//.test(c[2])&&(/\*|\//.test(c[1])||/\*|\//.test(c[0]))&&(c[2]+="-".concat(c[2]));for(var g=0;g<c.length;g++)if(c[g].indexOf(",")!=-1&&(c[g]=c[g].split(",").filter(function(S){return S!==""}).join(",")||"*"),c[g]=="*/1"&&(c[g]="*"),c[g].indexOf("/")>-1&&!/^\*|\-|\,/.test(c[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 P=c[g].split("/");c[g]="".concat(P[0],"-").concat(y,"/").concat(P[1]);}}},p.prototype.validate=function(c){var d="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(c[0],d),this.validateOnlyExpectedCharactersFound(c[1],d),this.validateOnlyExpectedCharactersFound(c[2],d),this.validateOnlyExpectedCharactersFound(c[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(c[4],d),this.validateOnlyExpectedCharactersFound(c[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(c[6],d),this.validateAnyRanges(c);},p.prototype.validateAnyRanges=function(c){a.default.secondRange(c[0]),a.default.minuteRange(c[1]),a.default.hourRange(c[2]),a.default.dayOfMonthRange(c[3]),a.default.monthRange(c[4],this.monthStartIndexZero),a.default.dayOfWeekRange(c[5],this.dayOfWeekStartIndexZero);},p.prototype.validateOnlyExpectedCharactersFound=function(c,d){var u=c.match(new RegExp("[^".concat(d,"]+"),"gi"));if(u&&u.length)throw new Error("Expression contains invalid values: '".concat(u.toString(),"'"))},p})();n.CronParser=l;}),333:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.ExpressionDescriptor=void 0;var a=i(823),l=i(949),p=(function(){function c(d,u){if(this.expression=d,this.options=u,this.expressionParts=new Array(5),!this.options.locale&&c.defaultLocale&&(this.options.locale=c.defaultLocale),!c.locales[this.options.locale]){var h=Object.keys(c.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(h,"'.")),this.options.locale=h;}this.i18n=c.locales[this.options.locale],u.use24HourTimeFormat===void 0&&(u.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault());}return c.toString=function(d,u){var h=u===void 0?{}:u,m=h.throwExceptionOnParseError,f=m===void 0?true:m,g=h.verbose,y=g===void 0?false:g,P=h.dayOfWeekStartIndexZero,S=P===void 0?true:P,b=h.monthStartIndexZero,w=b===void 0?false:b,k=h.use24HourTimeFormat,A=h.locale,B=A===void 0?null:A,L=h.logicalAndDayFields,F=L===void 0?false:L,ee={throwExceptionOnParseError:f,verbose:y,dayOfWeekStartIndexZero:S,monthStartIndexZero:w,use24HourTimeFormat:k,locale:B,logicalAndDayFields:F};ee.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Xt=new c(d,ee);return Xt.getFullDescription()},c.initialize=function(d,u){u===void 0&&(u="en"),c.specialCharacters=["/","-",",","*"],c.defaultLocale=u,d.load(c.locales);},c.prototype.getFullDescription=function(){var d,u,h="";try{var m=new l.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=m.parse(),this.expressionParts[0]==="@reboot")return ((u=(d=this.i18n).atReboot)===null||u===void 0?void 0:u.call(d))||"Run once, at startup";var f=this.getTimeOfDayDescription(),g=this.getDayOfMonthDescription(),y=this.getMonthDescription(),P=this.getDayOfWeekDescription(),S=this.getYearDescription();h+=f+g+P+y+S,h=this.transformVerbosity(h,!!this.options.verbose),h=h.charAt(0).toLocaleUpperCase()+h.substr(1);}catch(b){if(!this.options.throwExceptionOnParseError)h=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw "".concat(b)}return h},c.prototype.getTimeOfDayDescription=function(){var d=this.expressionParts[0],u=this.expressionParts[1],h=this.expressionParts[2],m="";if(!a.StringUtilities.containsAny(u,c.specialCharacters)&&!a.StringUtilities.containsAny(h,c.specialCharacters)&&!a.StringUtilities.containsAny(d,c.specialCharacters))m+=this.i18n.atSpace()+this.formatTime(h,u,d);else if(!d&&u.indexOf("-")>-1&&!(u.indexOf(",")>-1)&&!(u.indexOf("/")>-1)&&!a.StringUtilities.containsAny(h,c.specialCharacters)){var f=u.split("-");m+=a.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(h,f[0],""),this.formatTime(h,f[1],""));}else if(!d&&h.indexOf(",")>-1&&h.indexOf("-")==-1&&h.indexOf("/")==-1&&!a.StringUtilities.containsAny(u,c.specialCharacters)){var g=h.split(",");m+=this.i18n.at();for(var y=0;y<g.length;y++)m+=" ",m+=this.formatTime(g[y],u,""),y<g.length-2&&(m+=","),y==g.length-2&&(m+=this.i18n.spaceAnd());}else {var P=this.getSecondsDescription(),S=this.getMinutesDescription(),b=this.getHoursDescription();if(m+=P,m&&S&&(m+=", "),m+=S,S===b)return m;m&&b&&(m+=", "),m+=b;}return m},c.prototype.getSecondsDescription=function(){var d=this,u=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(h){return h},function(h){return a.StringUtilities.format(d.i18n.everyX0Seconds(h),h)},function(h){return d.i18n.secondsX0ThroughX1PastTheMinute()},function(h){return h=="0"?"":parseInt(h)<20?d.i18n.atX0SecondsPastTheMinute(h):d.i18n.atX0SecondsPastTheMinuteGt20()||d.i18n.atX0SecondsPastTheMinute(h)});return u},c.prototype.getMinutesDescription=function(){var d=this,u=this.expressionParts[0],h=this.expressionParts[2],m=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(f){return f},function(f){return a.StringUtilities.format(d.i18n.everyX0Minutes(f),f)},function(f){return d.i18n.minutesX0ThroughX1PastTheHour()},function(f){try{return f=="0"&&h.indexOf("/")==-1&&u==""?d.i18n.everyHour():parseInt(f)<20?d.i18n.atX0MinutesPastTheHour(f):d.i18n.atX0MinutesPastTheHourGt20()||d.i18n.atX0MinutesPastTheHour(f)}catch{return d.i18n.atX0MinutesPastTheHour(f)}});return m},c.prototype.getHoursDescription=function(){var d=this,u=this.expressionParts[2],h=0,m=[];u.split("/")[0].split(",").forEach(function(y){var P=y.split("-");P.length===2&&m.push({value:P[1],index:h+1}),h+=P.length;});var f=0,g=this.getSegmentDescription(u,this.i18n.everyHour(),function(y){var P=m.find(function(b){return b.value===y&&b.index===f}),S=P&&d.expressionParts[1]!=="0";return f++,S?d.formatTime(y,"59",""):d.formatTime(y,"0","")},function(y){return a.StringUtilities.format(d.i18n.everyX0Hours(y),y)},function(y){return d.i18n.betweenX0AndX1()},function(y){return d.i18n.atX0()});return g},c.prototype.getDayOfWeekDescription=function(){var d=this,u=this.i18n.daysOfTheWeek(),h=null;return this.expressionParts[5]=="*"?h="":h=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(m,f){var g=m;m.indexOf("#")>-1?g=m.substring(0,m.indexOf("#")):m.indexOf("L")>-1&&(g=g.replace("L",""));var y=parseInt(g),P=d.i18n.daysOfTheWeekInCase?d.i18n.daysOfTheWeekInCase(f)[y]:u[y];if(m.indexOf("#")>-1){var S=null,b=m.substring(m.indexOf("#")+1),w=m.substring(0,m.indexOf("#"));switch(b){case "1":S=d.i18n.first(w);break;case "2":S=d.i18n.second(w);break;case "3":S=d.i18n.third(w);break;case "4":S=d.i18n.fourth(w);break;case "5":S=d.i18n.fifth(w);break}P=S+" "+P;}return P},function(m){return parseInt(m)==1?"":a.StringUtilities.format(d.i18n.commaEveryX0DaysOfTheWeek(m),m)},function(m){var f=m.substring(0,m.indexOf("-")),g=d.expressionParts[3]!="*";return g?d.i18n.commaAndX0ThroughX1(f):d.i18n.commaX0ThroughX1(f)},function(m){var f=null;if(m.indexOf("#")>-1){var g=m.substring(m.indexOf("#")+1),y=m.substring(0,m.indexOf("#"));f=d.i18n.commaOnThe(g,y).trim()+d.i18n.spaceX0OfTheMonth();}else if(m.indexOf("L")>-1)f=d.i18n.commaOnTheLastX0OfTheMonth(m.replace("L",""));else {var P=d.expressionParts[3]!="*";P?d.options.logicalAndDayFields?f=d.i18n.commaOnlyOnX0(m):f=d.i18n.commaAndOnX0():f=d.i18n.commaOnlyOnX0(m);}return f}),h},c.prototype.getMonthDescription=function(){var d=this,u=this.i18n.monthsOfTheYear(),h=this.getSegmentDescription(this.expressionParts[4],"",function(m,f){return f&&d.i18n.monthsOfTheYearInCase?d.i18n.monthsOfTheYearInCase(f)[parseInt(m)-1]:u[parseInt(m)-1]},function(m){return parseInt(m)==1?"":a.StringUtilities.format(d.i18n.commaEveryX0Months(m),m)},function(m){return d.i18n.commaMonthX0ThroughMonthX1()||d.i18n.commaX0ThroughX1()},function(m){return d.i18n.commaOnlyInMonthX0?d.i18n.commaOnlyInMonthX0():d.i18n.commaOnlyInX0()});return h},c.prototype.getDayOfMonthDescription=function(){var d=this,u=null,h=this.expressionParts[3];switch(h){case "L":u=this.i18n.commaOnTheLastDayOfTheMonth();break;case "WL":case "LW":u=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var m=h.match(/(\d{1,2}W)|(W\d{1,2})/);if(m){var f=parseInt(m[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=h.match(/L-(\d{1,2})/);if(y){var P=y[1];u=a.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(P),P);break}else {if(h=="*"&&this.expressionParts[5]!="*")return "";u=this.getSegmentDescription(h,this.i18n.commaEveryDay(),function(S){return S=="L"?d.i18n.lastDay():d.i18n.dayX0?a.StringUtilities.format(d.i18n.dayX0(),S):S},function(S){return S=="1"?d.i18n.commaEveryDay():d.i18n.commaEveryX0Days(S)},function(S){return d.i18n.commaBetweenDayX0AndX1OfTheMonth(S)},function(S){return d.i18n.commaOnDayX0OfTheMonth(S)});}break}}return u},c.prototype.getYearDescription=function(){var d=this,u=this.getSegmentDescription(this.expressionParts[6],"",function(h){return /^\d+$/.test(h)?new Date(parseInt(h),1).getFullYear().toString():h},function(h){return a.StringUtilities.format(d.i18n.commaEveryX0Years(h),h)},function(h){return d.i18n.commaYearX0ThroughYearX1()||d.i18n.commaX0ThroughX1()},function(h){return d.i18n.commaOnlyInYearX0?d.i18n.commaOnlyInYearX0():d.i18n.commaOnlyInX0()});return u},c.prototype.getSegmentDescription=function(d,u,h,m,f,g){var y=null,P=d.indexOf("/")>-1,S=d.indexOf("-")>-1,b=d.indexOf(",")>-1;if(!d)y="";else if(d==="*")y=u;else if(!P&&!S&&!b)y=a.StringUtilities.format(g(d),h(d));else if(b){for(var w=d.split(","),k="",A=0;A<w.length;A++)if(A>0&&w.length>2&&(k+=",",A<w.length-1&&(k+=" ")),A>0&&w.length>1&&(A==w.length-1||w.length==2)&&(k+="".concat(this.i18n.spaceAnd()," ")),w[A].indexOf("/")>-1||w[A].indexOf("-")>-1){var B=w[A].indexOf("-")>-1&&w[A].indexOf("/")==-1,L=this.getSegmentDescription(w[A],u,h,m,B?this.i18n.commaX0ThroughX1:f,g);B&&(L=L.replace(", ","")),k+=L;}else P?k+=this.getSegmentDescription(w[A],u,h,m,f,g):k+=h(w[A]);P?y=k:y=a.StringUtilities.format(g(d),k);}else if(P){var w=d.split("/");if(y=a.StringUtilities.format(m(w[1]),w[1]),w[0].indexOf("-")>-1){var F=this.generateRangeSegmentDescription(w[0],f,h);F.indexOf(", ")!=0&&(y+=", "),y+=F;}else if(w[0].indexOf("*")==-1){var ee=a.StringUtilities.format(g(w[0]),h(w[0]));ee=ee.replace(", ",""),y+=a.StringUtilities.format(this.i18n.commaStartingX0(),ee);}}else S&&(y=this.generateRangeSegmentDescription(d,f,h));return y},c.prototype.generateRangeSegmentDescription=function(d,u,h){var m="",f=d.split("-"),g=h(f[0],1),y=h(f[1],2),P=u(d);return m+=a.StringUtilities.format(P,g,y),m},c.prototype.formatTime=function(d,u,h){var m=0,f=0,g=parseInt(d)+m,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 P="",S=false;this.options.use24HourTimeFormat||(S=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),P=S?"".concat(this.getPeriod(g)," "):" ".concat(this.getPeriod(g)),g>12&&(g-=12),g===0&&(g=12));var b="";return h&&(b=":".concat(("00"+h).substring(h.length))),"".concat(S?P:"").concat(("00"+g.toString()).substring(g.toString().length),":").concat(("00"+y.toString()).substring(y.toString().length)).concat(b).concat(S?"":P)},c.prototype.transformVerbosity=function(d,u){if(!u&&(d=d.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),d=d.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),d=d.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),d=d.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var h=0,m=Object.entries(this.i18n.conciseVerbosityReplacements());h<m.length;h++){var f=m[h],g=f[0],y=f[1];d=d.replace(new RegExp(g,"g"),y);}return d},c.prototype.getPeriod=function(d){return d>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},c.locales={},c})();n.ExpressionDescriptor=p;}),747:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.enLocaleLoader=void 0;var a=i(486),l=(function(){function p(){}return p.prototype.load=function(c){c.en=new a.en;},p})();n.enLocaleLoader=l;}),486:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.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})();n.en=i;}),515:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true});function i(l,p){if(!l)throw new Error(p)}var a=(function(){function l(){}return l.secondRange=function(p){for(var c=p.split(","),d=0;d<c.length;d++)if(!isNaN(parseInt(c[d],10))){var u=parseInt(c[d],10);i(u>=0&&u<=59,"seconds part must be >= 0 and <= 59");}},l.minuteRange=function(p){for(var c=p.split(","),d=0;d<c.length;d++)if(!isNaN(parseInt(c[d],10))){var u=parseInt(c[d],10);i(u>=0&&u<=59,"minutes part must be >= 0 and <= 59");}},l.hourRange=function(p){for(var c=p.split(","),d=0;d<c.length;d++)if(!isNaN(parseInt(c[d],10))){var u=parseInt(c[d],10);i(u>=0&&u<=23,"hours part must be >= 0 and <= 23");}},l.dayOfMonthRange=function(p){for(var c=p.split(","),d=0;d<c.length;d++)if(!isNaN(parseInt(c[d],10))){var u=parseInt(c[d],10);i(u>=1&&u<=31,"DOM part must be >= 1 and <= 31");}},l.monthRange=function(p,c){for(var d=p.split(","),u=0;u<d.length;u++)if(!isNaN(parseInt(d[u],10))){var h=parseInt(d[u],10);i(h>=1&&h<=12,c?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12");}},l.dayOfWeekRange=function(p,c){for(var d=p.split(","),u=0;u<d.length;u++)if(!isNaN(parseInt(d[u],10))){var h=parseInt(d[u],10);i(h>=0&&h<=6,c?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7");}},l})();n.default=a;}),823:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.StringUtilities=void 0;var i=(function(){function a(){}return a.format=function(l){for(var p=[],c=1;c<arguments.length;c++)p[c-1]=arguments[c];return l.replace(/%s/g,function(d){for(var u=[],h=1;h<arguments.length;h++)u[h-1]=arguments[h];return p.shift()})},a.containsAny=function(l,p){return p.some(function(c){return l.indexOf(c)>-1})},a})();n.StringUtilities=i;})},e={};function t(s){var n=e[s];if(n!==void 0)return n.exports;var i=e[s]={exports:{}};return o[s](i,i.exports,t),i.exports}var r={};return (()=>{var s=r;Object.defineProperty(s,"__esModule",{value:true}),s.toString=void 0;var n=t(333),i=t(747);n.ExpressionDescriptor.initialize(new i.enLocaleLoader),s.default=n.ExpressionDescriptor;var a=n.ExpressionDescriptor.toString;s.toString=a;})(),r})());});var O=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 io=o=>(e,t,r)=>{let s=O.get(e,t);return s||(s={middlewares:[]}),s.cacheConfig=o,O.set(e,t,s),r};V();V();var tr=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 tr;V();var rr=class{basename(e){switch(E.type){case "node":case "bun":case "deno":return gt__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(E.type){case "node":case "bun":case "deno":return gt__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(E.type){case "bun":case "node":case "deno":return gt__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(E.type){case "bun":case "node":case "deno":return gt__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new rr;var sr=class{async glob(...e){let t=await import('fs/promises'),r=N.getCwd(),s=x.resolve(r,e[1]?.cwd??""),n=[];for await(let i of t.glob(...e)){if(typeof i=="string"){n.push(x.resolve(s,i));continue}i.isFile()&&n.push(x.resolve(s,i.name));}return n}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 n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.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 n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.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 sr;var R=class extends Error{constructor(e){super(e);}};var co=()=>ao__default.default({level:"info",formatters:{level:e=>({level:e})}}),M=co();var yt=class extends R{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 Ne=class extends R{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var vt=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))):Yt("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)??Yt,de=async o=>{let e=x.join(process.cwd(),"node_modules");if(!await v.exists(e))return o;let r=[];for(let s of o){let n=x.join(e,s);await v.exists(n)||r.push(s);}return r},G=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"],U=async(o,e,t,r,s=true)=>{let n=Yr__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 vt=require('path'),go=require('pino'),ajv=require('ajv'),bo=require('fast-json-stringify'),child_process=require('child_process'),ts=require('readline'),module$1=require('module'),sn=require('crypto'),util=require('util'),zlib=require('zlib'),at=require('fs'),stream=require('stream'),async_hooks=require('async_hooks'),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 vt__default=/*#__PURE__*/_interopDefault(vt);var go__default=/*#__PURE__*/_interopDefault(go);var bo__default=/*#__PURE__*/_interopDefault(bo);var ts__namespace=/*#__PURE__*/_interopNamespace(ts);var sn__default=/*#__PURE__*/_interopDefault(sn);var at__default=/*#__PURE__*/_interopDefault(at);var no=Object.create;var yt=Object.defineProperty;var Yr=Object.getOwnPropertyDescriptor;var io=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,co=Object.prototype.hasOwnProperty;var Yt=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var lo=(o,e)=>()=>(o&&(e=o(o=0)),e);var po=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),uo=(o,e)=>{for(var t in e)yt(o,t,{get:e[t],enumerable:true});},mo=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of io(e))!co.call(o,s)&&s!==t&&yt(o,s,{get:()=>e[s],enumerable:!(r=Yr(e,s))||r.enumerable});return o};var ho=(o,e,t)=>(t=o!=null?no(ao(o)):{},mo(yt(t,"default",{value:o,enumerable:true}),o));var T=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,i;n>=0;n--)(i=o[n])&&(s=(i(e,t,s))||s);return s&&yt(e,t,s),s};var es={};uo(es,{runtime:()=>M});var er,M,J=lo(()=>{er=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")}},M=new er;});var vs=po((Ot,ur)=>{(function(e,t){typeof Ot=="object"&&typeof ur=="object"?ur.exports=t():typeof define=="function"&&define.amd?define("cronstrue",[],t):typeof Ot=="object"?Ot.cronstrue=t():e.cronstrue=t();})(globalThis,()=>(()=>{var o={949:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.CronParser=void 0;var a=i(515),c=(function(){function p(l,d,u){d===void 0&&(d=true),u===void 0&&(u=false),this.expression=l,this.dayOfWeekStartIndexZero=d,this.monthStartIndexZero=u;}return p.prototype.parse=function(){var l,d,u=(l=this.expression)!==null&&l!==void 0?l:"";if(u==="@reboot")return d=["@reboot","","","","","",""],d;if(u.startsWith("@")){var m=this.parseSpecial(this.expression);d=this.extractParts(m);}else d=this.extractParts(this.expression);return this.normalize(d),this.validate(d),d},p.prototype.parseSpecial=function(l){var d={"@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=d[l];if(!u)throw new Error("Unknown special expression.");return u},p.prototype.extractParts=function(l){if(!this.expression)throw new Error("cron expression is empty");for(var d=l.trim().split(/[ ]+/),u=0;u<d.length;u++)if(d[u].includes(",")){var m=d[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}),d[u]=m.map(function(f){return f!==null?f.toString():""}).join(",");}if(d.length<5)throw new Error("Expression has only ".concat(d.length," part").concat(d.length==1?"":"s",". At least 5 parts are required."));if(d.length==5)d.unshift(""),d.push("");else if(d.length==6){var h=/\d{4}$/.test(d[5])||d[4]=="?"||d[2]=="?";h?d.unshift(""):d.push("");}else if(d.length>7)throw new Error("Expression has ".concat(d.length," parts; too many!"));return d},p.prototype.normalize=function(l){var d=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(x){var w=x.replace(/\D/,""),b=w;return d.dayOfWeekStartIndexZero?w=="7"&&(b="0"):b=(parseInt(w)-1).toString(),x.replace(w,b)}),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(x){var w=x.replace(/\D/,""),b=w;return d.monthStartIndexZero&&(b=(parseInt(w)+1).toString()),x.replace(w,b)});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(x){return x!==""}).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 P=l[g].split("/");l[g]="".concat(P[0],"-").concat(y,"/").concat(P[1]);}}},p.prototype.validate=function(l){var d="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(l[0],d),this.validateOnlyExpectedCharactersFound(l[1],d),this.validateOnlyExpectedCharactersFound(l[2],d),this.validateOnlyExpectedCharactersFound(l[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(l[4],d),this.validateOnlyExpectedCharactersFound(l[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(l[6],d),this.validateAnyRanges(l);},p.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);},p.prototype.validateOnlyExpectedCharactersFound=function(l,d){var u=l.match(new RegExp("[^".concat(d,"]+"),"gi"));if(u&&u.length)throw new Error("Expression contains invalid values: '".concat(u.toString(),"'"))},p})();n.CronParser=c;}),333:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.ExpressionDescriptor=void 0;var a=i(823),c=i(949),p=(function(){function l(d,u){if(this.expression=d,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(d,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,P=m.dayOfWeekStartIndexZero,x=P===void 0?true:P,w=m.monthStartIndexZero,b=w===void 0?false:w,q=m.use24HourTimeFormat,A=m.locale,B=A===void 0?null:A,I=m.logicalAndDayFields,G=I===void 0?false:I,te={throwExceptionOnParseError:f,verbose:y,dayOfWeekStartIndexZero:x,monthStartIndexZero:b,use24HourTimeFormat:q,locale:B,logicalAndDayFields:G};te.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var Ne=new l(d,te);return Ne.getFullDescription()},l.initialize=function(d,u){u===void 0&&(u="en"),l.specialCharacters=["/","-",",","*"],l.defaultLocale=u,d.load(l.locales);},l.prototype.getFullDescription=function(){var d,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=(d=this.i18n).atReboot)===null||u===void 0?void 0:u.call(d))||"Run once, at startup";var f=this.getTimeOfDayDescription(),g=this.getDayOfMonthDescription(),y=this.getMonthDescription(),P=this.getDayOfWeekDescription(),x=this.getYearDescription();m+=f+g+P+y+x,m=this.transformVerbosity(m,!!this.options.verbose),m=m.charAt(0).toLocaleUpperCase()+m.substr(1);}catch(w){if(!this.options.throwExceptionOnParseError)m=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw "".concat(w)}return m},l.prototype.getTimeOfDayDescription=function(){var d=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(d,l.specialCharacters))h+=this.i18n.atSpace()+this.formatTime(m,u,d);else if(!d&&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(!d&&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 P=this.getSecondsDescription(),x=this.getMinutesDescription(),w=this.getHoursDescription();if(h+=P,h&&x&&(h+=", "),h+=x,x===w)return h;h&&w&&(h+=", "),h+=w;}return h},l.prototype.getSecondsDescription=function(){var d=this,u=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(m){return m},function(m){return a.StringUtilities.format(d.i18n.everyX0Seconds(m),m)},function(m){return d.i18n.secondsX0ThroughX1PastTheMinute()},function(m){return m=="0"?"":parseInt(m)<20?d.i18n.atX0SecondsPastTheMinute(m):d.i18n.atX0SecondsPastTheMinuteGt20()||d.i18n.atX0SecondsPastTheMinute(m)});return u},l.prototype.getMinutesDescription=function(){var d=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(d.i18n.everyX0Minutes(f),f)},function(f){return d.i18n.minutesX0ThroughX1PastTheHour()},function(f){try{return f=="0"&&m.indexOf("/")==-1&&u==""?d.i18n.everyHour():parseInt(f)<20?d.i18n.atX0MinutesPastTheHour(f):d.i18n.atX0MinutesPastTheHourGt20()||d.i18n.atX0MinutesPastTheHour(f)}catch{return d.i18n.atX0MinutesPastTheHour(f)}});return h},l.prototype.getHoursDescription=function(){var d=this,u=this.expressionParts[2],m=0,h=[];u.split("/")[0].split(",").forEach(function(y){var P=y.split("-");P.length===2&&h.push({value:P[1],index:m+1}),m+=P.length;});var f=0,g=this.getSegmentDescription(u,this.i18n.everyHour(),function(y){var P=h.find(function(w){return w.value===y&&w.index===f}),x=P&&d.expressionParts[1]!=="0";return f++,x?d.formatTime(y,"59",""):d.formatTime(y,"0","")},function(y){return a.StringUtilities.format(d.i18n.everyX0Hours(y),y)},function(y){return d.i18n.betweenX0AndX1()},function(y){return d.i18n.atX0()});return g},l.prototype.getDayOfWeekDescription=function(){var d=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),P=d.i18n.daysOfTheWeekInCase?d.i18n.daysOfTheWeekInCase(f)[y]:u[y];if(h.indexOf("#")>-1){var x=null,w=h.substring(h.indexOf("#")+1),b=h.substring(0,h.indexOf("#"));switch(w){case "1":x=d.i18n.first(b);break;case "2":x=d.i18n.second(b);break;case "3":x=d.i18n.third(b);break;case "4":x=d.i18n.fourth(b);break;case "5":x=d.i18n.fifth(b);break}P=x+" "+P;}return P},function(h){return parseInt(h)==1?"":a.StringUtilities.format(d.i18n.commaEveryX0DaysOfTheWeek(h),h)},function(h){var f=h.substring(0,h.indexOf("-")),g=d.expressionParts[3]!="*";return g?d.i18n.commaAndX0ThroughX1(f):d.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=d.i18n.commaOnThe(g,y).trim()+d.i18n.spaceX0OfTheMonth();}else if(h.indexOf("L")>-1)f=d.i18n.commaOnTheLastX0OfTheMonth(h.replace("L",""));else {var P=d.expressionParts[3]!="*";P?d.options.logicalAndDayFields?f=d.i18n.commaOnlyOnX0(h):f=d.i18n.commaAndOnX0():f=d.i18n.commaOnlyOnX0(h);}return f}),m},l.prototype.getMonthDescription=function(){var d=this,u=this.i18n.monthsOfTheYear(),m=this.getSegmentDescription(this.expressionParts[4],"",function(h,f){return f&&d.i18n.monthsOfTheYearInCase?d.i18n.monthsOfTheYearInCase(f)[parseInt(h)-1]:u[parseInt(h)-1]},function(h){return parseInt(h)==1?"":a.StringUtilities.format(d.i18n.commaEveryX0Months(h),h)},function(h){return d.i18n.commaMonthX0ThroughMonthX1()||d.i18n.commaX0ThroughX1()},function(h){return d.i18n.commaOnlyInMonthX0?d.i18n.commaOnlyInMonthX0():d.i18n.commaOnlyInX0()});return m},l.prototype.getDayOfMonthDescription=function(){var d=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 P=y[1];u=a.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(P),P);break}else {if(m=="*"&&this.expressionParts[5]!="*")return "";u=this.getSegmentDescription(m,this.i18n.commaEveryDay(),function(x){return x=="L"?d.i18n.lastDay():d.i18n.dayX0?a.StringUtilities.format(d.i18n.dayX0(),x):x},function(x){return x=="1"?d.i18n.commaEveryDay():d.i18n.commaEveryX0Days(x)},function(x){return d.i18n.commaBetweenDayX0AndX1OfTheMonth(x)},function(x){return d.i18n.commaOnDayX0OfTheMonth(x)});}break}}return u},l.prototype.getYearDescription=function(){var d=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(d.i18n.commaEveryX0Years(m),m)},function(m){return d.i18n.commaYearX0ThroughYearX1()||d.i18n.commaX0ThroughX1()},function(m){return d.i18n.commaOnlyInYearX0?d.i18n.commaOnlyInYearX0():d.i18n.commaOnlyInX0()});return u},l.prototype.getSegmentDescription=function(d,u,m,h,f,g){var y=null,P=d.indexOf("/")>-1,x=d.indexOf("-")>-1,w=d.indexOf(",")>-1;if(!d)y="";else if(d==="*")y=u;else if(!P&&!x&&!w)y=a.StringUtilities.format(g(d),m(d));else if(w){for(var b=d.split(","),q="",A=0;A<b.length;A++)if(A>0&&b.length>2&&(q+=",",A<b.length-1&&(q+=" ")),A>0&&b.length>1&&(A==b.length-1||b.length==2)&&(q+="".concat(this.i18n.spaceAnd()," ")),b[A].indexOf("/")>-1||b[A].indexOf("-")>-1){var B=b[A].indexOf("-")>-1&&b[A].indexOf("/")==-1,I=this.getSegmentDescription(b[A],u,m,h,B?this.i18n.commaX0ThroughX1:f,g);B&&(I=I.replace(", ","")),q+=I;}else P?q+=this.getSegmentDescription(b[A],u,m,h,f,g):q+=m(b[A]);P?y=q:y=a.StringUtilities.format(g(d),q);}else if(P){var b=d.split("/");if(y=a.StringUtilities.format(h(b[1]),b[1]),b[0].indexOf("-")>-1){var G=this.generateRangeSegmentDescription(b[0],f,m);G.indexOf(", ")!=0&&(y+=", "),y+=G;}else if(b[0].indexOf("*")==-1){var te=a.StringUtilities.format(g(b[0]),m(b[0]));te=te.replace(", ",""),y+=a.StringUtilities.format(this.i18n.commaStartingX0(),te);}}else x&&(y=this.generateRangeSegmentDescription(d,f,m));return y},l.prototype.generateRangeSegmentDescription=function(d,u,m){var h="",f=d.split("-"),g=m(f[0],1),y=m(f[1],2),P=u(d);return h+=a.StringUtilities.format(P,g,y),h},l.prototype.formatTime=function(d,u,m){var h=0,f=0,g=parseInt(d)+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 P="",x=false;this.options.use24HourTimeFormat||(x=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),P=x?"".concat(this.getPeriod(g)," "):" ".concat(this.getPeriod(g)),g>12&&(g-=12),g===0&&(g=12));var w="";return m&&(w=":".concat(("00"+m).substring(m.length))),"".concat(x?P:"").concat(("00"+g.toString()).substring(g.toString().length),":").concat(("00"+y.toString()).substring(y.toString().length)).concat(w).concat(x?"":P)},l.prototype.transformVerbosity=function(d,u){if(!u&&(d=d.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),d=d.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),d=d.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),d=d.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];d=d.replace(new RegExp(g,"g"),y);}return d},l.prototype.getPeriod=function(d){return d>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},l.locales={},l})();n.ExpressionDescriptor=p;}),747:((s,n,i)=>{Object.defineProperty(n,"__esModule",{value:true}),n.enLocaleLoader=void 0;var a=i(486),c=(function(){function p(){}return p.prototype.load=function(l){l.en=new a.en;},p})();n.enLocaleLoader=c;}),486:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.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})();n.en=i;}),515:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true});function i(c,p){if(!c)throw new Error(p)}var a=(function(){function c(){}return c.secondRange=function(p){for(var l=p.split(","),d=0;d<l.length;d++)if(!isNaN(parseInt(l[d],10))){var u=parseInt(l[d],10);i(u>=0&&u<=59,"seconds part must be >= 0 and <= 59");}},c.minuteRange=function(p){for(var l=p.split(","),d=0;d<l.length;d++)if(!isNaN(parseInt(l[d],10))){var u=parseInt(l[d],10);i(u>=0&&u<=59,"minutes part must be >= 0 and <= 59");}},c.hourRange=function(p){for(var l=p.split(","),d=0;d<l.length;d++)if(!isNaN(parseInt(l[d],10))){var u=parseInt(l[d],10);i(u>=0&&u<=23,"hours part must be >= 0 and <= 23");}},c.dayOfMonthRange=function(p){for(var l=p.split(","),d=0;d<l.length;d++)if(!isNaN(parseInt(l[d],10))){var u=parseInt(l[d],10);i(u>=1&&u<=31,"DOM part must be >= 1 and <= 31");}},c.monthRange=function(p,l){for(var d=p.split(","),u=0;u<d.length;u++)if(!isNaN(parseInt(d[u],10))){var m=parseInt(d[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(p,l){for(var d=p.split(","),u=0;u<d.length;u++)if(!isNaN(parseInt(d[u],10))){var m=parseInt(d[u],10);i(m>=0&&m<=6,l?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7");}},c})();n.default=a;}),823:((s,n)=>{Object.defineProperty(n,"__esModule",{value:true}),n.StringUtilities=void 0;var i=(function(){function a(){}return a.format=function(c){for(var p=[],l=1;l<arguments.length;l++)p[l-1]=arguments[l];return c.replace(/%s/g,function(d){for(var u=[],m=1;m<arguments.length;m++)u[m-1]=arguments[m];return p.shift()})},a.containsAny=function(c,p){return p.some(function(l){return c.indexOf(l)>-1})},a})();n.StringUtilities=i;})},e={};function t(s){var n=e[s];if(n!==void 0)return n.exports;var i=e[s]={exports:{}};return o[s](i,i.exports,t),i.exports}var r={};return (()=>{var s=r;Object.defineProperty(s,"__esModule",{value:true}),s.toString=void 0;var n=t(333),i=t(747);n.ExpressionDescriptor.initialize(new i.enLocaleLoader),s.default=n.ExpressionDescriptor;var a=n.ExpressionDescriptor.toString;s.toString=a;})(),r})());});var O=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 fo=o=>(e,t,r)=>{let s=O.get(e,t);return s||(s={middlewares:[]}),s.cacheConfig=o,O.set(e,t,s),r};J();J();var tr=class{getCwd(){switch(M.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},L=new tr;J();var rr=class{basename(e){switch(M.type){case "node":case "bun":case "deno":return vt__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(M.type){case "node":case "bun":case "deno":return vt__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(M.type){case "bun":case "node":case "deno":return vt__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(M.type){case "bun":case "node":case "deno":return vt__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},S=new rr;var sr=class{async glob(...e){let t=await import('fs/promises'),r=L.getCwd(),s=S.resolve(r,e[1]?.cwd??""),n=[];for await(let i of t.glob(...e)){if(typeof i=="string"){n.push(S.resolve(s,i));continue}i.isFile()&&n.push(S.resolve(s,i.name));}return n}async mkdir(e,t){switch(M.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(M.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(M.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 n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.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(M.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(M.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 n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async lstat(e){switch(M.type){case "node":let r=await(await import('fs/promises')).lstat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let n=await(await import('fs/promises')).lstat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let i=await Deno.lstat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:i.isSymlink,size:i.size}}}async unlink(e){switch(M.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(M.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(M.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 sr;var R=class extends Error{constructor(e){super(e);}};var yo=()=>go__default.default({level:"info",formatters:{level:e=>({level:e})}}),E=yo();var wt=class extends R{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 Ie=class extends R{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var bt=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))):Yt("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)??Yt,de=async o=>{let e=S.join(process.cwd(),"node_modules");if(!await v.exists(e))return o;let r=[];for(let s of o){let n=S.join(e,s);await v.exists(n)||r.push(s);}return r},V=async()=>await v.exists(S.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await v.exists(S.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await v.exists(S.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await v.exists(S.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await v.exists(S.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],Q=async(o,e,t,r,s=true)=>{let n=ts__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
|
-
(y/n): `;return new Promise(
|
|
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 Ne;if(!("toJSONSchema"in e))throw new Ne}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new Ne;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 yt(r):r}}};var bt=class extends R{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var D=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=vt("@sinclair/typebox"),this.typeboxModule}catch{throw new bt}}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}};function We(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let i=t[n];if(i&&typeof i=="object"&&!("$ref"in i)){let a=We(i);a!==i&&(s=true),r[n]=a;}else r[n]=i;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=We(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let i of r)if(i&&typeof i=="object"&&!("$ref"in i)){let a=We(i);a!==i&&(n=true),s.push(a);}else s.push(i);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let i in r){let a=r[i];if(a&&typeof a=="object"){let l=We(a);l!==a&&(n=true),s[i]=l;}else s[i]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var j=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 n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}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 n=We(e),i=uo__default.default(n,{ajv:this.ajv.opts});return r.set(t,i),i}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,n]of Object.entries(e)){let i=Number(s),a=null;if(H.isZodSchema(n)){let l=H.toJSONSchema(n);a=this.getOrCreateSerializer(l,"fast_stringify_zod");}else D.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"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 or=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);j.storeJsonSchema(t,"serialize_zod"),j.getOrCompileValidator(t,"serialize_zod");}catch(t){M.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(D.isTypeBoxSchema(o)){try{j.storeJsonSchema(o,"serialize_typebox"),j.getOrCompileValidator(o,"serialize_typebox");}catch(t){M.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 o=="object"&&o!==null){try{j.storeJsonSchema(o,"serialize_json"),j.getOrCompileValidator(o,"serialize_json");}catch(t){M.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(o);try{let t={type:typeof o};j.storeJsonSchema(t,`serialize_primitive_${e}`),j.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){M.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},ts=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);j.storeJsonSchema(t,"zod_schema"),j.getOrCompileValidator(t,"zod_schema");}catch(t){M.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(D.isTypeBoxSchema(o)){try{j.storeJsonSchema(o,"typebox_schema"),j.getOrCompileValidator(o,"typebox_schema");}catch(t){M.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 o=="object"&&o!==null){try{j.storeJsonSchema(o,"json_schema"),j.getOrCompileValidator(o,"json_schema");}catch(t){M.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(o);try{let t={type:typeof o};j.storeJsonSchema(t,`primitive_${e}`),j.getOrCompileValidator(t,`primitive_${e}`);}catch(t){M.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},rs=(o,e)=>{o&&ts(o),e&&ts(e);},ss=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,or(r),H.isZodSchema(r))try{let n=H.toJSONSchema(r);j.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else D.isTypeBoxSchema(r)?j.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&j.getOrCreateSerializer(r,"fast_stringify_json");}return e};var os=null;function ns(o){if(o.schema&&!o.map)throw new Error("setValidationErrorHandler: 'map' function is required when 'schema' is provided. The schema defines the response shape, so 'map' must transform AJV errors to match it.");os=o;}function Ie(){return os}var is=(o,e)=>async function(t,r,...s){try{if(e.headers){let n=t.validateHeaders(e.headers,!0);t.headers=n;}if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){let i=Ie();if(n instanceof ajv.ValidationError){let l=n,p={message:l.message,errors:l.errors,ajv:true,validation:true};if(i){let c=i.status??422,d=i.map?await i.map(p,t):p;return r.status(c).json(d)}return r.unprocessableEntity(p)}let a={message:n instanceof Error?n.message:String(n),errors:[],ajv:true,validation:true};if(i){let l=i.status??422,p=i.map?await i.map(a,t):a;return r.status(l).json(p)}return r.unprocessableEntity(n)}};var yo=util.promisify(zlib.gzip),vo=util.promisify(zlib.gunzip);function cs(o){let{prefix:e,method:t,route:r,routeParams:s,body:n,bodyKeys:i,includeBody:a=true,query:l,queryKeys:p,includeQuery:c=false,headers:d,headerKeys:u,includeHeaders:h=false,fromRequestValue:m}=o,f=[e,"global"];if(f.push(t.toUpperCase(),bo(r)),s&&Object.keys(s).length>0&&f.push(Ke(s)),c&&l){let g=nr(l,p);Object.keys(g).length>0&&f.push("q:"+Ke(g));}if(a&&n!=null){let g=nr(n,i);f.push("b:"+Ke(g));}if(h&&d){let g=nr(d,u);Object.keys(g).length>0&&f.push("h:"+Ke(g));}return m!=null&&f.push("c:"+Ke(m)),f.join(":")}function nr(o,e){if(!e||e.length===0)return o;let t={};for(let r of e)r in o&&(t[r]=o[r]);return t}function Ke(o){let e=Xe(o);return Jo.createHash("sha256").update(e).digest("hex").substring(0,32)}function Xe(o){return o===null?"null":o===void 0?"":typeof o!="object"?JSON.stringify(o):Array.isArray(o)?"["+o.map(r=>Xe(r)||"null").join(",")+"]":"{"+Object.keys(o).filter(r=>o[r]!==void 0).sort().map(r=>JSON.stringify(r)+":"+Xe(o[r])).join(",")+"}"}function bo(o){return o.toLowerCase().replace(/\/+/g,"/").replace(/\/$/,"")}function ir(o){return `lock:${o}`}function ar(o,e){return `${o}:tag:${e}`}async function ls(o){return yo(Buffer.from(o,"utf-8"))}async function ds(o){return (await vo(o)).toString("utf-8")}function wt(o){let e=o.include,t=true,r=false,s=false,n,i,a;return e&&(e.body===false?t=false:Array.isArray(e.body)?(t=true,n=e.body):e.body===true&&(t=true),e.body===void 0&&(t=false),e.query===true?r=true:Array.isArray(e.query)&&(r=true,i=e.query),e.headers===true?s=true:Array.isArray(e.headers)&&(s=true,a=e.headers)),{ttl:o.ttl,useCompression:o.useCompression,tags:o.tags,lockBehavior:o.lockBehavior,includeBody:t,includeQuery:r,includeHeaders:s,bodyKeys:n,queryKeys:i,headerKeys:a,fromRequest:e?.fromRequest}}var Le={defaultTtl:300,compressionThreshold:1024,keyPrefix:"cache",enableStats:true,lockTimeout:5e3,lockBehavior:"wait"};var ps=50,ue="x-cache",cr=(s=>(s.Hit="HIT",s.Miss="MISS",s.Wait="WAIT",s.Bypass="BYPASS",s))(cr||{});var Ze=class{log=M.child({scope:"CacheService"});provider;options;stats={hits:0,misses:0,hitRate:0,invalidations:0};constructor(e,t){this.provider=e,this.options=t;}async get(e){try{let t=await this.provider.get(e);if(!t)return this.options.enableStats&&(this.stats.misses++,this.updateHitRate()),null;this.options.enableStats&&(this.stats.hits++,this.updateHitRate());let r=JSON.parse(t),s=r.data;return r.compressed&&(s=await ds(Buffer.from(r.data,"base64"))),JSON.parse(s)}catch(t){return this.log.error({error:t,key:e},"Cache get failed"),null}}async set(e,t,r,s){try{let n=Xe(t),i=s?.compressed&&n.length>this.options.compressionThreshold,a=n;i&&(a=(await ls(n)).toString("base64"));let l={data:a,compressed:i??!1,createdAt:Date.now(),ttl:r};if(await this.provider.set(e,JSON.stringify(l),r),s?.tags?.length)for(let p of s.tags){let c=ar(this.options.keyPrefix,p);await this.provider.addToSet(c,[e],r+60);}}catch(n){this.log.error({error:n,key:e},"Cache set failed");}}async invalidate(e){if(!e.length)return 0;let t=0;try{for(let r of e){let s=ar(this.options.keyPrefix,r),n=await this.provider.getSetMembers(s);if(n.length>0){let i=await this.provider.delMany([...n,s]);t+=i-1;}}this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,tags:e},"Cache invalidate failed");}return t}async invalidateKey(e){try{if(await this.provider.del(e))return this.options.enableStats&&this.stats.invalidations++,!0}catch(t){this.log.error({error:t,key:e},"Cache invalidateKey failed");}return false}async invalidatePattern(e){let t=0;try{for await(let r of this.provider.scan(e))r.length>0&&(t+=await this.provider.delMany(r));this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,pattern:e},"Cache invalidatePattern failed");}return t}async acquireLock(e){try{let t=ir(e);return await this.provider.acquireLock(t,this.options.lockTimeout)}catch(t){return this.log.error({error:t,key:e},"Cache acquireLock failed"),true}}async releaseLock(e){try{let t=ir(e);await this.provider.releaseLock(t);}catch(t){this.log.warn({error:t,key:e},"Cache releaseLock failed");}}async waitForCache(e,t){let r=Date.now();for(;Date.now()-r<t;){let s=await this.get(e);if(s!==null)return s;await new Promise(n=>setTimeout(n,ps));}return null}getStats(){return {...this.stats}}getProvider(){return this.provider}async disconnect(){await this.provider.disconnect();}updateHitRate(){let e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0;}};var St=null,lr={...Le};function dr(o,e){return St=new Ze(o,e),lr=e,St}function Ye(){return St}function xt(){return lr}function wo(){St=null,lr={...Le};}function Tt(o,e,t){let r=M.child({scope:"CacheMiddleware"});return async(s,n,i)=>{try{let a={};if(e.includeHeaders&&s.rawHeaders)if(e.headerKeys)for(let m of e.headerKeys){let f=s.rawHeaders.get(m);f&&(a[m]=f);}else s.rawHeaders.forEach((m,f)=>{a[f]=m;});let l=s.url,p=l.startsWith("http")?new URL(l).pathname:l.split("?")[0],c=e.fromRequest?await e.fromRequest(s):void 0,d=cs({prefix:t.keyPrefix,method:s.method,route:p,routeParams:s.params,body:s.body,bodyKeys:e.bodyKeys,includeBody:e.includeBody,query:s.query,queryKeys:e.queryKeys,includeQuery:e.includeQuery,headers:a,headerKeys:e.headerKeys,includeHeaders:e.includeHeaders,fromRequestValue:c});r.debug({key:d},"Generated cache key");let u=await o.get(d);if(u!==null){n.setHeader(ue,"HIT"),n.json(u);return}let h=await o.acquireLock(d);if(!h){let m=e.lockBehavior??t.lockBehavior;if(!(await So(m,o,d,t.lockTimeout,n)).continueToHandler)return}n.setHeader(ue,"MISS"),await i();try{if(n.responseStatus>=200&&n.responseStatus<300){let m=n.getBody(),f=typeof m=="string"?JSON.parse(m):m;await o.set(d,f,e.ttl,{compressed:e.useCompression,tags:e.tags}),r.debug({key:d,ttl:e.ttl},"Cached response");}}catch(m){r.error({error:m,key:d},"Failed to cache response");}finally{h&&await o.releaseLock(d);}}catch(a){return r.error({error:a},"Cache middleware error"),n.setHeader(ue,"BYPASS"),i()}}}async function So(o,e,t,r,s){switch(o){case "bypass":return s.setHeader(ue,"BYPASS"),{continueToHandler:true};case "fail":return s.setHeader(ue,"BYPASS"),s.setHeader("Retry-After",String(Math.ceil(r/1e3))),s.status(503).json({error:"Service Unavailable",message:"Cache computation in progress"}),{continueToHandler:false};default:{s.setHeader(ue,"WAIT");let n=await e.waitForCache(t,r);return n!==null?(s.json(n),{continueToHandler:false}):{continueToHandler:true}}}}var us=null;function ms(o){if(o.schema&&!o.map)throw new Error("setPolicyErrorHandler: 'map' function is required when 'schema' is provided. The schema defines the response shape, so 'map' must return data matching it.");us=o;}function hs(){return us}var Pt=o=>async(e,t,r)=>{for(let s of o)if(!await s.manager.canAccess(s.scope,s.handler,e)){let i=hs();if(i){let a=i.status??401,l=i.map?await i.map(e):{error:"Unauthorized"};return t.status(a).json(l)}return t.unauthorized({error:"Unauthorized"})}return r()};var Fe=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;}},pr=class o{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,n,i,a,l=false){e=e.toUpperCase();let p=t.split("?")[0];rs(n?.body,n?.query);let c=ss(a),d=n&&(n.body||n.query||n.headers||n.all),u=d?is(s,n):s,h=d?n:void 0,m=this.trees.get(e);m||(m=new Fe,this.trees.set(e,m));let f=p.replace(/^\/+|\/+$/g,""),g=f.length===0?[]:f.split("/"),y=true,P=[],S=m;for(let w of g){if(w==="*"){y=false,S.wildcardChild||(S.wildcardChild=new Fe),S=S.wildcardChild;break}if(w.startsWith(":")){y=false;let k=w.slice(1);P.push(k),S.paramChild||(S.paramChild={node:new Fe,name:k}),S=S.paramChild.node;continue}S.staticChildren.has(w)||S.staticChildren.set(w,new Fe),S=S.staticChildren.get(w);}if(S.middleware=r,S.handler=u,P.length>0&&(S.paramName=P.join(",")),c&&this.handlerResponseSchemas.set(s,c),y){let w="/"+f,k=`${e}:${w}`;this.staticRouteCache.set(k,{middleware:r,handler:u,params:{},responseSchemas:c});}else {let w="/"+f.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),k=`${e}:${w}`;this.staticRouteCache.delete(k);}let b=this.routes.findIndex(w=>w.method===e&&w.path===t);if(b!==-1){if(!l)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[b].middleware=r,this.routes[b].handler=u,this.routes[b].swaggerOptions=i,this.routes[b].responses=a,this.routes[b].responseSchemas=c,this.routes[b].validationSchemas=h;return}this.routes.push({method:e,path:t,middleware:r,handler:u,swaggerOptions:i,responses:a,responseSchemas:c,validationSchemas:h});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,i=this.staticRouteCache.get(n);if(i)return i;let a=this.trees.get(e);if(!a)return null;let l=r.replace(/^\/+|\/+$/g,""),p=l.length===0?[]:l.split("/"),c={},d=a;for(let h=0;h<p.length;h++){let m=p[h];if(d.staticChildren.has(m)){d=d.staticChildren.get(m);continue}if(d.paramChild){c[d.paramChild.name]=m,d=d.paramChild.node;continue}if(d.wildcardChild){c["*"]=p.slice(h).join("/"),d=d.wildcardChild;break}return null}if(!d.handler||!d.middleware)return null;let u=this.handlerResponseSchemas.get(d.handler);return {middleware:d.middleware,handler:d.handler,params:c,responseSchemas:u}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.policy){let i=(Array.isArray(r.policy)?r.policy:[r.policy]).map(a=>({scope:a.scope,handler:a.handler,manager:a.manager}));s.unshift(Pt(i));}if(r.cache){let n=Ye();if(n){let i=wt(r.cache),a=Tt(n,i,xt());s.push(a);}}return {middlewares:s,handler:t,body:r.body,query:r.query,headers:r.headers,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,query:a,headers:l,responses:p,swaggerOptions:c}=this.extractOptionsAndHandler(t,r);if("body"in t||"all"in t)throw new Error(`Invalid route configuration for GET ${s}: body/all validation is not allowed. HTTP specification does not support request body for GET method. Use query or headers validation instead.`);let d=[...this.middlewares,...n],u={query:a,headers:l};this.addOrUpdate("GET",s,d,i,u,c,p);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:l,headers:p,all:c,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),h=[...this.middlewares,...n],m={body:a,query:l,headers:p,all:c};this.addOrUpdate("POST",s,h,i,m,u,d);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:l,headers:p,all:c,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),h=[...this.middlewares,...n],m={body:a,query:l,headers:p,all:c};this.addOrUpdate("PATCH",s,h,i,m,u,d);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:l,headers:p,all:c,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),h=[...this.middlewares,...n],m={body:a,query:l,headers:p,all:c};this.addOrUpdate("PUT",s,h,i,m,u,d);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,query:a,headers:l,responses:p,swaggerOptions:c}=this.extractOptionsAndHandler(t,r);if("body"in t||"all"in t)throw new Error(`Invalid route configuration for DELETE ${s}: body/all validation is not allowed. HTTP specification does not support request body for DELETE method. Use query or headers validation instead.`);let d=[...this.middlewares,...n],u={query:a,headers:l};this.addOrUpdate("DELETE",s,d,i,u,c,p);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:l,headers:p,all:c,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),h=[...this.middlewares,...n],m={body:a,query:l,headers:p,all:c};this.addOrUpdate("OPTIONS",s,h,i,m,u,d);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:l,headers:p,all:c,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),h=[...this.middlewares,...n],m={body:a,query:l,headers:p,all:c};this.addOrUpdate("HEAD",s,h,i,m,u,d);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new o(i,[...this.middlewares,...s]);n?.(a);for(let l of a.getRoutes())this.addOrUpdate(l.method,l.path,l.middleware,l.handler,l.validationSchemas,l.swaggerOptions,l.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}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 pr;var mr=class o{static cronstrue=null;static async getCronstrue(){return this.cronstrue||(this.cronstrue=await Promise.resolve().then(()=>no(fs())).catch(()=>{throw new R("cronstrue not installed as a dependency, it is required in order to consult cron jobs in UI")})),this.cronstrue}async generate(){let e=await o.getCronstrue(),t=W.scheduledJobs,r=new Set,s=new Set,i=t.map(c=>{let d=e.default.toString(c.args[0])||"-",u=c.args[2]?.timezone||"System Default";return r.add(d),s.add(u),{name:c.name,schedule:c.args[0],frequency:d,timezone:u}}).map(c=>`
|
|
5
|
-
<tr data-name="${this.escapeHtml(
|
|
6
|
-
<td class="name">${this.escapeHtml(
|
|
7
|
-
<td class="schedule"><code>${this.escapeHtml(
|
|
8
|
-
<td class="frequency">${this.escapeHtml(
|
|
9
|
-
<td class="timezone">${this.escapeHtml(
|
|
10
|
-
</tr>`).join(""),a=Array.from(r).sort().map(
|
|
3
|
+
(y/n): `;return new Promise(c=>{n.question(a,p=>{if(n.close(),p.toLowerCase()==="y"||p.toLowerCase()==="yes"){child_process.execSync(o,r),c(true);return}c(false);});})};var H=class{static zodModule=null;static zodSchemaCache=new WeakSet;static load(){if(this.zodModule)return this.zodModule;try{return this.zodModule=bt("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 Ie;if(!("toJSONSchema"in e))throw new Ie}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new Ie;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 wt(r):r}}};var St=class extends R{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var D=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=bt("@sinclair/typebox"),this.typeboxModule}catch{throw new St}}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}};function Xe(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let i=t[n];if(i&&typeof i=="object"&&!("$ref"in i)){let a=Xe(i);a!==i&&(s=true),r[n]=a;}else r[n]=i;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=Xe(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let i of r)if(i&&typeof i=="object"&&!("$ref"in i)){let a=Xe(i);a!==i&&(n=true),s.push(a);}else s.push(i);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let i in r){let a=r[i];if(a&&typeof a=="object"){let c=Xe(a);c!==a&&(n=true),s[i]=c;}else s[i]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var j=class{static ajv=new ajv.Ajv({validateSchema:false,strict:false,removeAdditional:"all"});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 n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}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 n=Xe(e),i=bo__default.default(n,{ajv:this.ajv.opts});return r.set(t,i),i}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,n]of Object.entries(e)){let i=Number(s),a=null;if(H.isZodSchema(n)){let c=H.toJSONSchema(n);a=this.getOrCreateSerializer(c,"fast_stringify_zod");}else D.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"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,removeAdditional:"all"}),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 or=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);j.storeJsonSchema(t,"serialize_zod"),j.getOrCompileValidator(t,"serialize_zod");}catch(t){E.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(D.isTypeBoxSchema(o)){try{j.storeJsonSchema(o,"serialize_typebox"),j.getOrCompileValidator(o,"serialize_typebox");}catch(t){E.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 o=="object"&&o!==null){try{j.storeJsonSchema(o,"serialize_json"),j.getOrCompileValidator(o,"serialize_json");}catch(t){E.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(o);try{let t={type:typeof o};j.storeJsonSchema(t,`serialize_primitive_${e}`),j.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},ss=o=>{if(H.isZodSchema(o)){try{let t=H.toJSONSchema(o);j.storeJsonSchema(t,"zod_schema"),j.getOrCompileValidator(t,"zod_schema");}catch(t){E.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(D.isTypeBoxSchema(o)){try{j.storeJsonSchema(o,"typebox_schema"),j.getOrCompileValidator(o,"typebox_schema");}catch(t){E.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 o=="object"&&o!==null){try{j.storeJsonSchema(o,"json_schema"),j.getOrCompileValidator(o,"json_schema");}catch(t){E.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(o);try{let t={type:typeof o};j.storeJsonSchema(t,`primitive_${e}`),j.getOrCompileValidator(t,`primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},os=(o,e)=>{o&&ss(o),e&&ss(e);},ns=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,or(r),H.isZodSchema(r))try{let n=H.toJSONSchema(r);j.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else D.isTypeBoxSchema(r)?j.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&j.getOrCreateSerializer(r,"fast_stringify_json");}return e};var is=null;function as(o){if(o.schema&&!o.map)throw new Error("setValidationErrorHandler: 'map' function is required when 'schema' is provided. The schema defines the response shape, so 'map' must transform AJV errors to match it.");is=o;}function Le(){return is}var cs=(o,e)=>async function(t,r,...s){try{if(e.headers){let n=t.validateHeaders(e.headers,!0);t.headers=n;}if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){let i=Le();if(n instanceof ajv.ValidationError){let c=n,p={message:c.message,errors:c.errors,ajv:true,validation:true};if(i){let l=i.status??422,d=i.map?await i.map(p,t):p;return r.status(l).json(d)}return r.unprocessableEntity(p)}let a={message:n instanceof Error?n.message:String(n),errors:[],ajv:true,validation:true};if(i){let c=i.status??422,p=i.map?await i.map(a,t):a;return r.status(c).json(p)}return r.unprocessableEntity(n)}};var Po=util.promisify(zlib.gzip),Co=util.promisify(zlib.gunzip);function ds(o){let{prefix:e,method:t,route:r,routeParams:s,body:n,bodyKeys:i,includeBody:a=true,query:c,queryKeys:p,includeQuery:l=false,headers:d,headerKeys:u,includeHeaders:m=false,fromRequestValue:h}=o,f=[e,"global"];if(f.push(t.toUpperCase(),Oo(r)),s&&Object.keys(s).length>0&&f.push(Ze(s)),l&&c){let g=nr(c,p);Object.keys(g).length>0&&f.push("q:"+Ze(g));}if(a&&n!=null){let g=nr(n,i);f.push("b:"+Ze(g));}if(m&&d){let g=nr(d,u);Object.keys(g).length>0&&f.push("h:"+Ze(g));}return h!=null&&f.push("c:"+Ze(h)),f.join(":")}function nr(o,e){if(!e||e.length===0)return o;let t={};for(let r of e)r in o&&(t[r]=o[r]);return t}function Ze(o){let e=Ye(o);return sn.createHash("sha256").update(e).digest("hex").substring(0,32)}function Ye(o){return o===null?"null":o===void 0?"":typeof o!="object"?JSON.stringify(o):Array.isArray(o)?"["+o.map(r=>Ye(r)||"null").join(",")+"]":"{"+Object.keys(o).filter(r=>o[r]!==void 0).sort().map(r=>JSON.stringify(r)+":"+Ye(o[r])).join(",")+"}"}function Oo(o){return o.toLowerCase().replace(/\/+/g,"/").replace(/\/$/,"")}function ir(o){return `lock:${o}`}function ar(o,e){return `${o}:tag:${e}`}async function ps(o){return Po(Buffer.from(o,"utf-8"))}async function us(o){return (await Co(o)).toString("utf-8")}function xt(o){let e=o.include,t=true,r=false,s=false,n,i,a;return e&&(e.body===false?t=false:Array.isArray(e.body)?(t=true,n=e.body):e.body===true&&(t=true),e.body===void 0&&(t=false),e.query===true?r=true:Array.isArray(e.query)&&(r=true,i=e.query),e.headers===true?s=true:Array.isArray(e.headers)&&(s=true,a=e.headers)),{ttl:o.ttl,useCompression:o.useCompression,tags:o.tags,lockBehavior:o.lockBehavior,includeBody:t,includeQuery:r,includeHeaders:s,bodyKeys:n,queryKeys:i,headerKeys:a,fromRequest:e?.fromRequest}}var De={defaultTtl:300,compressionThreshold:1024,keyPrefix:"cache",enableStats:true,lockTimeout:5e3,lockBehavior:"wait"};var ms=50,ue="x-cache",cr=(s=>(s.Hit="HIT",s.Miss="MISS",s.Wait="WAIT",s.Bypass="BYPASS",s))(cr||{});var et=class{log=E.child({scope:"CacheService"});provider;options;stats={hits:0,misses:0,hitRate:0,invalidations:0};constructor(e,t){this.provider=e,this.options=t;}async get(e){try{let t=await this.provider.get(e);if(!t)return this.options.enableStats&&(this.stats.misses++,this.updateHitRate()),null;this.options.enableStats&&(this.stats.hits++,this.updateHitRate());let r=JSON.parse(t),s=r.data;return r.compressed&&(s=await us(Buffer.from(r.data,"base64"))),JSON.parse(s)}catch(t){return this.log.error({error:t,key:e},"Cache get failed"),null}}async set(e,t,r,s){try{let n=Ye(t),i=s?.compressed&&n.length>this.options.compressionThreshold,a=n;i&&(a=(await ps(n)).toString("base64"));let c={data:a,compressed:i??!1,createdAt:Date.now(),ttl:r};if(await this.provider.set(e,JSON.stringify(c),r),s?.tags?.length)for(let p of s.tags){let l=ar(this.options.keyPrefix,p);await this.provider.addToSet(l,[e],r+60);}}catch(n){this.log.error({error:n,key:e},"Cache set failed");}}async invalidate(e){if(!e.length)return 0;let t=0;try{for(let r of e){let s=ar(this.options.keyPrefix,r),n=await this.provider.getSetMembers(s);if(n.length>0){let i=await this.provider.delMany([...n,s]);t+=i-1;}}this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,tags:e},"Cache invalidate failed");}return t}async invalidateKey(e){try{if(await this.provider.del(e))return this.options.enableStats&&this.stats.invalidations++,!0}catch(t){this.log.error({error:t,key:e},"Cache invalidateKey failed");}return false}async invalidatePattern(e){let t=0;try{for await(let r of this.provider.scan(e))r.length>0&&(t+=await this.provider.delMany(r));this.options.enableStats&&(this.stats.invalidations+=t);}catch(r){this.log.error({error:r,pattern:e},"Cache invalidatePattern failed");}return t}async acquireLock(e){try{let t=ir(e);return await this.provider.acquireLock(t,this.options.lockTimeout)}catch(t){return this.log.error({error:t,key:e},"Cache acquireLock failed"),true}}async releaseLock(e){try{let t=ir(e);await this.provider.releaseLock(t);}catch(t){this.log.warn({error:t,key:e},"Cache releaseLock failed");}}async waitForCache(e,t){let r=Date.now();for(;Date.now()-r<t;){let s=await this.get(e);if(s!==null)return s;await new Promise(n=>setTimeout(n,ms));}return null}getStats(){return {...this.stats}}getProvider(){return this.provider}async disconnect(){await this.provider.disconnect();}updateHitRate(){let e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0;}};var Tt=null,lr={...De};function dr(o,e){return Tt=new et(o,e),lr=e,Tt}function tt(){return Tt}function Rt(){return lr}function Eo(){Tt=null,lr={...De};}function Pt(o,e,t){let r=E.child({scope:"CacheMiddleware"});return async(s,n,i)=>{try{let a={};if(e.includeHeaders&&s.rawHeaders)if(e.headerKeys)for(let h of e.headerKeys){let f=s.rawHeaders.get(h);f&&(a[h]=f);}else s.rawHeaders.forEach((h,f)=>{a[f]=h;});let c=s.url,p=c.startsWith("http")?new URL(c).pathname:c.split("?")[0],l=e.fromRequest?await e.fromRequest(s):void 0,d=ds({prefix:t.keyPrefix,method:s.method,route:p,routeParams:s.params,body:s.body,bodyKeys:e.bodyKeys,includeBody:e.includeBody,query:s.query,queryKeys:e.queryKeys,includeQuery:e.includeQuery,headers:a,headerKeys:e.headerKeys,includeHeaders:e.includeHeaders,fromRequestValue:l});r.debug({key:d},"Generated cache key");let u=await o.get(d);if(u!==null){n.setHeader(ue,"HIT"),n.json(u);return}let m=await o.acquireLock(d);if(!m){let h=e.lockBehavior??t.lockBehavior;if(!(await Mo(h,o,d,t.lockTimeout,n)).continueToHandler)return}n.setHeader(ue,"MISS"),await i();try{if(n.responseStatus>=200&&n.responseStatus<300){let h=n.getBody(),f=typeof h=="string"?JSON.parse(h):h;await o.set(d,f,e.ttl,{compressed:e.useCompression,tags:e.tags}),r.debug({key:d,ttl:e.ttl},"Cached response");}}catch(h){r.error({error:h,key:d},"Failed to cache response");}finally{m&&await o.releaseLock(d);}}catch(a){return r.error({error:a},"Cache middleware error"),n.setHeader(ue,"BYPASS"),i()}}}async function Mo(o,e,t,r,s){switch(o){case "bypass":return s.setHeader(ue,"BYPASS"),{continueToHandler:true};case "fail":return s.setHeader(ue,"BYPASS"),s.setHeader("Retry-After",String(Math.ceil(r/1e3))),s.status(503).json({error:"Service Unavailable",message:"Cache computation in progress"}),{continueToHandler:false};default:{s.setHeader(ue,"WAIT");let n=await e.waitForCache(t,r);return n!==null?(s.json(n),{continueToHandler:false}):{continueToHandler:true}}}}var hs=null;function fs(o){if(o.schema&&!o.map)throw new Error("setPolicyErrorHandler: 'map' function is required when 'schema' is provided. The schema defines the response shape, so 'map' must return data matching it.");hs=o;}function gs(){return hs}var Ct=o=>async(e,t,r)=>{for(let s of o)if(!await s.manager.canAccess(s.scope,s.handler,e)){let i=gs();if(i){let a=i.status??401,c=i.map?await i.map(e):{error:"Unauthorized"};return t.status(a).json(c)}return t.unauthorized({error:"Unauthorized"})}return r()};var Fe=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;}},pr=class o{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,n,i,a,c=false){e=e.toUpperCase();let p=t.split("?")[0];os(n?.body,n?.query);let l=ns(a),d=n&&(n.body||n.query||n.headers||n.all),u=d?cs(s,n):s,m=d?n:void 0,h=this.trees.get(e);h||(h=new Fe,this.trees.set(e,h));let f=p.replace(/^\/+|\/+$/g,""),g=f.length===0?[]:f.split("/"),y=true,P=[],x=h;for(let b of g){if(b==="*"){y=false,x.wildcardChild||(x.wildcardChild=new Fe),x=x.wildcardChild;break}if(b.startsWith(":")){y=false;let q=b.slice(1);P.push(q),x.paramChild||(x.paramChild={node:new Fe,name:q}),x=x.paramChild.node;continue}x.staticChildren.has(b)||x.staticChildren.set(b,new Fe),x=x.staticChildren.get(b);}if(x.middleware=r,x.handler=u,P.length>0&&(x.paramName=P.join(",")),l&&this.handlerResponseSchemas.set(s,l),y){let b="/"+f,q=`${e}:${b}`;this.staticRouteCache.set(q,{middleware:r,handler:u,params:{},responseSchemas:l});}else {let b="/"+f.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),q=`${e}:${b}`;this.staticRouteCache.delete(q);}let w=this.routes.findIndex(b=>b.method===e&&b.path===t);if(w!==-1){if(!c)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[w].middleware=r,this.routes[w].handler=u,this.routes[w].swaggerOptions=i,this.routes[w].responses=a,this.routes[w].responseSchemas=l,this.routes[w].validationSchemas=m;return}this.routes.push({method:e,path:t,middleware:r,handler:u,swaggerOptions:i,responses:a,responseSchemas:l,validationSchemas:m});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,i=this.staticRouteCache.get(n);if(i)return i;let a=this.trees.get(e);if(!a)return null;let c=r.replace(/^\/+|\/+$/g,""),p=c.length===0?[]:c.split("/"),l={},d=a;for(let m=0;m<p.length;m++){let h=p[m];if(d.staticChildren.has(h)){d=d.staticChildren.get(h);continue}if(d.paramChild){l[d.paramChild.name]=ys(h),d=d.paramChild.node;continue}if(d.wildcardChild){l["*"]=ys(p.slice(m).join("/")),d=d.wildcardChild;break}return null}if(!d.handler||!d.middleware)return null;let u=this.handlerResponseSchemas.get(d.handler);return {middleware:d.middleware,handler:d.handler,params:l,responseSchemas:u}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.policy){let i=(Array.isArray(r.policy)?r.policy:[r.policy]).map(a=>({scope:a.scope,handler:a.handler,manager:a.manager}));s.unshift(Ct(i));}if(r.cache){let n=tt();if(n){let i=xt(r.cache),a=Pt(n,i,Rt());s.push(a);}}return {middlewares:s,handler:t,body:r.body,query:r.query,headers:r.headers,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,query:a,headers:c,responses:p,swaggerOptions:l}=this.extractOptionsAndHandler(t,r);if("body"in t||"all"in t)throw new Error(`Invalid route configuration for GET ${s}: body/all validation is not allowed. HTTP specification does not support request body for GET method. Use query or headers validation instead.`);let d=[...this.middlewares,...n],u={query:a,headers:c};this.addOrUpdate("GET",s,d,i,u,l,p);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:p,all:l,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),m=[...this.middlewares,...n],h={body:a,query:c,headers:p,all:l};this.addOrUpdate("POST",s,m,i,h,u,d);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:p,all:l,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),m=[...this.middlewares,...n],h={body:a,query:c,headers:p,all:l};this.addOrUpdate("PATCH",s,m,i,h,u,d);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:p,all:l,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),m=[...this.middlewares,...n],h={body:a,query:c,headers:p,all:l};this.addOrUpdate("PUT",s,m,i,h,u,d);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,query:a,headers:c,responses:p,swaggerOptions:l}=this.extractOptionsAndHandler(t,r);if("body"in t||"all"in t)throw new Error(`Invalid route configuration for DELETE ${s}: body/all validation is not allowed. HTTP specification does not support request body for DELETE method. Use query or headers validation instead.`);let d=[...this.middlewares,...n],u={query:a,headers:c};this.addOrUpdate("DELETE",s,d,i,u,l,p);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:p,all:l,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),m=[...this.middlewares,...n],h={body:a,query:c,headers:p,all:l};this.addOrUpdate("OPTIONS",s,m,i,h,u,d);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:i,body:a,query:c,headers:p,all:l,responses:d,swaggerOptions:u}=this.extractOptionsAndHandler(t,r),m=[...this.middlewares,...n],h={body:a,query:c,headers:p,all:l};this.addOrUpdate("HEAD",s,m,i,h,u,d);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new o(i,[...this.middlewares,...s]);n?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.validationSchemas,c.swaggerOptions,c.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}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 pr;function ys(o){if(o.includes("\0"))throw Object.assign(new Error("NUL byte in route parameter"),{status:400});try{let e=decodeURIComponent(o);if(e.includes("\0"))throw Object.assign(new Error("NUL byte in route parameter"),{status:400});return e}catch(e){if(e.status===400)throw e;return o}}var mr=class o{static cronstrue=null;static async getCronstrue(){return this.cronstrue||(this.cronstrue=await Promise.resolve().then(()=>ho(vs())).catch(()=>{throw new R("cronstrue not installed as a dependency, it is required in order to consult cron jobs in UI")})),this.cronstrue}async generate(){let e=await o.getCronstrue(),t=W.scheduledJobs,r=new Set,s=new Set,i=t.map(l=>{let d=e.default.toString(l.args[0])||"-",u=l.args[2]?.timezone||"System Default";return r.add(d),s.add(u),{name:l.name,schedule:l.args[0],frequency:d,timezone:u}}).map(l=>`
|
|
5
|
+
<tr data-name="${this.escapeHtml(l.name.toLowerCase())}" data-frequency="${this.escapeHtml(l.frequency)}" data-timezone="${this.escapeHtml(l.timezone)}">
|
|
6
|
+
<td class="name">${this.escapeHtml(l.name)}</td>
|
|
7
|
+
<td class="schedule"><code>${this.escapeHtml(l.schedule)}</code></td>
|
|
8
|
+
<td class="frequency">${this.escapeHtml(l.frequency)}</td>
|
|
9
|
+
<td class="timezone">${this.escapeHtml(l.timezone)}</td>
|
|
10
|
+
</tr>`).join(""),a=Array.from(r).sort().map(l=>`<option value="${this.escapeHtml(l)}">${this.escapeHtml(l)}</option>`).join(""),c=Array.from(s).sort().map(l=>`<option value="${this.escapeHtml(l)}">${this.escapeHtml(l)}</option>`).join(""),p=t.length===0?'<tr><td colspan="4" class="empty-state">No cron jobs configured</td></tr>':"";return `<!DOCTYPE html>
|
|
11
11
|
<html lang="en">
|
|
12
12
|
<head>
|
|
13
13
|
<meta charset="UTF-8">
|
|
@@ -415,7 +415,7 @@ Zod is a peer dependency required when using Zod schemas for validation.`)}}stat
|
|
|
415
415
|
<label for="timezone-filter">Timezone</label>
|
|
416
416
|
<select id="timezone-filter">
|
|
417
417
|
<option value="">All Timezones</option>
|
|
418
|
-
${
|
|
418
|
+
${c}
|
|
419
419
|
</select>
|
|
420
420
|
</div>
|
|
421
421
|
</div>
|
|
@@ -490,8 +490,10 @@ 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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},hr=new mr;var W=class{static scheduledJobs=[];static logger=M.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 R("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",n=>this.globalErrorHandler(n));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}`),M.error(s);});}));}},xo=o=>{W.globalErrorHandler=o.bind(W);},To=async o=>{if(!o||o.path.length===0)throw new R("Cron UI path is required");let e=await hr.generate();_.addOrUpdate("GET",o.path,[],(t,r)=>{r.html(e);},void 0,void 0,void 0,true);};var Po=(o,e)=>function(t,r,s){let n=s.value,i=async(...a)=>{let l=new t.constructor;return await n.apply(l,a)};return W.register(`${t.constructor.name}.${r}`,o,i,e),s};V();var fr=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 n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},gr=new fr;var Ct=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Ot=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),gs=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var be=(o,e)=>{if(!o||typeof o!="string")return e;let t=o.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(s){let n=Number.parseFloat(s[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var Ro=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:ys(r)}}return {name:o,value:true}},ys=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},we=()=>{let o=gr.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=Ro(s);if(n){if(n.value===true&&r+1<o.length){let i=o[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=ys(i),r++);}if(n.name in t){let i=t[n.name];Array.isArray(i)?i.push(n.value):t[n.name]=[i,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}};var Mt=()=>gr.getCliArgs()[0]||null;var Se="VALIDATION_ERROR";var vs=we().args.slice(1),$=o=>(e,t)=>{let r=Mt();if(!r||r!==e.commandName)return;let s=t;O.set(e,t,{type:"arg",name:s,description:o.description});let n=vs.length?vs.shift():o.defaultValue;if(o.required&&!n){let i=O.get(e,Se);O.set(e,Se,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var te=o=>(e,t)=>{let r=Mt();if(!r||r!==e.commandName)return;let s=o.name||t,n=we().flags,i=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...i],l=o.defaultValue;for(let p of a){let c=[p,`-${p}`,`--${p}`];for(let d of c)if(d in n){let u=n[d];o.type==="list"?l=(Array.isArray(u)?u:[u]).map(m=>{let f=String(m);return o.parse?o.parse(f):f}):(l=u,o.type==="boolean"?l=!!l:o.type==="number"?l=Number(l):o.type==="string"&&(l=String(l)),o.parse&&(l=o.parse(l)));break}if(l!==o.defaultValue)break}if(O.set(e,t,{type:"flag",name:s,aliases:i||[],description:o.description}),o.required&&(o.type==="list"?!l||Array.isArray(l)&&l.length===0:!l)){let c=O.get(e,Se);O.set(e,Se,[...c||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:l,enumerable:true,configurable:true,writable:true});};te.boolean=o=>te({...o,type:"boolean"});te.string=o=>te({...o,type:"string"});te.number=o=>te({...o,type:"number"});te.list=o=>te({...o,type:"list"});te.array=o=>te({...o,type:"list"});var C=te;var Co=(o,e)=>t=>{let r=O.get(t.prototype,"__class__"),s=r?.middlewares||[],n=r?.policies||[],i=O.getAll(t.prototype),a=new t;if(i){for(let[l,p]of i.entries()){if(!p.route)continue;let c=t.prototype[l].bind(a),d=o?x.join(o,p.route.path):p.route.path,u=[...n,...p.policies||[]],h=u.length>0?[Pt(u)]:[],m=[...s,...h,...p.middlewares||[]];if(p.cacheConfig){let f=Ye();if(f){let g=wt(p.cacheConfig),y=Tt(f,g,xt());m.push(y);}}_.addOrUpdate(p.route.method,d,m,c,{service:t.name.replace(/Controller$/,""),...e,...p.documentation});}O.clear(t.prototype);}};var Oo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"DELETE"},O.set(t,r,n),s};var Mo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"GET"},O.set(t,r,n),s};var Eo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PATCH"},O.set(t,r,n),s};var jo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"POST"},O.set(t,r,n),s};var qo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PUT"},O.set(t,r,n),s};var ko=o=>(e,t,r)=>{if(typeof t>"u"){let n=O.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!o)throw new Error(`Middleware ${String(o)} not found, are you sure you defined it before using it?`);return Array.isArray(o)||(o=[o]),n.middlewares.push(...o),O.set(e.prototype,"__class__",n),e}let s=O.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(o)||(o=[o]),s.middlewares.push(...o),O.set(e,t,s),r};var Et=(o,e,t=false)=>{if(!o(e)){if(t)throw new ajv.ValidationError(o.errors||[]);return e}return e};var et=new WeakMap,bs=new WeakSet,_o=o=>{let{jsonSchema:e,prefix:t}=ws(o);try{return j.getOrCompileValidator(e,t)}catch{return null}},ws=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"serialize_zod"}:D.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"serialize_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"serialize_json"}:{jsonSchema:{type:typeof o},prefix:`serialize_primitive_${JSON.stringify(o)}`},Ho=(o,e)=>(t,r,s)=>{let n=O.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);n.documentation.responses[i]=o,n.serializeOptions[i]=e?.throwErrorOnValidationFail??false,O.set(t,r,n),or(o);let{jsonSchema:a,prefix:l}=ws(o);j.getOrCreateSerializer(a,l);let p=et.get(s.value)||{};if(p[i]={name:r,schema:o,throwErrorOnValidationFail:e?.throwErrorOnValidationFail??false},et.set(s.value,p),!bs.has(s.value)){let c=s.value,d=async function(...h){let m=h[1];await c.apply(this,h);let f=m.responseStatus,g=et.get(d),y=g?.[f]?.schema,P=g?.[f]?.throwErrorOnValidationFail??false;if(!y)return;let S=m.getBody();if(P){let b=_o(y);if(b)try{await Et(b,S,P);}catch(w){return M.error({error:w,body:S,statusCode:f,schemaDescription:typeof y=="object"&&y!==null?Object.keys(y).slice(0,5).join(", "):"unknown"},"Response validation failed in @serialize decorator"),m.status(500).json({error:"Internal Server Error",message:"Response validation failed"})}}m.json(S,y);};bs.add(d);let u=et.get(c);u&&et.set(d,u),s.value=d;}};var xe=o=>(e,t,r)=>{let s=r.value,n=O.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),o.body&&(n.documentation.requestBody=o.body),o.query&&(n.documentation.query=o.query),o.all&&(n.documentation.requestBody=o.all,n.documentation.query=o.all),O.set(e,t,n),r.value=async function(...i){let a=i[0],l=i[1];try{let p,c,d,u=o.throwOnValidationFail??!0;o.body&&(p=a.validate(o.body,u)),o.query&&(c=a.validateQuery(o.query,u)),o.all&&(d=a.validateAll(o.all,u));let h=[...i];return p!==void 0&&h.push(p),c!==void 0&&h.push(c),d!==void 0&&h.push(d),s.apply(this,h)}catch(p){if(o.customError)return l.status(o.customError.status||400).json({received:a.body,schema:o.body,error:p});let c=Ie();if(p instanceof ajv.ValidationError){let u=p,h={message:u.message,errors:u.errors,ajv:true,validation:true};if(c){let m=c.status??422,f=c.map?c.map(h,a):h;return l.status(m).json(f)}return l.unprocessableEntity(h)}let d={message:p instanceof Error?p.message:String(p),errors:[],ajv:true,validation:true};if(c){let u=c.status??422,h=c.map?c.map(d,a):d;return l.status(u).json(h)}return l.unprocessableEntity(p)}},r};xe.query=(o,e)=>xe({query:o,...e});xe.body=(o,e)=>xe({body:o,...e});xe.all=(o,e)=>xe({all:o,...e});var Bo=xe;var yr=class{logger=M.child({scope:this.constructor.name})};var No=o=>{if(!Buffer.isBuffer(o))return o;let e=o.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},De=class o{static subscriptions=[];static client=null;static connectionOptions={};static logger=M.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 R("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:n="mqtt",...i}=e,a=`${n}://${r}:${s}`;this.client=await t.connectAsync(a,i),this.logger.info("MQTT client connected"),this.client.on("error",async l=>{await this.globalErrorHandler(l);}),this.client.on("message",(l,p)=>{this.handleMessage(l,p);}),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 n=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${n}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(n){this.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(n);}}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,n){let i=n.value;if(!i)return n;let a=async(l,p)=>{let c=new r.constructor,d=No(p);if(i.length===1){await i.call(c,d);return}await i.call(c,l,d);};return o.register(`${r.constructor.name}.${s}`,e,a,t),n}}async unsubscribe(e){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("MQTT client is not connected. Call MqttService.connect() first.");try{await o.client.unsubscribeAsync(e),o.subscriptions=o.subscriptions.filter(t=>t.topic!==e),o.logger.debug(`Unsubscribed from topic: ${String(e)}`);}catch(t){throw o.logger.error(`Failed to unsubscribe from topic ${String(e)}: ${t.message}`),t}}async publish(e,t,r){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("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 o.client.publishAsync(e,s,r||{}),M.debug(`Published message to topic: ${String(e)}`);}catch(n){throw M.error(`Failed to publish to topic ${String(e)}: ${n.message}`),n}}static async disconnect(){if(this.client)return new Promise(e=>{let t=this.client;t?.end(false,{},()=>{M.info("MQTT client disconnected gracefully"),t?.emit("disconnect",{cmd:"disconnect"}),this.client=null,e();});})}},Io=o=>{De.globalErrorHandler=o.bind(De);},Lo=new De;var Y=class extends R{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var vr=class{randomUUID(){return crypto.randomUUID()}},re=new vr;var ae=class{static options={connection:{}}},Ss=o=>{ae.options=o??{connection:{}};};var tt=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),n=re.randomUUID();return await s.add(e,t,{jobId:n,...ae.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=ae.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async a=>{try{await t(a.data);}catch(l){await r?.(a,l)??Promise.reject(l);}},{...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 Y("bullmq","ioredis")}),r=new t.Queue(e,{...ae.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 Y("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let n=await this.getQueueWithConfig(e,s),i=re.randomUUID(),a={jobId:i,...ae.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await n.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 n=ae.options??{},{errorHandler:i}=n,a=await this.getBullMQClient(),l={...n,...r};delete l.errorHandler,delete l.defaultJobOptions;let p=new a.Worker(e,async c=>{try{await t(c.data);}catch(d){await i?.(c,d)??Promise.reject(d);}},l);this.workers.set(s,p);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new Y("bullmq","ioredis")}),n={...ae.options||{connection:{}},...t},i=new s.Queue(e,n);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 rt=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=re.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(n=>{console.error("[MemoryPubSub] Fatal queue processing error:",n);}).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 se=class{static options={}},xs=o=>{se.options=o??{};};var st=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let n=r||{},i=await s.send(e,t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=se.options;s.errorHandler&&r.on("error",s.errorHandler);let n=await r.work(e,async i=>{let a=Array.isArray(i)?i:[i];for(let l of a)await t(l.data);});this.workers.set(e,n);}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 Y("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:n}=se.options,i=s??n,a=new r(i);return se.options?.errorHandler&&a.on("error",se.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 n=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,n);let i=r||{},a=await n.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 n=se.options;n.errorHandler&&s.on("error",n.errorHandler);let i=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async l=>{let p=Array.isArray(l)?l:[l];for(let c of p)await t(c.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 Y("pg-boss","pg")}),n=r.PgBoss.default??r.PgBoss,i=new n(e.connectionString);return se.options?.errorHandler&&i.on("error",se.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 me=class{static options={}},Ts=o=>{me.options=o??{};};var ot=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new n({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=me.options,s=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async l=>{let p=JSON.parse(l.Body||"{}");await t(p);}},i=s.Consumer.create(n),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=me.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 Y("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new Y("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=me.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{...n}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),l=s?.queueUrl??await this.resolveQueueUrl(e),p=new a({...n,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:l});return {id:(await i.send(p)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=me.options,n=await this.getSqsConsumerLib(),i=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:i,handleMessage:async c=>{let d=JSON.parse(c.Body||"{}");await t(d);}},l=n.Consumer.create(a),p=s.errorHandler;p&&(l.on("error",p),l.on("processing_error",p)),l.start(),this.consumers.set(e,l);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var oe=class{static map=new Map;static{this.map.set("bullmq",new tt),this.map.set("sqs",new ot),this.map.set("pgboss",new st),this.map.set("memory",new rt);}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 K=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=M.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,n){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:n});}static registerCustomQueue(e,t,r,s){let n=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(n)&&this.logger.warn(`Custom queue handler for ${n} already registered, overwriting previous handler`),this.customQueueSubscribers.set(n,{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:n,provider:i,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let l=oe.getProvider(i);a&&"subscribeWithConfig"in l&&typeof l.subscribeWithConfig=="function"?await l.subscribeWithConfig(s,n,a):await l.subscribe(s,n);}for(let{topic:r,handler:s,pubsub:n}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await n.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let n=await v.glob(s,{cwd:N.getCwd()});this.logger.info(`Pattern "${s}" matched ${n.length} file(s)`),r.push(...n);}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(n=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(n),t.throwOnError)throw n});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var jt=new WeakMap,Te=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=oe.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 oe.getProvider(this.provider).unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,n,i){let a=i.value,l=async p=>{let c=jt.get(s.constructor);return c||(c=K.instanceFactory(s.constructor),jt.set(s.constructor,c)),a.apply(c,[p])};return K.registerTypedQueue(`${s.constructor.name}.${String(n)}`,e,l,t,r),i}}async subscribeWithCallback(e){let t=oe.getProvider(this.provider);if(this.queueOptions){await t.subscribeWithConfig(this.topic,e,this.queueOptions);return}await t.subscribe(this.topic,e);}},qt=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,n){let i=n.value,a=async l=>{let p=jt.get(r.constructor);return p||(p=K.instanceFactory(r.constructor),jt.set(r.constructor,p)),i.apply(p,[l])};return K.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),n}}};function Fo(o,e){return new Te(o,"sqs",e)}function Do(o,e){return new Te(o,"bullmq",e)}function Qo(o,e){return new Te(o,"pgboss",e)}function br(o){return new Te(o,"memory")}function Uo(o,e){return new qt(o,e)}var zo=o=>{let e=["bullmq","pgboss","sqs"];o.bullmq&&Ss(o.bullmq),o.pgboss&&xs(o.pgboss),o.sqs&&Ts(o.sqs);for(let t of Object.keys(o)){let r=t;e.includes(r)||oe.setProvider(r,o[r]);}};V();var wr=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}`)}}},Qe=new wr;var q=class{static flagsAndArgs={flags:we().flags,args:we().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=M.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(p=>t.includes(p)))return;let s=this.commandName,n=this.description||"No description available",i=this.help||[],a=this.options,l=this.generateHelpOutput({name:s,description:n,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(l),Qe.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:i,args:a,flags:l}=e,p={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"},c=[`${p.title}${r}${p.reset}`,`${p.description}${s}${p.reset}`,"",`${p.subtitle}Usage:${p.reset}`,` ${p.code}${r}${p.reset} [options] [arguments]`,"",`${p.subtitle}Options:${p.reset}`,` ${p.flag}-h, --help${p.reset} Show this help message`,"",`${p.subtitle}Command Options:${p.reset}`,` ${p.flag}keepAlive${p.reset} ${i?.keepAlive??false?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,` ${p.flag}loggerPath${p.reset} ${i?.loggerPath??"src/logger.ts"}`,` ${p.flag}allowUnknownFlags${p.reset} ${i?.allowUnknownFlags??true?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];c.push(`${p.subtitle}Help:${p.reset}`),m.forEach(f=>{c.push(` ${p.description}${f}${p.reset}`);}),c.push("");}let d=O.getAll(t),u=d?Array.from(d.values()).filter(m=>m.type==="arg"):[],h=d?Array.from(d.values()).filter(m=>m.type==="flag"):[];return u.length&&(c.push(`${p.subtitle}Available Arguments:${p.reset}`),u.forEach(m=>{let f=m.required?` ${p.error}(required)${p.reset}`:"",g=m.description?` ${p.description}${m.description}${p.reset}`:"";c.push(` ${p.code}${m.name}${p.reset}${f}${g}`);}),c.push("")),h.length&&(c.push(`${p.subtitle}Available Flags:${p.reset}`),h.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let f=m.aliases.length?` ${p.flag}(${m.aliases.join(", ")})${p.reset}`:"",g=m.required?` ${p.error}(required)${p.reset}`:"",y=m.description?` ${p.description}${m.description}${p.reset}`:"";c.push(` ${p.flag}--${m.name}${f}${p.reset}${g}${y}`);}),c.push("")),((a?.length??0)>0||l&&Object.keys(l).length>0)&&(c.push(`${p.subtitle}Current Context:${p.reset}`),a?.length&&c.push(` ${p.info}Provided Arguments:${p.reset} ${p.code}${a.join(" ")}${p.reset}`),l&&Object.keys(l).length>0&&(c.push(` ${p.info}Provided Flags:${p.reset}`),Object.keys(l).forEach(m=>{let f=l[m],g=f!=null?` = ${p.code}${f}${p.reset}`:"";c.push(` ${p.flag}${m}${p.reset}${g}`);})),c.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(c.push(`${p.subtitle}Examples:${p.reset}`),(Array.isArray(n)?n.filter(f=>f.includes("example")):[n.split("example")[1].trim()]).forEach(f=>{c.push(` ${p.code}${f}${p.reset}`);}),c.push("")),c.join(`
|
|
494
|
-
|
|
493
|
+
</html>`}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},hr=new mr;var W=class{static scheduledJobs=[];static logger=E.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 R("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",n=>this.globalErrorHandler(n));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:L.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),E.error(s);});}));}},jo=o=>{W.globalErrorHandler=o.bind(W);},ko=async o=>{if(!o||o.path.length===0)throw new R("Cron UI path is required");let e=await hr.generate();_.addOrUpdate("GET",o.path,[],(t,r)=>{r.html(e);},void 0,void 0,void 0,true);};var qo=(o,e)=>function(t,r,s){let n=s.value,i=async(...a)=>{let c=new t.constructor;return await n.apply(c,a)};return W.register(`${t.constructor.name}.${r}`,o,i,e),s};J();var fr=class{getCliArgs(){switch(M.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(M.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 n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},gr=new fr;var Et=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Mt=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),ws=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var we=(o,e)=>{if(!o||typeof o!="string")return e;let t=o.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(s){let n=Number.parseFloat(s[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var Ao=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:bs(r)}}return {name:o,value:true}},bs=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},be=()=>{let o=gr.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=Ao(s);if(n){if(n.value===true&&r+1<o.length){let i=o[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=bs(i),r++);}if(n.name in t){let i=t[n.name];Array.isArray(i)?i.push(n.value):t[n.name]=[i,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}};var jt=()=>gr.getCliArgs()[0]||null;var Se="VALIDATION_ERROR";var Ss=be().args.slice(1),N=o=>(e,t)=>{let r=jt();if(!r||r!==e.commandName)return;let s=t;O.set(e,t,{type:"arg",name:s,description:o.description});let n=Ss.length?Ss.shift():o.defaultValue;if(o.required&&!n){let i=O.get(e,Se);O.set(e,Se,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var re=o=>(e,t)=>{let r=jt();if(!r||r!==e.commandName)return;let s=o.name||t,n=be().flags,i=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...i],c=o.defaultValue;for(let p of a){let l=[p,`-${p}`,`--${p}`];for(let d of l)if(d in n){let u=n[d];o.type==="list"?c=(Array.isArray(u)?u:[u]).map(h=>{let f=String(h);return o.parse?o.parse(f):f}):(c=u,o.type==="boolean"?c=!!c:o.type==="number"?c=Number(c):o.type==="string"&&(c=String(c)),o.parse&&(c=o.parse(c)));break}if(c!==o.defaultValue)break}if(O.set(e,t,{type:"flag",name:s,aliases:i||[],description:o.description}),o.required&&(o.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=O.get(e,Se);O.set(e,Se,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};re.boolean=o=>re({...o,type:"boolean"});re.string=o=>re({...o,type:"string"});re.number=o=>re({...o,type:"number"});re.list=o=>re({...o,type:"list"});re.array=o=>re({...o,type:"list"});var C=re;var _o=(o,e)=>t=>{let r=O.get(t.prototype,"__class__"),s=r?.middlewares||[],n=r?.policies||[],i=O.getAll(t.prototype),a=new t;if(i){for(let[c,p]of i.entries()){if(!p.route)continue;let l=t.prototype[c].bind(a),d=o?S.join(o,p.route.path):p.route.path,u=[...n,...p.policies||[]],m=u.length>0?[Ct(u)]:[],h=[...s,...m,...p.middlewares||[]];if(p.cacheConfig){let f=tt();if(f){let g=xt(p.cacheConfig),y=Pt(f,g,Rt());h.push(y);}}_.addOrUpdate(p.route.method,d,h,l,{service:t.name.replace(/Controller$/,""),...e,...p.documentation});}O.clear(t.prototype);}};var Ho=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"DELETE"},O.set(t,r,n),s};var $o=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"GET"},O.set(t,r,n),s};var Bo=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PATCH"},O.set(t,r,n),s};var No=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"POST"},O.set(t,r,n),s};var Io=(o,e)=>(t,r,s)=>{let n=O.get(t,r);return n||(n={middlewares:[],route:{path:o,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:o,method:"PUT"},O.set(t,r,n),s};var Lo=o=>(e,t,r)=>{if(typeof t>"u"){let n=O.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!o)throw new Error(`Middleware ${String(o)} not found, are you sure you defined it before using it?`);return Array.isArray(o)||(o=[o]),n.middlewares.push(...o),O.set(e.prototype,"__class__",n),e}let s=O.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(o)||(o=[o]),s.middlewares.push(...o),O.set(e,t,s),r};var Qe=(o,e,t=true)=>{if(!o(e)){if(t)throw new ajv.ValidationError(o.errors||[]);return e}return e};var rt=new WeakMap,xs=new WeakSet,Fo=o=>{let{jsonSchema:e,prefix:t}=Ts(o);try{return j.getOrCompileValidator(e,t)}catch{return null}},Ts=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"serialize_zod"}:D.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"serialize_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"serialize_json"}:{jsonSchema:{type:typeof o},prefix:`serialize_primitive_${JSON.stringify(o)}`},Qo=(o,e)=>(t,r,s)=>{let n=O.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);n.documentation.responses[i]=o,n.serializeOptions[i]=e?.throwErrorOnValidationFail??false,O.set(t,r,n),or(o);let{jsonSchema:a,prefix:c}=Ts(o);j.getOrCreateSerializer(a,c);let p=rt.get(s.value)||{};if(p[i]={name:r,schema:o,throwErrorOnValidationFail:e?.throwErrorOnValidationFail??false},rt.set(s.value,p),!xs.has(s.value)){let l=s.value,d=async function(...m){let h=m[1];await l.apply(this,m);let f=h.responseStatus,g=rt.get(d),y=g?.[f]?.schema,P=g?.[f]?.throwErrorOnValidationFail??false;if(!y)return;let x=h.getBody();if(P){let w=Fo(y);if(w)try{await Qe(w,x,P);}catch(b){return E.error({error:b,body:x,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(x,y);};xs.add(d);let u=rt.get(l);u&&rt.set(d,u),s.value=d;}};var xe=o=>(e,t,r)=>{let s=r.value,n=O.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),o.body&&(n.documentation.requestBody=o.body),o.query&&(n.documentation.query=o.query),o.all&&(n.documentation.requestBody=o.all,n.documentation.query=o.all),O.set(e,t,n),r.value=async function(...i){let a=i[0],c=i[1];try{let p,l,d,u=o.throwOnValidationFail??!0;o.body&&(p=a.validate(o.body,u)),o.query&&(l=a.validateQuery(o.query,u)),o.all&&(d=a.validateAll(o.all,u));let m=[...i];return p!==void 0&&m.push(p),l!==void 0&&m.push(l),d!==void 0&&m.push(d),s.apply(this,m)}catch(p){if(o.customError)return c.status(o.customError.status||400).json({received:a.body,schema:o.body,error:p});let l=Le();if(p instanceof ajv.ValidationError){let u=p,m={message:u.message,errors:u.errors,ajv:true,validation:true};if(l){let h=l.status??422,f=l.map?l.map(m,a):m;return c.status(h).json(f)}return c.unprocessableEntity(m)}let d={message:p instanceof Error?p.message:String(p),errors:[],ajv:true,validation:true};if(l){let u=l.status??422,m=l.map?l.map(d,a):d;return c.status(u).json(m)}return c.unprocessableEntity(p)}},r};xe.query=(o,e)=>xe({query:o,...e});xe.body=(o,e)=>xe({body:o,...e});xe.all=(o,e)=>xe({all:o,...e});var zo=xe;var yr=class o{constructor(e=new Map){this.variants=e;}defineVariant(...e){let[t,r,s]=e,n=new Map(this.variants);if(s)typeof r=="function"&&typeof s!="function"?n.set(t,{handler:r,schema:s}):n.set(t,{handler:s,schema:r});else {let i=typeof r=="function"?r:void 0,a=typeof r=="function"?void 0:r;n.set(t,{handler:i,schema:a});}return new o(n)}async useVariant(e,t,r){let s=this.variants.get(e);if(!s){let c=Array.from(this.variants.keys()).join(", ")||"(none)";throw new Error(`Serializer variant "${e}" is not defined. Defined variants: ${c}`)}let n=r?.ctx,i=r?.validate??false,a=await s.handler(t,n);return i&&s.schema?Go(s.schema,a):a}},Go=async(o,e)=>{if(H.isZodSchema(o))return o.parse(e);if(D.isTypeBoxSchema(o)){let{Value:r}=await import('@sinclair/typebox/value');if(!r.Check(o,e)){let s=Array.from(r.Errors(o,e));throw new Error(`Serializer validation failed:
|
|
494
|
+
${s.map(n=>` - ${n.message} at ${n.path}`).join(`
|
|
495
|
+
`)}`)}return r.Cast(o,e)}let t=j.getOrCompileValidator(o,"serializer_json");return Qe(t,e,true)};function Vo(o,e){return new yr}var vr=class{logger=E.child({scope:this.constructor.name})};var Jo=o=>{if(!Buffer.isBuffer(o))return o;let e=o.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},Ue=class o{static subscriptions=[];static client=null;static connectionOptions={};static logger=E.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 R("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:n="mqtt",...i}=e,a=`${n}://${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,p)=>{this.handleMessage(c,p);}),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 n=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${n}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(n){this.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(n);}}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:L.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,n){let i=n.value;if(!i)return n;let a=async(c,p)=>{let l=new r.constructor,d=Jo(p);if(i.length===1){await i.call(l,d);return}await i.call(l,c,d);};return o.register(`${r.constructor.name}.${s}`,e,a,t),n}}async unsubscribe(e){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("MQTT client is not connected. Call MqttService.connect() first.");try{await o.client.unsubscribeAsync(e),o.subscriptions=o.subscriptions.filter(t=>t.topic!==e),o.logger.debug(`Unsubscribed from topic: ${String(e)}`);}catch(t){throw o.logger.error(`Failed to unsubscribe from topic ${String(e)}: ${t.message}`),t}}async publish(e,t,r){if(!o.client)throw new R("MQTT client is not connected. Call MqttService.connect() first.");if(!o.client.connected)throw new R("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 o.client.publishAsync(e,s,r||{}),E.debug(`Published message to topic: ${String(e)}`);}catch(n){throw E.error(`Failed to publish to topic ${String(e)}: ${n.message}`),n}}static async disconnect(){if(this.client)return new Promise(e=>{let t=this.client;t?.end(false,{},()=>{E.info("MQTT client disconnected gracefully"),t?.emit("disconnect",{cmd:"disconnect"}),this.client=null,e();});})}},Wo=o=>{Ue.globalErrorHandler=o.bind(Ue);},Ko=new Ue;var Y=class extends R{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var wr=class{randomUUID(){return crypto.randomUUID()}},ee=new wr;var ae=class{static options={connection:{}}},Rs=o=>{ae.options=o??{connection:{}};};var st=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),n=ee.randomUUID();return await s.add(e,t,{jobId:n,...ae.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=ae.options??{},n=await this.getBullMQClient(),i=new n.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 Y("bullmq","ioredis")}),r=new t.Queue(e,{...ae.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 Y("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let n=await this.getQueueWithConfig(e,s),i=ee.randomUUID(),a={jobId:i,...ae.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await n.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 n=ae.options??{},{errorHandler:i}=n,a=await this.getBullMQClient(),c={...n,...r};delete c.errorHandler,delete c.defaultJobOptions;let p=new a.Worker(e,async l=>{try{await t(l.data);}catch(d){await i?.(l,d)??Promise.reject(d);}},c);this.workers.set(s,p);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new Y("bullmq","ioredis")}),n={...ae.options||{connection:{}},...t},i=new s.Queue(e,n);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 ot=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(n=>{console.error("[MemoryPubSub] Fatal queue processing error:",n);}).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 se=class{static options={}},Ps=o=>{se.options=o??{};};var nt=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let n=r||{},i=await s.send(e,t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=se.options;s.errorHandler&&r.on("error",s.errorHandler);let n=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,n);}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 Y("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:n}=se.options,i=s??n,a=new r(i);return se.options?.errorHandler&&a.on("error",se.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 n=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,n);let i=r||{},a=await n.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 n=se.options;n.errorHandler&&s.on("error",n.errorHandler);let i=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async c=>{let p=Array.isArray(c)?c:[c];for(let l of p)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 Y("pg-boss","pg")}),n=r.PgBoss.default??r.PgBoss,i=new n(e.connectionString);return se.options?.errorHandler&&i.on("error",se.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 me=class{static options={}},Cs=o=>{me.options=o??{};};var it=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new n({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=me.options,s=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let p=JSON.parse(c.Body||"{}");await t(p);}},i=s.Consumer.create(n),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=me.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 Y("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new Y("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=me.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{...n}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),p=new a({...n,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await i.send(p)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=me.options,n=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 d=JSON.parse(l.Body||"{}");await t(d);}},c=n.Consumer.create(a),p=s.errorHandler;p&&(c.on("error",p),c.on("processing_error",p)),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 oe=class{static map=new Map;static{this.map.set("bullmq",new st),this.map.set("sqs",new it),this.map.set("pgboss",new nt),this.map.set("memory",new ot);}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 K=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=E.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,n){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:n});}static registerCustomQueue(e,t,r,s){let n=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(n)&&this.logger.warn(`Custom queue handler for ${n} already registered, overwriting previous handler`),this.customQueueSubscribers.set(n,{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:n,provider:i,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let c=oe.getProvider(i);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,n,a):await c.subscribe(s,n);}for(let{topic:r,handler:s,pubsub:n}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await n.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let n=await v.glob(s,{cwd:L.getCwd()});this.logger.info(`Pattern "${s}" matched ${n.length} file(s)`),r.push(...n);}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(n=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(n),t.throwOnError)throw n});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var kt=new WeakMap,Te=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=oe.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 oe.getProvider(this.provider).unsubscribe(this.topic);}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,n,i){let a=i.value,c=async p=>{let l=kt.get(s.constructor);return l||(l=K.instanceFactory(s.constructor),kt.set(s.constructor,l)),a.apply(l,[p])};return K.registerTypedQueue(`${s.constructor.name}.${String(n)}`,e,c,t,r),i}}async subscribeWithCallback(e){let t=oe.getProvider(this.provider);if(this.queueOptions){await t.subscribeWithConfig(this.topic,e,this.queueOptions);return}await t.subscribe(this.topic,e);}},qt=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,n){let i=n.value,a=async c=>{let p=kt.get(r.constructor);return p||(p=K.instanceFactory(r.constructor),kt.set(r.constructor,p)),i.apply(p,[c])};return K.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),n}}};function Xo(o,e){return new Te(o,"sqs",e)}function Zo(o,e){return new Te(o,"bullmq",e)}function Yo(o,e){return new Te(o,"pgboss",e)}function br(o){return new Te(o,"memory")}function en(o,e){return new qt(o,e)}var tn=o=>{let e=["bullmq","pgboss","sqs"];o.bullmq&&Rs(o.bullmq),o.pgboss&&Ps(o.pgboss),o.sqs&&Cs(o.sqs);for(let t of Object.keys(o)){let r=t;e.includes(r)||oe.setProvider(r,o[r]);}};J();var Sr=class{exit(e){switch(M.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${M.type}`)}}},ze=new Sr;var k=class{static flagsAndArgs={flags:be().flags,args:be().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=E.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(p=>t.includes(p)))return;let s=this.commandName,n=this.description||"No description available",i=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:n,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(c),ze.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:i,args:a,flags:c}=e,p={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=[`${p.title}${r}${p.reset}`,`${p.description}${s}${p.reset}`,"",`${p.subtitle}Usage:${p.reset}`,` ${p.code}${r}${p.reset} [options] [arguments]`,"",`${p.subtitle}Options:${p.reset}`,` ${p.flag}-h, --help${p.reset} Show this help message`,"",`${p.subtitle}Command Options:${p.reset}`,` ${p.flag}keepAlive${p.reset} ${i?.keepAlive??false?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,` ${p.flag}loggerPath${p.reset} ${i?.loggerPath??"src/logger.ts"}`,` ${p.flag}allowUnknownFlags${p.reset} ${i?.allowUnknownFlags??true?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,""];if(n){let h=Array.isArray(n)?n:[n];l.push(`${p.subtitle}Help:${p.reset}`),h.forEach(f=>{l.push(` ${p.description}${f}${p.reset}`);}),l.push("");}let d=O.getAll(t),u=d?Array.from(d.values()).filter(h=>h.type==="arg"):[],m=d?Array.from(d.values()).filter(h=>h.type==="flag"):[];return u.length&&(l.push(`${p.subtitle}Available Arguments:${p.reset}`),u.forEach(h=>{let f=h.required?` ${p.error}(required)${p.reset}`:"",g=h.description?` ${p.description}${h.description}${p.reset}`:"";l.push(` ${p.code}${h.name}${p.reset}${f}${g}`);}),l.push("")),m.length&&(l.push(`${p.subtitle}Available Flags:${p.reset}`),m.forEach(h=>{h.aliases&&!Array.isArray(h.aliases)&&(h.aliases=[h.aliases]);let f=h.aliases.length?` ${p.flag}(${h.aliases.join(", ")})${p.reset}`:"",g=h.required?` ${p.error}(required)${p.reset}`:"",y=h.description?` ${p.description}${h.description}${p.reset}`:"";l.push(` ${p.flag}--${h.name}${f}${p.reset}${g}${y}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${p.subtitle}Current Context:${p.reset}`),a?.length&&l.push(` ${p.info}Provided Arguments:${p.reset} ${p.code}${a.join(" ")}${p.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${p.info}Provided Flags:${p.reset}`),Object.keys(c).forEach(h=>{let f=c[h],g=f!=null?` = ${p.code}${f}${p.reset}`:"";l.push(` ${p.flag}${h}${p.reset}${g}`);})),l.push("")),n&&(Array.isArray(n)?n.some(h=>h.includes("example")):n.includes("example"))&&(l.push(`${p.subtitle}Examples:${p.reset}`),(Array.isArray(n)?n.filter(f=>f.includes("example")):[n.split("example")[1].trim()]).forEach(f=>{l.push(` ${p.code}${f}${p.reset}`);}),l.push("")),l.join(`
|
|
496
|
+
`)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=O.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 n=Object.keys(e.flags).filter(i=>!t.has(i)&&!r.has(i));if(n.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(""),n.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}`),ze.exit(1);}};static validateContext=e=>{let t=Array.from(O.get(e,Se)||[]);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,n)=>{let i=`${r.info}${n+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}`),ze.exit(1);}}};var X=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,p]=await V();await Q(`${a} ${c} esbuild ${p}`,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=vt__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")});at__default.default.existsSync(r)||at__default.default.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&at__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),at__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=vt__default.default.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,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 ${n}`,output:n,assets:!!this.assets},null,2)),process.exit(0);}};T([C({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],X,"clearDist"),T([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"})],X,"entry"),T([C({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],X,"output"),T([C({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],X,"tsconfig"),T([C({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],X,"assets"),T([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'"})],X,"format"),T([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'"})],X,"packages"),T([C({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],X,"sourcemap");var Re=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 W.massiveImportCronJobs(e);let t=W.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)`),W.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};T([N({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],Re,"pattern"),T([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],Re,"additionalPatterns");var Ge=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(Pe.getCommand(this.name)){let s=Pe.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=S.join(this.path,`${this.name}.ts`),await v.exists(S.join(process.cwd(),this.path))||await v.mkdir(S.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
497
|
|
|
496
498
|
export default class extends Command {
|
|
497
499
|
static commandName = "${this.name}";
|
|
@@ -505,9 +507,9 @@ export default class extends Command {
|
|
|
505
507
|
static async handle(): Promise<void> {
|
|
506
508
|
// Implement your command logic here
|
|
507
509
|
}
|
|
508
|
-
}`}};T([
|
|
510
|
+
}`}};T([N({description:"The name of the command to generate",required:true})],Ge,"name");var Ce=class extends k{static commandName="generate-controller";static description="Generate a new controller in the specified path";static help=["Generate a new controller in the specified path","Example: npx balda generate-controller user -p src/controllers"];static controllerName;static path;static async handle(){let e=this.getControllerTemplate(),t=`${this.controllerName.toLowerCase()}.ts`;this.path=S.join(this.path,t),await v.exists(S.join(process.cwd(),this.path))||await v.mkdir(S.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=Mt(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
|
|
509
511
|
|
|
510
|
-
@controller("/${
|
|
512
|
+
@controller("/${ws(this.controllerName)}")
|
|
511
513
|
export default class ${e}Controller {
|
|
512
514
|
@get("/")
|
|
513
515
|
async index(req: Request, res: Response) {
|
|
@@ -533,7 +535,7 @@ export default class ${e}Controller {
|
|
|
533
535
|
async destroy(req: Request, res: Response) {
|
|
534
536
|
return { message: \`Delete ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
|
|
535
537
|
}
|
|
536
|
-
}`}};T([
|
|
538
|
+
}`}};T([N({description:"The name of the controller to generate",required:true})],Ce,"controllerName"),T([C({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],Ce,"path");var Oe=class extends k{static commandName="generate-cron";static description="Generate a new cron job in the specified path";static help=["Generate a new cron job in the specified path","Example: npx balda generate-cron my-cron -p src/cron"];static fileName;static path;static async handle(){let e=this.getCronTemplate();this.path=S.join(this.path,`${this.fileName}.ts`),await v.exists(S.join(process.cwd(),this.path))||await v.mkdir(S.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
|
|
537
539
|
|
|
538
540
|
export default class extends BaseCron {
|
|
539
541
|
@cron("* * * * *")
|
|
@@ -541,7 +543,7 @@ export default class extends BaseCron {
|
|
|
541
543
|
this.logger.info("Running cron job");
|
|
542
544
|
// Implement your cron job logic here
|
|
543
545
|
}
|
|
544
|
-
}`}};T([
|
|
546
|
+
}`}};T([N({description:"The name of the cron job file to generate",required:true})],Oe,"fileName"),T([C({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],Oe,"path");var Ee=class extends k{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=S.join(this.path,t),await v.exists(S.join(process.cwd(),this.path))||await v.mkdir(S.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=Mt(this.middlewareName);return `import { defineMiddleware } from "balda";
|
|
545
547
|
import type { TypedMiddleware } from "balda";
|
|
546
548
|
|
|
547
549
|
/**
|
|
@@ -558,7 +560,7 @@ export const ${e}: TypedMiddleware<${e}Extension> = defineMiddleware<${e}Extensi
|
|
|
558
560
|
// Add your middleware logic here
|
|
559
561
|
return next();
|
|
560
562
|
},
|
|
561
|
-
);`}};T([
|
|
563
|
+
);`}};T([N({description:"The name of the middleware to generate",required:true})],Ee,"middlewareName"),T([C({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],Ee,"path");var Me=class extends k{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=S.join(this.path,`${Et(this.topic.replace(/\//g,"_"))}.ts`),await v.exists(S.join(process.cwd(),this.path))||await v.mkdir(S.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
|
|
562
564
|
|
|
563
565
|
/**
|
|
564
566
|
* Define your MQTT topics interface for type safety
|
|
@@ -575,7 +577,7 @@ export default class extends BaseMqtt {
|
|
|
575
577
|
this.logger.info({ message }, "Message received");
|
|
576
578
|
// Implement your MQTT handler logic here
|
|
577
579
|
}
|
|
578
|
-
}`}};T([C({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],
|
|
580
|
+
}`}};T([C({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],Me,"path"),T([N({description:"The MQTT topic to subscribe to",required:true})],Me,"topic");var je=class extends k{static commandName="generate-plugin";static description="Generate a new plugin in the specified path";static help=["Generate a new plugin in the specified path","Example: npx balda generate-plugin my-plugin -p src/plugins"];static pluginName;static pluginPath;static async handle(){let e=this.getPluginTemplate();this.pluginPath=S.join(this.pluginPath,`${this.pluginName}.ts`),await v.exists(S.join(process.cwd(),this.pluginPath))||await v.mkdir(S.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
|
|
579
581
|
|
|
580
582
|
export default class extends BasePlugin {
|
|
581
583
|
async handle(): Promise<ServerRouteMiddleware> {
|
|
@@ -584,7 +586,7 @@ export default class extends BasePlugin {
|
|
|
584
586
|
await next();
|
|
585
587
|
};
|
|
586
588
|
}
|
|
587
|
-
}`}};T([
|
|
589
|
+
}`}};T([N({description:"The name of the plugin to generate",required:true})],je,"pluginName"),T([C({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],je,"pluginPath");var he=class extends k{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=S.join(this.path,`${Et(this.queueName)}.ts`),await v.exists(S.join(process.cwd(),this.path))||await v.mkdir(S.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await v.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
|
|
588
590
|
|
|
589
591
|
export type Payload = {
|
|
590
592
|
// Add your payload here
|
|
@@ -603,24 +605,24 @@ export default class extends BaseQueue {
|
|
|
603
605
|
this.logger.info({ payload }, 'Payload received');
|
|
604
606
|
return Promise.resolve();
|
|
605
607
|
}
|
|
606
|
-
}`}};T([
|
|
608
|
+
}`}};T([N({description:"The name of the queue to generate",required:true})],he,"queueName"),T([C({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],he,"path"),T([C({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],he,"provider");var z=class extends k{static commandName="generate-sdk";static description="Generate a TypeScript SDK from your server's OpenAPI specification";static help=["Generate a TypeScript SDK from your server's OpenAPI specification","This command imports your server instance, starts it if needed, downloads the OpenAPI spec, and generates an SDK","","Arguments:"," serverPath Path to the server instance file (default: test/server/instance.ts)","","Flags:"," -o, --output <path> Output directory for generated SDK (default: sdk)"," -s, --swagger-path <path> Swagger UI path on your server (default: /docs)"," -c, --client <type> HTTP client to use: axios or fetch (default: fetch)"," --unwrap-response-data Automatically unwrap response data property"," --single-http-client Generate single HTTP client instance"," --type-prefix <prefix> Add prefix to all generated types"," --type-suffix <suffix> Add suffix to all generated types"," --enum-names-as-values Use enum names as values"," --sort-types Sort types alphabetically","","Examples:"," npx balda generate-sdk"," npx balda generate-sdk src/server/index.ts -o ./client-sdk"," npx balda generate-sdk src/server.ts --client axios"," npx balda generate-sdk --unwrap-response-data --single-http-client"," npx balda generate-sdk --type-prefix Api --sort-types"];static serverPath;static outputPath;static swaggerPath;static httpClient;static unwrapResponseData;static singleHttpClient;static typePrefix;static typeSuffix;static enumNamesAsValues;static sortTypes;static async handle(){console.log(`
|
|
607
609
|
\u{1F680} Starting SDK generation...
|
|
608
|
-
`);let e="swagger-typescript-api",t=
|
|
609
|
-
`);let[b,
|
|
610
|
+
`);let e="swagger-typescript-api",t=S.join(process.cwd(),"node_modules"),r=await v.exists(t),s=S.join(t,e);if(!(r?await v.exists(s):false)){console.log(`\u{1F4E6} ${e} not found. Installing as dev dependency...
|
|
611
|
+
`);let[w,b,q]=await V();if(!await Q(`${w} ${b} ${e} ${q}`,w,[e],{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F SDK generation cancelled: swagger-typescript-api installation was skipped.\x1B[0m
|
|
610
612
|
`);return}console.log(`
|
|
611
613
|
\x1B[32m\u2705 ${e} installed successfully!\x1B[0m
|
|
612
|
-
`);}let i=
|
|
613
|
-
`);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let
|
|
614
|
-
`);break}}if(!
|
|
615
|
-
`);return}let d=false,u="";u="http://localhost:80";try{if(console.log(`\u{1F310} Starting server on ${u}...`),typeof
|
|
616
|
-
`),
|
|
617
|
-
`);}catch(
|
|
618
|
-
`);try{await v.exists(
|
|
619
|
-
\x1B[32m\u2705 SDK generated successfully!\x1B[0m`),console.log(`\x1B[32m\u{1F4C1} SDK location: ${
|
|
620
|
-
`);}catch(
|
|
614
|
+
`);}let i=S.resolve(process.cwd(),this.serverPath);if(!await v.exists(i)){console.error(`\x1B[31m\u274C Error: Server file not found at ${i}\x1B[0m
|
|
615
|
+
`);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let c;try{c=await import(`file://${i}`);}catch(w){console.error("\x1B[31m\u274C Error importing server module:\x1B[0m",w);return}let p=Object.keys(c),l=null;for(let w of p){let b=c[w];if("default"in b&&b.default&&(b=b.default),b&&"_brand"in b&&b._brand==="BaldaServer"&&typeof b=="object"&&"listen"in b){l=b,console.log(`\u2705 Found server instance in export: "${w}"
|
|
616
|
+
`);break}}if(!l){console.error(`\x1B[31m\u274C Error: No Server instance found in ${this.serverPath}\x1B[0m`),console.log(`\x1B[90mExpected exports: ${p.join(", ")}\x1B[0m
|
|
617
|
+
`);return}let d=false,u="";u="http://localhost:80";try{if(console.log(`\u{1F310} Starting server on ${u}...`),typeof l.listen=="function"&&!l.isListening)await new Promise((w,b)=>{try{l.listen(()=>{d=!0,console.log(`\u2705 Server started successfully!
|
|
618
|
+
`),w();});}catch(q){b(q);}}).catch(w=>{console.error("Failed to start the server, continuing...");});else throw new Error("Server instance does not have a listen() method")}catch(w){console.error("\x1B[31m\u274C Error starting server:\x1B[0m",w);return}let f=this.swaggerPath??(typeof l.serverOptions.swagger!="boolean"?l.serverOptions.swagger?.path:"/docs"),g=S.join(u,f??"/docs","/json");console.log(`\u{1F4E5} Downloading OpenAPI spec from: ${g}`);let y;try{let w=await globalThis.fetch(g);if(!w.ok)throw new Error(`Failed to fetch OpenAPI spec: ${w.status} ${w.statusText}`);y=await w.json(),console.log(`\u2705 OpenAPI spec downloaded successfully!
|
|
619
|
+
`);}catch(w){if(console.error("\x1B[31m\u274C Error downloading OpenAPI spec:\x1B[0m",w),d){let b=l;try{await b.close?.();}catch{}}return}let P=S.join(process.cwd(),".openapi-spec.json");try{await v.writeFile(P,new TextEncoder().encode(JSON.stringify(y,null,2)));}catch(w){if(console.error("\x1B[31m\u274C Error saving OpenAPI spec to file:\x1B[0m",w),d){let b=l;try{await b.close?.();}catch{}}return}let x=S.resolve(process.cwd(),this.outputPath);console.log(`\u{1F528} Generating SDK...
|
|
620
|
+
`);try{await v.exists(x)||await v.mkdir(x,{recursive:!0});let w=["npx swagger-typescript-api generate",`--path="${P}"`,`--output="${this.outputPath}"`,`--http-client ${this.httpClient}`,"--modular","--extract-request-params","--extract-request-body","--extract-response-body","--extract-response-error"];this.unwrapResponseData&&w.push("--unwrap-response-data"),this.singleHttpClient&&w.push("--single-http-client"),this.typePrefix&&w.push(`--type-prefix "${this.typePrefix}"`),this.typeSuffix&&w.push(`--type-suffix "${this.typeSuffix}"`),this.enumNamesAsValues&&w.push("--enum-names-as-values"),this.sortTypes&&w.push("--sort-types");let b=w.join(" ");child_process.execSync(b,{stdio:"inherit",cwd:process.cwd()}),console.log(`
|
|
621
|
+
\x1B[32m\u2705 SDK generated successfully!\x1B[0m`),console.log(`\x1B[32m\u{1F4C1} SDK location: ${x}\x1B[0m
|
|
622
|
+
`);}catch(w){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",w);}finally{try{await v.unlink(P);}catch{}if(d){let w=l;try{console.log("\u{1F6D1} Stopping server..."),await w.close?.(),console.log(`\u2705 Server stopped.
|
|
621
623
|
`);}catch{console.log(`\x1B[33m\u26A0\uFE0F Could not stop server gracefully.\x1B[0m
|
|
622
624
|
`);}}}console.log(`\x1B[32m\u2728 SDK generation complete!\x1B[0m
|
|
623
|
-
`);}};T([
|
|
625
|
+
`);}};T([N({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],z,"serverPath"),T([C({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],z,"outputPath"),T([C({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],z,"swaggerPath"),T([C({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],z,"httpClient"),T([C({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],z,"unwrapResponseData"),T([C({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],z,"singleHttpClient"),T([C({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],z,"typePrefix"),T([C({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],z,"typeSuffix"),T([C({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],z,"enumNamesAsValues"),T([C({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],z,"sortTypes");var ce=class extends k{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static mqtt;static cron;static graphql;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await V();if(["npm","yarn","pnpm"].includes(e)){let c=await de(this.devDependencies);if(c.length&&(this.logger.info(`Found ${c.length} missing dev dependencies`),!await Q(`${e} ${t} ${c.join(" ")} -${r}`,e,c,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}c.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let c=await de(["mqtt"]);c.length&&(await Q(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),c.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let c=await de(["node-cron"]);c.length>0&&(await Q(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),c.length||this.logger.info("node-cron package is already installed");}if(this.graphql&&["npm","yarn","pnpm"].includes(e)){let c=await de(["@apollo/server","@graphql-tools/schema","graphql"]);c.length>0&&(await Q(`${e} ${t} ${c.join(" ")}`,e,c,{stdio:"inherit"},false)||(this.logger.info("GraphQL installation cancelled by user. Skipping GraphQL scaffolding."),this.graphql=false)),c.length||this.logger.info("GraphQL packages are already installed");}let s=this.typescript?"ts":"js",n=this.getServerTemplate(),i=this.getIndexTemplate();v.exists(this.srcPath)||await v.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await v.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${s} file...`),await v.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(i));let a=this.getLoggerTemplate();if(this.logger.info(`Creating logger.${s} file...`),await v.writeFile(`${this.srcPath}/logger.${s}`,new TextEncoder().encode(a)),this.mqtt){let c=S.join(this.srcPath,"mqtt");await v.exists(c)||await v.mkdir(c,{recursive:true});let p=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await v.writeFile(S.join(c,`mqtt.config.${s}`),new TextEncoder().encode(p));}if(this.cron){let c=S.join(this.srcPath,"cron");await v.exists(c)||await v.mkdir(c,{recursive:true});let p=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await v.writeFile(S.join(c,`cron.config.${s}`),new TextEncoder().encode(p));}if(this.graphql){let c=S.join(this.srcPath,"graphql");await v.exists(c)||await v.mkdir(c,{recursive:true});let p=this.getGraphqlConfigTemplate();this.logger.info(`Creating graphql/graphql.config.${s} file...`),await v.writeFile(S.join(c,`graphql.config.${s}`),new TextEncoder().encode(p));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
|
|
624
626
|
import { logger } from "./logger.js";
|
|
625
627
|
|
|
626
628
|
const serverInstance = new Server({
|
|
@@ -690,7 +692,7 @@ import { CommandRegistry } from "../command_registry.js";
|
|
|
690
692
|
|
|
691
693
|
export const logger = pino({ level: "info" });
|
|
692
694
|
CommandRegistry.setLogger(logger);
|
|
693
|
-
`}};T([C.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],ce,"srcPath"),T([C.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],ce,"typescript"),T([C.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],ce,"mqtt"),T([C.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],ce,"cron"),T([C.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],ce,"graphql");var
|
|
695
|
+
`}};T([C.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],ce,"srcPath"),T([C.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],ce,"typescript"),T([C.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],ce,"mqtt"),T([C.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],ce,"cron"),T([C.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],ce,"graphql");var ke=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 V();if(["npm","yarn","pnpm"].includes(e)){let i=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],a=await de(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for mailer`),!await Q(`${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",n=S.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(n,new TextEncoder().encode(r)),this.logger.info(`Mailer configuration initialized successfully at ${n}`),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";
|
|
694
696
|
import { Mailer${e?`, ${this.getAdapterImport()}`:""} } from "balda";
|
|
695
697
|
|
|
696
698
|
/**
|
|
@@ -817,7 +819,7 @@ const adapter = new CustomAdapter();
|
|
|
817
819
|
* appName: "My App",
|
|
818
820
|
* },
|
|
819
821
|
* });
|
|
820
|
-
*`}};T([C.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],
|
|
822
|
+
*`}};T([C.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],ke,"templateEngine"),T([C.string({description:"Output directory for mailer configuration, default is src/mailer",aliases:"o",name:"output",required:false,defaultValue:"src/mailer"})],ke,"outputPath");var qe=class extends k{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await V();if(["npm","yarn","pnpm"].includes(e)){let i=this.queueDependencies[this.queueType],a=await de(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await Q(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,n=S.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(n,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${n}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
|
|
821
823
|
|
|
822
824
|
// Configure BullMQ connection and default options
|
|
823
825
|
defineBullMQConfiguration({
|
|
@@ -986,28 +988,28 @@ definePGBossConfiguration({
|
|
|
986
988
|
* console.log("Processing:", payload);
|
|
987
989
|
* });
|
|
988
990
|
*/
|
|
989
|
-
`}};T([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],
|
|
991
|
+
`}};T([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],qe,"queueType"),T([C.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],qe,"outputPath");var Ve=class extends k{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=sn__default.default.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",n=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
|
|
990
992
|
\u2728 Generated ${e==="sync"?"Sync":"Async"} Key Pair:
|
|
991
993
|
`),console.log(`\x1B[33mPublic Key (${s}):\x1B[0m`),console.log(`\x1B[32m${t}\x1B[0m`),console.log(`\x1B[33mPrivate Key (${n}):\x1B[0m`),console.log(`\x1B[32m${r}\x1B[0m`),await this.saveKeyToEnvFile(s,t),await this.saveKeyToEnvFile(n,r),console.log(`\x1B[90m\u{1F4A1} Keys saved to .env file as ${s} and ${n}\x1B[0m
|
|
992
|
-
`);}static async saveKeyToEnvFile(e,t){let r=
|
|
994
|
+
`);}static async saveKeyToEnvFile(e,t){let r=vt__default.default.join(L.getCwd(),".env"),s=`${e}="${t}"`;if(at__default.default.existsSync(r)){let n=at__default.default.readFileSync(r,"utf-8"),i=new RegExp(`^${e}=.*$`,"m");if(i.test(n)){let a=n.replace(i,s);at__default.default.writeFileSync(r,a),this.logger.info(`Updated ${e} in .env file`);return}at__default.default.appendFileSync(r,`
|
|
993
995
|
${s}
|
|
994
|
-
`),this.logger.info(`Added ${e} to .env file`);return}
|
|
995
|
-
`),this.logger.info(`Created .env file with ${e}`);}};T([C.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],
|
|
996
|
+
`),this.logger.info(`Added ${e} to .env file`);return}at__default.default.writeFileSync(r,`${s}
|
|
997
|
+
`),this.logger.info(`Created .env file with ${e}`);}};T([C.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],Ve,"type");var ct=class extends k{static commandName="list";static description="List all available commands";static help=["Display all registered Balda CLI commands with their descriptions","Example: npx balda list"];static async handle(){let e=Pe.getBuiltInCommands(),t=Pe.getUserDefinedCommands();if(console.log(`
|
|
996
998
|
\u2728 Available Balda Commands:
|
|
997
999
|
`),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
|
|
998
1000
|
`);let r=this.groupByCategory(t);this.displayCategorizedCommands(r);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
|
|
999
|
-
`);let r=e.sort((n,i)=>n.commandName.localeCompare(i.commandName)),s=Math.max(...r.map(n=>n.commandName.length));for(let n of r){let i=n.commandName.padEnd(s+2),a=n.description||"No description available",
|
|
1000
|
-
`);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(
|
|
1001
|
-
`);return}this.outputPath||await v.mkdir(
|
|
1001
|
+
`);let r=e.sort((n,i)=>n.commandName.localeCompare(i.commandName)),s=Math.max(...r.map(n=>n.commandName.length));for(let n of r){let i=n.commandName.padEnd(s+2),a=n.description||"No description available",c="";n.options?.deprecated&&(c=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${i}\x1B[0m ${a}${c}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
1002
|
+
`);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(c=>c&&c.commandName).sort((c,p)=>c.commandName.localeCompare(p.commandName));if(s.length===0)continue;let i={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${i}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(c=>c.commandName.length));for(let c of s){let p=c.commandName.padEnd(a+2),l=c.description||"No description available",d="";c.options?.deprecated&&(d=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${p}\x1B[0m ${l}${d}`);}console.log("");}}};var Ae=class extends k{static commandName="queue-start";static description="Start queue workers to process jobs";static help=["Start queue workers to process jobs from registered queues","Loads queue handlers from specified patterns and starts processing","Example: npx balda queue-start","Example: npx balda queue-start src/queues/**/*.ts --patterns src/jobs/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting queue workers...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading queue handlers from patterns: ${e.join(", ")}`),await K.massiveImportQueues(e,{throwOnError:false});let t=K.typedQueueSubscribers.size,r=K.customQueueSubscribers.size,s=t+r;if(s===0){this.logger.warn("No queue handlers found. Make sure your queue handlers are decorated with @queue decorator");return}this.logger.info(`Found ${s} queue handler(s) (${t} typed, ${r} custom)`),K.run().then(()=>{this.logger.info("Queue workers started successfully. Press Ctrl+C to stop.");}).catch(n=>{this.logger.error("Error starting queue workers",n);});}};T([N({required:false,defaultValue:"src/queues/**/*.{ts,js}",description:"Primary glob pattern for queue handlers (default: src/queues/**/*.{ts,js})"})],Ae,"pattern"),T([C.list({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for queue handlers"})],Ae,"additionalPatterns");J();var _e=class extends k{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=M.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){child_process.execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:L.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),child_process.execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:L.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!at__default.default.existsSync("node_modules/.bin/tsx")){let[r,s,n]=await V();if(!await Q(`${r} ${s} tsx ${n}`,r,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";child_process.execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};T([N({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],_e,"entry"),T([C.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],_e,"denoImportMap");var He=class extends k{static commandName="init-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
|
|
1003
|
+
`);return}this.outputPath||await v.mkdir(S.join(process.cwd(),this.outputPath),{recursive:true});let e=["s3","azure","local"];if(!e.includes(this.storageType)){console.error(`\x1B[31m\u274C Error: Invalid storage type '${this.storageType}'. Valid types: ${e.join(", ")}\x1B[0m
|
|
1002
1004
|
`);return}console.log(`
|
|
1003
1005
|
\u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
|
|
1004
1006
|
`);let t=this.getDependencies(this.storageType);if(t.length===0&&console.log(`\x1B[32m\u2705 ${this.storageType.toUpperCase()} storage doesn't require additional dependencies.\x1B[0m
|
|
1005
1007
|
`),t.length){let r=await this.checkMissingDependencies(t);if(r.length===0&&console.log(`\x1B[32m\u2705 All required dependencies are already installed.\x1B[0m
|
|
1006
|
-
`),r.length){let[s,n]=await
|
|
1008
|
+
`),r.length){let[s,n]=await V(),i=`${s} ${n} ${r.join(" ")}`;if(!await Q(i,s,r,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
|
|
1007
1009
|
`);return}console.log(`
|
|
1008
1010
|
\x1B[32m\u2705 Dependencies installed successfully!\x1B[0m
|
|
1009
1011
|
`);}}await this.createStorageSetup(this.storageType,this.outputPath),console.log(`\x1B[32m\u2728 ${this.storageType.toUpperCase()} storage setup complete!\x1B[0m
|
|
1010
|
-
`);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=
|
|
1012
|
+
`);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=S.join(process.cwd(),"package.json");if(!await v.exists(t))return e;let s=S.join(process.cwd(),"node_modules");if(!await v.exists(s))return e;let i=[];for(let a of e){let c=S.join(s,a);await v.exists(c)||i.push(a);}return i}static async createStorageSetup(e,t){let r=S.join(process.cwd(),t);await v.exists(r)||await v.mkdir(r,{recursive:true});let n=S.join(r,"storage.ts");if(await v.exists(n)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${n}\x1B[0m`);return}let a=this.getConfigTemplate(e);await v.writeFile(n,new TextEncoder().encode(a)),console.log(`\x1B[32m\u2705 Created configuration file: ${n}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { Storage, S3StorageProvider } from "balda";
|
|
1011
1013
|
|
|
1012
1014
|
/**
|
|
1013
1015
|
* S3 Storage Configuration
|
|
@@ -1087,16 +1089,16 @@ export const storage = new Storage(
|
|
|
1087
1089
|
defaultProvider: "local",
|
|
1088
1090
|
},
|
|
1089
1091
|
);
|
|
1090
|
-
`}[e]||""}};T([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],He,"storageType"),T([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],He,"outputPath");var Ko=[je,Ue,Oe,Ee,he,Ce,Me,z,ce,qe,ke,it,X,_e,He,ze,Ae,Pe],At=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=M.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),q.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(x.join(N.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),q.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){o.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{o.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(n=>n.default?n.default:n).catch(n=>(o.logger.error(`Error loading command ${r}: ${n}`),null));s&&this.commands.set(s.commandName,s);}for(let r of Ko)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Re=At.getInstance();function Xo(o){return o}function xr(o,e){let t={...Le,...e?.defaultTtl!==void 0&&{defaultTtl:e.defaultTtl},...e?.compressionThreshold!==void 0&&{compressionThreshold:e.compressionThreshold},...e?.keyPrefix!==void 0&&{keyPrefix:e.keyPrefix},...e?.enableStats!==void 0&&{enableStats:e.enableStats},...e?.lockTimeout!==void 0&&{lockTimeout:e.lockTimeout},...e?.lockBehavior!==void 0&&{lockBehavior:e.lockBehavior}};return dr(o,t),async(r,s,n)=>{await n();}}var at=class{store=new Map;sets=new Map;locks=new Map;async get(e){let t=this.store.get(e);return t?Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,r){this.store.set(e,{value:t,expiresAt:Date.now()+r*1e3});}async del(e){return this.store.delete(e)||this.sets.delete(e)}async delMany(e){let t=0;for(let r of e)(this.store.delete(r)||this.sets.delete(r))&&t++;return t}async addToSet(e,t,r){let s=this.sets.get(e);(!s||Date.now()>s.expiresAt)&&(s={members:new Set,expiresAt:r?Date.now()+r*1e3:Number.MAX_SAFE_INTEGER},this.sets.set(e,s));for(let n of t)s.members.add(n);r&&(s.expiresAt=Date.now()+r*1e3);}async getSetMembers(e){let t=this.sets.get(e);return t?Date.now()>t.expiresAt?(this.sets.delete(e),[]):Array.from(t.members):[]}async acquireLock(e,t){let r=this.locks.get(e);return r&&Date.now()<r?false:(this.locks.set(e,Date.now()+t),true)}async releaseLock(e){this.locks.delete(e);}async*scan(e){let t=Zo(e),r=[];for(let s of this.store.keys())if(t.test(s)){let n=this.store.get(s);Date.now()<=n.expiresAt&&(r.push(s),r.length>=100&&(yield [...r],r.length=0));}r.length>0&&(yield r);}async disconnect(){this.store.clear(),this.sets.clear(),this.locks.clear();}};function Zo(o){let e=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp("^"+e+"$")}var ct=class{redis=null;options;constructor(e={}){this.options=e;}async getClient(){if(this.redis)return this.redis;let e;try{let{default:t}=await import('ioredis');e=t;}catch{throw new Error("ioredis is required for RedisCacheProvider. Install it with: npm install ioredis")}return this.options.url?this.redis=new e(this.options.url):this.redis=new e({host:this.options.host??"localhost",port:this.options.port??6379,password:this.options.password,db:this.options.db??0,keyPrefix:this.options.keyPrefix}),this.redis}async get(e){return (await this.getClient()).get(e)}async set(e,t,r){await(await this.getClient()).set(e,t,"EX",r);}async del(e){return await(await this.getClient()).del(e)>0}async delMany(e){return e.length===0?0:(await this.getClient()).del(...e)}async addToSet(e,t,r){if(t.length===0)return;let n=(await this.getClient()).pipeline();n.sadd(e,...t),r&&n.expire(e,r),await n.exec();}async getSetMembers(e){return (await this.getClient()).smembers(e)}async acquireLock(e,t){return await(await this.getClient()).set(e,"1","PX",t,"NX")==="OK"}async releaseLock(e){await(await this.getClient()).del(e);}async*scan(e){let t=await this.getClient(),r=this.options.keyPrefix||"",s=r+e,n="0";do{let[i,a]=await t.scan(n,"MATCH",s,"COUNT",100);n=i,a.length>0&&(yield r?a.map(l=>l.startsWith(r)?l.slice(r.length):l):a);}while(n!=="0")}async disconnect(){this.redis&&(await this.redis.quit(),this.redis=null);}};V();var Ge=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 Yo=new Ge,I=o=>{let e=Yo.get("NODE_ENV")!=="production";return {code:o.name||"INTERNAL_ERROR",message:o.message,...e&&{stack:o.stack,cause:o.cause}}};var Je=class extends R{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var J=class extends R{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var ne=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 fe=(o,e,t,r)=>{let s=o.length;if(s===0){let a=e(t,r);return a&&typeof a.then=="function"?a.then(l=>(l&&r.send(l),r)):(a&&r.send(a),r)}let n=0,i=async()=>{if(n>=s){let p=await e(t,r);return p&&r.send(p),r}let a=n++,l=o[a];await l(t,r,i);};return i().then(()=>r)},en=new Set(["post","put","patch"]),le=o=>o?en.has(o.toLowerCase()):true,_t=async(o,e,t,r,s)=>{try{let{HeaderMap:n}=await import('@apollo/server'),i=new n;e.headers.forEach((m,f)=>{i.set(f,m);});let l=(e.headers.get("content-type")??"").includes("application/json"),p="";if(t!=="GET"){let m=await e.text();p=l&&m?JSON.parse(m):m;}let c={method:t.toUpperCase(),headers:i,body:p,search:r?`?${r}`:""},d=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:c,context:async()=>s}),u={};for(let[m,f]of d.headers)u[m]=f;if(d.body.kind==="complete")return new globalThis.Response(d.body.string,{status:d.status??200,headers:u});let h=new ReadableStream({async start(m){if(d.body.kind==="chunked")for await(let f of d.body.asyncIterator)m.enqueue(new TextEncoder().encode(f));m.close();}});return new globalThis.Response(h,{status:d.status??200,headers:u})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},Rs=async(o,e,t,r,s,n,i)=>{try{let{HeaderMap:a}=await import('@apollo/server'),l=new a;for(let[f,g]of Object.entries(e))g!==void 0&&l.set(f,Array.isArray(g)?g.join(", "):g);let d=(l.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,u={method:t?.toUpperCase()??"POST",headers:l,body:d,search:s?`?${s}`:""},h=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:u,context:async()=>n}),m=h.status??200;h.body.kind==="complete"?await i(h.headers,m,h.body.string):await i(h.headers,m,h.body.asyncIterator);}catch{await i(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},ge=o=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},s=async()=>{try{let{ApolloServer:n}=await import('@apollo/server'),{makeExecutableSchema:i}=await import('@graphql-tools/schema'),a=o.getSchemaOptions(),l=o.getApolloOptions(),p=i({typeDefs:a.typeDefs,resolvers:a.resolvers}),c=new n({schema:p,...l});return await c.start(),{server:c,url:"/graphql"}}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.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"):n}};return async()=>{if(!o.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(l){throw e=null,l}finally{t=false;}}};var ie=class o{static fromRequest(e){let t=Object.assign(new o,{url:e.url,method:e.method,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.#o=e.headers,t.#n=true,t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#r&&e){let t=stream.Readable.toWeb(this.#r);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.rawHeaders,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,duplex:"half"}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.rawHeaders,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 H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"zod_schema"}:D.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 j.storeJsonSchema(t,r),j.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return Et(s,t,r)}#t;#r;#e;#a=false;#o;#n=false;#d;#p=false;url="";method="GET";get rawHeaders(){if(this.#n)return this.#o;if(this.#e){let e=this.#e,t={};if(this.#a)for(let r in e){if(r.charCodeAt(0)===58)continue;let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}else for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}this.#o=new Headers(t);}else this.#o=new Headers;return this.#n=true,this.#o}get headers(){return this.#p?this.#d:{}}set headers(e){this.#d=e,this.#p=true;}signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file(e){return this.files.find(t=>t.formName===e)??null}#u;#c=false;get cookies(){if(!this.#c)throw new Error("Cookie middleware is required. Register the cookie plugin to access request cookies.");return this.#u}set cookies(e){this.#u=e,this.#c=true;}getOptionalCookies(){if(this.#c)return this.#u}cookie(e){return this.cookies[e]}timeout;#y;#v=false;get session(){if(!this.#v)throw new Error("Session middleware is required. Register the session plugin to access request session.");return this.#y}set session(e){this.#y=e,this.#v=true;}getOptionalSession(){if(this.#v)return this.#y}static _throwSaveSession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use saveSession.")};static _throwDestroySession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use destroySession.")};saveSession=o._throwSaveSession;destroySession=o._throwDestroySession;#h;#m=false;#l;get ip(){return this.#m?this.#h:(this.#m=true,this.#l&&(this.#h=this.#l(),this.#l=void 0),this.#h)}set ip(e){this.#h=e,this.#m=true,this.#l=void 0;}files=[];params={};#i;#s;#f=false;get query(){if(this.#f)return this.#i;if(!this.#s||this.#s==="")this.#i={};else if(this.#s.length<50&&!this.#s.includes("&")){let e=this.#s.indexOf("=");if(e===-1)this.#i={[this.#s]:""};else {let t=this.#s.slice(0,e),r=decodeURIComponent(this.#s.slice(e+1));this.#i={[t]:r};}}else this.#i=Object.fromEntries(new URLSearchParams(this.#s));return this.#f=true,this.#i}set query(e){this.#i=e,this.#f=true;}setQueryString(e){this.#s=e,this.#f=false,this.#i=void 0;}#g;get id(){return this.#g||(this.#g=re.randomUUID()),this.#g}set id(e){this.#g=e;}validate(e,t=false){return o.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return o.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return o.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}validateHeaders(e,t=false){let r=this.#p?this.#d:this.#b();return o.compileAndValidate(e,r,t)}#b(){let e={},t=new Map;this.rawHeaders.forEach((r,s)=>{let n=s.toLowerCase(),i=t.get(n);i?i.push(r):t.set(n,[r]);});for(let[r,s]of t)e[r]=s.length===1?s[0]:s;return e}setIpExtractor(e){this.#m=false,this.#l=()=>{let t=e.headers["x-forwarded-for"];return t?Array.isArray(t)?t[0].trim():t.split(",")[0].trim():e.socket.remoteAddress};}setBunIpExtractor(e,t){this.#m=false,this.#l=()=>{let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0].trim():t.requestIP(e)?.address};}setDenoIpExtractor(e,t){this.#m=false,this.#l=()=>{let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0].trim():t.remoteAddr?.hostname};}setRawHeaders(e,t){this.#e=e,this.#a=t,this.#n=false,this.#o=void 0;}setNodeRequest(e){this.#r=e;}};V();var Tr=class{file(e,t){switch(E.type){case "bun":case "node":return nt__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},Ht=new Tr;var Cs=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 Pr=(o,e)=>{let{source:t,path:r}=o,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),_.addOrUpdate("GET",`${s}/*`,[],async(n,i)=>sn(n,i,t),{},{service:"StaticFiles",...e},void 0,true),async(n,i,a)=>a()};async function sn(o,e,t){if(o.method!=="GET"&&o.method!=="HEAD")return e.status(405).json({...I(new Je(o.url,o.method))});let r=o.params["*"]||"",s=x.join(t,r),n=x.resolve(N.getCwd(),s),i=x.resolve(N.getCwd(),t);if(!n.startsWith(i))return e.notFound({...I(new J(o.url,o.method))});try{if(!(await v.stat(n)).isFile)return e.notFound({...I(new J(o.url,o.method))})}catch(p){if(p.code==="ENOENT")return e.notFound({...I(new J(o.url,o.method))});throw p}let a=Rr(x.extName(n));e.setHeader("Content-Type",a);let l=Ht.file(n);e.raw(l);}function Rr(o){return Cs.get(o)||"application/octet-stream"}var Q=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;#r;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#r=e,this.#e=j.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.#r?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:n}=this.getJsonSchemaWithPrefix(r);this.#t=j.getOrCreateSerializer(s,n)??void 0;}}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=Rr(r);this.body=Ht.file(e,t),this.headers["Content-Type"]=s;}ok(e){if(this.responseStatus=200,e!=null&&typeof e=="object"){this.json(e);return}this.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){M.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}getJsonSchemaWithPrefix(e){return H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"fast_stringify_zod"}:D.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)}`}}};var pe=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}cookies(){let e=this.response.headers["set-cookie"]||this.response.headers["Set-Cookie"];if(!e)return {};let t={},r=e.split(", ");for(let s of r){let[n]=s.split(";");if(n){let i=n.indexOf("=");if(i>0){let a=decodeURIComponent(n.slice(0,i).trim()),l=decodeURIComponent(n.slice(i+1).trim());t[a]=l;}}}return t}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}assertCookie(e,t){let r=this.cookies();if(r[e]!==t)throw new Error(`Expected cookie ${e} to be ${t}, but got ${r[e]??"undefined"}`);return this}assertCookieExists(e){let t=this.cookies();if(!(e in t))throw new Error(`Expected cookie ${e} to exist, but it was not found`);return this}assertCookieNotExists(e){let t=this.cookies();if(e in t)throw new Error(`Expected cookie ${e} to not exist, but it was found with value: ${t[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 n=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,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${s.length}`);for(let i of n){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 n=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} 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 n=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var lt=class{server;logger=M.child({scope:"MockServer"});ensureGraphQLHandler;bootstrapOptions;constructor(e,t){this.server=e,this.bootstrapOptions=t,this.ensureGraphQLHandler=ge(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:n={},cookies:i,ip:a}=r;this.validateOptions(r),await this.server.ensureBootstrapped(this.bootstrapOptions);let l=this.server.graphql.isEnabled,p=t.startsWith("/graphql");if(l&&p)return this.handleGraphQLRequest(e,t,r);let c=_.find(e.toUpperCase(),t);if(!c){let g=new Q(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new pe(g)}let d,u="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?d=JSON.stringify(r.body):d=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;u=`multipart/form-data; boundary=${g}`,d=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(u="application/x-www-form-urlencoded",d=new URLSearchParams(r.urlencoded).toString());let h=new URL(`http://${this.server.host}:${this.server.port}${t}`);h.search=new URLSearchParams(n).toString();let m=new globalThis.Request(h.toString(),{method:e.toUpperCase(),body:le(e)?d:void 0,headers:{"content-type":u,...s}}),f=ie.fromRequest(m);f.query={...Object.fromEntries(h.searchParams.entries()),...n},f.params=c.params,i!==void 0&&(f.cookies=i),f.ip=a;try{let g=await fe(c.middleware,c.handler,f,new Q);return new pe(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let y=new Q(500);return y.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new pe(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[l,p]of e.entries()){s.push(r.encode(`--${t}\r
|
|
1091
|
-
`));let
|
|
1092
|
-
`),s.push(r.encode(`${
|
|
1092
|
+
`}[e]||""}};T([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],He,"storageType"),T([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],He,"outputPath");var an=[je,Ge,Oe,Me,he,Ce,Ee,z,ce,ke,qe,ct,X,_e,He,Ve,Ae,Re],_t=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=E.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(S.join(L.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.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){o.logger.info(`Loading commands from ${e}`);let t=await v.glob(e,{cwd:L.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{o.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(n=>n.default?n.default:n).catch(n=>(o.logger.error(`Error loading command ${r}: ${n}`),null));s&&this.commands.set(s.commandName,s);}for(let r of an)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Pe=_t.getInstance();function cn(o){return o}function Tr(o,e){let t={...De,...e?.defaultTtl!==void 0&&{defaultTtl:e.defaultTtl},...e?.compressionThreshold!==void 0&&{compressionThreshold:e.compressionThreshold},...e?.keyPrefix!==void 0&&{keyPrefix:e.keyPrefix},...e?.enableStats!==void 0&&{enableStats:e.enableStats},...e?.lockTimeout!==void 0&&{lockTimeout:e.lockTimeout},...e?.lockBehavior!==void 0&&{lockBehavior:e.lockBehavior}};return dr(o,t),async(r,s,n)=>{await n();}}var lt=class{store=new Map;sets=new Map;locks=new Map;async get(e){let t=this.store.get(e);return t?Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,r){this.store.set(e,{value:t,expiresAt:Date.now()+r*1e3});}async del(e){return this.store.delete(e)||this.sets.delete(e)}async delMany(e){let t=0;for(let r of e)(this.store.delete(r)||this.sets.delete(r))&&t++;return t}async addToSet(e,t,r){let s=this.sets.get(e);(!s||Date.now()>s.expiresAt)&&(s={members:new Set,expiresAt:r?Date.now()+r*1e3:Number.MAX_SAFE_INTEGER},this.sets.set(e,s));for(let n of t)s.members.add(n);r&&(s.expiresAt=Date.now()+r*1e3);}async getSetMembers(e){let t=this.sets.get(e);return t?Date.now()>t.expiresAt?(this.sets.delete(e),[]):Array.from(t.members):[]}async acquireLock(e,t){let r=this.locks.get(e);return r&&Date.now()<r?false:(this.locks.set(e,Date.now()+t),true)}async releaseLock(e){this.locks.delete(e);}async*scan(e){let t=ln(e),r=[];for(let s of this.store.keys())if(t.test(s)){let n=this.store.get(s);Date.now()<=n.expiresAt&&(r.push(s),r.length>=100&&(yield [...r],r.length=0));}r.length>0&&(yield r);}async disconnect(){this.store.clear(),this.sets.clear(),this.locks.clear();}};function ln(o){let e=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp("^"+e+"$")}var dt=class{redis=null;options;constructor(e={}){this.options=e;}async getClient(){if(this.redis)return this.redis;let e;try{let{default:t}=await import('ioredis');e=t;}catch{throw new Error("ioredis is required for RedisCacheProvider. Install it with: npm install ioredis")}return this.options.url?this.redis=new e(this.options.url):this.redis=new e({host:this.options.host??"localhost",port:this.options.port??6379,password:this.options.password,db:this.options.db??0,keyPrefix:this.options.keyPrefix}),this.redis}async get(e){return (await this.getClient()).get(e)}async set(e,t,r){await(await this.getClient()).set(e,t,"EX",r);}async del(e){return await(await this.getClient()).del(e)>0}async delMany(e){return e.length===0?0:(await this.getClient()).del(...e)}async addToSet(e,t,r){if(t.length===0)return;let n=(await this.getClient()).pipeline();n.sadd(e,...t),r&&n.expire(e,r),await n.exec();}async getSetMembers(e){return (await this.getClient()).smembers(e)}async acquireLock(e,t){return await(await this.getClient()).set(e,"1","PX",t,"NX")==="OK"}async releaseLock(e){await(await this.getClient()).del(e);}async*scan(e){let t=await this.getClient(),r=this.options.keyPrefix||"",s=r+e,n="0";do{let[i,a]=await t.scan(n,"MATCH",s,"COUNT",100);n=i,a.length>0&&(yield r?a.map(c=>c.startsWith(r)?c.slice(r.length):c):a);}while(n!=="0")}async disconnect(){this.redis&&(await this.redis.quit(),this.redis=null);}};J();var Je=class{get(e){switch(M.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${M.type}`)}}getEnvironment(){switch(M.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var dn=new Je,$=o=>{let e=dn.get("NODE_ENV")==="development";return {code:o.name||"INTERNAL_ERROR",message:o.message,...e&&{stack:o.stack,cause:o.cause}}};var We=class extends R{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var U=class extends R{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var ne=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 fe=(o,e,t,r)=>{let s=o.length;if(s===0){let a=e(t,r);return a&&typeof a.then=="function"?a.then(c=>(c&&r.send(c),r)):(a&&r.send(a),r)}let n=0,i=async()=>{if(n>=s){let p=await e(t,r);return p&&r.send(p),r}let a=n++,c=o[a];await c(t,r,i);};return i().then(()=>r)},pn=new Set(["post","put","patch"]),le=o=>o?pn.has(o.toLowerCase()):true,Ht=async(o,e,t,r,s)=>{try{let{HeaderMap:n}=await import('@apollo/server'),i=new n;e.headers.forEach((h,f)=>{i.set(f,h);});let c=(e.headers.get("content-type")??"").includes("application/json"),p="";if(t!=="GET"){let h=await e.text();p=c&&h?JSON.parse(h):h;}let l={method:t.toUpperCase(),headers:i,body:p,search:r?`?${r}`:""},d=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:l,context:async()=>s}),u={};for(let[h,f]of d.headers)u[h]=f;if(d.body.kind==="complete")return new globalThis.Response(d.body.string,{status:d.status??200,headers:u});let m=new ReadableStream({async start(h){if(d.body.kind==="chunked")for await(let f of d.body.asyncIterator)h.enqueue(new TextEncoder().encode(f));h.close();}});return new globalThis.Response(m,{status:d.status??200,headers:u})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},Es=async(o,e,t,r,s,n,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 d=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,u={method:t?.toUpperCase()??"POST",headers:c,body:d,search:s?`?${s}`:""},m=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:u,context:async()=>n}),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"}]}));}},ge=o=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},s=async()=>{try{let{ApolloServer:n}=await import('@apollo/server'),{makeExecutableSchema:i}=await import('@graphql-tools/schema'),a=o.getSchemaOptions(),c=o.getApolloOptions(),p=i({typeDefs:a.typeDefs,resolvers:a.resolvers}),l=new n({schema:p,...c});return await l.start(),{server:l,url:"/graphql"}}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.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"):n}};return async()=>{if(!o.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 ie=class o{static fromRequest(e){let t=Object.assign(new o,{url:e.url,method:e.method,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.#o=e.headers,t.#n=true,t.#e=e,t}toWebApi(){if(this.#e)return this.#e;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#r&&e){let t=stream.Readable.toWeb(this.#r);return this.#e=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.rawHeaders,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,duplex:"half"}),this.#e}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.rawHeaders,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 H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"zod_schema"}:D.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 j.storeJsonSchema(t,r),j.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return Qe(s,t,r)}#e;#r;#t;#a=false;#o;#n=false;#d;#p=false;url="";method="GET";get rawHeaders(){if(this.#n)return this.#o;if(this.#t){let e=this.#t,t={};if(this.#a)for(let r in e){if(r.charCodeAt(0)===58)continue;let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}else for(let r in e){let s=e[r];s!==void 0&&(t[r]=Array.isArray(s)?s.join(", "):s);}this.#o=new Headers(t);}else this.#o=new Headers;return this.#n=true,this.#o}get headers(){return this.#p?this.#d:{}}set headers(e){this.#d=e,this.#p=true;}signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file(e){return this.files.find(t=>t.formName===e)??null}#u;#c=false;get cookies(){if(!this.#c)throw new Error("Cookie middleware is required. Register the cookie plugin to access request cookies.");return this.#u}set cookies(e){this.#u=e,this.#c=true;}#y;#v=false;get signedCookies(){if(!this.#v)throw new Error("Cookie middleware is required. Register the cookie plugin to access signed cookies.");return this.#y}set signedCookies(e){this.#y=e,this.#v=true;}getOptionalCookies(){if(this.#c)return this.#u}cookie(e){if(this.#v){let t=this.#y[e];if(t!==void 0)return t}return this.cookies[e]}timeout;#w;#b=false;_sessionDirty=false;_sessionId;_sessionTtl;_sessionStore;_sessionCookieName;_sessionCookieDefaults;get session(){if(!this.#b)throw new Error("Session middleware is required. Register the session plugin to access request session.");return this.#w}set session(e){this.#w=e,this.#b=true;}getOptionalSession(){if(this.#b)return this.#w}static _throwSaveSession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use saveSession.")};static _throwDestroySession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use destroySession.")};static _throwRegenerateSession=async()=>{throw new Error("Session middleware is required. Register the session plugin to use regenerateSession.")};saveSession=o._throwSaveSession;destroySession=o._throwDestroySession;regenerateSession=o._throwRegenerateSession;#h;#m=false;#l;get ip(){return this.#m?this.#h:(this.#m=true,this.#l&&(this.#h=this.#l(),this.#l=void 0),this.#h)}set ip(e){this.#h=e,this.#m=true,this.#l=void 0;}files=[];params={};#i;#s;#f=false;get query(){if(this.#f)return this.#i;if(!this.#s||this.#s==="")this.#i={};else if(this.#s.length<50&&!this.#s.includes("&")){let e=this.#s.indexOf("=");if(e===-1)this.#i={[this.#s]:""};else {let t=this.#s.slice(0,e),r=decodeURIComponent(this.#s.slice(e+1));this.#i={[t]:r};}}else this.#i=Object.fromEntries(new URLSearchParams(this.#s));return this.#f=true,this.#i}set query(e){this.#i=e,this.#f=true;}setQueryString(e){this.#s=e,this.#f=false,this.#i=void 0;}#g;get id(){return this.#g||(this.#g=ee.randomUUID()),this.#g}set id(e){this.#g=e;}validate(e,t=false){return o.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return o.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return o.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}validateHeaders(e,t=false){let r=this.#p?this.#d:this.#S();return o.compileAndValidate(e,r,t)}#S(){let e={},t=new Map;this.rawHeaders.forEach((r,s)=>{let n=s.toLowerCase(),i=t.get(n);i?i.push(r):t.set(n,[r]);});for(let[r,s]of t)e[r]=s.length===1?s[0]:s;return e}setIpExtractor(e){this.#m=false,this.#l=()=>e.socket.remoteAddress;}setBunIpExtractor(e,t){this.#m=false,this.#l=()=>t.requestIP(e)?.address;}setDenoIpExtractor(e,t){this.#m=false,this.#l=()=>t.remoteAddr?.hostname;}setRawHeaders(e,t){this.#t=e,this.#a=t,this.#n=false,this.#o=void 0;}setNodeRequest(e){this.#r=e;}};J();var Rr=class{file(e,t){switch(M.type){case "bun":case "node":return at__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},$t=new Rr;var Ms=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 Pr=(o,e)=>{let{source:t,path:r}=o,s=o.dotfiles??"ignore",n=o.followSymlinks??false,i=r;return i.startsWith("/")||(i="/"+i),i!=="/"&&i.endsWith("/")&&(i=i.slice(0,-1)),_.addOrUpdate("GET",`${i}/*`,[],async(a,c)=>hn(a,c,t,s,n),{},{service:"StaticFiles",...e},void 0,true),async(a,c,p)=>p()};async function hn(o,e,t,r,s){if(o.method!=="GET"&&o.method!=="HEAD")return e.status(405).json({...$(new We(o.url,o.method))});let n=o.params["*"]||"";if(n.includes("\0"))return e.notFound({...$(new U(o.url,o.method))});let i=S.join(t,n),a=S.resolve(L.getCwd(),i),c=S.resolve(L.getCwd(),t);if(a!==c&&!a.startsWith(c+"/")&&!a.startsWith(c+"\\"))return e.notFound({...$(new U(o.url,o.method))});if(S.basename(a).startsWith(".")){if(r==="deny")return e.status(403).json({message:"Forbidden"});if(r==="ignore")return e.notFound({...$(new U(o.url,o.method))})}try{let u=await v.lstat(a);if(u.isSymbolicLink&&!s)return e.notFound({...$(new U(o.url,o.method))});if(!u.isFile)return e.notFound({...$(new U(o.url,o.method))})}catch(u){if(u.code==="ENOENT")return e.notFound({...$(new U(o.url,o.method))});throw u}let l=Cr(S.extName(a));e.setHeader("Content-Type",l);let d=$t.file(a);e.raw(d);}function Cr(o){return Ms.get(o)||"application/octet-stream"}var F=class{static toWebResponse(e){let t=e.getBody(),r=e.headers["Content-Type"]?.toLowerCase(),s=new globalThis.Headers(e.headers);for(let n of e.cookieHeaders)s.append("Set-Cookie",n);return r==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:s}):globalThis.Response.json(t,{status:e.responseStatus,headers:s}):new globalThis.Response(t,{status:e.responseStatus,headers:s})}responseStatus;headers;cookieHeaders;body;#e;#r;#t;constructor(e=200){this.responseStatus=e,this.headers={},this.cookieHeaders=[];}setRouteResponseSchemas(e){this.#r=e,this.#t=j.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){if(/[\r\n]/.test(e)||/[\r\n]/.test(t))throw new Error(`Invalid header: CR/LF characters are not permitted in header names or values. key=${JSON.stringify(e)}`);return e.toLowerCase()==="set-cookie"?this.cookieHeaders.push(t):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;}setBodyDirect(e){this.body=e,this.#e=void 0;}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.#t){let s=this.#t.get(this.responseStatus);if(s){this.#e=s;return}}let r=t??this.#r?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:n}=this.getJsonSchemaWithPrefix(r);this.#e=j.getOrCreateSerializer(s,n)??void 0;}}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=S.extName(e),s=Cr(r);this.body=$t.file(e,t),this.headers["Content-Type"]=s;}ok(e){if(this.responseStatus=200,e!=null&&typeof e=="object"){this.json(e);return}this.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.#e&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#e(this.body),this.#e=void 0;}catch(e){E.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#e=void 0;}return this.body}getJsonSchemaWithPrefix(e){return H.isZodSchema(e)?{jsonSchema:H.toJSONSchema(e),prefix:"fast_stringify_zod"}:D.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)}`}}};var pe=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}cookies(){let e=this.response.cookieHeaders;if(!e||e.length===0)return {};let t={};for(let r of e){let[s]=r.split(";");if(s){let n=s.indexOf("=");if(n>0)try{let i=decodeURIComponent(s.slice(0,n).trim()),a=decodeURIComponent(s.slice(n+1).trim());t[i]=a;}catch{}}}return t}rawCookieHeaders(){return this.response.cookieHeaders??[]}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}assertCookie(e,t){let r=this.cookies();if(r[e]!==t)throw new Error(`Expected cookie ${e} to be ${t}, but got ${r[e]??"undefined"}`);return this}assertCookieExists(e){let t=this.cookies();if(!(e in t))throw new Error(`Expected cookie ${e} to exist, but it was not found`);return this}assertCookieNotExists(e){let t=this.cookies();if(e in t)throw new Error(`Expected cookie ${e} to not exist, but it was found with value: ${t[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 n=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,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${s.length}`);for(let i of n){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 n=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} 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 n=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var pt=class{server;logger=E.child({scope:"MockServer"});ensureGraphQLHandler;bootstrapOptions;constructor(e,t){this.server=e,this.bootstrapOptions=t,this.ensureGraphQLHandler=ge(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:n={},cookies:i,ip:a}=r;this.validateOptions(r),await this.server.ensureBootstrapped(this.bootstrapOptions);let c=this.server.graphql.isEnabled,p=t.startsWith("/graphql");if(c&&p)return this.handleGraphQLRequest(e,t,r);let l=_.find(e.toUpperCase(),t);if(!l){let g=new F(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new pe(g)}let d,u="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?d=JSON.stringify(r.body):d=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;u=`multipart/form-data; boundary=${g}`,d=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(u="application/x-www-form-urlencoded",d=new URLSearchParams(r.urlencoded).toString());let m=new URL(`http://${this.server.host}:${this.server.port}${t}`);m.search=new URLSearchParams(n).toString();let h=new globalThis.Request(m.toString(),{method:e.toUpperCase(),body:le(e)?d:void 0,headers:{"content-type":u,...s}}),f=ie.fromRequest(h);f.query={...Object.fromEntries(m.searchParams.entries()),...n},f.params=l.params,i!==void 0&&(f.cookies=i),f.ip=a;try{let g=await fe(l.middleware,l.handler,f,new F);return new pe(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let y=new F(500);return y.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new pe(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,p]of e.entries()){s.push(r.encode(`--${t}\r
|
|
1093
|
+
`));let l=`Content-Disposition: form-data; name="${c}"`,d="";if(p instanceof File&&(l+=`; filename="${p.name}"`,d=`Content-Type: ${p.type||"application/octet-stream"}\r
|
|
1094
|
+
`),s.push(r.encode(`${l}\r
|
|
1093
1095
|
${d}\r
|
|
1094
1096
|
`)),p instanceof File){let u=await p.arrayBuffer();s.push(new Uint8Array(u)),s.push(r.encode(`\r
|
|
1095
1097
|
`));}else s.push(r.encode(`${String(p)}\r
|
|
1096
1098
|
`));}s.push(r.encode(`--${t}--\r
|
|
1097
|
-
`));let n=s.reduce((
|
|
1098
|
-
`).find(
|
|
1099
|
-
`).find(Ks=>Ks.toLowerCase().startsWith("content-type:")),ee=F?F.split(":")[1].trim():"application/octet-stream";if(o?.allowedMimeTypes&&!o.allowedMimeTypes.includes(ee))return t.badRequest({...I(new R(`Invalid file type: "${ee}" is not allowed. Allowed types: ${o.allowedMimeTypes.join(", ")}`))});let Xt=nn(ee),Zt=x.join(await Os.tmpdir(),`${re.randomUUID()}${Xt}`);await v.writeFile(Zt,S.data),s.push(Zt),g.push({formName:k,mimeType:ee,size:S.data.length,tmpPath:Zt,originalName:B});}else y[k]=new TextDecoder().decode(S.data);}e.files=g,e.body=y,e.bodyUsed=!0,await r(),await js(s);}catch(n){throw await js(s),n}},js=async o=>{await Promise.allSettled(o.map(e=>v.unlink(e)));};var nn=o=>({"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"})[o.toLowerCase()]||".bin";var dt=class extends R{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var ks=100*1024,As=o=>async(e,t,r)=>{if(!an(e)||!le(e.method)||e.bodyUsed)return r();let s=be(o?.sizeLimit,ks)??ks,n=e.rawHeaders.get("content-length");if(n&&Number.parseInt(n)>s){let i={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...o?.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({...I(new dt("Invalid JSON syntax"))}):t.badRequest({...I(new dt("Invalid request body encoding"))})}await r();};function an(o){let e=cn(o);return e?ln(e)==="application/json":false}function cn(o){let e=o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function ln(o){let e=o.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var _s=1024*1024,Hs=o=>{let t={limit:be(o?.limit,_s)??_s,extended:o?.extended??false,charset:o?.charset??"utf8",allowEmpty:o?.allowEmpty??true,parameterLimit:o?.parameterLimit??1e3};return async(r,s,n)=>{if(!(r.rawHeaders.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();let a=r.rawHeaders.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 dn(r,t),await n();}catch(l){if(l instanceof Error&&l.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw l}}};async function dn(o,e){if(o.body||o.bodyUsed)return;let r=await o.toWebApi().arrayBuffer();if(r.byteLength>e.limit)throw new Error(`Body size ${r.byteLength} exceeds limit ${e.limit}`);let n=new TextDecoder(e.charset).decode(r),i=pn(n,e);o.body=i,o.bodyUsed=true;}function pn(o,e){let t={},r=new URLSearchParams(o);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?un(t,s,n):t[s]=n);return t}function un(o,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(o[e]=t);return}let n=o,i=e.split("[")[0];if(r.includes(i))return;for(let l=0;l<s.length-1;l++){let p=s[l].slice(1,-1);if(r.includes(p))return;if(n[i]||(n[i]={}),p===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][p]||(n[i][p]={}),n=n[i][p];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(n)||(n=[]),n.push(t);return}n[a]=t;}}var mn=o=>(o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type"))?.split(";")[0]??null,Mr=(o={})=>{let e=o.json,t=o.urlencoded,r=o.fileParser;return async(s,n,i)=>{if(!le(s.method)||s.bodyUsed)return i();let a=mn(s);if(a==="application/json"&&e)return As(e)(s,n,i);if(a==="multipart/form-data"&&r)return qs(r)(s,n,i);if(a==="application/x-www-form-urlencoded"&&t)return Hs(t)(s,n,i);if(a?.includes("text/")){let l=new TextDecoder,p=s.toWebApi();s.body=l.decode(await p.arrayBuffer()),s.bodyUsed=true;}return !s.body&&!s.bodyUsed&&(s.body=await s.toWebApi().arrayBuffer(),s.bodyUsed=true),i()}};var fn=1024,gn=6,yn=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Er=o=>{let e=o?.threshold??fn,t=Math.max(0,Math.min(9,o?.level??gn)),r=o?.filter??yn;return async(s,n,i)=>{if(!(s.rawHeaders.get("accept-encoding")||"").includes("gzip"))return i();let p=n.send.bind(n),c=n.text.bind(n),d=(u,h)=>{if(!bn(u,h,e,r))return u;let m=$s(u);if(!m||m.length<e)return u;let f=zlib.gzipSync(m,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",f.length.toString()),f};n.send=function(u){let h=n.headers["Content-Type"],m=d(u,h);return p(m)},n.json=function(u,h){let m=null;if(h){let{jsonSchema:y,prefix:P}=vn(h);m=j.getOrCreateSerializer(y,P);}let f=m&&typeof u=="object"&&u!==null?m(u):typeof u=="string"?u:JSON.stringify(u),g=d(f,"application/json");return g!==f?(n.setHeader("Content-Type","application/json"),p(g)):p(f)},n.text=function(u){let h=d(u,"text/plain");return h!==u?(n.setHeader("Content-Type","text/plain"),p(h)):c(u)},await i();}},vn=o=>H.isZodSchema(o)?{jsonSchema:H.toJSONSchema(o),prefix:"fast_stringify_zod"}:D.isTypeBoxSchema(o)?{jsonSchema:o,prefix:"fast_stringify_typebox"}:typeof o=="object"&&o!==null?{jsonSchema:o,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof o},prefix:`fast_stringify_primitive_${JSON.stringify(o)}`},bn=(o,e,t,r)=>{if(!o||!e)return false;let s=$s(o);return !s||s.length<t?false:r.some(n=>n.test(e))},$s=o=>typeof o=="string"?Buffer.from(o,"utf-8"):Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o):typeof o=="object"?Buffer.from(JSON.stringify(o),"utf-8"):null;var jr=o=>{if(o?.sign&&!o.secret)throw new Error("Cookie signing requires a secret. Set `secret` when `sign` is enabled.");let e={secret:o?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...o?.defaults},parse:o?.parse??true,sign:o?.sign??false};return async(t,r,s)=>{if(e.parse){let n=Sn(t.rawHeaders.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(n)){if(e.sign&&e.secret){let l=Pn(a,e.secret);l!==false&&(t.cookies[i]=l);continue}t.cookies[i]=a;}}r.cookie=(n,i,a)=>{Ns(r,n,i,{...e.defaults,...a},e);},r.clearCookie=(n,i)=>{xn(r,n,{...e.defaults,...i});},await s();}};function Sn(o){let e={};if(!o)return e;let t=o.split(";");for(let r of t){let s=r.trim(),n=s.indexOf("=");if(n>0){let i=s.slice(0,n),a=s.slice(n+1);e[decodeURIComponent(i)]=decodeURIComponent(a);}}return e}function Ns(o,e,t,r,s){let n=s.sign&&s.secret?Tn(t,s.secret):t,i=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;r.domain&&(i+=`; Domain=${r.domain}`),r.path&&(i+=`; Path=${r.path}`),r.expires&&(i+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(i+=`; Max-Age=${r.maxAge}`),r.secure&&(i+="; Secure"),r.httpOnly&&(i+="; HttpOnly"),r.sameSite&&(i+=`; SameSite=${r.sameSite}`),r.priority&&(i+=`; Priority=${r.priority}`);let a=o.headers["Set-Cookie"]||"",l=a?`${a}, ${i}`:i;o.setHeader("Set-Cookie",l);}function xn(o,e,t){let r={...t,expires:new Date(0),maxAge:0};Ns(o,e,"",r,{secret:"",sign:false});}function Tn(o,e){let t=Jo.createHmac("sha256",e).update(o).digest("hex");return `${o}.${t}`}function Pn(o,e){let t=o.lastIndexOf(".");if(t<=0||t===o.length-1)return false;let r=o.slice(0,t),s=o.slice(t+1),n=Jo.createHmac("sha256",e).update(r).digest("hex");if(s.length!==n.length)return false;let i=Buffer.from(s,"hex"),a=Buffer.from(n,"hex");return i.length!==a.length||!Jo.timingSafeEqual(i,a)?false:r}var kr=o=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...o};return async(t,r,s)=>{let n=t.rawHeaders.get("origin")||"";if(t.method==="OPTIONS")return Rn(t,r,e,n,s);Cn(t,r,e,n),await s();}};function Rn(o,e,t,r,s){let n=Is(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(Ls(e,t,n,o.rawHeaders.get("access-control-request-headers")||void 0),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Cn(o,e,t,r){let s=Is(t,r);s&&Ls(e,t,s);}function Is(o,e){if(typeof o.origin=="string")return o.origin;if(Array.isArray(o.origin)){let t=o.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return t?typeof t=="string"?t:e:false}return "*"}function Ls(o,e,t,r){o.setHeader("Access-Control-Allow-Origin",t),e.credentials&&o.setHeader("Access-Control-Allow-Credentials","true");let s=qr(e.exposedHeaders);s&&o.setHeader("Access-Control-Expose-Headers",s);let n=e.allowedHeaders===void 0?r:qr(e.allowedHeaders);n&&o.setHeader("Access-Control-Allow-Headers",n);let i=qr(e.methods);o.setHeader("Access-Control-Allow-Methods",String(i||"")),typeof e.maxAge=="number"&&o.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function qr(o){if(o!==void 0)return Array.isArray(o)?o.join(","):o}function Fs(o,e=""){let t=new URL(o.url),r=Object.fromEntries(o.rawHeaders.entries()),n=o.rawHeaders.get("x-forwarded-proto")||t.protocol.replace(":","");return {body:o.body,query:o.query,params:o.params,cookies:o.cookies,session:o.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:o.method,ip:o.ip,headers:r,url:t.pathname,get(a){return o.rawHeaders.get(a.toLowerCase())??void 0},header(a){return o.rawHeaders.get(a.toLowerCase())??void 0},app:{},res:null,route:null,protocol:n,secure:n==="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=>o.params[a]??o.query[a],files:o.files,file:o.file,rawBody:o.body}}function Ds(o){return {locals:{},headersSent:false,statusCode:o.responseStatus,status(t){return o.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!o.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return o.html(t),this}return o.send(t),this},json(t){return this.headersSent=true,o.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return o.status(n).setHeader("Location",s),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return o.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,n]of Object.entries(t))o.setHeader(s,n);else r!==void 0&&o.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return o.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,o.send(t??""),this},write(t){return M.warn({method:"write"},"res.write() is not fully supported in Express compatibility layer - responses will be buffered"),true},get(t){return o.headers[t]},getHeader(t){return o.headers[t]},removeHeader(t){return delete o.headers[t],this},append(t,r){let s=o.headers[t],n=Array.isArray(r)?r.join(", "):r;return o.setHeader(t,s?`${s}, ${n}`:n),this},cookie(t,r,s){return o.cookie?.(t,r,s),this},clearCookie(t,r){return o.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?o.setHeader("Content-Disposition",`attachment; filename="${t}"`):o.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){o.file(t);},download(t,r,s,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),o.file(t);},links(t){let r=Object.entries(t).map(([s,n])=>`<${n}>; rel="${s}"`).join(", ");return o.setHeader("Link",r),this},location(t){return o.setHeader("Location",t),this},vary(t){return o.setHeader("Vary",t),this},app:{},req:null}}function $e(o,e=""){return async(t,r,s)=>{let n=Fs(t,e),i=Ds(r);n.res=i,i.req=n;let a=false,l=3e4;await Promise.race([new Promise((p,c)=>{let d=u=>{if(a=true,u){c(u);return}p();};try{let u=o(n,i,d);u instanceof Promise&&u.catch(c);}catch(u){c(u);}}),new Promise(p=>{setTimeout(()=>{!a&&!i.headersSent&&M.warn({basePath:e,timeout:l},"Express middleware did not call next() within timeout and did not send response"),p();},l);})]),i.headersSent||await s();}}function Qs(o,e=""){return async(t,r)=>{let s=Fs(t,e),n=Ds(r);s.res=n,n.req=s;let i=()=>{};try{await o(s,n,i);}catch(a){throw M.error({error:a,basePath:e},"Express handler threw an error"),a}}}function pt(o,e){let t=Ar(o),r=e.stack;if(!r){M.warn({basePath:o},"Express router has no stack - routes may not be registered");return}for(let s of r)Us(s,t);}function Us(o,e){if(o.route){let t=Ar(e+o.route.path),r=Object.keys(o.route.methods).filter(s=>o.route.methods[s]);for(let s of r){let n=o.route.stack.map(i=>i.handle);On(s.toUpperCase(),t,n,e);}return}if(o.handle&&typeof o.handle=="function"){let t=o.path||"",r=Ar(e+t),s=o.handle.stack;if(s&&Array.isArray(s)){for(let l of s)Us(l,r);return}let n=r==="/"?"/*":`${r}/*`,i=$e(o.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let l of a)_.addOrUpdate(l,n,[i],async()=>{},{},{excludeFromSwagger:true});}}function On(o,e,t,r){let s=t.slice(0,-1).map(a=>$e(a,r)),n=t[t.length-1],i=Qs(n,r);_.addOrUpdate(o,e,s,i,{},{excludeFromSwagger:true});}function Ar(o){let e=o.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function _r(o){return {use(e,t){if(typeof e=="string"){let n=e,i=t,a=i.stack;if(a&&Array.isArray(a)){pt(n,i);return}o.use($e(i,n));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){pt("/",r);return}o.use($e(r));}}}var Hr=o=>{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,...o};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,a=n.includeSubDomains!==void 0?n.includeSubDomains:true,l=n.preload!==void 0?n.preload:false,p=`max-age=${i}`;a!==false&&(p+="; includeSubDomains"),l&&(p+="; preload"),r.setHeader("Strict-Transport-Security",p);}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 $r=o=>{let e=M.child({scope:"LogMiddleware"});return async(t,r,s)=>{try{let n=t.body;(o?.logRequest??!0)&&e.info({type:"request",requestId:t.id,method:o?.requestPayload?.method??!0?t.method:void 0,url:o?.requestPayload?.url??!0?t.url:void 0,ip:o?.requestPayload?.ip??!0?t.ip:void 0,headers:o?.requestPayload?.headers??!0?t.headers:void 0,body:o?.requestPayload?.body??!1?zs(n):void 0});let i=performance.now();await s();let l=performance.now()-i;(o?.logResponse??!0)&&e.info({type:"response",requestId:t.id,status:o?.responsePayload?.status??!0?r.responseStatus:void 0,duration:`${l.toFixed(2)}ms`,body:o?.responsePayload?.body??!1?zs(r.getBody()):void 0,headers:o?.responsePayload?.headers??!1?r.headers:void 0});}catch(n){throw e.error(n),n}}};function zs(o){if(typeof o=="string"||o&&typeof o=="object"&&o.constructor===Object)return o}var Mn=["POST"],En="X-HTTP-Method-Override",jn=["GET","POST","PUT","PATCH","DELETE"],Br=o=>{let e=(o?.methods??Mn).map(r=>r.toUpperCase()),t=o?.header??En;return async(r,s,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let a=r.rawHeaders.get(t);if(!a)return n();let l=a.toUpperCase();if(!jn.includes(l))return n();r.method=l,await n();}};var Bt=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 Nr=(o,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...o},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new Bt(r.windowMs):{get:r.get,set:r.set};return async(n,i,a)=>{let l=t.type==="ip"?n.ip:t.key(n),p=await s.get(l);return p>=t.limit?i.status(t.statusCode).json({message:t.message}):(await s.set(l,p+1),a())}};var Nt=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 Ir=o=>{let e=o?.name??"sid",t=o?.ttl??3600*24,r=o?.store??new Nt,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...o?.cookie??{}};return async(n,i,a)=>{let p=n.cookies&&n.cookies[e],c=p?await r.get(p):void 0;(!p||!c)&&(p||=re.randomUUID(),c||={},await r.set(p,c,t),i.cookie?.(e,p,s)),n.session=c,n.saveSession=async()=>r.set(p,c,t),n.destroySession=async()=>{await r.destroy(p),i.clearCookie?.(e,s);},await a(),await r.set(p,c,t);}};var qn={json:"application/json","form-data":"multipart/form-data",urlencoded:"application/x-www-form-urlencoded",binary:"application/octet-stream",text:"text/plain","event-stream":"text/event-stream"},kn={type:"object",properties:{message:{type:"string"},errors:{type:"array",items:{type:"object",properties:{instancePath:{type:"string"},schemaPath:{type:"string"},keyword:{type:"string"},params:{type:"object"},message:{type:"string"}}}},ajv:{type:"boolean"},validation:{type:"boolean"}}};function Gs(o){return o?qn[o]??o:"application/json"}var Vs=o=>{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:{}};o&&typeof o!="boolean"&&(e={...e,...o});let t=An(e),r=`${e.path}`,s=`${r}/json`,n;e.type==="rapidoc"?n=Hn(s,e):e.type==="scalar"?n=$n(s,e):e.type==="elements"?n=Bn(s,e):e.type==="custom"?n=e.customUIGenerator(s,e):n=_n(s,e),_.addOrUpdate("GET",r,[],(i,a)=>{a.html(n);},void 0,void 0,void 0,true),_.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);},void 0,void 0,void 0,true);},ve=o=>o?o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):"";function ye(o){if(!o||typeof o!="object")return {type:"string"};let e="json_schema";H.isZodSchema(o)?e="zod_schema":D.isTypeBoxSchema(o)&&(e="typebox_schema");let t=j.getJsonSchema(o,e);if(t)return t;if(H.isZodSchema(o))try{let s=H.toJSONSchema(o);return j.storeJsonSchema(s,e),s}catch(s){return M.debug({error:s instanceof Error?s.message:String(s),schemaType:o?.constructor?.name||typeof o},"Failed to convert Zod schema to JSON Schema for Swagger documentation"),{type:"object"}}let r=o;return j.storeJsonSchema(r,e),r}function An(o){let e=_.getRoutes(),t={},r;if(o.models)if(Array.isArray(o.models))r=o.models.reduce((n,i,a)=>{let l=ye(i),p=l.$id||l.title||`Model${a}`;return n[p]=l,n},{});else {r={};for(let[n,i]of Object.entries(o.models))r[n]=ye(i);}let s={...o.components,securitySchemes:o.securitySchemes||{},schemas:r?{...o.components?.schemas||{},...r}:o.components?.schemas?{...o.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let a=n.method.toLowerCase(),l={summary:i?.name||`${a.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},p=[],c=n.validationSchemas?.query;if(c){let f=c;if(f.type==="object"&&f.shape)for(let[g,y]of Object.entries(f.shape))!y||typeof y!="object"||p.push({name:g,in:"query",required:Array.isArray(f.shape[g].required)?f.shape[g].required.includes(g):false,schema:ye(y)});}i&&i.params?p=p.concat(Js(n.path,i.params)):p=p.concat(Js(n.path));let d=n.validationSchemas?.headers;if(d){let f=d;if(f.type==="object"&&f.shape)for(let[g,y]of Object.entries(f.shape))!y||typeof y!="object"||p.push({name:g,in:"header",required:Array.isArray(f.shape[g].required)?f.shape[g].required.includes(g):false,schema:ye(y)});}p.length>0&&(l.parameters=p);let u=n.validationSchemas?.body||n.validationSchemas?.all;if(u){let f=Gs(i?.bodyType);l.requestBody={content:{[f]:{schema:ye(u)}},required:true};}else if(i?.bodyType){let f=Gs(i.bodyType);l.requestBody={content:{[f]:{schema:{type:"object"}}},required:true};}l.responses={};let h=n.responses;if(h)for(let[f,g]of Object.entries(h))l.responses[f]={description:`Response for ${f}`,content:{"application/json":{schema:ye(g)}}};if(Object.keys(l.responses).length===0&&(l.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n.validationSchemas?.body||n.validationSchemas?.query||n.validationSchemas?.all){let f=Ie(),g={statusCode:i?.validationErrorResponse?.statusCode??o.validationErrorResponse?.statusCode??f?.status??422,description:i?.validationErrorResponse?.description??o.validationErrorResponse?.description??"Validation error",schema:i?.validationErrorResponse?.schema??o.validationErrorResponse?.schema??(f?.schema?ye(f.schema):kn)},y=String(g.statusCode);l.responses[y]||(l.responses[y]={description:g.description,content:{"application/json":{schema:g.schema}}});}if(i?.security){let f=[];Array.isArray(i.security)||(i.security=[i.security]);for(let g of i.security)if(g.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:g.bearerFormat||"JWT",description:g.description}),f.push({bearer:[]});else if(g.type==="apiKey")s.securitySchemes[g.name]||(s.securitySchemes[g.name]={type:"apiKey",name:g.name,in:g.in,description:g.description}),f.push({[g.name]:[]});else if(g.type==="oauth2"){let y=g.name||"oauth2";s.securitySchemes[y]||(s.securitySchemes[y]={type:"oauth2",flows:g.flows,description:g.description}),f.push({[y]:[]});}else if(g.type==="openIdConnect"){let y=g.name||"openIdConnect";s.securitySchemes[y]||(s.securitySchemes[y]={type:"openIdConnect",openIdConnectUrl:g.openIdConnectUrl,description:g.description}),f.push({[y]:[]});}f.length&&(l.security=f);}else o.security&&(l.security=o.security);t[n.path][a]=l;}return {openapi:"3.0.0",info:{title:o.title,description:o.description,version:o.version,...o.info},servers:o.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:s,security:o.security||[],tags:o.tags?Object.entries(o.tags).map(([n,i])=>({name:n,...i})):[]}}function _n(o,e){return `
|
|
1099
|
+
`));let n=s.reduce((c,p)=>c+p.byteLength,0),i=new Uint8Array(n),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 m=new F(500);return m.json({errors:[{message:"GraphQL handler not initialized"}]}),new pe(m)}let{headers:n={},query:i={},cookies:a,ip:c}=r,p=new URL(`http://${this.server.host}:${this.server.port}${t}`);p.search=new URLSearchParams(i).toString();let l;r.body!==void 0&&le(e)&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?l=JSON.stringify(r.body):l=r.body);let d=new globalThis.Request(p.toString(),{method:e.toUpperCase(),body:l,headers:{"content-type":"application/json",...n}}),u=ie.fromRequest(d);u.query={...Object.fromEntries(p.searchParams.entries()),...i},a!==void 0&&(u.cookies=a),u.ip=c;try{let{HeaderMap:m}=await import('@apollo/server'),h=new m;for(let[I,G]of Object.entries(n))G!==void 0&&h.set(I,Array.isArray(G)?G.join(", "):String(G));let g=(h.get("content-type")??"").includes("application/json"),y="";typeof l=="string"?y=l:l instanceof Uint8Array?y=new TextDecoder().decode(l):l&&typeof l=="object"&&(y=new TextDecoder().decode(new Uint8Array(l)));let P=g&&y?JSON.parse(y):y,x={method:e.toUpperCase(),headers:h,body:P,search:p.search},w=this.server.graphql.getApolloOptions(),b=w.context&&typeof w.context=="function"?await w.context({req:u}):{req:u},q=await s.server.executeHTTPGraphQLRequest({httpGraphQLRequest:x,context:async()=>b}),A=q.status??200,B=new F(A);for(let[I,G]of q.headers)B.setHeader(I,G);if(q.body.kind==="complete"){let I=q.body.string;try{B.json(JSON.parse(I));}catch{B.text(I);}}else {let I="";for await(let G of q.body.asyncIterator)I+=G;try{B.json(JSON.parse(I));}catch{B.text(I);}}return new pe(B)}catch(m){this.logger.error({error:m},`Error processing GraphQL request ${e} ${t}:`);let h=new F(500);return h.json({errors:[{message:"Internal server error"}]}),new pe(h)}}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 Ke=new async_hooks.AsyncLocalStorage,Or=o=>async(e,t,r)=>{let s={};for(let[n,i]of Object.entries(o))s[n]=await i(e);return e.ctx=new Proxy({},{get(n,i){return Ke.getStore()?.[i]},set(n,i,a){let c=Ke.getStore();return c?(c[i]=a,true):false},ownKeys(){let n=Ke.getStore();return n?Object.keys(n):[]},has(n,i){let a=Ke.getStore();return a?i in a:false}}),Ke.run(s,async()=>{await r();})};var Bt=class extends R{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};J();var Er=class{async tmpdir(){switch(M.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},js=new Er;var ks=1024*1024,qs=10*1024*1024,_s=o=>async(e,t,r)=>{let s=[];try{let n=e.rawHeaders.get("content-type")??e.rawHeaders.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||e.body||e.bodyUsed)return r();let i=e.rawHeaders.get("content-length"),a=we(o?.maxFileSize,qs)??qs;if(i&&parseInt(i)>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let c=n.match(/boundary=(.*)(;|$)/i);if(!c)return r();let p=c[1].replace(/(^\s*"?|"?\s*$)/g,"");if(p.length>70)return t.badRequest({...$(new R("Multipart boundary exceeds 70-character RFC 2046 limit"))});let 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 d=new TextEncoder().encode(`--${p}`),u=new Uint8Array([13,10,13,10]),m=[],h=(x,w,b=0)=>{e:for(let q=b;q<=x.length-w.length;q++){for(let A=0;A<w.length;A++)if(x[q+A]!==w[A])continue e;return q}return -1},f=h(l,d);for(;f!==-1&&(f+=d.length,!(l[f]===45&&l[f+1]===45));){l[f]===13&&l[f+1]===10&&(f+=2);let x=h(l,u,f);if(x===-1)break;let w=l.subarray(f,x),b=new TextDecoder().decode(w),q=x+u.length,A=h(l,d,q);if(A===-1)break;let B=A-1;l[B]===10&&B--,l[B]===13&&B--;let I=l.subarray(q,B+1);m.push({headers:b,data:I}),f=A;}let g=[],y={},P=we(o?.maxFileSize,ks)??ks;for(let x of m){let w=x.headers.split(`\r
|
|
1100
|
+
`).find(te=>te.toLowerCase().startsWith("content-disposition:"));if(!w)continue;let b=w.match(/name="([^"]+)"/);if(!b)continue;let q=b[1],A=w.match(/filename="([^"]*)"/),B=A?A[1]:"";if(B&&/[/\\\0]|\.\./.test(B))return t.badRequest({...$(new R(`Unsafe filename: "${B}"`))});let I=gn(B);if(!!B){if(o?.maxFiles&&g.length>=o.maxFiles)return t.badRequest({...$(new R(`Too many files: Maximum ${o.maxFiles} files allowed`))});if(P&&x.data.length>P)return t.badRequest({...$(new Bt(I,x.data.length,P))});let te=x.headers.split(`\r
|
|
1101
|
+
`).find(oo=>oo.toLowerCase().startsWith("content-type:")),Ne=te?te.split(":")[1].trim():"application/octet-stream";if(o?.allowedMimeTypes&&!o.allowedMimeTypes.includes(Ne))return t.badRequest({...$(new R(`Invalid file type: "${Ne}" is not allowed. Allowed types: ${o.allowedMimeTypes.join(", ")}`))});let so=yn(Ne),Zt=S.join(await js.tmpdir(),`${ee.randomUUID()}${so}`);await v.writeFile(Zt,x.data),s.push(Zt),g.push({formName:q,mimeType:Ne,size:x.data.length,tmpPath:Zt,originalName:I});}else y[q]=new TextDecoder().decode(x.data);}e.files=g,e.body=y,e.bodyUsed=!0,await r(),await As(s);}catch(n){throw await As(s),n}},As=async o=>{await Promise.allSettled(o.map(e=>v.unlink(e)));},gn=o=>o.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim(),yn=o=>({"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"})[o.toLowerCase()]||".bin";var ut=class extends R{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var Hs=100*1024,vn=32,wn=1e4,$s=o=>{let e=o?.maxDepth??vn,t=o?.maxKeys??wn;return async(r,s,n)=>{if(!Sn(r)||!le(r.method)||r.bodyUsed)return n();let i=we(o?.sizeLimit,Hs)??Hs,a=r.rawHeaders.get("content-length");if(a&&Number.parseInt(a)>i){let c={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...o?.customErrorMessage};return s.status(c.status).json({error:c.message})}if(r.body||r.bodyUsed)return n();try{let c=r.toWebApi(),p=await bn(c,i);if(p===null){let d={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...o?.customErrorMessage};return s.status(d.status).json({error:d.message})}let l=JSON.parse(p);Mr(l,e,t,0,{count:0}),r.body=l,r.bodyUsed=!0;}catch(c){return c instanceof SyntaxError?s.badRequest({...$(new ut("Invalid JSON syntax"))}):c instanceof RangeError?s.status(413).json({error:c.message}):s.badRequest({...$(new ut("Invalid request body encoding"))})}await n();}};async function bn(o,e){let t=o.body?.getReader();if(!t)return "";let r=[],s=0;try{for(;;){let{done:a,value:c}=await t.read();if(a)break;if(s+=c.length,s>e)return t.cancel(),null;r.push(c);}}finally{t.releaseLock();}let n=new Uint8Array(s),i=0;for(let a of r)n.set(a,i),i+=a.length;return new TextDecoder().decode(n)}function Mr(o,e,t,r,s){if(r>e)throw new RangeError(`JSON depth limit (${e}) exceeded`);if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let n=Object.keys(o);if(s.count+=n.length,s.count>t)throw new RangeError(`JSON key count limit (${t}) exceeded`);for(let i of n)Mr(o[i],e,t,r+1,s);}else if(Array.isArray(o))for(let n of o)Mr(n,e,t,r+1,s);}function Sn(o){let e=xn(o);return e?Tn(e)==="application/json":false}function xn(o){let e=o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function Tn(o){let e=o.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var Bs=1024*1024,Ns=o=>{let t={limit:we(o?.limit,Bs)??Bs,extended:o?.extended??false,charset:o?.charset??"utf8",allowEmpty:o?.allowEmpty??true,parameterLimit:o?.parameterLimit??1e3};return async(r,s,n)=>{if(!(r.rawHeaders.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();let a=r.rawHeaders.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 Rn(r,t),await n();}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 Rn(o,e){if(o.body||o.bodyUsed)return;let r=await o.toWebApi().arrayBuffer();if(r.byteLength>e.limit)throw new Error(`Body size ${r.byteLength} exceeds limit ${e.limit}`);let n=new TextDecoder(e.charset).decode(r),i=Pn(n,e);o.body=i,o.bodyUsed=true;}function Pn(o,e){let t={},r=new URLSearchParams(o);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?Cn(t,s,n):t[s]=n);return t}function Cn(o,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(o[e]=t);return}let n=o,i=e.split("[")[0];if(r.includes(i))return;for(let c=0;c<s.length-1;c++){let p=s[c].slice(1,-1);if(r.includes(p))return;if(n[i]||(n[i]={}),p===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][p]||(n[i][p]={}),n=n[i][p];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(n)||(n=[]),n.push(t);return}n[a]=t;}}var On=o=>(o.rawHeaders.get("content-type")??o.rawHeaders.get("Content-Type"))?.split(";")[0]??null,jr=(o={})=>{let e=o.json,t=o.urlencoded,r=o.fileParser;return async(s,n,i)=>{if(!le(s.method)||s.bodyUsed)return i();let a=On(s);if(a==="application/json"&&e)return $s(e)(s,n,i);if(a==="multipart/form-data"&&r)return _s(r)(s,n,i);if(a==="application/x-www-form-urlencoded"&&t)return Ns(t)(s,n,i);if(a?.includes("text/")){let c=new TextDecoder,p=s.toWebApi();s.body=c.decode(await p.arrayBuffer()),s.bodyUsed=true;}return !s.body&&!s.bodyUsed&&(s.body=await s.toWebApi().arrayBuffer(),s.bodyUsed=true),i()}};var jn=util.promisify(zlib.gzip),kn=1024,qn=6,An=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],kr=o=>{let e=o?.threshold??kn,t=Math.max(0,Math.min(9,o?.level??qn)),r=o?.filter??An,s=o?.skipFor;return async(n,i,a)=>{i.setHeader("Vary","Accept-Encoding");let c=n.rawHeaders.get("accept-encoding")||"";if(!_n(c))return a();if(await a(),s?.(n,i))return;let p=i.getBody();if(p==null)return;let l=i.headers["Content-Type"];if(!l||!r.some(m=>m.test(l)))return;let d=Hn(p);if(!d||d.length<e)return;let u=await jn(d,{level:t});i.setHeader("Content-Encoding","gzip"),i.setHeader("Content-Length",u.length.toString()),i.setBodyDirect(u);}};function _n(o){for(let e of o.split(",")){let[t,...r]=e.trim().split(";");if(t.trim().toLowerCase()!=="gzip")continue;let s=r.find(n=>n.trim().startsWith("q="));if(s){let n=parseFloat(s.trim().slice(2));return !Number.isNaN(n)&&n>0}return true}return false}var Hn=o=>typeof o=="string"?Buffer.from(o,"utf-8"):Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o):typeof o=="object"?Buffer.from(JSON.stringify(o),"utf-8"):null;var Bn=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,Nn=/^[\x20-\x7E]*$/,In=/[;\r\n]/,Fs=new Set(["__proto__","prototype","constructor"]),Ln=8192,Dn=50,qr=o=>{let e=Fn(o?.secret);if(o?.sign&&e.length===0)throw new Error("Cookie signing requires a secret. Set `secret` when `sign` is enabled.");let t=o?.sign??false,r={path:"/",httpOnly:true,secure:true,sameSite:"Lax",...o?.defaults},s=o?.parse??true;return async(n,i,a)=>{if(n.cookies=Object.create(null),n.signedCookies=Object.create(null),s){let c=Un(n.rawHeaders.get("cookie")||"");for(let[p,l]of Object.entries(c)){if(t&&e.length>0){let d=Gn(l,e);d!==false&&(n.signedCookies[p]=d);continue}n.cookies[p]=l;}}i.cookie=(c,p,l)=>{let d={...r,...l},u=l?.signed!==void 0?l.signed:t;Ls(i,c,p,d,u,e);},i.clearCookie=(c,p)=>{let l={...r,...p,maxAge:0,expires:new Date(0)};Ls(i,c,"",l,false,[]);},await a();}};function Fn(o){return o?Array.isArray(o)?o.filter(Boolean):[o]:[]}function Qn(o){if(o.includes("__proto__")||o.includes("constructor")||o.includes("prototype"))return true;if(o.startsWith("{")||o.startsWith("["))try{let e=JSON.parse(o),t=(r,s=0)=>{if(s>3||typeof r!="object"||r===null)return !1;for(let n in r)if(Fs.has(n)||t(r[n],s+1))return !0;return !1};return t(e)}catch{return false}return false}function Un(o){let e=Object.create(null);if(!o)return e;let r=o.slice(0,Ln).split(";"),s=0;for(let n of r){if(s>=Dn)break;let i=n.trim(),a=i.indexOf("=");if(a<=0)continue;let c,p;try{c=decodeURIComponent(i.slice(0,a)),p=decodeURIComponent(i.slice(a+1));}catch{continue}Fs.has(c)||Qn(p)||(e[c]=p,s++);}return e}function Is(o,e){if(!Nn.test(e)||In.test(e))throw new Error(`Cookie ${o} contains invalid characters (CR, LF, or semicolons are not permitted): ${JSON.stringify(e)}`)}function Ls(o,e,t,r,s,n){if(!Bn.test(e))throw new Error(`Invalid cookie name ${JSON.stringify(e)}: must be a valid RFC 6265 token.`);if(r.sameSite==="None"&&!r.secure)throw new Error(`Cookie ${JSON.stringify(e)}: sameSite "None" requires secure: true.`);let i=s&&n.length>0?zn(t,n[0]):t,a=`${encodeURIComponent(e)}=${encodeURIComponent(i)}`;if(r.domain&&(Is("domain",r.domain),a+=`; Domain=${r.domain}`),r.path&&(Is("path",r.path),a+=`; Path=${r.path}`),r.expires!==void 0){if(Number.isNaN(r.expires.getTime()))throw new Error(`Cookie ${JSON.stringify(e)}: expires is an Invalid Date.`);a+=`; Expires=${r.expires.toUTCString()}`;}if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge)||r.maxAge<0)throw new Error(`Cookie ${JSON.stringify(e)}: maxAge must be a non-negative integer, got ${r.maxAge}.`);a+=`; Max-Age=${r.maxAge}`;}if(r.secure&&(a+="; Secure"),r.httpOnly&&(a+="; HttpOnly"),r.sameSite&&(a+=`; SameSite=${r.sameSite}`),r.priority){if(!["Low","Medium","High"].includes(r.priority))throw new Error(`Cookie ${JSON.stringify(e)}: priority must be "Low", "Medium", or "High".`);a+=`; Priority=${r.priority}`;}o.setHeader("Set-Cookie",a);}function zn(o,e){let t=sn.createHmac("sha256",e).update(o).digest("hex");return `${o}.${t}`}function Gn(o,e){let t=o.lastIndexOf(".");if(t<=0||t===o.length-1)return false;let r=o.slice(0,t),s=o.slice(t+1),n=Buffer.from(s,"hex");for(let i of e){let a=sn.createHmac("sha256",i).update(r).digest("hex"),c=Buffer.from(a,"hex");if(n.length===c.length&&sn.timingSafeEqual(n,c))return r}return false}var Vn=/^[A-Za-z0-9:/.\-]+$/,Jn=["Content-Type","Accept","Authorization"],Wn=[/\(\.[^+*\[]+\)\+/,/\([+.]\*[+.]*\)/,/^(a+)+$/];function Kn(o){let e=o.source;o.flags.includes("g")&&e.includes("(?:");for(let r of Wn)if(r.test(e))throw new Error(`CORS origin regex pattern is potentially vulnerable to ReDoS: ${e}. Avoid nested quantifiers and overlapping patterns. Use explicit character classes instead.`);e.length>200&&console.warn(`CORS origin regex pattern is very long (${e.length} chars), may impact performance: ${e.slice(0,50)}...`);}var _r=o=>{if(!o)throw new Error("cors() requires an options object with an explicit `origin`. Use cors({ origin: '*' }) for public APIs or specify allowed origins.");if(o.origin==="*"&&o.credentials===true)throw new Error("cors(): `origin: '*'` and `credentials: true` cannot be combined. This is forbidden by the Fetch spec and browsers will reject such responses. Use an explicit origin list when credentials are required.");let e=[];if(Array.isArray(o.origin))for(let r of o.origin)r instanceof RegExp&&(Kn(r),e.push(r));let t={origin:o.origin??"*",methods:o.methods??["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:o.allowedHeaders?Array.isArray(o.allowedHeaders)?o.allowedHeaders:[o.allowedHeaders]:Jn,exposedHeaders:o.exposedHeaders,credentials:o.credentials??false,maxAge:o.maxAge,preflightContinue:o.preflightContinue??false,optionsSuccessStatus:o.optionsSuccessStatus??204,allowNullOrigin:o.allowNullOrigin??false,precompiledRegex:e};return async(r,s,n)=>{let i=r.rawHeaders.get("origin")||"";if(!i){await n();return}if(r.method==="OPTIONS")return Xn(r,s,t,i,n);Zn(r,s,t,i),await n();}};function Xn(o,e,t,r,s){let n=Us(t,r);if(!n){e.forbidden("CORS origin not allowed");return}let i=o.rawHeaders.get("access-control-request-method");if(i&&!(Array.isArray(t.methods)?t.methods.map(c=>c.toUpperCase()):String(t.methods).split(",").map(c=>c.trim().toUpperCase())).includes(i.toUpperCase())){e.forbidden("CORS method not allowed");return}if(zs(e,t,n,true),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Zn(o,e,t,r){let s=Us(t,r);s&&zs(e,t,s,false);}function Us(o,e){return e==="null"&&!o.allowNullOrigin||!Vn.test(e)?false:typeof o.origin=="string"?o.origin==="*"?"*":e===o.origin?e:false:Array.isArray(o.origin)&&o.origin.find((r,s)=>{if(typeof r=="string")return r===e;if(r instanceof RegExp&&o.precompiledRegex?.[s])try{return o.precompiledRegex[s].test(e)}catch{return false}return false})?e:false}function zs(o,e,t,r){o.setHeader("Access-Control-Allow-Origin",t),t!=="*"&&Ar(o,"Origin"),e.credentials&&o.setHeader("Access-Control-Allow-Credentials","true");let s=Qs(e.exposedHeaders);s&&o.setHeader("Access-Control-Expose-Headers",s);let n=Qs(e.methods);o.setHeader("Access-Control-Allow-Methods",String(n||"")),r&&(o.setHeader("Access-Control-Allow-Headers",e.allowedHeaders.join(",")),Ar(o,"Access-Control-Request-Headers"),Ar(o,"Access-Control-Request-Method"),typeof e.maxAge=="number"&&o.setHeader("Access-Control-Max-Age",e.maxAge.toString()));}function Ar(o,e){let t=o.headers.Vary;t?t.split(",").map(r=>r.trim()).includes(e)||o.setHeader("Vary",`${t}, ${e}`):o.setHeader("Vary",e);}function Qs(o){if(o!==void 0)return Array.isArray(o)?o.join(","):o}function Gs(o,e=""){let t=new URL(o.url),r=Object.fromEntries(o.rawHeaders.entries()),n=o.rawHeaders.get("x-forwarded-proto")||t.protocol.replace(":","");return {body:o.body,query:o.query,params:o.params,cookies:o.cookies,session:o.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:o.method,ip:o.ip,headers:r,url:t.pathname,get(a){return o.rawHeaders.get(a.toLowerCase())??void 0},header(a){return o.rawHeaders.get(a.toLowerCase())??void 0},app:{},res:null,route:null,protocol:n,secure:n==="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=>o.params[a]??o.query[a],files:o.files,file:o.file,rawBody:o.body}}function Vs(o){return {locals:{},headersSent:false,statusCode:o.responseStatus,status(t){return o.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!o.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return o.html(t),this}return o.send(t),this},json(t){return this.headersSent=true,o.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return o.status(n).setHeader("Location",s),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return o.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,n]of Object.entries(t))o.setHeader(s,n);else r!==void 0&&o.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return o.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,o.send(t??""),this},write(t){return E.warn({method:"write"},"res.write() is not fully supported in Express compatibility layer - responses will be buffered"),true},get(t){return o.headers[t]},getHeader(t){return o.headers[t]},removeHeader(t){return delete o.headers[t],this},append(t,r){let s=o.headers[t],n=Array.isArray(r)?r.join(", "):r;return o.setHeader(t,s?`${s}, ${n}`:n),this},cookie(t,r,s){return o.cookie?.(t,r,s),this},clearCookie(t,r){return o.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?o.setHeader("Content-Disposition",`attachment; filename="${t}"`):o.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){o.file(t);},download(t,r,s,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),o.file(t);},links(t){let r=Object.entries(t).map(([s,n])=>`<${n}>; rel="${s}"`).join(", ");return o.setHeader("Link",r),this},location(t){return o.setHeader("Location",t),this},vary(t){return o.setHeader("Vary",t),this},app:{},req:null}}function $e(o,e=""){return async(t,r,s)=>{let n=Gs(t,e),i=Vs(r);n.res=i,i.req=n;let a=false,c=3e4;await Promise.race([new Promise((p,l)=>{let d=u=>{if(a=true,u){l(u);return}p();};try{let u=o(n,i,d);u instanceof Promise&&u.catch(l);}catch(u){l(u);}}),new Promise(p=>{setTimeout(()=>{!a&&!i.headersSent&&E.warn({basePath:e,timeout:c},"Express middleware did not call next() within timeout and did not send response"),p();},c);})]),i.headersSent||await s();}}function Js(o,e=""){return async(t,r)=>{let s=Gs(t,e),n=Vs(r);s.res=n,n.req=s;let i=()=>{};try{await o(s,n,i);}catch(a){throw E.error({error:a,basePath:e},"Express handler threw an error"),a}}}function mt(o,e){let t=Hr(o),r=e.stack;if(!r){E.warn({basePath:o},"Express router has no stack - routes may not be registered");return}for(let s of r)Ws(s,t);}function Ws(o,e){if(o.route){let t=Hr(e+o.route.path),r=Object.keys(o.route.methods).filter(s=>o.route.methods[s]);for(let s of r){let n=o.route.stack.map(i=>i.handle);Yn(s.toUpperCase(),t,n,e);}return}if(o.handle&&typeof o.handle=="function"){let t=o.path||"",r=Hr(e+t),s=o.handle.stack;if(s&&Array.isArray(s)){for(let c of s)Ws(c,r);return}let n=r==="/"?"/*":`${r}/*`,i=$e(o.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)_.addOrUpdate(c,n,[i],async()=>{},{},{excludeFromSwagger:true});}}function Yn(o,e,t,r){let s=t.slice(0,-1).map(a=>$e(a,r)),n=t[t.length-1],i=Js(n,r);_.addOrUpdate(o,e,s,i,{},{excludeFromSwagger:true});}function Hr(o){let e=o.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function $r(o){return {use(e,t){if(typeof e=="string"){let n=e,i=t,a=i.stack;if(a&&Array.isArray(a)){mt(n,i);return}o.use($e(i,n));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){mt("/",r);return}o.use($e(r));}}}var Br=o=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssLegacyHeader:false,xssFilter:void 0,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:"default-src 'self'",permissionsPolicy:"camera=(), microphone=(), geolocation=()",originAgentCluster:true,...o},t=e.xssLegacyHeader!==void 0?e.xssLegacyHeader:e.xssFilter??false;return async(r,s,n)=>{if(e.dnsPrefetchControl&&s.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let i="SAMEORIGIN";typeof e.frameguard=="object"&&(i=e.frameguard.action),s.setHeader("X-Frame-Options",i);}if(e.hsts){let i={};typeof e.hsts=="object"&&(i=e.hsts);let a=i.maxAge!==void 0?i.maxAge:15552e3,c=i.includeSubDomains!==void 0?i.includeSubDomains:true,p=i.preload!==void 0?i.preload:false,l=`max-age=${a}`;c!==false&&(l+="; includeSubDomains"),p&&(l+="; preload"),s.setHeader("Strict-Transport-Security",l);}e.contentTypeOptions&&s.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&s.setHeader("X-Download-Options","noopen"),t&&s.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&s.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&s.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&s.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&s.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&s.setHeader("Content-Security-Policy",e.contentSecurityPolicy),e.permissionsPolicy&&s.setHeader("Permissions-Policy",e.permissionsPolicy),e.originAgentCluster&&s.setHeader("Origin-Agent-Cluster","?1"),await n();}};var Nr=o=>{let e=E.child({scope:"LogMiddleware"});return async(t,r,s)=>{try{let n=t.body;(o?.logRequest??!0)&&e.info({type:"request",requestId:t.id,method:o?.requestPayload?.method??!0?t.method:void 0,url:o?.requestPayload?.url??!0?t.url:void 0,ip:o?.requestPayload?.ip??!0?t.ip:void 0,headers:o?.requestPayload?.headers??!0?t.headers:void 0,body:o?.requestPayload?.body??!1?Ks(n):void 0});let i=performance.now();await s();let c=performance.now()-i;(o?.logResponse??!0)&&e.info({type:"response",requestId:t.id,status:o?.responsePayload?.status??!0?r.responseStatus:void 0,duration:`${c.toFixed(2)}ms`,body:o?.responsePayload?.body??!1?Ks(r.getBody()):void 0,headers:o?.responsePayload?.headers??!1?r.headers:void 0});}catch(n){throw e.error(n),n}}};function Ks(o){if(typeof o=="string"||o&&typeof o=="object"&&o.constructor===Object)return o}var ei=["POST"],ti="X-HTTP-Method-Override",ri=["GET","POST","PUT","PATCH","DELETE"],si=["PUT","PATCH","DELETE"],Ir=o=>{let e=(o?.methods??ei).map(s=>s.toUpperCase()),t=o?.header??ti,r=o?.disableCsrfCheck??false;return async(s,n,i)=>{let a=s.method.toUpperCase();if(!e.includes(a))return i();let c=s.rawHeaders.get(t);if(!c)return i();let p=c.toUpperCase();if(!ri.includes(p))return i();if(!r&&si.includes(p)){let l=s.rawHeaders.get("host"),d=s.rawHeaders.get("origin"),u=s.rawHeaders.get("referer"),m=d||(u?oi(u):null);if(m&&l){let h=ni(m);if(h&&h!==l)return n.forbidden("Cross-site method override rejected")}}s.method=p,await i();}};function oi(o){try{return new URL(o).origin}catch{return null}}function ni(o){try{return new URL(o).host}catch{return null}}var Nt=class{storage=new Map;windowMs;maxKeys;constructor(e,t=1e5){this.windowMs=e,this.maxKeys=t;}async increment(e,t){let r=Date.now(),s=t||this.windowMs,n=this.storage.get(e);if(n&&n.resetAt>r)return n.count+=1,{count:n.count,resetAt:n.resetAt};if(!n&&this.storage.size>=this.maxKeys){let a=this.storage.keys().next().value;a!==void 0&&this.storage.delete(a);}else if(n)return n.count=1,n.resetAt=r+s,{count:1,resetAt:n.resetAt};let i={count:1,resetAt:r+s};return this.storage.set(e,i),{count:1,resetAt:i.resetAt}}};var Lr=(o,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...o},r={type:"memory",...e},s=r.type==="memory"?r.windowMs??6e4:6e4,n=t.failClosed??false,i=r.type==="memory"?new Nt(s,r.maxKeys):{increment:r.increment};return async(a,c,p)=>{let l=t.type==="ip"?a.ip:t.key(a);if(!l)return p();let d;try{d=(await i.increment(l,s)).count;}catch{return n?c.status(t.statusCode).json({message:t.message}):p()}return d>t.limit?c.status(t.statusCode).json({message:t.message}):p()}};var It=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 Dr=o=>{let e=o?.name??"sid",t=o?.ttl??3600*24,r=o?.store??new It,n={path:"/",httpOnly:true,secure:true,sameSite:"Lax",...!!o?.secret?{signed:true}:{},...o?.cookie??{}};return async(i,a,c)=>{let l=ii(i,e),d=l?await r.get(l):void 0;if(!l||!d){l=ee.randomUUID();let m={};await r.set(l,m,t),a.cookie?.(e,l,n),i.session={...m},i._sessionDirty=true,i._sessionId=l,i._sessionTtl=t,i._sessionStore=r,i._sessionCookieName=e,i._sessionCookieDefaults=n;}else i.session={...d},i._sessionDirty=false,i._sessionId=l,i._sessionTtl=t,i._sessionStore=r,i._sessionCookieName=e,i._sessionCookieDefaults=n;let u=false;i.saveSession=async()=>{if(!i._sessionId||!i._sessionStore)throw new Error("Cannot save session: no session ID or store available");if(!i.session)throw new Error("Cannot save session: session data is undefined");await i._sessionStore.set(i._sessionId,i.session,i._sessionTtl),i._sessionDirty=false;},i.destroySession=async()=>{if(!i._sessionId||!i._sessionStore)throw new Error("Cannot destroy session: no session ID or store available");u=true,await i._sessionStore.destroy(i._sessionId),a.clearCookie?.(i._sessionCookieName??"sid",i._sessionCookieDefaults),i._sessionDirty=false;},i.regenerateSession=async()=>{if(!i._sessionId||!i._sessionStore)throw new Error("Cannot regenerate session: no session ID or store available");if(!i.session)throw new Error("Cannot regenerate session: session data is undefined");await i._sessionStore.destroy(i._sessionId);let m=ee.randomUUID();await i._sessionStore.set(m,i.session,i._sessionTtl),a.cookie?.(i._sessionCookieName??"sid",m,i._sessionCookieDefaults),i._sessionId=m,i._sessionDirty=true;},await c(),!u&&i._sessionDirty&&i._sessionId&&i._sessionStore&&i.session&&await i._sessionStore.set(i._sessionId,i.session,i._sessionTtl);}};function ii(o,e){try{let t=o.signedCookies[e];if(t!==void 0)return t}catch{}try{return o.cookies[e]}catch{return}}var ai={json:"application/json","form-data":"multipart/form-data",urlencoded:"application/x-www-form-urlencoded",binary:"application/octet-stream",text:"text/plain","event-stream":"text/event-stream"},ci={type:"object",properties:{message:{type:"string"},errors:{type:"array",items:{type:"object",properties:{instancePath:{type:"string"},schemaPath:{type:"string"},keyword:{type:"string"},params:{type:"object"},message:{type:"string"}}}},ajv:{type:"boolean"},validation:{type:"boolean"}}};function Xs(o){return o?ai[o]??o:"application/json"}var Ys=o=>{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:{}};o&&typeof o!="boolean"&&(e={...e,...o});let t=li(e),r=`${e.path}`,s=`${r}/json`,n;e.type==="rapidoc"?n=pi(s,e):e.type==="scalar"?n=ui(s,e):e.type==="elements"?n=mi(s,e):e.type==="custom"?n=e.customUIGenerator(s,e):n=di(s,e),_.addOrUpdate("GET",r,[],(i,a)=>{a.html(n);},void 0,void 0,void 0,true),_.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);},void 0,void 0,void 0,true);},ve=o=>o?o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):"";function ye(o){if(!o||typeof o!="object")return {type:"string"};let e="json_schema";H.isZodSchema(o)?e="zod_schema":D.isTypeBoxSchema(o)&&(e="typebox_schema");let t=j.getJsonSchema(o,e);if(t)return t;if(H.isZodSchema(o))try{let s=H.toJSONSchema(o);return j.storeJsonSchema(s,e),s}catch(s){return E.debug({error:s instanceof Error?s.message:String(s),schemaType:o?.constructor?.name||typeof o},"Failed to convert Zod schema to JSON Schema for Swagger documentation"),{type:"object"}}let r=o;return j.storeJsonSchema(r,e),r}function li(o){let e=_.getRoutes(),t={},r;if(o.models)if(Array.isArray(o.models))r=o.models.reduce((n,i,a)=>{let c=ye(i),p=c.$id||c.title||`Model${a}`;return n[p]=c,n},{});else {r={};for(let[n,i]of Object.entries(o.models))r[n]=ye(i);}let s={...o.components,securitySchemes:o.securitySchemes||{},schemas:r?{...o.components?.schemas||{},...r}:o.components?.schemas?{...o.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let a=n.method.toLowerCase(),c={summary:i?.name||`${a.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},p=[],l=n.validationSchemas?.query;if(l){let f=l;if(f.type==="object"&&f.shape)for(let[g,y]of Object.entries(f.shape))!y||typeof y!="object"||p.push({name:g,in:"query",required:Array.isArray(f.shape[g].required)?f.shape[g].required.includes(g):false,schema:ye(y)});}i&&i.params?p=p.concat(Zs(n.path,i.params)):p=p.concat(Zs(n.path));let d=n.validationSchemas?.headers;if(d){let f=d;if(f.type==="object"&&f.shape)for(let[g,y]of Object.entries(f.shape))!y||typeof y!="object"||p.push({name:g,in:"header",required:Array.isArray(f.shape[g].required)?f.shape[g].required.includes(g):false,schema:ye(y)});}p.length>0&&(c.parameters=p);let u=n.validationSchemas?.body||n.validationSchemas?.all;if(u){let f=Xs(i?.bodyType);c.requestBody={content:{[f]:{schema:ye(u)}},required:true};}else if(i?.bodyType){let f=Xs(i.bodyType);c.requestBody={content:{[f]:{schema:{type:"object"}}},required:true};}c.responses={};let m=n.responses;if(m)for(let[f,g]of Object.entries(m))c.responses[f]={description:`Response for ${f}`,content:{"application/json":{schema:ye(g)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n.validationSchemas?.body||n.validationSchemas?.query||n.validationSchemas?.all){let f=Le(),g={statusCode:i?.validationErrorResponse?.statusCode??o.validationErrorResponse?.statusCode??f?.status??422,description:i?.validationErrorResponse?.description??o.validationErrorResponse?.description??"Validation error",schema:i?.validationErrorResponse?.schema??o.validationErrorResponse?.schema??(f?.schema?ye(f.schema):ci)},y=String(g.statusCode);c.responses[y]||(c.responses[y]={description:g.description,content:{"application/json":{schema:g.schema}}});}if(i?.security){let f=[];Array.isArray(i.security)||(i.security=[i.security]);for(let g of i.security)if(g.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:g.bearerFormat||"JWT",description:g.description}),f.push({bearer:[]});else if(g.type==="apiKey")s.securitySchemes[g.name]||(s.securitySchemes[g.name]={type:"apiKey",name:g.name,in:g.in,description:g.description}),f.push({[g.name]:[]});else if(g.type==="oauth2"){let y=g.name||"oauth2";s.securitySchemes[y]||(s.securitySchemes[y]={type:"oauth2",flows:g.flows,description:g.description}),f.push({[y]:[]});}else if(g.type==="openIdConnect"){let y=g.name||"openIdConnect";s.securitySchemes[y]||(s.securitySchemes[y]={type:"openIdConnect",openIdConnectUrl:g.openIdConnectUrl,description:g.description}),f.push({[y]:[]});}f.length&&(c.security=f);}else o.security&&(c.security=o.security);t[n.path][a]=c;}return {openapi:"3.0.0",info:{title:o.title,description:o.description,version:o.version,...o.info},servers:o.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:s,security:o.security||[],tags:o.tags?Object.entries(o.tags).map(([n,i])=>({name:n,...i})):[]}}function di(o,e){return `
|
|
1100
1102
|
<!DOCTYPE html>
|
|
1101
1103
|
<html lang="en">
|
|
1102
1104
|
<head>
|
|
@@ -1144,7 +1146,7 @@ ${d}\r
|
|
|
1144
1146
|
};
|
|
1145
1147
|
</script>
|
|
1146
1148
|
</body>
|
|
1147
|
-
</html>`}function
|
|
1149
|
+
</html>`}function pi(o,e){return `
|
|
1148
1150
|
<!DOCTYPE html>
|
|
1149
1151
|
<html>
|
|
1150
1152
|
<head>
|
|
@@ -1175,7 +1177,7 @@ ${d}\r
|
|
|
1175
1177
|
<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
|
|
1176
1178
|
</body>
|
|
1177
1179
|
</html>
|
|
1178
|
-
`}function
|
|
1180
|
+
`}function ui(o,e){return `
|
|
1179
1181
|
<!DOCTYPE html>
|
|
1180
1182
|
<html lang="en">
|
|
1181
1183
|
<head>
|
|
@@ -1199,7 +1201,7 @@ ${d}\r
|
|
|
1199
1201
|
<script src="https://unpkg.com/@scalar/api-reference@latest/dist/browser/standalone.js"></script>
|
|
1200
1202
|
</body>
|
|
1201
1203
|
</html>
|
|
1202
|
-
`}function
|
|
1204
|
+
`}function mi(o,e){return `
|
|
1203
1205
|
<!DOCTYPE html>
|
|
1204
1206
|
<html lang="en">
|
|
1205
1207
|
<head>
|
|
@@ -1226,6 +1228,6 @@ ${d}\r
|
|
|
1226
1228
|
<script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
|
|
1227
1229
|
</body>
|
|
1228
1230
|
</html>
|
|
1229
|
-
`}function Js(o,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(o))!==null;){let n=s[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=ye(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var Lr=o=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},o.ms);try{await r();}finally{clearTimeout(s);}};var Fr=o=>{let e=o?.header??"x-forwarded-for",t=o?.trust??true,r=o?.hop??"first";return async(s,n,i)=>{if(!t)return i();let a=s.rawHeaders.get(e);if(a&&typeof a=="string"){let l=a.split(",").map(p=>p.trim()).filter(Boolean);l.length&&(s.ip=r==="first"?l[0]:l[l.length-1]);}return i()}};var It=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.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ne,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},n=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,l)=>{let p=a.url,c=p.indexOf("://")+3,d=p.indexOf("/",c),u=d===-1?"/":p.slice(d),h=u.indexOf("?"),m=h===-1?u:u.slice(0,h),f=h===-1?"":u.slice(h+1),g=_.find(a.method,m),y=ie.fromRequest(a);if(y.params=g?.params??{},y.setQueryString(f),y.setBunIpExtractor(a,l),await t?.call(this,y,l),n&&m.startsWith(i)){let b=await this.ensureGraphQLHandler();if(b){let w=y.toWebApi();return _t(b.server,w,a.method,f,{req:y,server:l})}}if(r&&y.rawHeaders.get("upgrade")==="websocket"){let b=y.toWebApi();if(l.upgrade(b,{data:{}}))return}let P=new Q;return g?.responseSchemas&&P.setRouteResponseSchemas(g.responseSchemas),await fe(g?.middleware??[],g?.handler??((b,w)=>{w.notFound({...I(new J(b.url,b.method))});}),y,P),Q.toWebResponse(P)},...r?{websocket:r}:{},...s});}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Lt=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.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ne,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,n="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let l=i.url,p=l.indexOf("://")+3,c=l.indexOf("/",p),d=c===-1?"/":l.slice(c),u=d.indexOf("?"),h=u===-1?d:d.slice(0,u),m=u===-1?"":d.slice(u+1),f=_.find(i.method,h),g=ie.fromRequest(i);if(g.params=f?.params??{},g.setQueryString(m),g.setDenoIpExtractor(i,a),await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&h.startsWith(n)){let b=await this.ensureGraphQLHandler();if(b){let w=g.toWebApi();return _t(b.server,w,i.method,m,{req:g,info:a})}}if(g.rawHeaders.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let b=g.toWebApi(),{socket:w,response:k}=Deno.upgradeWebSocket(b);return this.tapOptions?.deno?.websocket?.open&&(w.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(w)),this.tapOptions?.deno?.websocket?.message&&(w.onmessage=A=>{this.tapOptions?.deno?.websocket?.message?.(w,A.data);}),this.tapOptions?.deno?.websocket?.close&&(w.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(w)),k}let P=new Q;return f?.responseSchemas&&P.setRouteResponseSchemas(f.responseSchemas),await fe(f?.middleware??[],f?.handler??((b,w)=>{w.notFound({...I(new J(b.url,b.method))});}),g,P),Q.toWebResponse(P)},...r});}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var Un=async(o,e)=>{let t=stream.Readable.fromWeb(o);return promises.pipeline(t,e)},Ft=class{port;host;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 ne,this.ensureGraphQLHandler=ge(this.graphql),this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure",this.createServerWithHandler();}get url(){return `${this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http"}://${this.host}:${this.port}`}createServerWithHandler(){let e=this.graphql.isEnabled,t="/graphql";this.runtimeServer=this.createServer(async(r,s)=>{if(this.tapOptions&&this.tapOptions.node){let h=this.tapOptions.node;await h?.(r);}let n=r.url,i=n.indexOf("?"),a=i===-1?n:n.slice(0,i),l=i===-1?"":n.slice(i+1);if(e&&a.startsWith(t)){let h=await this.ensureGraphQLHandler();if(h){let m=le(r.method)?await this.readRequestBody(r):"";await Rs(h.server,r.headers,r.method??"POST",m,l,{req:r},async(f,g,y)=>{for(let[P,S]of f)s.setHeader(P,S);if(s.statusCode=g,typeof y=="string")s.end(y);else {for await(let P of y)s.write(P);s.end();}});return}}let p=_.find(r.method,a),c=new ie;c.url=`${this.url}${n}`,c.method=r.method,le(r.method)&&c.setNodeRequest(r),c.setRawHeaders(r.headers,this.needsHeaderFiltering),c.setIpExtractor(r),c.setQueryString(l),c.params=p?.params??{};let d=new Q;d.nodeResponse=s,p?.responseSchemas&&d.setRouteResponseSchemas(p.responseSchemas);let u=fe(p?.middleware??[],p?.handler??((h,m)=>{m.notFound({...I(new J(h.url,h.method))});}),c,d);u instanceof Q?this.writeResponse(u,s):u.then(h=>this.writeResponse(h,s));});}listen(){this.runtimeServer.listen(this.port,this.host);}writeResponse(e,t){if(t.headersSent||t.writableEnded)return;let r=e.getBody();if(r instanceof ReadableStream){t.writeHead(e.responseStatus,e.headers),Un(r,t);return}t.writeHead(e.responseStatus,e.headers),r instanceof Buffer||r instanceof Uint8Array||typeof r=="string"?t.end(r):e.headers["Content-Type"]==="application/json"?t.end(typeof r=="string"?r:JSON.stringify(r)):t.end(r!=null?String(r):void 0);}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 n=e[s];n!==void 0&&(t[s]=Array.isArray(n)?n.join(", "):n);}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",n=>s.push(Buffer.from(n))),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 Dt=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}set port(e){this.server.port=e;}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 It(e);if(e?.runtime==="node")return new Ft(e);if(e?.runtime==="deno")return new Lt(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};V();var Qt=class{_brand="BaldaServer";#t=new Ge;serverOptions;router=_;logger;isListening;isProduction;graphql;#r;#e;#a=[];#o=["node_modules"];#n;#d;#p=[];#u=[];#c;inject;constructor(e){this.#r=false,this.logger=(e?.logger??M).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:(e?.port??Number(this.#t.get("PORT")||"80"))||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},e?.ajvInstance&&j.setGlobalInstance(e.ajvInstance),this.#d=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 ne(this.serverOptions.graphql),this.#e=new Dt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:E.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#d,graphql:this.graphql}),this.setupAbortSignalHandler(),this.inject=this.createInjectFunction();}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}set port(e){if(this.isListening)throw new Error("Cannot change port while server is listening, please call `.close()` before changing the port");this.#e.port=e;}get host(){return this.#e.host}get routes(){return _.getRoutes()||[]}get fs(){return v}getEnvironment(){return this.#t.getEnvironment()}tmpDir(...e){return x.join("tmp",...e)}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){Qe.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.#a.push(...e);}useExpress(e,t){_r(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){pt(e,t);}setErrorHandler(e){this.#a.unshift(async(t,r,s)=>{try{await s();}catch(n){await e?.(t,r,s,n);}});}setNotFoundHandler(e){this.#n=e?.bind(this);}setValidationErrorHandler(e){ns(e);}setPolicyErrorHandler(e){ms(e);}beforeStart(e){this.#p.push(e);}beforeClose(e){this.#u.push(e);}listen(e,t){let r=typeof e=="function"?e:t;if(typeof e=="number"&&Number.isFinite(e)&&(this.port=e),this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let s={port:this.port,host:this.host,url:this.url};this.bootstrap().then(async()=>{for(let n of this.#p)await n();this.#e.listen(),this.isListening=true,r?.({...s,error:void 0});}).catch(n=>{r?.({...s,error:n});});}async waitUntilListening(e){return e??=this.port,new Promise((t,r)=>{try{this.listen(e,()=>{t({port:this.port,host:this.host,url:this.url});});}catch(s){r(s);}})}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{for(let e of this.#u)await e();await this.#e.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}getMockServer(e){return new lt(this,e)}async ensureBootstrapped(e){await this.bootstrap(e);}createInjectFunction(){let e=()=>(this.#c||(this.#c=new lt(this)),this.#c),t=(r,s,n)=>e().request(r,s,n);return t.get=(r,s)=>e().get(r,s),t.post=(r,s)=>e().post(r,s),t.put=(r,s)=>e().put(r,s),t.patch=(r,s)=>e().patch(r,s),t.delete=(r,s)=>e().delete(r,s),t}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.#o.some(n=>s.includes(n))),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(n=>{this.logger.error(`Error importing controller ${s}: ${n}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}applyPlugins(e){if(Array.isArray(e)){this.use(...e);return}Object.entries(e).forEach(([t,r])=>{switch(t){case "bodyParser":this.use(Mr(r));break;case "cors":this.use(kr(r));break;case "static":this.use(Pr(r));break;case "helmet":this.use(Hr(r));break;case "cookie":this.use(jr(r));break;case "methodOverride":this.use(Br(r));break;case "compression":this.use(Er(r));break;case "log":this.use($r(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:n}=r;this.use(Nr(s,n));break;case "trustProxy":this.use(Fr(r));break;case "timeout":this.use(Lr(r));break;case "session":this.use(Ir(r));break;case "asyncLocalStorage":this.use(Cr(r));break;case "cache":{let i=r,a;i.provider&&typeof i.provider=="object"&&"get"in i.provider?a=i.provider:i.provider==="redis"?a=new ct(i.redis):a=new at,this.use(xr(a,i));break}default:this.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.#r||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.swagger&&Vs(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#a.length&&_.applyGlobalMiddlewaresToAllRoutes(this.#a),this.#r=true);}handleNotFound=(e,t)=>{if(this.#n){this.#n(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],n=[];for(let a of s){if(a===e.method.toUpperCase())continue;let l=_.find(a,r);l&&l.handler!==this.handleNotFound&&n.push(a);}if(n.length){t.setHeader("Allow",n.join(", "));let a=new Je(r,e.method);t.methodNotAllowed({...I(a)});return}let i=new J(r,e.method);t.notFound({...I(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)_.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true},void 0,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 Dr=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)),n=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"},n,this.KEY_LENGTH),a=this.encodeBase64(s),l=this.encodeBase64(new Uint8Array(i));return `${a}:${l}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,a]=n,l=this.decodeBase64(i),p=this.decodeBase64(a),c=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:l,iterations:this.ITERATIONS,hash:"SHA-256"},c,this.KEY_LENGTH),u=new Uint8Array(d);if(u.length!==p.length)return !1;let h=0;for(let m=0;m<u.length;m++)h|=u[m]^p[m];return h===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 n=0;n<r;n++)s[n]=t.charCodeAt(n);return s}},zn=new Dr;var Ws=()=>{let o=j.getCacheStats(),e=o.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:o.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:o.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Gn=()=>{let o=Ws();M.info({validators:o.validators.size,totalSchemaRefs:o.totalSchemaReferences,memoryEstimate:o.memoryEstimate.total},"Schema cache metrics");},Jn=()=>{j.clearAllCaches(),M.debug("All schema caches cleared");};var Z=class extends R{constructor(e){super(`File not found: ${e}`);}};var Qr=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),n=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:n},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),n=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:n},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 Z(e);let n=t;if(n==="stream")return stream.Readable.toWeb(s.readableStreamBody);let i=[];for await(let l of s.readableStreamBody)i.push(Buffer.isBuffer(l)?l:Buffer.from(l));let a=Buffer.concat(i);switch(n){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new R("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new Z(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),n=t;await s.upload(n,n.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 R("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 R("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Ur=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new R("`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 n=[];return await this.listFilesRecursively(r,t,n),n}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 Z(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 R("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=x.join(this.options.directory,e),n=x.join(s,"..");await v.mkdir(n,{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 n=await this.readDirectory(e);for(let i of n){let a=x.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(V(),Zr));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 R("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;}};V();var zr=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:n}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:n,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new R("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 Z(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 R("Invalid return type")}}catch(s){throw s instanceof Z?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new Z(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 Z(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 R("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new Z(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 R("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 R("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 R("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 Gr=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 Ut=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 R("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var zt=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 R("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Gt=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 R("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var Jt=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 R("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var Vt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,n)=>{let i=t[s];return i===void 0?r:n&&this.helpers.has(n)?this.helpers.get(n)(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 ut=class extends R{constructor(e){super(e),this.name="MailerError";}},mt=class extends ut{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},Wt=class extends ut{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Kt=class extends ut{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var ht=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,n=s.build();return s.hasTemplate()?this.sendWithTemplate(n):this.sendDirect(n)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new Wt;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 Jr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Kt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new ht(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new mt(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,n=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:n,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=br("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 n=s;n.isFilePath?r.templateFile(n.template,n.data):r.template(n.template,n.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 mt(String(this.defaultProvider));return e}};var Vr=class{};var Wr=o=>(e,t)=>(r,s,n)=>{let i={scope:e,handler:t,manager:o};if(typeof s>"u"){let l=O.get(r.prototype,"__class__");return l||(l={policies:[]}),l.policies||(l.policies=[]),l.policies.push(i),O.set(r.prototype,"__class__",l),r}let a=O.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),O.set(r,s,a),n};var Kr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Wr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new R(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Dg=_,Qg=Qt;
|
|
1230
|
-
Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return ajv.ValidationError}});exports.AzureBlobStorageProvider=
|
|
1231
|
+
`}function Zs(o,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(o))!==null;){let n=s[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=ye(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var Fr=o=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},o.ms);try{await r();}finally{clearTimeout(s);}};var Qr=o=>{if(!o||!o.trustedProxies||o.trustedProxies.length===0)throw new Error("trustProxy() requires `trustedProxies` \u2014 an explicit allowlist of trusted proxy IPs or CIDR ranges.");let e=o.trustedProxies,t=Math.max(1,o?.hops??1),r=o?.header??"x-forwarded-for";return async(s,n,i)=>{let a=s.ip;if(!a||!hi(a,e))return i();let c=s.rawHeaders.get(r);if(!c||typeof c!="string")return i();let p=c.split(",").map(u=>u.trim()).filter(Boolean);if(p.length===0)return i();let l=p.length-t,d=p[l>=0?l:0];return s.ip=d,i()}};function hi(o,e){for(let t of e)if(t.includes("/")){if(fi(o,t))return true}else if(o===t)return true;return false}function fi(o,e){let[t,r]=e.split("/");if(!t||!r)return false;let s=Number.parseInt(r,10);if(Number.isNaN(s)||s<0||s>32)return false;let n=eo(o),i=eo(t);if(n===null||i===null)return false;let a=s===0?0:-1<<32-s>>>0;return (n&a)===(i&a)}function eo(o){let e=o.split(".");if(e.length!==4)return null;let t=0;for(let r of e){let s=Number.parseInt(r,10);if(Number.isNaN(s)||s<0||s>255)return null;t=t<<8|s;}return t>>>0}var Lt=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.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ne,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{},n=this.graphql.isEnabled,i="/graphql";this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(a,c)=>{let p=a.url,l=p.indexOf("://")+3,d=p.indexOf("/",l),u=d===-1?"/":p.slice(d),m=u.indexOf("?"),h=m===-1?u:u.slice(0,m),f=m===-1?"":u.slice(m+1),g=_.find(a.method,h),y=ie.fromRequest(a);if(y.params=g?.params??{},y.setQueryString(f),y.setBunIpExtractor(a,c),await t?.call(this,y,c),n&&h.startsWith(i)){let w=await this.ensureGraphQLHandler();if(w){let b=y.toWebApi();return Ht(w.server,b,a.method,f,{req:y,server:c})}}if(r&&y.rawHeaders.get("upgrade")==="websocket"){let w=y.toWebApi();if(c.upgrade(w,{data:{}}))return}let P=new F;return g?.responseSchemas&&P.setRouteResponseSchemas(g.responseSchemas),await fe(g?.middleware??[],g?.handler??((w,b)=>{b.notFound({...$(new U(w.url,w.method))});}),y,P),F.toWebResponse(P)},...r?{websocket:r}:{},...s});}async close(){this.runtimeServer&&await this.runtimeServer.stop();}};var Dt=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.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new ne,this.ensureGraphQLHandler=ge(this.graphql);}get url(){return `http://${this.host}:${this.port}`}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{},s=this.graphql.isEnabled,n="/graphql";this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(i,a)=>{let c=i.url,p=c.indexOf("://")+3,l=c.indexOf("/",p),d=l===-1?"/":c.slice(l),u=d.indexOf("?"),m=u===-1?d:d.slice(0,u),h=u===-1?"":d.slice(u+1),f=_.find(i.method,m),g=ie.fromRequest(i);if(g.params=f?.params??{},g.setQueryString(h),g.setDenoIpExtractor(i,a),await t?.(i,a))return new globalThis.Response(null,{status:426});if(s&&m.startsWith(n)){let w=await this.ensureGraphQLHandler();if(w){let b=g.toWebApi();return Ht(w.server,b,i.method,h,{req:g,info:a})}}if(g.rawHeaders.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let w=g.toWebApi(),{socket:b,response:q}=Deno.upgradeWebSocket(w);return this.tapOptions?.deno?.websocket?.open&&(b.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(b)),this.tapOptions?.deno?.websocket?.message&&(b.onmessage=A=>{this.tapOptions?.deno?.websocket?.message?.(b,A.data);}),this.tapOptions?.deno?.websocket?.close&&(b.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(b)),q}let P=new F;return f?.responseSchemas&&P.setRouteResponseSchemas(f.responseSchemas),await fe(f?.middleware??[],f?.handler??((w,b)=>{b.notFound({...$(new U(w.url,w.method))});}),g,P),F.toWebResponse(P)},...r});}async close(){this.runtimeServer&&await this.runtimeServer.shutdown();}};var xi=async(o,e)=>{let t=stream.Readable.fromWeb(o);return promises.pipeline(t,e)};function Ti(o){return JSON.stringify(o).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026")}var Ft=class{port;host;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 ne,this.ensureGraphQLHandler=ge(this.graphql),this.needsHeaderFiltering=this.nodeHttpClient==="http2"||this.nodeHttpClient==="http2-secure",this.createServerWithHandler();}get url(){return `${this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http"}://${this.host}:${this.port}`}createServerWithHandler(){let e=this.graphql.isEnabled,t="/graphql";this.runtimeServer=this.createServer(async(r,s)=>{if(this.tapOptions&&this.tapOptions.node){let m=this.tapOptions.node;await m?.(r);}let n=r.url,i=n.indexOf("?"),a=i===-1?n:n.slice(0,i),c=i===-1?"":n.slice(i+1);if(e&&a.startsWith(t)){let m=await this.ensureGraphQLHandler();if(m){let h=le(r.method)?await this.readRequestBody(r):"";await Es(m.server,r.headers,r.method??"POST",h,c,{req:r},async(f,g,y)=>{for(let[P,x]of f)s.setHeader(P,x);if(s.statusCode=g,typeof y=="string")s.end(y);else {for await(let P of y)s.write(P);s.end();}});return}}let p=_.find(r.method,a),l=new ie;l.url=`${this.url}${n}`,l.method=r.method,le(r.method)&&l.setNodeRequest(r),l.setRawHeaders(r.headers,this.needsHeaderFiltering),l.setIpExtractor(r),l.setQueryString(c),l.params=p?.params??{};let d=new F;d.nodeResponse=s,p?.responseSchemas&&d.setRouteResponseSchemas(p.responseSchemas);let u=fe(p?.middleware??[],p?.handler??((m,h)=>{h.notFound({...$(new U(m.url,m.method))});}),l,d);u instanceof F?this.writeResponse(u,s):u.then(m=>this.writeResponse(m,s));});}listen(){this.runtimeServer.listen(this.port,this.host);}writeResponse(e,t){if(t.headersSent||t.writableEnded)return;let r=e.getBody();if(r instanceof ReadableStream){t.writeHead(e.responseStatus,e.headers),xi(r,t);return}let s={...e.headers};if(e.cookieHeaders.length>0&&(s["Set-Cookie"]=e.cookieHeaders),t.writeHead(e.responseStatus,s),r instanceof Buffer||r instanceof Uint8Array||typeof r=="string")t.end(r);else if(e.headers["Content-Type"]==="application/json"){let n=typeof r=="string"?r:Ti(r);t.end(n);}else t.end(r!=null?String(r):void 0);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}async readRequestBody(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(Buffer.from(n))),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");let r={minVersion:"TLSv1.2",honorCipherOrder:true,...this.httpsOptions};return http2.createSecureServer(r,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");let t={minVersion:"TLSv1.2",honorCipherOrder:true,...this.httpsOptions};return https.createServer(t,e)}};var Qt=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}set port(e){this.server.port=e;}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 Lt(e);if(e?.runtime==="node")return new Ft(e);if(e?.runtime==="deno")return new Dt(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};J();var Ri={cookie:0,session:1};function to(o){return Ri[o]??50}var Ut=class{_brand="BaldaServer";#e=new Je;serverOptions;router=_;logger;isListening;isProduction;graphql;#r;#t;#a=[];#o=["node_modules"];#n;#d;#p=[];#u=[];#c;inject;constructor(e){this.logger=(e?.logger??E).child({scope:"Balda"}),this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:(e?.port??Number(this.#e.get("PORT")||"80"))||80,host:e?.host??this.#e.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},e?.ajvInstance&&j.setGlobalInstance(e.ajvInstance),this.#d=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.#e.get("NODE_ENV")==="production",this.graphql=new ne(this.serverOptions.graphql),this.#t=new Qt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:M.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.#d,graphql:this.graphql}),this.setupAbortSignalHandler(),this.inject=this.createInjectFunction();}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.#t.url}get port(){return this.#t.port}set port(e){if(this.isListening)throw new Error("Cannot change port while server is listening, please call `.close()` before changing the port");this.#t.port=e;}get host(){return this.#t.host}get routes(){return _.getRoutes()||[]}get fs(){return v}getEnvironment(){return this.#e.getEnvironment()}tmpDir(...e){return S.join("tmp",...e)}getNodeServer(){if(M.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.#t.getServer("node")}getBunServer(){if(M.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.#t.getServer("bun")}getDenoServer(){if(M.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.#t.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){ze.exit(e);}on(e,t){switch(M.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${M.type}, only node, bun and deno are supported`)}}once(e,t){switch(M.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${M.type}, only node, bun and deno are supported`)}}use(...e){this.#a.push(...e);}useExpress(e,t){$r(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){mt(e,t);}setErrorHandler(e){this.#a.unshift(async(t,r,s)=>{try{await s();}catch(n){await e?.(t,r,s,n);}});}setNotFoundHandler(e){this.#n=e?.bind(this);}setValidationErrorHandler(e){as(e);}setPolicyErrorHandler(e){fs(e);}beforeStart(e){this.#p.push(e);}beforeClose(e){this.#u.push(e);}listen(e,t){let r=typeof e=="function"?e:t;if(typeof e=="number"&&Number.isFinite(e)&&(this.port=e),this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");let s={port:this.port,host:this.host,url:this.url};this.bootstrap().then(async()=>{for(let n of this.#p)await n();this.#t.listen(),this.isListening=true,r?.({...s,error:void 0});}).catch(n=>{r?.({...s,error:n});});}async waitUntilListening(e){return e??=this.port,new Promise((t,r)=>{try{this.listen(e,()=>{t({port:this.port,host:this.host,url:this.url});});}catch(s){r(s);}})}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{for(let e of this.#u)await e();await this.#t.close();}catch(e){throw this.logger.error({error:e},"Error closing server connector"),e}finally{this.isListening=false;}}getMockServer(e){return new pt(this,e)}async ensureBootstrapped(e){await this.bootstrap(e);}createInjectFunction(){let e=()=>(this.#c||(this.#c=new pt(this)),this.#c),t=(r,s,n)=>e().request(r,s,n);return t.get=(r,s)=>e().get(r,s),t.post=(r,s)=>e().post(r,s),t.put=(r,s)=>e().put(r,s),t.patch=(r,s)=>e().patch(r,s),t.delete=(r,s)=>e().delete(r,s),t}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:L.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.#o.some(n=>s.includes(n))),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(n=>{this.logger.error(`Error importing controller ${s}: ${n}`);});}));}catch(r){this.logger.warn(`Could not auto-import controllers: ${r instanceof Error?r.message:String(r)}`);}}applyPlugins(e){if(Array.isArray(e)){this.use(...e);return}Object.entries(e).sort(([r],[s])=>to(r)-to(s)).forEach(([r,s])=>{switch(r){case "bodyParser":this.use(jr(s));break;case "cors":this.use(_r(s));break;case "static":this.use(Pr(s));break;case "helmet":this.use(Br(s));break;case "cookie":this.use(qr(s));break;case "methodOverride":this.use(Ir(s));break;case "compression":this.use(kr(s));break;case "log":this.use(Nr(s));break;case "rateLimiter":let{keyOptions:n,storageOptions:i}=s;this.use(Lr(n,i));break;case "trustProxy":this.use(Qr(s));break;case "timeout":this.use(Fr(s));break;case "session":this.use(Dr(s));break;case "asyncLocalStorage":this.use(Or(s));break;case "cache":{let a=s,c;a.provider&&typeof a.provider=="object"&&"get"in a.provider?c=a.provider:a.provider==="redis"?c=new dt(a.redis):c=new lt,this.use(Tr(c,a));break}default:this.logger.warn(`Unknown plugin ${r}`);break}});}bootstrap(e){return this.#r?this.#r:(this.#r=(async()=>{await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.serverOptions.swagger&&Ys(this.serverOptions.swagger),this.registerNotFoundRoutes(),this.#a.length&&_.applyGlobalMiddlewaresToAllRoutes(this.#a);})(),this.#r)}handleNotFound=(e,t)=>{if(this.#n){this.#n(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE"],n=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=_.find(a,r);c&&c.handler!==this.handleNotFound&&n.push(a);}if(n.length){t.setHeader("Allow",n.join(", "));let a=new We(r,e.method);t.methodNotAllowed({...$(a)});return}let i=new U(r,e.method);t.notFound({...$(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)_.addOrUpdate(t,"*",[],this.handleNotFound,{},{excludeFromSwagger:true},void 0,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 Ur=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)),n=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"},n,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),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,a]=n,c=this.decodeBase64(i),p=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),u=new Uint8Array(d);if(u.length!==p.length)return !1;let m=0;for(let h=0;h<u.length;h++)m|=u[h]^p[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 n=0;n<r;n++)s[n]=t.charCodeAt(n);return s}},Pi=new Ur;var ro=()=>{let o=j.getCacheStats(),e=o.schemaCount*3,t=e,r=s=>s<1024?`~${s}KB`:`~${(s/1024).toFixed(2)}MB`;return {validators:{size:o.schemaCount,description:"Compiled schemas stored in Ajv for validation and serialization"},totalSchemaReferences:o.totalRefsCreated,memoryEstimate:{validators:r(e),total:r(t)}}},Ci=()=>{let o=ro();E.info({validators:o.validators.size,totalSchemaRefs:o.totalSchemaReferences,memoryEstimate:o.memoryEstimate.total},"Schema cache metrics");},Oi=()=>{j.clearAllCaches(),E.debug("All schema caches cleared");};var Z=class extends R{constructor(e){super(`File not found: ${e}`);}};var zr=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),n=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:n},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),n=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:n},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 Z(e);let n=t;if(n==="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(n){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new R("Invalid return type")}}catch(r){throw r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404?new Z(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),n=t;await s.upload(n,n.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 R("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 R("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Gr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new R("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new R("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=S.resolve(this.options.directory),r=e?S.join(t,e):t;if(!await v.exists(r))return [];let n=[];return await this.listFilesRecursively(r,t,n),n}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=S.join(this.options.directory,e);if(!await v.exists(r))throw new Z(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 R("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=S.join(this.options.directory,e),n=S.join(s,"..");await v.mkdir(n,{recursive:true}),await v.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=S.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 n=await this.readDirectory(e);for(let i of n){let a=S.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(J(),es));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 R("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;}};J();var Vr=class{isBun;clientInitialized=false;options;constructor(e){this.options=e,this.isBun=M.type==="bun";}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),this.options.cloudfrontOptions){let{domainName:r,keyPairId:s,privateKey:n}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:n,dateLessThan:a})}if(this.isBun)return this.bunS3Client.file(e).presign({method:"GET",expiresIn:t});throw new R("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 Z(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 R("Invalid return type")}}catch(s){throw s instanceof Z?s:s&&typeof s=="object"&&"code"in s&&(s.code==="NoSuchKey"||s.code==="NotFound")?new Z(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 Z(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 R("Invalid return type")}}catch(s){throw s&&typeof s=="object"&&"name"in s&&s.name==="NoSuchKey"?new Z(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 R("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 R("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 R("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 Jr=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 zt=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 R("Library not installed: handlebars, try run npm install handlebars @types/handlebars")});this.handlebars=t.default?.default||t.default||t;}};var Gt=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 R("Library not installed: edge.js, try run npm install edge.js")}),{Edge:t}=e;this.edge=new t;}};var Vt=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 R("Library not installed: mustache, try run npm install mustache @types/mustache")});this.mustache=e.default||e;}};var Jt=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 R("Library not installed: ejs, try run npm install ejs @types/ejs")});this.ejs=e.default||e;}};var Wt=class{helpers=new Map;render(e,t){return e.replace(/\{\{(\w+)(?::(\w+))?\}\}/g,(r,s,n)=>{let i=t[s];return i===void 0?r:n&&this.helpers.has(n)?this.helpers.get(n)(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 ht=class extends R{constructor(e){super(e),this.name="MailerError";}},ft=class extends ht{constructor(e){super(`[Mailer] Provider '${e}' not found`),this.name="ProviderNotFoundError";}},Kt=class extends ht{constructor(){super("[MailProvider] Template adapter not configured for this provider"),this.name="TemplateAdapterNotConfiguredError";}},Xt=class extends ht{constructor(e){super(`[Mailer] Default provider '${e}' not found in provider options`),this.name="InvalidDefaultProviderError";}};var gt=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,n=s.build();return s.hasTemplate()?this.sendWithTemplate(n):this.sendDirect(n)}async sendDirect(e){let t={...e,from:e.from||this.defaultFrom};return this.transporter.sendMail(t)}async sendWithTemplate(e){if(!this.templateAdapter)throw new Kt;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 Wr=class{defaultProvider;providerMap;emailQueue=null;queueInitialized=false;constructor(e,t){if(!e[t.defaultProvider])throw new Xt(String(t.defaultProvider));this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.keys(e).map(r=>[r,new gt(e[r])]));}use(e){let t=this.providerMap.get(e);if(!t)throw new ft(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,n=s.build(),i=s.hasTemplate();await this.emailQueue.publish({options:n,isTemplate:i});}async initializeQueue(){this.queueInitialized||(this.emailQueue=br("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 n=s;n.isFilePath?r.templateFile(n.template,n.data):r.template(n.template,n.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 ft(String(this.defaultProvider));return e}};var Kr=class{};var Xr=o=>(e,t)=>(r,s,n)=>{let i={scope:e,handler:t,manager:o};if(typeof s>"u"){let c=O.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),O.set(r.prototype,"__class__",c),r}let a=O.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),O.set(r,s,a),n};var Zr=class{providers;constructor(e){this.providers=e;}createDecorator(){return Xr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new R(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var Py=_,Cy=Ut;
|
|
1232
|
+
Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return ajv.ValidationError}});exports.AzureBlobStorageProvider=zr;exports.BaseCron=vr;exports.BasePlugin=Kr;exports.BullMQPubSub=st;exports.CACHE_STATUS_HEADER=ue;exports.CacheService=et;exports.CacheStatus=cr;exports.Command=k;exports.CommandRegistry=_t;exports.CronService=W;exports.CustomAdapter=Wt;exports.DEFAULT_CACHE_OPTIONS=De;exports.EdgeAdapter=Gt;exports.EjsAdapter=Jt;exports.GraphQL=ne;exports.HandlebarsAdapter=zt;exports.LocalStorageProvider=Gr;exports.MailOptionsBuilder=Be;exports.MailProvider=gt;exports.Mailer=Wr;exports.MemoryCacheProvider=lt;exports.MemoryPubSub=ot;exports.MqttService=Ue;exports.MustacheAdapter=Vt;exports.PGBossPubSub=nt;exports.PolicyManager=Zr;exports.QueueManager=oe;exports.QueueService=K;exports.RedisCacheProvider=dt;exports.S3StorageProvider=Vr;exports.SQSPubSub=it;exports.Server=Ut;exports.Storage=Jr;exports.arg=N;exports.asyncLocalStorage=Or;exports.asyncStorage=Ke;exports.bodyParser=jr;exports.bullmqQueue=Zo;exports.cache=fo;exports.cacheMiddleware=Tr;exports.clearAllSchemaCaches=Oi;exports.commandRegistry=Pe;exports.compression=kr;exports.controller=_o;exports.cookie=qr;exports.cors=_r;exports.createExpressAdapter=$r;exports.createPolicyDecorator=Xr;exports.createQueue=en;exports.cron=qo;exports.cronUIInstance=hr;exports.cronUi=ko;exports.default=Cy;exports.defineMiddleware=cn;exports.defineQueueConfiguration=tn;exports.del=Ho;exports.expressHandler=Js;exports.expressMiddleware=$e;exports.flag=C;exports.get=$o;exports.getCacheService=tt;exports.getSchemaCacheMetrics=ro;exports.hash=Pi;exports.helmet=Br;exports.initCacheService=dr;exports.log=Nr;exports.logSchemaCacheMetrics=Ci;exports.logger=E;exports.memoryQueue=br;exports.methodOverride=Ir;exports.middleware=Lo;exports.mountExpressRouter=mt;exports.mqtt=Ko;exports.patch=Bo;exports.pgbossQueue=Yo;exports.post=No;exports.put=Io;exports.rateLimiter=Lr;exports.resetCacheService=Eo;exports.router=Py;exports.serialize=Qo;exports.serializer=Vo;exports.serveStatic=Pr;exports.session=Dr;exports.setCronGlobalErrorHandler=jo;exports.setMqttGlobalErrorHandler=Wo;exports.sqsQueue=Xo;exports.timeoutMw=Fr;exports.trustProxy=Qr;exports.validate=zo;//# sourceMappingURL=index.cjs.map
|
|
1231
1233
|
//# sourceMappingURL=index.cjs.map
|