molnos 1.4.1 → 1.4.3

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/VERSION CHANGED
@@ -1 +1 @@
1
- 1.4.1
1
+ 1.4.3
@@ -1,11 +1,11 @@
1
1
  // MolnOS Core - See LICENSE file for copyright and license details.
2
- var D=class{requests=new Map;limit;windowMs;constructor(e=100,t=60){this.limit=e,this.windowMs=t*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return(!r||r.resetTime<t)&&(r={count:0,resetTime:t+this.windowMs},this.requests.set(s,r)),r.count++,r.count<=this.limit}getRemainingRequests(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return!r||r.resetTime<t?this.limit:Math.max(0,this.limit-r.count)}getResetTime(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return!r||r.resetTime<t?Math.floor((t+this.windowMs)/1e3):Math.floor(r.resetTime/1e3)}cleanup(){let e=Date.now();for(let[t,s]of this.requests.entries())s.resetTime<e&&this.requests.delete(t)}};import{URL as he}from"url";var q=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(e){return this.globalMiddlewares.push(e),this}get(e,...t){let s=t.pop();return this.register("GET",e,s,t)}post(e,...t){let s=t.pop();return this.register("POST",e,s,t)}put(e,...t){let s=t.pop();return this.register("PUT",e,s,t)}delete(e,...t){let s=t.pop();return this.register("DELETE",e,s,t)}patch(e,...t){let s=t.pop();return this.register("PATCH",e,s,t)}any(e,...t){let s=t.pop(),r=t;return this.register("GET",e,s,r),this.register("POST",e,s,r),this.register("PUT",e,s,r),this.register("DELETE",e,s,r),this.register("PATCH",e,s,r),this.register("OPTIONS",e,s,r),this}options(e,...t){let s=t.pop();return this.register("OPTIONS",e,s,t)}match(e,t){for(let s of this.routes){if(s.method!==e)continue;let r=this.pathPatterns.get(s.path);if(!r)continue;let i=r.pattern.exec(t);if(!i)continue;let o={};return r.paramNames.forEach((n,a)=>{o[n]=i[a+1]||""}),{route:s,params:o}}return null}async handle(e,t){let s=e.method||"GET",r=new he(e.url||"/",`http://${e.headers.host}`),i=r.pathname,o=this.match(s,i);if(!o)return null;let{route:n,params:a}=o,c={};r.searchParams.forEach((u,d)=>{c[d]=u});let l={req:e,res:t,params:a,query:c,body:e.body||{},headers:e.headers,path:i,state:{},raw:()=>t,binary:(u,d="application/octet-stream",y=200)=>({statusCode:y,body:u,headers:{"Content-Type":d,"Content-Length":u.length.toString()},isRaw:!0}),text:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/plain"}}),form:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/json"}}),html:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/html"}}),redirect:(u,d=302)=>({statusCode:d,body:null,headers:{Location:u}}),status:function(u){return{raw:()=>t,binary:(d,y="application/octet-stream")=>({statusCode:u,body:d,headers:{"Content-Type":y,"Content-Length":d.length.toString()},isRaw:!0}),text:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/plain"}}),json:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/json"}}),html:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/html"}}),form:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(d,y=302)=>({statusCode:y,body:null,headers:{Location:d}}),status:d=>this.status(d)}}},f=[...this.globalMiddlewares,...n.middlewares];return this.executeMiddlewareChain(l,f,n.handler)}register(e,t,s,r=[]){return this.routes.push({method:e,path:t,handler:s,middlewares:r}),this.pathPatterns.set(t,this.createPathPattern(t)),this}createPathPattern(e){let t=[],s=e.replace(/\/:[^/]+/g,r=>{let i=r.slice(2);return t.push(i),"/([^/]+)"});return s.endsWith("/*")?(s=`${s.slice(0,-2)}(?:/(.*))?`,t.push("wildcard")):s=s.replace(/\/$/,"/?"),{pattern:new RegExp(`^${s}$`),paramNames:t}}async executeMiddlewareChain(e,t,s){let r=0,i=async()=>{if(r<t.length){let o=t[r++];return o(e,i)}return s(e)};return i()}};var E=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:pe(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function pe(e){return e==="true"||e===!0}var $=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as me,readFileSync as ye}from"node:fs";var I=class{config={};options=[];validators=[];autoValidate=!0;constructor(e){let t=e?.configFilePath,s=e?.args||[],r=e?.config||{};this.options=e?.options||[],this.validators=e?.validators||[],e?.autoValidate!==void 0&&(this.autoValidate=e.autoValidate),this.config=this.createConfig(t,s,r)}deepMerge(e,t){let s={...e};for(let r in t)t[r]!==void 0&&(t[r]!==null&&typeof t[r]=="object"&&!Array.isArray(t[r])&&r in e&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])?s[r]=this.deepMerge(e[r],t[r]):t[r]!==void 0&&(s[r]=t[r]));return s}setValueAtPath(e,t,s){let r=t.split("."),i=e;for(let n=0;n<r.length-1;n++){let a=r[n];!(a in i)||i[a]===null?i[a]={}:typeof i[a]!="object"&&(i[a]={}),i=i[a]}let o=r[r.length-1];i[o]=s}getValueAtPath(e,t){let s=t.split("."),r=e;for(let i of s){if(r==null)return;r=r[i]}return r}createConfig(e,t=[],s={}){let r={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(r,a.path,a.defaultValue);let i={};if(e&&me(e))try{let a=ye(e,"utf8");i=JSON.parse(a),console.log(`Loaded configuration from ${e}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let o=this.parseCliArgs(t),n=this.deepMerge({},r);return n=this.deepMerge(n,i),n=this.deepMerge(n,s),n=this.deepMerge(n,o),n}parseCliArgs(e){let t={},s=e[0]?.endsWith("node")||e[0]?.endsWith("node.exe")?2:0;for(;s<e.length;){let r=e[s++],i=this.options.find(o=>o.flag===r);if(i)if(i.isFlag)this.setValueAtPath(t,i.path,!0);else if(s<e.length&&!e[s].startsWith("-")){let o=e[s++];if(i.parser)try{o=i.parser(o)}catch(n){console.error(`Error parsing value for ${i.flag}: ${n instanceof Error?n.message:String(n)}`);continue}if(i.validator){let n=i.validator(o);if(n!==!0&&typeof n=="string"){console.error(`Invalid value for ${i.flag}: ${n}`);continue}if(n===!1){console.error(`Invalid value for ${i.flag}`);continue}}this.setValueAtPath(t,i.path,o)}else console.error(`Missing value for option ${r}`)}return t}validate(){for(let e of this.validators){let t=this.getValueAtPath(this.config,e.path),s=e.validator(t,this.config);if(s===!1)throw new $(e.message);if(typeof s=="string")throw new $(s)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(e,t){let s=this.getValueAtPath(this.config,e);return s!==void 0?s:t}setValue(e,t){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let s=this.getValueAtPath(this.config,e)||{};if(typeof s=="object"&&!Array.isArray(s)){let r=this.deepMerge(s,t);this.setValueAtPath(this.config,e,r);return}}this.setValueAtPath(this.config,e,t)}getHelpText(){let e=`Available configuration options:
2
+ var q=class{requests=new Map;limit;windowMs;constructor(e=100,t=60){this.limit=e,this.windowMs=t*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return(!r||r.resetTime<t)&&(r={count:0,resetTime:t+this.windowMs},this.requests.set(s,r)),r.count++,r.count<=this.limit}getRemainingRequests(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return!r||r.resetTime<t?this.limit:Math.max(0,this.limit-r.count)}getResetTime(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return!r||r.resetTime<t?Math.floor((t+this.windowMs)/1e3):Math.floor(r.resetTime/1e3)}cleanup(){let e=Date.now();for(let[t,s]of this.requests.entries())s.resetTime<e&&this.requests.delete(t)}};import{URL as ye}from"url";var z=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(e){return this.globalMiddlewares.push(e),this}get(e,...t){let s=t.pop();return this.register("GET",e,s,t)}post(e,...t){let s=t.pop();return this.register("POST",e,s,t)}put(e,...t){let s=t.pop();return this.register("PUT",e,s,t)}delete(e,...t){let s=t.pop();return this.register("DELETE",e,s,t)}patch(e,...t){let s=t.pop();return this.register("PATCH",e,s,t)}any(e,...t){let s=t.pop(),r=t;return this.register("GET",e,s,r),this.register("POST",e,s,r),this.register("PUT",e,s,r),this.register("DELETE",e,s,r),this.register("PATCH",e,s,r),this.register("OPTIONS",e,s,r),this}options(e,...t){let s=t.pop();return this.register("OPTIONS",e,s,t)}match(e,t){for(let s of this.routes){if(s.method!==e)continue;let r=this.pathPatterns.get(s.path);if(!r)continue;let i=r.pattern.exec(t);if(!i)continue;let n={};return r.paramNames.forEach((o,a)=>{n[o]=i[a+1]||""}),{route:s,params:n}}return null}async handle(e,t){let s=e.method||"GET",r=new ye(e.url||"/",`http://${e.headers.host}`),i=r.pathname,n=this.match(s,i);if(!n)return null;let{route:o,params:a}=n,d={};r.searchParams.forEach((c,u)=>{d[u]=c});let l={req:e,res:t,params:a,query:d,body:e.body||{},headers:e.headers,path:i,state:{},raw:()=>t,binary:(c,u="application/octet-stream",g=200)=>({statusCode:g,body:c,headers:{"Content-Type":u,"Content-Length":c.length.toString()},isRaw:!0}),text:(c,u=200)=>({statusCode:u,body:c,headers:{"Content-Type":"text/plain"}}),form:(c,u=200)=>({statusCode:u,body:c,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(c,u=200)=>({statusCode:u,body:c,headers:{"Content-Type":"application/json"}}),html:(c,u=200)=>({statusCode:u,body:c,headers:{"Content-Type":"text/html"}}),redirect:(c,u=302)=>({statusCode:u,body:null,headers:{Location:c}}),status:function(c){return{raw:()=>t,binary:(u,g="application/octet-stream")=>({statusCode:c,body:u,headers:{"Content-Type":g,"Content-Length":u.length.toString()},isRaw:!0}),text:u=>({statusCode:c,body:u,headers:{"Content-Type":"text/plain"}}),json:u=>({statusCode:c,body:u,headers:{"Content-Type":"application/json"}}),html:u=>({statusCode:c,body:u,headers:{"Content-Type":"text/html"}}),form:u=>({statusCode:c,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(u,g=302)=>({statusCode:g,body:null,headers:{Location:u}}),status:u=>this.status(u)}}},f=[...this.globalMiddlewares,...o.middlewares];return this.executeMiddlewareChain(l,f,o.handler)}register(e,t,s,r=[]){return this.routes.push({method:e,path:t,handler:s,middlewares:r}),this.pathPatterns.set(t,this.createPathPattern(t)),this}createPathPattern(e){let t=[],s=e.replace(/\/:[^/]+/g,r=>{let i=r.slice(2);return t.push(i),"/([^/]+)"});return s.endsWith("/*")?(s=`${s.slice(0,-2)}(?:/(.*))?`,t.push("wildcard")):s=s.replace(/\/$/,"/?"),{pattern:new RegExp(`^${s}$`),paramNames:t}}async executeMiddlewareChain(e,t,s){let r=0,i=async()=>{if(r<t.length){let n=t[r++];return n(e,i)}return s(e)};return i()}};var E=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:ge(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function ge(e){return e==="true"||e===!0}var A=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as be,readFileSync as we}from"node:fs";var $=class{config={};options=[];validators=[];autoValidate=!0;constructor(e){let t=e?.configFilePath,s=e?.args||[],r=e?.config||{};this.options=e?.options||[],this.validators=e?.validators||[],e?.autoValidate!==void 0&&(this.autoValidate=e.autoValidate),this.config=this.createConfig(t,s,r)}deepMerge(e,t){let s={...e};for(let r in t)t[r]!==void 0&&(t[r]!==null&&typeof t[r]=="object"&&!Array.isArray(t[r])&&r in e&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])?s[r]=this.deepMerge(e[r],t[r]):t[r]!==void 0&&(s[r]=t[r]));return s}setValueAtPath(e,t,s){let r=t.split("."),i=e;for(let o=0;o<r.length-1;o++){let a=r[o];!(a in i)||i[a]===null?i[a]={}:typeof i[a]!="object"&&(i[a]={}),i=i[a]}let n=r[r.length-1];i[n]=s}getValueAtPath(e,t){let s=t.split("."),r=e;for(let i of s){if(r==null)return;r=r[i]}return r}createConfig(e,t=[],s={}){let r={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(r,a.path,a.defaultValue);let i={};if(e&&be(e))try{let a=we(e,"utf8");i=JSON.parse(a),console.log(`Loaded configuration from ${e}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let n=this.parseCliArgs(t),o=this.deepMerge({},r);return o=this.deepMerge(o,i),o=this.deepMerge(o,s),o=this.deepMerge(o,n),o}parseCliArgs(e){let t={},s=e[0]?.endsWith("node")||e[0]?.endsWith("node.exe")?2:0;for(;s<e.length;){let r=e[s++],i=this.options.find(n=>n.flag===r);if(i)if(i.isFlag)this.setValueAtPath(t,i.path,!0);else if(s<e.length&&!e[s].startsWith("-")){let n=e[s++];if(i.parser)try{n=i.parser(n)}catch(o){console.error(`Error parsing value for ${i.flag}: ${o instanceof Error?o.message:String(o)}`);continue}if(i.validator){let o=i.validator(n);if(o!==!0&&typeof o=="string"){console.error(`Invalid value for ${i.flag}: ${o}`);continue}if(o===!1){console.error(`Invalid value for ${i.flag}`);continue}}this.setValueAtPath(t,i.path,n)}else console.error(`Missing value for option ${r}`)}return t}validate(){for(let e of this.validators){let t=this.getValueAtPath(this.config,e.path),s=e.validator(t,this.config);if(s===!1)throw new A(e.message);if(typeof s=="string")throw new A(s)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(e,t){let s=this.getValueAtPath(this.config,e);return s!==void 0?s:t}setValue(e,t){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let s=this.getValueAtPath(this.config,e)||{};if(typeof s=="object"&&!Array.isArray(s)){let r=this.deepMerge(s,t);this.setValueAtPath(this.config,e,r);return}}this.setValueAtPath(this.config,e,t)}getHelpText(){let e=`Available configuration options:
3
3
 
4
4
  `;for(let t of this.options)e+=`${t.flag}${t.isFlag?"":" <value>"}
5
5
  `,t.description&&(e+=` ${t.description}
6
6
  `),t.defaultValue!==void 0&&(e+=` Default: ${JSON.stringify(t.defaultValue)}
7
7
  `),e+=`
8
- `;return e}};var O={int:e=>{let t=e.trim();if(!/^[+-]?\d+$/.test(t))throw new Error(`Cannot parse "${e}" as an integer`);let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new Error(`Cannot parse "${e}" as an integer`);return s},float:e=>{let t=e.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)){if(t==="Infinity"||t==="-Infinity")return t==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${e}" as a number`)}let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error(`Cannot parse "${e}" as a number`);return s},boolean:e=>{let t=e.trim().toLowerCase();if(["true","yes","1","y"].includes(t))return!0;if(["false","no","0","n"].includes(t))return!1;throw new Error(`Cannot parse "${e}" as a boolean`)},array:e=>e.split(",").map(t=>t.trim()),json:e=>{try{return JSON.parse(e)}catch{throw new Error(`Cannot parse "${e}" as JSON`)}}};var g=E(),z=e=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:g.port},{flag:"--host",path:"host",defaultValue:g.host},{flag:"--https",path:"useHttps",defaultValue:g.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:g.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:g.sslCert},{flag:"--key",path:"sslKey",defaultValue:g.sslKey},{flag:"--ca",path:"sslCa",defaultValue:g.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:g.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:g.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:g.allowedDomains,parser:O.array},{flag:"--debug",path:"debug",defaultValue:g.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:g.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:g.requestTimeout}],config:e});function B(e,t){let s=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!s)throw new Error("Invalid multipart/form-data: missing boundary");let r=s[1]||s[2],i=Buffer.from(`--${r}`),o=Buffer.from(`--${r}--`),n={},a={},c=ge(e,i);for(let l of c){if(l.length===0||l.equals(o.subarray(i.length)))continue;let f=be(l);if(!f)continue;let{name:u,filename:d,contentType:y,data:w}=f;if(d){let b={filename:d,contentType:y||"application/octet-stream",data:w,size:w.length};a[u]?Array.isArray(a[u])?a[u].push(b):a[u]=[a[u],b]:a[u]=b}else{let b=w.toString("utf8");n[u]?Array.isArray(n[u])?n[u].push(b):n[u]=[n[u],b]:n[u]=b}}return{fields:n,files:a}}function ge(e,t){let s=[],r=0;for(;r<e.length;){let i=e.indexOf(t,r);if(i===-1)break;r!==i&&s.push(e.subarray(r,i)),r=i+t.length,r<e.length&&e[r]===13&&e[r+1]===10&&(r+=2)}return s}function be(e){let t=Buffer.from(`\r
8
+ `;return e}};var k={int:e=>{let t=e.trim();if(!/^[+-]?\d+$/.test(t))throw new Error(`Cannot parse "${e}" as an integer`);let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new Error(`Cannot parse "${e}" as an integer`);return s},float:e=>{let t=e.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)){if(t==="Infinity"||t==="-Infinity")return t==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${e}" as a number`)}let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error(`Cannot parse "${e}" as a number`);return s},boolean:e=>{let t=e.trim().toLowerCase();if(["true","yes","1","y"].includes(t))return!0;if(["false","no","0","n"].includes(t))return!1;throw new Error(`Cannot parse "${e}" as a boolean`)},array:e=>e.split(",").map(t=>t.trim()),json:e=>{try{return JSON.parse(e)}catch{throw new Error(`Cannot parse "${e}" as JSON`)}}};var b=E(),B=e=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:b.port},{flag:"--host",path:"host",defaultValue:b.host},{flag:"--https",path:"useHttps",defaultValue:b.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:b.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:b.sslCert},{flag:"--key",path:"sslKey",defaultValue:b.sslKey},{flag:"--ca",path:"sslCa",defaultValue:b.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:b.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:b.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:b.allowedDomains,parser:k.array},{flag:"--debug",path:"debug",defaultValue:b.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:b.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:b.requestTimeout}],config:e});function F(e,t){let s=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!s)throw new Error("Invalid multipart/form-data: missing boundary");let r=s[1]||s[2],i=Buffer.from(`--${r}`),n=Buffer.from(`--${r}--`),o={},a={},d=ve(e,i);for(let l of d){if(l.length===0||l.equals(n.subarray(i.length)))continue;let f=Ce(l);if(!f)continue;let{name:c,filename:u,contentType:g,data:v}=f;if(u){let w={filename:u,contentType:g||"application/octet-stream",data:v,size:v.length};a[c]?Array.isArray(a[c])?a[c].push(w):a[c]=[a[c],w]:a[c]=w}else{let w=v.toString("utf8");o[c]?Array.isArray(o[c])?o[c].push(w):o[c]=[o[c],w]:o[c]=w}}return{fields:o,files:a}}function ve(e,t){let s=[],r=0;for(;r<e.length;){let i=e.indexOf(t,r);if(i===-1)break;r!==i&&s.push(e.subarray(r,i)),r=i+t.length,r<e.length&&e[r]===13&&e[r+1]===10&&(r+=2)}return s}function Ce(e){let t=Buffer.from(`\r
9
9
  \r
10
- `),s=e.indexOf(t);if(s===-1)return null;let r=e.subarray(0,s),i=e.subarray(s+4),n=r.toString("utf8").split(`\r
11
- `),a="",c="",l,f;for(let d of n){let y=d.toLowerCase();if(y.startsWith("content-disposition:")){a=d.substring(20).trim();let w=a.match(/name="([^"]+)"/);w&&(c=w[1]);let b=a.match(/filename="([^"]+)"/);b&&(l=b[1])}else y.startsWith("content-type:")&&(f=d.substring(13).trim())}if(!c)return null;let u=i;return u.length>=2&&u[u.length-2]===13&&u[u.length-1]===10&&(u=u.subarray(0,u.length-2)),{disposition:a,name:c,filename:l,contentType:f,data:u}}import{readFileSync as x}from"fs";import k from"http";import we from"http2";import ve from"https";var L=class{config;rateLimiter;router;shutdownHandlers=[];constructor(e){let t=new I(z(e||{})).get();t.debug&&console.log("Using configuration:",t),this.config=t,this.router=new q;let s=t.rateLimit.requestsPerMinute||E().rateLimit.requestsPerMinute;this.rateLimiter=new D(s,60),t.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(e){return this.router.use(e),this}get(e,...t){return this.router.get(e,...t),this}post(e,...t){return this.router.post(e,...t),this}put(e,...t){return this.router.put(e,...t),this}delete(e,...t){return this.router.delete(e,...t),this}patch(e,...t){return this.router.patch(e,...t),this}any(e,...t){return this.router.any(e,...t),this}options(e,...t){return this.router.options(e,...t),this}start(){let e=this.createServer(),{port:t,host:s}=this.config;return this.setupGracefulShutdown(e),e.listen(t,s,()=>{let r=e.address(),i=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${i}://${r.address!=="::"?r.address:"localhost"}:${r.port}`)}),e}createServer(){let e=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let t={key:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return we.createSecureServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let t={key:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return ve.createServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}return k.createServer(e)}async rateLimitMiddleware(e,t){let s=e.req.socket.remoteAddress||"unknown";return e.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),e.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(s).toString()),e.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(s).toString()),this.rateLimiter.isAllowed(s)?t():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(e,t){let s=Date.now(),r=e.method||"UNKNOWN",i=e.url||"/unknown",o=this.config.debug;try{if(this.setCorsHeaders(t,e),this.setSecurityHeaders(t,this.config.useHttps),o&&console.log(`${r} ${i}`),e.method==="OPTIONS"){if(t instanceof k.ServerResponse)t.statusCode=204,t.end();else{let a=t;a.writeHead(204),a.end()}return}try{e.body=await this.parseBody(e)}catch(a){return o&&console.error("Body parsing error:",a.message),this.respond(t,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let n=await this.router.handle(e,t);return n?n._handled?void 0:this.respond(t,n):this.respond(t,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(n){return console.error("Server error:",n),this.respond(t,{statusCode:500,body:{error:"Internal Server Error",message:o?n.message:"An unexpected error occurred"}})}finally{o&&this.logDuration(s,r,i)}}logDuration(e,t,s){let r=Date.now()-e;console.log(`${t} ${s} completed in ${r}ms`)}async parseBody(e){return new Promise((t,s)=>{let r=[],i=0,o=this.config.maxBodySize,n=!1,a=null,c=this.config.debug,l=e.headers["content-type"]||"";c&&console.log("Content-Type:",l),this.config.requestTimeout>0&&(a=setTimeout(()=>{n||(n=!0,c&&console.log("Request timeout exceeded"),s(new Error("Request timeout")))},this.config.requestTimeout));let f=()=>{a&&(clearTimeout(a),a=null)};e.on("data",u=>{if(!n){if(i+=u.length,c&&console.log(`Received chunk: ${u.length} bytes, total size: ${i}`),i>o){n=!0,f(),c&&console.log(`Body size exceeded limit: ${i} > ${o}`),s(new Error("Request body too large"));return}r.push(u)}}),e.on("end",()=>{if(!n){n=!0,f(),c&&console.log(`Request body complete: ${i} bytes`);try{if(r.length>0){let u=Buffer.concat(r);if(l.includes("application/json"))try{let d=u.toString("utf8");t(JSON.parse(d))}catch(d){s(new Error(`Invalid JSON in request body: ${d.message}`))}else if(l.includes("application/x-www-form-urlencoded")){let d=u.toString("utf8"),y={};new URLSearchParams(d).forEach((w,b)=>{y[b]=w}),t(y)}else if(l.includes("multipart/form-data"))try{let d=B(u,l);t(d)}catch(d){s(new Error(`Invalid multipart form data: ${d.message}`))}else this.isBinaryContentType(l)?t(u):t(u.toString("utf8"))}else t({})}catch(u){s(new Error(`Invalid request body: ${u}`))}}}),e.on("error",u=>{n||(n=!0,f(),s(new Error(`Error reading request body: ${u.message}`)))}),e.on("close",()=>{f()})})}isBinaryContentType(e){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(s=>e.includes(s))}setCorsHeaders(e,t){let s=t.headers.origin,{allowedDomains:r=["*"]}=this.config;!s||r.length===0||r.includes("*")?e.setHeader("Access-Control-Allow-Origin","*"):r.includes(s)&&(e.setHeader("Access-Control-Allow-Origin",s),e.setHeader("Vary","Origin")),e.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(e,t=!1){let s={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((t||this.config.useHttp2)&&(s["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),e instanceof k.ServerResponse)Object.entries(s).forEach(([r,i])=>{e.setHeader(r,i)});else{let r=e;Object.entries(s).forEach(([i,o])=>{r.setHeader(i,o)})}}respond(e,t){let s={...t.headers||{}};(i=>typeof i.writeHead=="function"&&typeof i.end=="function")(e)?(e.writeHead(t.statusCode,s),t.body===null||t.body===void 0?e.end():t.isRaw||typeof t.body=="string"?e.end(t.body):e.end(JSON.stringify(t.body))):(console.warn("Unexpected response object type without writeHead/end methods"),e.writeHead?.(t.statusCode,s),t.body===null||t.body===void 0?e.end?.():t.isRaw||typeof t.body=="string"?e.end?.(t.body):e.end?.(JSON.stringify(t.body)))}setupGracefulShutdown(e){let t=n=>{console.log("Shutting down MikroServe server..."),n&&console.error("Error:",n),this.cleanupShutdownHandlers(),e.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(n?1:0))})},s=()=>t(),r=()=>t(),i=n=>t(n),o=n=>t(n);this.shutdownHandlers=[s,r,i,o],process.on("SIGINT",s),process.on("SIGTERM",r),process.on("uncaughtException",i),process.on("unhandledRejection",o)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[e,t,s,r]=this.shutdownHandlers;process.removeListener("SIGINT",e),process.removeListener("SIGTERM",t),process.removeListener("uncaughtException",s),process.removeListener("unhandledRejection",r),this.shutdownHandlers=[]}}};function P(e){if(!e.deflate&&!e.inflate)throw new Error("Dictionary must provide either deflate or inflate mapping");if(e.deflate&&e.inflate)throw new Error("Dictionary should provide only one of deflate or inflate (not both). The inverse will be auto-generated.");return e.deflate?{deflate:e.deflate,inflate:F(e.deflate)}:{deflate:F(e.inflate),inflate:e.inflate}}function F(e){let t={};for(let[s,r]of Object.entries(e))t[r]=s;return t}function T(e,t){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>T(r,t));let s={};for(let[r,i]of Object.entries(e)){let o=t[r]||r;s[o]=T(i,t)}return s}function C(e){if(!e||typeof e!="string")throw new Error("Table name must be a non-empty string");if(e.length>255)throw new Error("Table name must not exceed 255 characters");if(e.includes("/")||e.includes("\\"))throw new Error("Table name must not contain path separators");if(e.includes(".."))throw new Error('Table name must not contain ".."');if(e.startsWith("."))throw new Error('Table name must not start with "."');if(e.includes("\0"))throw new Error("Table name must not contain null bytes");if(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(e.toUpperCase()))throw new Error(`Table name "${e}" is reserved by the filesystem`)}function R(e){if(e==null)throw new Error("Key must be defined");if(typeof e!="string")throw new Error("Key must be a string");if(e.length===0)throw new Error("Key must not be empty");if(e.length>1024)throw new Error("Key must not exceed 1024 characters");if(e.includes("\0"))throw new Error("Key must not contain null bytes")}function U(e){if(e===void 0)throw new Error("Value must not be undefined (use null instead)");let t=typeof e;if(t==="function")throw new Error("Value must be JSON-serializable: functions are not supported");if(t==="symbol")throw new Error("Value must be JSON-serializable: symbols are not supported");try{if(JSON.stringify(e)===void 0)throw new Error("Value must be JSON-serializable: value cannot be serialized")}catch(s){throw new Error(`Value must be JSON-serializable: ${s instanceof Error?s.message:String(s)}`)}}import{existsSync as H,mkdirSync as Ce,readdirSync as Se,openSync as xe,closeSync as Te}from"fs";import{readFile as Ee,writeFile as Pe,rename as Re,unlink as G,open as je}from"fs/promises";import{join as V,dirname as Ae}from"path";var N=class{data=new Map;databaseDirectory;dictionaries=new Map;useFsync;constructor(e){this.databaseDirectory=e.databaseDirectory,this.useFsync=e.durableWrites??!1,e.dictionaries&&Object.entries(e.dictionaries).forEach(([t,s])=>{let r=P(s);this.dictionaries.set(t,r)}),H(this.databaseDirectory)||Ce(this.databaseDirectory,{recursive:!0})}async start(){try{let e=Se(this.databaseDirectory);for(let t of e)!t.endsWith(".tmp")&&!t.startsWith(".")&&await this.loadTable(t)}catch(e){throw console.error("Failed to start database:",e),e}}async write(e,t,s,r,i){if(C(e),R(t),U(s),i&&!this.dictionaries.has(i))throw new Error(`Dictionary "${i}" not found. Available dictionaries: ${Array.from(this.dictionaries.keys()).join(", ")||"none"}`);try{this.data.has(e)||this.data.set(e,new Map);let o=this.data.get(e),a=(o.get(t)?.version||0)+1,c={value:s,version:a,timestamp:Date.now(),expiration:r||null,dictionaryName:i||void 0};return o.set(t,c),await this.persistTable(e),!0}catch(o){return console.error(`Write failed for ${e}:${t}:`,o),!1}}async get(e,t){C(e),t!==void 0&&R(t);try{this.data.has(e)||await this.loadTable(e);let s=this.data.get(e);if(!s)return t?void 0:[];if(t!==void 0){let o=s.get(t);if(!o)return;if(this.isExpired(o)){s.delete(t),await this.persistTable(e);return}return o.value}let r=[],i=[];for(let[o,n]of s.entries())this.isExpired(n)?i.push(o):r.push([o,n.value]);if(i.length>0){for(let o of i)s.delete(o);await this.persistTable(e)}return r}catch(s){return console.error(`Read failed for ${e}:${t}:`,s),t?void 0:[]}}async delete(e,t){C(e),R(t);try{this.data.has(e)||await this.loadTable(e);let s=this.data.get(e);if(!s||!s.has(t))return!1;let r=s.get(t);return r?this.isExpired(r)?(s.delete(t),await this.persistTable(e),!1):(s.delete(t),await this.persistTable(e),!0):!1}catch(s){return console.error(`Delete failed for ${e}:${t}:`,s),!1}}async getTableSize(e){C(e);try{this.data.has(e)||await this.loadTable(e);let t=this.data.get(e);if(!t)return 0;let s=0,r=[];for(let[i,o]of t.entries())this.isExpired(o)?r.push(i):s++;if(r.length>0){for(let i of r)t.delete(i);await this.persistTable(e)}return s}catch(t){return console.error(`Get table size failed for ${e}:`,t),0}}isExpired(e){return e.expiration===null?!1:Date.now()>e.expiration}async cleanupExpired(e){C(e);try{this.data.has(e)||await this.loadTable(e);let t=this.data.get(e);if(!t)return 0;let s=[];for(let[r,i]of t.entries())this.isExpired(i)&&s.push(r);for(let r of s)t.delete(r);return s.length>0&&await this.persistTable(e),s.length}catch(t){return console.error(`Cleanup failed for ${e}:`,t),0}}async cleanupAllExpired(){let e=0;for(let t of this.data.keys())e+=await this.cleanupExpired(t);return e}async deleteTable(e){C(e);try{this.data.delete(e);let t=V(this.databaseDirectory,e);return H(t)&&await G(t),!0}catch(t){return console.error(`Delete table failed for ${e}:`,t),!1}}listTables(){return Array.from(this.data.keys())}async flush(){try{let e=Array.from(this.data.keys()).map(t=>this.persistTable(t));await Promise.all(e)}catch(e){throw console.error("Flush failed:",e),e}}async close(){await this.flush()}addDictionary(e,t){let s=P(t);this.dictionaries.set(e,s)}removeDictionary(e){return this.dictionaries.delete(e)}listDictionaries(){return Array.from(this.dictionaries.keys())}async loadTable(e){let t=V(this.databaseDirectory,e);if(!H(t)){this.data.set(e,new Map);return}try{let s=await Ee(t);if(s.length===0){this.data.set(e,new Map);return}let r=this.deserializeTable(s);this.data.set(e,r)}catch(s){console.error(`Failed to load table ${e}:`,s),this.data.set(e,new Map)}}async persistTable(e){let t=this.data.get(e);if(!t)return;let s=this.serializeTable(t),r=V(this.databaseDirectory,e),i=`${r}.tmp.${Date.now()}.${Math.random().toString(36).substring(7)}`;try{if(await Pe(i,s),this.useFsync){let o=await je(i,"r+");try{await o.sync()}finally{await o.close()}}if(await Re(i,r),this.useFsync){let o=Ae(r),n=xe(o,"r");try{Te(n)}catch{}}}catch(o){try{await G(i)}catch{}throw o}}serializeTable(e){let t=Array.from(e.entries()).map(([s,r])=>{let i=r.dictionaryName?this.dictionaries.get(r.dictionaryName):void 0,o={d:i?T(r.value,i.deflate):r.value,v:r.version,t:r.timestamp,x:r.expiration};return r.dictionaryName&&(o.n=r.dictionaryName),[s,o]});return Buffer.from(JSON.stringify(t),"utf8")}deserializeTable(e){let s=JSON.parse(e.toString("utf8")).map(([r,i])=>{let o=i.n,n=o?this.dictionaries.get(o):void 0;return[r,{value:n?T(i.d,n.inflate):i.d,version:i.v,timestamp:i.t,expiration:i.x,dictionaryName:o||void 0}]});return new Map(s)}};import{join as fe}from"node:path";import{statSync as Fe}from"node:fs";var m=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(e.properties,t),i=this.compileErrors(s,r),o=this.isSuccessful(s,i);return{errors:i,success:o}}compileErrors(e,t){let s=e.filter(r=>r.success===!1);return[...t,...s].flatMap(r=>r)}isSuccessful(e,t){return e.every(s=>s.success===!0)&&t.length===0}validate(e,t,s=[],r=[]){let i=e?.additionalProperties??!0,o=e?.required||[];r=this.checkForRequiredKeysErrors(o,t,r),r=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),r,i);for(let n in e){let a=o.includes(n)&&n!=="required",c=e[n],l=t[n],f=c.additionalProperties??!0;a&&(r=this.checkForRequiredKeysErrors(c.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(n,l,c,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(c),r,f),this.handleNestedObject(l,c,s,r))}return{results:s,errors:r}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,s){if(!this.areRequiredKeysPresent(e,t)){let r=t?Object.keys(t):[],i=this.findNonOverlappingElements(e,r),o=i.length>0?`Missing the required key: '${i.join(", ")}'!`:`Missing values for required keys: '${r.filter(n=>!t[n]).join(", ")}'!`;s.push({key:"",value:t,success:!1,error:o})}return s}checkForDisallowedProperties(e,t,s,r){if(!r){let i=this.findNonOverlappingElements(e,t);i.length>0&&s.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${i.join(", ")}'!`})}return s}handleValidation(e,t,s,r){this.updatePropertyPath(e);let i=this.validateProperty(this.propertyPath,s,t);r.push(...i);let o=(a,c)=>{a.forEach(l=>{let f=this.validateProperty(this.propertyPath,c.items,l);r.push(...f)}),this.updatePropertyPath()},n=a=>{let c=Object.keys(a),l=this.propertyPath;c.forEach(f=>{if(this.updatePropertyPath(f,l),this.isArray(a[f])&&s[f]?.items!=null)o(a[f],s[f]);else{let u=this.validateProperty(this.propertyPath,s[f],a[f]);r.push(...u)}})};this.isArray(t)&&s.items!=null?o(t,s):this.isObject(t)?n(t):this.updatePropertyPath()}handleNestedObject(e,t,s,r){if(this.isObject(e)){let i=this.getNestedObjects(e);for(let o of i){let n=t[o],a=e[o];n&&typeof a=="object"&&this.validate(n,a,s,r)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(s=>!t.includes(s))}areRequiredKeysPresent(e,t=[]){return e.every(s=>Object.keys(t).includes(s)?this.isDefined(t[s]):!1)}validateProperty(e,t,s){return this.validateInput(t,s).map(i=>{let{success:o,error:n}=i;return{key:e,value:s,success:o,error:n??""}})}validateInput(e,t){if(e){let s=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],r=[];for(let i of s)i.condition()&&!i.validator()&&r.push({success:!1,error:i.error});return r}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(s=>{switch(s){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let s in e){let r=e[s];t.properties.required.push(s),Array.isArray(r)?t.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?t.properties[s]=this.generateNestedObjectSchema(r):t.properties[s]=this.generatePropertySchema(r)}return t}generateArraySchema(e){let t={type:"array"},s=e.filter(r=>r);if(s.length>0){let r=s[0];s.every(o=>typeof o==typeof r)?typeof r=="object"&&!Array.isArray(r)?t.items=this.generateNestedObjectSchema(r):t.items=this.generatePropertySchema(r):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let s in e){let r=e[s];t.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?t[s]=this.generateNestedObjectSchema(r):t[s]=this.generatePropertySchema(r)}return t}generatePropertySchema(e){let t=typeof e,s={type:t};return t==="string"&&(s.minLength=1),s}};async function j(e){return e.body||{}}function h(e,t="An error occurred"){let s=e?.message||e||t,r=e?.cause?.statusCode||e?.statusCode||400;return{message:s,status:r}}function W(e,t,s={}){let r=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let n=new Error("Unauthorized: User or roles missing");throw n.cause={statusCode:403},n}let i=e.roles.flatMap(n=>n?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(n=>i.includes(n)||i.includes("*")?!0:i.some(a=>{if(a.endsWith(".*")){let c=a.slice(0,-2);return n.startsWith(`${c}.`)}return!1}))){let n=new Error("Unauthorized");throw n.cause={statusCode:403},n}return!0}function J(e,t,s,r,i){let o=e.find(c=>c.service===t);if(!o){let c=new Error(`Function bindings do not include access to service: ${t}`);throw c.cause={statusCode:403},c}if(!o.permissions||o.permissions.length===0)return;for(let c of o.permissions)if(!(c.resource&&c.resource!==s)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(r)){if(c.targets&&c.targets.length>0){if(!i)return;if(!c.targets.includes(i))continue}return}}let n=i?`:${i}`:"",a=new Error(`Function bindings do not allow: ${t}.${s}.${r}${n}`);throw a.cause={statusCode:403},a}import{readFileSync as Me,existsSync as $e}from"node:fs";function S(){let e=process.env.MOLNOS_RUNTIME_CONFIG,t={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!e||!$e(e))return t;try{let s=Me(e,"utf-8");return JSON.parse(s)}catch(s){return console.error("[loadRuntimeConfig] Failed to load runtime config:",s),t}}async function p(e,t,s,r,i,o,n){if(!t)return null;let a=e.headers["x-molnos-service-token"];if(a){let f=S();if(f.internalServiceSecret&&a===f.internalServiceSecret)return null}let c=e.state.user;if(!c){let f=e.headers.authorization;if(!f){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let u=f.replace(/^Bearer\s+/i,"");if(c=await t.getUserFromToken(u),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}W(c,s,{});let l=e.headers["x-function-bindings"];if(l)try{let f=Array.isArray(l)?l[0]:l,u=JSON.parse(f);J(u,r,i,o,n)}catch(f){if(f.cause?.statusCode===403)throw f;let u=new Error("Invalid function bindings header");throw u.cause={statusCode:400},u}return c}var _={properties:{tableName:{type:"string",minLength:1},key:{type:"string"}},required:["tableName"],additionalProperties:!1};var Oe=new m(!0);async function K(e,t,s){try{let r=await j(e),i=Oe.test(_,r);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);let{tableName:o,key:n}=r;if(!o)return e.json("tableName is required",400);await p(e,s,"databases.table.get","databases","table","read",o);let a=await t.get(o,n);return a===void 0?e.json(null,404):e.json(a,200)}catch(r){let{message:i,status:o}=h(r,"Error getting table data");return e.json({error:i},o)}}var X={properties:{tableName:{type:"string",minLength:1},key:{type:"string"},value:{},expiration:{type:"number"},dictionaryName:{type:"string"}},required:["tableName"],additionalProperties:!1};var Le=new m(!0);async function Z(e,t,s){try{let r=await j(e),i=Le.test(X,r);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);let{tableName:o,key:n,value:a,expiration:c,dictionaryName:l}=r;if(!o||a===void 0)return e.json("tableName and value are required",400);await p(e,s,"databases.table.update","databases","table","write",o);let f=await t.write(o,n,a,c,l);return e.json(f,200)}catch(r){let{message:i,status:o}=h(r,"Error writing table data");return e.json({error:i},o)}}var Y={properties:{tableName:{type:"string",minLength:1},key:{type:"string",minLength:1}},required:["tableName","key"],additionalProperties:!1};var Ve=new m(!0);async function Q(e,t,s){try{let r=Ve.test(Y,e.query);if(!r.success)return e.json({error:"Invalid input",details:r.errors},400);let{tableName:i,key:o}=e.query;if(!i||!o)return e.json("tableName and key are required",400);await p(e,s,"databases.table.delete","databases","table","delete",i);let n=await t.delete(i,o);return e.json(n,200)}catch(r){let{message:i,status:o}=h(r,"Error deleting table item");return e.json({error:i},o)}}async function ee(e,t,s,r,i,o,n){try{await p(e,s,"databases.table.get","databases","table","read");let a=t.listTables(),c=e.query.context;if(c&&r){let f=e.headers.authorization?.replace(/^Bearer\s+/i,""),u=await r.listResourcesByType(c,"database",f);a=a.filter(d=>u.includes(d))}let l=await Promise.all(a.map(async f=>{let u=await t.getTableSize(f),d=o(i,f);return{name:f,items:u,size:n(d)}}));return e.json({tables:l},200)}catch(a){let{message:c,status:l}=h(a,"Error listing tables");return e.json({error:c},l)}}var v={properties:{tableName:{type:"string",minLength:1},context:{type:"string",minLength:1}},required:["tableName"],additionalProperties:!1};var De=new m(!0);async function te(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=De.test(v,{tableName:r});return i.success?(await p(e,s,"databases.table.create","databases","table","create",r),t.listTables().includes(r)?e.json({error:"Table already exists"},409):(await t.write(r,"__init__",null),await t.delete(r,"__init__"),e.json({success:!0,name:r,message:"Table created successfully"},201))):e.json({error:"Invalid input",details:i.errors},400)}catch(r){let{message:i,status:o}=h(r,"Error creating table");return e.json({error:i},o)}}var qe=new m(!0);async function re(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=qe.test(v,{tableName:r});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await p(e,s,"databases.table.delete","databases","table","delete",r),!t.listTables().includes(r))return e.json({error:"Table not found"},404);let n=await t.deleteTable(r);return e.json({success:n,name:r,message:"Table deleted successfully"},200)}catch(r){let{message:i,status:o}=h(r,"Error deleting table");return e.json({error:i},o)}}var ze=new m(!0);async function se(e,t,s,r,i,o){try{let n=e.params.tableName;if(!n)return e.json({error:"tableName is required"},400);let a=ze.test(v,{tableName:n});if(!a.success)return e.json({error:"Invalid input",details:a.errors},400);if(await p(e,s,"databases.table.get","databases","table","read",n),!t.listTables().includes(n))return e.json({error:"Table not found"},404);let l=await t.getTableSize(n),f=i(r,n);return e.json({name:n,items:l,size:o(f)},200)}catch(n){let{message:a,status:c}=h(n,"Error getting table info");return e.json({error:a},c)}}async function ie(e,t,s){try{if(!e.query.tableName)return e.json({error:"tableName is required"},400);let{tableName:r}=e.query;await p(e,s,"databases.table.get","databases","table","read",r);let i=await t.get(r),o=i?i.length:0;return e.json(o,200)}catch(r){let{message:i,status:o}=h(r,"Error getting table size");return e.json({error:i},o)}}var Be=new m(!0);async function ne(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=Be.test(v,{tableName:r});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await p(e,s,"databases.table.get","databases","table","read",r),!t.listTables().includes(r))return e.json({error:"Table not found"},404);let n=await t.get(r),a=n?Object.entries(n).map(([c,l])=>Array.isArray(l)&&l.length===2?{key:l[0],value:l[1]}:{key:c,value:l}):[];return e.json({items:a},200)}catch(r){let{message:i,status:o}=h(r,"Error getting table items");return e.json({error:i},o)}}function oe(e,t){let s={enabled:!1,requestsPerMinute:0};if(!t)return s;let r=t.services?.[e];return r||(t.global?t.global:s)}function ae(e,t){let s=e?.api?.port;if(!s)throw new Error('Missing "port" input when create API service!');let r=S(),i=e?.dataPath||r.molnos.dataPath,o=e?.api?.host||r.server.host,n=e?.identityApiUrl!==void 0?e.identityApiUrl:r.identity.apiUrl,a=e?.contextApiUrl!==void 0?e.contextApiUrl:r.context.apiUrl,c=e?.debug||!1,l;return t&&(l=oe(t,r.molnos.rateLimit)),{dataPath:i,api:{port:s,host:o},...n?{identityApiUrl:n}:{},...a?{contextApiUrl:a}:{},...l?{rateLimit:l}:{},debug:c}}var A=class{baseUrl;authToken;constructor(t,s){this.baseUrl=t.replace(/\/$/,""),this.authToken=s}async createCustomRole(t,s,r,i){let o=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:t,name:s,description:r,permissions:i})});if(!o.ok){let n=`Failed to create role: ${o.statusText}`;try{n=(await o.json()).error||n}catch{n=await o.text().catch(()=>o.statusText)||n}throw new Error(n)}}async updateRole(t,s){let r=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(s)});if(!r.ok){let i=await r.json();throw new Error(i.error||`Failed to update role: ${r.statusText}`)}}async deleteRole(t){let s=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete role: ${s.statusText}`)}}async addServiceAccount(t,s,r){let i=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:t,description:s,roles:r})});if(!i.ok){let n=`Failed to create service account: ${i.statusText}`;try{n=(await i.json()).error||n}catch{n=await i.text().catch(()=>i.statusText)||n}throw new Error(n)}let o=await i.json();return{id:o.id,apiKey:o.apiKey}}async deleteIdentity(t){let s=await fetch(`${this.baseUrl}/identity/service-accounts/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete service account: ${s.statusText}`)}}async getUserFromToken(t){try{let s=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return s.ok?await s.json():null}catch{return null}}getHeaders(){let t={"Content-Type":"application/json"};return this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),t}};function le(e){return e?new A(e):null}var M=class{baseUrl;constructor(t){this.baseUrl=t.replace(/\/$/,"")}async listResourcesByType(t,s,r){let i=`${this.baseUrl}/contexts/${encodeURIComponent(t)}`;try{let o={"Content-Type":"application/json"};r&&(o.Authorization=`Bearer ${r}`);let n=await fetch(i,{method:"GET",headers:o});if(!n.ok)return[];let c=(await n.json()).context?.resources||{};switch(s){case"function":return c.functions||[];case"database":return c.databases||[];case"storage":return c.storage||[];case"site":return c.sites||[];default:return[]}}catch{return[]}}};function ce(e){return e?new M(e):null}function ue(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**s).toFixed(1)} ${t[s]}`}function de(e,t){try{let s=fe(e,t);return Fe(s).size}catch{return 0}}async function Ue(e){let t=e.dataPath||"data",s=fe(t,"databases"),r=new N({databaseDirectory:s});await r.start();let i=le(e.identityApiUrl),o=ce(e.contextApiUrl),n=S(),a=new L({port:e.api.port||n.services.databases.port,host:e.api.host||n.services.databases.host,rateLimit:e.rateLimit||n.molnos.rateLimit.global});return a.get("/table",async l=>ie(l,r,i)),a.post("/get",async l=>K(l,r,i)),a.post("/write",async l=>Z(l,r,i)),a.delete("/delete",async l=>Q(l,r,i)),a.get("/tables",async l=>ee(l,r,i,o,s,de,ue)),a.post("/tables/:tableName",async l=>te(l,r,i)),a.delete("/tables/:tableName",async l=>re(l,r,i)),a.get("/tables/:tableName",async l=>se(l,r,i,s,de,ue)),a.get("/tables/:tableName/items",async l=>ne(l,r,i)),a.start()}if(import.meta.url===`file://${process.argv[1]}`){let e=S(),s=process.argv.slice(2).find(o=>o.startsWith("--port=")),r=s?parseInt(s.split("=")[1],10):e.services.databases.port,i=ae({api:{port:r}},"databases");Ue(i)}export{Ue as startServer};
10
+ `),s=e.indexOf(t);if(s===-1)return null;let r=e.subarray(0,s),i=e.subarray(s+4),o=r.toString("utf8").split(`\r
11
+ `),a="",d="",l,f;for(let u of o){let g=u.toLowerCase();if(g.startsWith("content-disposition:")){a=u.substring(20).trim();let v=a.match(/name="([^"]+)"/);v&&(d=v[1]);let w=a.match(/filename="([^"]+)"/);w&&(l=w[1])}else g.startsWith("content-type:")&&(f=u.substring(13).trim())}if(!d)return null;let c=i;return c.length>=2&&c[c.length-2]===13&&c[c.length-1]===10&&(c=c.subarray(0,c.length-2)),{disposition:a,name:d,filename:l,contentType:f,data:c}}import{readFileSync as T}from"fs";import N from"http";import Se from"http2";import xe from"https";var L=class{config;rateLimiter;router;shutdownHandlers=[];constructor(e){let t=new $(B(e||{})).get();t.debug&&console.log("Using configuration:",t),this.config=t,this.router=new z;let s=t.rateLimit.requestsPerMinute||E().rateLimit.requestsPerMinute;this.rateLimiter=new q(s,60),t.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(e){return this.router.use(e),this}get(e,...t){return this.router.get(e,...t),this}post(e,...t){return this.router.post(e,...t),this}put(e,...t){return this.router.put(e,...t),this}delete(e,...t){return this.router.delete(e,...t),this}patch(e,...t){return this.router.patch(e,...t),this}any(e,...t){return this.router.any(e,...t),this}options(e,...t){return this.router.options(e,...t),this}start(){let e=this.createServer(),{port:t,host:s}=this.config;return this.setupGracefulShutdown(e),e.listen(t,s,()=>{let r=e.address(),i=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${i}://${r.address!=="::"?r.address:"localhost"}:${r.port}`)}),e}createServer(){let e=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let t={key:T(this.config.sslKey),cert:T(this.config.sslCert),...this.config.sslCa?{ca:T(this.config.sslCa)}:{}};return Se.createSecureServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let t={key:T(this.config.sslKey),cert:T(this.config.sslCert),...this.config.sslCa?{ca:T(this.config.sslCa)}:{}};return xe.createServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}return N.createServer(e)}async rateLimitMiddleware(e,t){let s=e.req.socket.remoteAddress||"unknown";return e.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),e.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(s).toString()),e.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(s).toString()),this.rateLimiter.isAllowed(s)?t():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(e,t){let s=Date.now(),r=e.method||"UNKNOWN",i=e.url||"/unknown",n=this.config.debug;try{if(this.setCorsHeaders(t,e),this.setSecurityHeaders(t,this.config.useHttps),n&&console.log(`${r} ${i}`),e.method==="OPTIONS"){if(t instanceof N.ServerResponse)t.statusCode=204,t.end();else{let a=t;a.writeHead(204),a.end()}return}try{e.body=await this.parseBody(e)}catch(a){return n&&console.error("Body parsing error:",a.message),this.respond(t,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let o=await this.router.handle(e,t);return o?o._handled?void 0:this.respond(t,o):this.respond(t,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(o){return console.error("Server error:",o),this.respond(t,{statusCode:500,body:{error:"Internal Server Error",message:n?o.message:"An unexpected error occurred"}})}finally{n&&this.logDuration(s,r,i)}}logDuration(e,t,s){let r=Date.now()-e;console.log(`${t} ${s} completed in ${r}ms`)}async parseBody(e){return new Promise((t,s)=>{let r=[],i=0,n=this.config.maxBodySize,o=!1,a=null,d=this.config.debug,l=e.headers["content-type"]||"";d&&console.log("Content-Type:",l),this.config.requestTimeout>0&&(a=setTimeout(()=>{o||(o=!0,d&&console.log("Request timeout exceeded"),s(new Error("Request timeout")))},this.config.requestTimeout));let f=()=>{a&&(clearTimeout(a),a=null)};e.on("data",c=>{if(!o){if(i+=c.length,d&&console.log(`Received chunk: ${c.length} bytes, total size: ${i}`),i>n){o=!0,f(),d&&console.log(`Body size exceeded limit: ${i} > ${n}`),s(new Error("Request body too large"));return}r.push(c)}}),e.on("end",()=>{if(!o){o=!0,f(),d&&console.log(`Request body complete: ${i} bytes`);try{if(r.length>0){let c=Buffer.concat(r);if(l.includes("application/json"))try{let u=c.toString("utf8");t(JSON.parse(u))}catch(u){s(new Error(`Invalid JSON in request body: ${u.message}`))}else if(l.includes("application/x-www-form-urlencoded")){let u=c.toString("utf8"),g={};new URLSearchParams(u).forEach((v,w)=>{g[w]=v}),t(g)}else if(l.includes("multipart/form-data"))try{let u=F(c,l);t(u)}catch(u){s(new Error(`Invalid multipart form data: ${u.message}`))}else this.isBinaryContentType(l)?t(c):t(c.toString("utf8"))}else t({})}catch(c){s(new Error(`Invalid request body: ${c}`))}}}),e.on("error",c=>{o||(o=!0,f(),s(new Error(`Error reading request body: ${c.message}`)))}),e.on("close",()=>{f()})})}isBinaryContentType(e){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(s=>e.includes(s))}setCorsHeaders(e,t){let s=t.headers.origin,{allowedDomains:r=["*"]}=this.config;!s||r.length===0||r.includes("*")?e.setHeader("Access-Control-Allow-Origin","*"):r.includes(s)&&(e.setHeader("Access-Control-Allow-Origin",s),e.setHeader("Vary","Origin")),e.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(e,t=!1){let s={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((t||this.config.useHttp2)&&(s["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),e instanceof N.ServerResponse)Object.entries(s).forEach(([r,i])=>{e.setHeader(r,i)});else{let r=e;Object.entries(s).forEach(([i,n])=>{r.setHeader(i,n)})}}respond(e,t){let s={...t.headers||{}};(i=>typeof i.writeHead=="function"&&typeof i.end=="function")(e)?(e.writeHead(t.statusCode,s),t.body===null||t.body===void 0?e.end():t.isRaw||typeof t.body=="string"?e.end(t.body):e.end(JSON.stringify(t.body))):(console.warn("Unexpected response object type without writeHead/end methods"),e.writeHead?.(t.statusCode,s),t.body===null||t.body===void 0?e.end?.():t.isRaw||typeof t.body=="string"?e.end?.(t.body):e.end?.(JSON.stringify(t.body)))}setupGracefulShutdown(e){let t=o=>{console.log("Shutting down MikroServe server..."),o&&console.error("Error:",o),this.cleanupShutdownHandlers(),e.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(o?1:0))})},s=()=>t(),r=()=>t(),i=o=>t(o),n=o=>t(o);this.shutdownHandlers=[s,r,i,n],process.on("SIGINT",s),process.on("SIGTERM",r),process.on("uncaughtException",i),process.on("unhandledRejection",n)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[e,t,s,r]=this.shutdownHandlers;process.removeListener("SIGINT",e),process.removeListener("SIGTERM",t),process.removeListener("uncaughtException",s),process.removeListener("unhandledRejection",r),this.shutdownHandlers=[]}}};function R(e){if(!e.deflate&&!e.inflate)throw new Error("Dictionary must provide either deflate or inflate mapping");if(e.deflate&&e.inflate)throw new Error("Dictionary should provide only one of deflate or inflate (not both). The inverse will be auto-generated.");return e.deflate?{deflate:e.deflate,inflate:U(e.deflate)}:{deflate:U(e.inflate),inflate:e.inflate}}function U(e){let t={};for(let[s,r]of Object.entries(e))t[r]=s;return t}function P(e,t){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>P(r,t));let s={};for(let[r,i]of Object.entries(e)){let n=t[r]||r;s[n]=P(i,t)}return s}function S(e){if(!e||typeof e!="string")throw new Error("Table name must be a non-empty string");if(e.length>255)throw new Error("Table name must not exceed 255 characters");if(e.includes("/")||e.includes("\\"))throw new Error("Table name must not contain path separators");if(e.includes(".."))throw new Error('Table name must not contain ".."');if(e.startsWith("."))throw new Error('Table name must not start with "."');if(e.includes("\0"))throw new Error("Table name must not contain null bytes");if(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(e.toUpperCase()))throw new Error(`Table name "${e}" is reserved by the filesystem`)}function j(e){if(e==null)throw new Error("Key must be defined");if(typeof e!="string")throw new Error("Key must be a string");if(e.length===0)throw new Error("Key must not be empty");if(e.length>1024)throw new Error("Key must not exceed 1024 characters");if(e.includes("\0"))throw new Error("Key must not contain null bytes")}function G(e){if(e===void 0)throw new Error("Value must not be undefined (use null instead)");let t=typeof e;if(t==="function")throw new Error("Value must be JSON-serializable: functions are not supported");if(t==="symbol")throw new Error("Value must be JSON-serializable: symbols are not supported");try{if(JSON.stringify(e)===void 0)throw new Error("Value must be JSON-serializable: value cannot be serialized")}catch(s){throw new Error(`Value must be JSON-serializable: ${s instanceof Error?s.message:String(s)}`)}}import{existsSync as H,mkdirSync as Te,readdirSync as Pe,openSync as Ee,closeSync as Re}from"fs";import{readFile as je,writeFile as Ie,rename as Me,unlink as _,open as Oe}from"fs/promises";import{join as V,dirname as Ae}from"path";var D=class{data=new Map;databaseDirectory;dictionaries=new Map;useFsync;constructor(e){this.databaseDirectory=e.databaseDirectory,this.useFsync=e.durableWrites??!1,e.dictionaries&&Object.entries(e.dictionaries).forEach(([t,s])=>{let r=R(s);this.dictionaries.set(t,r)}),H(this.databaseDirectory)||Te(this.databaseDirectory,{recursive:!0})}async start(){try{let e=Pe(this.databaseDirectory);for(let t of e)!t.endsWith(".tmp")&&!t.startsWith(".")&&await this.loadTable(t)}catch(e){throw console.error("Failed to start database:",e),e}}async write(e,t,s,r,i){if(S(e),j(t),G(s),i&&!this.dictionaries.has(i))throw new Error(`Dictionary "${i}" not found. Available dictionaries: ${Array.from(this.dictionaries.keys()).join(", ")||"none"}`);try{this.data.has(e)||this.data.set(e,new Map);let n=this.data.get(e),a=(n.get(t)?.version||0)+1,d={value:s,version:a,timestamp:Date.now(),expiration:r||null,dictionaryName:i||void 0};return n.set(t,d),await this.persistTable(e),!0}catch(n){return console.error(`Write failed for ${e}:${t}:`,n),!1}}async get(e,t){S(e),t!==void 0&&j(t);try{this.data.has(e)||await this.loadTable(e);let s=this.data.get(e);if(!s)return t?void 0:[];if(t!==void 0){let n=s.get(t);if(!n)return;if(this.isExpired(n)){s.delete(t),await this.persistTable(e);return}return n.value}let r=[],i=[];for(let[n,o]of s.entries())this.isExpired(o)?i.push(n):r.push([n,o.value]);if(i.length>0){for(let n of i)s.delete(n);await this.persistTable(e)}return r}catch(s){return console.error(`Read failed for ${e}:${t}:`,s),t?void 0:[]}}async delete(e,t){S(e),j(t);try{this.data.has(e)||await this.loadTable(e);let s=this.data.get(e);if(!s||!s.has(t))return!1;let r=s.get(t);return r?this.isExpired(r)?(s.delete(t),await this.persistTable(e),!1):(s.delete(t),await this.persistTable(e),!0):!1}catch(s){return console.error(`Delete failed for ${e}:${t}:`,s),!1}}async getTableSize(e){S(e);try{this.data.has(e)||await this.loadTable(e);let t=this.data.get(e);if(!t)return 0;let s=0,r=[];for(let[i,n]of t.entries())this.isExpired(n)?r.push(i):s++;if(r.length>0){for(let i of r)t.delete(i);await this.persistTable(e)}return s}catch(t){return console.error(`Get table size failed for ${e}:`,t),0}}isExpired(e){return e.expiration===null?!1:Date.now()>e.expiration}async cleanupExpired(e){S(e);try{this.data.has(e)||await this.loadTable(e);let t=this.data.get(e);if(!t)return 0;let s=[];for(let[r,i]of t.entries())this.isExpired(i)&&s.push(r);for(let r of s)t.delete(r);return s.length>0&&await this.persistTable(e),s.length}catch(t){return console.error(`Cleanup failed for ${e}:`,t),0}}async cleanupAllExpired(){let e=0;for(let t of this.data.keys())e+=await this.cleanupExpired(t);return e}async deleteTable(e){S(e);try{this.data.delete(e);let t=V(this.databaseDirectory,e);return H(t)&&await _(t),!0}catch(t){return console.error(`Delete table failed for ${e}:`,t),!1}}listTables(){return Array.from(this.data.keys())}async flush(){try{let e=Array.from(this.data.keys()).map(t=>this.persistTable(t));await Promise.all(e)}catch(e){throw console.error("Flush failed:",e),e}}async close(){await this.flush()}addDictionary(e,t){let s=R(t);this.dictionaries.set(e,s)}removeDictionary(e){return this.dictionaries.delete(e)}listDictionaries(){return Array.from(this.dictionaries.keys())}async loadTable(e){let t=V(this.databaseDirectory,e);if(!H(t)){this.data.set(e,new Map);return}try{let s=await je(t);if(s.length===0){this.data.set(e,new Map);return}let r=this.deserializeTable(s);this.data.set(e,r)}catch(s){console.error(`Failed to load table ${e}:`,s),this.data.set(e,new Map)}}async persistTable(e){let t=this.data.get(e);if(!t)return;let s=this.serializeTable(t),r=V(this.databaseDirectory,e),i=`${r}.tmp.${Date.now()}.${Math.random().toString(36).substring(7)}`;try{if(await Ie(i,s),this.useFsync){let n=await Oe(i,"r+");try{await n.sync()}finally{await n.close()}}if(await Me(i,r),this.useFsync){let n=Ae(r),o=Ee(n,"r");try{Re(o)}catch{}}}catch(n){try{await _(i)}catch{}throw n}}serializeTable(e){let t=Array.from(e.entries()).map(([s,r])=>{let i=r.dictionaryName?this.dictionaries.get(r.dictionaryName):void 0,n={d:i?P(r.value,i.deflate):r.value,v:r.version,t:r.timestamp,x:r.expiration};return r.dictionaryName&&(n.n=r.dictionaryName),[s,n]});return Buffer.from(JSON.stringify(t),"utf8")}deserializeTable(e){let s=JSON.parse(e.toString("utf8")).map(([r,i])=>{let n=i.n,o=n?this.dictionaries.get(n):void 0;return[r,{value:o?P(i.d,o.inflate):i.d,version:i.v,timestamp:i.t,expiration:i.x,dictionaryName:n||void 0}]});return new Map(s)}};import{join as me}from"node:path";import{statSync as Ke}from"node:fs";var y=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(e.properties,t),i=this.compileErrors(s,r),n=this.isSuccessful(s,i);return{errors:i,success:n}}compileErrors(e,t){let s=e.filter(r=>r.success===!1);return[...t,...s].flatMap(r=>r)}isSuccessful(e,t){return e.every(s=>s.success===!0)&&t.length===0}validate(e,t,s=[],r=[]){let i=e?.additionalProperties??!0,n=e?.required||[];r=this.checkForRequiredKeysErrors(n,t,r),r=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),r,i);for(let o in e){let a=n.includes(o)&&o!=="required",d=e[o],l=t[o],f=d.additionalProperties??!0;a&&(r=this.checkForRequiredKeysErrors(d.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(o,l,d,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(d),r,f),this.handleNestedObject(l,d,s,r))}return{results:s,errors:r}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,s){if(!this.areRequiredKeysPresent(e,t)){let r=t?Object.keys(t):[],i=this.findNonOverlappingElements(e,r),n=i.length>0?`Missing the required key: '${i.join(", ")}'!`:`Missing values for required keys: '${r.filter(o=>!t[o]).join(", ")}'!`;s.push({key:"",value:t,success:!1,error:n})}return s}checkForDisallowedProperties(e,t,s,r){if(!r){let i=this.findNonOverlappingElements(e,t);i.length>0&&s.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${i.join(", ")}'!`})}return s}handleValidation(e,t,s,r){this.updatePropertyPath(e);let i=this.validateProperty(this.propertyPath,s,t);r.push(...i);let n=(a,d)=>{a.forEach(l=>{let f=this.validateProperty(this.propertyPath,d.items,l);r.push(...f)}),this.updatePropertyPath()},o=a=>{let d=Object.keys(a),l=this.propertyPath;d.forEach(f=>{if(this.updatePropertyPath(f,l),this.isArray(a[f])&&s[f]?.items!=null)n(a[f],s[f]);else{let c=this.validateProperty(this.propertyPath,s[f],a[f]);r.push(...c)}})};this.isArray(t)&&s.items!=null?n(t,s):this.isObject(t)?o(t):this.updatePropertyPath()}handleNestedObject(e,t,s,r){if(this.isObject(e)){let i=this.getNestedObjects(e);for(let n of i){let o=t[n],a=e[n];o&&typeof a=="object"&&this.validate(o,a,s,r)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(s=>!t.includes(s))}areRequiredKeysPresent(e,t=[]){return e.every(s=>Object.keys(t).includes(s)?this.isDefined(t[s]):!1)}validateProperty(e,t,s){return this.validateInput(t,s).map(i=>{let{success:n,error:o}=i;return{key:e,value:s,success:n,error:o??""}})}validateInput(e,t){if(e){let s=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],r=[];for(let i of s)i.condition()&&!i.validator()&&r.push({success:!1,error:i.error});return r}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(s=>{switch(s){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let s in e){let r=e[s];t.properties.required.push(s),Array.isArray(r)?t.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?t.properties[s]=this.generateNestedObjectSchema(r):t.properties[s]=this.generatePropertySchema(r)}return t}generateArraySchema(e){let t={type:"array"},s=e.filter(r=>r);if(s.length>0){let r=s[0];s.every(n=>typeof n==typeof r)?typeof r=="object"&&!Array.isArray(r)?t.items=this.generateNestedObjectSchema(r):t.items=this.generatePropertySchema(r):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let s in e){let r=e[s];t.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?t[s]=this.generateNestedObjectSchema(r):t[s]=this.generatePropertySchema(r)}return t}generatePropertySchema(e){let t=typeof e,s={type:t};return t==="string"&&(s.minLength=1),s}};async function I(e){return e.body||{}}function h(e,t="An error occurred"){let s=e?.message||e||t,r=e?.cause?.statusCode||e?.statusCode||400;return{message:s,status:r}}function J(e,t,s={}){let r=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let o=new Error("Unauthorized: User or roles missing");throw o.cause={statusCode:403},o}let i=e.roles.flatMap(o=>o?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(o=>i.some(a=>$e(a,o)))){let o=new Error("Unauthorized");throw o.cause={statusCode:403},o}return!0}function $e(e,t){if(e==="*"||e===t)return!0;if(!e.includes("*"))return!1;let s=e.split("*").map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${s}$`).test(t)}function K(e,t,s,r,i){let n=e.find(d=>d.service===t);if(!n){let d=new Error(`Function bindings do not include access to service: ${t}`);throw d.cause={statusCode:403},d}if(!n.permissions||n.permissions.length===0)return;for(let d of n.permissions)if(!(d.resource&&d.resource!==s)){if(!d.resource||!d.actions||d.actions.length===0)return;if(d.actions.includes(r)&&!(d.targets&&d.targets.length>0&&(!i||!d.targets.includes(i)&&!d.targets.includes("*"))))return}let o=i?`:${i}`:"",a=new Error(`Function bindings do not allow: ${t}.${s}.${r}${o}`);throw a.cause={statusCode:403},a}import{readFileSync as ke,existsSync as Ne}from"node:fs";function x(){let e=process.env.MOLNOS_RUNTIME_CONFIG,t={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!e||!Ne(e))return t;try{let s=ke(e,"utf-8");return JSON.parse(s)}catch(s){return console.error("[loadRuntimeConfig] Failed to load runtime config:",s),t}}async function m(e,t,s,r,i,n,o){if(!t)return null;let a=e.headers["x-molnos-service-token"];if(a){let f=x();if(f.internalServiceSecret&&a===f.internalServiceSecret)return null}let d=e.state.user;if(!d){let f=e.headers.authorization;if(!f){let u=new Error("Unauthorized: No authentication provided");throw u.cause={statusCode:401},u}let c=f.replace(/^Bearer\s+/i,"");if(d=await t.getUserFromToken(c),!d){let u=new Error("Unauthorized: Invalid token");throw u.cause={statusCode:401},u}}J(d,s,{});let l=e.headers["x-function-bindings"];if(l)try{let f=Array.isArray(l)?l[0]:l,c=JSON.parse(f);K(c,r,i,n,o)}catch(f){if(f.cause?.statusCode===403)throw f;let c=new Error("Invalid function bindings header");throw c.cause={statusCode:400},c}return d}var p={ai:{generation:{generate:"ai.generation.generate",read:"ai.generation.read",apply:"ai.generation.apply",discard:"ai.generation.discard",delete:"ai.generation.delete"}},applications:{application:{create:"applications.application.create",read:"applications.application.read",list:"applications.application.list",update:"applications.application.update",delete:"applications.application.delete"}},contexts:{context:{create:"contexts.context.create",get:"contexts.context.get",update:"contexts.context.update",delete:"contexts.context.delete",deleteResources:"contexts.context.delete-resources"}},databases:{table:{create:"databases.table.create",get:"databases.table.get",update:"databases.table.update",delete:"databases.table.delete"}},functions:{function:{create:"functions.function.create",get:"functions.function.get",update:"functions.function.update",delete:"functions.function.delete",execute:"functions.function.execute"}},iac:{config:{create:"iac.config.create",get:"iac.config.get"}},identity:{identities:{get:"identity.identities.get"},user:{create:"identity.user.create",get:"identity.user.get",update:"identity.user.update",delete:"identity.user.delete"},role:{create:"identity.role.create",get:"identity.role.get",update:"identity.role.update",delete:"identity.role.delete"},serviceAccount:{create:"identity.service-account.create",get:"identity.service-account.get",update:"identity.service-account.update",delete:"identity.service-account.delete"}},management:{service:{create:"management.service.create",get:"management.service.get",update:"management.service.update",delete:"management.service.delete",start:"management.service.start",stop:"management.service.stop"},services:{get:"management.services.get"}},observability:{event:{create:"observability.event.create",read:"observability.event.read",delete:"observability.event.delete"},stats:{read:"observability.stats.read"},buffer:{write:"observability.buffer.write"},metrics:{read:"observability.metrics.read"}},schemas:{schema:{create:"schemas.schema.create",read:"schemas.schema.read",list:"schemas.schema.list",update:"schemas.schema.update",delete:"schemas.schema.delete"}},sites:{project:{create:"sites.project.create",list:"sites.project.list",delete:"sites.project.delete",download:"sites.project.download"}},storage:{bucket:{create:"storage.bucket.create",read:"storage.bucket.read",update:"storage.bucket.update",delete:"storage.bucket.delete",list:"storage.bucket.list"},object:{write:"storage.object.write",read:"storage.object.read",delete:"storage.object.delete",list:"storage.object.list"}}};function W(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let s of Object.values(e))W(s,t)}var X=[];W(p,X);var Le=[...new Set(X)],fr=Object.freeze(Le);var Y={properties:{tableName:{type:"string",minLength:1},key:{type:"string"}},required:["tableName"],additionalProperties:!1};var Ve=new y(!0);async function Z(e,t,s){try{let r=await I(e),i=Ve.test(Y,r);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);let{tableName:n,key:o}=r;if(!n)return e.json("tableName is required",400);await m(e,s,p.databases.table.get,"databases","table","read",n);let a=await t.get(n,o);return a===void 0?e.json(null,404):e.json(a,200)}catch(r){let{message:i,status:n}=h(r,"Error getting table data");return e.json({error:i},n)}}var Q={properties:{tableName:{type:"string",minLength:1},key:{type:"string"},value:{},expiration:{type:"number"},dictionaryName:{type:"string"}},required:["tableName"],additionalProperties:!1};var qe=new y(!0);async function ee(e,t,s){try{let r=await I(e),i=qe.test(Q,r);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);let{tableName:n,key:o,value:a,expiration:d,dictionaryName:l}=r;if(!n||a===void 0)return e.json("tableName and value are required",400);await m(e,s,p.databases.table.update,"databases","table","write",n);let f=await t.write(n,o,a,d,l);return e.json(f,200)}catch(r){let{message:i,status:n}=h(r,"Error writing table data");return e.json({error:i},n)}}var te={properties:{tableName:{type:"string",minLength:1},key:{type:"string",minLength:1}},required:["tableName","key"],additionalProperties:!1};var Be=new y(!0);async function re(e,t,s){try{let r=Be.test(te,e.query);if(!r.success)return e.json({error:"Invalid input",details:r.errors},400);let{tableName:i,key:n}=e.query;if(!i||!n)return e.json("tableName and key are required",400);await m(e,s,p.databases.table.delete,"databases","table","delete",i);let o=await t.delete(i,n);return e.json(o,200)}catch(r){let{message:i,status:n}=h(r,"Error deleting table item");return e.json({error:i},n)}}async function se(e,t,s,r,i,n,o){try{await m(e,s,p.databases.table.get,"databases","table","read");let a=t.listTables(),d=e.query.context;if(d&&r){let f=e.headers.authorization?.replace(/^Bearer\s+/i,""),c=await r.listResourcesByType(d,"database",f);a=a.filter(u=>c.includes(u))}let l=await Promise.all(a.map(async f=>{let c=await t.getTableSize(f),u=n(i,f);return{name:f,items:c,size:o(u)}}));return e.json({tables:l},200)}catch(a){let{message:d,status:l}=h(a,"Error listing tables");return e.json({error:d},l)}}var C={properties:{tableName:{type:"string",minLength:1},context:{type:"string",minLength:1}},required:["tableName"],additionalProperties:!1};var Ue=new y(!0);async function ie(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=Ue.test(C,{tableName:r});return i.success?(await m(e,s,p.databases.table.create,"databases","table","create",r),t.listTables().includes(r)?e.json({error:"Table already exists"},409):(await t.write(r,"__init__",null),await t.delete(r,"__init__"),e.json({success:!0,name:r,message:"Table created successfully"},201))):e.json({error:"Invalid input",details:i.errors},400)}catch(r){let{message:i,status:n}=h(r,"Error creating table");return e.json({error:i},n)}}var Ge=new y(!0);async function ne(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=Ge.test(C,{tableName:r});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await m(e,s,p.databases.table.delete,"databases","table","delete",r),!t.listTables().includes(r))return e.json({error:"Table not found"},404);let o=await t.deleteTable(r);return e.json({success:o,name:r,message:"Table deleted successfully"},200)}catch(r){let{message:i,status:n}=h(r,"Error deleting table");return e.json({error:i},n)}}var _e=new y(!0);async function oe(e,t,s,r,i,n){try{let o=e.params.tableName;if(!o)return e.json({error:"tableName is required"},400);let a=_e.test(C,{tableName:o});if(!a.success)return e.json({error:"Invalid input",details:a.errors},400);if(await m(e,s,p.databases.table.get,"databases","table","read",o),!t.listTables().includes(o))return e.json({error:"Table not found"},404);let l=await t.getTableSize(o),f=i(r,o);return e.json({name:o,items:l,size:n(f)},200)}catch(o){let{message:a,status:d}=h(o,"Error getting table info");return e.json({error:a},d)}}async function ae(e,t,s){try{if(!e.query.tableName)return e.json({error:"tableName is required"},400);let{tableName:r}=e.query;await m(e,s,p.databases.table.get,"databases","table","read",r);let i=await t.get(r),n=i?i.length:0;return e.json(n,200)}catch(r){let{message:i,status:n}=h(r,"Error getting table size");return e.json({error:i},n)}}var Je=new y(!0);async function le(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=Je.test(C,{tableName:r});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await m(e,s,p.databases.table.get,"databases","table","read",r),!t.listTables().includes(r))return e.json({error:"Table not found"},404);let o=await t.get(r),a=o?Object.entries(o).map(([d,l])=>Array.isArray(l)&&l.length===2?{key:l[0],value:l[1]}:{key:d,value:l}):[];return e.json({items:a},200)}catch(r){let{message:i,status:n}=h(r,"Error getting table items");return e.json({error:i},n)}}function ce(e,t){let s={enabled:!1,requestsPerMinute:0};if(!t)return s;let r=t.services?.[e];return r||(t.global?t.global:s)}function de(e,t){let s=e?.api?.port;if(!s)throw new Error('Missing "port" input when create API service!');let r=x(),i=e?.dataPath||r.molnos.dataPath,n=e?.api?.host||r.server.host,o=e?.identityApiUrl!==void 0?e.identityApiUrl:r.identity.apiUrl,a=e?.contextApiUrl!==void 0?e.contextApiUrl:r.context.apiUrl,d=e?.debug||!1,l;return t&&(l=ce(t,r.molnos.rateLimit)),{dataPath:i,api:{port:s,host:n},...o?{identityApiUrl:o}:{},...a?{contextApiUrl:a}:{},...l?{rateLimit:l}:{},debug:d}}var M=class{baseUrl;authToken;constructor(t,s){this.baseUrl=t.replace(/\/$/,""),this.authToken=s}async createCustomRole(t,s,r,i){let n=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:t,name:s,description:r,permissions:i})});if(!n.ok){let o=`Failed to create role: ${n.statusText}`;try{o=(await n.json()).error||o}catch{o=await n.text().catch(()=>n.statusText)||o}throw new Error(o)}}async updateRole(t,s){let r=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(s)});if(!r.ok){let i=await r.json();throw new Error(i.error||`Failed to update role: ${r.statusText}`)}}async deleteRole(t){let s=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete role: ${s.statusText}`)}}async addServiceAccount(t,s,r){let i=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:t,description:s,roles:r})});if(!i.ok){let o=`Failed to create service account: ${i.statusText}`;try{o=(await i.json()).error||o}catch{o=await i.text().catch(()=>i.statusText)||o}throw new Error(o)}let n=await i.json();return{id:n.id,apiKey:n.apiKey}}async deleteIdentity(t){let s=await fetch(`${this.baseUrl}/identity/service-accounts/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete service account: ${s.statusText}`)}}async getUserFromToken(t){try{let s=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return s.ok?await s.json():null}catch{return null}}getHeaders(){let t={"Content-Type":"application/json"};return this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),t}};function ue(e){return e?new M(e):null}var O=class{baseUrl;constructor(t){this.baseUrl=t.replace(/\/$/,"")}async listResourcesByType(t,s,r){let i=`${this.baseUrl}/contexts/${encodeURIComponent(t)}`;try{let n={"Content-Type":"application/json"};r&&(n.Authorization=`Bearer ${r}`);let o=await fetch(i,{method:"GET",headers:n});if(!o.ok)return[];let d=(await o.json()).context?.resources||{};switch(s){case"function":return d.functions||[];case"database":return d.databases||[];case"storage":return d.storage||[];case"site":return d.sites||[];default:return[]}}catch{return[]}}};function fe(e){return e?new O(e):null}function pe(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**s).toFixed(1)} ${t[s]}`}function he(e,t){try{let s=me(e,t);return Ke(s).size}catch{return 0}}async function We(e){let t=e.dataPath||"data",s=me(t,"databases"),r=new D({databaseDirectory:s});await r.start();let i=ue(e.identityApiUrl),n=fe(e.contextApiUrl),o=x(),a=new L({port:e.api.port||o.services.databases.port,host:e.api.host||o.services.databases.host,rateLimit:e.rateLimit||o.molnos.rateLimit.global});return a.get("/table",async l=>ae(l,r,i)),a.post("/get",async l=>Z(l,r,i)),a.post("/write",async l=>ee(l,r,i)),a.delete("/delete",async l=>re(l,r,i)),a.get("/tables",async l=>se(l,r,i,n,s,he,pe)),a.post("/tables/:tableName",async l=>ie(l,r,i)),a.delete("/tables/:tableName",async l=>ne(l,r,i)),a.get("/tables/:tableName",async l=>oe(l,r,i,s,he,pe)),a.get("/tables/:tableName/items",async l=>le(l,r,i)),a.start()}if(import.meta.url===`file://${process.argv[1]}`){let e=x(),s=process.argv.slice(2).find(n=>n.startsWith("--port=")),r=s?parseInt(s.split("=")[1],10):e.services.databases.port,i=de({api:{port:r}},"databases");We(i)}export{We as startServer};
@@ -1,14 +1,14 @@
1
1
  // MolnOS Core - See LICENSE file for copyright and license details.
2
- import{existsSync as q}from"node:fs";import{join as k}from"node:path";import{mkdir as Ye,writeFile as se,readFile as Pe,unlink as Ke}from"node:fs/promises";import{pathToFileURL as Te}from"node:url";var oe=class{requests=new Map;limit;windowMs;constructor(t=100,e=60){this.limit=t,this.windowMs=e*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return(!n||n.resetTime<e)&&(n={count:0,resetTime:e+this.windowMs},this.requests.set(r,n)),n.count++,n.count<=this.limit}getRemainingRequests(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return!n||n.resetTime<e?this.limit:Math.max(0,this.limit-n.count)}getResetTime(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return!n||n.resetTime<e?Math.floor((e+this.windowMs)/1e3):Math.floor(n.resetTime/1e3)}cleanup(){let t=Date.now();for(let[e,r]of this.requests.entries())r.resetTime<t&&this.requests.delete(e)}};import{URL as Ie}from"url";var ae=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(t){return this.globalMiddlewares.push(t),this}get(t,...e){let r=e.pop();return this.register("GET",t,r,e)}post(t,...e){let r=e.pop();return this.register("POST",t,r,e)}put(t,...e){let r=e.pop();return this.register("PUT",t,r,e)}delete(t,...e){let r=e.pop();return this.register("DELETE",t,r,e)}patch(t,...e){let r=e.pop();return this.register("PATCH",t,r,e)}any(t,...e){let r=e.pop(),n=e;return this.register("GET",t,r,n),this.register("POST",t,r,n),this.register("PUT",t,r,n),this.register("DELETE",t,r,n),this.register("PATCH",t,r,n),this.register("OPTIONS",t,r,n),this}options(t,...e){let r=e.pop();return this.register("OPTIONS",t,r,e)}match(t,e){for(let r of this.routes){if(r.method!==t)continue;let n=this.pathPatterns.get(r.path);if(!n)continue;let s=n.pattern.exec(e);if(!s)continue;let i={};return n.paramNames.forEach((o,a)=>{i[o]=s[a+1]||""}),{route:r,params:i}}return null}async handle(t,e){let r=t.method||"GET",n=new Ie(t.url||"/",`http://${t.headers.host}`),s=n.pathname,i=this.match(r,s);if(!i)return null;let{route:o,params:a}=i,c={};n.searchParams.forEach((u,d)=>{c[d]=u});let f={req:t,res:e,params:a,query:c,body:t.body||{},headers:t.headers,path:s,state:{},raw:()=>e,binary:(u,d="application/octet-stream",p=200)=>({statusCode:p,body:u,headers:{"Content-Type":d,"Content-Length":u.length.toString()},isRaw:!0}),text:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/plain"}}),form:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/json"}}),html:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/html"}}),redirect:(u,d=302)=>({statusCode:d,body:null,headers:{Location:u}}),status:function(u){return{raw:()=>e,binary:(d,p="application/octet-stream")=>({statusCode:u,body:d,headers:{"Content-Type":p,"Content-Length":d.length.toString()},isRaw:!0}),text:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/plain"}}),json:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/json"}}),html:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/html"}}),form:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(d,p=302)=>({statusCode:p,body:null,headers:{Location:d}}),status:d=>this.status(d)}}},l=[...this.globalMiddlewares,...o.middlewares];return this.executeMiddlewareChain(f,l,o.handler)}register(t,e,r,n=[]){return this.routes.push({method:t,path:e,handler:r,middlewares:n}),this.pathPatterns.set(e,this.createPathPattern(e)),this}createPathPattern(t){let e=[],r=t.replace(/\/:[^/]+/g,n=>{let s=n.slice(2);return e.push(s),"/([^/]+)"});return r.endsWith("/*")?(r=`${r.slice(0,-2)}(?:/(.*))?`,e.push("wildcard")):r=r.replace(/\/$/,"/?"),{pattern:new RegExp(`^${r}$`),paramNames:e}}async executeMiddlewareChain(t,e,r){let n=0,s=async()=>{if(n<e.length){let i=e[n++];return i(t,s)}return r(t)};return s()}};var M=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:Fe(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function Fe(t){return t==="true"||t===!0}var V=class extends Error{constructor(t){super(t),this.name="ValidationError",this.message=t||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as Ae,readFileSync as Re}from"node:fs";var z=class{config={};options=[];validators=[];autoValidate=!0;constructor(t){let e=t?.configFilePath,r=t?.args||[],n=t?.config||{};this.options=t?.options||[],this.validators=t?.validators||[],t?.autoValidate!==void 0&&(this.autoValidate=t.autoValidate),this.config=this.createConfig(e,r,n)}deepMerge(t,e){let r={...t};for(let n in e)e[n]!==void 0&&(e[n]!==null&&typeof e[n]=="object"&&!Array.isArray(e[n])&&n in t&&t[n]!==null&&typeof t[n]=="object"&&!Array.isArray(t[n])?r[n]=this.deepMerge(t[n],e[n]):e[n]!==void 0&&(r[n]=e[n]));return r}setValueAtPath(t,e,r){let n=e.split("."),s=t;for(let o=0;o<n.length-1;o++){let a=n[o];!(a in s)||s[a]===null?s[a]={}:typeof s[a]!="object"&&(s[a]={}),s=s[a]}let i=n[n.length-1];s[i]=r}getValueAtPath(t,e){let r=e.split("."),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}createConfig(t,e=[],r={}){let n={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(n,a.path,a.defaultValue);let s={};if(t&&Ae(t))try{let a=Re(t,"utf8");s=JSON.parse(a),console.log(`Loaded configuration from ${t}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let i=this.parseCliArgs(e),o=this.deepMerge({},n);return o=this.deepMerge(o,s),o=this.deepMerge(o,r),o=this.deepMerge(o,i),o}parseCliArgs(t){let e={},r=t[0]?.endsWith("node")||t[0]?.endsWith("node.exe")?2:0;for(;r<t.length;){let n=t[r++],s=this.options.find(i=>i.flag===n);if(s)if(s.isFlag)this.setValueAtPath(e,s.path,!0);else if(r<t.length&&!t[r].startsWith("-")){let i=t[r++];if(s.parser)try{i=s.parser(i)}catch(o){console.error(`Error parsing value for ${s.flag}: ${o instanceof Error?o.message:String(o)}`);continue}if(s.validator){let o=s.validator(i);if(o!==!0&&typeof o=="string"){console.error(`Invalid value for ${s.flag}: ${o}`);continue}if(o===!1){console.error(`Invalid value for ${s.flag}`);continue}}this.setValueAtPath(e,s.path,i)}else console.error(`Missing value for option ${n}`)}return e}validate(){for(let t of this.validators){let e=this.getValueAtPath(this.config,t.path),r=t.validator(e,this.config);if(r===!1)throw new V(t.message);if(typeof r=="string")throw new V(r)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(t,e){let r=this.getValueAtPath(this.config,t);return r!==void 0?r:e}setValue(t,e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=this.getValueAtPath(this.config,t)||{};if(typeof r=="object"&&!Array.isArray(r)){let n=this.deepMerge(r,e);this.setValueAtPath(this.config,t,n);return}}this.setValueAtPath(this.config,t,e)}getHelpText(){let t=`Available configuration options:
2
+ import{existsSync as V}from"node:fs";import{join as M}from"node:path";import{mkdir as rt,writeFile as ie,readFile as je,unlink as nt}from"node:fs/promises";import{pathToFileURL as Re}from"node:url";var ae=class{requests=new Map;limit;windowMs;constructor(t=100,e=60){this.limit=t,this.windowMs=e*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return(!n||n.resetTime<e)&&(n={count:0,resetTime:e+this.windowMs},this.requests.set(r,n)),n.count++,n.count<=this.limit}getRemainingRequests(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return!n||n.resetTime<e?this.limit:Math.max(0,this.limit-n.count)}getResetTime(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return!n||n.resetTime<e?Math.floor((e+this.windowMs)/1e3):Math.floor(n.resetTime/1e3)}cleanup(){let t=Date.now();for(let[e,r]of this.requests.entries())r.resetTime<t&&this.requests.delete(e)}};import{URL as Ae}from"url";var ce=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(t){return this.globalMiddlewares.push(t),this}get(t,...e){let r=e.pop();return this.register("GET",t,r,e)}post(t,...e){let r=e.pop();return this.register("POST",t,r,e)}put(t,...e){let r=e.pop();return this.register("PUT",t,r,e)}delete(t,...e){let r=e.pop();return this.register("DELETE",t,r,e)}patch(t,...e){let r=e.pop();return this.register("PATCH",t,r,e)}any(t,...e){let r=e.pop(),n=e;return this.register("GET",t,r,n),this.register("POST",t,r,n),this.register("PUT",t,r,n),this.register("DELETE",t,r,n),this.register("PATCH",t,r,n),this.register("OPTIONS",t,r,n),this}options(t,...e){let r=e.pop();return this.register("OPTIONS",t,r,e)}match(t,e){for(let r of this.routes){if(r.method!==t)continue;let n=this.pathPatterns.get(r.path);if(!n)continue;let s=n.pattern.exec(e);if(!s)continue;let i={};return n.paramNames.forEach((o,a)=>{i[o]=s[a+1]||""}),{route:r,params:i}}return null}async handle(t,e){let r=t.method||"GET",n=new Ae(t.url||"/",`http://${t.headers.host}`),s=n.pathname,i=this.match(r,s);if(!i)return null;let{route:o,params:a}=i,c={};n.searchParams.forEach((u,d)=>{c[d]=u});let f={req:t,res:e,params:a,query:c,body:t.body||{},headers:t.headers,path:s,state:{},raw:()=>e,binary:(u,d="application/octet-stream",h=200)=>({statusCode:h,body:u,headers:{"Content-Type":d,"Content-Length":u.length.toString()},isRaw:!0}),text:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/plain"}}),form:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/json"}}),html:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/html"}}),redirect:(u,d=302)=>({statusCode:d,body:null,headers:{Location:u}}),status:function(u){return{raw:()=>e,binary:(d,h="application/octet-stream")=>({statusCode:u,body:d,headers:{"Content-Type":h,"Content-Length":d.length.toString()},isRaw:!0}),text:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/plain"}}),json:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/json"}}),html:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/html"}}),form:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(d,h=302)=>({statusCode:h,body:null,headers:{Location:d}}),status:d=>this.status(d)}}},l=[...this.globalMiddlewares,...o.middlewares];return this.executeMiddlewareChain(f,l,o.handler)}register(t,e,r,n=[]){return this.routes.push({method:t,path:e,handler:r,middlewares:n}),this.pathPatterns.set(e,this.createPathPattern(e)),this}createPathPattern(t){let e=[],r=t.replace(/\/:[^/]+/g,n=>{let s=n.slice(2);return e.push(s),"/([^/]+)"});return r.endsWith("/*")?(r=`${r.slice(0,-2)}(?:/(.*))?`,e.push("wildcard")):r=r.replace(/\/$/,"/?"),{pattern:new RegExp(`^${r}$`),paramNames:e}}async executeMiddlewareChain(t,e,r){let n=0,s=async()=>{if(n<e.length){let i=e[n++];return i(t,s)}return r(t)};return s()}};var H=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:Fe(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function Fe(t){return t==="true"||t===!0}var z=class extends Error{constructor(t){super(t),this.name="ValidationError",this.message=t||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as $e,readFileSync as Oe}from"node:fs";var _=class{config={};options=[];validators=[];autoValidate=!0;constructor(t){let e=t?.configFilePath,r=t?.args||[],n=t?.config||{};this.options=t?.options||[],this.validators=t?.validators||[],t?.autoValidate!==void 0&&(this.autoValidate=t.autoValidate),this.config=this.createConfig(e,r,n)}deepMerge(t,e){let r={...t};for(let n in e)e[n]!==void 0&&(e[n]!==null&&typeof e[n]=="object"&&!Array.isArray(e[n])&&n in t&&t[n]!==null&&typeof t[n]=="object"&&!Array.isArray(t[n])?r[n]=this.deepMerge(t[n],e[n]):e[n]!==void 0&&(r[n]=e[n]));return r}setValueAtPath(t,e,r){let n=e.split("."),s=t;for(let o=0;o<n.length-1;o++){let a=n[o];!(a in s)||s[a]===null?s[a]={}:typeof s[a]!="object"&&(s[a]={}),s=s[a]}let i=n[n.length-1];s[i]=r}getValueAtPath(t,e){let r=e.split("."),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}createConfig(t,e=[],r={}){let n={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(n,a.path,a.defaultValue);let s={};if(t&&$e(t))try{let a=Oe(t,"utf8");s=JSON.parse(a),console.log(`Loaded configuration from ${t}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let i=this.parseCliArgs(e),o=this.deepMerge({},n);return o=this.deepMerge(o,s),o=this.deepMerge(o,r),o=this.deepMerge(o,i),o}parseCliArgs(t){let e={},r=t[0]?.endsWith("node")||t[0]?.endsWith("node.exe")?2:0;for(;r<t.length;){let n=t[r++],s=this.options.find(i=>i.flag===n);if(s)if(s.isFlag)this.setValueAtPath(e,s.path,!0);else if(r<t.length&&!t[r].startsWith("-")){let i=t[r++];if(s.parser)try{i=s.parser(i)}catch(o){console.error(`Error parsing value for ${s.flag}: ${o instanceof Error?o.message:String(o)}`);continue}if(s.validator){let o=s.validator(i);if(o!==!0&&typeof o=="string"){console.error(`Invalid value for ${s.flag}: ${o}`);continue}if(o===!1){console.error(`Invalid value for ${s.flag}`);continue}}this.setValueAtPath(e,s.path,i)}else console.error(`Missing value for option ${n}`)}return e}validate(){for(let t of this.validators){let e=this.getValueAtPath(this.config,t.path),r=t.validator(e,this.config);if(r===!1)throw new z(t.message);if(typeof r=="string")throw new z(r)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(t,e){let r=this.getValueAtPath(this.config,t);return r!==void 0?r:e}setValue(t,e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=this.getValueAtPath(this.config,t)||{};if(typeof r=="object"&&!Array.isArray(r)){let n=this.deepMerge(r,e);this.setValueAtPath(this.config,t,n);return}}this.setValueAtPath(this.config,t,e)}getHelpText(){let t=`Available configuration options:
3
3
 
4
4
  `;for(let e of this.options)t+=`${e.flag}${e.isFlag?"":" <value>"}
5
5
  `,e.description&&(t+=` ${e.description}
6
6
  `),e.defaultValue!==void 0&&(t+=` Default: ${JSON.stringify(e.defaultValue)}
7
7
  `),t+=`
8
- `;return t}};var G={int:t=>{let e=t.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`Cannot parse "${t}" as an integer`);let r=Number.parseInt(e,10);if(Number.isNaN(r))throw new Error(`Cannot parse "${t}" as an integer`);return r},float:t=>{let e=t.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)){if(e==="Infinity"||e==="-Infinity")return e==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${t}" as a number`)}let r=Number.parseFloat(e);if(Number.isNaN(r))throw new Error(`Cannot parse "${t}" as a number`);return r},boolean:t=>{let e=t.trim().toLowerCase();if(["true","yes","1","y"].includes(e))return!0;if(["false","no","0","n"].includes(e))return!1;throw new Error(`Cannot parse "${t}" as a boolean`)},array:t=>t.split(",").map(e=>e.trim()),json:t=>{try{return JSON.parse(t)}catch{throw new Error(`Cannot parse "${t}" as JSON`)}}};var b=M(),ce=t=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:b.port},{flag:"--host",path:"host",defaultValue:b.host},{flag:"--https",path:"useHttps",defaultValue:b.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:b.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:b.sslCert},{flag:"--key",path:"sslKey",defaultValue:b.sslKey},{flag:"--ca",path:"sslCa",defaultValue:b.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:b.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:b.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:b.allowedDomains,parser:G.array},{flag:"--debug",path:"debug",defaultValue:b.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:b.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:b.requestTimeout}],config:t});function ue(t,e){let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new Error("Invalid multipart/form-data: missing boundary");let n=r[1]||r[2],s=Buffer.from(`--${n}`),i=Buffer.from(`--${n}--`),o={},a={},c=je(t,s);for(let f of c){if(f.length===0||f.equals(i.subarray(s.length)))continue;let l=$e(f);if(!l)continue;let{name:u,filename:d,contentType:p,data:h}=l;if(d){let g={filename:d,contentType:p||"application/octet-stream",data:h,size:h.length};a[u]?Array.isArray(a[u])?a[u].push(g):a[u]=[a[u],g]:a[u]=g}else{let g=h.toString("utf8");o[u]?Array.isArray(o[u])?o[u].push(g):o[u]=[o[u],g]:o[u]=g}}return{fields:o,files:a}}function je(t,e){let r=[],n=0;for(;n<t.length;){let s=t.indexOf(e,n);if(s===-1)break;n!==s&&r.push(t.subarray(n,s)),n=s+e.length,n<t.length&&t[n]===13&&t[n+1]===10&&(n+=2)}return r}function $e(t){let e=Buffer.from(`\r
8
+ `;return t}};var G={int:t=>{let e=t.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`Cannot parse "${t}" as an integer`);let r=Number.parseInt(e,10);if(Number.isNaN(r))throw new Error(`Cannot parse "${t}" as an integer`);return r},float:t=>{let e=t.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)){if(e==="Infinity"||e==="-Infinity")return e==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${t}" as a number`)}let r=Number.parseFloat(e);if(Number.isNaN(r))throw new Error(`Cannot parse "${t}" as a number`);return r},boolean:t=>{let e=t.trim().toLowerCase();if(["true","yes","1","y"].includes(e))return!0;if(["false","no","0","n"].includes(e))return!1;throw new Error(`Cannot parse "${t}" as a boolean`)},array:t=>t.split(",").map(e=>e.trim()),json:t=>{try{return JSON.parse(t)}catch{throw new Error(`Cannot parse "${t}" as JSON`)}}};var b=H(),ue=t=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:b.port},{flag:"--host",path:"host",defaultValue:b.host},{flag:"--https",path:"useHttps",defaultValue:b.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:b.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:b.sslCert},{flag:"--key",path:"sslKey",defaultValue:b.sslKey},{flag:"--ca",path:"sslCa",defaultValue:b.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:b.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:b.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:b.allowedDomains,parser:G.array},{flag:"--debug",path:"debug",defaultValue:b.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:b.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:b.requestTimeout}],config:t});function le(t,e){let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new Error("Invalid multipart/form-data: missing boundary");let n=r[1]||r[2],s=Buffer.from(`--${n}`),i=Buffer.from(`--${n}--`),o={},a={},c=ke(t,s);for(let f of c){if(f.length===0||f.equals(i.subarray(s.length)))continue;let l=Me(f);if(!l)continue;let{name:u,filename:d,contentType:h,data:p}=l;if(d){let g={filename:d,contentType:h||"application/octet-stream",data:p,size:p.length};a[u]?Array.isArray(a[u])?a[u].push(g):a[u]=[a[u],g]:a[u]=g}else{let g=p.toString("utf8");o[u]?Array.isArray(o[u])?o[u].push(g):o[u]=[o[u],g]:o[u]=g}}return{fields:o,files:a}}function ke(t,e){let r=[],n=0;for(;n<t.length;){let s=t.indexOf(e,n);if(s===-1)break;n!==s&&r.push(t.subarray(n,s)),n=s+e.length,n<t.length&&t[n]===13&&t[n+1]===10&&(n+=2)}return r}function Me(t){let e=Buffer.from(`\r
9
9
  \r
10
10
  `),r=t.indexOf(e);if(r===-1)return null;let n=t.subarray(0,r),s=t.subarray(r+4),o=n.toString("utf8").split(`\r
11
- `),a="",c="",f,l;for(let d of o){let p=d.toLowerCase();if(p.startsWith("content-disposition:")){a=d.substring(20).trim();let h=a.match(/name="([^"]+)"/);h&&(c=h[1]);let g=a.match(/filename="([^"]+)"/);g&&(f=g[1])}else p.startsWith("content-type:")&&(l=d.substring(13).trim())}if(!c)return null;let u=s;return u.length>=2&&u[u.length-2]===13&&u[u.length-1]===10&&(u=u.subarray(0,u.length-2)),{disposition:a,name:c,filename:f,contentType:l,data:u}}import{readFileSync as I}from"fs";import _ from"http";import He from"http2";import ke from"https";var J=class{config;rateLimiter;router;shutdownHandlers=[];constructor(t){let e=new z(ce(t||{})).get();e.debug&&console.log("Using configuration:",e),this.config=e,this.router=new ae;let r=e.rateLimit.requestsPerMinute||M().rateLimit.requestsPerMinute;this.rateLimiter=new oe(r,60),e.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(t){return this.router.use(t),this}get(t,...e){return this.router.get(t,...e),this}post(t,...e){return this.router.post(t,...e),this}put(t,...e){return this.router.put(t,...e),this}delete(t,...e){return this.router.delete(t,...e),this}patch(t,...e){return this.router.patch(t,...e),this}any(t,...e){return this.router.any(t,...e),this}options(t,...e){return this.router.options(t,...e),this}start(){let t=this.createServer(),{port:e,host:r}=this.config;return this.setupGracefulShutdown(t),t.listen(e,r,()=>{let n=t.address(),s=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${s}://${n.address!=="::"?n.address:"localhost"}:${n.port}`)}),t}createServer(){let t=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let e={key:I(this.config.sslKey),cert:I(this.config.sslCert),...this.config.sslCa?{ca:I(this.config.sslCa)}:{}};return He.createSecureServer(e,t)}catch(e){throw e.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${e.message}`):e}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let e={key:I(this.config.sslKey),cert:I(this.config.sslCert),...this.config.sslCa?{ca:I(this.config.sslCa)}:{}};return ke.createServer(e,t)}catch(e){throw e.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${e.message}`):e}}return _.createServer(t)}async rateLimitMiddleware(t,e){let r=t.req.socket.remoteAddress||"unknown";return t.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),t.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(r).toString()),t.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(r).toString()),this.rateLimiter.isAllowed(r)?e():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(t,e){let r=Date.now(),n=t.method||"UNKNOWN",s=t.url||"/unknown",i=this.config.debug;try{if(this.setCorsHeaders(e,t),this.setSecurityHeaders(e,this.config.useHttps),i&&console.log(`${n} ${s}`),t.method==="OPTIONS"){if(e instanceof _.ServerResponse)e.statusCode=204,e.end();else{let a=e;a.writeHead(204),a.end()}return}try{t.body=await this.parseBody(t)}catch(a){return i&&console.error("Body parsing error:",a.message),this.respond(e,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let o=await this.router.handle(t,e);return o?o._handled?void 0:this.respond(e,o):this.respond(e,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(o){return console.error("Server error:",o),this.respond(e,{statusCode:500,body:{error:"Internal Server Error",message:i?o.message:"An unexpected error occurred"}})}finally{i&&this.logDuration(r,n,s)}}logDuration(t,e,r){let n=Date.now()-t;console.log(`${e} ${r} completed in ${n}ms`)}async parseBody(t){return new Promise((e,r)=>{let n=[],s=0,i=this.config.maxBodySize,o=!1,a=null,c=this.config.debug,f=t.headers["content-type"]||"";c&&console.log("Content-Type:",f),this.config.requestTimeout>0&&(a=setTimeout(()=>{o||(o=!0,c&&console.log("Request timeout exceeded"),r(new Error("Request timeout")))},this.config.requestTimeout));let l=()=>{a&&(clearTimeout(a),a=null)};t.on("data",u=>{if(!o){if(s+=u.length,c&&console.log(`Received chunk: ${u.length} bytes, total size: ${s}`),s>i){o=!0,l(),c&&console.log(`Body size exceeded limit: ${s} > ${i}`),r(new Error("Request body too large"));return}n.push(u)}}),t.on("end",()=>{if(!o){o=!0,l(),c&&console.log(`Request body complete: ${s} bytes`);try{if(n.length>0){let u=Buffer.concat(n);if(f.includes("application/json"))try{let d=u.toString("utf8");e(JSON.parse(d))}catch(d){r(new Error(`Invalid JSON in request body: ${d.message}`))}else if(f.includes("application/x-www-form-urlencoded")){let d=u.toString("utf8"),p={};new URLSearchParams(d).forEach((h,g)=>{p[g]=h}),e(p)}else if(f.includes("multipart/form-data"))try{let d=ue(u,f);e(d)}catch(d){r(new Error(`Invalid multipart form data: ${d.message}`))}else this.isBinaryContentType(f)?e(u):e(u.toString("utf8"))}else e({})}catch(u){r(new Error(`Invalid request body: ${u}`))}}}),t.on("error",u=>{o||(o=!0,l(),r(new Error(`Error reading request body: ${u.message}`)))}),t.on("close",()=>{l()})})}isBinaryContentType(t){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(r=>t.includes(r))}setCorsHeaders(t,e){let r=e.headers.origin,{allowedDomains:n=["*"]}=this.config;!r||n.length===0||n.includes("*")?t.setHeader("Access-Control-Allow-Origin","*"):n.includes(r)&&(t.setHeader("Access-Control-Allow-Origin",r),t.setHeader("Vary","Origin")),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(t,e=!1){let r={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((e||this.config.useHttp2)&&(r["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),t instanceof _.ServerResponse)Object.entries(r).forEach(([n,s])=>{t.setHeader(n,s)});else{let n=t;Object.entries(r).forEach(([s,i])=>{n.setHeader(s,i)})}}respond(t,e){let r={...e.headers||{}};(s=>typeof s.writeHead=="function"&&typeof s.end=="function")(t)?(t.writeHead(e.statusCode,r),e.body===null||e.body===void 0?t.end():e.isRaw||typeof e.body=="string"?t.end(e.body):t.end(JSON.stringify(e.body))):(console.warn("Unexpected response object type without writeHead/end methods"),t.writeHead?.(e.statusCode,r),e.body===null||e.body===void 0?t.end?.():e.isRaw||typeof e.body=="string"?t.end?.(e.body):t.end?.(JSON.stringify(e.body)))}setupGracefulShutdown(t){let e=o=>{console.log("Shutting down MikroServe server..."),o&&console.error("Error:",o),this.cleanupShutdownHandlers(),t.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(o?1:0))})},r=()=>e(),n=()=>e(),s=o=>e(o),i=o=>e(o);this.shutdownHandlers=[r,n,s,i],process.on("SIGINT",r),process.on("SIGTERM",n),process.on("uncaughtException",s),process.on("unhandledRejection",i)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[t,e,r,n]=this.shutdownHandlers;process.removeListener("SIGINT",t),process.removeListener("SIGTERM",e),process.removeListener("uncaughtException",r),process.removeListener("unhandledRejection",n),this.shutdownHandlers=[]}}};var v=class extends Error{constructor(e){super(),this.name="ValidationError",this.message=e||"Invalid input",this.cause={statusCode:400}}};var O=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};var R=class extends Error{constructor(e){super(),this.name="InvalidMethodError",this.message=e||"Invalid HTTP method",this.cause={statusCode:400}}};var D=class extends Error{constructor(e){super(),this.name="ServiceRequestError",this.message=e||"Service request failed",this.cause={statusCode:502}}};var L=class{generatePermissionsFromBindings(e){let r=[];for(let n of e){let s=n.service;for(let i of n.permissions){if(!i.resource){r.push(`${s}.*`);continue}let o=i.resource,a=i.actions||["*"];if(i.targets&&i.targets.length>0)for(let c of a)for(let f of i.targets)r.push(`${s}.${o}.${c}:${f}`);else for(let c of a)r.push(`${s}.${o}.${c}`)}}return[...new Set(r)]}validateBindings(e){let r=["databases","storage","observability","sites","functions","events","schemas"];for(let n of e){if(!r.includes(n.service))throw new v(`Invalid service: ${n.service}. Must be one of: ${r.join(", ")}`);if(!n.permissions||n.permissions.length===0)throw new v("Bindings must have at least one permission");for(let s of n.permissions)if(s.targets&&s.targets.length>0){if(!s.resource)throw new v("Action-level bindings (with targets) must specify resource");if(!s.actions||s.actions.length===0)throw new v("Action-level bindings (with targets) must specify actions")}}}};var W=class{constructor(e,r,n){this.baseUrl=e;this.authToken=r;this.bindings=n}async request(e,r,n,s){let i=`${this.baseUrl}${r}`;if(s){let u=new URLSearchParams(s);i+=`?${u.toString()}`}let o={"Content-Type":"application/json"};this.authToken&&(o.Authorization=`Bearer ${this.authToken}`),this.bindings&&this.bindings.length>0&&(o["X-Function-Bindings"]=JSON.stringify(this.bindings));let a={method:e,headers:o};n&&(a.body=JSON.stringify(n));let c=await fetch(i,a),f=c.headers.get("content-type"),l;if(f?.includes("application/json")){let u=await c.text();u?l=JSON.parse(u):l=null}else l=await c.text();if(!c.ok)throw new D(`Service request failed (${c.status}): ${typeof l=="string"?l:JSON.stringify(l)}`);return l}},X=class extends W{async get(e,r){return this.request("POST","/get",{tableName:e,key:r})}async write(e,r,n,s,i){return this.request("POST","/write",{tableName:e,key:r,value:n,expiration:s,dictionaryName:i})}async delete(e,r){return this.request("DELETE","/delete",void 0,{tableName:e,key:r})}async listTables(){return this.request("GET","/tables")}async getTableSize(e){return this.request("GET","/table",void 0,{tableName:e})}async getTableInfo(e){return this.request("GET",`/tables/${e}`)}async createTable(e){return this.request("POST",`/tables/${e}`)}async deleteTable(e){return this.request("DELETE",`/tables/${e}`)}},Z=class{constructor(e){this.eventBus=e}async emit(e,r){await this.eventBus.emit(e,r)}},Y=class{constructor(e){this.schemaRegistry=e}validate(e,r,n){return this.schemaRegistry.validate(e,r,n)}},j=class{constructor(e,r,n,s){this.serviceBaseUrls=e;this.authToken=r;this.eventBus=n;this.schemaRegistry=s}createBindings(e){let r={};for(let n of e)switch(n.service){case"databases":{let s=this.serviceBaseUrls[n.service];if(!s)continue;r.databases=new X(s,this.authToken,e);break}case"events":this.eventBus&&(r.events=new Z(this.eventBus));break;case"schemas":this.schemaRegistry&&(r.schemas=new Y(this.schemaRegistry));break}return r}};var $=class{isSilent;propertyPath="";constructor(t=!1){this.isSilent=t}test(t,e){if(!e)throw new Error("Missing input!");this.updatePropertyPath();let{results:r,errors:n}=this.validate(t.properties,e),s=this.compileErrors(r,n),i=this.isSuccessful(r,s);return{errors:s,success:i}}compileErrors(t,e){let r=t.filter(n=>n.success===!1);return[...e,...r].flatMap(n=>n)}isSuccessful(t,e){return t.every(r=>r.success===!0)&&e.length===0}validate(t,e,r=[],n=[]){let s=t?.additionalProperties??!0,i=t?.required||[];n=this.checkForRequiredKeysErrors(i,e,n),n=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),n,s);for(let o in t){let a=i.includes(o)&&o!=="required",c=t[o],f=e[o],l=c.additionalProperties??!0;a&&(n=this.checkForRequiredKeysErrors(c.required||[],f,n)),this.isDefined(f)&&(this.handleValidation(o,f,c,r),n=this.checkForDisallowedProperties(Object.keys(f),Object.keys(c),n,l),this.handleNestedObject(f,c,r,n))}return{results:r,errors:n}}updatePropertyPath(t,e=""){if(!t){this.propertyPath="";return}e&&(this.propertyPath=e),this.propertyPath=`${this.propertyPath}.${t}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(t){return!!(typeof t=="number"&&t===0||t||t===""||typeof t=="boolean")}checkForRequiredKeysErrors(t,e,r){if(!this.areRequiredKeysPresent(t,e)){let n=e?Object.keys(e):[],s=this.findNonOverlappingElements(t,n),i=s.length>0?`Missing the required key: '${s.join(", ")}'!`:`Missing values for required keys: '${n.filter(o=>!e[o]).join(", ")}'!`;r.push({key:"",value:e,success:!1,error:i})}return r}checkForDisallowedProperties(t,e,r,n){if(!n){let s=this.findNonOverlappingElements(t,e);s.length>0&&r.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${s.join(", ")}'!`})}return r}handleValidation(t,e,r,n){this.updatePropertyPath(t);let s=this.validateProperty(this.propertyPath,r,e);n.push(...s);let i=(a,c)=>{a.forEach(f=>{let l=this.validateProperty(this.propertyPath,c.items,f);n.push(...l)}),this.updatePropertyPath()},o=a=>{let c=Object.keys(a),f=this.propertyPath;c.forEach(l=>{if(this.updatePropertyPath(l,f),this.isArray(a[l])&&r[l]?.items!=null)i(a[l],r[l]);else{let u=this.validateProperty(this.propertyPath,r[l],a[l]);n.push(...u)}})};this.isArray(e)&&r.items!=null?i(e,r):this.isObject(e)?o(e):this.updatePropertyPath()}handleNestedObject(t,e,r,n){if(this.isObject(t)){let s=this.getNestedObjects(t);for(let i of s){let o=e[i],a=t[i];o&&typeof a=="object"&&this.validate(o,a,r,n)}}}getNestedObjects(t){return Object.keys(t).filter(e=>{if(this.isObject(t))return e})}findNonOverlappingElements(t,e){return t.filter(r=>!e.includes(r))}areRequiredKeysPresent(t,e=[]){return t.every(r=>Object.keys(e).includes(r)?this.isDefined(e[r]):!1)}validateProperty(t,e,r){return this.validateInput(e,r).map(s=>{let{success:i,error:o}=s;return{key:t,value:r,success:i,error:o??""}})}validateInput(t,e){if(t){let r=[{condition:()=>t.type,validator:()=>this.isCorrectType(t.type,e),error:"Invalid type"},{condition:()=>t.format,validator:()=>this.isCorrectFormat(t.format,e),error:"Invalid format"},{condition:()=>t.minLength,validator:()=>this.isMinimumLength(t.minLength,e),error:"Length too short"},{condition:()=>t.maxLength,validator:()=>this.isMaximumLength(t.maxLength,e),error:"Length too long"},{condition:()=>t.minValue,validator:()=>this.isMinimumValue(t.minValue,e),error:"Value too small"},{condition:()=>t.maxValue,validator:()=>this.isMaximumValue(t.maxValue,e),error:"Value too large"},{condition:()=>t.matchesPattern,validator:()=>this.matchesPattern(t.matchesPattern,e),error:"Pattern does not match"}],n=[];for(let s of r)s.condition()&&!s.validator()&&n.push({success:!1,error:s.error});return n}else this.isSilent||console.warn(`Missing property '${t}' for match '${e}'. Skipping...`);return[{success:!0}]}isCorrectType(t,e){return Array.isArray(t)||(t=[t]),t.some(r=>{switch(r){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"object":return this.isObject(e);case"array":return this.isArray(e)}})}isObject(t){return t!==null&&!this.isArray(t)&&typeof t=="object"&&t instanceof Object&&Object.prototype.toString.call(t)==="[object Object]"}isArray(t){return Array.isArray(t)}isCorrectFormat(t,e){switch(t){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(e);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(e);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(e);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(e);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(e);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(e)}}isMinimumLength(t,e){return Array.isArray(e)?e.length>=t:e?.toString().length>=t}isMaximumLength(t,e){return Array.isArray(e)?e.length<=t:e.toString().length<=t}isMinimumValue(t,e){return e>=t}isMaximumValue(t,e){return e<=t}matchesPattern(t,e){return new RegExp(t).test(e)}schemaFrom(t){let e={properties:{additionalProperties:!1,required:[]}};for(let r in t){let n=t[r];e.properties.required.push(r),Array.isArray(n)?e.properties[r]=this.generateArraySchema(n):typeof n=="object"&&n!==null?e.properties[r]=this.generateNestedObjectSchema(n):e.properties[r]=this.generatePropertySchema(n)}return e}generateArraySchema(t){let e={type:"array"},r=t.filter(n=>n);if(r.length>0){let n=r[0];r.every(i=>typeof i==typeof n)?typeof n=="object"&&!Array.isArray(n)?e.items=this.generateNestedObjectSchema(n):e.items=this.generatePropertySchema(n):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return e}generateNestedObjectSchema(t){let e={type:"object",additionalProperties:!1,required:[]};for(let r in t){let n=t[r];e.required.push(r),typeof n=="object"&&!Array.isArray(n)&&n!==null?e[r]=this.generateNestedObjectSchema(n):e[r]=this.generatePropertySchema(n)}return e}generatePropertySchema(t){let e=typeof t,r={type:e};return e==="string"&&(r.minLength=1),r}};async function F(t){return t.body||{}}function w(t,e="An error occurred"){let r=t?.message||t||e,n=t?.cause?.statusCode||t?.statusCode||400;return{message:r,status:n}}function le(t,e,r={}){let n=Array.isArray(e)?e:[e];if(!t||!t.roles||!Array.isArray(t.roles)){let o=new Error("Unauthorized: User or roles missing");throw o.cause={statusCode:403},o}let s=t.roles.flatMap(o=>o?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(f=>typeof f=="string"?f:f&&typeof f=="object"&&f.actions?f.actions:[]))||[]);if(!n.every(o=>s.includes(o)||s.includes("*")?!0:s.some(a=>{if(a.endsWith(".*")){let c=a.slice(0,-2);return o.startsWith(`${c}.`)}return!1}))){let o=new Error("Unauthorized");throw o.cause={statusCode:403},o}return!0}function de(t,e,r,n,s){let i=t.find(c=>c.service===e);if(!i){let c=new Error(`Function bindings do not include access to service: ${e}`);throw c.cause={statusCode:403},c}if(!i.permissions||i.permissions.length===0)return;for(let c of i.permissions)if(!(c.resource&&c.resource!==r)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(n)){if(c.targets&&c.targets.length>0){if(!s)return;if(!c.targets.includes(s))continue}return}}let o=s?`:${s}`:"",a=new Error(`Function bindings do not allow: ${e}.${r}.${n}${o}`);throw a.cause={statusCode:403},a}import{readFileSync as Me,existsSync as Oe}from"node:fs";function x(){let t=process.env.MOLNOS_RUNTIME_CONFIG,e={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!t||!Oe(t))return e;try{let r=Me(t,"utf-8");return JSON.parse(r)}catch(r){return console.error("[loadRuntimeConfig] Failed to load runtime config:",r),e}}async function S(t,e,r,n,s,i,o){if(!e)return null;let a=t.headers["x-molnos-service-token"];if(a){let l=x();if(l.internalServiceSecret&&a===l.internalServiceSecret)return null}let c=t.state.user;if(!c){let l=t.headers.authorization;if(!l){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let u=l.replace(/^Bearer\s+/i,"");if(c=await e.getUserFromToken(u),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}le(c,r,{});let f=t.headers["x-function-bindings"];if(f)try{let l=Array.isArray(f)?f[0]:f,u=JSON.parse(l);de(u,n,s,i,o)}catch(l){if(l.cause?.statusCode===403)throw l;let u=new Error("Invalid function bindings header");throw u.cause={statusCode:400},u}return c}var fe={properties:{id:{type:"string",minLength:1,maxLength:40,pattern:"^[a-zA-Z0-9_-]{1,40}$"},name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},trigger:{type:"object"},triggers:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["http","event"]},eventName:{type:"string"}},required:["type"]}},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"},context:{type:"string",minLength:1}},required:["name","code"],additionalProperties:!1};var Le=new $(!0);async function he(t,e,r){try{let n=await F(t),s=Le.test(fe,n);if(!s.success)return t.json({error:"Invalid input",details:s.errors},400);await S(t,r,"functions.function.create","functions","function","create");let{id:i,name:o,code:a,methods:c,bindings:f,trigger:l,triggers:u,passAllHeaders:d,allowUnauthenticated:p}=n,h=u||(l?[l]:void 0),g=await e.deployFunction(o,a,c,f,h,d,p,i);return t.json({success:!0,function:g},201)}catch(n){let{message:s,status:i}=w(n,"Error deploying function");return t.json({error:s},i)}}async function pe(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);let s=e.getFunction(n);return s?s.triggers&&s.triggers.length>0&&!s.triggers.some(i=>i.type==="http")?t.json({error:"Not Found",message:"Function not found"},404):(s.allowUnauthenticated!==!0&&await S(t,r,"functions.function.execute","functions","function","execute",n),await e.executeFunction(n,t)):t.json({error:"Not Found",message:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error executing function");return t.json({error:s},i)}}var ge={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},trigger:{type:"object"},triggers:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["http","event"]},eventName:{type:"string"}},required:["type"]}},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var Ue=new $(!0);async function me(t,e,r){try{let n=t.params.functionId,s=await F(t);if(!n)return t.json({error:"functionId is required"},400);let i=Ue.test(ge,s);if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);await S(t,r,"functions.function.update","functions","function","update",n);let{code:o,methods:a,bindings:c,trigger:f,triggers:l,passAllHeaders:u,allowUnauthenticated:d}=s,p=l||(f?[f]:void 0),h=await e.updateFunction(n,{code:o,methods:a,bindings:c,triggers:p,passAllHeaders:u,allowUnauthenticated:d});return h?t.json({success:!0,function:h},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error updating function");return t.json({error:s},i)}}async function ye(t,e,r){try{let n=t.params.functionId;return n?(await S(t,r,"functions.function.delete","functions","function","delete",n),await e.deleteFunction(n)?t.json({success:!0,message:"Function deleted"},200):t.json({error:"Function not found"},404)):t.json({error:"functionId is required"},400)}catch(n){let{message:s,status:i}=w(n,"Error deleting function");return t.json({error:s},i)}}async function ve(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);await S(t,r,"functions.function.get","functions","function","read",n);let s=e.getFunction(n);return s?t.json({success:!0,function:s},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error getting function");return t.json({error:s},i)}}async function be(t,e,r,n){try{await S(t,r,"functions.function.get","functions","function","read");let s=e.getFunctions(),i=t.query.context;if(i&&n){let o=t.headers.authorization?.replace(/^Bearer\s+/i,""),a=await n.listResourcesByType(i,"function",o);s=s.filter(c=>a.includes(c.id))}return t.json({success:!0,count:s.length,functions:s},200)}catch(s){let{message:i,status:o}=w(s,"Error listing functions");return t.json({error:i},o)}}import{EventEmitter as Be}from"node:events";var K=class t{static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new Be,t.instance.setMaxListeners(100)),t.instance}};function Q(){return K.getInstance()}function we(t){let e=Q();try{e.emit("function.log",t)}catch(r){console.error("Failed to emit function log event:",r)}}import{getRandomValues as qe}from"node:crypto";var ee=class{options;defaultLength=16;defaultOnlyLowerCase=!1;defaultStyle="extended";defaultUrlSafe=!0;constructor(t){if(this.options={},t)for(let[e,r]of Object.entries(t))this.options[e]=this.generateConfig(r)}add(t){if(!t?.name)throw new Error("Missing name for the ID configuration");let e=this.generateConfig(t);this.options[t.name]=e}remove(t){if(!t?.name)throw new Error("Missing name for the ID configuration");delete this.options[t.name]}create(t,e,r,n){let s=this.generateConfig({length:t,style:e,onlyLowerCase:r,urlSafe:n});return this.generateId(s)}custom(t){if(this.options[t])return this.generateId(this.options[t]);throw new Error(`No configuration found with name: ${t}`)}generateConfig(t){return{name:t?.name||"",length:t?.length||this.defaultLength,onlyLowerCase:t?.onlyLowerCase??this.defaultOnlyLowerCase,style:t?.style||this.defaultStyle,urlSafe:t?.urlSafe??this.defaultUrlSafe}}getCharacterSet(t,e,r){if(t==="hex")return e?"0123456789abcdef":"0123456789ABCDEFabcdef";if(t==="alphanumeric")return e?"abcdefghijklmnopqrstuvwxyz0123456789":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";if(t==="extended")return r?e?"abcdefghijklmnopqrstuvwxyz0123456789-._~":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~":e?"abcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:";throw new Error(`Unknown ID style "${t} provided. Must be one of "extended" (default), "alphanumeric", or "hex".`)}generateId(t){let{length:e,onlyLowerCase:r,style:n,urlSafe:s}=t;if(e<0||e===0)throw new Error("ID length cannot be negative");let i=this.getCharacterSet(n,r,s),o=(2<<Math.log(i.length-1)/Math.LN2)-1,a=Math.ceil(1.6*o*e/i.length),c="";for(;c.length<e;){let f=new Uint8Array(a);qe(f);for(let l=0;l<a;l++){let u=f[l]&o;if(u<i.length&&(c+=i[u],c.length===e))break}}return c}};var Ve=8,ze=40,Ge=/^[a-zA-Z0-9_-]{1,40}$/;function _e(){return new ee().create(Ve,"alphanumeric",!1,!0)}function Je(t){return Ge.test(t)}function We(t){if(!Je(t))throw new Error(`Invalid ID format: "${t}". IDs must be 1-${ze} characters using only alphanumeric characters, underscores, and hyphens.`)}function te(t){return t?(We(t),t):_e()}import{EventEmitter as Xe}from"events";var re=class{emitter;targets={};options;constructor(t){this.emitter=new Xe,t?.maxListeners===0?this.emitter.setMaxListeners(0):this.emitter.setMaxListeners(t?.maxListeners||10),this.options={errorHandler:t?.errorHandler||(e=>console.error(e)),isSilent:t?.isSilent||!1}}addTarget(t){return(Array.isArray(t)?t:[t]).map(n=>this.targets[n.name]?(this.options.isSilent||console.error(`Target with name '${n.name}' already exists.`),!1):(this.targets[n.name]={name:n.name,url:n.url,headers:n.headers||{},events:n.events||[]},!0)).every(n=>n===!0)}updateTarget(t,e){if(!this.targets[t])return console.error(`Target with name '${t}' does not exist.`),!1;let r=this.targets[t];return e.url!==void 0&&(r.url=e.url),e.headers&&(r.headers={...r.headers,...e.headers}),e.events&&(r.events=e.events),!0}removeTarget(t){return this.targets[t]?(delete this.targets[t],!0):(console.error(`Target with name '${t}' does not exist.`),!1)}addEventToTarget(t,e){if(!this.targets[t])return console.error(`Target with name '${t}' does not exist.`),!1;let r=Array.isArray(e)?e:[e],n=this.targets[t];return r.forEach(s=>{n.events.includes(s)||n.events.push(s)}),!0}on(t,e){return this.emitter.on(t,e),this}off(t,e){return this.emitter.off(t,e),this}once(t,e){return this.emitter.once(t,e),this}async emit(t,e){let r={success:!0,errors:[]},n=(o,a,c)=>({target:o,event:a,error:c}),s=Object.values(this.targets).filter(o=>o.events.includes(t)||o.events.includes("*"));s.filter(o=>!o.url).forEach(o=>{try{this.emitter.emit(t,e)}catch(a){let c=a instanceof Error?a:new Error(String(a));r.errors.push({target:o.name,event:t,error:c}),this.options.errorHandler(c,t,e),r.success=!1}});let i=s.filter(o=>o.url);if(i.length>0){let o=i.map(async a=>{try{let c=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json",...a.headers},body:JSON.stringify({eventName:t,data:e})});if(!c.ok){let f=`HTTP error! Status: ${c.status}: ${c.statusText}`,l=new Error(f);r.errors.push(n(a.name,t,l)),this.options.errorHandler(l,t,e),r.success=!1}}catch(c){let f=c instanceof Error?c:new Error(String(c));r.errors.push(n(a.name,t,f)),this.options.errorHandler(f,t,e),r.success=!1}});await Promise.allSettled(o)}return r}async handleIncomingEvent(t){try{let{eventName:e,data:r}=typeof t=="string"?JSON.parse(t):t;process.nextTick(()=>{try{this.emitter.emit(e,r)}catch(n){this.options.errorHandler(n instanceof Error?n:new Error(String(n)),e,r)}})}catch(e){throw this.options.errorHandler(e instanceof Error?e:new Error(String(e)),"parse_event"),e}}createMiddleware(){return async(t,e,r)=>{if(t.method!=="POST"){r&&r();return}if(t.body)try{await this.handleIncomingEvent(t.body),e.statusCode=202,e.end()}catch(n){e.statusCode=400,e.end(JSON.stringify({error:"Invalid event format"})),r&&r(n)}else{let n="";t.on("data",s=>n+=s.toString()),t.on("end",async()=>{try{await this.handleIncomingEvent(n),e.statusCode=202,e.end()}catch(s){e.statusCode=400,e.end(JSON.stringify({error:"Invalid event format"})),r&&r(s)}})}}}};var N=null;function H(){return N||(N=new re,N.addTarget({name:"molnos-internal",events:["*"]})),N}var Ze=null;function ne(){return Ze||void 0}function Se(t,e){let r={enabled:!1,requestsPerMinute:0};if(!e)return r;let n=e.services?.[t];return n||(e.global?e.global:r)}function xe(t,e){let r=t?.api?.port;if(!r)throw new Error('Missing "port" input when create API service!');let n=x(),s=t?.dataPath||n.molnos.dataPath,i=t?.api?.host||n.server.host,o=t?.identityApiUrl!==void 0?t.identityApiUrl:n.identity.apiUrl,a=t?.contextApiUrl!==void 0?t.contextApiUrl:n.context.apiUrl,c=t?.debug||!1,f;return e&&(f=Se(e,n.molnos.rateLimit)),{dataPath:s,api:{port:r,host:i},...o?{identityApiUrl:o}:{},...a?{contextApiUrl:a}:{},...f?{rateLimit:f}:{},debug:c}}var U=class{baseUrl;authToken;constructor(e,r){this.baseUrl=e.replace(/\/$/,""),this.authToken=r}async createCustomRole(e,r,n,s){let i=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:e,name:r,description:n,permissions:s})});if(!i.ok){let o=`Failed to create role: ${i.statusText}`;try{o=(await i.json()).error||o}catch{o=await i.text().catch(()=>i.statusText)||o}throw new Error(o)}}async updateRole(e,r){let n=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let s=await n.json();throw new Error(s.error||`Failed to update role: ${n.statusText}`)}}async deleteRole(e){let r=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete role: ${r.statusText}`)}}async addServiceAccount(e,r,n){let s=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:e,description:r,roles:n})});if(!s.ok){let o=`Failed to create service account: ${s.statusText}`;try{o=(await s.json()).error||o}catch{o=await s.text().catch(()=>s.statusText)||o}throw new Error(o)}let i=await s.json();return{id:i.id,apiKey:i.apiKey}}async deleteIdentity(e){let r=await fetch(`${this.baseUrl}/identity/service-accounts/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete service account: ${r.statusText}`)}}async getUserFromToken(e){try{let r=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return r.ok?await r.json():null}catch{return null}}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}};function Ce(t){return t?new U(t):null}var B=class{baseUrl;constructor(e){this.baseUrl=e.replace(/\/$/,"")}async listResourcesByType(e,r,n){let s=`${this.baseUrl}/contexts/${encodeURIComponent(e)}`;try{let i={"Content-Type":"application/json"};n&&(i.Authorization=`Bearer ${n}`);let o=await fetch(s,{method:"GET",headers:i});if(!o.ok)return[];let c=(await o.json()).context?.resources||{};switch(r){case"function":return c.functions||[];case"database":return c.databases||[];case"storage":return c.storage||[];case"site":return c.sites||[];default:return[]}}catch{return[]}}};function Ee(t){return t?new B(t):null}var ie=class t{static MAX_EVENT_CHAIN_DEPTH=10;functionsDir;functions=new Map;eventHandlers=new Map;eventChainDepth=0;debug;bindingService;constructor(e){this.functionsDir=e.functionsDir||k(process.cwd(),"functions-data"),this.debug=e.debug||!1,this.bindingService=new L}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions(),this.subscribeEventTriggeredFunctions()}getFunction(e){return this.functions.get(e)}getFunctions(){return Array.from(this.functions.values()).map(e=>({name:e.name,endpoint:e.endpoint,id:e.id,filePath:e.filePath,methods:e.methods,...e.bindings?{bindings:e.bindings}:{},...e.triggers&&e.triggers.length>0?{triggers:e.triggers}:{},...e.passAllHeaders!==void 0?{passAllHeaders:e.passAllHeaders}:{},...e.allowUnauthenticated!==void 0?{allowUnauthenticated:e.allowUnauthenticated}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}))}async ensureFunctionsDirExists(){q(this.functionsDir)||await Ye(this.functionsDir,{recursive:!0})}async loadExistingFunctions(){try{let e=k(this.functionsDir,"functions.json");if(q(e)){let r=await Pe(e,"utf8"),n=JSON.parse(r);for(let s of n)q(s.filePath)&&this.functions.set(s.id,s)}}catch{}}async saveFunctionsMetadata(){try{let e=k(this.functionsDir,"functions.json"),r=Array.from(this.functions.values());await se(e,JSON.stringify(r,null,2),"utf8")}catch{}}async deployFunction(e,r,n,s,i,o,a,c){if(!e||typeof e!="string")throw new v("Function name is required and must be a string");if(!r||typeof r!="string")throw new v("Function code is required and must be a string");if(n!==void 0){if(!Array.isArray(n))throw new v("Methods must be an array");let h=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let g of n)if(!h.includes(g.toUpperCase()))throw new R(`Invalid HTTP method: ${g}. Must be one of: ${h.join(", ")}`)}if(s&&s.length>0&&this.bindingService.validateBindings(s),i&&i.length>0){for(let h of i)if(h.type==="event"&&!h.eventName)throw new v("Event trigger must specify an eventName")}let f=te(c),l=k(this.functionsDir,`${f}.mjs`),u=this.wrapFunctionCode(r);await se(l,u,"utf8");let d=Date.now(),p={id:f,name:e,filePath:l,endpoint:`/functions/run/${f}`,...n&&n.length>0?{methods:n.map(h=>h.toUpperCase())}:{},...s?{bindings:s}:{},...i&&i.length>0?{triggers:i}:{},...o!==void 0?{passAllHeaders:o}:{},...a!==void 0?{allowUnauthenticated:a}:{},createdAt:d,updatedAt:d};return this.functions.set(f,p),await this.saveFunctionsMetadata(),this.subscribeToEvents(p),p}async updateFunction(e,r){let n=this.functions.get(e);if(!n)throw new O(`Function with ID ${e} not found`);let{code:s,methods:i,bindings:o,triggers:a,passAllHeaders:c,allowUnauthenticated:f}=r;if(s===void 0&&i===void 0&&o===void 0&&a===void 0&&c===void 0&&f===void 0)throw new v("At least one parameter (code, methods, bindings, triggers, passAllHeaders, or allowUnauthenticated) must be provided");if(s!==void 0&&(typeof s!="string"||!s))throw new v("Function code must be a non-empty string");if(i!==void 0){if(!Array.isArray(i))throw new v("Methods must be an array");let l=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let u of i)if(!l.includes(u.toUpperCase()))throw new R(`Invalid HTTP method: ${u}. Must be one of: ${l.join(", ")}`)}if(s!==void 0){let l=this.wrapFunctionCode(s);await se(n.filePath,l,"utf8")}if(i!==void 0&&(i.length>0?n.methods=i.map(l=>l.toUpperCase()):delete n.methods),o!==void 0&&(o.length>0&&this.bindingService.validateBindings(o),n.bindings=o.length>0?o:void 0),c!==void 0&&(c?n.passAllHeaders=!0:delete n.passAllHeaders),a!==void 0){for(let l of a)if(l.type==="event"&&!l.eventName)throw new v("Event trigger must specify an eventName");this.unsubscribeFromEvents(e),n.triggers=a.length>0?a:void 0,this.subscribeToEvents(n)}return f!==void 0&&(n.allowUnauthenticated=f),n.updatedAt=Date.now(),this.functions.set(e,n),await this.saveFunctionsMetadata(),n}async deleteFunction(e){let r=this.functions.get(e);if(!r)return!1;try{return this.unsubscribeFromEvents(e),q(r.filePath)&&await Ke(r.filePath),this.functions.delete(e),await this.saveFunctionsMetadata(),!0}catch(n){throw console.error(`Error deleting function ${e}:`,n.message),n}}wrapFunctionCode(e){let r=e;if(/export\s+default\s+\w+/.test(e))return`// FunctionsService generated module
11
+ `),a="",c="",f,l;for(let d of o){let h=d.toLowerCase();if(h.startsWith("content-disposition:")){a=d.substring(20).trim();let p=a.match(/name="([^"]+)"/);p&&(c=p[1]);let g=a.match(/filename="([^"]+)"/);g&&(f=g[1])}else h.startsWith("content-type:")&&(l=d.substring(13).trim())}if(!c)return null;let u=s;return u.length>=2&&u[u.length-2]===13&&u[u.length-1]===10&&(u=u.subarray(0,u.length-2)),{disposition:a,name:c,filename:f,contentType:l,data:u}}import{readFileSync as R}from"fs";import J from"http";import He from"http2";import Ne from"https";var W=class{config;rateLimiter;router;shutdownHandlers=[];constructor(t){let e=new _(ue(t||{})).get();e.debug&&console.log("Using configuration:",e),this.config=e,this.router=new ce;let r=e.rateLimit.requestsPerMinute||H().rateLimit.requestsPerMinute;this.rateLimiter=new ae(r,60),e.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(t){return this.router.use(t),this}get(t,...e){return this.router.get(t,...e),this}post(t,...e){return this.router.post(t,...e),this}put(t,...e){return this.router.put(t,...e),this}delete(t,...e){return this.router.delete(t,...e),this}patch(t,...e){return this.router.patch(t,...e),this}any(t,...e){return this.router.any(t,...e),this}options(t,...e){return this.router.options(t,...e),this}start(){let t=this.createServer(),{port:e,host:r}=this.config;return this.setupGracefulShutdown(t),t.listen(e,r,()=>{let n=t.address(),s=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${s}://${n.address!=="::"?n.address:"localhost"}:${n.port}`)}),t}createServer(){let t=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let e={key:R(this.config.sslKey),cert:R(this.config.sslCert),...this.config.sslCa?{ca:R(this.config.sslCa)}:{}};return He.createSecureServer(e,t)}catch(e){throw e.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${e.message}`):e}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let e={key:R(this.config.sslKey),cert:R(this.config.sslCert),...this.config.sslCa?{ca:R(this.config.sslCa)}:{}};return Ne.createServer(e,t)}catch(e){throw e.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${e.message}`):e}}return J.createServer(t)}async rateLimitMiddleware(t,e){let r=t.req.socket.remoteAddress||"unknown";return t.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),t.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(r).toString()),t.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(r).toString()),this.rateLimiter.isAllowed(r)?e():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(t,e){let r=Date.now(),n=t.method||"UNKNOWN",s=t.url||"/unknown",i=this.config.debug;try{if(this.setCorsHeaders(e,t),this.setSecurityHeaders(e,this.config.useHttps),i&&console.log(`${n} ${s}`),t.method==="OPTIONS"){if(e instanceof J.ServerResponse)e.statusCode=204,e.end();else{let a=e;a.writeHead(204),a.end()}return}try{t.body=await this.parseBody(t)}catch(a){return i&&console.error("Body parsing error:",a.message),this.respond(e,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let o=await this.router.handle(t,e);return o?o._handled?void 0:this.respond(e,o):this.respond(e,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(o){return console.error("Server error:",o),this.respond(e,{statusCode:500,body:{error:"Internal Server Error",message:i?o.message:"An unexpected error occurred"}})}finally{i&&this.logDuration(r,n,s)}}logDuration(t,e,r){let n=Date.now()-t;console.log(`${e} ${r} completed in ${n}ms`)}async parseBody(t){return new Promise((e,r)=>{let n=[],s=0,i=this.config.maxBodySize,o=!1,a=null,c=this.config.debug,f=t.headers["content-type"]||"";c&&console.log("Content-Type:",f),this.config.requestTimeout>0&&(a=setTimeout(()=>{o||(o=!0,c&&console.log("Request timeout exceeded"),r(new Error("Request timeout")))},this.config.requestTimeout));let l=()=>{a&&(clearTimeout(a),a=null)};t.on("data",u=>{if(!o){if(s+=u.length,c&&console.log(`Received chunk: ${u.length} bytes, total size: ${s}`),s>i){o=!0,l(),c&&console.log(`Body size exceeded limit: ${s} > ${i}`),r(new Error("Request body too large"));return}n.push(u)}}),t.on("end",()=>{if(!o){o=!0,l(),c&&console.log(`Request body complete: ${s} bytes`);try{if(n.length>0){let u=Buffer.concat(n);if(f.includes("application/json"))try{let d=u.toString("utf8");e(JSON.parse(d))}catch(d){r(new Error(`Invalid JSON in request body: ${d.message}`))}else if(f.includes("application/x-www-form-urlencoded")){let d=u.toString("utf8"),h={};new URLSearchParams(d).forEach((p,g)=>{h[g]=p}),e(h)}else if(f.includes("multipart/form-data"))try{let d=le(u,f);e(d)}catch(d){r(new Error(`Invalid multipart form data: ${d.message}`))}else this.isBinaryContentType(f)?e(u):e(u.toString("utf8"))}else e({})}catch(u){r(new Error(`Invalid request body: ${u}`))}}}),t.on("error",u=>{o||(o=!0,l(),r(new Error(`Error reading request body: ${u.message}`)))}),t.on("close",()=>{l()})})}isBinaryContentType(t){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(r=>t.includes(r))}setCorsHeaders(t,e){let r=e.headers.origin,{allowedDomains:n=["*"]}=this.config;!r||n.length===0||n.includes("*")?t.setHeader("Access-Control-Allow-Origin","*"):n.includes(r)&&(t.setHeader("Access-Control-Allow-Origin",r),t.setHeader("Vary","Origin")),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(t,e=!1){let r={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((e||this.config.useHttp2)&&(r["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),t instanceof J.ServerResponse)Object.entries(r).forEach(([n,s])=>{t.setHeader(n,s)});else{let n=t;Object.entries(r).forEach(([s,i])=>{n.setHeader(s,i)})}}respond(t,e){let r={...e.headers||{}};(s=>typeof s.writeHead=="function"&&typeof s.end=="function")(t)?(t.writeHead(e.statusCode,r),e.body===null||e.body===void 0?t.end():e.isRaw||typeof e.body=="string"?t.end(e.body):t.end(JSON.stringify(e.body))):(console.warn("Unexpected response object type without writeHead/end methods"),t.writeHead?.(e.statusCode,r),e.body===null||e.body===void 0?t.end?.():e.isRaw||typeof e.body=="string"?t.end?.(e.body):t.end?.(JSON.stringify(e.body)))}setupGracefulShutdown(t){let e=o=>{console.log("Shutting down MikroServe server..."),o&&console.error("Error:",o),this.cleanupShutdownHandlers(),t.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(o?1:0))})},r=()=>e(),n=()=>e(),s=o=>e(o),i=o=>e(o);this.shutdownHandlers=[r,n,s,i],process.on("SIGINT",r),process.on("SIGTERM",n),process.on("uncaughtException",s),process.on("unhandledRejection",i)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[t,e,r,n]=this.shutdownHandlers;process.removeListener("SIGINT",t),process.removeListener("SIGTERM",e),process.removeListener("uncaughtException",r),process.removeListener("unhandledRejection",n),this.shutdownHandlers=[]}}};var v=class extends Error{constructor(e){super(),this.name="ValidationError",this.message=e||"Invalid input",this.cause={statusCode:400}}};var N=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};var F=class extends Error{constructor(e){super(),this.name="InvalidMethodError",this.message=e||"Invalid HTTP method",this.cause={statusCode:400}}};var D=class extends Error{constructor(e){super(),this.name="ServiceRequestError",this.message=e||"Service request failed",this.cause={statusCode:502}}};var L=class{generatePermissionsFromBindings(e){let r=[];for(let n of e){let s=n.service;for(let i of n.permissions){if(!i.resource){r.push(`${s}.*`);continue}let o=i.resource,a=i.actions||["*"];if(i.targets&&i.targets.length>0)for(let c of a)for(let f of i.targets)r.push(`${s}.${o}.${c}:${f}`);else for(let c of a)r.push(`${s}.${o}.${c}`)}}return[...new Set(r)]}validateBindings(e){let r=["databases","storage","observability","sites","functions","events","schemas"];for(let n of e){if(!r.includes(n.service))throw new v(`Invalid service: ${n.service}. Must be one of: ${r.join(", ")}`);if(!n.permissions||n.permissions.length===0)throw new v("Bindings must have at least one permission");for(let s of n.permissions)if(s.targets&&s.targets.length>0){if(!s.resource)throw new v("Action-level bindings (with targets) must specify resource");if(!s.actions||s.actions.length===0)throw new v("Action-level bindings (with targets) must specify actions")}}}};var X=class{constructor(e,r,n){this.baseUrl=e;this.authToken=r;this.bindings=n}async request(e,r,n,s){let i=`${this.baseUrl}${r}`;if(s){let u=new URLSearchParams(s);i+=`?${u.toString()}`}let o={"Content-Type":"application/json"};this.authToken&&(o.Authorization=`Bearer ${this.authToken}`),this.bindings&&this.bindings.length>0&&(o["X-Function-Bindings"]=JSON.stringify(this.bindings));let a={method:e,headers:o};n&&(a.body=JSON.stringify(n));let c=await fetch(i,a),f=c.headers.get("content-type"),l;if(f?.includes("application/json")){let u=await c.text();u?l=JSON.parse(u):l=null}else l=await c.text();if(!c.ok)throw new D(`Service request failed (${c.status}): ${typeof l=="string"?l:JSON.stringify(l)}`);return l}},Y=class extends X{async get(e,r){return this.request("POST","/get",{tableName:e,key:r})}async write(e,r,n,s,i){return this.request("POST","/write",{tableName:e,key:r,value:n,expiration:s,dictionaryName:i})}async delete(e,r){return this.request("DELETE","/delete",void 0,{tableName:e,key:r})}async listTables(){return this.request("GET","/tables")}async getTableSize(e){return this.request("GET","/table",void 0,{tableName:e})}async getTableInfo(e){return this.request("GET",`/tables/${e}`)}async createTable(e){return this.request("POST",`/tables/${e}`)}async deleteTable(e){return this.request("DELETE",`/tables/${e}`)}},Z=class{constructor(e){this.eventBus=e}async emit(e,r){await this.eventBus.emit(e,r)}},K=class{constructor(e){this.schemaRegistry=e}validate(e,r,n){return this.schemaRegistry.validate(e,r,n)}},$=class{constructor(e,r,n,s){this.serviceBaseUrls=e;this.authToken=r;this.eventBus=n;this.schemaRegistry=s}createBindings(e){let r={};for(let n of e)switch(n.service){case"databases":{let s=this.serviceBaseUrls[n.service];if(!s)continue;r.databases=new Y(s,this.authToken,e);break}case"events":this.eventBus&&(r.events=new Z(this.eventBus));break;case"schemas":this.schemaRegistry&&(r.schemas=new K(this.schemaRegistry));break}return r}};var O=class{isSilent;propertyPath="";constructor(t=!1){this.isSilent=t}test(t,e){if(!e)throw new Error("Missing input!");this.updatePropertyPath();let{results:r,errors:n}=this.validate(t.properties,e),s=this.compileErrors(r,n),i=this.isSuccessful(r,s);return{errors:s,success:i}}compileErrors(t,e){let r=t.filter(n=>n.success===!1);return[...e,...r].flatMap(n=>n)}isSuccessful(t,e){return t.every(r=>r.success===!0)&&e.length===0}validate(t,e,r=[],n=[]){let s=t?.additionalProperties??!0,i=t?.required||[];n=this.checkForRequiredKeysErrors(i,e,n),n=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),n,s);for(let o in t){let a=i.includes(o)&&o!=="required",c=t[o],f=e[o],l=c.additionalProperties??!0;a&&(n=this.checkForRequiredKeysErrors(c.required||[],f,n)),this.isDefined(f)&&(this.handleValidation(o,f,c,r),n=this.checkForDisallowedProperties(Object.keys(f),Object.keys(c),n,l),this.handleNestedObject(f,c,r,n))}return{results:r,errors:n}}updatePropertyPath(t,e=""){if(!t){this.propertyPath="";return}e&&(this.propertyPath=e),this.propertyPath=`${this.propertyPath}.${t}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(t){return!!(typeof t=="number"&&t===0||t||t===""||typeof t=="boolean")}checkForRequiredKeysErrors(t,e,r){if(!this.areRequiredKeysPresent(t,e)){let n=e?Object.keys(e):[],s=this.findNonOverlappingElements(t,n),i=s.length>0?`Missing the required key: '${s.join(", ")}'!`:`Missing values for required keys: '${n.filter(o=>!e[o]).join(", ")}'!`;r.push({key:"",value:e,success:!1,error:i})}return r}checkForDisallowedProperties(t,e,r,n){if(!n){let s=this.findNonOverlappingElements(t,e);s.length>0&&r.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${s.join(", ")}'!`})}return r}handleValidation(t,e,r,n){this.updatePropertyPath(t);let s=this.validateProperty(this.propertyPath,r,e);n.push(...s);let i=(a,c)=>{a.forEach(f=>{let l=this.validateProperty(this.propertyPath,c.items,f);n.push(...l)}),this.updatePropertyPath()},o=a=>{let c=Object.keys(a),f=this.propertyPath;c.forEach(l=>{if(this.updatePropertyPath(l,f),this.isArray(a[l])&&r[l]?.items!=null)i(a[l],r[l]);else{let u=this.validateProperty(this.propertyPath,r[l],a[l]);n.push(...u)}})};this.isArray(e)&&r.items!=null?i(e,r):this.isObject(e)?o(e):this.updatePropertyPath()}handleNestedObject(t,e,r,n){if(this.isObject(t)){let s=this.getNestedObjects(t);for(let i of s){let o=e[i],a=t[i];o&&typeof a=="object"&&this.validate(o,a,r,n)}}}getNestedObjects(t){return Object.keys(t).filter(e=>{if(this.isObject(t))return e})}findNonOverlappingElements(t,e){return t.filter(r=>!e.includes(r))}areRequiredKeysPresent(t,e=[]){return t.every(r=>Object.keys(e).includes(r)?this.isDefined(e[r]):!1)}validateProperty(t,e,r){return this.validateInput(e,r).map(s=>{let{success:i,error:o}=s;return{key:t,value:r,success:i,error:o??""}})}validateInput(t,e){if(t){let r=[{condition:()=>t.type,validator:()=>this.isCorrectType(t.type,e),error:"Invalid type"},{condition:()=>t.format,validator:()=>this.isCorrectFormat(t.format,e),error:"Invalid format"},{condition:()=>t.minLength,validator:()=>this.isMinimumLength(t.minLength,e),error:"Length too short"},{condition:()=>t.maxLength,validator:()=>this.isMaximumLength(t.maxLength,e),error:"Length too long"},{condition:()=>t.minValue,validator:()=>this.isMinimumValue(t.minValue,e),error:"Value too small"},{condition:()=>t.maxValue,validator:()=>this.isMaximumValue(t.maxValue,e),error:"Value too large"},{condition:()=>t.matchesPattern,validator:()=>this.matchesPattern(t.matchesPattern,e),error:"Pattern does not match"}],n=[];for(let s of r)s.condition()&&!s.validator()&&n.push({success:!1,error:s.error});return n}else this.isSilent||console.warn(`Missing property '${t}' for match '${e}'. Skipping...`);return[{success:!0}]}isCorrectType(t,e){return Array.isArray(t)||(t=[t]),t.some(r=>{switch(r){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"object":return this.isObject(e);case"array":return this.isArray(e)}})}isObject(t){return t!==null&&!this.isArray(t)&&typeof t=="object"&&t instanceof Object&&Object.prototype.toString.call(t)==="[object Object]"}isArray(t){return Array.isArray(t)}isCorrectFormat(t,e){switch(t){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(e);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(e);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(e);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(e);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(e);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(e)}}isMinimumLength(t,e){return Array.isArray(e)?e.length>=t:e?.toString().length>=t}isMaximumLength(t,e){return Array.isArray(e)?e.length<=t:e.toString().length<=t}isMinimumValue(t,e){return e>=t}isMaximumValue(t,e){return e<=t}matchesPattern(t,e){return new RegExp(t).test(e)}schemaFrom(t){let e={properties:{additionalProperties:!1,required:[]}};for(let r in t){let n=t[r];e.properties.required.push(r),Array.isArray(n)?e.properties[r]=this.generateArraySchema(n):typeof n=="object"&&n!==null?e.properties[r]=this.generateNestedObjectSchema(n):e.properties[r]=this.generatePropertySchema(n)}return e}generateArraySchema(t){let e={type:"array"},r=t.filter(n=>n);if(r.length>0){let n=r[0];r.every(i=>typeof i==typeof n)?typeof n=="object"&&!Array.isArray(n)?e.items=this.generateNestedObjectSchema(n):e.items=this.generatePropertySchema(n):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return e}generateNestedObjectSchema(t){let e={type:"object",additionalProperties:!1,required:[]};for(let r in t){let n=t[r];e.required.push(r),typeof n=="object"&&!Array.isArray(n)&&n!==null?e[r]=this.generateNestedObjectSchema(n):e[r]=this.generatePropertySchema(n)}return e}generatePropertySchema(t){let e=typeof t,r={type:e};return e==="string"&&(r.minLength=1),r}};async function j(t){return t.body||{}}function S(t,e="An error occurred"){let r=t?.message||t||e,n=t?.cause?.statusCode||t?.statusCode||400;return{message:r,status:n}}function de(t,e,r={}){let n=Array.isArray(e)?e:[e];if(!t||!t.roles||!Array.isArray(t.roles)){let o=new Error("Unauthorized: User or roles missing");throw o.cause={statusCode:403},o}let s=t.roles.flatMap(o=>o?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(f=>typeof f=="string"?f:f&&typeof f=="object"&&f.actions?f.actions:[]))||[]);if(!n.every(o=>s.some(a=>De(a,o)))){let o=new Error("Unauthorized");throw o.cause={statusCode:403},o}return!0}function De(t,e){if(t==="*"||t===e)return!0;if(!t.includes("*"))return!1;let r=t.split("*").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`).test(e)}function fe(t,e,r,n,s){let i=t.find(c=>c.service===e);if(!i){let c=new Error(`Function bindings do not include access to service: ${e}`);throw c.cause={statusCode:403},c}if(!i.permissions||i.permissions.length===0)return;for(let c of i.permissions)if(!(c.resource&&c.resource!==r)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(n)&&!(c.targets&&c.targets.length>0&&(!s||!c.targets.includes(s)&&!c.targets.includes("*"))))return}let o=s?`:${s}`:"",a=new Error(`Function bindings do not allow: ${e}.${r}.${n}${o}`);throw a.cause={statusCode:403},a}import{readFileSync as Le,existsSync as Ue}from"node:fs";function E(){let t=process.env.MOLNOS_RUNTIME_CONFIG,e={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!t||!Ue(t))return e;try{let r=Le(t,"utf-8");return JSON.parse(r)}catch(r){return console.error("[loadRuntimeConfig] Failed to load runtime config:",r),e}}async function x(t,e,r,n,s,i,o){if(!e)return null;let a=t.headers["x-molnos-service-token"];if(a){let l=E();if(l.internalServiceSecret&&a===l.internalServiceSecret)return null}let c=t.state.user;if(!c){let l=t.headers.authorization;if(!l){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let u=l.replace(/^Bearer\s+/i,"");if(c=await e.getUserFromToken(u),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}de(c,r,{});let f=t.headers["x-function-bindings"];if(f)try{let l=Array.isArray(f)?f[0]:f,u=JSON.parse(l);fe(u,n,s,i,o)}catch(l){if(l.cause?.statusCode===403)throw l;let u=new Error("Invalid function bindings header");throw u.cause={statusCode:400},u}return c}var w={ai:{generation:{generate:"ai.generation.generate",read:"ai.generation.read",apply:"ai.generation.apply",discard:"ai.generation.discard",delete:"ai.generation.delete"}},applications:{application:{create:"applications.application.create",read:"applications.application.read",list:"applications.application.list",update:"applications.application.update",delete:"applications.application.delete"}},contexts:{context:{create:"contexts.context.create",get:"contexts.context.get",update:"contexts.context.update",delete:"contexts.context.delete",deleteResources:"contexts.context.delete-resources"}},databases:{table:{create:"databases.table.create",get:"databases.table.get",update:"databases.table.update",delete:"databases.table.delete"}},functions:{function:{create:"functions.function.create",get:"functions.function.get",update:"functions.function.update",delete:"functions.function.delete",execute:"functions.function.execute"}},iac:{config:{create:"iac.config.create",get:"iac.config.get"}},identity:{identities:{get:"identity.identities.get"},user:{create:"identity.user.create",get:"identity.user.get",update:"identity.user.update",delete:"identity.user.delete"},role:{create:"identity.role.create",get:"identity.role.get",update:"identity.role.update",delete:"identity.role.delete"},serviceAccount:{create:"identity.service-account.create",get:"identity.service-account.get",update:"identity.service-account.update",delete:"identity.service-account.delete"}},management:{service:{create:"management.service.create",get:"management.service.get",update:"management.service.update",delete:"management.service.delete",start:"management.service.start",stop:"management.service.stop"},services:{get:"management.services.get"}},observability:{event:{create:"observability.event.create",read:"observability.event.read",delete:"observability.event.delete"},stats:{read:"observability.stats.read"},buffer:{write:"observability.buffer.write"},metrics:{read:"observability.metrics.read"}},schemas:{schema:{create:"schemas.schema.create",read:"schemas.schema.read",list:"schemas.schema.list",update:"schemas.schema.update",delete:"schemas.schema.delete"}},sites:{project:{create:"sites.project.create",list:"sites.project.list",delete:"sites.project.delete",download:"sites.project.download"}},storage:{bucket:{create:"storage.bucket.create",read:"storage.bucket.read",update:"storage.bucket.update",delete:"storage.bucket.delete",list:"storage.bucket.list"},object:{write:"storage.object.write",read:"storage.object.read",delete:"storage.object.delete",list:"storage.object.list"}}};function pe(t,e){if(typeof t=="string"){e.push(t);return}if(!(!t||typeof t!="object"))for(let r of Object.values(t))pe(r,e)}var he=[];pe(w,he);var qe=[...new Set(he)],pr=Object.freeze(qe);var ge={properties:{id:{type:"string",minLength:1,maxLength:40,pattern:"^[a-zA-Z0-9_-]{1,40}$"},name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},trigger:{type:"object"},triggers:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["http","event"]},eventName:{type:"string"}},required:["type"]}},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"},context:{type:"string",minLength:1}},required:["name","code"],additionalProperties:!1};var Ve=new O(!0);async function me(t,e,r){try{let n=await j(t),s=Ve.test(ge,n);if(!s.success)return t.json({error:"Invalid input",details:s.errors},400);await x(t,r,w.functions.function.create,"functions","function","create");let{id:i,name:o,code:a,methods:c,bindings:f,trigger:l,triggers:u,passAllHeaders:d,allowUnauthenticated:h}=n,p=u||(l?[l]:void 0),g=await e.deployFunction(o,a,c,f,p,d,h,i);return t.json({success:!0,function:g},201)}catch(n){let{message:s,status:i}=S(n,"Error deploying function");return t.json({error:s},i)}}async function ye(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);let s=e.getFunction(n);return s?s.triggers&&s.triggers.length>0&&!s.triggers.some(i=>i.type==="http")?t.json({error:"Not Found",message:"Function not found"},404):(s.allowUnauthenticated!==!0&&await x(t,r,w.functions.function.execute,"functions","function","execute",n),await e.executeFunction(n,t)):t.json({error:"Not Found",message:"Function not found"},404)}catch(n){let{message:s,status:i}=S(n,"Error executing function");return t.json({error:s},i)}}var ve={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},trigger:{type:"object"},triggers:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["http","event"]},eventName:{type:"string"}},required:["type"]}},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var _e=new O(!0);async function be(t,e,r){try{let n=t.params.functionId,s=await j(t);if(!n)return t.json({error:"functionId is required"},400);let i=_e.test(ve,s);if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);await x(t,r,w.functions.function.update,"functions","function","update",n);let{code:o,methods:a,bindings:c,trigger:f,triggers:l,passAllHeaders:u,allowUnauthenticated:d}=s,h=l||(f?[f]:void 0),p=await e.updateFunction(n,{code:o,methods:a,bindings:c,triggers:h,passAllHeaders:u,allowUnauthenticated:d});return p?t.json({success:!0,function:p},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=S(n,"Error updating function");return t.json({error:s},i)}}async function we(t,e,r){try{let n=t.params.functionId;return n?(await x(t,r,w.functions.function.delete,"functions","function","delete",n),await e.deleteFunction(n)?t.json({success:!0,message:"Function deleted"},200):t.json({error:"Function not found"},404)):t.json({error:"functionId is required"},400)}catch(n){let{message:s,status:i}=S(n,"Error deleting function");return t.json({error:s},i)}}async function Se(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);await x(t,r,w.functions.function.get,"functions","function","read",n);let s=e.getFunction(n);return s?t.json({success:!0,function:s},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=S(n,"Error getting function");return t.json({error:s},i)}}async function xe(t,e,r,n){try{await x(t,r,w.functions.function.get,"functions","function","read");let s=e.getFunctions(),i=t.query.context;if(i&&n){let o=t.headers.authorization?.replace(/^Bearer\s+/i,""),a=await n.listResourcesByType(i,"function",o);s=s.filter(c=>a.includes(c.id))}return t.json({success:!0,count:s.length,functions:s},200)}catch(s){let{message:i,status:o}=S(s,"Error listing functions");return t.json({error:i},o)}}import{EventEmitter as Ge}from"node:events";var Q=class t{static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new Ge,t.instance.setMaxListeners(100)),t.instance}};function ee(){return Q.getInstance()}function Ee(t){let e=ee();try{e.emit("function.log",t)}catch(r){console.error("Failed to emit function log event:",r)}}import{getRandomValues as Je}from"node:crypto";var te=class{options;defaultLength=16;defaultOnlyLowerCase=!1;defaultStyle="extended";defaultUrlSafe=!0;constructor(t){if(this.options={},t)for(let[e,r]of Object.entries(t))this.options[e]=this.generateConfig(r)}add(t){if(!t?.name)throw new Error("Missing name for the ID configuration");let e=this.generateConfig(t);this.options[t.name]=e}remove(t){if(!t?.name)throw new Error("Missing name for the ID configuration");delete this.options[t.name]}create(t,e,r,n){let s=this.generateConfig({length:t,style:e,onlyLowerCase:r,urlSafe:n});return this.generateId(s)}custom(t){if(this.options[t])return this.generateId(this.options[t]);throw new Error(`No configuration found with name: ${t}`)}generateConfig(t){return{name:t?.name||"",length:t?.length||this.defaultLength,onlyLowerCase:t?.onlyLowerCase??this.defaultOnlyLowerCase,style:t?.style||this.defaultStyle,urlSafe:t?.urlSafe??this.defaultUrlSafe}}getCharacterSet(t,e,r){if(t==="hex")return e?"0123456789abcdef":"0123456789ABCDEFabcdef";if(t==="alphanumeric")return e?"abcdefghijklmnopqrstuvwxyz0123456789":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";if(t==="extended")return r?e?"abcdefghijklmnopqrstuvwxyz0123456789-._~":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~":e?"abcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:";throw new Error(`Unknown ID style "${t} provided. Must be one of "extended" (default), "alphanumeric", or "hex".`)}generateId(t){let{length:e,onlyLowerCase:r,style:n,urlSafe:s}=t;if(e<0||e===0)throw new Error("ID length cannot be negative");let i=this.getCharacterSet(n,r,s),o=(2<<Math.log(i.length-1)/Math.LN2)-1,a=Math.ceil(1.6*o*e/i.length),c="";for(;c.length<e;){let f=new Uint8Array(a);Je(f);for(let l=0;l<a;l++){let u=f[l]&o;if(u<i.length&&(c+=i[u],c.length===e))break}}return c}};var We=8,Xe=40,Ye=/^[a-zA-Z0-9_-]{1,40}$/;function Ze(){return new te().create(We,"alphanumeric",!1,!0)}function Ke(t){return Ye.test(t)}function Qe(t){if(!Ke(t))throw new Error(`Invalid ID format: "${t}". IDs must be 1-${Xe} characters using only alphanumeric characters, underscores, and hyphens.`)}function re(t){return t?(Qe(t),t):Ze()}import{EventEmitter as et}from"events";var ne=class{emitter;targets={};options;constructor(t){this.emitter=new et,t?.maxListeners===0?this.emitter.setMaxListeners(0):this.emitter.setMaxListeners(t?.maxListeners||10),this.options={errorHandler:t?.errorHandler||(e=>console.error(e)),isSilent:t?.isSilent||!1}}addTarget(t){return(Array.isArray(t)?t:[t]).map(n=>this.targets[n.name]?(this.options.isSilent||console.error(`Target with name '${n.name}' already exists.`),!1):(this.targets[n.name]={name:n.name,url:n.url,headers:n.headers||{},events:n.events||[]},!0)).every(n=>n===!0)}updateTarget(t,e){if(!this.targets[t])return console.error(`Target with name '${t}' does not exist.`),!1;let r=this.targets[t];return e.url!==void 0&&(r.url=e.url),e.headers&&(r.headers={...r.headers,...e.headers}),e.events&&(r.events=e.events),!0}removeTarget(t){return this.targets[t]?(delete this.targets[t],!0):(console.error(`Target with name '${t}' does not exist.`),!1)}addEventToTarget(t,e){if(!this.targets[t])return console.error(`Target with name '${t}' does not exist.`),!1;let r=Array.isArray(e)?e:[e],n=this.targets[t];return r.forEach(s=>{n.events.includes(s)||n.events.push(s)}),!0}on(t,e){return this.emitter.on(t,e),this}off(t,e){return this.emitter.off(t,e),this}once(t,e){return this.emitter.once(t,e),this}async emit(t,e){let r={success:!0,errors:[]},n=(o,a,c)=>({target:o,event:a,error:c}),s=Object.values(this.targets).filter(o=>o.events.includes(t)||o.events.includes("*"));s.filter(o=>!o.url).forEach(o=>{try{this.emitter.emit(t,e)}catch(a){let c=a instanceof Error?a:new Error(String(a));r.errors.push({target:o.name,event:t,error:c}),this.options.errorHandler(c,t,e),r.success=!1}});let i=s.filter(o=>o.url);if(i.length>0){let o=i.map(async a=>{try{let c=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json",...a.headers},body:JSON.stringify({eventName:t,data:e})});if(!c.ok){let f=`HTTP error! Status: ${c.status}: ${c.statusText}`,l=new Error(f);r.errors.push(n(a.name,t,l)),this.options.errorHandler(l,t,e),r.success=!1}}catch(c){let f=c instanceof Error?c:new Error(String(c));r.errors.push(n(a.name,t,f)),this.options.errorHandler(f,t,e),r.success=!1}});await Promise.allSettled(o)}return r}async handleIncomingEvent(t){try{let{eventName:e,data:r}=typeof t=="string"?JSON.parse(t):t;process.nextTick(()=>{try{this.emitter.emit(e,r)}catch(n){this.options.errorHandler(n instanceof Error?n:new Error(String(n)),e,r)}})}catch(e){throw this.options.errorHandler(e instanceof Error?e:new Error(String(e)),"parse_event"),e}}createMiddleware(){return async(t,e,r)=>{if(t.method!=="POST"){r&&r();return}if(t.body)try{await this.handleIncomingEvent(t.body),e.statusCode=202,e.end()}catch(n){e.statusCode=400,e.end(JSON.stringify({error:"Invalid event format"})),r&&r(n)}else{let n="";t.on("data",s=>n+=s.toString()),t.on("end",async()=>{try{await this.handleIncomingEvent(n),e.statusCode=202,e.end()}catch(s){e.statusCode=400,e.end(JSON.stringify({error:"Invalid event format"})),r&&r(s)}})}}}};var U=null;function k(){return U||(U=new ne,U.addTarget({name:"molnos-internal",events:["*"]})),U}var tt=null;function se(){return tt||void 0}function Ce(t,e){let r={enabled:!1,requestsPerMinute:0};if(!e)return r;let n=e.services?.[t];return n||(e.global?e.global:r)}function Pe(t,e){let r=t?.api?.port;if(!r)throw new Error('Missing "port" input when create API service!');let n=E(),s=t?.dataPath||n.molnos.dataPath,i=t?.api?.host||n.server.host,o=t?.identityApiUrl!==void 0?t.identityApiUrl:n.identity.apiUrl,a=t?.contextApiUrl!==void 0?t.contextApiUrl:n.context.apiUrl,c=t?.debug||!1,f;return e&&(f=Ce(e,n.molnos.rateLimit)),{dataPath:s,api:{port:r,host:i},...o?{identityApiUrl:o}:{},...a?{contextApiUrl:a}:{},...f?{rateLimit:f}:{},debug:c}}var q=class{baseUrl;authToken;constructor(e,r){this.baseUrl=e.replace(/\/$/,""),this.authToken=r}async createCustomRole(e,r,n,s){let i=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:e,name:r,description:n,permissions:s})});if(!i.ok){let o=`Failed to create role: ${i.statusText}`;try{o=(await i.json()).error||o}catch{o=await i.text().catch(()=>i.statusText)||o}throw new Error(o)}}async updateRole(e,r){let n=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let s=await n.json();throw new Error(s.error||`Failed to update role: ${n.statusText}`)}}async deleteRole(e){let r=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete role: ${r.statusText}`)}}async addServiceAccount(e,r,n){let s=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:e,description:r,roles:n})});if(!s.ok){let o=`Failed to create service account: ${s.statusText}`;try{o=(await s.json()).error||o}catch{o=await s.text().catch(()=>s.statusText)||o}throw new Error(o)}let i=await s.json();return{id:i.id,apiKey:i.apiKey}}async deleteIdentity(e){let r=await fetch(`${this.baseUrl}/identity/service-accounts/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete service account: ${r.statusText}`)}}async getUserFromToken(e){try{let r=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return r.ok?await r.json():null}catch{return null}}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}};function Te(t){return t?new q(t):null}var B=class{baseUrl;constructor(e){this.baseUrl=e.replace(/\/$/,"")}async listResourcesByType(e,r,n){let s=`${this.baseUrl}/contexts/${encodeURIComponent(e)}`;try{let i={"Content-Type":"application/json"};n&&(i.Authorization=`Bearer ${n}`);let o=await fetch(s,{method:"GET",headers:i});if(!o.ok)return[];let c=(await o.json()).context?.resources||{};switch(r){case"function":return c.functions||[];case"database":return c.databases||[];case"storage":return c.storage||[];case"site":return c.sites||[];default:return[]}}catch{return[]}}};function Ie(t){return t?new B(t):null}var oe=class t{static MAX_EVENT_CHAIN_DEPTH=10;functionsDir;functions=new Map;eventHandlers=new Map;eventChainDepth=0;debug;bindingService;constructor(e){this.functionsDir=e.functionsDir||M(process.cwd(),"functions-data"),this.debug=e.debug||!1,this.bindingService=new L}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions(),this.subscribeEventTriggeredFunctions()}getFunction(e){return this.functions.get(e)}getFunctions(){return Array.from(this.functions.values()).map(e=>({name:e.name,endpoint:e.endpoint,id:e.id,filePath:e.filePath,methods:e.methods,...e.bindings?{bindings:e.bindings}:{},...e.triggers&&e.triggers.length>0?{triggers:e.triggers}:{},...e.passAllHeaders!==void 0?{passAllHeaders:e.passAllHeaders}:{},...e.allowUnauthenticated!==void 0?{allowUnauthenticated:e.allowUnauthenticated}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}))}async ensureFunctionsDirExists(){V(this.functionsDir)||await rt(this.functionsDir,{recursive:!0})}async loadExistingFunctions(){try{let e=M(this.functionsDir,"functions.json");if(V(e)){let r=await je(e,"utf8"),n=JSON.parse(r);for(let s of n)V(s.filePath)&&this.functions.set(s.id,s)}}catch{}}async saveFunctionsMetadata(){try{let e=M(this.functionsDir,"functions.json"),r=Array.from(this.functions.values());await ie(e,JSON.stringify(r,null,2),"utf8")}catch{}}async deployFunction(e,r,n,s,i,o,a,c){if(!e||typeof e!="string")throw new v("Function name is required and must be a string");if(!r||typeof r!="string")throw new v("Function code is required and must be a string");if(n!==void 0){if(!Array.isArray(n))throw new v("Methods must be an array");let p=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let g of n)if(!p.includes(g.toUpperCase()))throw new F(`Invalid HTTP method: ${g}. Must be one of: ${p.join(", ")}`)}if(s&&s.length>0&&this.bindingService.validateBindings(s),i&&i.length>0){for(let p of i)if(p.type==="event"&&!p.eventName)throw new v("Event trigger must specify an eventName")}let f=re(c),l=M(this.functionsDir,`${f}.mjs`),u=this.wrapFunctionCode(r);await ie(l,u,"utf8");let d=Date.now(),h={id:f,name:e,filePath:l,endpoint:`/functions/run/${f}`,...n&&n.length>0?{methods:n.map(p=>p.toUpperCase())}:{},...s?{bindings:s}:{},...i&&i.length>0?{triggers:i}:{},...o!==void 0?{passAllHeaders:o}:{},...a!==void 0?{allowUnauthenticated:a}:{},createdAt:d,updatedAt:d};return this.functions.set(f,h),await this.saveFunctionsMetadata(),this.subscribeToEvents(h),h}async updateFunction(e,r){let n=this.functions.get(e);if(!n)throw new N(`Function with ID ${e} not found`);let{code:s,methods:i,bindings:o,triggers:a,passAllHeaders:c,allowUnauthenticated:f}=r;if(s===void 0&&i===void 0&&o===void 0&&a===void 0&&c===void 0&&f===void 0)throw new v("At least one parameter (code, methods, bindings, triggers, passAllHeaders, or allowUnauthenticated) must be provided");if(s!==void 0&&(typeof s!="string"||!s))throw new v("Function code must be a non-empty string");if(i!==void 0){if(!Array.isArray(i))throw new v("Methods must be an array");let l=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let u of i)if(!l.includes(u.toUpperCase()))throw new F(`Invalid HTTP method: ${u}. Must be one of: ${l.join(", ")}`)}if(s!==void 0){let l=this.wrapFunctionCode(s);await ie(n.filePath,l,"utf8")}if(i!==void 0&&(i.length>0?n.methods=i.map(l=>l.toUpperCase()):delete n.methods),o!==void 0&&(o.length>0&&this.bindingService.validateBindings(o),n.bindings=o.length>0?o:void 0),c!==void 0&&(c?n.passAllHeaders=!0:delete n.passAllHeaders),a!==void 0){for(let l of a)if(l.type==="event"&&!l.eventName)throw new v("Event trigger must specify an eventName");this.unsubscribeFromEvents(e),n.triggers=a.length>0?a:void 0,this.subscribeToEvents(n)}return f!==void 0&&(n.allowUnauthenticated=f),n.updatedAt=Date.now(),this.functions.set(e,n),await this.saveFunctionsMetadata(),n}async deleteFunction(e){let r=this.functions.get(e);if(!r)return!1;try{return this.unsubscribeFromEvents(e),V(r.filePath)&&await nt(r.filePath),this.functions.delete(e),await this.saveFunctionsMetadata(),!0}catch(n){throw console.error(`Error deleting function ${e}:`,n.message),n}}wrapFunctionCode(e){let r=e;if(/export\s+default\s+\w+/.test(e))return`// FunctionsService generated module
12
12
  // Generated at: ${new Date().toISOString()}
13
13
 
14
14
  // User function code starts here
@@ -22,4 +22,4 @@ export default handler;`;return`// FunctionsService generated module
22
22
  // User function code starts here
23
23
  ${r}
24
24
  // User function code ends here
25
- `}async executeFunction(e,r){try{let n=this.functions.get(e);if(!n)return r.json({error:"Not Found",message:"Function not found"},404);if(n.triggers&&n.triggers.length>0&&!n.triggers.some(p=>p.type==="http"))return r.json({error:"Not Found",message:"Function not found"},404);if(n.allowUnauthenticated!==!0&&!r.headers.authorization)return r.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(n.methods&&n.methods.length>0){let p=(r.req.method||"GET").toUpperCase();if(!n.methods.includes(p)){let h=n.methods.join(", "),g=r.json({error:"Method Not Allowed",message:`This function only accepts: ${h}`},405);return g.headers={...g.headers||{},allow:h},g}}let s=null;try{let p=r.req.method||"GET";["POST","PUT","PATCH"].includes(p)&&((r.headers["content-type"]||"").includes("application/json")?s=await F(r):s=r.body)}catch{}let i=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],o={},a=r.req.headers;for(let[p,h]of Object.entries(a))(n.passAllHeaders||!i.includes(p.toLowerCase()))&&(o[p]=h);let c=new URL(r.req.url||"","http://127.0.0.1").pathname,f=`/run/${e}`,l=c.startsWith(f)?c.substring(f.length):"/";l||(l="/");let u={};if(n.bindings&&n.bindings.length>0){let h=r.headers.authorization?.replace(/^Bearer\s+/i,"")||null,g=x(),m={databases:g.services.databases.url,storage:g.services.storage.url,observability:g.services.observability.url,sites:g.services.sites.url,functions:g.services.functions.url};u=new j(m,h,H(),ne()).createBindings(n.bindings)}let d={request:{method:r.req.method||"GET",path:c,subpath:l,query:r.query,headers:o,body:s},functionId:e,functionName:n.name,bindings:u};try{let g=(await import(`${Te(n.filePath).href}?t=${Date.now()}`)).default;if(typeof g!="function")return r.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:m,restore:C}=this.createConsoleInterceptor(e,n.name);Object.assign(console,m);let y;try{y=await g(d.request,d)}finally{C()}if(y&&typeof y=="object"){if(y.statusCode!==void 0&&y.body!==void 0){let A=y.statusCode||200,E=y.headers||{};if(typeof y.body=="object"){let P=r.json(y.body,A);return Object.keys(E).length>0&&(P.headers={...P.headers||{},...E}),P}let T=r.text(y.body,A);return Object.keys(E).length>0&&(T.headers={...T.headers||{},...E}),T}return r.json(y)}return typeof y=="string"?r.text(y):typeof y=="number"||typeof y=="boolean"?r.json({result:y}):r.json({result:y===null?null:void 0})}catch(p){return console.error("Function execution error:",p),r.json({error:"Function Execution Error",message:this.debug?p.message:"Error executing function",stack:this.debug?p.stack:void 0},500)}}catch(n){return console.error("Error processing function execution:",n),r.json({error:"Internal Server Error",message:this.debug?n.message:"Failed to process function execution"},500)}}subscribeEventTriggeredFunctions(){for(let e of this.functions.values())this.subscribeToEvents(e)}subscribeToEvents(e){if(!e.triggers||e.triggers.length===0)return;this.unsubscribeFromEvents(e.id);let r=H();for(let n of e.triggers){if(n.type!=="event"||!n.eventName)continue;let s=n.eventName,i=async a=>{await this.executeFunctionFromEvent(e.id,s,a)},o=`${e.id}:${s}`;this.eventHandlers.set(o,i),r.on(s,i)}}unsubscribeFromEvents(e){let r=H(),n=`${e}:`;for(let[s,i]of this.eventHandlers.entries())if(s.startsWith(n)){let o=s.substring(n.length);r.off(o,i),this.eventHandlers.delete(s)}}async executeFunctionFromEvent(e,r,n){if(this.eventChainDepth>=t.MAX_EVENT_CHAIN_DEPTH){console.error(`Event chain depth limit (${t.MAX_EVENT_CHAIN_DEPTH}) exceeded. Dropping event "${r}" for function "${e}". This likely indicates an infinite loop.`);return}let s=this.functions.get(e);if(s){this.eventChainDepth++;try{let i={};if(s.bindings&&s.bindings.length>0){let p=x(),h={databases:p.services.databases.url,storage:p.services.storage.url,observability:p.services.observability.url,sites:p.services.sites.url,functions:p.services.functions.url};i=new j(h,null,H(),ne()).createBindings(s.bindings)}let o={eventName:r,data:n,timestamp:Date.now(),id:te()},a={functionId:e,functionName:s.name,bindings:i},l=(await import(`${Te(s.filePath).href}?t=${Date.now()}`)).default;if(typeof l!="function")return;let{interceptedConsole:u,restore:d}=this.createConsoleInterceptor(e,s.name);Object.assign(console,u);try{return await l(o,a)}finally{d()}}catch(i){console.error(`Event-triggered function execution error (${e}):`,i.message)}finally{this.eventChainDepth--}}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(r=>({id:r.id,name:r.name,endpoint:r.endpoint,createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()}))}}createConsoleInterceptor(e,r){let n={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),debug:console.debug.bind(console)},s=(i,o)=>{let a=o.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" ");we({functionId:e,functionName:r,level:i,message:a,timestamp:Date.now()})};return{interceptedConsole:{log:(...i)=>{n.log(...i),s("info",i)},error:(...i)=>{n.error(...i),s("error",i)},warn:(...i)=>{n.warn(...i),s("warn",i)},info:(...i)=>{n.info(...i),s("info",i)},debug:(...i)=>{n.debug(...i),s("debug",i)}},restore:()=>{console.log=n.log,console.error=n.error,console.warn=n.warn,console.info=n.info,console.debug=n.debug}}}};async function Qe(t){let e=t.dataPath||"data",r=k(e,"functions"),n=t.debug||!1,s=new ie({functionsDir:r,debug:n});await s.start();let i=Ce(t.identityApiUrl),o=Ee(t.contextApiUrl),a=Q(),c=x(),f=c.services.observability.url,l=c.internalServiceSecret;a.on("function.log",h=>{let g={"Content-Type":"application/json"};l&&(g["x-molnos-service-token"]=l),fetch(`${f}/events`,{method:"POST",headers:g,body:JSON.stringify({service:`functions.${h.functionId}`,level:h.level,message:h.message,metadata:{functionId:h.functionId,functionName:h.functionName,...h.metadata}})}).catch(m=>{n&&console.error("Failed to send log to observability service:",m)})});let u=new J({port:t.api.port||c.services.functions.port,host:t.api.host||c.services.functions.host,rateLimit:t.rateLimit||{enabled:!1,requestsPerMinute:0}});u.post("/deploy",async h=>he(h,s,i)),u.get("/list",async h=>be(h,s,i,o)),u.get("/stats",async h=>{try{let g=s.getStats();return h.json({success:!0,stats:g})}catch(g){return h.json({error:g.message},500)}}),u.get("/:functionId/config",async h=>{try{let g=h.params.functionId,m=s.getFunction(g);if(!m)return h.json({error:"Function not found"},404);let C="";try{let y=await Pe(m.filePath,"utf8"),A="// User function code starts here",E="// User function code ends here",T=y.indexOf(A),P=y.indexOf(E);T!==-1&&P!==-1?(C=y.substring(T+A.length,P).trim().replace(/^\n+/,"").replace(/\n+$/,""),C=C.replace(/\n*export\s+default\s+handler;\s*$/,"")):C=y}catch(y){return h.json({error:"Failed to read function code",message:y.message},500)}return h.json({success:!0,function:{id:m.id,name:m.name,endpoint:m.endpoint,filePath:m.filePath,code:C,...m.methods?{methods:m.methods}:{},...m.bindings?{bindings:m.bindings}:{},...m.triggers&&m.triggers.length>0?{triggers:m.triggers}:{},...m.passAllHeaders!==void 0?{passAllHeaders:m.passAllHeaders}:{},...m.allowUnauthenticated!==void 0?{allowUnauthenticated:m.allowUnauthenticated}:{},createdAt:new Date(m.createdAt).toISOString(),updatedAt:new Date(m.updatedAt).toISOString()}})}catch(g){return h.json({error:g.message},500)}}),u.get("/:functionId",async h=>ve(h,s,i)),u.put("/:functionId",async h=>me(h,s,i)),u.delete("/:functionId",async h=>ye(h,s,i));let d=async h=>pe(h,s,i);return u.get("/run/:functionId/*",d),u.post("/run/:functionId/*",d),u.put("/run/:functionId/*",d),u.patch("/run/:functionId/*",d),u.delete("/run/:functionId/*",d),u.get("/run/:functionId",d),u.post("/run/:functionId",d),u.put("/run/:functionId",d),u.patch("/run/:functionId",d),u.delete("/run/:functionId",d),u.start()}if(import.meta.url===`file://${process.argv[1]}`){let t=x(),r=process.argv.slice(2).find(i=>i.startsWith("--port=")),n=r?parseInt(r.split("=")[1],10):t.services.functions.port,s=xe({api:{port:n}},"functions");Qe(s)}export{ie as FunctionsService,Qe as startServer};
25
+ `}async executeFunction(e,r){try{let n=this.functions.get(e);if(!n)return r.json({error:"Not Found",message:"Function not found"},404);if(n.triggers&&n.triggers.length>0&&!n.triggers.some(h=>h.type==="http"))return r.json({error:"Not Found",message:"Function not found"},404);if(n.allowUnauthenticated!==!0&&!r.headers.authorization)return r.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(n.methods&&n.methods.length>0){let h=(r.req.method||"GET").toUpperCase();if(!n.methods.includes(h)){let p=n.methods.join(", "),g=r.json({error:"Method Not Allowed",message:`This function only accepts: ${p}`},405);return g.headers={...g.headers||{},allow:p},g}}let s=null;try{let h=r.req.method||"GET";["POST","PUT","PATCH"].includes(h)&&((r.headers["content-type"]||"").includes("application/json")?s=await j(r):s=r.body)}catch{}let i=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],o={},a=r.req.headers;for(let[h,p]of Object.entries(a))(n.passAllHeaders||!i.includes(h.toLowerCase()))&&(o[h]=p);let c=new URL(r.req.url||"","http://127.0.0.1").pathname,f=`/run/${e}`,l=c.startsWith(f)?c.substring(f.length):"/";l||(l="/");let u={};if(n.bindings&&n.bindings.length>0){let p=r.headers.authorization?.replace(/^Bearer\s+/i,"")||null,g=E(),m={databases:g.services.databases.url,storage:g.services.storage.url,observability:g.services.observability.url,sites:g.services.sites.url,functions:g.services.functions.url};u=new $(m,p,k(),se()).createBindings(n.bindings)}let d={request:{method:r.req.method||"GET",path:c,subpath:l,query:r.query,headers:o,body:s},functionId:e,functionName:n.name,bindings:u};try{let g=(await import(`${Re(n.filePath).href}?t=${Date.now()}`)).default;if(typeof g!="function")return r.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:m,restore:C}=this.createConsoleInterceptor(e,n.name);Object.assign(console,m);let y;try{y=await g(d.request,d)}finally{C()}if(y&&typeof y=="object"){if(y.statusCode!==void 0&&y.body!==void 0){let A=y.statusCode||200,P=y.headers||{};if(typeof y.body=="object"){let I=r.json(y.body,A);return Object.keys(P).length>0&&(I.headers={...I.headers||{},...P}),I}let T=r.text(y.body,A);return Object.keys(P).length>0&&(T.headers={...T.headers||{},...P}),T}return r.json(y)}return typeof y=="string"?r.text(y):typeof y=="number"||typeof y=="boolean"?r.json({result:y}):r.json({result:y===null?null:void 0})}catch(h){return console.error("Function execution error:",h),r.json({error:"Function Execution Error",message:this.debug?h.message:"Error executing function",stack:this.debug?h.stack:void 0},500)}}catch(n){return console.error("Error processing function execution:",n),r.json({error:"Internal Server Error",message:this.debug?n.message:"Failed to process function execution"},500)}}subscribeEventTriggeredFunctions(){for(let e of this.functions.values())this.subscribeToEvents(e)}subscribeToEvents(e){if(!e.triggers||e.triggers.length===0)return;this.unsubscribeFromEvents(e.id);let r=k();for(let n of e.triggers){if(n.type!=="event"||!n.eventName)continue;let s=n.eventName,i=async a=>{await this.executeFunctionFromEvent(e.id,s,a)},o=`${e.id}:${s}`;this.eventHandlers.set(o,i),r.on(s,i)}}unsubscribeFromEvents(e){let r=k(),n=`${e}:`;for(let[s,i]of this.eventHandlers.entries())if(s.startsWith(n)){let o=s.substring(n.length);r.off(o,i),this.eventHandlers.delete(s)}}async executeFunctionFromEvent(e,r,n){if(this.eventChainDepth>=t.MAX_EVENT_CHAIN_DEPTH){console.error(`Event chain depth limit (${t.MAX_EVENT_CHAIN_DEPTH}) exceeded. Dropping event "${r}" for function "${e}". This likely indicates an infinite loop.`);return}let s=this.functions.get(e);if(s){this.eventChainDepth++;try{let i={};if(s.bindings&&s.bindings.length>0){let h=E(),p={databases:h.services.databases.url,storage:h.services.storage.url,observability:h.services.observability.url,sites:h.services.sites.url,functions:h.services.functions.url};i=new $(p,null,k(),se()).createBindings(s.bindings)}let o={eventName:r,data:n,timestamp:Date.now(),id:re()},a={functionId:e,functionName:s.name,bindings:i},l=(await import(`${Re(s.filePath).href}?t=${Date.now()}`)).default;if(typeof l!="function")return;let{interceptedConsole:u,restore:d}=this.createConsoleInterceptor(e,s.name);Object.assign(console,u);try{return await l(o,a)}finally{d()}}catch(i){console.error(`Event-triggered function execution error (${e}):`,i.message)}finally{this.eventChainDepth--}}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(r=>({id:r.id,name:r.name,endpoint:r.endpoint,createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()}))}}createConsoleInterceptor(e,r){let n={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),debug:console.debug.bind(console)},s=(i,o)=>{let a=o.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" ");Ee({functionId:e,functionName:r,level:i,message:a,timestamp:Date.now()})};return{interceptedConsole:{log:(...i)=>{n.log(...i),s("info",i)},error:(...i)=>{n.error(...i),s("error",i)},warn:(...i)=>{n.warn(...i),s("warn",i)},info:(...i)=>{n.info(...i),s("info",i)},debug:(...i)=>{n.debug(...i),s("debug",i)}},restore:()=>{console.log=n.log,console.error=n.error,console.warn=n.warn,console.info=n.info,console.debug=n.debug}}}};async function st(t){let e=t.dataPath||"data",r=M(e,"functions"),n=t.debug||!1,s=new oe({functionsDir:r,debug:n});await s.start();let i=Te(t.identityApiUrl),o=Ie(t.contextApiUrl),a=ee(),c=E(),f=c.services.observability.url,l=c.internalServiceSecret;a.on("function.log",p=>{let g={"Content-Type":"application/json"};l&&(g["x-molnos-service-token"]=l),fetch(`${f}/events`,{method:"POST",headers:g,body:JSON.stringify({service:`functions.${p.functionId}`,level:p.level,message:p.message,metadata:{functionId:p.functionId,functionName:p.functionName,...p.metadata}})}).catch(m=>{n&&console.error("Failed to send log to observability service:",m)})});let u=new W({port:t.api.port||c.services.functions.port,host:t.api.host||c.services.functions.host,rateLimit:t.rateLimit||{enabled:!1,requestsPerMinute:0}});u.post("/deploy",async p=>me(p,s,i)),u.get("/list",async p=>xe(p,s,i,o)),u.get("/stats",async p=>{try{let g=s.getStats();return p.json({success:!0,stats:g})}catch(g){return p.json({error:g.message},500)}}),u.get("/:functionId/config",async p=>{try{let g=p.params.functionId,m=s.getFunction(g);if(!m)return p.json({error:"Function not found"},404);let C="";try{let y=await je(m.filePath,"utf8"),A="// User function code starts here",P="// User function code ends here",T=y.indexOf(A),I=y.indexOf(P);T!==-1&&I!==-1?(C=y.substring(T+A.length,I).trim().replace(/^\n+/,"").replace(/\n+$/,""),C=C.replace(/\n*export\s+default\s+handler;\s*$/,"")):C=y}catch(y){return p.json({error:"Failed to read function code",message:y.message},500)}return p.json({success:!0,function:{id:m.id,name:m.name,endpoint:m.endpoint,filePath:m.filePath,code:C,...m.methods?{methods:m.methods}:{},...m.bindings?{bindings:m.bindings}:{},...m.triggers&&m.triggers.length>0?{triggers:m.triggers}:{},...m.passAllHeaders!==void 0?{passAllHeaders:m.passAllHeaders}:{},...m.allowUnauthenticated!==void 0?{allowUnauthenticated:m.allowUnauthenticated}:{},createdAt:new Date(m.createdAt).toISOString(),updatedAt:new Date(m.updatedAt).toISOString()}})}catch(g){return p.json({error:g.message},500)}}),u.get("/:functionId",async p=>Se(p,s,i)),u.put("/:functionId",async p=>be(p,s,i)),u.delete("/:functionId",async p=>we(p,s,i));let d=async p=>ye(p,s,i);return u.get("/run/:functionId/*",d),u.post("/run/:functionId/*",d),u.put("/run/:functionId/*",d),u.patch("/run/:functionId/*",d),u.delete("/run/:functionId/*",d),u.get("/run/:functionId",d),u.post("/run/:functionId",d),u.put("/run/:functionId",d),u.patch("/run/:functionId",d),u.delete("/run/:functionId",d),u.start()}if(import.meta.url===`file://${process.argv[1]}`){let t=E(),r=process.argv.slice(2).find(i=>i.startsWith("--port=")),n=r?parseInt(r.split("=")[1],10):t.services.functions.port,s=Pe({api:{port:n}},"functions");st(s)}export{oe as FunctionsService,st as startServer};