mutorjs 1.5.7 → 1.5.9
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 +21 -21
- package/dist/cli.cjs +17 -17
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +10 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -9
- package/dist/index.d.ts +48 -9
- package/dist/index.js +11 -11
- package/dist/index.js.map +1 -1
- package/dist/mutor.global.js +10 -10
- package/dist/mutor.global.js.map +1 -1
- package/dist/server.cjs +11 -11
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +49 -13
- package/dist/server.d.ts +49 -13
- package/dist/server.js +11 -11
- package/dist/server.js.map +1 -1
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Onah Victor
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Onah Victor
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/cli.cjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var ae=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var ct=Object.prototype.hasOwnProperty;var ut=(e,t)=>{for(var r in t)ae(e,r,{get:t[r],enumerable:!0})},pt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of at(t))!ct.call(e,o)&&o!==r&&ae(e,o,{get:()=>t[o],enumerable:!(n=it(t,o))||n.enumerable});return e};var lt=e=>pt(ae({},"__esModule",{value:!0}),e);var Yt={};ut(Yt,{handleBuildCommand:()=>Xe,handleCompileCommand:()=>He,handleRenderCommand:()=>Ze,parseArgs:()=>Ve,safeParseJsonFile:()=>oe,safeReadFile:()=>ne,safeWriteFile:()=>fe});module.exports=lt(Yt);var R=require("fs"),B=require("process");var be="1.5.9";var Je=require("fs"),O=require("fs/promises"),A=require("path");function F(e,t=""){return{context:e,renderedPath:t,includeStack:new Set([t&&t])}}function ce(e,t){return`${" ".repeat(e+t)}^`}var d=class e extends Error{constructor(r){super(r);this.name="MutorError";Object.setPrototypeOf(this,e.prototype)}},k=class e extends d{constructor(r,n,o,s,i){let l=n.toString().length+2,u=`${r}
|
|
3
3
|
|
|
4
|
-
`;
|
|
5
|
-
`,n>1&&(
|
|
6
|
-
`),
|
|
7
|
-
`,
|
|
8
|
-
Access to this computed property '${e}' is forbidden.`);return e}function
|
|
4
|
+
`;u+=`at ${i}:${n}:${s+1}
|
|
5
|
+
`,n>1&&(u+=`${(n-1).toString().padStart(l-2)} | ...
|
|
6
|
+
`),u+=`${n} | ${o}
|
|
7
|
+
`,u+=ce(s,l+1);super(u);this.name="MutorCompilerError";Object.setPrototypeOf(this,e.prototype)}};var Se=new Set(["for","if","else","true","false","null","undefined","end","in","of","switch","case","default","break","continue"]),K=new Set(["::","||","??","&&","**","^","|","&","!","-","%","+","*","/",">","<",">=","<=","==","!=",">>","<<",".","?.","(",")","[","]",",",":","?"]);var xe=new Set(["==","!="]),Pe=new Set([">","<",">=","<="]),Oe=new Set([">>","<<","^","|","&"]),Re=new Set(["+","-"]),ke=new Set(["*","/","%"]),Ae=new Set([".","?.","[","::"]),Ce=new Set(["-","+","!"]),Ne=new Set(["|"]),Ie=new Set(["^"]),Te=new Set(["&"]),$e=new Set(["**"]),ve={"&":"&","<":"<",">":">",'"':""","'":"'"},b={build:{include:new Set([".html",".txt"]),exclude:new Set(["node_modules",".git"])},autoEscape:!0,allowedProps:new Set,forbiddenProps:new Set(["__proto__","constructor","prototype","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","caller","callee","arguments"]),allowFnCalls:!1,delimiters:{closingTag:"}}",openingTag:"{{",openingTagEscape:"\\",whitespaceTrim:"~",commentTag:"#"},keepOpeningTagEscapeDelimiter:!1,onIncludeFail:"throw",cache:{active:!0,maxSize:50*1024*1024}},Fe={JSON:{stringify(e,t){return JSON.stringify(e,null,t)},parse(e){return JSON.parse(e)}},Object:{keys(e){return Object.keys(e)},values(e){return Object.values(e)},entries(e){return Object.entries(e)},hasOwn(e,t){return Object.hasOwn(e,t)},fromEntries(e){return Object.fromEntries(e)},pick(e,t){if(!e||typeof e!="object")throw new d("Object::pick expects an object");if(!Array.isArray(t))throw new d("Object::pick expects an array of keys");let r={};for(let n of t)Object.hasOwn(e,n)&&(r[n]=e[n]);return r},omit(e,t){if(!e||typeof e!="object")throw new d("Object::omit expects an object");if(!Array.isArray(t))throw new d("Object::omit expects an array of keys");let r={...e};for(let n of t)delete r[n];return r}},Array:{isArray(e){return Array.isArray(e)},from(e){return Array.from(e)},of(...e){return Array.of(...e)},unique(e){if(!Array.isArray(e))throw new d("Array::unique expects an array");return[...new Set(e)]},compact(e){if(!Array.isArray(e))throw new d("Array::compact expects an array");return e.filter(Boolean)},chunk(e,t){if(!Array.isArray(e))throw new d("Array::chunk expects an array");if(!Number.isInteger(t)||t<=0)throw new d("Array::chunk expects a positive integer size");let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r},range(e,t,r=1){if(!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r))throw new d("Array::range expects finite numbers");if(r===0)throw new d("Array::range step cannot be 0");if(e<=t&&r<0||e>t&&r>0)throw new d("Invalid step direction: step must match range direction");let n=[];for(let o=e;e<=t?o<=t:o>=t;o+=r)n.push(o);return n}},Number:{isFinite(e){return Number.isFinite(e)},isNaN(e){return Number.isNaN(e)},isInteger(e){return Number.isInteger(e)},parseInt(e,t=10){return Number.parseInt(e,t)},parseFloat(e){return Number.parseFloat(e)},clamp(e,t,r){return Math.min(Math.max(e,t),r)},toFixed(e,t=0){return e.toFixed(t)},random(e=0,t=1){return Math.random()*(t-e)+e}},String:{fromCharCode(...e){return String.fromCharCode(...e)},capitalize(e){if(typeof e!="string")throw new d("String::capitalize expects a string");return e.length?e[0].toUpperCase()+e.slice(1):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)},trunc(e){return Math.trunc(e)},sign(e){return Math.sign(e)},sqrt(e){return Math.sqrt(e)},pow(e,t){return e**t},max(...e){return Math.max(...e)},min(...e){return Math.min(...e)},random(){return Math.random()},PI:Math.PI},Date:{now(){return Date.now()},parse(e){return Date.parse(e)},new(e){return e===void 0?new Date:new Date(e)},iso(e){return new Date(e??Date.now()).toISOString()},timestamp(e){return new Date(e??Date.now()).getTime()}},Boolean:{valueOf(e){return!!e}},URL:{encode(e){return encodeURIComponent(e)},decode(e){return decodeURIComponent(e)}}},Me=(async()=>{}).constructor;function z(e){return typeof e!="string"?e:/[&<>"']/.test(e)?e.replace(/[&<>"']/g,t=>ve[t]):e}var L=require("path");function h(e,...t){let r=(0,L.isAbsolute)(e)?e:(0,L.resolve)(process.cwd(),e);if(t.length){let n=(0,L.dirname)(r);return(0,L.resolve)(n,...t)}return r}function G(e,t,r){if(typeof e!="string"&&typeof e!="number")throw new d("Computed property keys must be strings or numbers.");if(r.has(e)&&!t.has(e))throw new d(`Forbidden property access.
|
|
8
|
+
Access to this computed property '${e}' is forbidden.`);return e}function W(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$/g,"\\$")}function Y(e,t){let n=e.slice(0,t).split(`
|
|
9
9
|
`).length,o=e.lastIndexOf(`
|
|
10
|
-
`,t-1)+1;return[n,o]}function
|
|
11
|
-
`,t);return e.slice(t,r===-1?void 0:r).replaceAll(" "," ")}function
|
|
12
|
-
Expected an operator or the end of the expression.`};return n}function
|
|
13
|
-
${t.message}`)),this.__config.onIncludeError?.(s,t)??""}
|
|
10
|
+
`,t-1)+1;return[n,o]}function q(e,t){let r=e.indexOf(`
|
|
11
|
+
`,t);return e.slice(t,r===-1?void 0:r).replaceAll(" "," ")}var De=/^`|`$/gm;function mt(e,t){if(e.forbiddenProps.has(t.value)&&!e.allowedProps.has(t.value))throw{message:`Property "${t.value}" is forbidden.`,pos:t.pos};return e.scope.includes(t.value)?t.value:`ctx.${t.value}`}function ht(e,t){let r=t.left.value,n=t.right.value;if(e.forbiddenProps.has(r)&&!e.allowedProps.has(r)||e.forbiddenProps.has(n)&&!e.allowedProps.has(n))throw{message:"Forbidden namespace access.",pos:t.pos};return`namespaces.${r}.${n}`}function gt(e,t){let r=S(e,t.left),n=t.optional?"?.":"";if(t.bracketNotation){let s=S(e,t.right);if(t.right.type===4&&e.forbiddenProps.has(s.replaceAll(De,""))&&!e.allowedProps.has(s.replaceAll(De,"")))throw{message:"Forbidden property access.",pos:t.right.pos};return t.right.type===4||t.right.type===5?`${r}${n}[${s}]`:`${r}${n}[validateComputedProps(${s}, allowedProps, forbiddenProps)]`}let o=t.right.value;if(e.forbiddenProps.has(o)&&!e.allowedProps.has(o))throw{message:"Forbidden property access.",pos:t.right.pos};return`${r}${n||"."}${o}`}function Et(e,t){let r=S(e,t.expr),n=t.optional?"?.":"",o=t.args.map(s=>S(e,s)).join(", ");return`${r}${n}(${o})`}function wt(e,t){let{iterable:r,loopType:n,variable:o,secondaryVariable:s}=t,i=n===1?"in":"of",l=M(r,e.context);return i==="of"?`for(let $__i=0,$__iterable=${l};$__i<$__iterable.length;$__i++){const ${o}=$__iterable[$__i];${s?`const ${s}=$__i;`:""}`:s?`for(const [${o}, ${s}] of Object.entries(${l})){`:`for(const ${o} in ${l}){`}function yt(e,t){let{condition:r}=t;return`if(${M(r,e.context)}){`}function _t(e,t){let{condition:r}=t;return`}else if(${M(r,e.context)}){`}function bt(e,t){return`switch(${M(t.condition,e.context)}){`}function St(e,t){return`case ${M(t.condition,e.context)}:`}function S(e,t){let{type:r}=t;if(r===5)return t.value;if(r===12)return"null";if(r===11)return"undefined";if(r===10)return t.true?"true":"false";switch(r){case 22:return"}";case 4:return`\`${/[$`\\]/.test(t.value)?W(t.value):t.value}\``;case 7:return mt(e,t);case 9:return`(${S(e,t.expr)})`;case 2:{let{operator:n,expr:o}=t;return`${n}${S(e,o)}`}case 0:{let{left:n,operator:o,right:s}=t;return`${S(e,n)} ${o} ${S(e,s)}`}case 1:{let{condition:n,left:o,right:s}=t;return`${S(e,n)} ? ${S(e,o)} : ${S(e,s)}`}case 8:return gt(e,t);case 3:return Et(e,t);case 6:return ht(e,t);case 13:return wt(e,t);case 16:return"} else {";case 14:return yt(e,t);case 15:return _t(e,t);case 17:return bt(e,t);case 18:return St(e,t);case 19:return"default:";case 20:return"break;";case 21:return"continue;";default:throw new d(`Unsupported expression type '${r}'`)}}function M(e,t){let r={scope:t.scope,forbiddenProps:t.forbiddenProps,allowedProps:t.allowedProps,context:t},n=S(r,e);return n.includes("namespaces.Mutor.await")?n.replaceAll("namespaces.Mutor.await","await namespaces.Mutor.await"):n}function J(e){switch(e){case 0:return"identifier";case 1:return"keyword";case 2:return"number";case 4:return"operator";case 3:return"string"}}function P(e,t,r){let n=e.tokens[e.cursor],o=e.tokens[e.tokens.length-1];if(!n)throw{message:`Unexpected end of expression. Expected ${r?`'${r}'`:`${t===0?"an":"a"} ${J(t)}`}.`,pos:o.pos+o.value.length-1};if(n.type!==t)throw{message:`Unexpected token type. Expected ${r?`'${r}'`:J(t)} but got ${J(n.type)} instead.`,pos:n.pos};if(r!==void 0&&n.value!==r)throw{message:`Unexpected token '${n.value}'. Expected ${t===0?"an":"a"} ${J(t)} instead.`,pos:n.pos};return e.tokens[e.cursor++]}function xt(e){let t=e.tokens[e.cursor-1].pos,r=P(e,0).value,n,o;e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value===","&&(e.cursor++,n=P(e,0).value);try{o=P(e,1,"in")}catch{o=P(e,1,"of")}let s=o.value==="in"?1:0,i=x(e);return{type:13,loopType:s,iterable:i,variable:r,secondaryVariable:n,pos:t}}function Ye(e){let t=x(e);return{condition:t,pos:t.pos,type:14}}function Pt(e){let t=x(e);return{condition:t,pos:t.pos,type:17}}function Ot(e){let t=e.tokens[e.cursor-1].pos;try{return P(e,1,"if"),{...Ye(e),type:15,pos:t}}catch{return{type:16,pos:t}}}function Le(e){let t=[];if(e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value===")")return t;for(t.push(x(e));e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value===",";)e.cursor++,t.push(x(e));return t}function We(e){let t=e.tokens[e.cursor++];if(!t)throw{message:"Unexpected end of expression.",pos:e.tokens[e.tokens.length-1].pos};if(t.type===2)return{type:5,value:t.value,pos:t.pos};if(t.type===3)return{type:4,value:t.value,pos:t.pos};if(t.type===1){if(t.value==="for"&&e.cursor===1)return xt(e);if(t.value==="true")return{type:10,true:!0,pos:t.pos};if(t.value==="false")return{type:10,true:!1,pos:t.pos};if(t.value==="undefined")return{type:11,pos:t.pos};if(t.value==="null")return{type:12,pos:t.pos};if(t.value==="end"&&e.tokens.length===1)return{type:22,pos:t.pos};if(t.value==="if"&&e.cursor===1)return Ye(e);if(t.value==="switch"&&e.cursor===1)return Pt(e);if(t.value==="case"&&e.cursor===1){let r=x(e);return{type:18,condition:r,pos:r.pos}}if(t.value==="default"&&e.tokens.length===1)return{type:19,pos:t.pos};if(t.value==="break"&&e.tokens.length===1)return{type:20,pos:t.pos};if(t.value==="continue"&&e.tokens.length===1)return{type:21,pos:t.pos};if(t.value==="else"&&e.cursor===1)return Ot(e)}if(t.type===0)return{type:7,value:t.value,pos:t.pos};if(t.type===4&&t.value==="("){let r=x(e);return P(e,4,")"),{type:9,expr:r,pos:t.pos}}if(t.type===4&&Ce.has(t.value)){let r=qe(e);return{type:2,operator:t.value,expr:r,pos:t.pos}}throw{message:`Unexpected token '${t.value}'.`,pos:t.pos}}function Ue(e){let t=e.tokens[e.cursor++];if(!t||t.type!==0&&t.type!==1)throw{message:"Expected an identifier after property access.",pos:t?.pos??e.tokens[e.cursor-2].pos};return{type:7,value:t.value,pos:t.pos}}function qe(e){let t=We(e);for(;e.tokens[e.cursor];){let r=e.tokens[e.cursor];if(r?.type===4&&r?.value==="("){if(e.cursor++,!e.config.allowFnCalls&&t.type!==6)throw{message:"Function calls are not allowed.",pos:r.pos};let n=Le(e);P(e,4,")"),t={type:3,expr:t,args:n,pos:e.tokens[e.cursor-1].pos}}else if(r?.type===4&&r?.value==="?."&&e.tokens[e.cursor+1]?.type===4&&e.tokens[e.cursor+1]?.value==="("){if(!e.config.allowFnCalls&&t.type!==6)throw{message:"Function calls are not allowed.",pos:e.tokens[e.cursor+1].pos};e.cursor+=2;let n=Le(e);P(e,4,")"),t={type:3,expr:t,args:n,optional:!0,pos:e.tokens[e.cursor-1].pos}}else if(r?.type===4&&Ae.has(r?.value)){let n=r.value==="::",o=r.value==="[",s=r.value==="?.";if(e.cursor++,n&&(e.tokens[e.cursor-2]?.type!==0||e.tokens[e.cursor]?.type!==0))throw{message:`Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${e.tokens[e.cursor-2]?.value}::${e.tokens[e.cursor]?.value??""}' instead.`,pos:e.tokens[e.cursor]?.pos??e.tokens[e.cursor-1].pos};if(n){let i=We(e);t={type:6,left:t,right:i,pos:e.tokens[e.cursor-1].pos}}else if(o){let i=x(e);P(e,4,"]"),t={type:8,left:t,right:i,bracketNotation:!0,pos:e.tokens[e.cursor-1].pos}}else if(s)if(e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value==="["){e.cursor++;let i=x(e);P(e,4,"]"),t={type:8,left:t,right:i,bracketNotation:!0,optional:!0,pos:e.tokens[e.cursor-1].pos}}else{let i=Ue(e);t={type:8,left:t,right:i,optional:!0,pos:e.tokens[e.cursor-1].pos}}else{let i=Ue(e);t={type:8,left:t,right:i,pos:e.tokens[e.cursor-1].pos}}}else break}return t}function T(e,t,r){let n=t(e);for(;e.tokens[e.cursor]?.type===4&&r.has(e.tokens[e.cursor]?.value);){let o=e.tokens[e.cursor++].value,s=t(e);n={type:0,left:n,right:s,operator:o,pos:e.tokens[e.cursor-1].pos}}return n}function Rt(e){return T(e,qe,$e)}function kt(e){return T(e,Rt,ke)}function At(e){return T(e,kt,Re)}function Ct(e){return T(e,At,Oe)}function Nt(e){return T(e,Ct,Pe)}function Ke(e){return T(e,Nt,xe)}function It(e){return T(e,Tt,Ne)}function Tt(e){return T(e,$t,Ie)}function $t(e){return T(e,Ke,Te)}function ze(e){let t=It(e);for(;e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value==="&&";){e.cursor++;let r=Ke(e);t={type:0,left:t,right:r,operator:"&&",pos:e.tokens[e.cursor-1].pos}}return t}function Ge(e){let t=ze(e);for(;e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value==="||";){e.cursor++;let r=ze(e);t={type:0,left:t,right:r,operator:"||",pos:e.tokens[e.cursor-1].pos}}return t}function vt(e){let t=Ge(e);for(;e.tokens[e.cursor]?.type===4&&e.tokens[e.cursor]?.value==="??";){e.cursor++;let r=Ge(e);t={type:0,left:t,right:r,operator:"??",pos:e.tokens[e.cursor-1].pos}}return t}function x(e){let t=vt(e);if(e.tokens[e.cursor]?.type!==4||e.tokens[e.cursor]?.value!=="?")return t;e.cursor++;let r=x(e);P(e,4,":");let n=x(e);return{type:1,condition:t,left:r,right:n,pos:e.tokens[e.cursor-1].pos}}function ue(e,t){let r={cursor:0,tokens:e,config:t},n=x(r);if(r.cursor!==r.tokens.length)throw{pos:r.tokens[r.cursor].pos,message:`Expected token '${r.tokens[r.cursor].value}'.
|
|
12
|
+
Expected an operator or the end of the expression.`};return n}function pe(e,{delimiters:t}){let r=`${t.openingTag}${t.whitespaceTrim}`,n=`${t.whitespaceTrim}${t.closingTag}`,o=e.startsWith(r),s=e.endsWith(n),i=o?r.length:t.openingTag.length,l=s?n.length:t.closingTag.length,u=e.slice(i,e.length-l),a=u.trim(),p=a.startsWith(t.commentTag);return p?{isComment:p,leftTrim:o,rightTrim:s}:{leftTrim:o,rightTrim:s,inner:u,isBlock:a.startsWith("for ")||a.startsWith("if ")||a==="else"||a.startsWith("else if ")||a.startsWith("switch ")||a.startsWith("case ")||a==="default"||a==="break"||a==="continue",isBlockEnd:a==="end",hasContext:a.startsWith("for "),requiresBlockClose:a.startsWith("for ")||a.startsWith("if ")||a.startsWith("switch "),usesAwait:u.includes("Mutor::await")}}var Ft=/[a-zA-Z$_]/,Mt=/[a-zA-Z$_0-9]/,Dt=/[0-9]/,Bt=/[0-9.oxe]/,jt=/[a-zA-Z$_0-9\s\t\r\n'"`]/;function le(e){let t=0,r="",n=[];function o(){let u="";if(Ft.test(r)){let a=t;for(;Mt.test(e[a])&&a<e.length;)u+=e[a],a++;n.push({type:Se.has(u)?1:0,value:u,pos:t}),t=a,r=e[t]}}function s(){if(r!=='"'&&r!=="'"&&r!=="`")return!1;let u=r,a=t,p=t+1,y="";for(;p<e.length;){let _=e[p];if(_==="\\"){if(p+1>=e.length)throw{pos:p,message:"Unexpected end of string after escape character."};y+=_,y+=e[p+1],p+=2;continue}if(_===u)break;y+=_,p++}if(p>=e.length||e[p]!==u)throw{pos:a,message:`String literal missing closing ${u}.`};n.push({type:3,value:y,pos:a}),t=p}function i(){if(Dt.test(r)){let u=t,a="";for(;Bt.test(e[u])&&u<e.length;)a+=e[u],u++;let p=Number(a);if(Number.isNaN(p))throw{pos:t,message:"Found invalid number literal."};n.push({type:2,value:`${p}`,pos:t}),t=u-1,r=e[t]}}function l(){let u=`${r}${e[t+1]}`;if(K.has(u)){n.push({type:4,value:u,pos:t}),t++;return}if(K.has(r)){n.push({type:4,value:r,pos:t});return}}for(;t<e.length;){if(r=e[t],i(),o(),s(),l(),!jt.test(r)&&!K.has(r)&&!K.has(e[t-1]+r))throw{message:`Unexpected token '${r}' in expression.`,pos:t};t++}return n.length?n:[{type:3,value:"",pos:0}]}function de(e,t,r){let n=[],o=[],{delimiters:s,keepOpeningTagEscapeDelimiter:i,allowFnCalls:l,allowedProps:u,forbiddenProps:a,autoEscape:p}=t,y="sync",_=!1,$=0,N='let acc="";';for(;$<e.length;){let Z=function(){let f=m,c=0;for(;f>=s.openingTagEscape.length&&e.slice(f-s.openingTagEscape.length,f)===s.openingTagEscape;)c++,f-=s.openingTagEscape.length;return c%2===1};var qt=Z;let m=e.indexOf(s.openingTag,$);if(m===-1){let f=e.slice($);_&&(f=f.trimStart()),f&&(N+=`acc+=\`${W(f)}\`;`);break}if(Z()){let f=e.slice($,i?m+s.openingTagEscape.length+1:m-s.openingTag.length+1);_&&(f=f.trimStart(),_=!1),N+=`acc+=\`${W(f)}\`;`,i||(N+=`acc+=\`${s.openingTag}\`;`),$=m+s.openingTag.length;continue}let U=e.indexOf(s.closingTag,m);if(U===-1){let[f,c]=Y(e,m),g=q(e,c);throw new k("No closing tag found.",f,g,m,r.path)}let se=e.slice(m,U+s.closingTag.length),{inner:tt,leftTrim:ge,rightTrim:rt,isBlock:ie,isBlockEnd:Ee,hasContext:we,requiresBlockClose:ye,isComment:nt,usesAwait:ot}=pe(se,{delimiters:s});ot&&y!=="async"&&(y="async");let I=e.slice($,m);if(I){let f=o[o.length-1];if(f?.type===1&&!f.hasCase){let c=I.search(/\S/);if(c===-1)I="";else{let g=$+c,[v,E]=Y(e,g),j=q(e,E);throw new k("A switch block must begin with a case or default tag.",v,j,g-E,r.path)}}_&&(I=I.trimStart()),ge&&(I=I.trimEnd()),I&&(N+=`acc+=\`${W(I)}\`;`)}_=!1,$=U+s.closingTag.length;try{if(!nt){let f=le(tt),c=ue(f,{allowFnCalls:l}),g=o[o.length-1];if(g?.type===1&&!g.hasCase&&c.type!==18&&c.type!==19&&c.type!==22)throw{message:"A switch block must begin with a case or default tag.",pos:c.pos};if((c.type===18||c.type===19)&&g?.type!==1)throw{message:`'${c.type===18?"case":"default"}' can only be used directly inside a switch block.`,pos:c.pos};if(c.type===19){if(g.hasDefault)throw{message:"A switch block can only have one default case.",pos:c.pos};g.hasDefault=!0}if((c.type===18||c.type===19)&&(g.hasCase=!0),(c.type===16||c.type===15)&&g?.type!==2)throw{message:`'${c.type===16?"else":"else if"}' can only be used directly inside an if block.`,pos:c.pos};if((c.type===16||c.type===15)&&g.hasElse)throw{message:`'${c.type===16?"else":"else if"}' cannot be used after an else block.`,pos:c.pos};if(c.type===16&&(g.hasElse=!0),c.type===20&&!o.some(({type:E})=>E===0||E===1))throw{message:"'break' can only be used inside a loop or switch block.",pos:c.pos};if(c.type===21&&!o.some(({type:E})=>E===0))throw{message:"'continue' can only be used inside a loop block.",pos:c.pos};let v=M(c,{allowedProps:u,forbiddenProps:a,scope:n});if(ie&&ye&&we){let{variable:E,secondaryVariable:j}=c;n.push(E),j&&n.push(j),o.push({type:0,pos:m,loopType:c.loopType,scopeSize:j===void 0?1:2,hasCase:!1,hasDefault:!1,hasElse:!1})}else ie&&ye&&!we&&o.push({type:c.type===17?1:2,pos:m,loopType:void 0,scopeSize:0,hasCase:!1,hasDefault:!1,hasElse:!1});if(Ee){let E=o.pop();if(E===void 0)throw{message:"Unexpected end of block",pos:m};E?.type===0&&n.splice(-E.scopeSize)}ie||Ee?N+=v:N+=p&&!v.startsWith("namespaces.Mutor.include")?`acc+=escapeFn(${v});`:`acc+=${v};`}rt&&(_=!0)}catch(f){let{message:c,pos:g}=f,v=ge?s.whitespaceTrim.length+s.openingTag.length:s.openingTag.length,E=m+g+v,[j,_e]=Y(e,E),st=q(e,_e);throw new k(c,j,st,E-_e,r.path)}}if(o.length){let m=o.pop()?.pos,[Z,U]=Y(e,m),se=q(e,U);throw new k("Unclosed block detected.",Z,se,m-U,r.path)}return N+="return acc;",y==="async"?new Me("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",N):new Function("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",N)}var V=class{constructor(t={}){this.__cacheSize=0;this.__config={...b};this.__compiledTemplatesMap=new Map;this.__namespaces=Fe;this.addConfig(t),this.__namespaces.Mutor={await:async r=>await r}}addConfig(t){let{autoEscape:r,delimiters:n,allowedProps:o,forbiddenProps:s,keepOpeningTagEscapeDelimiter:i,allowFnCalls:l,cache:u,build:a,onIncludeFail:p,onIncludeError:y,rootDir:_}=t;return this.__config={build:{include:new Set([...a?.include||b.build.include]),exclude:new Set([...b.build.exclude,...a?.exclude||[]])},rootDir:_,autoEscape:r===!0?!0:r!==!1,allowedProps:new Set([...o||b.allowedProps]),allowFnCalls:!!l,onIncludeFail:p||b.onIncludeFail,onIncludeError:y||b.onIncludeError,cache:{...b.cache,...u||{}},forbiddenProps:new Set([...b.forbiddenProps,...s||[]]),keepOpeningTagEscapeDelimiter:i??!1,delimiters:{...b.delimiters,...n||{}}},this.__config}restoreDefaultConfig(){this.__config={...b}}__compile(t,r){return de(t,this.__config,{path:r?.renderedPath||"anonymous"})}compile(t){let r=this.__compile(t);return n=>r(n,this.__createNamespacesWithRuntime(F(n)),this.__config.allowedProps,this.__config.forbiddenProps,z,G)}renderAsync(t,r){return new Promise(n=>{n(this.render(t,r))})}render(t,r){let n=F(r,"anonymous");return this.__renderWithRuntime(t,n)}__renderWithRuntime(t,r){return this.__compile(t,r)(r.context,this.__createNamespacesWithRuntime(r),this.__config.allowedProps,this.__config.forbiddenProps,z,G)}__createNamespacesWithRuntime(t){return{...this.__namespaces,Mutor:{...this.__namespaces.Mutor,$$context:t.context}}}__handleError(t,r,n,o){if(this.__config.onIncludeFail==="throw")throw t instanceof k?t:new d(t.message);let s={from:r,path:n,absolutePath:o};return this.__config.onIncludeFail==="ignoreLog"&&!this.__config.onIncludeError&&(t instanceof k?console.log(t):console.log(`[Mutor.js]
|
|
13
|
+
${t.message}`)),this.__config.onIncludeError?.(s,t)??""}__createEntrySpaceForTemplate(t){if(this.__cacheSize+t<=this.__config.cache.maxSize)return!0;if(t>this.__config.cache.maxSize)return!1;let r=this.__compiledTemplatesMap.entries().next().value;if(r){let[n,o]=r;this.__compiledTemplatesMap.delete(n),this.__cacheSize-=o.size}return this.__createEntrySpaceForTemplate(t)}getDiagnostics(){let t=this.__config.cache.maxSize;return{bytesUsed:this.__cacheSize,bytesMax:t,readableUsed:`${(this.__cacheSize/1024/1024).toFixed(2)} MB`,readableMax:`${(t/1024/1024).toFixed(2)} MB`,totalEntries:this.__compiledTemplatesMap.size,percentFull:t>0?Math.min(100,Math.round(this.__cacheSize/t*100)):0,avgTemplateSize:this.__compiledTemplatesMap.size>0?Math.round(this.__cacheSize/this.__compiledTemplatesMap.size):0}}__register(t,r){let n=r.length*2+500,o=this.__compiledTemplatesMap.get(t)?.size??0;if(this.__cacheSize-o+n>this.__config.cache.maxSize)throw new d(`The template for the component '${t}' is too large and will not fit in the cache. Consider increasing 'cache.maxSize' in the config`);let s=F(null,t),i=this.__compile(r,s);this.__compiledTemplatesMap.delete(t),this.__cacheSize-=o,this.__cacheSize+=r.length*2+500,this.__compiledTemplatesMap.set(t,{fn:i,size:n})}reset(){this.__config={...b},this.__compiledTemplatesMap.clear(),this.__cacheSize=0}};var H=class extends V{constructor(t={}){super(t)}__resolvePath(t,r){let n=t.startsWith("@/"),o=this.__config.rootDir?h(this.__config.rootDir):process.cwd(),s;return n?s=(0,A.join)(o,t.replace(/^@\//,"./")):r?s=h(r,t):s=(0,A.resolve)(process.cwd(),t),s}__setupIncludeForRuntime(t){this.__namespaces.Mutor.include=(r,n)=>{let o=this.__resolvePath(r,t.renderedPath);if(t.includeStack.has(o))throw new d(`Circular include detected.
|
|
14
14
|
${Array.from(t.includeStack).join(`
|
|
15
15
|
`)}
|
|
16
|
-
${o}`);let s=t.renderedPath;t.includeStack.add(o),t.renderedPath=o;try{return this.__renderFile(o,n??t.context,t)}catch(i){return this.
|
|
16
|
+
${o}`);let s=t.renderedPath;t.includeStack.add(o),t.renderedPath=o;try{return this.__renderFile(o,n??t.context,t)}catch(i){return this.__handleError(i,s,r,o)}finally{t.includeStack.delete(o),t.renderedPath=s}}}render(t,r){let n=F(r,"anonymous");return this.__setupIncludeForRuntime(n),this.__renderWithRuntime(t,n)}renderAsync(t,r){return new Promise(n=>{n(this.render(t,r))})}__renderFile(t,r,n){this.__setupIncludeForRuntime(n);let o=this.__resolvePath(t),s,i=n.context,l=n.renderedPath;n.context=r??i,n.renderedPath=o;try{if(this.__config.cache.active&&this.__compiledTemplatesMap.has(o)){let a=this.__compiledTemplatesMap.get(o);s=a.fn,this.__compiledTemplatesMap.delete(o),this.__compiledTemplatesMap.set(o,a)}else{let a=(0,Je.readFileSync)(o,"utf-8");if(s=this.__compile(a,n),this.__config.cache.active){let p=a.length*2+500;this.__cacheSize+p>this.__config.cache.maxSize?this.__createEntrySpaceForTemplate(p)&&(this.__compiledTemplatesMap.set(o,{fn:s,size:p}),this.__cacheSize+=p):(this.__compiledTemplatesMap.set(o,{fn:s,size:p}),this.__cacheSize+=p)}}return s(n.context,this.__createNamespacesWithRuntime(n),this.__config.allowedProps,this.__config.forbiddenProps,z,G)}finally{n.context=i,n.renderedPath=l}}renderFile(t,r){return this.__renderFile(t,r,F(null,t))}renderFileAsync(t,r){return new Promise(n=>{n(this.renderFile(t,r))})}async buildDir(t,r,n){let o=h(r),s=h(t);await(0,O.mkdir)(o,{recursive:!0});let i=await(0,O.readdir)(s,{withFileTypes:!0});await Promise.all(i.map(async l=>{let u=(0,A.join)(s,l.name),a=(0,A.join)(o,l.name);if(this.__config.build.exclude.has(l.name))return;if(l.isDirectory())return this.buildDir(u,a,n);let p=(0,A.extname)(u);if(this.__config.build.include.has(p)){let y=this.renderFile(u,n);await(0,O.writeFile)(a,y,"utf-8")}else return await(0,O.copyFile)(u,a)}))}async compileDir(t){let r=h(t),n=await(0,O.readdir)(r,{withFileTypes:!0});await Promise.all(n.map(async o=>{let s=(0,A.join)(r,o.name);if(this.__config.build.exclude.has(o.name))return;if(o.isDirectory())return this.compileDir(s);let i=(0,A.extname)(s);if(this.__config.build.include.has(i)){let l=await(0,O.readFile)(s,"utf-8");this.__register(s,l)}}))}};var C={Success:0,RuntimeError:1,ArgumentError:2},D=class extends Error{constructor(r,n=C.RuntimeError){super(r);this.exitCode=n;this.name="CliError"}},w=class extends D{constructor(t){super(t,C.ArgumentError),this.name="ArgumentError"}},Q=class extends D{constructor(t,r){let n=r instanceof Error?r.message:String(r);super(`could not read file '${t}': ${n}`,C.RuntimeError),this.name="FileReadError"}},ee=class extends D{constructor(t,r){let n=r instanceof Error?r.message:String(r);super(`could not write file '${t}': ${n}`,C.RuntimeError),this.name="FileWriteError"}},te=class extends D{constructor(t,r){let n=r instanceof Error?r.message:String(r);super(`failed to parse JSON in '${t}': ${n}`,C.RuntimeError),this.name="JsonParseError"}};var Lt=new Set(["compile","build","render"]),Wt=new Set(["--out","--data","--config"]),Ut=`Mutor.js v${be}`,re=`
|
|
17
17
|
Usage: mutor <command> <input> [options]
|
|
18
18
|
|
|
19
19
|
Commands:
|
|
@@ -32,13 +32,13 @@ Exit codes:
|
|
|
32
32
|
0 success
|
|
33
33
|
1 runtime error (I/O failure, render failure, etc.)
|
|
34
34
|
2 argument error (bad flags, missing or wrong-typed values)
|
|
35
|
-
`.trim();function ne(e){try{return(0,
|
|
35
|
+
`.trim();function ne(e){try{return(0,R.readFileSync)(e,"utf-8")}catch(t){throw new Q(e,t)}}function fe(e,t){try{(0,R.writeFileSync)(e,t,"utf-8")}catch(r){throw new ee(e,r)}}function oe(e){let t=ne(e);try{return JSON.parse(t)}catch(r){throw new te(e,r)}}function X(e,t){let r;try{r=(0,R.statSync)(e)}catch{throw new w(`${t} path '${e}' does not exist`)}if(!r.isFile())throw new w(`${t} path '${e}' is not a file`)}function zt(e,t){let r;try{r=(0,R.statSync)(e)}catch{throw new w(`${t} path '${e}' does not exist`)}if(!r.isDirectory())throw new w(`${t} path '${e}' is not a directory`)}function me(e,t,...r){if(!r.some(o=>e.endsWith(o)))throw new w(`${t} expects a file with extension ${r.join(" or ")} \u2014 got '${e}'`)}function Ve(e){(e.length===0||e[0]==="--help")&&(console.log(re),(0,B.exit)(C.Success)),e[0]==="--version"&&(console.log(Ut),(0,B.exit)(C.Success));let t=e[0];if(!Lt.has(t))throw new w(`unknown command '${t}'
|
|
36
36
|
|
|
37
|
-
${re}`);let r=e[1];if(!r||r.startsWith("--"))throw new
|
|
37
|
+
${re}`);let r=e[1];if(!r||r.startsWith("--"))throw new w(`command '${t}' requires an input path as its first argument
|
|
38
38
|
|
|
39
|
-
${re}`);let n={command:t,commandData:r};for(let o=2;o<e.length;o++){let s=e[o];if(!
|
|
39
|
+
${re}`);let n={command:t,commandData:r};for(let o=2;o<e.length;o++){let s=e[o];if(!Wt.has(s))throw new w(`unknown option '${s}'
|
|
40
40
|
|
|
41
|
-
${re}`);let i=e[o+1];if(!i||i.startsWith("--"))throw new
|
|
42
|
-
Build interrupted \u2014 removing partial output...`);try{(0,
|
|
43
|
-
Received ${e}.`),
|
|
41
|
+
${re}`);let i=e[o+1];if(!i||i.startsWith("--"))throw new w(`option '${s}' requires a value`);n[s]=i,o++}return n}function He(e,t){let r=h(t.commandData);X(r,"<input>");let n=ne(r),s=e.compile(n).toString();if(t["--out"]){let i=h(t["--out"]);he(()=>{try{(0,R.rmSync)(i,{force:!0})}catch{}}),fe(i,s),console.log(`Compiled \u2192 ${t["--out"]}`)}else console.log(s)}async function Xe(e,t){if(!t["--data"])throw new w("'build' requires a data source via --data");if(!t["--out"])throw new w("'build' requires an output directory via --out");let r=h(t.commandData),n=h(t["--data"]),o=h(t["--out"]);zt(r,"<input>"),X(n,"--data"),me(n,"--data",".json");let s=oe(n),i=!1;he(()=>{if(i){console.warn(`
|
|
42
|
+
Build interrupted \u2014 removing partial output...`);try{(0,R.rmSync)(o,{recursive:!0,force:!0})}catch{}}}),i=!0,await e.buildDir(r,o,s),i=!1,console.log(`Built \u2192 ${t["--out"]}`)}async function Ze(e,t){if(!t["--data"])throw new w("'render' requires a data source via --data");let r=h(t.commandData),n=h(t["--data"]);X(r,"<input>"),X(n,"--data"),me(n,"--data",".json");let o=oe(n),s=ne(r),i=e.render(s,o);if(t["--out"]){let l=h(t["--out"]);he(()=>{try{(0,R.rmSync)(l,{force:!0})}catch{}}),fe(l,i),console.log(`Rendered \u2192 ${t["--out"]}`)}else console.log(i)}var Qe=null;function he(e){Qe=e}function et(e){console.warn(`
|
|
43
|
+
Received ${e}.`),Qe?.(),(0,B.exit)(C.RuntimeError)}process.on("SIGINT",()=>et("SIGINT"));process.on("SIGTERM",()=>et("SIGTERM"));async function Gt(){let e=Ve(B.argv.slice(2)),t=new H;if(e["--config"]){let r=h(e["--config"]);X(r,"--config"),me(r,"--config",".json");let n=oe(r);t.addConfig(n)}switch(e.command){case"compile":He(t,e);break;case"build":await Xe(t,e);break;case"render":await Ze(t,e);break}}process.env.NODE_ENV!=="test"&&Gt().catch(e=>{e instanceof D&&(console.error(`error: ${e.message}`),(0,B.exit)(e.exitCode)),console.error("unexpected error:",e),(0,B.exit)(C.RuntimeError)});0&&(module.exports={handleBuildCommand,handleCompileCommand,handleRenderCommand,parseArgs,safeParseJsonFile,safeReadFile,safeWriteFile});
|
|
44
44
|
//# sourceMappingURL=cli.cjs.map
|