molnos 1.0.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/LICENSE ADDED
@@ -0,0 +1,89 @@
1
+ MolnOS Commercial Software License
2
+
3
+ Copyright (c) 2025-present Mikael Vesavuori
4
+
5
+ PROPRIETARY SOFTWARE - NOT OPEN SOURCE
6
+
7
+ This software is proprietary and confidential. Unauthorized copying, modification,
8
+ distribution, or use is strictly prohibited.
9
+
10
+ ================================================================================
11
+ IMPORTANT NOTICE
12
+ ================================================================================
13
+
14
+ This LICENSE file is a SUMMARY ONLY and does not constitute the complete legal
15
+ agreement. The full Software License Agreement available at:
16
+
17
+ https://molnos.cloud/agreement
18
+
19
+ governs your use of this software and supersedes any conflicting terms in this
20
+ file. By using this software, you agree to be bound by the complete agreement.
21
+
22
+ ================================================================================
23
+ LICENSE GRANTS
24
+ ================================================================================
25
+
26
+ Subject to compliance with the full agreement at <https://molnos.cloud/agreement>,
27
+ licensed users are granted the following rights:
28
+
29
+ FREE LICENSE (Individual/Non-Commercial Use):
30
+
31
+ - Natural persons may use this software for personal, educational, or other
32
+ non-commercial purposes
33
+ - "Personal use" means use by an individual not acting on behalf of any
34
+ organization and not for commercial benefit
35
+
36
+ COMMERCIAL LICENSE (Organizational/Commercial Use):
37
+
38
+ - Organizations and commercial users must purchase a valid license
39
+ - Trial periods up to 30 days are permitted for evaluation purposes
40
+ - Licenses grant perpetual use of the major version purchased, including
41
+ all minor and patch updates to that major version
42
+ - Upgrades to new major versions require purchase of a new license
43
+
44
+ Licensed users may:
45
+
46
+ - Install and use the software on their own infrastructure
47
+ - Use the software according to their license tier and entitlements
48
+
49
+ ================================================================================
50
+ RESTRICTIONS
51
+ ================================================================================
52
+
53
+ You may NOT, without express written permission:
54
+
55
+ - Reverse engineer, decompile, or disassemble this software
56
+ - Distribute, sublicense, sell, lease, or transfer this software
57
+ - Remove, obscure, or modify any copyright, trademark, or license notices
58
+ - Use this software to provide hosted services or SaaS offerings to third parties
59
+ - Use this software for the primary purpose of developing competing products
60
+ - Exceed the scope or usage limits defined in your license tier
61
+
62
+ ================================================================================
63
+ WARRANTY DISCLAIMER
64
+ ================================================================================
65
+
66
+ THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
67
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
68
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS
69
+ TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU.
70
+
71
+ ================================================================================
72
+ LIMITATION OF LIABILITY
73
+ ================================================================================
74
+
75
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
76
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
77
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
78
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
79
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
80
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
81
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
82
+
83
+ ================================================================================
84
+ CONTACT & LICENSING
85
+ ================================================================================
86
+
87
+ For full terms and conditions: <https://molnos.cloud/agreement>
88
+ For licensing inquiries: <contact@molnos.cloud>
89
+ For general information: <https://molnos.cloud>
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # MolnOS Core
2
+
3
+ The core API for [MolnOS](https://molnos.cloud).
4
+
5
+ ## Quick Start
6
+
7
+ Create `molnos.config.json` in the project root (setting your own details):
8
+
9
+ ```json
10
+ {
11
+ "email": {
12
+ "emailSubject": "Sign In To MolnOS",
13
+ "user": "signin@molnos.cloud",
14
+ "password": "",
15
+ "host": "smtp.protonmail.ch",
16
+ "port": 465,
17
+ "secure": true,
18
+ "maxRetries": 2
19
+ },
20
+ "molnos": {
21
+ "dataPath": "data",
22
+ "initialUser": {
23
+ "userName": "user",
24
+ "email": "user@domain.com"
25
+ }
26
+ },
27
+ "auth": {
28
+ "jwtSecret": "your-jwt-secret",
29
+ "magicLinkExpirySeconds": 900,
30
+ "jwtExpirySeconds": 3600,
31
+ "refreshTokenExpirySeconds": 604800,
32
+ "maxActiveSessions": 3,
33
+ "consoleUrl": "http://localhost:8000"
34
+ },
35
+ "server": {
36
+ "allowedDomains": [
37
+ "*"
38
+ ]
39
+ }
40
+ }
41
+ ```
42
+
43
+ Start the server with:
44
+
45
+ ```bash
46
+ npm start
47
+ ```
48
+
49
+ The API will be available at `http://localhost:3000`.
50
+
51
+ ## Essential Commands
52
+
53
+ - `npm start` - Build and start the server
54
+ - `npm run start:clean` - Start with fresh database (wipes all data)
55
+ - `npm test` - Run linting and tests
56
+ - `npm run build` - Build for distribution
57
+
58
+ ## Using with MolnOS Console
59
+
60
+ When running the Console project locally, configure it to use Core's API URL:
61
+
62
+ ```text
63
+ http://localhost:3000
64
+ ```
65
+
66
+ The Console's API URL (configured in `auth.consoleUrl` above) should match the Console's running port, typically `http://localhost:8000`.
package/dist/bin.mjs ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Import from the built file to avoid double execution
4
+ // @ts-expect-error - molnos_core.mjs is generated at build time
5
+ import('./molnos_core.mjs');
@@ -0,0 +1,2 @@
1
+ // MolnOS Core - See LICENSE file for copyright and license details.
2
+ var ae=(e,t,s)=>(r,n)=>{let a=-1;return o(0);async function o(i){if(i<=a)throw new Error("next() called multiple times");a=i;let c,l=!1,h;if(e[i]?(h=e[i][0][0],r.req.routeIndex=i):h=i===e.length&&n||void 0,h)try{c=await h(r,()=>o(i+1))}catch(u){if(u instanceof Error&&t)r.error=u,c=await t(u,r),l=!0;else throw u}else r.finalized===!1&&s&&(c=await s(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}};var Pe=Symbol();var Ce=async(e,t=Object.create(null))=>{let{all:s=!1,dot:r=!1}=t,a=(e instanceof U?e.raw.headers:e.headers).get("Content-Type");return a?.startsWith("multipart/form-data")||a?.startsWith("application/x-www-form-urlencoded")?At(e,{all:s,dot:r}):{}};async function At(e,t){let s=await e.formData();return s?Mt(s,t):{}}function Mt(e,t){let s=Object.create(null);return e.forEach((r,n)=>{t.all||n.endsWith("[]")?Dt(s,n,r):s[n]=r}),t.dot&&Object.entries(s).forEach(([r,n])=>{r.includes(".")&&(Ht(s,r,n),delete s[r])}),s}var Dt=(e,t,s)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(s):e[t]=[e[t],s]:t.endsWith("[]")?e[t]=[s]:e[t]=s},Ht=(e,t,s)=>{let r=e,n=t.split(".");n.forEach((a,o)=>{o===n.length-1?r[a]=s:((!r[a]||typeof r[a]!="object"||Array.isArray(r[a])||r[a]instanceof File)&&(r[a]=Object.create(null)),r=r[a])})};var ie=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},je=e=>{let{groups:t,path:s}=kt(e),r=ie(s);return $t(r,t)},kt=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(s,r)=>{let n=`@${r}`;return t.push([n,s]),n}),{groups:t,path:e}},$t=(e,t)=>{for(let s=t.length-1;s>=0;s--){let[r]=t[s];for(let n=e.length-1;n>=0;n--)if(e[n].includes(r)){e[n]=e[n].replace(r,t[s][1]);break}}return e},V={},Oe=(e,t)=>{if(e==="*")return"*";let s=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(s){let r=`${e}#${t}`;return V[r]||(s[2]?V[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,s[1],new RegExp(`^${s[2]}(?=/${t})`)]:[e,s[1],new RegExp(`^${s[2]}$`)]:V[r]=[e,s[1],!0]),V[r]}return null},W=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,s=>{try{return t(s)}catch{return s}})}},Lt=e=>W(e,decodeURI),ce=e=>{let t=e.url,s=t.indexOf("/",t.indexOf(":")+4),r=s;for(;r<t.length;r++){let n=t.charCodeAt(r);if(n===37){let a=t.indexOf("?",r),o=t.slice(s,a===-1?void 0:a);return Lt(o.includes("%25")?o.replace(/%25/g,"%2525"):o)}else if(n===63)break}return t.slice(s,r)};var Te=e=>{let t=ce(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},C=(e,t,...s)=>(s.length&&(t=C(t,...s)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),G=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),s=[],r="";return t.forEach(n=>{if(n!==""&&!/\:/.test(n))r+="/"+n;else if(/\:/.test(n))if(/\?/.test(n)){s.length===0&&r===""?s.push("/"):s.push(r);let a=n.replace("?","");r+="/"+a,s.push(r)}else r+="/"+n}),s.filter((n,a,o)=>o.indexOf(n)===a)},oe=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?W(e,le):e):e,Ae=(e,t,s)=>{let r;if(!s&&t&&!/[%+]/.test(t)){let o=e.indexOf("?",8);if(o===-1)return;for(e.startsWith(t,o+1)||(o=e.indexOf(`&${t}`,o+1));o!==-1;){let i=e.charCodeAt(o+t.length+1);if(i===61){let c=o+t.length+2,l=e.indexOf("&",c);return oe(e.slice(c,l===-1?void 0:l))}else if(i==38||isNaN(i))return"";o=e.indexOf(`&${t}`,o+1)}if(r=/[%+]/.test(e),!r)return}let n={};r??=/[%+]/.test(e);let a=e.indexOf("?",8);for(;a!==-1;){let o=e.indexOf("&",a+1),i=e.indexOf("=",a);i>o&&o!==-1&&(i=-1);let c=e.slice(a+1,i===-1?o===-1?void 0:o:i);if(r&&(c=oe(c)),a=o,c==="")continue;let l;i===-1?l="":(l=e.slice(i+1,o===-1?void 0:o),r&&(l=oe(l))),s?(n[c]&&Array.isArray(n[c])||(n[c]=[]),n[c].push(l)):n[c]??=l}return t?n[t]:n},Me=Ae,De=(e,t)=>Ae(e,t,!0),le=decodeURIComponent;var He=e=>W(e,le),U=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",s=[[]]){this.raw=e,this.path=t,this.#e=s,this.#t={}}param(e){return e?this.#r(e):this.#a()}#r(e){let t=this.#e[0][this.routeIndex][1][e],s=this.#n(t);return s&&/\%/.test(s)?He(s):s}#a(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let s of t){let r=this.#n(this.#e[0][this.routeIndex][1][s]);r!==void 0&&(e[s]=/\%/.test(r)?He(r):r)}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Me(this.url,e)}queries(e){return De(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((s,r)=>{t[r]=s}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Ce(this,e)}#s=e=>{let{bodyCache:t,raw:s}=this,r=t[e];if(r)return r;let n=Object.keys(t)[0];return n?t[n].then(a=>(n==="json"&&(a=JSON.stringify(a)),new Response(a)[e]())):t[e]=s[e]()};json(){return this.#s("text").then(e=>JSON.parse(e))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Pe](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var ke={Stringify:1,BeforeStream:2,Stream:3},It=(e,t)=>{let s=new String(e);return s.isEscaped=!0,s.callbacks=t,s};var he=async(e,t,s,r,n)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);n?n[0]+=e:n=[e];let o=Promise.all(a.map(i=>i({phase:t,buffer:n,context:r}))).then(i=>Promise.all(i.filter(Boolean).map(c=>he(c,t,!1,r,n))).then(()=>n[0]));return s?It(await o,a):o};var qt="text/plain; charset=UTF-8",ue=(e,t)=>({"Content-Type":e,...t}),$e=class{#t;#e;env={};#r;finalized=!1;error;#a;#n;#s;#h;#c;#l;#i;#u;#f;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new U(this.#t,this.#f,this.#u),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=new Response(null,{headers:this.#i??=new Headers})}set res(e){if(this.#s&&e){e=new Response(e.body,e);for(let[t,s]of this.#s.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#s.headers.getSetCookie();e.headers.delete("set-cookie");for(let n of r)e.headers.append("set-cookie",n)}else e.headers.set(t,s)}this.#s=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#h=e;getLayout=()=>this.#h;setRenderer=e=>{this.#c=e};header=(e,t,s)=>{this.finalized&&(this.#s=new Response(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#i??=new Headers;t===void 0?r.delete(e):s?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#a=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,s){let r=this.#s?new Headers(this.#s.headers):this.#i??new Headers;if(typeof t=="object"&&"headers"in t){let a=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,i]of a)o.toLowerCase()==="set-cookie"?r.append(o,i):r.set(o,i)}if(s)for(let[a,o]of Object.entries(s))if(typeof o=="string")r.set(a,o);else{r.delete(a);for(let i of o)r.append(a,i)}let n=typeof t=="number"?t:t?.status??this.#a;return new Response(e,{status:n,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,s)=>this.#o(e,t,s);text=(e,t,s)=>!this.#i&&!this.#a&&!t&&!s&&!this.finalized?new Response(e):this.#o(e,t,ue(qt,s));json=(e,t,s)=>this.#o(JSON.stringify(e),t,ue("application/json",s));html=(e,t,s)=>{let r=n=>this.#o(n,t,ue("text/html; charset=UTF-8",s));return typeof e=="object"?he(e,ke.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let s=String(e);return this.header("Location",/[^\x00-\xFF]/.test(s)?encodeURI(s):s),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))};var f="ALL",Le="all",Ie=["get","post","put","delete","options","patch"],K="Can not add a route since the matcher is already built.",J=class extends Error{};var qe="__COMPOSED_HANDLER";var _t=e=>e.text("404 Not Found",404),_e=(e,t)=>{if("getResponse"in e){let s=e.getResponse();return t.newResponse(s.body,s)}return console.error(e),t.text("Internal Server Error",500)},Ne=class Fe{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Ie,Le].forEach(a=>{this[a]=(o,...i)=>(typeof o=="string"?this.#t=o:this.#a(a,this.#t,o),i.forEach(c=>{this.#a(a,this.#t,c)}),this)}),this.on=(a,o,...i)=>{for(let c of[o].flat()){this.#t=c;for(let l of[a].flat())i.map(h=>{this.#a(l.toUpperCase(),this.#t,h)})}return this},this.use=(a,...o)=>(typeof a=="string"?this.#t=a:(this.#t="*",o.unshift(a)),o.forEach(i=>{this.#a(f,this.#t,i)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??ce:Te}#e(){let t=new Fe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=_t;errorHandler=_e;route(t,s){let r=this.basePath(t);return s.routes.map(n=>{let a;s.errorHandler===_e?a=n.handler:(a=async(o,i)=>(await ae([],s.errorHandler)(o,()=>n.handler(o,i))).res,a[qe]=n.handler),r.#a(n.method,n.path,a)}),this}basePath(t){let s=this.#e();return s._basePath=C(this._basePath,t),s}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,s,r){let n,a;r&&(typeof r=="function"?a=r:(a=r.optionHandler,r.replaceRequest===!1?n=c=>c:n=r.replaceRequest));let o=a?c=>{let l=a(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};n||=(()=>{let c=C(this._basePath,t),l=c==="/"?0:c.length;return h=>{let u=new URL(h.url);return u.pathname=u.pathname.slice(l)||"/",new Request(u,h)}})();let i=async(c,l)=>{let h=await s(n(c.req.raw),...o(c));if(h)return h;await l()};return this.#a(f,C(t,"*"),i),this}#a(t,s,r){t=t.toUpperCase(),s=C(this._basePath,s);let n={basePath:this._basePath,path:s,method:t,handler:r};this.router.add(t,s,[r,n]),this.routes.push(n)}#n(t,s){if(t instanceof Error)return this.errorHandler(t,s);throw t}#s(t,s,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#s(t,s,r,"GET")))();let a=this.getPath(t,{env:r}),o=this.router.match(n,a),i=new $e(t,{path:a,matchResult:o,env:r,executionCtx:s,notFoundHandler:this.#r});if(o[0].length===1){let l;try{l=o[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(h){return this.#n(h,i)}return l instanceof Promise?l.then(h=>h||(i.finalized?i.res:this.#r(i))).catch(h=>this.#n(h,i)):l??this.#r(i)}let c=ae(o[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(i);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,i)}})()}fetch=(t,...s)=>this.#s(t,s[1],s[0],t.method);request=(t,s,r,n)=>t instanceof Request?this.fetch(s?new Request(t,s):t,r,n):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${C("/",t)}`,s),r,n));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#s(t.request,t,void 0,t.request.method))})}};var Q=[];function fe(e,t){let s=this.buildAllMatchers(),r=((n,a)=>{let o=s[n]||s[f],i=o[2][a];if(i)return i;let c=a.match(o[0]);if(!c)return[[],Q];let l=c.indexOf("",1);return[o[1][l],c]});return this.match=r,r(e,t)}var X="[^/]+",I=".*",q="(?:|/.*)",j=Symbol(),Nt=new Set(".\\+*[^]$()");function Ft(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===I||e===q?1:t===I||t===q?-1:e===X?1:t===X?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Be=class de{#t;#e;#r=Object.create(null);insert(t,s,r,n,a){if(t.length===0){if(this.#t!==void 0)throw j;if(a)return;this.#t=s;return}let[o,...i]=t,c=o==="*"?i.length===0?["","",I]:["","",X]:o==="/*"?["","",q]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let h=c[1],u=c[2]||X;if(h&&c[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw j;if(l=this.#r[u],!l){if(Object.keys(this.#r).some(d=>d!==I&&d!==q))throw j;if(a)return;l=this.#r[u]=new de,h!==""&&(l.#e=n.varIndex++)}!a&&h!==""&&r.push([h,l.#e])}else if(l=this.#r[o],!l){if(Object.keys(this.#r).some(h=>h.length>1&&h!==I&&h!==q))throw j;if(a)return;l=this.#r[o]=new de}l.insert(i,s,r,n,a)}buildRegExpStr(){let s=Object.keys(this.#r).sort(Ft).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:Nt.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&s.unshift(`#${this.#t}`),s.length===0?"":s.length===1?s[0]:"(?:"+s.join("|")+")"}};var ze=class{#t={varIndex:0};#e=new Be;insert(e,t,s){let r=[],n=[];for(let o=0;;){let i=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${o}`;return n[o]=[l,c],o++,i=!0,l}),!i)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=n.length-1;o>=0;o--){let[i]=n[o];for(let c=a.length-1;c>=0;c--)if(a[c].indexOf(i)!==-1){a[c]=a[c].replace(i,n[o][1]);break}}return this.#e.insert(a,t,r,this.#t,s),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,s=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,a,o)=>a!==void 0?(s[++t]=Number(a),"$()"):(o!==void 0&&(r[Number(o)]=++t),"")),[new RegExp(`^${e}`),s,r]}};var Bt=[/^$/,[],Object.create(null)],Ue=Object.create(null);function Ve(e){return Ue[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,s)=>s?`\\${s}`:"(?:|/.*)")}$`)}function zt(){Ue=Object.create(null)}function Ut(e){let t=new ze,s=[];if(e.length===0)return Bt;let r=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,h],[u,d])=>l?1:u?-1:h.length-d.length),n=Object.create(null);for(let l=0,h=-1,u=r.length;l<u;l++){let[d,m,v]=r[l];d?n[m]=[v.map(([g])=>[g,Object.create(null)]),Q]:h++;let p;try{p=t.insert(m,h,d)}catch(g){throw g===j?new J(m):g}d||(s[h]=v.map(([g,x])=>{let B=Object.create(null);for(x-=1;x>=0;x--){let[z,E]=p[x];B[z]=E}return[g,B]}))}let[a,o,i]=t.buildRegExp();for(let l=0,h=s.length;l<h;l++)for(let u=0,d=s[l].length;u<d;u++){let m=s[l][u]?.[1];if(!m)continue;let v=Object.keys(m);for(let p=0,g=v.length;p<g;p++)m[v[p]]=i[m[v[p]]]}let c=[];for(let l in o)c[l]=s[o[l]];return[a,c,n]}function M(e,t){if(e){for(let s of Object.keys(e).sort((r,n)=>n.length-r.length))if(Ve(s).test(t))return[...e[s]]}}var Y=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[f]:Object.create(null)},this.#e={[f]:Object.create(null)}}add(e,t,s){let r=this.#t,n=this.#e;if(!r||!n)throw new Error(K);r[e]||[r,n].forEach(i=>{i[e]=Object.create(null),Object.keys(i[f]).forEach(c=>{i[e][c]=[...i[f][c]]})}),t==="/*"&&(t="*");let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let i=Ve(t);e===f?Object.keys(r).forEach(c=>{r[c][t]||=M(r[c],t)||M(r[f],t)||[]}):r[e][t]||=M(r[e],t)||M(r[f],t)||[],Object.keys(r).forEach(c=>{(e===f||e===c)&&Object.keys(r[c]).forEach(l=>{i.test(l)&&r[c][l].push([s,a])})}),Object.keys(n).forEach(c=>{(e===f||e===c)&&Object.keys(n[c]).forEach(l=>i.test(l)&&n[c][l].push([s,a]))});return}let o=G(t)||[t];for(let i=0,c=o.length;i<c;i++){let l=o[i];Object.keys(n).forEach(h=>{(e===f||e===h)&&(n[h][l]||=[...M(r[h],l)||M(r[f],l)||[]],n[h][l].push([s,a-c+i+1]))})}}match=fe;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,zt(),e}#r(e){let t=[],s=e===f;return[this.#t,this.#e].forEach(r=>{let n=r[e]?Object.keys(r[e]).map(a=>[a,r[e][a]]):[];n.length!==0?(s||=!0,t.push(...n)):e!==f&&t.push(...Object.keys(r[f]).map(a=>[a,r[f][a]]))}),s?Ut(t):null}};var pe=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,s){if(!this.#e)throw new Error(K);this.#e.push([e,t,s])}match(e,t){if(!this.#e)throw new Error("Fatal error");let s=this.#t,r=this.#e,n=s.length,a=0,o;for(;a<n;a++){let i=s[a];try{for(let c=0,l=r.length;c<l;c++)i.add(...r[c]);o=i.match(e,t)}catch(c){if(c instanceof J)continue;throw c}this.match=i.match.bind(i),this.#t=[i],this.#e=void 0;break}if(a===n)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var _=Object.create(null),We=class Ge{#t;#e;#r;#a=0;#n=_;constructor(t,s,r){if(this.#e=r||Object.create(null),this.#t=[],t&&s){let n=Object.create(null);n[t]={handler:s,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(t,s,r){this.#a=++this.#a;let n=this,a=je(s),o=[];for(let i=0,c=a.length;i<c;i++){let l=a[i],h=a[i+1],u=Oe(l,h),d=Array.isArray(u)?u[0]:l;if(d in n.#e){n=n.#e[d],u&&o.push(u[1]);continue}n.#e[d]=new Ge,u&&(n.#r.push(u),o.push(u[1])),n=n.#e[d]}return n.#t.push({[t]:{handler:r,possibleKeys:o.filter((i,c,l)=>l.indexOf(i)===c),score:this.#a}}),n}#s(t,s,r,n){let a=[];for(let o=0,i=t.#t.length;o<i;o++){let c=t.#t[o],l=c[s]||c[f],h={};if(l!==void 0&&(l.params=Object.create(null),a.push(l),r!==_||n&&n!==_))for(let u=0,d=l.possibleKeys.length;u<d;u++){let m=l.possibleKeys[u],v=h[l.score];l.params[m]=n?.[m]&&!v?n[m]:r[m]??n?.[m],h[l.score]=!0}}return a}search(t,s){let r=[];this.#n=_;let a=[this],o=ie(s),i=[];for(let c=0,l=o.length;c<l;c++){let h=o[c],u=c===l-1,d=[];for(let m=0,v=a.length;m<v;m++){let p=a[m],g=p.#e[h];g&&(g.#n=p.#n,u?(g.#e["*"]&&r.push(...this.#s(g.#e["*"],t,p.#n)),r.push(...this.#s(g,t,p.#n))):d.push(g));for(let x=0,B=p.#r.length;x<B;x++){let z=p.#r[x],E=p.#n===_?{}:{...p.#n};if(z==="*"){let S=p.#e["*"];S&&(r.push(...this.#s(S,t,p.#n)),S.#n=E,d.push(S));continue}let[jt,Se,L]=z;if(!h&&!(L instanceof RegExp))continue;let R=p.#e[jt],Ot=o.slice(c).join("/");if(L instanceof RegExp){let S=L.exec(Ot);if(S){if(E[Se]=S[0],r.push(...this.#s(R,t,p.#n,E)),Object.keys(R.#e).length){R.#n=E;let Tt=S[0].match(/\//)?.length??0;(i[Tt]||=[]).push(R)}continue}}(L===!0||L.test(h))&&(E[Se]=h,u?(r.push(...this.#s(R,t,E,p.#n)),R.#e["*"]&&r.push(...this.#s(R.#e["*"],t,E,p.#n))):(R.#n=E,d.push(R)))}}a=d.concat(i.shift()??[])}return r.length>1&&r.sort((c,l)=>c.score-l.score),[r.map(({handler:c,params:l})=>[c,l])]}};var me=class{name="TrieRouter";#t;constructor(){this.#t=new We}add(e,t,s){let r=G(t);if(r){for(let n=0,a=r.length;n<a;n++)this.#t.insert(e,r[n],s);return}this.#t.insert(e,t,s)}match(e,t){return this.#t.search(e,t)}};var ye=class extends Ne{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new Y,new me]})}};import{join as Ct}from"node:path";function O(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 Z(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 Ke(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)}`)}}function ee(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:Je(e.deflate)}:{deflate:Je(e.inflate),inflate:e.inflate}}function Je(e){let t={};for(let[s,r]of Object.entries(e))t[r]=s;return t}function D(e,t){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>D(r,t));let s={};for(let[r,n]of Object.entries(e)){let a=t[r]||r;s[a]=D(n,t)}return s}import{existsSync as be,mkdirSync as Vt,readdirSync as Wt,openSync as Gt,closeSync as Kt}from"fs";import{readFile as Jt,writeFile as Qt,rename as Xt,unlink as Qe,open as Yt}from"fs/promises";import{join as ge,dirname as Zt}from"path";var we=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=ee(s);this.dictionaries.set(t,r)}),be(this.databaseDirectory)||Vt(this.databaseDirectory,{recursive:!0})}async start(){try{let e=Wt(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,n){if(O(e),Z(t),Ke(s),n&&!this.dictionaries.has(n))throw new Error(`Dictionary "${n}" not found. Available dictionaries: ${Array.from(this.dictionaries.keys()).join(", ")||"none"}`);try{this.data.has(e)||this.data.set(e,new Map);let a=this.data.get(e),i=(a.get(t)?.version||0)+1,c={value:s,version:i,timestamp:Date.now(),expiration:r||null,dictionaryName:n||void 0};return a.set(t,c),await this.persistTable(e),!0}catch(a){return console.error(`Write failed for ${e}:${t}:`,a),!1}}async get(e,t){O(e),t!==void 0&&Z(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 a=s.get(t);if(!a)return;if(this.isExpired(a)){s.delete(t),await this.persistTable(e);return}return a.value}let r=[],n=[];for(let[a,o]of s.entries())this.isExpired(o)?n.push(a):r.push([a,o.value]);if(n.length>0){for(let a of n)s.delete(a);await this.persistTable(e)}return r}catch(s){return console.error(`Read failed for ${e}:${t}:`,s),t?void 0:[]}}async delete(e,t){O(e),Z(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){O(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[n,a]of t.entries())this.isExpired(a)?r.push(n):s++;if(r.length>0){for(let n of r)t.delete(n);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){O(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,n]of t.entries())this.isExpired(n)&&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){O(e);try{this.data.delete(e);let t=ge(this.databaseDirectory,e);return be(t)&&await Qe(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=ee(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=ge(this.databaseDirectory,e);if(!be(t)){this.data.set(e,new Map);return}try{let s=await Jt(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=ge(this.databaseDirectory,e),n=`${r}.tmp.${Date.now()}.${Math.random().toString(36).substring(7)}`;try{if(await Qt(n,s),this.useFsync){let a=await Yt(n,"r+");try{await a.sync()}finally{await a.close()}}if(await Xt(n,r),this.useFsync){let a=Zt(r),o=Gt(a,"r");try{Kt(o)}catch{}}}catch(a){try{await Qe(n)}catch{}throw a}}serializeTable(e){let t=Array.from(e.entries()).map(([s,r])=>{let n=r.dictionaryName?this.dictionaries.get(r.dictionaryName):void 0,a={d:n?D(r.value,n.deflate):r.value,v:r.version,t:r.timestamp,x:r.expiration};return r.dictionaryName&&(a.n=r.dictionaryName),[s,a]});return Buffer.from(JSON.stringify(t),"utf8")}deserializeTable(e){let s=JSON.parse(e.toString("utf8")).map(([r,n])=>{let a=n.n,o=a?this.dictionaries.get(a):void 0;return[r,{value:o?D(n.d,o.inflate):n.d,version:n.v,timestamp:n.t,expiration:n.x,dictionaryName:a||void 0}]});return new Map(s)}};import{createServer as er}from"http";import{Http2ServerRequest as tr}from"http2";import{Http2ServerRequest as ve}from"http2";import{Readable as Xe}from"stream";import dr from"crypto";var T=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},rr=e=>e instanceof T?e:new T(e.message,{cause:e}),sr=global.Request,N=class extends sr{constructor(e,t){typeof e=="object"&&$ in e&&(e=e[$]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},nr=e=>{let t=[],s=e.rawHeaders;for(let r=0;r<s.length;r+=2){let{[r]:n,[r+1]:a}=s;n.charCodeAt(0)!==58&&t.push([n,a])}return new Headers(t)},Ze=Symbol("wrapBodyStream"),ar=(e,t,s,r,n)=>{let a={method:e,headers:s,signal:n.signal};if(e==="TRACE"){a.method="GET";let o=new N(t,a);return Object.defineProperty(o,"method",{get(){return"TRACE"}}),o}if(!(e==="GET"||e==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(o){o.enqueue(r.rawBody),o.close()}});else if(r[Ze]){let o;a.body=new ReadableStream({async pull(i){try{o||=Xe.toWeb(r).getReader();let{done:c,value:l}=await o.read();c?i.close():i.enqueue(l)}catch(c){i.error(c)}}})}else a.body=Xe.toWeb(r);return new N(t,a)},$=Symbol("getRequestCache"),or=Symbol("requestCache"),te=Symbol("incomingKey"),re=Symbol("urlKey"),ir=Symbol("headersKey"),k=Symbol("abortControllerKey"),cr=Symbol("getAbortController"),se={get method(){return this[te].method||"GET"},get url(){return this[re]},get headers(){return this[ir]||=nr(this[te])},[cr](){return this[$](),this[k]},[$](){return this[k]||=new AbortController,this[or]||=ar(this.method,this[re],this.headers,this[te],this[k])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(se,e,{get(){return this[$]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(se,e,{value:function(){return this[$]()[e]()}})});Object.setPrototypeOf(se,N.prototype);var lr=(e,t)=>{let s=Object.create(se);s[te]=e;let r=e.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(e instanceof ve)throw new T("Absolute URL for :path is not allowed in HTTP/2");try{let i=new URL(r);s[re]=i.href}catch(i){throw new T("Invalid absolute URL",{cause:i})}return s}let n=(e instanceof ve?e.authority:e.headers.host)||t;if(!n)throw new T("Missing host header");let a;if(e instanceof ve){if(a=e.scheme,!(a==="http"||a==="https"))throw new T("Unsupported scheme")}else a=e.socket&&e.socket.encrypted?"https":"http";let o=new URL(`${a}://${n}${r}`);if(o.hostname.length!==n.length&&o.hostname!==n.replace(/:\d+$/,""))throw new T("Invalid host header");return s[re]=o.href,s},Ye=Symbol("responseCache"),H=Symbol("getResponseCache"),A=Symbol("cache"),Re=global.Response,F=class et{#t;#e;[H](){return delete this[A],this[Ye]||=new Re(this.#t,this.#e)}constructor(t,s){let r;if(this.#t=t,s instanceof et){let n=s[Ye];if(n){this.#e=n,this[H]();return}else this.#e=s.#e,r=new Headers(s.#e.headers)}else this.#e=s;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(r||=s?.headers||{"content-type":"text/plain; charset=UTF-8"},this[A]=[s?.status||200,t,r])}get headers(){let t=this[A];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2])),t[2]):this[H]().headers}get status(){return this[A]?.[0]??this[H]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(F.prototype,e,{get(){return this[H]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(F.prototype,e,{value:function(){return this[H]()[e]()}})});Object.setPrototypeOf(F,Re);Object.setPrototypeOf(F.prototype,Re.prototype);async function hr(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function tt(e,t,s){let r=i=>{e.cancel(i).catch(()=>{})};return t.on("close",r),t.on("error",r),(s??e.read()).then(o,n),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function n(i){i&&t.destroy(i)}function a(){e.read().then(o,n)}function o({done:i,value:c}){try{if(i)t.end();else if(!t.write(c))t.once("drain",a);else return e.read().then(o,n)}catch(l){n(l)}}}function ur(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:tt(e.getReader(),t)}var rt=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[r,n]of e)r==="set-cookie"?s.push(n):t[r]=n;return s.length>0&&(t["set-cookie"]=s),t["content-type"]??="text/plain; charset=UTF-8",t},fr="x-hono-already-sent",pr=global.fetch;typeof global.crypto>"u"&&(global.crypto=dr);global.fetch=(e,t)=>(t={compress:!1,...t},pr(e,t));var xe=Symbol("outgoingEnded"),mr=()=>new Response(null,{status:400}),st=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Ee=(e,t)=>{let s=e instanceof Error?e:new Error("unknown error",{cause:e});s.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${s.message}`),t.destroy(s))},nt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},at=async(e,t)=>{let[s,r,n]=e[A];n instanceof Headers&&(n=rt(n)),typeof r=="string"?n["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?n["Content-Length"]=r.byteLength:r instanceof Blob&&(n["Content-Length"]=r.size),t.writeHead(s,n),typeof r=="string"||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(nt(t),await ur(r,t)?.catch(a=>Ee(a,t))),t[xe]?.()},yr=e=>typeof e.then=="function",br=async(e,t,s={})=>{if(yr(e))if(s.errorHandler)try{e=await e}catch(n){let a=await s.errorHandler(n);if(!a)return;e=a}else e=await e.catch(st);if(A in e)return at(e,t);let r=rt(e.headers);if(e.body){let n=e.body.getReader(),a=[],o=!1,i;if(r["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){i||=n.read();let h=await hr(i).catch(u=>{console.error(u),o=!0});if(!h){if(l===1){await new Promise(u=>setTimeout(u)),c=3;continue}break}if(i=void 0,h.value&&a.push(h.value),h.done){o=!0;break}}o&&!("content-length"in r)&&(r["content-length"]=a.reduce((l,h)=>l+h.length,0))}t.writeHead(e.status,r),a.forEach(c=>{t.write(c)}),o?t.end():(a.length===0&&nt(t),await tt(n,t,i))}else r[fr]||(t.writeHead(e.status,r),t.end());t[xe]?.()},gr=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==N&&(Object.defineProperty(global,"Request",{value:N}),Object.defineProperty(global,"Response",{value:F})),async(r,n)=>{let a,o;try{o=lr(r,t.hostname);let i=!s||r.method==="GET"||r.method==="HEAD";if(i||(r[Ze]=!0,r.on("end",()=>{i=!0}),r instanceof tr&&(n[xe]=()=>{i||setTimeout(()=>{i||setTimeout(()=>{r.destroy(),n.destroy()})})})),n.on("close",()=>{o[k]&&(r.errored?o[k].abort(r.errored.toString()):n.writableFinished||o[k].abort("Client connection prematurely closed.")),i||setTimeout(()=>{i||setTimeout(()=>{r.destroy()})})}),a=e(o,{incoming:r,outgoing:n}),A in a)return at(a,n)}catch(i){if(a)return Ee(i,n);if(t.errorHandler){if(a=await t.errorHandler(o?i:rr(i)),!a)return}else o?a=st(i):a=mr()}try{return await br(a,n,t)}catch(i){return Ee(i,n)}}},wr=e=>{let t=e.fetch,s=gr(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||er)(e.serverOptions||{},s)},ot=(e,t)=>{let s=wr(e);return s.listen(e?.port??3e3,e.hostname,()=>{let r=s.address();t&&t(r)}),s};import{statSync as Hr}from"node:fs";import{readFileSync as vr,existsSync as Er}from"node:fs";function it(){let e=process.env.MOLNOS_RUNTIME_CONFIG;if(!e||!Er(e))return{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}};try{let t=vr(e,"utf-8");return JSON.parse(t)}catch(t){return console.error("[loadRuntimeConfig] Failed to load runtime config:",t),{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}}}}var w=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),n=this.compileErrors(s,r),a=this.isSuccessful(s,n);return{errors:n,success:a}}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 n=e?.additionalProperties??!0,a=e?.required||[];r=this.checkForRequiredKeysErrors(a,t,r),r=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),r,n);for(let o in e){let i=a.includes(o)&&o!=="required",c=e[o],l=t[o],h=c.additionalProperties??!0;i&&(r=this.checkForRequiredKeysErrors(c.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(o,l,c,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(c),r,h),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):[],n=this.findNonOverlappingElements(e,r),a=n.length>0?`Missing the required key: '${n.join(", ")}'!`:`Missing values for required keys: '${r.filter(o=>!t[o]).join(", ")}'!`;s.push({key:"",value:t,success:!1,error:a})}return s}checkForDisallowedProperties(e,t,s,r){if(!r){let n=this.findNonOverlappingElements(e,t);n.length>0&&s.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${n.join(", ")}'!`})}return s}handleValidation(e,t,s,r){this.updatePropertyPath(e);let n=this.validateProperty(this.propertyPath,s,t);r.push(...n);let a=(i,c)=>{i.forEach(l=>{let h=this.validateProperty(this.propertyPath,c.items,l);r.push(...h)}),this.updatePropertyPath()},o=i=>{let c=Object.keys(i),l=this.propertyPath;c.forEach(h=>{if(this.updatePropertyPath(h,l),this.isArray(i[h])&&s[h]?.items!=null)a(i[h],s[h]);else{let u=this.validateProperty(this.propertyPath,s[h],i[h]);r.push(...u)}})};this.isArray(t)&&s.items!=null?a(t,s):this.isObject(t)?o(t):this.updatePropertyPath()}handleNestedObject(e,t,s,r){if(this.isObject(e)){let n=this.getNestedObjects(e);for(let a of n){let o=t[a],i=e[a];o&&typeof i=="object"&&this.validate(o,i,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(n=>{let{success:a,error:o}=n;return{key:e,value:s,success:a,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 n of s)n.condition()&&!n.validator()&&r.push({success:!1,error:n.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(a=>typeof a==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 ne(e){try{return await e.req.json()}catch{return{}}}function y(e,t="An error occurred"){let s=e?.message||e||t,r=e?.cause?.statusCode||e?.statusCode||400;return{message:s,status:r}}function ct(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 n=e.roles.flatMap(o=>o?.policies?.flatMap(i=>(i?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(o=>n.includes(o)||n.includes("*")?!0:n.some(i=>{if(i.endsWith(".*")){let c=i.slice(0,-2);return o.startsWith(`${c}.`)}return!1}))){let o=new Error("Unauthorized");throw o.cause={statusCode:403},o}return!0}function lt(e,t,s,r,n){let a=e.find(c=>c.service===t);if(!a){let c=new Error(`Function bindings do not include access to service: ${t}`);throw c.cause={statusCode:403},c}if(!a.permissions||a.permissions.length===0)return;for(let c of a.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(!n)return;if(!c.targets.includes(n))continue}return}}let o=n?`:${n}`:"",i=new Error(`Function bindings do not allow: ${t}.${s}.${r}${o}`);throw i.cause={statusCode:403},i}async function b(e,t,s,r,n,a,o){if(!t)return null;let i=e.get("user");if(!i){let l=e.req.header("authorization");if(!l){let u=new Error("Unauthorized: No authentication provided");throw u.cause={statusCode:401},u}let h=l.replace(/^Bearer\s+/i,"");if(i=await t.getUserFromToken(h),!i){let u=new Error("Unauthorized: Invalid token");throw u.cause={statusCode:401},u}}ct(i,s,{});let c=e.req.header("x-function-bindings");if(c)try{let l=JSON.parse(c);lt(l,r,n,a,o)}catch(l){if(l.cause?.statusCode===403)throw l;let h=new Error("Invalid function bindings header");throw h.cause={statusCode:400},h}return i}var ht={properties:{tableName:{type:"string",minLength:1},key:{type:"string"}},required:["tableName"],additionalProperties:!1};var xr=new w;async function ut(e,t,s){try{let r=await ne(e),n=xr.test(ht,r);if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);let{tableName:a,key:o}=r;if(!a)return e.json("tableName is required",400);await b(e,s,"databases.table.get","databases","table","read",a);let i=await t.get(a,o);return i?e.json(i,200):e.json(null,404)}catch(r){let{message:n,status:a}=y(r,"Error getting table data");return e.text(n,a)}}var ft={properties:{tableName:{type:"string",minLength:1},key:{type:"string"},value:{},expiration:{type:"number"},dictionaryName:{type:"string"}},required:["tableName"],additionalProperties:!1};var Pr=new w;async function dt(e,t,s){try{let r=await ne(e),n=Pr.test(ft,r);if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);let{tableName:a,key:o,value:i,expiration:c,dictionaryName:l}=r;if(!a||i===void 0)return e.json("tableName and value are required",400);await b(e,s,"databases.table.update","databases","table","write",a);let h=await t.write(a,o,i,c,l);return e.json(h,200)}catch(r){let{message:n,status:a}=y(r,"Error writing table data");return e.text(n,a)}}var pt={properties:{tableName:{type:"string",minLength:1},key:{type:"string",minLength:1}},required:["tableName","key"],additionalProperties:!1};var jr=new w;async function mt(e,t,s){try{let r=e.req.query(),n=jr.test(pt,r);if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);let{tableName:a,key:o}=r;if(!a||!o)return e.json("tableName and key are required",400);await b(e,s,"databases.table.delete","databases","table","delete",a);let i=await t.delete(a,o);return e.json(i,200)}catch(r){let{message:n,status:a}=y(r,"Error deleting table item");return e.text(n,a)}}async function yt(e,t,s,r,n,a){try{await b(e,s,"databases.table.get","databases","table","read");let o=t.listTables(),i=await Promise.all(o.map(async c=>{let l=await t.getTableSize(c),h=n(r,c);return{name:c,items:l,size:a(h)}}));return e.json({tables:i},200)}catch(o){let{message:i,status:c}=y(o,"Error listing tables");return e.text(i,c)}}var P={properties:{tableName:{type:"string",minLength:1}},required:["tableName"],additionalProperties:!1};var Tr=new w;async function bt(e,t,s){try{let{tableName:r}=e.req.param();if(!r)return e.json({error:"tableName is required"},400);let n=Tr.test(P,{tableName:r});return n.success?(await b(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:n.errors},400)}catch(r){let{message:n,status:a}=y(r,"Error creating table");return e.text(n,a)}}var Ar=new w;async function gt(e,t,s){try{let{tableName:r}=e.req.param();if(!r)return e.json({error:"tableName is required"},400);let n=Ar.test(P,{tableName:r});if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);if(await b(e,s,"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:n,status:a}=y(r,"Error deleting table");return e.text(n,a)}}var Mr=new w;async function wt(e,t,s,r,n,a){try{let{tableName:o}=e.req.param();if(!o)return e.json({error:"tableName is required"},400);let i=Mr.test(P,{tableName:o});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await b(e,s,"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),h=n(r,o);return e.json({name:o,items:l,size:a(h)},200)}catch(o){let{message:i,status:c}=y(o,"Error getting table info");return e.text(i,c)}}async function vt(e,t,s){try{let r=e.req.query();if(!r.tableName)return e.json({error:"tableName is required"},400);let{tableName:n}=r;await b(e,s,"databases.table.get","databases","table","read",n);let a=await t.get(n),o=a?a.length:0;return e.json(o,200)}catch(r){let{message:n,status:a}=y(r,"Error getting table size");return e.text(n,a)}}var Dr=new w;async function Et(e,t,s){try{let{tableName:r}=e.req.param();if(!r)return e.json({error:"tableName is required"},400);let n=Dr.test(P,{tableName:r});if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);if(await b(e,s,"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),i=o?Object.entries(o).map(([c,l])=>Array.isArray(l)&&l.length===2?{key:l[0],value:l[1]}:{key:c,value:l}):[];return e.json({items:i},200)}catch(r){let{message:n,status:a}=y(r,"Error getting table items");return e.text(n,a)}}function Rt(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 xt(e,t){try{let s=Ct(e,t);return Hr(s).size}catch{return 0}}async function kr(e){let t=e.dataPath||"data",s=Ct(t,"databases"),r=new we({databaseDirectory:e.db?.databaseDirectory||s});await r.start();let n=e.identityService||null,a=new ye;return a.get("/table",async o=>vt(o,r,n)),a.post("/get",async o=>ut(o,r,n)),a.post("/write",async o=>dt(o,r,n)),a.delete("/delete",async o=>mt(o,r,n)),a.get("/tables",async o=>yt(o,r,n,s,xt,Rt)),a.post("/tables/:tableName",async o=>bt(o,r,n)),a.delete("/tables/:tableName",async o=>gt(o,r,n)),a.get("/tables/:tableName",async o=>wt(o,r,n,s,xt,Rt)),a.get("/tables/:tableName/items",async o=>Et(o,r,n)),ot({fetch:a.fetch,port:e.server.port||3004,hostname:e.server.host||"localhost"}),console.log(`Database server started on ${e.server.host||"localhost"}:${e.server.port||3004}`),a}var $r=process.argv.slice(2),St=$r.find(e=>e.startsWith("--port=")),Lr=St?parseInt(St.split("=")[1],10):3004,Pt=it(),Ir={molnos:{dataPath:Pt.molnos.dataPath},db:{},server:{port:Lr,host:Pt.server.host}};kr(Ir);export{kr as startServer};
@@ -0,0 +1,16 @@
1
+ // MolnOS Core - See LICENSE file for copyright and license details.
2
+ import{createHash as yr}from"node:crypto";import{existsSync as ce}from"node:fs";var ue=(t,e,s)=>(r,n)=>{let o=-1;return i(0);async function i(c){if(c<=o)throw new Error("next() called multiple times");o=c;let a,u=!1,l;if(t[c]?(l=t[c][0][0],r.req.routeIndex=c):l=c===t.length&&n||void 0,l)try{a=await l(r,()=>i(c+1))}catch(d){if(d instanceof Error&&e)r.error=d,a=await e(d,r),u=!0;else throw d}else r.finalized===!1&&s&&(a=await s(r));return a&&(r.finalized===!1||u)&&(r.res=a),r}};var He=Symbol();var Ie=async(t,e=Object.create(null))=>{let{all:s=!1,dot:r=!1}=e,o=(t instanceof z?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Ot(t,{all:s,dot:r}):{}};async function Ot(t,e){let s=await t.formData();return s?Tt(s,e):{}}function Tt(t,e){let s=Object.create(null);return t.forEach((r,n)=>{e.all||n.endsWith("[]")?Ft(s,n,r):s[n]=r}),e.dot&&Object.entries(s).forEach(([r,n])=>{r.includes(".")&&($t(s,r,n),delete s[r])}),s}var Ft=(t,e,s)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(s):t[e]=[t[e],s]:e.endsWith("[]")?t[e]=[s]:t[e]=s},$t=(t,e,s)=>{let r=t,n=e.split(".");n.forEach((o,i)=>{i===n.length-1?r[o]=s:((!r[o]||typeof r[o]!="object"||Array.isArray(r[o])||r[o]instanceof File)&&(r[o]=Object.create(null)),r=r[o])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},De=t=>{let{groups:e,path:s}=Ht(t),r=de(s);return It(r,e)},Ht=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(s,r)=>{let n=`@${r}`;return e.push([n,s]),n}),{groups:e,path:t}},It=(t,e)=>{for(let s=e.length-1;s>=0;s--){let[r]=e[s];for(let n=t.length-1;n>=0;n--)if(t[n].includes(r)){t[n]=t[n].replace(r,e[s][1]);break}}return t},G={},ke=(t,e)=>{if(t==="*")return"*";let s=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(s){let r=`${t}#${e}`;return G[r]||(s[2]?G[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,s[1],new RegExp(`^${s[2]}(?=/${e})`)]:[t,s[1],new RegExp(`^${s[2]}$`)]:G[r]=[t,s[1],!0]),G[r]}return null},V=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,s=>{try{return e(s)}catch{return s}})}},Dt=t=>V(t,decodeURI),he=t=>{let e=t.url,s=e.indexOf("/",e.indexOf(":")+4),r=s;for(;r<e.length;r++){let n=e.charCodeAt(r);if(n===37){let o=e.indexOf("?",r),i=e.slice(s,o===-1?void 0:o);return Dt(i.includes("%25")?i.replace(/%25/g,"%2525"):i)}else if(n===63)break}return e.slice(s,r)};var Me=t=>{let e=he(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},S=(t,e,...s)=>(s.length&&(e=S(e,...s)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),W=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),s=[],r="";return e.forEach(n=>{if(n!==""&&!/\:/.test(n))r+="/"+n;else if(/\:/.test(n))if(/\?/.test(n)){s.length===0&&r===""?s.push("/"):s.push(r);let o=n.replace("?","");r+="/"+o,s.push(r)}else r+="/"+n}),s.filter((n,o,i)=>i.indexOf(n)===o)},le=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?V(t,fe):t):t,Ue=(t,e,s)=>{let r;if(!s&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let c=t.charCodeAt(i+e.length+1);if(c===61){let a=i+e.length+2,u=t.indexOf("&",a);return le(t.slice(a,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";i=t.indexOf(`&${e}`,i+1)}if(r=/[%+]/.test(t),!r)return}let n={};r??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let i=t.indexOf("&",o+1),c=t.indexOf("=",o);c>i&&i!==-1&&(c=-1);let a=t.slice(o+1,c===-1?i===-1?void 0:i:c);if(r&&(a=le(a)),o=i,a==="")continue;let u;c===-1?u="":(u=t.slice(c+1,i===-1?void 0:i),r&&(u=le(u))),s?(n[a]&&Array.isArray(n[a])||(n[a]=[]),n[a].push(u)):n[a]??=u}return e?n[e]:n},qe=Ue,Le=(t,e)=>Ue(t,e,!0),fe=decodeURIComponent;var Ne=t=>V(t,fe),z=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",s=[[]]){this.raw=t,this.path=e,this.#e=s,this.#t={}}param(t){return t?this.#r(t):this.#o()}#r(t){let e=this.#e[0][this.routeIndex][1][t],s=this.#n(e);return s&&/\%/.test(s)?Ne(s):s}#o(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let s of e){let r=this.#n(this.#e[0][this.routeIndex][1][s]);r!==void 0&&(t[s]=/\%/.test(r)?Ne(r):r)}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return qe(this.url,t)}queries(t){return Le(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((s,r)=>{e[r]=s}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Ie(this,t)}#s=t=>{let{bodyCache:e,raw:s}=this,r=e[t];if(r)return r;let n=Object.keys(e)[0];return n?e[n].then(o=>(n==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=s[t]()};json(){return this.#s("text").then(t=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[He](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Be={Stringify:1,BeforeStream:2,Stream:3},kt=(t,e)=>{let s=new String(t);return s.isEscaped=!0,s.callbacks=e,s};var pe=async(t,e,s,r,n)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);n?n[0]+=t:n=[t];let i=Promise.all(o.map(c=>c({phase:e,buffer:n,context:r}))).then(c=>Promise.all(c.filter(Boolean).map(a=>pe(a,e,!1,r,n))).then(()=>n[0]));return s?kt(await i,o):i};var Mt="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),_e=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#s;#l;#c;#u;#a;#d;#h;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#u=e.notFoundHandler,this.#h=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new z(this.#t,this.#h,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=new Response(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=new Response(t.body,t);for(let[e,s]of this.#s.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let r=this.#s.headers.getSetCookie();t.headers.delete("set-cookie");for(let n of r)t.headers.append("set-cookie",n)}else t.headers.set(e,s)}this.#s=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#l=t;getLayout=()=>this.#l;setRenderer=t=>{this.#c=t};header=(t,e,s)=>{this.finalized&&(this.#s=new Response(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;e===void 0?r.delete(t):s?.append?r.append(t,e):r.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,s){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,c]of o)i.toLowerCase()==="set-cookie"?r.append(i,c):r.set(i,c)}if(s)for(let[o,i]of Object.entries(s))if(typeof i=="string")r.set(o,i);else{r.delete(o);for(let c of i)r.append(o,c)}let n=typeof e=="number"?e:e?.status??this.#o;return new Response(t,{status:n,headers:r})}newResponse=(...t)=>this.#i(...t);body=(t,e,s)=>this.#i(t,e,s);text=(t,e,s)=>!this.#a&&!this.#o&&!e&&!s&&!this.finalized?new Response(t):this.#i(t,e,me(Mt,s));json=(t,e,s)=>this.#i(JSON.stringify(t),e,me("application/json",s));html=(t,e,s)=>{let r=n=>this.#i(n,e,me("text/html; charset=UTF-8",s));return typeof t=="object"?pe(t,Be.Stringify,!1,{}).then(r):r(t)};redirect=(t,e)=>{let s=String(t);return this.header("Location",/[^\x00-\xFF]/.test(s)?encodeURI(s):s),this.newResponse(null,e??302)};notFound=()=>(this.#u??=()=>new Response,this.#u(this))};var g="ALL",ze="all",Ge=["get","post","put","delete","options","patch"],J="Can not add a route since the matcher is already built.",K=class extends Error{};var Ve="__COMPOSED_HANDLER";var Ut=t=>t.text("404 Not Found",404),We=(t,e)=>{if("getResponse"in t){let s=t.getResponse();return e.newResponse(s.body,s)}return console.error(t),e.text("Internal Server Error",500)},Je=class Ke{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ge,ze].forEach(o=>{this[o]=(i,...c)=>(typeof i=="string"?this.#t=i:this.#o(o,this.#t,i),c.forEach(a=>{this.#o(o,this.#t,a)}),this)}),this.on=(o,i,...c)=>{for(let a of[i].flat()){this.#t=a;for(let u of[o].flat())c.map(l=>{this.#o(u.toUpperCase(),this.#t,l)})}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(c=>{this.#o(g,this.#t,c)}),this);let{strict:r,...n}=e;Object.assign(this,n),this.getPath=r??!0?e.getPath??he:Me}#e(){let e=new Ke({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Ut;errorHandler=We;route(e,s){let r=this.basePath(e);return s.routes.map(n=>{let o;s.errorHandler===We?o=n.handler:(o=async(i,c)=>(await ue([],s.errorHandler)(i,()=>n.handler(i,c))).res,o[Ve]=n.handler),r.#o(n.method,n.path,o)}),this}basePath(e){let s=this.#e();return s._basePath=S(this._basePath,e),s}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,s,r){let n,o;r&&(typeof r=="function"?o=r:(o=r.optionHandler,r.replaceRequest===!1?n=a=>a:n=r.replaceRequest));let i=o?a=>{let u=o(a);return Array.isArray(u)?u:[u]}:a=>{let u;try{u=a.executionCtx}catch{}return[a.env,u]};n||=(()=>{let a=S(this._basePath,e),u=a==="/"?0:a.length;return l=>{let d=new URL(l.url);return d.pathname=d.pathname.slice(u)||"/",new Request(d,l)}})();let c=async(a,u)=>{let l=await s(n(a.req.raw),...i(a));if(l)return l;await u()};return this.#o(g,S(e,"*"),c),this}#o(e,s,r){e=e.toUpperCase(),s=S(this._basePath,s);let n={basePath:this._basePath,path:s,method:e,handler:r};this.router.add(e,s,[r,n]),this.routes.push(n)}#n(e,s){if(e instanceof Error)return this.errorHandler(e,s);throw e}#s(e,s,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#s(e,s,r,"GET")))();let o=this.getPath(e,{env:r}),i=this.router.match(n,o),c=new _e(e,{path:o,matchResult:i,env:r,executionCtx:s,notFoundHandler:this.#r});if(i[0].length===1){let u;try{u=i[0][0][0][0](c,async()=>{c.res=await this.#r(c)})}catch(l){return this.#n(l,c)}return u instanceof Promise?u.then(l=>l||(c.finalized?c.res:this.#r(c))).catch(l=>this.#n(l,c)):u??this.#r(c)}let a=ue(i[0],this.errorHandler,this.#r);return(async()=>{try{let u=await a(c);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#n(u,c)}})()}fetch=(e,...s)=>this.#s(e,s[1],s[0],e.method);request=(e,s,r,n)=>e instanceof Request?this.fetch(s?new Request(e,s):e,r,n):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${S("/",e)}`,s),r,n));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method))})}};var Q=[];function ge(t,e){let s=this.buildAllMatchers(),r=((n,o)=>{let i=s[n]||s[g],c=i[2][o];if(c)return c;let a=o.match(i[0]);if(!a)return[[],Q];let u=a.indexOf("",1);return[i[1][u],a]});return this.match=r,r(t,e)}var Y="[^/]+",k=".*",M="(?:|/.*)",j=Symbol(),qt=new Set(".\\+*[^]$()");function Lt(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===k||t===M?1:e===k||e===M?-1:t===Y?1:e===Y?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Qe=class ye{#t;#e;#r=Object.create(null);insert(e,s,r,n,o){if(e.length===0){if(this.#t!==void 0)throw j;if(o)return;this.#t=s;return}let[i,...c]=e,a=i==="*"?c.length===0?["","",k]:["","",Y]:i==="/*"?["","",M]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(a){let l=a[1],d=a[2]||Y;if(l&&a[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw j;if(u=this.#r[d],!u){if(Object.keys(this.#r).some(h=>h!==k&&h!==M))throw j;if(o)return;u=this.#r[d]=new ye,l!==""&&(u.#e=n.varIndex++)}!o&&l!==""&&r.push([l,u.#e])}else if(u=this.#r[i],!u){if(Object.keys(this.#r).some(l=>l.length>1&&l!==k&&l!==M))throw j;if(o)return;u=this.#r[i]=new ye}u.insert(c,s,r,n,o)}buildRegExpStr(){let s=Object.keys(this.#r).sort(Lt).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:qt.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&s.unshift(`#${this.#t}`),s.length===0?"":s.length===1?s[0]:"(?:"+s.join("|")+")"}};var Ye=class{#t={varIndex:0};#e=new Qe;insert(t,e,s){let r=[],n=[];for(let i=0;;){let c=!1;if(t=t.replace(/\{[^}]+\}/g,a=>{let u=`@\\${i}`;return n[i]=[u,a],i++,c=!0,u}),!c)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[c]=n[i];for(let a=o.length-1;a>=0;a--)if(o[a].indexOf(c)!==-1){o[a]=o[a].replace(c,n[i][1]);break}}return this.#e.insert(o,e,r,this.#t,s),r}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,s=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,i)=>o!==void 0?(s[++e]=Number(o),"$()"):(i!==void 0&&(r[Number(i)]=++e),"")),[new RegExp(`^${t}`),s,r]}};var Nt=[/^$/,[],Object.create(null)],Xe=Object.create(null);function Ze(t){return Xe[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,s)=>s?`\\${s}`:"(?:|/.*)")}$`)}function Bt(){Xe=Object.create(null)}function _t(t){let e=new Ye,s=[];if(t.length===0)return Nt;let r=t.map(u=>[!/\*|\/:/.test(u[0]),...u]).sort(([u,l],[d,h])=>u?1:d?-1:l.length-h.length),n=Object.create(null);for(let u=0,l=-1,d=r.length;u<d;u++){let[h,f,b]=r[u];h?n[f]=[b.map(([y])=>[y,Object.create(null)]),Q]:l++;let p;try{p=e.insert(f,l,h)}catch(y){throw y===j?new K(f):y}h||(s[l]=b.map(([y,m])=>{let O=Object.create(null);for(m-=1;m>=0;m--){let[T,v]=p[m];O[T]=v}return[y,O]}))}let[o,i,c]=e.buildRegExp();for(let u=0,l=s.length;u<l;u++)for(let d=0,h=s[u].length;d<h;d++){let f=s[u][d]?.[1];if(!f)continue;let b=Object.keys(f);for(let p=0,y=b.length;p<y;p++)f[b[p]]=c[f[b[p]]]}let a=[];for(let u in i)a[u]=s[i[u]];return[o,a,n]}function F(t,e){if(t){for(let s of Object.keys(t).sort((r,n)=>n.length-r.length))if(Ze(s).test(e))return[...t[s]]}}var X=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[g]:Object.create(null)},this.#e={[g]:Object.create(null)}}add(t,e,s){let r=this.#t,n=this.#e;if(!r||!n)throw new Error(J);r[t]||[r,n].forEach(c=>{c[t]=Object.create(null),Object.keys(c[g]).forEach(a=>{c[t][a]=[...c[g][a]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let c=Ze(e);t===g?Object.keys(r).forEach(a=>{r[a][e]||=F(r[a],e)||F(r[g],e)||[]}):r[t][e]||=F(r[t],e)||F(r[g],e)||[],Object.keys(r).forEach(a=>{(t===g||t===a)&&Object.keys(r[a]).forEach(u=>{c.test(u)&&r[a][u].push([s,o])})}),Object.keys(n).forEach(a=>{(t===g||t===a)&&Object.keys(n[a]).forEach(u=>c.test(u)&&n[a][u].push([s,o]))});return}let i=W(e)||[e];for(let c=0,a=i.length;c<a;c++){let u=i[c];Object.keys(n).forEach(l=>{(t===g||t===l)&&(n[l][u]||=[...F(r[l],u)||F(r[g],u)||[]],n[l][u].push([s,o-a+c+1]))})}}match=ge;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,Bt(),t}#r(t){let e=[],s=t===g;return[this.#t,this.#e].forEach(r=>{let n=r[t]?Object.keys(r[t]).map(o=>[o,r[t][o]]):[];n.length!==0?(s||=!0,e.push(...n)):t!==g&&e.push(...Object.keys(r[g]).map(o=>[o,r[g][o]]))}),s?_t(e):null}};var be=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,s){if(!this.#e)throw new Error(J);this.#e.push([t,e,s])}match(t,e){if(!this.#e)throw new Error("Fatal error");let s=this.#t,r=this.#e,n=s.length,o=0,i;for(;o<n;o++){let c=s[o];try{for(let a=0,u=r.length;a<u;a++)c.add(...r[a]);i=c.match(t,e)}catch(a){if(a instanceof K)continue;throw a}this.match=c.match.bind(c),this.#t=[c],this.#e=void 0;break}if(o===n)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var U=Object.create(null),et=class tt{#t;#e;#r;#o=0;#n=U;constructor(e,s,r){if(this.#e=r||Object.create(null),this.#t=[],e&&s){let n=Object.create(null);n[e]={handler:s,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(e,s,r){this.#o=++this.#o;let n=this,o=De(s),i=[];for(let c=0,a=o.length;c<a;c++){let u=o[c],l=o[c+1],d=ke(u,l),h=Array.isArray(d)?d[0]:u;if(h in n.#e){n=n.#e[h],d&&i.push(d[1]);continue}n.#e[h]=new tt,d&&(n.#r.push(d),i.push(d[1])),n=n.#e[h]}return n.#t.push({[e]:{handler:r,possibleKeys:i.filter((c,a,u)=>u.indexOf(c)===a),score:this.#o}}),n}#s(e,s,r,n){let o=[];for(let i=0,c=e.#t.length;i<c;i++){let a=e.#t[i],u=a[s]||a[g],l={};if(u!==void 0&&(u.params=Object.create(null),o.push(u),r!==U||n&&n!==U))for(let d=0,h=u.possibleKeys.length;d<h;d++){let f=u.possibleKeys[d],b=l[u.score];u.params[f]=n?.[f]&&!b?n[f]:r[f]??n?.[f],l[u.score]=!0}}return o}search(e,s){let r=[];this.#n=U;let o=[this],i=de(s),c=[];for(let a=0,u=i.length;a<u;a++){let l=i[a],d=a===u-1,h=[];for(let f=0,b=o.length;f<b;f++){let p=o[f],y=p.#e[l];y&&(y.#n=p.#n,d?(y.#e["*"]&&r.push(...this.#s(y.#e["*"],e,p.#n)),r.push(...this.#s(y,e,p.#n))):h.push(y));for(let m=0,O=p.#r.length;m<O;m++){let T=p.#r[m],v=p.#n===U?{}:{...p.#n};if(T==="*"){let P=p.#e["*"];P&&(r.push(...this.#s(P,e,p.#n)),P.#n=v,h.push(P));continue}let[jt,$e,D]=T;if(!l&&!(D instanceof RegExp))continue;let R=p.#e[jt],At=i.slice(a).join("/");if(D instanceof RegExp){let P=D.exec(At);if(P){if(v[$e]=P[0],r.push(...this.#s(R,e,p.#n,v)),Object.keys(R.#e).length){R.#n=v;let Ct=P[0].match(/\//)?.length??0;(c[Ct]||=[]).push(R)}continue}}(D===!0||D.test(l))&&(v[$e]=l,d?(r.push(...this.#s(R,e,v,p.#n)),R.#e["*"]&&r.push(...this.#s(R.#e["*"],e,v,p.#n))):(R.#n=v,h.push(R)))}}o=h.concat(c.shift()??[])}return r.length>1&&r.sort((a,u)=>a.score-u.score),[r.map(({handler:a,params:u})=>[a,u])]}};var we=class{name="TrieRouter";#t;constructor(){this.#t=new et}add(t,e,s){let r=W(e);if(r){for(let n=0,o=r.length;n<o;n++)this.#t.insert(t,r[n],s);return}this.#t.insert(t,e,s)}match(t,e){return this.#t.search(t,e)}};var ve=class extends Je{constructor(t={}){super(t),this.router=t.router??new be({routers:[new X,new we]})}};import{join as _}from"node:path";import{mkdir as br,writeFile as Te,readFile as St,unlink as wr}from"node:fs/promises";import{pathToFileURL as vr}from"node:url";import{createServer as zt}from"http";import{Http2ServerRequest as Gt}from"http2";import{Http2ServerRequest as Ee}from"http2";import{Readable as rt}from"stream";import sr from"crypto";var A=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Vt=t=>t instanceof A?t:new A(t.message,{cause:t}),Wt=global.Request,q=class extends Wt{constructor(t,e){typeof t=="object"&&I in t&&(t=t[I]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Jt=t=>{let e=[],s=t.rawHeaders;for(let r=0;r<s.length;r+=2){let{[r]:n,[r+1]:o}=s;n.charCodeAt(0)!==58&&e.push([n,o])}return new Headers(e)},nt=Symbol("wrapBodyStream"),Kt=(t,e,s,r,n)=>{let o={method:t,headers:s,signal:n.signal};if(t==="TRACE"){o.method="GET";let i=new q(e,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(r.rawBody),i.close()}});else if(r[nt]){let i;o.body=new ReadableStream({async pull(c){try{i||=rt.toWeb(r).getReader();let{done:a,value:u}=await i.read();a?c.close():c.enqueue(u)}catch(a){c.error(a)}}})}else o.body=rt.toWeb(r);return new q(e,o)},I=Symbol("getRequestCache"),Qt=Symbol("requestCache"),Z=Symbol("incomingKey"),ee=Symbol("urlKey"),Yt=Symbol("headersKey"),H=Symbol("abortControllerKey"),Xt=Symbol("getAbortController"),te={get method(){return this[Z].method||"GET"},get url(){return this[ee]},get headers(){return this[Yt]||=Jt(this[Z])},[Xt](){return this[I](),this[H]},[I](){return this[H]||=new AbortController,this[Qt]||=Kt(this.method,this[ee],this.headers,this[Z],this[H])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(te,t,{get(){return this[I]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(te,t,{value:function(){return this[I]()[t]()}})});Object.setPrototypeOf(te,q.prototype);var Zt=(t,e)=>{let s=Object.create(te);s[Z]=t;let r=t.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(t instanceof Ee)throw new A("Absolute URL for :path is not allowed in HTTP/2");try{let c=new URL(r);s[ee]=c.href}catch(c){throw new A("Invalid absolute URL",{cause:c})}return s}let n=(t instanceof Ee?t.authority:t.headers.host)||e;if(!n)throw new A("Missing host header");let o;if(t instanceof Ee){if(o=t.scheme,!(o==="http"||o==="https"))throw new A("Unsupported scheme")}else o=t.socket&&t.socket.encrypted?"https":"http";let i=new URL(`${o}://${n}${r}`);if(i.hostname.length!==n.length&&i.hostname!==n.replace(/:\d+$/,""))throw new A("Invalid host header");return s[ee]=i.href,s},st=Symbol("responseCache"),$=Symbol("getResponseCache"),C=Symbol("cache"),Re=global.Response,L=class ot{#t;#e;[$](){return delete this[C],this[st]||=new Re(this.#t,this.#e)}constructor(e,s){let r;if(this.#t=e,s instanceof ot){let n=s[st];if(n){this.#e=n,this[$]();return}else this.#e=s.#e,r=new Headers(s.#e.headers)}else this.#e=s;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(r||=s?.headers||{"content-type":"text/plain; charset=UTF-8"},this[C]=[s?.status||200,e,r])}get headers(){let e=this[C];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[$]().headers}get status(){return this[C]?.[0]??this[$]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(L.prototype,t,{get(){return this[$]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(L.prototype,t,{value:function(){return this[$]()[t]()}})});Object.setPrototypeOf(L,Re);Object.setPrototypeOf(L.prototype,Re.prototype);async function er(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function it(t,e,s){let r=c=>{t.cancel(c).catch(()=>{})};return e.on("close",r),e.on("error",r),(s??t.read()).then(i,n),t.closed.finally(()=>{e.off("close",r),e.off("error",r)});function n(c){c&&e.destroy(c)}function o(){t.read().then(i,n)}function i({done:c,value:a}){try{if(c)e.end();else if(!e.write(a))e.once("drain",o);else return t.read().then(i,n)}catch(u){n(u)}}}function tr(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:it(t.getReader(),e)}var at=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let s=[];for(let[r,n]of t)r==="set-cookie"?s.push(n):e[r]=n;return s.length>0&&(e["set-cookie"]=s),e["content-type"]??="text/plain; charset=UTF-8",e},rr="x-hono-already-sent",nr=global.fetch;typeof global.crypto>"u"&&(global.crypto=sr);global.fetch=(t,e)=>(e={compress:!1,...e},nr(t,e));var Pe=Symbol("outgoingEnded"),or=()=>new Response(null,{status:400}),ct=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),xe=(t,e)=>{let s=t instanceof Error?t:new Error("unknown error",{cause:t});s.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${s.message}`),e.destroy(s))},ut=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},lt=async(t,e)=>{let[s,r,n]=t[C];n instanceof Headers&&(n=at(n)),typeof r=="string"?n["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?n["Content-Length"]=r.byteLength:r instanceof Blob&&(n["Content-Length"]=r.size),e.writeHead(s,n),typeof r=="string"||r instanceof Uint8Array?e.end(r):r instanceof Blob?e.end(new Uint8Array(await r.arrayBuffer())):(ut(e),await tr(r,e)?.catch(o=>xe(o,e))),e[Pe]?.()},ir=t=>typeof t.then=="function",ar=async(t,e,s={})=>{if(ir(t))if(s.errorHandler)try{t=await t}catch(n){let o=await s.errorHandler(n);if(!o)return;t=o}else t=await t.catch(ct);if(C in t)return lt(t,e);let r=at(t.headers);if(t.body){let n=t.body.getReader(),o=[],i=!1,c;if(r["transfer-encoding"]!=="chunked"){let a=2;for(let u=0;u<a;u++){c||=n.read();let l=await er(c).catch(d=>{console.error(d),i=!0});if(!l){if(u===1){await new Promise(d=>setTimeout(d)),a=3;continue}break}if(c=void 0,l.value&&o.push(l.value),l.done){i=!0;break}}i&&!("content-length"in r)&&(r["content-length"]=o.reduce((u,l)=>u+l.length,0))}e.writeHead(t.status,r),o.forEach(a=>{e.write(a)}),i?e.end():(o.length===0&&ut(e),await it(n,e,c))}else r[rr]||(e.writeHead(t.status,r),e.end());e[Pe]?.()},cr=(t,e={})=>{let s=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==q&&(Object.defineProperty(global,"Request",{value:q}),Object.defineProperty(global,"Response",{value:L})),async(r,n)=>{let o,i;try{i=Zt(r,e.hostname);let c=!s||r.method==="GET"||r.method==="HEAD";if(c||(r[nt]=!0,r.on("end",()=>{c=!0}),r instanceof Gt&&(n[Pe]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{r.destroy(),n.destroy()})})})),n.on("close",()=>{i[H]&&(r.errored?i[H].abort(r.errored.toString()):n.writableFinished||i[H].abort("Client connection prematurely closed.")),c||setTimeout(()=>{c||setTimeout(()=>{r.destroy()})})}),o=t(i,{incoming:r,outgoing:n}),C in o)return lt(o,n)}catch(c){if(o)return xe(c,n);if(e.errorHandler){if(o=await e.errorHandler(i?c:Vt(c)),!o)return}else i?o=ct(c):o=or()}try{return await ar(o,n,e)}catch(c){return xe(c,n)}}},ur=t=>{let e=t.fetch,s=cr(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||zt)(t.serverOptions||{},s)},dt=(t,e)=>{let s=ur(t);return s.listen(t?.port??3e3,t.hostname,()=>{let r=s.address();e&&e(r)}),s};import{readFileSync as lr,existsSync as dr}from"node:fs";function ht(){let t=process.env.MOLNOS_RUNTIME_CONFIG;if(!t||!dr(t))return{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}};try{let e=lr(t,"utf-8");return JSON.parse(e)}catch(e){return console.error("[loadRuntimeConfig] Failed to load runtime config:",e),{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}}}}var w=class extends Error{constructor(e){super(),this.name="ValidationError",this.message=e||"Invalid input",this.cause={statusCode:400}}};var re=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};var N=class extends Error{constructor(e){super(),this.name="InvalidMethodError",this.message=e||"Invalid HTTP method",this.cause={statusCode:400}}};var se=class extends Error{constructor(e){super(),this.name="ServiceRequestError",this.message=e||"Service request failed",this.cause={statusCode:502}}};var ne=class{generatePermissionsFromBindings(e){let s=[];for(let r of e){let n=r.service;for(let o of r.permissions){if(!o.resource){s.push(`${n}.*`);continue}let i=o.resource,c=o.actions||["*"];if(o.targets&&o.targets.length>0)for(let a of c)for(let u of o.targets)s.push(`${n}.${i}.${a}:${u}`);else for(let a of c)s.push(`${n}.${i}.${a}`)}}return[...new Set(s)]}validateBindings(e){let s=["databases","storage","observability","sites","functions"];for(let r of e){if(!s.includes(r.service))throw new w(`Invalid service: ${r.service}. Must be one of: ${s.join(", ")}`);if(!r.permissions||r.permissions.length===0)throw new w("Bindings must have at least one permission");for(let n of r.permissions)if(n.targets&&n.targets.length>0){if(!n.resource)throw new w("Action-level bindings (with targets) must specify resource");if(!n.actions||n.actions.length===0)throw new w("Action-level bindings (with targets) must specify actions")}}}};var Se=class{constructor(e,s,r){this.baseUrl=e;this.authToken=s;this.bindings=r}async request(e,s,r,n){let o=`${this.baseUrl}${s}`;if(n){let d=new URLSearchParams(n);o+=`?${d.toString()}`}let i={"Content-Type":"application/json"};this.authToken&&(i.Authorization=`Bearer ${this.authToken}`),this.bindings&&this.bindings.length>0&&(i["X-Function-Bindings"]=JSON.stringify(this.bindings));let c={method:e,headers:i};r&&(c.body=JSON.stringify(r));let a=await fetch(o,c),u=a.headers.get("content-type"),l;if(u?.includes("application/json")?l=await a.json():l=await a.text(),!a.ok)throw new se(`Service request failed (${a.status}): ${typeof l=="string"?l:JSON.stringify(l)}`);return l}},je=class extends Se{async get(e,s){return this.request("POST","/get",{tableName:e,key:s})}async write(e,s,r,n,o){return this.request("POST","/write",{tableName:e,key:s,value:r,expiration:n,dictionaryName:o})}async delete(e,s){return this.request("DELETE","/delete",void 0,{tableName:e,key:s})}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}`)}},oe=class{constructor(e,s){this.serviceBaseUrls=e;this.authToken=s}createBindings(e){let s={};for(let r of e){let n=this.serviceBaseUrls[r.service];n&&r.service==="databases"&&(s.databases=new je(n,this.authToken,e))}return s}};import{EventEmitter as hr}from"node:events";var Ae=class t{static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new hr,t.instance.setMaxListeners(100)),t.instance}};function Ce(){return Ae.getInstance()}function ft(t){let e=Ce();try{e.emit("function.log",t)}catch(s){console.error("Failed to emit function log event:",s)}}var B=class{isSilent;propertyPath="";constructor(t=!1){this.isSilent=t}test(t,e){if(!e)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(t.properties,e),n=this.compileErrors(s,r),o=this.isSuccessful(s,n);return{errors:n,success:o}}compileErrors(t,e){let s=t.filter(r=>r.success===!1);return[...e,...s].flatMap(r=>r)}isSuccessful(t,e){return t.every(s=>s.success===!0)&&e.length===0}validate(t,e,s=[],r=[]){let n=t?.additionalProperties??!0,o=t?.required||[];r=this.checkForRequiredKeysErrors(o,e,r),r=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),r,n);for(let i in t){let c=o.includes(i)&&i!=="required",a=t[i],u=e[i],l=a.additionalProperties??!0;c&&(r=this.checkForRequiredKeysErrors(a.required||[],u,r)),this.isDefined(u)&&(this.handleValidation(i,u,a,s),r=this.checkForDisallowedProperties(Object.keys(u),Object.keys(a),r,l),this.handleNestedObject(u,a,s,r))}return{results:s,errors:r}}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,s){if(!this.areRequiredKeysPresent(t,e)){let r=e?Object.keys(e):[],n=this.findNonOverlappingElements(t,r),o=n.length>0?`Missing the required key: '${n.join(", ")}'!`:`Missing values for required keys: '${r.filter(i=>!e[i]).join(", ")}'!`;s.push({key:"",value:e,success:!1,error:o})}return s}checkForDisallowedProperties(t,e,s,r){if(!r){let n=this.findNonOverlappingElements(t,e);n.length>0&&s.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${n.join(", ")}'!`})}return s}handleValidation(t,e,s,r){this.updatePropertyPath(t);let n=this.validateProperty(this.propertyPath,s,e);r.push(...n);let o=(c,a)=>{c.forEach(u=>{let l=this.validateProperty(this.propertyPath,a.items,u);r.push(...l)}),this.updatePropertyPath()},i=c=>{let a=Object.keys(c),u=this.propertyPath;a.forEach(l=>{if(this.updatePropertyPath(l,u),this.isArray(c[l])&&s[l]?.items!=null)o(c[l],s[l]);else{let d=this.validateProperty(this.propertyPath,s[l],c[l]);r.push(...d)}})};this.isArray(e)&&s.items!=null?o(e,s):this.isObject(e)?i(e):this.updatePropertyPath()}handleNestedObject(t,e,s,r){if(this.isObject(t)){let n=this.getNestedObjects(t);for(let o of n){let i=e[o],c=t[o];i&&typeof c=="object"&&this.validate(i,c,s,r)}}}getNestedObjects(t){return Object.keys(t).filter(e=>{if(this.isObject(t))return e})}findNonOverlappingElements(t,e){return t.filter(s=>!e.includes(s))}areRequiredKeysPresent(t,e=[]){return t.every(s=>Object.keys(e).includes(s)?this.isDefined(e[s]):!1)}validateProperty(t,e,s){return this.validateInput(e,s).map(n=>{let{success:o,error:i}=n;return{key:t,value:s,success:o,error:i??""}})}validateInput(t,e){if(t){let s=[{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"}],r=[];for(let n of s)n.condition()&&!n.validator()&&r.push({success:!1,error:n.error});return r}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(s=>{switch(s){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 s in t){let r=t[s];e.properties.required.push(s),Array.isArray(r)?e.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?e.properties[s]=this.generateNestedObjectSchema(r):e.properties[s]=this.generatePropertySchema(r)}return e}generateArraySchema(t){let e={type:"array"},s=t.filter(r=>r);if(s.length>0){let r=s[0];s.every(o=>typeof o==typeof r)?typeof r=="object"&&!Array.isArray(r)?e.items=this.generateNestedObjectSchema(r):e.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 e}generateNestedObjectSchema(t){let e={type:"object",additionalProperties:!1,required:[]};for(let s in t){let r=t[s];e.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?e[s]=this.generateNestedObjectSchema(r):e[s]=this.generatePropertySchema(r)}return e}generatePropertySchema(t){let e=typeof t,s={type:e};return e==="string"&&(s.minLength=1),s}};async function ie(t){try{return await t.req.json()}catch{return{}}}function E(t,e="An error occurred"){let s=t?.message||t||e,r=t?.cause?.statusCode||t?.statusCode||400;return{message:s,status:r}}function pt(t,e,s={}){let r=Array.isArray(e)?e:[e];if(!t||!t.roles||!Array.isArray(t.roles)){let i=new Error("Unauthorized: User or roles missing");throw i.cause={statusCode:403},i}let n=t.roles.flatMap(i=>i?.policies?.flatMap(c=>(c?.permissions||[]).flatMap(u=>typeof u=="string"?u:u&&typeof u=="object"&&u.actions?u.actions:[]))||[]);if(!r.every(i=>n.includes(i)||n.includes("*")?!0:n.some(c=>{if(c.endsWith(".*")){let a=c.slice(0,-2);return i.startsWith(`${a}.`)}return!1}))){let i=new Error("Unauthorized");throw i.cause={statusCode:403},i}return!0}function mt(t,e,s,r,n){let o=t.find(a=>a.service===e);if(!o){let a=new Error(`Function bindings do not include access to service: ${e}`);throw a.cause={statusCode:403},a}if(!o.permissions||o.permissions.length===0)return;for(let a of o.permissions)if(!(a.resource&&a.resource!==s)){if(!a.resource||!a.actions||a.actions.length===0)return;if(a.actions.includes(r)){if(a.targets&&a.targets.length>0){if(!n)return;if(!a.targets.includes(n))continue}return}}let i=n?`:${n}`:"",c=new Error(`Function bindings do not allow: ${e}.${s}.${r}${i}`);throw c.cause={statusCode:403},c}async function x(t,e,s,r,n,o,i){if(!e)return null;let c=t.get("user");if(!c){let u=t.req.header("authorization");if(!u){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let l=u.replace(/^Bearer\s+/i,"");if(c=await e.getUserFromToken(l),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}pt(c,s,{});let a=t.req.header("x-function-bindings");if(a)try{let u=JSON.parse(a);mt(u,r,n,o,i)}catch(u){if(u.cause?.statusCode===403)throw u;let l=new Error("Invalid function bindings header");throw l.cause={statusCode:400},l}return c}var gt={properties:{name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},required:["name","code"],additionalProperties:!1};var pr=new B;async function yt(t,e,s){try{let r=await ie(t),n=pr.test(gt,r);if(!n.success)return t.json({error:"Invalid input",details:n.errors},400);await x(t,s,"functions.function.create","functions","function","create");let{name:o,code:i,methods:c,bindings:a,passAllHeaders:u,allowUnauthenticated:l}=r,d=await e.deployFunction(o,i,c,a,u,l);return t.json({success:!0,function:d},201)}catch(r){let{message:n,status:o}=E(r,"Error deploying function");return t.json({error:n},o)}}async function Oe(t,e,s){try{let{functionId:r}=t.req.param();if(!r)return t.json({error:"functionId is required"},400);let n=e.getFunction(r);return n?(n.allowUnauthenticated!==!0&&await x(t,s,"functions.function.execute","functions","function","execute",r),await e.executeFunction(r,t)):t.json({error:"Not Found",message:"Function not found"},404)}catch(r){let{message:n,status:o}=E(r,"Error executing function");return t.text(n,o)}}var bt={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var gr=new B;async function wt(t,e,s){try{let{functionId:r}=t.req.param(),n=await ie(t);if(!r)return t.json({error:"functionId is required"},400);let o=gr.test(bt,n);if(!o.success)return t.json({error:"Invalid input",details:o.errors},400);await x(t,s,"functions.function.update","functions","function","update",r);let{code:i,methods:c,bindings:a,passAllHeaders:u,allowUnauthenticated:l}=n,d=await e.updateFunction(r,{code:i,methods:c,bindings:a,passAllHeaders:u,allowUnauthenticated:l});return d?t.json({success:!0,function:d},200):t.json({error:"Function not found"},404)}catch(r){let{message:n,status:o}=E(r,"Error updating function");return t.json({error:n},o)}}async function vt(t,e,s){try{let{functionId:r}=t.req.param();return r?(await x(t,s,"functions.function.delete","functions","function","delete",r),await e.deleteFunction(r)?t.json({success:!0,message:"Function deleted"},200):t.json({error:"Function not found"},404)):t.json({error:"functionId is required"},400)}catch(r){let{message:n,status:o}=E(r,"Error deleting function");return t.json({error:n},o)}}async function Et(t,e,s){try{let{functionId:r}=t.req.param();if(!r)return t.json({error:"functionId is required"},400);await x(t,s,"functions.function.get","functions","function","read",r);let n=e.getFunction(r);return n?t.json({success:!0,function:n},200):t.json({error:"Function not found"},404)}catch(r){let{message:n,status:o}=E(r,"Error getting function");return t.json({error:n},o)}}async function xt(t,e,s){try{await x(t,s,"functions.function.get","functions","function","read");let r=e.getFunctions();return t.json({success:!0,count:r.length,functions:r},200)}catch(r){let{message:n,status:o}=E(r,"Error listing functions");return t.json({error:n},o)}}var ae=class{baseUrl;authToken;constructor(e,s){this.baseUrl=e.replace(/\/$/,""),this.authToken=s}async createCustomRole(e,s,r,n){let o=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:e,name:s,description:r,permissions:n})});if(!o.ok){let i=`Failed to create role: ${o.statusText}`;try{i=(await o.json()).error||i}catch{i=await o.text().catch(()=>o.statusText)||i}throw new Error(i)}}async updateRole(e,s){let r=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(s)});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to update role: ${r.statusText}`)}}async deleteRole(e){let s=await fetch(`${this.baseUrl}/identity/roles/${e}`,{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(e,s,r){let n=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:e,description:s,roles:r})});if(!n.ok){let i=`Failed to create service account: ${n.statusText}`;try{i=(await n.json()).error||i}catch{i=await n.text().catch(()=>n.statusText)||i}throw new Error(i)}let o=await n.json();return{id:o.id,apiKey:o.apiKey}}async deleteIdentity(e){let s=await fetch(`${this.baseUrl}/identity/service-accounts/${e}`,{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(e){try{let s=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return s.ok?await s.json():null}catch{return null}}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}};var Fe=class{functionsDir;functions=new Map;debug;bindingService;constructor(e){this.functionsDir=e.functionsDir||_(process.cwd(),"functions-data"),this.debug=e.debug||!1,this.bindingService=new ne}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions()}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.passAllHeaders!==void 0?{passAllHeaders:e.passAllHeaders}:{},...e.allowUnauthenticated!==void 0?{allowUnauthenticated:e.allowUnauthenticated}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}))}async ensureFunctionsDirExists(){ce(this.functionsDir)||(this.debug&&console.log(`Creating functions directory: ${this.functionsDir}`),await br(this.functionsDir,{recursive:!0}))}async loadExistingFunctions(){try{let e=_(this.functionsDir,"functions.json");if(ce(e)){let s=await St(e,"utf8"),r=JSON.parse(s);for(let n of r)ce(n.filePath)&&(this.functions.set(n.id,n),this.debug&&console.log(`Loaded function: ${n.name} (${n.id})`))}}catch(e){this.debug&&console.error("Error loading functions metadata:",e.message)}}async saveFunctionsMetadata(){try{let e=_(this.functionsDir,"functions.json"),s=Array.from(this.functions.values());await Te(e,JSON.stringify(s,null,2),"utf8")}catch(e){this.debug&&console.error("Error saving functions metadata:",e.message)}}async deployFunction(e,s,r,n,o,i){if(!e||typeof e!="string")throw new w("Function name is required and must be a string");if(!s||typeof s!="string")throw new w("Function code is required and must be a string");if(r!==void 0){if(!Array.isArray(r))throw new w("Methods must be an array");let h=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let f of r)if(!h.includes(f.toUpperCase()))throw new N(`Invalid HTTP method: ${f}. Must be one of: ${h.join(", ")}`)}n&&n.length>0&&this.bindingService.validateBindings(n);let c=yr("sha256").update(`${e}-${Date.now()}`).digest("hex").substring(0,12),a=_(this.functionsDir,`${c}.mjs`),u=this.wrapFunctionCode(s);await Te(a,u,"utf8");let l=Date.now(),d={id:c,name:e,filePath:a,endpoint:`/functions/run/${c}`,...r&&r.length>0?{methods:r.map(h=>h.toUpperCase())}:{},...n?{bindings:n}:{},...o!==void 0?{passAllHeaders:o}:{},...i!==void 0?{allowUnauthenticated:i}:{},createdAt:l,updatedAt:l};return this.functions.set(c,d),await this.saveFunctionsMetadata(),this.debug&&(console.log(`Function deployed: ${e} (${c})`),console.log(`Endpoint: ${d.endpoint}`),d.methods&&console.log(`Allowed methods: ${d.methods.join(", ")}`)),d}async updateFunction(e,s){let r=this.functions.get(e);if(!r)throw new re(`Function with ID ${e} not found`);let{code:n,methods:o,bindings:i,passAllHeaders:c,allowUnauthenticated:a}=s;if(n===void 0&&o===void 0&&i===void 0&&c===void 0&&a===void 0)throw new w("At least one parameter (code, methods, bindings, passAllHeaders, or allowUnauthenticated) must be provided");if(n!==void 0&&(typeof n!="string"||!n))throw new w("Function code must be a non-empty string");if(o!==void 0){if(!Array.isArray(o))throw new w("Methods must be an array");let u=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let l of o)if(!u.includes(l.toUpperCase()))throw new N(`Invalid HTTP method: ${l}. Must be one of: ${u.join(", ")}`)}if(n!==void 0){let u=this.wrapFunctionCode(n);await Te(r.filePath,u,"utf8")}return o!==void 0&&(o.length>0?r.methods=o.map(u=>u.toUpperCase()):delete r.methods),i!==void 0&&(i.length>0&&this.bindingService.validateBindings(i),r.bindings=i.length>0?i:void 0),c!==void 0&&(c?r.passAllHeaders=!0:delete r.passAllHeaders),a!==void 0&&(r.allowUnauthenticated=a),r.updatedAt=Date.now(),this.functions.set(e,r),await this.saveFunctionsMetadata(),this.debug&&(console.log(`Function updated: ${r.name} (${e})`),r.methods&&console.log(`Allowed methods: ${r.methods.join(", ")}`)),r}async deleteFunction(e){let s=this.functions.get(e);if(!s)return!1;try{return ce(s.filePath)&&await wr(s.filePath),this.functions.delete(e),await this.saveFunctionsMetadata(),this.debug&&console.log(`Function deleted: ${s.name} (${e})`),!0}catch(r){throw console.error(`Error deleting function ${e}:`,r.message),r}}wrapFunctionCode(e){let s=e;if(/export\s+default\s+\w+/.test(e))return`// FunctionsService generated module
3
+ // Generated at: ${new Date().toISOString()}
4
+
5
+ // User function code starts here
6
+ ${s}
7
+ // User function code ends here
8
+ `;let r=e.match(/export\s*\{([^}]+)\}/);if(r){let n=r[1],o=n.match(/(\w+)\s+as\s+handler\b/)||n.match(/\bhandler\b/);if(o){let i=o[1]||"handler";s=e.replace(/export\s*\{[^}]+\}/,`export default ${i}`)}}else s=`${e}
9
+
10
+ export default handler;`;return`// FunctionsService generated module
11
+ // Generated at: ${new Date().toISOString()}
12
+
13
+ // User function code starts here
14
+ ${s}
15
+ // User function code ends here
16
+ `}async executeFunction(e,s){try{let r=this.functions.get(e);if(!r)return s.json({error:"Not Found",message:"Function not found"},404);if(r.allowUnauthenticated!==!0&&!s.req.header("authorization"))return s.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(r.methods&&r.methods.length>0){let h=s.req.method.toUpperCase();if(!r.methods.includes(h))return s.json({error:"Method Not Allowed",message:`This function only accepts: ${r.methods.join(", ")}`},405,{Allow:r.methods.join(", ")})}this.debug&&console.log(`Executing function: ${r.name} (${e})`);let n=null;try{["POST","PUT","PATCH"].includes(s.req.method)&&((s.req.header("content-type")||"").includes("application/json")?n=await s.req.json():n=await s.req.text())}catch{}let o=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],i={};s.req.raw.headers.forEach((h,f)=>{(r.passAllHeaders||!o.includes(f.toLowerCase()))&&(i[f]=h)});let c=s.req.path,a=`/run/${e}`,u=c.startsWith(a)?c.substring(a.length):"/";u||(u="/");let l={};if(r.bindings&&r.bindings.length>0){let f=s.req.header("authorization")?.replace(/^Bearer\s+/i,"")||null,b={databases:"http://localhost:3004",storage:"http://localhost:3001",observability:"http://localhost:3005",sites:"http://localhost:3003",functions:"http://localhost:3002"};l=new oe(b,f).createBindings(r.bindings)}let d={request:{method:s.req.method,path:s.req.path,subpath:u,query:s.req.query(),headers:i,body:n},functionId:e,functionName:r.name,bindings:l};try{let b=(await import(`${vr(r.filePath).href}?t=${Date.now()}`)).default;if(typeof b!="function")return s.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:p,restore:y}=this.createConsoleInterceptor(e,r.name);Object.assign(console,p);let m;try{m=await b(d.request,d)}finally{y()}if(m&&typeof m=="object"){if(m.statusCode!==void 0&&m.body!==void 0){let O=m.statusCode||200,T=m.headers||{},v=typeof m.body=="object"?JSON.stringify(m.body):m.body;return s.body(v,O,T)}return s.json(m)}return typeof m=="string"?s.text(m):typeof m=="number"||typeof m=="boolean"?s.json({result:m}):s.json({result:m===null?null:void 0})}catch(h){return console.error("Function execution error:",h),s.json({error:"Function Execution Error",message:this.debug?h.message:"Error executing function",stack:this.debug?h.stack:void 0},500)}}catch(r){return console.error("Error processing function execution:",r),s.json({error:"Internal Server Error",message:this.debug?r.message:"Failed to process function execution"},500)}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(s=>({id:s.id,name:s.name,endpoint:s.endpoint,createdAt:new Date(s.createdAt).toISOString(),updatedAt:new Date(s.updatedAt).toISOString()}))}}createConsoleInterceptor(e,s){let r={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)},n=(o,i)=>{let c=i.map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" ");ft({functionId:e,functionName:s,level:o,message:c,timestamp:Date.now()})};return{interceptedConsole:{log:(...o)=>{r.log(...o),n("info",o)},error:(...o)=>{r.error(...o),n("error",o)},warn:(...o)=>{r.warn(...o),n("warn",o)},info:(...o)=>{r.info(...o),n("info",o)},debug:(...o)=>{r.debug(...o),n("debug",o)}},restore:()=>{console.log=r.log,console.error=r.error,console.warn=r.warn,console.info=r.info,console.debug=r.debug}}}};async function Er(t){let e=t.dataPath||"data",s=_(e,"functions"),r=new Fe({functionsDir:t.functions?.path||s,debug:t.functions?.debug||!1});await r.start();let n=t.identityApiUrl?new ae(t.identityApiUrl):null,o=Ce(),i=t.observability?.url||"http://localhost:3005";o.on("function.log",a=>{fetch(`${i}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:`functions.${a.functionId}`,level:a.level,message:a.message,metadata:{functionId:a.functionId,functionName:a.functionName,...a.metadata}})}).catch(u=>{t.functions?.debug&&console.error("Failed to send log to observability service:",u)})});let c=new ve;return c.post("/deploy",async a=>yt(a,r,n)),c.get("/list",async a=>xt(a,r,n)),c.get("/stats",async a=>{try{let u=r.getStats();return a.json({success:!0,stats:u})}catch(u){return a.json({error:u.message},500)}}),c.get("/:functionId/config",async a=>{try{let u=a.req.param("functionId"),l=r.getFunction(u);if(!l)return a.json({error:"Function not found"},404);let d="";try{let h=await St(l.filePath,"utf8"),f="// User function code starts here",b="// User function code ends here",p=h.indexOf(f),y=h.indexOf(b);p!==-1&&y!==-1?(d=h.substring(p+f.length,y).trim().replace(/^\n+/,"").replace(/\n+$/,""),d=d.replace(/\n*export\s+default\s+handler;\s*$/,"")):d=h}catch(h){return a.json({error:"Failed to read function code",message:h.message},500)}return a.json({success:!0,function:{id:l.id,name:l.name,endpoint:l.endpoint,filePath:l.filePath,code:d,...l.methods?{methods:l.methods}:{},...l.bindings?{bindings:l.bindings}:{},...l.passAllHeaders!==void 0?{passAllHeaders:l.passAllHeaders}:{},...l.allowUnauthenticated!==void 0?{allowUnauthenticated:l.allowUnauthenticated}:{},createdAt:new Date(l.createdAt).toISOString(),updatedAt:new Date(l.updatedAt).toISOString()}})}catch(u){return a.json({error:u.message},500)}}),c.get("/:functionId",async a=>Et(a,r,n)),c.put("/:functionId",async a=>wt(a,r,n)),c.delete("/:functionId",async a=>vt(a,r,n)),c.all("/run/:functionId/*",async a=>Oe(a,r,n)),c.all("/run/:functionId",async a=>Oe(a,r,n)),dt({fetch:c.fetch,port:t.server.port||3002,hostname:t.server.host||"localhost"}),console.log(`Functions server started on ${t.server.host||"localhost"}:${t.server.port||3002}`),c}var xr=process.argv.slice(2),Rt=xr.find(t=>t.startsWith("--port=")),Rr=Rt?parseInt(Rt.split("=")[1],10):3002,Pt=ht(),Pr={molnos:{dataPath:Pt.molnos.dataPath},functions:{debug:!0},server:{port:Rr,host:Pt.server.host},identityApiUrl:process.env.IDENTITY_API_URL||"http://localhost:3000"};Er(Pr);export{Fe as FunctionsService,Er as startServer};