mutorjs 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.cjs CHANGED
@@ -1,16 +1,1480 @@
1
- "use strict";var Q=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var we=(e,r)=>{for(var t in r)Q(e,t,{get:r[t],enumerable:!0})},be=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Ee(r))!Oe.call(e,o)&&o!==t&&Q(e,o,{get:()=>r[o],enumerable:!(s=ye(r,o))||s.enumerable});return e};var Re=e=>be(Q({},"__esModule",{value:!0}),e);var Ne={};we(Ne,{default:()=>Ce});module.exports=Re(Ne);var de=require("fs"),P=require("fs/promises"),I=require("path");function X(e,r){return`${" ".repeat(e+r+1)}^`}var d=class e extends Error{constructor(t){super(t);this.name="MutorError";Object.setPrototypeOf(this,e.prototype)}},j=class e extends d{constructor(t,s,o,c,f){let m=s.toString().length+2,i=`${t}
2
-
3
- `;i+=`at ${f}:${s}:${c+1}
4
- `,s>1&&(i+=`${(s-1).toString().padStart(m-2)} | ...
5
- `),i+=`${s} | ${o}
6
- `,i+=X(c,m);super(i);this.name="MutorCompilerError";Object.setPrototypeOf(this,e.prototype)}};var oe=new Set(["for","if","else","true","false","null","undefined","end","in","of"]),W=new Set(["::","||","??","&&","**","^","|","&","!","-","%","+","*","/",">","<",">=","<=","==","!=",">>","<<",".","?.","(",")","[","]",",",":","?"]);var se=new Set(["==","!="]),k=new Set([">","<",">=","<="]);var ie=new Set(["+","-"]),ae=new Set(["*","/","%"]),ce=new Set([".","?.","[","::"]),pe=new Set(["-","+","!"]),le={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},C={build:{include:new Set([".html",".txt"]),exclude:new Set(["node_modules",".git"])},autoEscape:!0,allowedProps:new Set,forbiddenProps:new Set(["__proto__","constructor","prototype"]),allowFnCalls:!1,delimiters:{closingTag:"}}",openingTag:"{{",openingTagEscape:"\\",whitespaceTrim:"~",commentTag:"#"},keepOpeningTagEscapeDelimiter:!1,cache:{active:!0,maxSize:50*1024*1024}},ue={JSON:{stringify(e){try{return JSON.stringify(e)}catch{throw new d("JSON.stringify failed: invalid value")}},parse(e){if(typeof e!="string")throw new d("JSON.parse expects a string");try{return JSON.parse(e)}catch{throw new d("JSON.parse failed: invalid JSON string")}}},Object:{keys(e){if(!e||typeof e!="object")throw new d("Object.keys expects an object");return Object.keys(e)},values(e){if(!e||typeof e!="object")throw new d("Object.values expects an object");return Object.values(e)},entries(e){if(!e||typeof e!="object")throw new d("Object.entries expects an object");return Object.entries(e)},hasOwn(e,r){if(!e||typeof e!="object")throw new d("Object.hasOwn expects an object");return Object.hasOwn(e,r)},freeze(e){if(!e||typeof e!="object")throw new d("Object.freeze expects an object");return Object.freeze(e)},seal(e){if(!e||typeof e!="object")throw new d("Object.seal expects an object");return Object.seal(e)},fromEntries(e){if(!Array.isArray(e))throw new d("Object.fromEntries expects an array");return Object.fromEntries(e)}},Array:{isArray(e){return Array.isArray(e)},from(e){return Array.from(e)}},Number:{isFinite(e){return Number.isFinite(e)},isNaN(e){return Number.isNaN(e)},parseInt(e,r=10){return Number.parseInt(e,r)},parseFloat(e){return Number.parseFloat(e)}},String:{fromCharCode(...e){return String.fromCharCode(...e)}},Math:{abs(e){return Math.abs(e)},floor(e){return Math.floor(e)},ceil(e){return Math.ceil(e)},round(e){return Math.round(e)},max(...e){return Math.max(...e)},min(...e){return Math.min(...e)},random(){return Math.random()}},Date:{now(){return Date.now()},parse(e){if(typeof e!="string")throw new d("Date.parse expects a string");return Date.parse(e)}},Boolean:{valueOf(e){return!!e}}};function z(e){return typeof e!="string"?e:/[&<>"']/.test(e)?e.replace(/[&<>"']/g,r=>le[r]):e}var $=require("path");function v(e,...r){let t=(0,$.isAbsolute)(e)?e:(0,$.resolve)(process.cwd(),e);if(r.length){let s=(0,$.dirname)(t);return(0,$.resolve)(s,...r)}return t}function B(e,r,t){if(t.has(e)&&!r.has(e))throw new d(`Forbidden property access. Access to this computed property "${e}" is forbidden.`);return e}var Y="object",fe=Symbol("__mutor_safe_context");function L(e){if(!e||typeof e!==Y||fe in e)return e;let r=new WeakSet;function t(o,c=""){if(!o||typeof o!==Y||r.has(o))return o;r.add(o);let f=Object.getPrototypeOf(o);if(f&&f!==Object.prototype&&f!==Array.prototype)throw new d(`Unsafe prototype detected at ${c||"root"}`);if(Array.isArray(o)){for(let i=0;i<o.length;i++)o[i]=t(o[i],`${c}[${i}]`);return o}if(o instanceof Map){for(let[i,p]of o.entries())typeof i===Y&&t(i,`${c}.mapKey`),o.set(i,t(p,`${c}.mapValue`));return o}if(o instanceof Set){let i=new Set;for(let p of o.values())i.add(t(p,c));o.clear();for(let p of i)o.add(p);return o}let m=Object.getOwnPropertyDescriptors(o);for(let i of Object.keys(m)){let p=m[i];if(p.get||p.set)throw new d(`Getter/setter not allowed: ${c}.${i}`);let _=o[i];_&&typeof _===Y&&(o[i]=t(_,`${c}.${i}`))}return o}let s=t(e);return s&&typeof s===Y&&Object.defineProperty(s,fe,{value:!0,enumerable:!1,writable:!1,configurable:!1}),s}function G(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$/g,"\\$")}function K(e,r){let s=e.slice(0,r).split(`
7
- `).length,o=e.lastIndexOf(`
8
- `,r-1)+1;return{line:s,lineIndex:o}}function J(e,r,t){let s=e.indexOf(`
9
- `,r);return{line:e.slice(r,s===-1?void 0:s),pos:t-r}}function U(e,r){let{scope:t,forbiddenProps:s,allowedProps:o}=r;function c(a){return t.includes(a)?a:`ctx.${a}`}function f(a){switch(a.type){case 17:return"}";case 5:return a.value;case 4:return`\`${/\$/.test(a.value)?a.value.replaceAll("$","\\$"):a.value}\``;case 10:return a.true?"true":"false";case 12:return"null";case 11:return"undefined";case 7:return c(a.value);case 9:return`(${f(a.expr)})`;case 2:return`${a.operator}${f(a.expr)}`;case 0:return`${f(a.left)} ${a.operator} ${f(a.right)}`;case 1:return`${f(a.condition)} ? ${f(a.left)} : ${f(a.right)}`;case 8:return i(a);case 3:return p(a);case 6:return m(a);case 13:return _(a);case 16:return"} else {";case 14:return y(a);case 15:return b(a);default:throw new d(`Unsupported expression type: ${a.type}`)}}function m(a){if(a.left.type!==7)throw{message:"Invalid usage of namespace operator.",pos:a.pos};return`namespaces.${a.left.value}.${a.right.value}`}function i(a){let E=f(a.left);if(a.bracketNotation){let h=f(a.right),O=a.optional?"?.":"";return a.right.type===4||a.right.type===5?`${E}${O}[${h}]`:`${E}${O}[validateComputedProps(${h}, allowedProps, forbiddenProps)]`}else{let h=a.right.value,O=a.optional?"?.":".";if(s.has(h)&&!o.has(h))throw{message:"Forbidden property access.",pos:a.right.pos};return`${E}${O}${h}`}}function p(a){let E=f(a.expr),h=a.optional?"?.":"",O=a.args.map(S=>f(S)).join(", ");return`${E}${h}(${O})`}function _(a){let{iterable:E,loopType:h,variable:O}=a;return`for(const ${O} ${h===1?"in":"of"} ${U(E,r)}){`}function y(a){let{condition:E}=a;return`if(${U(E,r)}){`}function b(a){let{condition:E}=a;return`}else if(${U(E,r)}){`}return f(e)}function q(e){switch(e){case 0:return"identifier";case 1:return"keyword";case 2:return"number";case 4:return"operator";case 3:return"string"}}function ee(e,r){let t=0,s=!1;function o(n,l){let u=e[t],N=e[e.length-1];if(!u)throw{message:`Unexpected end of expression. Expected ${l?`'${l}'`:`${n===0?"an":"a"} ${q(n)}`}.`,pos:N.pos+N.value.length-1};if(u.type!==n)throw{message:`Unexpected token type. Expected ${l?`'${l}'`:q(n)} but got ${q(u.type)} instead.`,pos:u.pos};if(l!==void 0&&u.value!==l)throw{message:`Unexpected token '${u?.value}'. Expected ${n===0?"an":"a"} ${q(n)} instead.`,pos:u.pos};return e[t++]}function c(){let n=e[t-1].pos,l=o(0).value,u;try{u=o(1,"in")}catch{u=o(1,"of")}let N=u.value==="in"?1:0,F=w();return{type:13,loopType:N,iterable:F,variable:l,pos:n}}function f(){let n=w();return{condition:n,pos:n.pos,type:14}}function m(){let n=e[t-1].pos;try{return o(1,"if"),{...f(),type:15,pos:n}}catch{return{type:16,pos:n}}}function i(){let n=[];if(e[t]?.type===4&&e[t]?.value===")")return n;for(n.push(w());e[t]?.type===4&&e[t]?.value===","&&e[t]?.value!==")";)t++,n.push(w());return n}function p(){let n=e[t++];if(n?.type===2)return{type:5,value:n.value,pos:n.pos};if(n?.type===3)return{type:4,value:n.value,pos:n.pos};if(n?.type===1){if(n.value==="for"&&t===1)return c();if(n.value==="true"||n.value==="false")return{type:10,true:n.value==="true",pos:n.pos};if(n.value==="undefined")return{type:11,pos:n.pos};if(n.value==="null")return{type:12,pos:n.pos};if(n.value==="end"&&e.length===1)return{type:17,pos:n.pos};if(n.value==="if"&&t===1)return f();if(n.value==="else"&&t===1)return m()}if(n?.type===0)return{type:7,value:n.value,pos:n.pos};if(n?.type===4&&n.value==="("){let l=w();return o(4,")"),{type:9,expr:l,pos:n.pos}}if(n?.type===4&&pe.has(n.value)){let l=n.value,u=w();return{type:2,operator:l,expr:u,pos:n.pos}}throw t>e.length?{message:"Unexpected end of expression.",pos:e[e.length-1].pos}:{message:`Unexpected token '${n?.value}'.`,pos:n.pos}}function _(){let n=p();for(;e[t];){let l=e[t];if(l?.type===4&&l?.value==="("){if(t++,!s&&!r.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let u=i();o(4,")"),n={type:3,expr:n,args:u,pos:e[t-1].pos}}else if(l?.type===4&&l?.value==="?."&&e[t+1]?.type===4&&e[t+1]?.value==="("){if(t++,t++,!s&&!r.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let u=i();o(4,")"),n={type:3,expr:n,args:u,optional:!0,pos:e[t-1].pos}}else if(l?.type===4&&ce.has(l?.value)){let u=l?.value==="::",N=l?.value==="[",F=l?.value==="?.";if(t++,u&&(e[t-2]?.type!==0||e[t]?.type!==0))throw{message:`Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${e[t-2]?.value}::${e[t]?.value}' instead.`,pos:e[t]?.pos};if(u){s=!0;let R=p();n={type:6,left:n,right:R,pos:e[t-1].pos}}else if(N){let R=w();o(4,"]"),n={type:8,right:R,left:n,bracketNotation:!0,pos:e[t-1].pos}}else if(F)if(e[t]?.type===4&&e[t]?.value==="["){t++;let R=w();o(4,"]"),n={type:8,left:n,right:R,bracketNotation:!0,optional:!0,pos:e[t-1].pos}}else{let R=p();n={type:8,left:n,right:R,optional:!0,pos:e[t-1].pos}}else{let R=p();n={type:8,left:n,right:R,pos:e[t-1].pos}}}else break}return s=!1,n}function y(){let n=_();for(;e[t]?.type===4&&ae.has(e[t]?.value);){let l=e[t++].value,u=_();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function b(){let n=y();for(;e[t]?.type===4&&ie.has(e[t]?.value);){let l=e[t++].value,u=y();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function a(){let n=b();for(;e[t]?.type===4&&k.has(e[t]?.value);){let l=e[t++].value,u=b();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function E(){let n=a();for(;e[t]?.type===4&&k.has(e[t]?.value);){let l=e[t++].value,u=a();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function h(){let n=E();for(;e[t]?.type===4&&se.has(e[t]?.value);){let l=e[t++].value,u=E();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function O(){let n=S();for(;e[t]?.type===4&&e[t]?.value==="||";){let l=e[t++].value,u=S();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function S(){let n=M();for(;e[t]?.type===4&&e[t]?.value==="&&";){let l=e[t++].value,u=M();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function M(){let n=h();for(;e[t]?.type===4&&e[t]?.value==="??";){let l=e[t++].value,u=h();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function w(){let n=O();if(e[t]?.type!==4||e[t]?.value!=="?")return n;t++;let l=w();o(4,":");let u=w();return{type:1,left:l,right:u,condition:n,pos:e[t-1].pos}}return w()}function te(e,{delimiters:r}){let t=`${r.openingTag}${r.whitespaceTrim}`,s=`${r.whitespaceTrim}${r.closingTag}`,o=e.startsWith(t),c=e.endsWith(s),f=e.startsWith(o?t+r.commentTag:r.openingTag+r.commentTag);if(f)return{isComment:f,leftTrim:o,rightTrim:c};let m=e.slice(o?t.length:r.openingTag.length,e.length-(c?s.length:r.closingTag.length)),i=m.trim(),p=i.startsWith("for")||i.startsWith("if")||i.startsWith("else"),_=i.startsWith("for")||i.startsWith("if"),y=i==="end",b=i.startsWith("for");return{leftTrim:o,rightTrim:c,inner:m,isBlock:p,isBlockEnd:y,hasContext:b,requiresBlockClose:_}}function re(e){let r=0,t="",s=[];function o(){let i="";if(/[a-zA-Z$_]/.test(t)){let p=r;for(;/[a-zA-Z$_0-9]/.test(e[p])&&p<e.length;)i+=e[p],p++;s.push({type:oe.has(i)?1:0,value:i,pos:r}),r=p,t=e[r]}}function c(){let i="";if(t==='"'||t==="'"||t==="`"){let p=r+1;for(;e[p]!==t&&p<e.length;)i+=e[p],p++;if(p>e.length)throw{pos:r,message:"Found string without closing quote."};s.push({type:3,value:i,pos:r}),r=p}}function f(){if(/[0-9]/.test(t)){let i=r,p="";for(;/[0-9.oxe]/.test(e[i])&&i<e.length;)p+=e[i],i++;let _=Number(p);if(Number.isNaN(_))throw{pos:r,message:"Found invalid number literal."};s.push({type:2,value:`${_}`,pos:r}),r=i-1,t=e[r]}}function m(){let i=`${t}${e[r+1]}`;if(W.has(i)){s.push({type:4,value:i,pos:r}),r++;return}if(W.has(t)){s.push({type:4,value:t,pos:r});return}}for(;r<e.length;){if(t=e[r],f(),o(),c(),m(),!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(t)&&!W.has(t)&&!W.has(e[r-1]+t))throw{message:`Unexpected token '${t}' in expression.`,pos:r};r++}return s}function ne(e,r,t){let s=[],o=[],{delimiters:c,keepOpeningTagEscapeDelimiter:f,allowFnCalls:m,allowedProps:i,forbiddenProps:p,autoEscape:_}=r,y=!1,b=0,a='let acc="";';for(;b<e.length;){let O=function(){let g=h,x=0;for(;g>=c.openingTagEscape.length&&e.slice(g-c.openingTagEscape.length,g)===c.openingTagEscape;)x++,g-=c.openingTagEscape.length;return x%2===1};var E=O;let h=e.indexOf(c.openingTag,b);if(h===-1){let g=e.slice(b);y&&(g=g.trimStart()),g&&(a+=`acc+=\`${G(g)}\`;`);break}if(O()){let g=e.slice(b,f?h+c.openingTagEscape.length+1:h-c.openingTag.length+1);y&&(g=g.trimStart(),y=!1),a+=`acc+=\`${G(g)}\`;`,f||(a+=`acc+=\`${c.openingTag}\`;`),b=h+c.openingTag.length;continue}let S=e.indexOf(c.closingTag,h);if(S===-1){let{line:g,lineIndex:x}=K(e,h),{line:A,pos:D}=J(e,x,h);throw new j("No closing tag found.",g,A,D,t.path)}let M=e.slice(h,S+c.closingTag.length),{inner:w,leftTrim:H,rightTrim:n,isBlock:l,isBlockEnd:u,hasContext:N,requiresBlockClose:F,isComment:R}=te(M,{delimiters:c}),T=e.slice(b,h);T&&(y&&(T=T.trimStart()),H&&(T=T.trimEnd()),T&&(a+=`acc+=\`${G(T)}\`;`)),y=!1,b=S+c.closingTag.length;try{if(!R){let g=re(w),x=ee(g,{allowFnCalls:m});if(l&&F&&N?(s.push(x.variable),o.push({type:0,pos:h})):l&&F&&!N&&o.push({type:1,pos:h}),u){let D=o.pop();if(D?.type===0&&s.pop(),D===void 0)throw{message:"Unexpected end of block",pos:h}}let A=U(x,{allowedProps:i,forbiddenProps:p,scope:s});l||u?a+=A:a+=_&&!A.startsWith("namespaces.Mutor.include")?`acc+=escapeFn(${A});`:`acc+=${A};`}n&&(y=!0)}catch(g){let{message:x,pos:A}=g,{line:D,lineIndex:me}=K(e,h),{line:ge,pos:_e}=J(e,me,h);throw new j(x,D,ge,_e+A+(H?c.openingTag.length+c.whitespaceTrim.length:c.openingTag.length),t.path)}}if(o.length){let h=o.pop()?.pos,{line:O,lineIndex:S}=K(e,h),{line:M,pos:w}=J(e,S,h);throw new j("Unclosed block detected.",O,M,w+c.openingTag.length,t.path)}return a+="return acc;",new Function("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",a)}var Z=class{constructor(r={}){this.__currentRenderedPath="";this.__includeStack=new Set;this.__cacheSize=0;this.__config={...C};this.__compiledTemplatesMap=new Map;this.__currentContext=null;this.__namespaces={...ue,Mutor:{include:(r,t)=>{if(this.__includeStack.has(r))throw new d(`Circular include detected:
10
- ${Array.from(this.__includeStack).join(`
11
- `)}
12
- ${r}`);try{return this.__includeStack.add(r),this.renderComponent(r,t??this.__currentContext)}finally{this.__includeStack.delete(r)}}}};this.addConfig(r),Object.defineProperty(this.__namespaces.Mutor,"$$context",{get:()=>this.__currentContext})}addConfig(r){let{autoEscape:t,delimiters:s,allowedProps:o,forbiddenProps:c,keepOpeningTagEscapeDelimiter:f,allowFnCalls:m,cache:i,build:p}=r;return this.__config={build:{include:new Set([...p?.include||C.build.include]),exclude:new Set([...C.build.exclude,...p?.exclude||[]])},autoEscape:t===!0?!0:t!==!1,allowedProps:o||C.allowedProps,allowFnCalls:!!m,cache:{...C.cache,...i||{}},forbiddenProps:new Set([...C.forbiddenProps,...c||[]]),keepOpeningTagEscapeDelimiter:f===!0?!0:f!==!1,delimiters:{...C.delimiters,...s||{}}},this.__config}restoreDefaultConfig(){this.__config={...C}}compile(r){return ne(r,this.__config,{path:this.__currentRenderedPath||"anonymous"})}render(r,t){let s=this.__currentContext;s!==t&&(this.__currentContext=t);let o=this.compile(r)(L(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,z,B);return this.__currentContext=s,o}renderComponent(r,t){if(!this.__compiledTemplatesMap.has(r))throw new d(`No template exists with the identifier '${r}'`);let s=this.__currentRenderedPath,o=this.__currentContext,c=this.__compiledTemplatesMap.get(r);this.__currentContext=t,this.__currentRenderedPath=r;let f=c.fn(L(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,z,B);return this.__currentContext=o,this.__currentRenderedPath=s,f}registerComponent(r,t){let s=t.length*2+500;if(this.__cacheSize+s>this.__config.cache.maxSize&&!this.createEntrySpaceForTemplate(s))throw new d(`The template for the component '${r}' is too large. Consider increasing 'cache.maxSize' in the config`);this.__cacheSize+=t.length*2+500,this.__compiledTemplatesMap.set(r,{fn:this.compile(t),size:s})}reset(){this.__config={...C},this.__compiledTemplatesMap.clear(),this.__currentContext=null,this.__cacheSize=0}createEntrySpaceForTemplate(r){if(this.__cacheSize+r<this.__config.cache.maxSize)return!0;if(r>this.__config.cache.maxSize)return!1;let t=this.__compiledTemplatesMap.entries().next().value;if(t){let[s,o]=t;this.__compiledTemplatesMap.delete(s),this.__cacheSize-=o.size}return this.createEntrySpaceForTemplate(r)}getDiagnostics(){let r=this.__config.cache.maxSize;return{bytesUsed:this.__cacheSize,bytesMax:r,readableUsed:`${(this.__cacheSize/1024/1024).toFixed(2)} MB`,readableMax:`${(r/1024/1024).toFixed(2)} MB`,totalEntries:this.__compiledTemplatesMap.size,percentFull:r>0?Math.min(100,Math.round(this.__cacheSize/r*100)):0,avgTemplateSize:this.__compiledTemplatesMap.size>0?Math.round(this.__cacheSize/this.__compiledTemplatesMap.size):0}}};var V=class extends Z{constructor(r={}){super(r),this.__namespaces.Mutor.include=(t,s)=>{let o=v(this.__currentRenderedPath,t);if(this.__includeStack.has(o))throw new d(`Circular include detected:
13
- ${Array.from(this.__includeStack).join(`
14
- `)}
15
- ${o}`);try{return this.__includeStack.add(o),this.renderFile(o,s??this.__currentContext)}finally{this.__includeStack.delete(o)}}}renderFile(r,t){let s=v(r),o,c=this.__currentContext,f=this.__currentRenderedPath;if(this.__currentContext=t,this.__currentRenderedPath=r,this.__config.cache.active&&this.__compiledTemplatesMap.has(s))o=this.__compiledTemplatesMap.get(s).fn;else{let i=(0,de.readFileSync)(s,"utf-8");if(o=this.compile(i),this.__config.cache.active){let p=i.length*2+500;this.__cacheSize+p>this.__config.cache.maxSize?this.createEntrySpaceForTemplate(p)&&(this.__compiledTemplatesMap.set(s,{fn:o,size:p}),this.__cacheSize+=p):(this.__compiledTemplatesMap.set(s,{fn:o,size:p}),this.__cacheSize+=p)}}let m=o(L(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,z,B);return this.__currentContext=c,this.__currentRenderedPath=f,m}async buildDir(r,t,s){let o=v(t),c=v(r);await(0,P.mkdir)(o,{recursive:!0});let f=await(0,P.readdir)(c,{withFileTypes:!0});await Promise.all(f.map(async m=>{let i=(0,I.join)(c,m.name),p=(0,I.join)(o,m.name);if(this.__config.build.exclude.has(m.name))return;if(m.isDirectory())return this.buildDir(i,p,s);let _=(0,I.extname)(i);if(this.__config.build.include.has(_)){let y=this.renderFile(i,s);await(0,P.writeFile)(p,y,"utf-8")}else return await(0,P.copyFile)(i,p)}))}async compileDir(r){let t=v(r),s=await(0,P.readdir)(t,{withFileTypes:!0});await Promise.all(s.map(async o=>{let c=(0,I.join)(t,o.name);if(this.__config.build.exclude.has(o.name))return;if(o.isDirectory())return this.compileDir(c);let f=(0,I.extname)(c);if(this.__config.build.include.has(f))try{let m=await(0,P.readFile)(c,"utf-8");this.registerComponent(c,m)}catch{}}))}};var Ce=V;
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ default: () => server_default
24
+ });
25
+ module.exports = __toCommonJS(server_exports);
26
+
27
+ // src/core/mutor.server.ts
28
+ var import_node_fs = require("fs");
29
+ var import_promises = require("fs/promises");
30
+ var import_node_path2 = require("path");
31
+
32
+ // src/utils/construct-pointer.ts
33
+ function constructPointer(pos, offset) {
34
+ return `${" ".repeat(pos + offset + 1)}^`;
35
+ }
36
+
37
+ // src/core/error.ts
38
+ var MutorError = class _MutorError extends Error {
39
+ constructor(message) {
40
+ super(message);
41
+ this.name = "MutorError";
42
+ Object.setPrototypeOf(this, _MutorError.prototype);
43
+ }
44
+ };
45
+ var MutorCompilerError = class _MutorCompilerError extends MutorError {
46
+ constructor(message, line, lineText, column, file) {
47
+ const gutterWidth = line.toString().length + 2;
48
+ let report = `${message}
49
+
50
+ `;
51
+ report += `at ${file}:${line}:${column + 1}
52
+ `;
53
+ if (line > 1) {
54
+ report += `${(line - 1).toString().padStart(gutterWidth - 2)} | ...
55
+ `;
56
+ }
57
+ report += `${line} | ${lineText}
58
+ `;
59
+ report += constructPointer(column, gutterWidth);
60
+ super(report);
61
+ this.name = "MutorCompilerError";
62
+ Object.setPrototypeOf(this, _MutorCompilerError.prototype);
63
+ }
64
+ };
65
+
66
+ // src/core/constants.ts
67
+ var keywords = /* @__PURE__ */ new Set([
68
+ "for",
69
+ "if",
70
+ "else",
71
+ "true",
72
+ "false",
73
+ "null",
74
+ "undefined",
75
+ "end",
76
+ "in",
77
+ "of"
78
+ ]);
79
+ var operators = /* @__PURE__ */ new Set([
80
+ "::",
81
+ // Namespace access
82
+ "||",
83
+ // Or
84
+ "??",
85
+ // Nullish coalesce
86
+ "&&",
87
+ // And
88
+ "**",
89
+ // Power
90
+ "^",
91
+ // Bitwise XOr
92
+ "|",
93
+ // Bitwise Or
94
+ "&",
95
+ // Bitwise And
96
+ "!",
97
+ // Not
98
+ "-",
99
+ // Minus
100
+ "%",
101
+ // Modulus
102
+ "+",
103
+ // Plus
104
+ "*",
105
+ // Times
106
+ "/",
107
+ // Divide
108
+ ">",
109
+ // Greater than
110
+ "<",
111
+ // Less than
112
+ ">=",
113
+ // Greater or equal
114
+ "<=",
115
+ // Less or equal
116
+ "==",
117
+ // Strict equal
118
+ "!=",
119
+ // Strict not equal
120
+ ">>",
121
+ // Bitwise right shift
122
+ "<<",
123
+ // Bitwise left shift
124
+ ".",
125
+ // Property acess
126
+ "?.",
127
+ // Optional property access
128
+ "(",
129
+ // Open parentheses
130
+ ")",
131
+ // Close parentheses
132
+ "[",
133
+ // Square open parentheses
134
+ "]",
135
+ // Square close parentheses
136
+ ",",
137
+ // Comma
138
+ ":",
139
+ // Column
140
+ "?"
141
+ // Ternary operator
142
+ ]);
143
+ var equalityOperators = /* @__PURE__ */ new Set(["==", "!="]);
144
+ var comparisonOperators = /* @__PURE__ */ new Set([">", "<", ">=", "<="]);
145
+ var additiveOperators = /* @__PURE__ */ new Set(["+", "-"]);
146
+ var multiplicativeOperators = /* @__PURE__ */ new Set(["*", "/", "%"]);
147
+ var propertyAccessOperators = /* @__PURE__ */ new Set([".", "?.", "[", "::"]);
148
+ var unaryOperators = /* @__PURE__ */ new Set(["-", "+", "!"]);
149
+ var ESCAPE_MAP = {
150
+ "&": "&amp;",
151
+ "<": "&lt;",
152
+ ">": "&gt;",
153
+ '"': "&quot;",
154
+ "'": "&#39;"
155
+ };
156
+ var defaultConfig = {
157
+ build: {
158
+ include: /* @__PURE__ */ new Set([".html", ".txt"]),
159
+ exclude: /* @__PURE__ */ new Set(["node_modules", ".git"])
160
+ },
161
+ autoEscape: true,
162
+ allowedProps: /* @__PURE__ */ new Set(),
163
+ forbiddenProps: /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]),
164
+ allowFnCalls: false,
165
+ delimiters: {
166
+ closingTag: "}}",
167
+ openingTag: "{{",
168
+ openingTagEscape: "\\",
169
+ whitespaceTrim: "~",
170
+ commentTag: "#"
171
+ },
172
+ keepOpeningTagEscapeDelimiter: false,
173
+ cache: {
174
+ active: true,
175
+ maxSize: 50 * 1024 * 1024
176
+ // 50MB
177
+ }
178
+ };
179
+ var namespaces = {
180
+ JSON: {
181
+ stringify(value) {
182
+ try {
183
+ return JSON.stringify(value);
184
+ } catch {
185
+ throw new MutorError("JSON.stringify failed: invalid value");
186
+ }
187
+ },
188
+ parse(str) {
189
+ if (typeof str !== "string") {
190
+ throw new MutorError("JSON.parse expects a string");
191
+ }
192
+ try {
193
+ return JSON.parse(str);
194
+ } catch {
195
+ throw new MutorError("JSON.parse failed: invalid JSON string");
196
+ }
197
+ }
198
+ },
199
+ Object: {
200
+ keys(obj) {
201
+ if (!obj || typeof obj !== "object") {
202
+ throw new MutorError("Object.keys expects an object");
203
+ }
204
+ return Object.keys(obj);
205
+ },
206
+ values(obj) {
207
+ if (!obj || typeof obj !== "object") {
208
+ throw new MutorError("Object.values expects an object");
209
+ }
210
+ return Object.values(obj);
211
+ },
212
+ entries(obj) {
213
+ if (!obj || typeof obj !== "object") {
214
+ throw new MutorError("Object.entries expects an object");
215
+ }
216
+ return Object.entries(obj);
217
+ },
218
+ hasOwn(obj, key) {
219
+ if (!obj || typeof obj !== "object") {
220
+ throw new MutorError("Object.hasOwn expects an object");
221
+ }
222
+ return Object.hasOwn(obj, key);
223
+ },
224
+ freeze(obj) {
225
+ if (!obj || typeof obj !== "object") {
226
+ throw new MutorError("Object.freeze expects an object");
227
+ }
228
+ return Object.freeze(obj);
229
+ },
230
+ seal(obj) {
231
+ if (!obj || typeof obj !== "object") {
232
+ throw new MutorError("Object.seal expects an object");
233
+ }
234
+ return Object.seal(obj);
235
+ },
236
+ fromEntries(entries) {
237
+ if (!Array.isArray(entries)) {
238
+ throw new MutorError("Object.fromEntries expects an array");
239
+ }
240
+ return Object.fromEntries(entries);
241
+ }
242
+ },
243
+ Array: {
244
+ isArray(value) {
245
+ return Array.isArray(value);
246
+ },
247
+ from(value) {
248
+ return Array.from(value);
249
+ }
250
+ },
251
+ Number: {
252
+ isFinite(value) {
253
+ return Number.isFinite(value);
254
+ },
255
+ isNaN(value) {
256
+ return Number.isNaN(value);
257
+ },
258
+ parseInt(value, radix = 10) {
259
+ return Number.parseInt(value, radix);
260
+ },
261
+ parseFloat(value) {
262
+ return Number.parseFloat(value);
263
+ }
264
+ },
265
+ String: {
266
+ fromCharCode(...args) {
267
+ return String.fromCharCode(...args);
268
+ }
269
+ },
270
+ Math: {
271
+ abs(x) {
272
+ return Math.abs(x);
273
+ },
274
+ floor(x) {
275
+ return Math.floor(x);
276
+ },
277
+ ceil(x) {
278
+ return Math.ceil(x);
279
+ },
280
+ round(x) {
281
+ return Math.round(x);
282
+ },
283
+ max(...args) {
284
+ return Math.max(...args);
285
+ },
286
+ min(...args) {
287
+ return Math.min(...args);
288
+ },
289
+ random() {
290
+ return Math.random();
291
+ }
292
+ },
293
+ Date: {
294
+ now() {
295
+ return Date.now();
296
+ },
297
+ parse(str) {
298
+ if (typeof str !== "string") {
299
+ throw new MutorError("Date.parse expects a string");
300
+ }
301
+ return Date.parse(str);
302
+ }
303
+ },
304
+ Boolean: {
305
+ valueOf(value) {
306
+ return Boolean(value);
307
+ }
308
+ }
309
+ };
310
+
311
+ // src/utils/escape-fn.ts
312
+ function escapeFn(e) {
313
+ if (typeof e !== "string") return e;
314
+ return /[&<>"']/.test(e) ? e.replace(/[&<>"']/g, (char) => ESCAPE_MAP[char]) : e;
315
+ }
316
+
317
+ // src/utils/to-absolute-path.ts
318
+ var import_node_path = require("path");
319
+ function toAbsolutePath(basePath, ...relativePaths) {
320
+ const absoluteBase = (0, import_node_path.isAbsolute)(basePath) ? basePath : (0, import_node_path.resolve)(process.cwd(), basePath);
321
+ if (relativePaths.length) {
322
+ const baseDir = (0, import_node_path.dirname)(absoluteBase);
323
+ return (0, import_node_path.resolve)(baseDir, ...relativePaths);
324
+ }
325
+ return absoluteBase;
326
+ }
327
+
328
+ // src/utils/validate-computed-prop.ts
329
+ function validateComputedProp(r, allowedProps, forbiddenProps) {
330
+ if (forbiddenProps.has(r) && !allowedProps.has(r)) {
331
+ throw new MutorError(
332
+ `Forbidden property access. Access to this computed property "${r}" is forbidden.`
333
+ );
334
+ }
335
+ return r;
336
+ }
337
+
338
+ // src/utils/validate-context.ts
339
+ var OBJECT = "object";
340
+ var MUTOR_SAFE = /* @__PURE__ */ Symbol("__mutor_safe_context");
341
+ function validateContext(ctx) {
342
+ if (!ctx || typeof ctx !== OBJECT) {
343
+ return ctx;
344
+ }
345
+ if (MUTOR_SAFE in ctx) {
346
+ return ctx;
347
+ }
348
+ const seen = /* @__PURE__ */ new WeakSet();
349
+ function walk(value, path = "") {
350
+ if (!value || typeof value !== OBJECT) return value;
351
+ if (seen.has(value)) return value;
352
+ seen.add(value);
353
+ const proto = Object.getPrototypeOf(value);
354
+ if (proto && proto !== Object.prototype && proto !== Array.prototype) {
355
+ throw new MutorError(`Unsafe prototype detected at ${path || "root"}`);
356
+ }
357
+ if (Array.isArray(value)) {
358
+ for (let i = 0; i < value.length; i++) {
359
+ value[i] = walk(value[i], `${path}[${i}]`);
360
+ }
361
+ return value;
362
+ }
363
+ if (value instanceof Map) {
364
+ for (const [k, v] of value.entries()) {
365
+ if (typeof k === OBJECT) walk(k, `${path}.mapKey`);
366
+ value.set(k, walk(v, `${path}.mapValue`));
367
+ }
368
+ return value;
369
+ }
370
+ if (value instanceof Set) {
371
+ const next = /* @__PURE__ */ new Set();
372
+ for (const v of value.values()) {
373
+ next.add(walk(v, path));
374
+ }
375
+ value.clear();
376
+ for (const v of next) value.add(v);
377
+ return value;
378
+ }
379
+ const descriptors = Object.getOwnPropertyDescriptors(value);
380
+ for (const key of Object.keys(descriptors)) {
381
+ const desc = descriptors[key];
382
+ if (desc.get || desc.set) {
383
+ throw new MutorError(`Getter/setter not allowed: ${path}.${key}`);
384
+ }
385
+ const prop = value[key];
386
+ if (prop && typeof prop === OBJECT) {
387
+ value[key] = walk(prop, `${path}.${key}`);
388
+ }
389
+ }
390
+ return value;
391
+ }
392
+ const safeData = walk(ctx);
393
+ if (safeData && typeof safeData === OBJECT) {
394
+ Object.defineProperty(safeData, MUTOR_SAFE, {
395
+ value: true,
396
+ enumerable: false,
397
+ writable: false,
398
+ configurable: false
399
+ });
400
+ }
401
+ return safeData;
402
+ }
403
+
404
+ // src/utils/escape-raw-text.ts
405
+ function escapeRawText(text) {
406
+ return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
407
+ }
408
+
409
+ // src/utils/get-line-and-column-nums.ts
410
+ function getLineAndColumnNumbers(str, idx) {
411
+ const lines = str.slice(0, idx).split("\n");
412
+ const line = lines.length;
413
+ const lineIndex = str.lastIndexOf("\n", idx - 1) + 1;
414
+ return { line, lineIndex };
415
+ }
416
+
417
+ // src/utils/get-line-snapshot.ts
418
+ function getLineSnapshot(str, lineIdx, idx) {
419
+ const nextNewlineIdx = str.indexOf("\n", lineIdx);
420
+ const line = str.slice(
421
+ lineIdx,
422
+ nextNewlineIdx === -1 ? void 0 : nextNewlineIdx
423
+ );
424
+ return { line, pos: idx - lineIdx };
425
+ }
426
+
427
+ // src/core/build.ts
428
+ function build(ast, context) {
429
+ const { scope, forbiddenProps, allowedProps } = context;
430
+ function prefixWithCtx(ident) {
431
+ return scope.includes(ident) ? ident : `ctx.${ident}`;
432
+ }
433
+ function buildExpr(expr) {
434
+ switch (expr.type) {
435
+ case 17 /* END */:
436
+ return "}";
437
+ case 5 /* NUMBER */:
438
+ return expr.value;
439
+ case 4 /* STRING */:
440
+ return `\`${/\$/.test(expr.value) ? expr.value.replaceAll("$", "\\$") : expr.value}\``;
441
+ case 10 /* BOOLEAN */:
442
+ return expr.true ? "true" : "false";
443
+ case 12 /* NULL */:
444
+ return "null";
445
+ case 11 /* UNDEFINED */:
446
+ return "undefined";
447
+ case 7 /* IDENT */:
448
+ return prefixWithCtx(expr.value);
449
+ case 9 /* GROUP */:
450
+ return `(${buildExpr(expr.expr)})`;
451
+ case 2 /* UNARY */:
452
+ return `${expr.operator}${buildExpr(expr.expr)}`;
453
+ case 0 /* BINARY */:
454
+ return `${buildExpr(expr.left)} ${expr.operator} ${buildExpr(expr.right)}`;
455
+ case 1 /* TERNARY */:
456
+ return `${buildExpr(expr.condition)} ? ${buildExpr(expr.left)} : ${buildExpr(expr.right)}`;
457
+ case 8 /* PROP_ACCESS */:
458
+ return buildPropAccess(expr);
459
+ case 3 /* CALL */:
460
+ return buildCall(expr);
461
+ case 6 /* NAMESPACE */:
462
+ return buildNamespace(expr);
463
+ case 13 /* FOR */:
464
+ return buildForLoop(expr);
465
+ case 16 /* ELSE */:
466
+ return "} else {";
467
+ case 14 /* IF */:
468
+ return buildIfBlock(expr);
469
+ case 15 /* ELSE_IF */:
470
+ return buildElseIfBlock(expr);
471
+ default:
472
+ throw new MutorError(
473
+ `Unsupported expression type: ${expr.type}`
474
+ );
475
+ }
476
+ }
477
+ function buildNamespace(expr) {
478
+ if (expr.left.type !== 7 /* IDENT */) {
479
+ throw {
480
+ message: "Invalid usage of namespace operator.",
481
+ pos: expr.pos
482
+ };
483
+ }
484
+ return `namespaces.${expr.left.value}.${expr.right.value}`;
485
+ }
486
+ function buildPropAccess(expr) {
487
+ const left = buildExpr(expr.left);
488
+ if (expr.bracketNotation) {
489
+ const right = buildExpr(expr.right);
490
+ const optionalChain = expr.optional ? "?." : "";
491
+ return expr.right.type === 4 /* STRING */ || expr.right.type === 5 /* NUMBER */ ? `${left}${optionalChain}[${right}]` : `${left}${optionalChain}[validateComputedProps(${right}, allowedProps, forbiddenProps)]`;
492
+ } else {
493
+ const propName = expr.right.value;
494
+ const optionalChain = expr.optional ? "?." : ".";
495
+ if (forbiddenProps.has(propName) && !allowedProps.has(propName)) {
496
+ throw { message: "Forbidden property access.", pos: expr.right.pos };
497
+ }
498
+ return `${left}${optionalChain}${propName}`;
499
+ }
500
+ }
501
+ function buildCall(expr) {
502
+ const func = buildExpr(expr.expr);
503
+ const optionalChain = expr.optional ? "?." : "";
504
+ const args = expr.args.map((arg) => buildExpr(arg)).join(", ");
505
+ return `${func}${optionalChain}(${args})`;
506
+ }
507
+ function buildForLoop(expr) {
508
+ const { iterable, loopType, variable } = expr;
509
+ return `for(const ${variable} ${loopType === 1 /* IN */ ? "in" : "of"} ${build(iterable, context)}){`;
510
+ }
511
+ function buildIfBlock(expr) {
512
+ const { condition } = expr;
513
+ return `if(${build(condition, context)}){`;
514
+ }
515
+ function buildElseIfBlock(expr) {
516
+ const { condition } = expr;
517
+ return `}else if(${build(condition, context)}){`;
518
+ }
519
+ return buildExpr(ast);
520
+ }
521
+
522
+ // src/utils/get-token-type-words.ts
523
+ function getTokenTypeWords(type) {
524
+ switch (type) {
525
+ case 0 /* IDENT */:
526
+ return "identifier";
527
+ case 1 /* KEYWORD */:
528
+ return "keyword";
529
+ case 2 /* NUMBER */:
530
+ return "number";
531
+ case 4 /* OPERATOR */:
532
+ return "operator";
533
+ case 3 /* STRING */:
534
+ return "string";
535
+ }
536
+ }
537
+
538
+ // src/core/generate-ast.ts
539
+ function generateAst(tokens, config) {
540
+ let cursor = 0, generatingNamespace = false;
541
+ function expectOrThrow(type, value) {
542
+ const token = tokens[cursor];
543
+ const lastToken = tokens[tokens.length - 1];
544
+ if (!token) {
545
+ throw {
546
+ message: `Unexpected end of expression. Expected ${value ? `'${value}'` : `${type === 0 /* IDENT */ ? "an" : "a"} ${getTokenTypeWords(type)}`}.`,
547
+ pos: lastToken.pos + lastToken.value.length - 1
548
+ };
549
+ }
550
+ if (token.type !== type) {
551
+ throw {
552
+ message: `Unexpected token type. Expected ${value ? `'${value}'` : getTokenTypeWords(type)} but got ${getTokenTypeWords(token.type)} instead.`,
553
+ pos: token.pos
554
+ };
555
+ }
556
+ if (value !== void 0 && token.value !== value) {
557
+ throw {
558
+ message: `Unexpected token '${token?.value}'. Expected ${type === 0 /* IDENT */ ? "an" : "a"} ${getTokenTypeWords(type)} instead.`,
559
+ pos: token.pos
560
+ };
561
+ }
562
+ return tokens[cursor++];
563
+ }
564
+ function parseForLoop() {
565
+ const pos = tokens[cursor - 1].pos;
566
+ const variable = expectOrThrow(0 /* IDENT */).value;
567
+ let token;
568
+ try {
569
+ token = expectOrThrow(1 /* KEYWORD */, "in");
570
+ } catch {
571
+ token = expectOrThrow(1 /* KEYWORD */, "of");
572
+ }
573
+ const loopType = token.value === "in" ? 1 /* IN */ : 0 /* OF */;
574
+ const iterable = parseTernaryExpr();
575
+ return { type: 13 /* FOR */, loopType, iterable, variable, pos };
576
+ }
577
+ function parseIfExpression() {
578
+ const condition = parseTernaryExpr();
579
+ return { condition, pos: condition.pos, type: 14 /* IF */ };
580
+ }
581
+ function parseElseExpression() {
582
+ const pos = tokens[cursor - 1].pos;
583
+ try {
584
+ expectOrThrow(1 /* KEYWORD */, "if");
585
+ return { ...parseIfExpression(), type: 15 /* ELSE_IF */, pos };
586
+ } catch {
587
+ return { type: 16 /* ELSE */, pos };
588
+ }
589
+ }
590
+ function extractFnArgs() {
591
+ const args = [];
592
+ const emptyArgs = tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === ")";
593
+ if (emptyArgs) {
594
+ return args;
595
+ }
596
+ args.push(parseTernaryExpr());
597
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "," && tokens[cursor]?.value !== ")") {
598
+ cursor++;
599
+ args.push(parseTernaryExpr());
600
+ }
601
+ return args;
602
+ }
603
+ function parsePrimaryExpr() {
604
+ const token = tokens[cursor++];
605
+ if (token?.type === 2 /* NUMBER */) {
606
+ return { type: 5 /* NUMBER */, value: token.value, pos: token.pos };
607
+ }
608
+ if (token?.type === 3 /* STRING */) {
609
+ return { type: 4 /* STRING */, value: token.value, pos: token.pos };
610
+ }
611
+ if (token?.type === 1 /* KEYWORD */) {
612
+ if (token.value === "for" && cursor === 1) {
613
+ return parseForLoop();
614
+ }
615
+ if (token.value === "true" || token.value === "false") {
616
+ return {
617
+ type: 10 /* BOOLEAN */,
618
+ true: token.value === "true",
619
+ pos: token.pos
620
+ };
621
+ }
622
+ if (token.value === "undefined") {
623
+ return { type: 11 /* UNDEFINED */, pos: token.pos };
624
+ }
625
+ if (token.value === "null") {
626
+ return { type: 12 /* NULL */, pos: token.pos };
627
+ }
628
+ if (token.value === "end" && tokens.length === 1) {
629
+ return { type: 17 /* END */, pos: token.pos };
630
+ }
631
+ if (token.value === "if" && cursor === 1) {
632
+ return parseIfExpression();
633
+ }
634
+ if (token.value === "else" && cursor === 1) {
635
+ return parseElseExpression();
636
+ }
637
+ }
638
+ if (token?.type === 0 /* IDENT */) {
639
+ return { type: 7 /* IDENT */, value: token.value, pos: token.pos };
640
+ }
641
+ if (token?.type === 4 /* OPERATOR */ && token.value === "(") {
642
+ const expr = parseTernaryExpr();
643
+ expectOrThrow(4 /* OPERATOR */, ")");
644
+ return { type: 9 /* GROUP */, expr, pos: token.pos };
645
+ }
646
+ if (token?.type === 4 /* OPERATOR */ && unaryOperators.has(token.value)) {
647
+ const operator = token.value;
648
+ const expr = parseTernaryExpr();
649
+ return { type: 2 /* UNARY */, operator, expr, pos: token.pos };
650
+ }
651
+ if (cursor > tokens.length) {
652
+ throw {
653
+ message: `Unexpected end of expression.`,
654
+ pos: tokens[tokens.length - 1].pos
655
+ };
656
+ }
657
+ throw {
658
+ message: `Unexpected token '${token?.value}'.`,
659
+ pos: token.pos
660
+ };
661
+ }
662
+ function parsePropertyAccess() {
663
+ let left = parsePrimaryExpr();
664
+ while (tokens[cursor]) {
665
+ const token = tokens[cursor];
666
+ if (token?.type === 4 /* OPERATOR */ && token?.value === "(") {
667
+ cursor++;
668
+ if (!generatingNamespace && !config.allowFnCalls) {
669
+ throw {
670
+ message: "Function calls are not allowed.",
671
+ pos: tokens[cursor - 1].pos
672
+ };
673
+ }
674
+ const args = extractFnArgs();
675
+ expectOrThrow(4 /* OPERATOR */, ")");
676
+ left = {
677
+ type: 3 /* CALL */,
678
+ expr: left,
679
+ args,
680
+ pos: tokens[cursor - 1].pos
681
+ };
682
+ } else if (token?.type === 4 /* OPERATOR */ && token?.value === "?." && tokens[cursor + 1]?.type === 4 /* OPERATOR */ && tokens[cursor + 1]?.value === "(") {
683
+ cursor++;
684
+ cursor++;
685
+ if (!generatingNamespace && !config.allowFnCalls) {
686
+ throw {
687
+ message: "Function calls are not allowed.",
688
+ pos: tokens[cursor - 1].pos
689
+ };
690
+ }
691
+ const args = extractFnArgs();
692
+ expectOrThrow(4 /* OPERATOR */, ")");
693
+ left = {
694
+ type: 3 /* CALL */,
695
+ expr: left,
696
+ args,
697
+ optional: true,
698
+ pos: tokens[cursor - 1].pos
699
+ };
700
+ } else if (token?.type === 4 /* OPERATOR */ && propertyAccessOperators.has(token?.value)) {
701
+ const isNamespace = token?.value === "::";
702
+ const isBracketNotation = token?.value === "[";
703
+ const isOptional = token?.value === "?.";
704
+ cursor++;
705
+ if (isNamespace && (tokens[cursor - 2]?.type !== 0 /* IDENT */ || tokens[cursor]?.type !== 0 /* IDENT */)) {
706
+ throw {
707
+ message: `Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${tokens[cursor - 2]?.value}::${tokens[cursor]?.value}' instead.`,
708
+ pos: tokens[cursor]?.pos
709
+ };
710
+ }
711
+ if (isNamespace) {
712
+ generatingNamespace = true;
713
+ const right = parsePrimaryExpr();
714
+ left = {
715
+ type: 6 /* NAMESPACE */,
716
+ left,
717
+ right,
718
+ pos: tokens[cursor - 1].pos
719
+ };
720
+ } else if (isBracketNotation) {
721
+ const right = parseTernaryExpr();
722
+ expectOrThrow(4 /* OPERATOR */, "]");
723
+ left = {
724
+ type: 8 /* PROP_ACCESS */,
725
+ right,
726
+ left,
727
+ bracketNotation: true,
728
+ pos: tokens[cursor - 1].pos
729
+ };
730
+ } else if (isOptional) {
731
+ if (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "[") {
732
+ cursor++;
733
+ const right = parseTernaryExpr();
734
+ expectOrThrow(4 /* OPERATOR */, "]");
735
+ left = {
736
+ type: 8 /* PROP_ACCESS */,
737
+ left,
738
+ right,
739
+ bracketNotation: true,
740
+ optional: true,
741
+ pos: tokens[cursor - 1].pos
742
+ };
743
+ } else {
744
+ const right = parsePrimaryExpr();
745
+ left = {
746
+ type: 8 /* PROP_ACCESS */,
747
+ left,
748
+ right,
749
+ optional: true,
750
+ pos: tokens[cursor - 1].pos
751
+ };
752
+ }
753
+ } else {
754
+ const right = parsePrimaryExpr();
755
+ left = {
756
+ type: 8 /* PROP_ACCESS */,
757
+ left,
758
+ right,
759
+ pos: tokens[cursor - 1].pos
760
+ };
761
+ }
762
+ } else {
763
+ break;
764
+ }
765
+ }
766
+ generatingNamespace = false;
767
+ return left;
768
+ }
769
+ function parseMultiplicativeExpr() {
770
+ let left = parsePropertyAccess();
771
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && multiplicativeOperators.has(tokens[cursor]?.value)) {
772
+ const operator = tokens[cursor++].value;
773
+ const right = parsePropertyAccess();
774
+ left = {
775
+ type: 0 /* BINARY */,
776
+ left,
777
+ right,
778
+ operator,
779
+ pos: tokens[cursor - 1].pos
780
+ };
781
+ }
782
+ return left;
783
+ }
784
+ function parseAdditiveExpr() {
785
+ let left = parseMultiplicativeExpr();
786
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && additiveOperators.has(tokens[cursor]?.value)) {
787
+ const operator = tokens[cursor++].value;
788
+ const right = parseMultiplicativeExpr();
789
+ left = {
790
+ type: 0 /* BINARY */,
791
+ left,
792
+ right,
793
+ operator,
794
+ pos: tokens[cursor - 1].pos
795
+ };
796
+ }
797
+ return left;
798
+ }
799
+ function parseBitwiseExpr() {
800
+ let left = parseAdditiveExpr();
801
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && comparisonOperators.has(tokens[cursor]?.value)) {
802
+ const operator = tokens[cursor++].value;
803
+ const right = parseAdditiveExpr();
804
+ left = {
805
+ type: 0 /* BINARY */,
806
+ left,
807
+ right,
808
+ operator,
809
+ pos: tokens[cursor - 1].pos
810
+ };
811
+ }
812
+ return left;
813
+ }
814
+ function parseComparisonExpr() {
815
+ let left = parseBitwiseExpr();
816
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && comparisonOperators.has(tokens[cursor]?.value)) {
817
+ const operator = tokens[cursor++].value;
818
+ const right = parseBitwiseExpr();
819
+ left = {
820
+ type: 0 /* BINARY */,
821
+ left,
822
+ right,
823
+ operator,
824
+ pos: tokens[cursor - 1].pos
825
+ };
826
+ }
827
+ return left;
828
+ }
829
+ function parseEqualityExpr() {
830
+ let left = parseComparisonExpr();
831
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && equalityOperators.has(tokens[cursor]?.value)) {
832
+ const operator = tokens[cursor++].value;
833
+ const right = parseComparisonExpr();
834
+ left = {
835
+ type: 0 /* BINARY */,
836
+ left,
837
+ right,
838
+ operator,
839
+ pos: tokens[cursor - 1].pos
840
+ };
841
+ }
842
+ return left;
843
+ }
844
+ function parseLogicalOrExpr() {
845
+ let left = parseLogicalAndExpr();
846
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "||") {
847
+ const operator = tokens[cursor++].value;
848
+ const right = parseLogicalAndExpr();
849
+ left = {
850
+ type: 0 /* BINARY */,
851
+ left,
852
+ right,
853
+ operator,
854
+ pos: tokens[cursor - 1].pos
855
+ };
856
+ }
857
+ return left;
858
+ }
859
+ function parseLogicalAndExpr() {
860
+ let left = parseNullishCoalesceExpr();
861
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "&&") {
862
+ const operator = tokens[cursor++].value;
863
+ const right = parseNullishCoalesceExpr();
864
+ left = {
865
+ type: 0 /* BINARY */,
866
+ left,
867
+ right,
868
+ operator,
869
+ pos: tokens[cursor - 1].pos
870
+ };
871
+ }
872
+ return left;
873
+ }
874
+ function parseNullishCoalesceExpr() {
875
+ let left = parseEqualityExpr();
876
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "??") {
877
+ const operator = tokens[cursor++].value;
878
+ const right = parseEqualityExpr();
879
+ left = {
880
+ type: 0 /* BINARY */,
881
+ left,
882
+ right,
883
+ operator,
884
+ pos: tokens[cursor - 1].pos
885
+ };
886
+ }
887
+ return left;
888
+ }
889
+ function parseTernaryExpr() {
890
+ const condition = parseLogicalOrExpr();
891
+ if (tokens[cursor]?.type !== 4 /* OPERATOR */ || tokens[cursor]?.value !== "?") {
892
+ return condition;
893
+ }
894
+ cursor++;
895
+ const left = parseTernaryExpr();
896
+ expectOrThrow(4 /* OPERATOR */, ":");
897
+ const right = parseTernaryExpr();
898
+ return {
899
+ type: 1 /* TERNARY */,
900
+ left,
901
+ right,
902
+ condition,
903
+ pos: tokens[cursor - 1].pos
904
+ };
905
+ }
906
+ const ast = parseTernaryExpr();
907
+ return ast;
908
+ }
909
+
910
+ // src/core/parse.ts
911
+ function parse(templateBlock, { delimiters }) {
912
+ const openingTagWithWhitespaceCtrl = `${delimiters.openingTag}${delimiters.whitespaceTrim}`;
913
+ const closingTagWithWhitespaceCtrl = `${delimiters.whitespaceTrim}${delimiters.closingTag}`;
914
+ const leftTrim = templateBlock.startsWith(openingTagWithWhitespaceCtrl);
915
+ const rightTrim = templateBlock.endsWith(closingTagWithWhitespaceCtrl);
916
+ const isComment = templateBlock.startsWith(
917
+ leftTrim ? openingTagWithWhitespaceCtrl + delimiters.commentTag : delimiters.openingTag + delimiters.commentTag
918
+ );
919
+ if (isComment) {
920
+ return { isComment, leftTrim, rightTrim };
921
+ }
922
+ const inner = templateBlock.slice(
923
+ leftTrim ? openingTagWithWhitespaceCtrl.length : delimiters.openingTag.length,
924
+ templateBlock.length - (rightTrim ? closingTagWithWhitespaceCtrl.length : delimiters.closingTag.length)
925
+ );
926
+ const trimmed = inner.trim();
927
+ const isBlock = trimmed.startsWith("for") || trimmed.startsWith("if") || trimmed.startsWith("else");
928
+ const requiresBlockClose = trimmed.startsWith("for") || trimmed.startsWith("if");
929
+ const isBlockEnd = trimmed === "end";
930
+ const hasContext = trimmed.startsWith("for");
931
+ return {
932
+ leftTrim,
933
+ rightTrim,
934
+ inner,
935
+ isBlock,
936
+ isBlockEnd,
937
+ hasContext,
938
+ requiresBlockClose
939
+ };
940
+ }
941
+
942
+ // src/core/tokenize.ts
943
+ function tokenize(expr) {
944
+ let cursor = 0, char = "";
945
+ const tokens = [];
946
+ function accumulateKeywordOrIdentifier() {
947
+ let buffer = "";
948
+ if (/[a-zA-Z$_]/.test(char)) {
949
+ let j = cursor;
950
+ while (/[a-zA-Z$_0-9]/.test(expr[j]) && j < expr.length) {
951
+ buffer += expr[j];
952
+ j++;
953
+ }
954
+ tokens.push({
955
+ type: keywords.has(buffer) ? 1 /* KEYWORD */ : 0 /* IDENT */,
956
+ value: buffer,
957
+ pos: cursor
958
+ });
959
+ cursor = j;
960
+ char = expr[cursor];
961
+ }
962
+ }
963
+ function accumulateStr() {
964
+ let buffer = "";
965
+ if (char === '"' || char === "'" || char === "`") {
966
+ let j = cursor + 1;
967
+ while (expr[j] !== char && j < expr.length) {
968
+ buffer += expr[j];
969
+ j++;
970
+ }
971
+ if (j > expr.length) {
972
+ throw { pos: cursor, message: `Found string without closing quote.` };
973
+ }
974
+ tokens.push({ type: 3 /* STRING */, value: buffer, pos: cursor });
975
+ cursor = j;
976
+ }
977
+ }
978
+ function accumulateNumber() {
979
+ if (/[0-9]/.test(char)) {
980
+ let j = cursor, buffer = "";
981
+ while (/[0-9.oxe]/.test(expr[j]) && j < expr.length) {
982
+ buffer += expr[j];
983
+ j++;
984
+ }
985
+ const numVal = Number(buffer);
986
+ const isNan = Number.isNaN(numVal);
987
+ if (isNan) {
988
+ throw { pos: cursor, message: "Found invalid number literal." };
989
+ }
990
+ tokens.push({ type: 2 /* NUMBER */, value: `${numVal}`, pos: cursor });
991
+ cursor = j - 1;
992
+ char = expr[cursor];
993
+ }
994
+ }
995
+ function accumulateOperator() {
996
+ const op = `${char}${expr[cursor + 1]}`;
997
+ if (operators.has(op)) {
998
+ tokens.push({ type: 4 /* OPERATOR */, value: op, pos: cursor });
999
+ cursor++;
1000
+ return;
1001
+ }
1002
+ if (operators.has(char)) {
1003
+ tokens.push({ type: 4 /* OPERATOR */, value: char, pos: cursor });
1004
+ return;
1005
+ }
1006
+ }
1007
+ while (cursor < expr.length) {
1008
+ char = expr[cursor];
1009
+ accumulateNumber();
1010
+ accumulateKeywordOrIdentifier();
1011
+ accumulateStr();
1012
+ accumulateOperator();
1013
+ if (!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(char) && !operators.has(char) && !operators.has(expr[cursor - 1] + char)) {
1014
+ throw {
1015
+ message: `Unexpected token '${char}' in expression.`,
1016
+ pos: cursor
1017
+ };
1018
+ }
1019
+ cursor++;
1020
+ }
1021
+ return tokens;
1022
+ }
1023
+
1024
+ // src/core/compile.ts
1025
+ function compile(src, config, meta) {
1026
+ const scope = [];
1027
+ const blockOpeningStack = [];
1028
+ const {
1029
+ delimiters,
1030
+ keepOpeningTagEscapeDelimiter,
1031
+ allowFnCalls,
1032
+ allowedProps,
1033
+ forbiddenProps,
1034
+ autoEscape
1035
+ } = config;
1036
+ let trimNext = false, cursor = 0, body = `let acc="";`;
1037
+ while (cursor < src.length) {
1038
+ let isEscaped2 = function() {
1039
+ let j = templateOpenTagIdx, count = 0;
1040
+ while (j >= delimiters.openingTagEscape.length && src.slice(j - delimiters.openingTagEscape.length, j) === delimiters.openingTagEscape) {
1041
+ count++;
1042
+ j -= delimiters.openingTagEscape.length;
1043
+ }
1044
+ return count % 2 === 1;
1045
+ };
1046
+ var isEscaped = isEscaped2;
1047
+ const templateOpenTagIdx = src.indexOf(delimiters.openingTag, cursor);
1048
+ if (templateOpenTagIdx === -1) {
1049
+ let lastChunk = src.slice(cursor);
1050
+ if (trimNext) lastChunk = lastChunk.trimStart();
1051
+ if (lastChunk) body += `acc+=\`${escapeRawText(lastChunk)}\`;`;
1052
+ break;
1053
+ }
1054
+ if (isEscaped2()) {
1055
+ let escapedChunk = src.slice(
1056
+ cursor,
1057
+ keepOpeningTagEscapeDelimiter ? templateOpenTagIdx + delimiters.openingTagEscape.length + 1 : templateOpenTagIdx - delimiters.openingTag.length + 1
1058
+ );
1059
+ if (trimNext) {
1060
+ escapedChunk = escapedChunk.trimStart();
1061
+ trimNext = false;
1062
+ }
1063
+ body += `acc+=\`${escapeRawText(escapedChunk)}\`;`;
1064
+ if (!keepOpeningTagEscapeDelimiter)
1065
+ body += `acc+=\`${delimiters.openingTag}\`;`;
1066
+ cursor = templateOpenTagIdx + delimiters.openingTag.length;
1067
+ continue;
1068
+ }
1069
+ const templateEndTagIdx = src.indexOf(
1070
+ delimiters.closingTag,
1071
+ templateOpenTagIdx
1072
+ );
1073
+ if (templateEndTagIdx === -1) {
1074
+ const { line, lineIndex } = getLineAndColumnNumbers(
1075
+ src,
1076
+ templateOpenTagIdx
1077
+ );
1078
+ const { line: lineText, pos } = getLineSnapshot(
1079
+ src,
1080
+ lineIndex,
1081
+ templateOpenTagIdx
1082
+ );
1083
+ throw new MutorCompilerError(
1084
+ "No closing tag found.",
1085
+ line,
1086
+ lineText,
1087
+ pos,
1088
+ meta.path
1089
+ );
1090
+ }
1091
+ const template = src.slice(
1092
+ templateOpenTagIdx,
1093
+ templateEndTagIdx + delimiters.closingTag.length
1094
+ );
1095
+ const {
1096
+ inner,
1097
+ leftTrim,
1098
+ rightTrim,
1099
+ isBlock,
1100
+ isBlockEnd,
1101
+ hasContext,
1102
+ requiresBlockClose,
1103
+ isComment
1104
+ } = parse(template, { delimiters });
1105
+ let rawText = src.slice(cursor, templateOpenTagIdx);
1106
+ if (rawText) {
1107
+ if (trimNext) {
1108
+ rawText = rawText.trimStart();
1109
+ }
1110
+ if (leftTrim) {
1111
+ rawText = rawText.trimEnd();
1112
+ }
1113
+ if (rawText) {
1114
+ body += `acc+=\`${escapeRawText(rawText)}\`;`;
1115
+ }
1116
+ }
1117
+ trimNext = false;
1118
+ cursor = templateEndTagIdx + delimiters.closingTag.length;
1119
+ try {
1120
+ if (!isComment) {
1121
+ const tokens = tokenize(inner);
1122
+ const ast = generateAst(tokens, { allowFnCalls });
1123
+ if (isBlock && requiresBlockClose && hasContext) {
1124
+ scope.push(ast.variable);
1125
+ blockOpeningStack.push({
1126
+ type: 0 /* LOOP */,
1127
+ pos: templateOpenTagIdx
1128
+ });
1129
+ } else if (isBlock && requiresBlockClose && !hasContext) {
1130
+ blockOpeningStack.push({
1131
+ type: 1 /* NON_LOOP */,
1132
+ pos: templateOpenTagIdx
1133
+ });
1134
+ }
1135
+ if (isBlockEnd) {
1136
+ const lastBlockOpened = blockOpeningStack.pop();
1137
+ if (lastBlockOpened?.type === 0 /* LOOP */) scope.pop();
1138
+ if (lastBlockOpened === void 0)
1139
+ throw {
1140
+ message: "Unexpected end of block",
1141
+ pos: templateOpenTagIdx
1142
+ };
1143
+ }
1144
+ const js = build(ast, { allowedProps, forbiddenProps, scope });
1145
+ if (isBlock || isBlockEnd) {
1146
+ body += js;
1147
+ } else {
1148
+ body += autoEscape && !js.startsWith("namespaces.Mutor.include") ? `acc+=escapeFn(${js});` : `acc+=${js};`;
1149
+ }
1150
+ }
1151
+ if (rightTrim) trimNext = true;
1152
+ } catch (e) {
1153
+ const { message, pos: relPos } = e;
1154
+ const { line, lineIndex } = getLineAndColumnNumbers(
1155
+ src,
1156
+ templateOpenTagIdx
1157
+ );
1158
+ const { line: lineText, pos } = getLineSnapshot(
1159
+ src,
1160
+ lineIndex,
1161
+ templateOpenTagIdx
1162
+ );
1163
+ throw new MutorCompilerError(
1164
+ message,
1165
+ line,
1166
+ lineText,
1167
+ pos + relPos + (leftTrim ? delimiters.openingTag.length + delimiters.whitespaceTrim.length : delimiters.openingTag.length),
1168
+ meta.path
1169
+ );
1170
+ }
1171
+ }
1172
+ if (blockOpeningStack.length) {
1173
+ const lastPos = blockOpeningStack.pop()?.pos;
1174
+ const { line, lineIndex } = getLineAndColumnNumbers(src, lastPos);
1175
+ const { line: lineText, pos } = getLineSnapshot(src, lineIndex, lastPos);
1176
+ throw new MutorCompilerError(
1177
+ "Unclosed block detected.",
1178
+ line,
1179
+ lineText,
1180
+ pos + delimiters.openingTag.length,
1181
+ meta.path
1182
+ );
1183
+ }
1184
+ body += `return acc;`;
1185
+ return new Function(
1186
+ "ctx",
1187
+ "namespaces",
1188
+ "allowedProps",
1189
+ "forbiddenProps",
1190
+ "escapeFn",
1191
+ "validateComputedProps",
1192
+ body
1193
+ );
1194
+ }
1195
+
1196
+ // src/core/mutor.ts
1197
+ var Mutor = class {
1198
+ constructor(config = {}) {
1199
+ this.__currentRenderedPath = "";
1200
+ this.__includeStack = /* @__PURE__ */ new Set();
1201
+ this.__cacheSize = 0;
1202
+ this.__config = { ...defaultConfig };
1203
+ this.__compiledTemplatesMap = /* @__PURE__ */ new Map();
1204
+ this.__currentContext = null;
1205
+ this.__namespaces = {
1206
+ ...namespaces,
1207
+ Mutor: {
1208
+ include: (path, ctx) => {
1209
+ if (this.__includeStack.has(path)) {
1210
+ throw new MutorError(
1211
+ `Circular include detected:
1212
+ ${Array.from(this.__includeStack).join("\n")}
1213
+ ${path}`
1214
+ );
1215
+ }
1216
+ try {
1217
+ this.__includeStack.add(path);
1218
+ return this.renderComponent(path, ctx ?? this.__currentContext);
1219
+ } finally {
1220
+ this.__includeStack.delete(path);
1221
+ }
1222
+ }
1223
+ }
1224
+ };
1225
+ this.addConfig(config);
1226
+ Object.defineProperty(this.__namespaces.Mutor, "$$context", {
1227
+ get: () => {
1228
+ return this.__currentContext;
1229
+ }
1230
+ });
1231
+ }
1232
+ addConfig(conf) {
1233
+ const {
1234
+ autoEscape,
1235
+ delimiters: overrideDelimeters,
1236
+ allowedProps,
1237
+ forbiddenProps,
1238
+ keepOpeningTagEscapeDelimiter,
1239
+ allowFnCalls,
1240
+ cache,
1241
+ build: build2
1242
+ } = conf;
1243
+ this.__config = {
1244
+ build: {
1245
+ include: /* @__PURE__ */ new Set([...build2?.include || defaultConfig.build.include]),
1246
+ exclude: /* @__PURE__ */ new Set([
1247
+ ...defaultConfig.build.exclude,
1248
+ ...build2?.exclude || []
1249
+ ])
1250
+ },
1251
+ autoEscape: autoEscape === true ? true : autoEscape !== false,
1252
+ allowedProps: allowedProps || defaultConfig.allowedProps,
1253
+ allowFnCalls: !!allowFnCalls,
1254
+ cache: { ...defaultConfig.cache, ...cache || {} },
1255
+ forbiddenProps: /* @__PURE__ */ new Set([
1256
+ ...defaultConfig.forbiddenProps,
1257
+ ...forbiddenProps || []
1258
+ ]),
1259
+ keepOpeningTagEscapeDelimiter: keepOpeningTagEscapeDelimiter === true ? true : keepOpeningTagEscapeDelimiter !== false,
1260
+ delimiters: {
1261
+ ...defaultConfig.delimiters,
1262
+ ...overrideDelimeters || {}
1263
+ }
1264
+ };
1265
+ return this.__config;
1266
+ }
1267
+ restoreDefaultConfig() {
1268
+ this.__config = { ...defaultConfig };
1269
+ }
1270
+ compile(template) {
1271
+ return compile(template, this.__config, {
1272
+ path: this.__currentRenderedPath || "anonymous"
1273
+ });
1274
+ }
1275
+ render(template, context) {
1276
+ const prevContext = this.__currentContext;
1277
+ if (prevContext !== context) {
1278
+ this.__currentContext = context;
1279
+ }
1280
+ const result = this.compile(template)(
1281
+ validateContext(context),
1282
+ this.__namespaces,
1283
+ this.__config.allowedProps,
1284
+ this.__config.forbiddenProps,
1285
+ escapeFn,
1286
+ validateComputedProp
1287
+ );
1288
+ this.__currentContext = prevContext;
1289
+ return result;
1290
+ }
1291
+ renderComponent(identifier, context) {
1292
+ if (!this.__compiledTemplatesMap.has(identifier)) {
1293
+ throw new MutorError(
1294
+ `No template exists with the identifier '${identifier}'`
1295
+ );
1296
+ }
1297
+ const prevRenderComponentIdentifier = this.__currentRenderedPath;
1298
+ const prevContext = this.__currentContext;
1299
+ const compiled = this.__compiledTemplatesMap.get(identifier);
1300
+ this.__currentContext = context;
1301
+ this.__currentRenderedPath = identifier;
1302
+ const result = compiled.fn(
1303
+ validateContext(context),
1304
+ this.__namespaces,
1305
+ this.__config.allowedProps,
1306
+ this.__config.forbiddenProps,
1307
+ escapeFn,
1308
+ validateComputedProp
1309
+ );
1310
+ this.__currentContext = prevContext;
1311
+ this.__currentRenderedPath = prevRenderComponentIdentifier;
1312
+ return result;
1313
+ }
1314
+ registerComponent(identifier, template) {
1315
+ const templateSize = template.length * 2 + 500;
1316
+ if (this.__cacheSize + templateSize > this.__config.cache.maxSize) {
1317
+ if (!this.createEntrySpaceForTemplate(templateSize)) {
1318
+ throw new MutorError(
1319
+ `The template for the component '${identifier}' is too large. Consider increasing 'cache.maxSize' in the config`
1320
+ );
1321
+ }
1322
+ }
1323
+ this.__cacheSize += template.length * 2 + 500;
1324
+ this.__compiledTemplatesMap.set(identifier, {
1325
+ fn: this.compile(template),
1326
+ size: templateSize
1327
+ });
1328
+ }
1329
+ reset() {
1330
+ this.__config = { ...defaultConfig };
1331
+ this.__compiledTemplatesMap.clear();
1332
+ this.__currentContext = null;
1333
+ this.__cacheSize = 0;
1334
+ }
1335
+ createEntrySpaceForTemplate(targetSize) {
1336
+ if (this.__cacheSize + targetSize < this.__config.cache.maxSize) {
1337
+ return true;
1338
+ }
1339
+ if (targetSize > this.__config.cache.maxSize) {
1340
+ return false;
1341
+ }
1342
+ const firstEntry = this.__compiledTemplatesMap.entries().next().value;
1343
+ if (firstEntry) {
1344
+ const [oldestKey, oldestData] = firstEntry;
1345
+ this.__compiledTemplatesMap.delete(oldestKey);
1346
+ this.__cacheSize -= oldestData.size;
1347
+ }
1348
+ return this.createEntrySpaceForTemplate(targetSize);
1349
+ }
1350
+ getDiagnostics() {
1351
+ const maxSize = this.__config.cache.maxSize;
1352
+ return {
1353
+ bytesUsed: this.__cacheSize,
1354
+ bytesMax: maxSize,
1355
+ readableUsed: `${(this.__cacheSize / 1024 / 1024).toFixed(2)} MB`,
1356
+ readableMax: `${(maxSize / 1024 / 1024).toFixed(2)} MB`,
1357
+ totalEntries: this.__compiledTemplatesMap.size,
1358
+ percentFull: maxSize > 0 ? Math.min(100, Math.round(this.__cacheSize / maxSize * 100)) : 0,
1359
+ avgTemplateSize: this.__compiledTemplatesMap.size > 0 ? Math.round(this.__cacheSize / this.__compiledTemplatesMap.size) : 0
1360
+ };
1361
+ }
1362
+ };
1363
+
1364
+ // src/core/mutor.server.ts
1365
+ var Mutor2 = class extends Mutor {
1366
+ constructor(config = {}) {
1367
+ super(config);
1368
+ this.__namespaces.Mutor.include = (path, context) => {
1369
+ const resolvedPath = toAbsolutePath(this.__currentRenderedPath, path);
1370
+ if (this.__includeStack.has(resolvedPath)) {
1371
+ throw new MutorError(
1372
+ `Circular include detected:
1373
+ ${Array.from(this.__includeStack).join("\n")}
1374
+ ${resolvedPath}`
1375
+ );
1376
+ }
1377
+ try {
1378
+ this.__includeStack.add(resolvedPath);
1379
+ return this.renderFile(resolvedPath, context ?? this.__currentContext);
1380
+ } finally {
1381
+ this.__includeStack.delete(resolvedPath);
1382
+ }
1383
+ };
1384
+ }
1385
+ renderFile(path, context) {
1386
+ const absolutePath = toAbsolutePath(path);
1387
+ let compiled;
1388
+ const prevContext = this.__currentContext;
1389
+ const prevRenderComponentIdentifier = this.__currentRenderedPath;
1390
+ this.__currentContext = context;
1391
+ this.__currentRenderedPath = path;
1392
+ if (this.__config.cache.active && this.__compiledTemplatesMap.has(absolutePath)) {
1393
+ compiled = this.__compiledTemplatesMap.get(absolutePath).fn;
1394
+ } else {
1395
+ const template = (0, import_node_fs.readFileSync)(absolutePath, "utf-8");
1396
+ compiled = this.compile(template);
1397
+ if (this.__config.cache.active) {
1398
+ const templateSize = template.length * 2 + 500;
1399
+ if (this.__cacheSize + templateSize > this.__config.cache.maxSize) {
1400
+ if (this.createEntrySpaceForTemplate(templateSize)) {
1401
+ this.__compiledTemplatesMap.set(absolutePath, {
1402
+ fn: compiled,
1403
+ size: templateSize
1404
+ });
1405
+ this.__cacheSize += templateSize;
1406
+ }
1407
+ } else {
1408
+ this.__compiledTemplatesMap.set(absolutePath, {
1409
+ fn: compiled,
1410
+ size: templateSize
1411
+ });
1412
+ this.__cacheSize += templateSize;
1413
+ }
1414
+ }
1415
+ }
1416
+ const result = compiled(
1417
+ validateContext(context),
1418
+ this.__namespaces,
1419
+ this.__config.allowedProps,
1420
+ this.__config.forbiddenProps,
1421
+ escapeFn,
1422
+ validateComputedProp
1423
+ );
1424
+ this.__currentContext = prevContext;
1425
+ this.__currentRenderedPath = prevRenderComponentIdentifier;
1426
+ return result;
1427
+ }
1428
+ async buildDir(src, destination, context) {
1429
+ const absoluteDestinationPath = toAbsolutePath(destination);
1430
+ const absoluteSrcPath = toAbsolutePath(src);
1431
+ await (0, import_promises.mkdir)(absoluteDestinationPath, { recursive: true });
1432
+ const entries = await (0, import_promises.readdir)(absoluteSrcPath, { withFileTypes: true });
1433
+ await Promise.all(
1434
+ entries.map(async (entry) => {
1435
+ const srcPath = (0, import_node_path2.join)(absoluteSrcPath, entry.name);
1436
+ const destinationPath = (0, import_node_path2.join)(absoluteDestinationPath, entry.name);
1437
+ if (this.__config.build.exclude.has(entry.name)) {
1438
+ return;
1439
+ }
1440
+ if (entry.isDirectory()) {
1441
+ return this.buildDir(srcPath, destinationPath, context);
1442
+ }
1443
+ const extension = (0, import_node_path2.extname)(srcPath);
1444
+ if (this.__config.build.include.has(extension)) {
1445
+ const rendered = this.renderFile(srcPath, context);
1446
+ await (0, import_promises.writeFile)(destinationPath, rendered, "utf-8");
1447
+ } else {
1448
+ return await (0, import_promises.copyFile)(srcPath, destinationPath);
1449
+ }
1450
+ })
1451
+ );
1452
+ }
1453
+ async compileDir(src) {
1454
+ const absolutePath = toAbsolutePath(src);
1455
+ const entries = await (0, import_promises.readdir)(absolutePath, { withFileTypes: true });
1456
+ await Promise.all(
1457
+ entries.map(async (entry) => {
1458
+ const absoluteSrcPath = (0, import_node_path2.join)(absolutePath, entry.name);
1459
+ if (this.__config.build.exclude.has(entry.name)) {
1460
+ return;
1461
+ }
1462
+ if (entry.isDirectory()) {
1463
+ return this.compileDir(absoluteSrcPath);
1464
+ }
1465
+ const extension = (0, import_node_path2.extname)(absoluteSrcPath);
1466
+ if (this.__config.build.include.has(extension)) {
1467
+ try {
1468
+ const template = await (0, import_promises.readFile)(absoluteSrcPath, "utf-8");
1469
+ this.registerComponent(absoluteSrcPath, template);
1470
+ } catch {
1471
+ }
1472
+ }
1473
+ })
1474
+ );
1475
+ }
1476
+ };
1477
+
1478
+ // src/server.ts
1479
+ var server_default = Mutor2;
16
1480
  //# sourceMappingURL=server.cjs.map