mutorjs 1.0.0
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/README.md +140 -0
- package/dist/index.cjs +13 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +62 -0
- package/dist/index.d.ts +62 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/server.cjs +16 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +69 -0
- package/dist/server.d.ts +69 -0
- package/dist/server.js +16 -0
- package/dist/server.js.map +1 -0
- package/package.json +76 -0
package/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Mutor.js
|
|
2
|
+
|
|
3
|
+
> **The Secure, AST-Powered Template Engine.**
|
|
4
|
+
|
|
5
|
+
Most template engines force a choice: **Extreme Speed** (using unsafe string manipulation and `eval`) or **Total Security** (using slow interpreters). Mutor.js refuses to compromise. By utilizing an Abstract Syntax Tree (AST) to compile templates into pure, optimized JavaScript, Mutor delivers top-tier performance while running in a strictly sandboxed environment.
|
|
6
|
+
|
|
7
|
+
Developed by Onah Victor, Mutor is engineered for high-concurrency environments and is efficient enough to run flawlessly on anything from modern cloud infrastructure to legacy 1st-generation core processors.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## โก Why Switch to Mutor?
|
|
12
|
+
|
|
13
|
+
* **Raw Speed**: Surpasses Eta by **1.2x to 5.0x** in raw compiled template execution, often tying with native JavaScript.
|
|
14
|
+
* **Security by Design**: Completely sandboxed. Forbidden properties (like `__proto__`) are blocked by default. Arbitrary function execution is locked down.
|
|
15
|
+
* **Namespace Operator**: Access built-in JS utilities (Math, JSON, String) safely without polluting the global scope.
|
|
16
|
+
* **Precision Whitespace Control**: Clean up your output without messy regex workarounds.
|
|
17
|
+
* **Developer-Friendly Error Traces**: Because it's AST-based, errors map directly to line and column numbers.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## ๐ก A Detailed Example
|
|
22
|
+
|
|
23
|
+
Mutor handles complex nested logic, data formatting, and whitespace control natively, without requiring arbitrary JS execution.
|
|
24
|
+
```hbs
|
|
25
|
+
{{# Manage a project list with precision logic and security #}}
|
|
26
|
+
<section class="project-board">
|
|
27
|
+
{{~ if projects.length > 0 ~}}
|
|
28
|
+
{{ for item of projects }}
|
|
29
|
+
<div class="card">
|
|
30
|
+
<h3>{{ item.name.toUpperCase() }}</h3>
|
|
31
|
+
<p>Budget: {{ Math::floor(item.budget) }} USD</p>
|
|
32
|
+
|
|
33
|
+
{{# Securely handle nested logic #}}
|
|
34
|
+
{{ if item.status == "active" }}
|
|
35
|
+
<span class="status-pill">Last Updated: {{ JSON::stringify(item.meta.date) }}</span>
|
|
36
|
+
{{ end }}
|
|
37
|
+
</div>
|
|
38
|
+
{{ end }}
|
|
39
|
+
{{~ else ~}}
|
|
40
|
+
<p>No active projects found in {{ Date::getFullYear() }}.</p>
|
|
41
|
+
{{~ end ~}}
|
|
42
|
+
</section>
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## ๐ Architecture & Pipeline
|
|
48
|
+
|
|
49
|
+
Mutor isn't just a regex replacer; it's a full compiler.
|
|
50
|
+
|
|
51
|
+
1. **Tokenize (`src/core/tokenize.ts`)**: Breaks your template string into distinct logical units.
|
|
52
|
+
2. **Parse (`src/core/parse.ts` & `src/core/generate-ast.ts`)**: Converts tokens into a secure Abstract Syntax Tree (AST).
|
|
53
|
+
3. **Compile (`src/core/compile.ts`)**: Transforms the AST into a highly optimized, "pure" JavaScript function.
|
|
54
|
+
4. **Execute**: The compiled function runs within a restricted scope, safely interpolating your context.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## ๐ Core Innovations
|
|
59
|
+
|
|
60
|
+
### 1. The Namespace Operator (`::`)
|
|
61
|
+
Traditional engines either block all JS helpers or give templates full access to your server's global object. Mutorโs Namespace Operator solves this elegantly. Safely tap into built-ins directly in the template:
|
|
62
|
+
* `{{ Math::floor(price) }}`
|
|
63
|
+
* `{{ JSON::stringify(data) }}`
|
|
64
|
+
* `{{ Array::isArray(items) }}`
|
|
65
|
+
|
|
66
|
+
### 2. Perfect Whitespace Control
|
|
67
|
+
Use the configurable whitespace directive (`~` by default) exactly where you need it:
|
|
68
|
+
* `{{~ name }}` (Trim left)
|
|
69
|
+
* `{{ name ~}}` (Trim right)
|
|
70
|
+
* `{{~ name ~}}` (Trim both sides)
|
|
71
|
+
|
|
72
|
+
### 3. Total Flexibility
|
|
73
|
+
Don't like `{{` and `}}`? Change them. Mutor allows you to completely redefine the syntax delimiters (e.g., `<%=` and `%>`) via the configuration object.
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## ๐ Performance Benchmarks
|
|
78
|
+
|
|
79
|
+
Mutor is built to dominate in scale and high-load scenarios.
|
|
80
|
+
|
|
81
|
+
| Metric | Mutor.js | Eta | EJS | Nunjucks / Handlebars |
|
|
82
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
83
|
+
| **Full Pipeline (Compile + Exec)** | **2nd Overall** | 1st | Distant 3rd | Slower |
|
|
84
|
+
| **Raw Execution (Compiled)** | **Top Tier (1.2x - 5x lead)** | Competitive | Significantly Slower | Significantly Slower |
|
|
85
|
+
|
|
86
|
+
*Memory Management*: Mutor includes a built-in LRU cache (defaulting to 50MB) to ensure frequently used templates execute instantly without causing memory leaks.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## โ๏ธ Out-of-the-Box Configuration
|
|
91
|
+
|
|
92
|
+
Mutor works instantly, but exposes deep controls for enterprise needs.
|
|
93
|
+
```typescript
|
|
94
|
+
export const defaultConfig: MutorConfig = {
|
|
95
|
+
build: {
|
|
96
|
+
include: new Set([".html", ".txt"]),
|
|
97
|
+
exclude: new Set(["node_modules", ".git"]),
|
|
98
|
+
},
|
|
99
|
+
autoEscape: true,
|
|
100
|
+
allowedProps: new Set(),
|
|
101
|
+
forbiddenProps: new Set(["__proto__", "constructor", "prototype"]),
|
|
102
|
+
allowFnCalls: false, // Prevents unintended side effects
|
|
103
|
+
delimiters: {
|
|
104
|
+
closingTag: "}}",
|
|
105
|
+
openingTag: "{{",
|
|
106
|
+
openingTagEscape: "\\",
|
|
107
|
+
whitespaceTrim: "~",
|
|
108
|
+
},
|
|
109
|
+
keepOpeningTagEscapeDelimiter: false,
|
|
110
|
+
cache: {
|
|
111
|
+
active: true,
|
|
112
|
+
maxSize: 50 * 1024 * 1024, // 50MB
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## โ๏ธ Is Mutor Right For You? (Honest Trade-offs)
|
|
120
|
+
|
|
121
|
+
**When to use Mutor:**
|
|
122
|
+
* You are rendering user-generated content and cannot risk XSS or prototype pollution.
|
|
123
|
+
* You need near-native execution speed for high-traffic applications.
|
|
124
|
+
* You want clean, debuggable templates that fail with exact line/column numbers.
|
|
125
|
+
* You need to pre-compile entire view directories ahead of time.
|
|
126
|
+
|
|
127
|
+
**When NOT to use Mutor:**
|
|
128
|
+
* You require the ability to write complex, arbitrary JavaScript directly inside your HTML. Mutor's sandbox will block this.
|
|
129
|
+
* You only need simple string replacement for a tiny script where initializing an AST engine is overkill.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## ๐ Coming Soon: The CLI Tool
|
|
134
|
+
|
|
135
|
+
Mutor's core features are ready, and the CLI is currently in active development to streamline your CI/CD pipelines.
|
|
136
|
+
```bash
|
|
137
|
+
# Preview CLI Commands
|
|
138
|
+
mutor compile ./views/index.html --out ./dist
|
|
139
|
+
mutor build ./views --max-mem 50MB
|
|
140
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";var G=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var he=(e,n)=>{for(var t in n)G(e,t,{get:n[t],enumerable:!0})},de=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ue(n))!fe.call(e,o)&&o!==t&&G(e,o,{get:()=>n[o],enumerable:!(i=le(n,o))||i.enumerable});return e};var ge=e=>de(G({},"__esModule",{value:!0}),e);var ye={};he(ye,{default:()=>Oe});module.exports=ge(ye);function K(e,n){return`${" ".repeat(e+n+1)}^`}var d=class e extends Error{constructor(t){super(t);this.name="MutorError";Object.setPrototypeOf(this,e.prototype)}},I=class e extends d{constructor(t,i,o,p,f){let g=i.toString().length+2,a=`${t}
|
|
2
|
+
|
|
3
|
+
`;a+=`at ${f}:${i}:${p+1}
|
|
4
|
+
`,i>1&&(a+=`${(i-1).toString().padStart(g-2)} | ...
|
|
5
|
+
`),a+=`${i} | ${o}
|
|
6
|
+
`,a+=K(p,g);super(a);this.name="MutorCompilerError";Object.setPrototypeOf(this,e.prototype)}};var Q=new Set(["for","if","else","true","false","null","undefined","end","in","of"]),M=new Set(["::","||","??","&&","**","^","|","&","!","-","%","+","*","/",">","<",">=","<=","==","!=",">>","<<",".","?.","(",")","[","]",",",":","?"]);var X=new Set(["==","!="]),J=new Set([">","<",">=","<="]);var k=new Set(["+","-"]),ee=new Set(["*","/","%"]),te=new Set([".","?.","[","::"]),re=new Set(["-","+","!"]),ne={"&":"&","<":"<",">":">",'"':""","'":"'"},A={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:"~"},keepOpeningTagEscapeDelimiter:!1,cache:{active:!0,maxSize:50*1024*1024}},oe={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,n){if(!e||typeof e!="object")throw new d("Object.hasOwn expects an object");return Object.hasOwn(e,n)},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,n=10){return Number.parseInt(e,n)},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 U(e){return typeof e!="string"?e:/[&<>"']/.test(e)?e.replace(/[&<>"']/g,n=>ne[n]):e}function z(e,n,t){if(n.has(e)&&!t.has(e))throw new d(`Forbidden property access. Access to this computed property "${e}" is forbidden.`);return e}var F="object",se=Symbol("__mutor_safe_context");function W(e){if(!e||typeof e!==F||se in e)return e;let n=new WeakSet;function t(o,p=""){if(!o||typeof o!==F||n.has(o))return o;n.add(o);let f=Object.getPrototypeOf(o);if(f&&f!==Object.prototype&&f!==Array.prototype)throw new d(`Unsafe prototype detected at ${p||"root"}`);if(Array.isArray(o)){for(let a=0;a<o.length;a++)o[a]=t(o[a],`${p}[${a}]`);return o}if(o instanceof Map){for(let[a,u]of o.entries())typeof a===F&&t(a,`${p}.mapKey`),o.set(a,t(u,`${p}.mapValue`));return o}if(o instanceof Set){let a=new Set;for(let u of o.values())a.add(t(u,p));o.clear();for(let u of a)o.add(u);return o}let g=Object.getOwnPropertyDescriptors(o);for(let a of Object.keys(g)){let u=g[a];if(u.get||u.set)throw new d(`Getter/setter not allowed: ${p}.${a}`);let O=o[a];O&&typeof O===F&&(o[a]=t(O,`${p}.${a}`))}return o}let i=t(e);return i&&typeof i===F&&Object.defineProperty(i,se,{value:!0,enumerable:!1,writable:!1,configurable:!1}),i}function D(e,n){let i=e.slice(0,n).split(`
|
|
7
|
+
`).length,o=e.lastIndexOf(`
|
|
8
|
+
`,n-1)+1;return{line:i,lineIndex:o}}function j(e,n,t){let i=e.indexOf(`
|
|
9
|
+
`,n);return{line:e.slice(n,i===-1?void 0:i),pos:t-n}}function v(e,n){let{scope:t,forbiddenProps:i,allowedProps:o}=n;function p(s){return t.includes(s)?s:`ctx.${s}`}function f(s){switch(s.type){case 17:return"}";case 5:return s.value;case 4:return`"${s.value}"`;case 10:return s.true?"true":"false";case 12:return"null";case 11:return"undefined";case 7:return p(s.value);case 9:return`(${f(s.expr)})`;case 2:return`${s.operator}${f(s.expr)}`;case 0:return`${f(s.left)} ${s.operator} ${f(s.right)}`;case 1:return`${f(s.condition)} ? ${f(s.left)} : ${f(s.right)}`;case 8:return a(s);case 3:return u(s);case 6:return g(s);case 13:return O(s);case 16:return"} else {";case 14:return b(s);case 15:return R(s);default:throw new d(`Unsupported expression type: ${s.type}`)}}function g(s){if(s.left.type!==7)throw{message:"Invalid usage of namespace operator.",pos:s.pos};return`namespaces.${s.left.value}.${s.right.value}`}function a(s){let y=f(s.left);if(s.bracketNotation){let h=f(s.right),w=s.optional?"?.":"";return s.right.type!==4&&s.right.type!==5?`${y}${w}[${h}]`:`${y}${w}[validateComputedProps(${h}, allowedProps, forbiddenProps)]`}else{let h=s.right.value,w=s.optional?"?.":".";if(i.has(h)&&!o.has(h))throw{message:"Forbidden property access.",pos:s.right.pos};return`${y}${w}${h}`}}function u(s){let y=f(s.expr),h=s.optional?"?.":"",w=s.args.map(N=>f(N)).join(", ");return`${y}${h}(${w})`}function O(s){let{iterable:y,loopType:h,variable:w}=s;return`for(const ${w} ${h===1?"in":"of"} ${v(y,n)}){`}function b(s){let{condition:y}=s;return`if(${v(y,n)}){`}function R(s){let{condition:y}=s;return`}else if(${v(y,n)}){`}return f(e)}function B(e){switch(e){case 0:return"identifier";case 1:return"keyword";case 2:return"number";case 4:return"operator";case 3:return"string"}}function q(e,n){let t=0,i=!1;function o(r,c){let l=e[t],S=e[e.length-1];if(!l)throw{message:`Unexpected end of expression. Expected ${c?`'${c}'`:`${r===0?"an":"a"} ${B(r)}`}.`,pos:S.pos+S.value.length-1};if(l.type!==r)throw{message:`Unexpected token type. Expected ${c?`'${c}'`:B(r)} but got ${B(l.type)} instead.`,pos:l.pos};if(c!==void 0&&l.value!==c)throw{message:`Unexpected token '${l?.value}'. Expected ${r===0?"an":"a"} ${B(r)} instead.`,pos:l.pos};return e[t++]}function p(){let r=e[t-1].pos,c=o(0).value,l;try{l=o(1,"in")}catch{l=o(1,"of")}let S=l.value==="in"?1:0,T=_();return{type:13,loopType:S,iterable:T,variable:c,pos:r}}function f(){let r=_();return{condition:r,pos:r.pos,type:14}}function g(){let r=e[t-1].pos;try{return o(1,"if"),{...f(),type:15,pos:r}}catch{return{type:16,pos:r}}}function a(){let r=[];if(e[t]?.type===4&&e[t]?.value===")")return r;for(r.push(_());e[t]?.type===4&&e[t]?.value===","&&e[t]?.value!==")";)t++,r.push(_());return r}function u(){let r=e[t++];if(r?.type===2)return{type:5,value:r.value,pos:r.pos};if(r?.type===3)return{type:4,value:r.value,pos:r.pos};if(r?.type===1){if(r.value==="for"&&t===1)return p();if(r.value==="true"||r.value==="false")return{type:10,true:r.value==="true",pos:r.pos};if(r.value==="undefined")return{type:11,pos:r.pos};if(r.value==="null")return{type:12,pos:r.pos};if(r.value==="end"&&e.length===1)return{type:17,pos:r.pos};if(r.value==="if"&&t===1)return f();if(r.value==="else"&&t===1)return g()}if(r?.type===0)return{type:7,value:r.value,pos:r.pos};if(r?.type===4&&r.value==="("){let c=_();return o(4,")"),{type:9,expr:c,pos:r.pos}}if(r?.type===4&&re.has(r.value)){let c=r.value,l=_();return{type:2,operator:c,expr:l,pos:r.pos}}throw t>e.length?{message:"Unexpected end of expression.",pos:e[e.length-1].pos}:{message:`Unexpected token '${r?.value}'.`,pos:r.pos}}function O(){let r=u();for(;e[t];){let c=e[t];if(c?.type===4&&c?.value==="("){if(t++,!i&&!n.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let l=a();o(4,")"),r={type:3,expr:r,args:l,pos:e[t-1].pos}}else if(c?.type===4&&c?.value==="?."&&e[t+1]?.type===4&&e[t+1]?.value==="("){if(t++,t++,!i&&!n.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let l=a();o(4,")"),r={type:3,expr:r,args:l,optional:!0,pos:e[t-1].pos}}else if(c?.type===4&&te.has(c?.value)){let l=c?.value==="::",S=c?.value==="[",T=c?.value==="?.";if(t++,l&&(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(l){i=!0;let E=u();r={type:6,left:r,right:E,pos:e[t-1].pos}}else if(S){let E=_();o(4,"]"),r={type:8,right:E,left:r,bracketNotation:!0,pos:e[t-1].pos}}else if(T)if(e[t]?.type===4&&e[t]?.value==="["){t++;let E=_();o(4,"]"),r={type:8,left:r,right:E,bracketNotation:!0,optional:!0,pos:e[t-1].pos}}else{let E=u();r={type:8,left:r,right:E,optional:!0,pos:e[t-1].pos}}else{let E=u();r={type:8,left:r,right:E,pos:e[t-1].pos}}}else break}return i=!1,r}function b(){let r=O();for(;e[t]?.type===4&&ee.has(e[t]?.value);){let c=e[t++].value,l=O();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function R(){let r=b();for(;e[t]?.type===4&&k.has(e[t]?.value);){let c=e[t++].value,l=b();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function s(){let r=R();for(;e[t]?.type===4&&J.has(e[t]?.value);){let c=e[t++].value,l=R();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function y(){let r=s();for(;e[t]?.type===4&&J.has(e[t]?.value);){let c=e[t++].value,l=s();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function h(){let r=y();for(;e[t]?.type===4&&X.has(e[t]?.value);){let c=e[t++].value,l=y();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function w(){let r=N();for(;e[t]?.type===4&&e[t]?.value==="||";){let c=e[t++].value,l=N();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function N(){let r=x();for(;e[t]?.type===4&&e[t]?.value==="&&";){let c=e[t++].value,l=x();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function x(){let r=h();for(;e[t]?.type===4&&e[t]?.value==="??";){let c=e[t++].value,l=h();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function _(){let r=w();if(e[t]?.type!==4||e[t]?.value!=="?")return r;t++;let c=_();o(4,":");let l=_();return{type:1,left:c,right:l,condition:r,pos:e[t-1].pos}}return _()}function Z(e,{delimiters:n}){let t=`${n.openingTag}${n.whitespaceTrim}`,i=`${n.whitespaceTrim}${n.closingTag}`,o=e.startsWith(t),p=e.endsWith(i),f=e.slice(o?t.length:n.openingTag.length,e.length-(p?i.length:n.closingTag.length)),g=f.trim(),a=g.startsWith("for")||g.startsWith("if")||g.startsWith("else"),u=g.startsWith("for")||g.startsWith("if"),O=g==="end",b=g.startsWith("for");return{leftTrim:o,rightTrim:p,inner:f,isBlock:a,isBlockEnd:O,hasContext:b,requiresBlockClose:u}}function V(e){let n=0,t="",i=[];function o(){let a="";if(/[a-zA-Z$_]/.test(t)){let u=n;for(;/[a-zA-Z$_0-9]/.test(e[u])&&u<e.length;)a+=e[u],u++;i.push({type:Q.has(a)?1:0,value:a,pos:n}),n=u,t=e[n]}}function p(){let a="";if(t==='"'||t==="'"||t==="`"){let u=n+1;for(;e[u]!==t&&u<e.length;)a+=e[u],u++;if(u>e.length)throw{pos:n,message:"Found string without closing quote."};i.push({type:3,value:a,pos:n}),n=u}}function f(){if(/[0-9]/.test(t)){let a=n,u="";for(;/[0-9.oxe]/.test(e[a])&&a<e.length;)u+=e[a],a++;let O=Number(u);if(Number.isNaN(O))throw{pos:n,message:"Found invalid number literal."};i.push({type:2,value:`${O}`,pos:n}),n=a-1,t=e[n]}}function g(){let a=`${t}${e[n+1]}`;if(M.has(a)){i.push({type:4,value:a,pos:n}),n++;return}if(M.has(t)){i.push({type:4,value:t,pos:n});return}}for(;n<e.length;){if(t=e[n],f(),o(),p(),g(),!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(t)&&!M.has(t)&&!M.has(e[n-1]+t))throw{message:`Unexpected token '${t}' in expression.`,pos:n};n++}return i}function H(e,n,t){let i=[],o=[],{delimiters:p,keepOpeningTagEscapeDelimiter:f,allowFnCalls:g,allowedProps:a,forbiddenProps:u,autoEscape:O}=n,b=!1,R=0,s='let acc="";';for(;R<e.length;){let w=function(){let m=h,P=0;for(;m>=p.openingTagEscape.length&&e.slice(m-p.openingTagEscape.length,m)===p.openingTagEscape;)P++,m-=p.openingTagEscape.length;return P%2===1};var y=w;let h=e.indexOf(p.openingTag,R);if(h===-1){let m=e.slice(R);b&&(m=m.trimStart()),m&&(s+=`acc+=\`${m}\`;`);break}if(w()){let m=e.slice(R,f?h+p.openingTagEscape.length+1:h-p.openingTag.length+1);b&&(m=m.trimStart(),b=!1),s+=`acc+=\`${m}\`;`,f||(s+=`acc+=\`${p.openingTag}\`;`),R=h+p.openingTag.length;continue}let N=e.indexOf(p.closingTag,h);if(N===-1){let{line:m,lineIndex:P}=D(e,h),{line:C,pos:$}=j(e,P,h);throw new I("No closing tag found.",m,C,$,t.path)}let x=e.slice(h,N+p.closingTag.length),{inner:_,leftTrim:Y,rightTrim:r,isBlock:c,isBlockEnd:l,hasContext:S,requiresBlockClose:T}=Z(x,{delimiters:p}),E=e.slice(R,h);E&&(b&&(E=E.trimStart()),Y&&(E=E.trimEnd()),E&&(s+=`acc+=\`${E}\`;`)),b=!1,R=N+p.closingTag.length;try{let m=V(_),P=q(m,{allowFnCalls:g});if(c&&T&&S?(i.push(P.variable),o.push({type:0,pos:h})):c&&T&&!S&&o.push({type:1,pos:h}),l){let $=o.pop();if($?.type===0&&i.pop(),$===void 0)throw{message:"Unexpected end of block",pos:h}}let C=v(P,{allowedProps:a,forbiddenProps:u,scope:i});c||l?s+=C:s+=O?`acc+=escapeFn(${C});`:`acc+=${C};`,r&&(b=!0)}catch(m){let{message:P,pos:C}=m,{line:$,lineIndex:ae}=D(e,h),{line:ce,pos:pe}=j(e,ae,h);throw new I(P,$,ce,pe+C+(Y?p.openingTag.length+p.whitespaceTrim.length:p.openingTag.length),t.path)}}if(o.length){let h=o.pop()?.pos,{line:w,lineIndex:N}=D(e,h),{line:x,pos:_}=j(e,N,h);throw new I("Unclosed block detected.",w,x,_+p.openingTag.length,t.path)}return s+="return acc;",new Function("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",s)}var L=class{constructor(n){this.__currentRenderedPath="";this.__includeStack=new Set;this.__cacheSize=0;this.__config={...A};this.__compiledTemplatesMap=new Map;this.__currentContext=null;this.__namespaces={...oe,Mutor:{include:(n,t)=>{if(this.__includeStack.has(n))throw new d(`Circular include detected:
|
|
10
|
+
${Array.from(this.__includeStack).join(`
|
|
11
|
+
`)}
|
|
12
|
+
${n}`);try{return this.__includeStack.add(n),this.renderComponent(n,t??this.__currentContext)}finally{this.__includeStack.delete(n)}}}};this.addConfig(n),Object.defineProperty(this.__namespaces.Mutor,"$$context",{get:()=>this.__currentContext})}addConfig(n){let{autoEscape:t,delimiters:i,allowedProps:o,forbiddenProps:p,keepOpeningTagEscapeDelimiter:f,allowFnCalls:g,cache:a,build:u}=n;return this.__config={build:{include:new Set([...A.build.include,...u?.include||[]]),exclude:new Set([...A.build.exclude,...u?.exclude||[]])},autoEscape:t===!0?!0:t!==!1,allowedProps:o||new Set,allowFnCalls:!!g,cache:{...A.cache,...a||{}},forbiddenProps:p||new Set,keepOpeningTagEscapeDelimiter:f===!0?!0:f!==!1,delimiters:{...A.delimiters,...i||{}}},this.__config}restoreDefaultConfig(){return this.__config={...A},this.__config}compile(n,t="anonymous"){return H(n,this.__config,{path:t})}render(n,t){let i=this.__currentContext;i!==t&&(this.__currentContext=t);let o=this.compile(n)(W(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,U,z);return this.__currentContext=i,o}renderComponent(n,t){if(!this.__compiledTemplatesMap.has(n))throw new d(`No template exists with the identifier '${n}'`);let i=this.__currentRenderedPath,o=this.__currentContext,p=this.__compiledTemplatesMap.get(n);this.__currentContext=t,this.__currentRenderedPath=n;let f=p.fn(W(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,U,z);return this.__currentContext=o,this.__currentRenderedPath=i,f}registerComponent(n,t){let i=t.length*2+500;if(this.__cacheSize+i>this.__config.cache.maxSize&&!this.createEntrySpaceForTemplate(i))throw new d(`The template for the component '${n}' is too large. Consider increasing 'cache.maxSize' in the config`);this.__cacheSize+=t.length*2+500,this.__compiledTemplatesMap.set(n,{fn:this.compile(t),size:i})}reset(){this.__config={...A},this.__compiledTemplatesMap.clear(),this.__currentContext=null,this.__cacheSize=0}createEntrySpaceForTemplate(n){if(this.__cacheSize+n<this.__config.cache.maxSize)return!0;if(n>this.__config.cache.maxSize)return!1;let t=this.__compiledTemplatesMap.entries().next().value;if(t){let[i,o]=t;this.__compiledTemplatesMap.delete(i),this.__cacheSize-=o.size}return this.createEntrySpaceForTemplate(n)}getDiagnostics(){let n=this.__config.cache.maxSize;return{bytesUsed:this.__cacheSize,bytesMax:n,readableUsed:`${(this.__cacheSize/1024/1024).toFixed(2)} MB`,readableMax:`${(n/1024/1024).toFixed(2)} MB`,totalEntries:this.__compiledTemplatesMap.size,percentFull:n>0?Math.min(100,Math.round(this.__cacheSize/n*100)):0,avgTemplateSize:this.__compiledTemplatesMap.size>0?Math.round(this.__cacheSize/this.__compiledTemplatesMap.size):0}}};var Oe=L;
|
|
13
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/construct-pointer.ts","../src/core/error.ts","../src/core/constants.ts","../src/utils/escape-fn.ts","../src/utils/validate-computed-prop.ts","../src/utils/validate-context.ts","../src/utils/get-line-and-column-nums.ts","../src/utils/get-line-snapshot.ts","../src/core/build.ts","../src/utils/get-token-type-words.ts","../src/core/generate-ast.ts","../src/core/parse.ts","../src/core/tokenize.ts","../src/core/compile.ts","../src/core/mutor.ts"],"sourcesContent":["import Mutor from \"./core/mutor\";\nexport default Mutor;\n","/**\n * Creates a visual text-based pointer `^`.\n * @param pos The position in the text to be pointed at.\n * @param offset The offset to the left to compensate for line numbering.\n * @returns\n */\nexport default function constructPointer(pos: number, offset: number) {\n // pos is the index in the text, offset is the width of \"Line | \"\n return `${\" \".repeat(pos + offset + 1)}^`;\n}\n","import constructPointer from \"../utils/construct-pointer\";\n\nexport class MutorError extends Error {\n public name = \"MutorError\";\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, MutorError.prototype);\n }\n}\n\nexport class MutorCompilerError extends MutorError {\n public name = \"MutorCompilerError\";\n\n constructor(\n message: string,\n line: number,\n lineText: string,\n column: number, // 0-indexed column from snapshot\n file: string,\n ) {\n // Dynamic gutter width for alignment\n const gutterWidth = line.toString().length + 2;\n let report = `${message}\\n\\n`;\n\n report += `at ${file}:${line}:${column + 1}\\n`;\n\n // Line snippet with gutter\n if (line > 1) {\n report += `${(line - 1).toString().padStart(gutterWidth - 2)} | ...\\n`;\n }\n\n report += `${line} | ${lineText}\\n`;\n // Visual Pointer\n report += constructPointer(column, gutterWidth);\n\n super(report);\n Object.setPrototypeOf(this, MutorCompilerError.prototype);\n }\n}\n","import type { MutorConfig } from \"../types/types\";\nimport { MutorError } from \"./error\";\n\nexport const keywords = new Set([\n \"for\",\n \"if\",\n \"else\",\n \"true\",\n \"false\",\n \"null\",\n \"undefined\",\n \"end\",\n \"in\",\n \"of\",\n]);\n\nexport const operators = new Set([\n \"::\", // Namespace access\n \"||\", // Or\n \"??\", // Nullish coalesce\n \"&&\", // And\n \"**\", // Power\n \"^\", // Bitwise XOr\n \"|\", // Bitwise Or\n \"&\", // Bitwise And\n \"!\", // Not\n \"-\", // Minus\n \"%\", // Modulus\n \"+\", // Plus\n \"*\", // Times\n \"/\", // Divide\n \">\", // Greater than\n \"<\", // Less than\n \">=\", // Greater or equal\n \"<=\", // Less or equal\n \"==\", // Strict equal\n \"!=\", // Strict not equal\n \">>\", // Bitwise right shift\n \"<<\", // Bitwise left shift\n \".\", // Property acess\n \"?.\", // Optional property access\n \"(\", // Open parentheses\n \")\", // Close parentheses\n \"[\", // Square open parentheses\n \"]\", // Square close parentheses\n \",\", // Comma\n \":\", // Column\n \"?\", // Ternary operator\n]);\n\nexport const logicalOperators = new Set([\"&&\", \"||\", \"??\"]);\n\nexport const equalityOperators = new Set([\"==\", \"!=\"]);\n\nexport const comparisonOperators = new Set([\">\", \"<\", \">=\", \"<=\"]);\n\nexport const bitwiseOperators = new Set([\">>\", \"<<\"]);\n\nexport const additiveOperators = new Set([\"+\", \"-\"]);\n\nexport const multiplicativeOperators = new Set([\"*\", \"/\", \"%\"]);\n\nexport const propertyAccessOperators = new Set([\".\", \"?.\", \"[\", \"::\"]);\n\nexport const unaryOperators = new Set([\"-\", \"+\", \"!\"]);\n\nexport const ESCAPE_MAP: Record<string, string> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nexport const defaultConfig: MutorConfig = {\n build: {\n include: new Set([\".html\", \".txt\"]),\n exclude: new Set([\"node_modules\", \".git\"]),\n },\n autoEscape: true,\n allowedProps: new Set(),\n forbiddenProps: new Set([\"__proto__\", \"constructor\", \"prototype\"]),\n allowFnCalls: false,\n delimiters: {\n closingTag: \"}}\",\n openingTag: \"{{\",\n openingTagEscape: \"\\\\\",\n whitespaceTrim: \"~\",\n },\n keepOpeningTagEscapeDelimiter: false,\n cache: {\n active: true,\n maxSize: 50 * 1024 * 1024, // 50MB\n },\n};\n\nexport const namespaces = {\n JSON: {\n stringify(value: any) {\n try {\n return JSON.stringify(value);\n } catch {\n throw new MutorError(\"JSON.stringify failed: invalid value\");\n }\n },\n\n parse(str: string) {\n if (typeof str !== \"string\") {\n throw new MutorError(\"JSON.parse expects a string\");\n }\n\n try {\n return JSON.parse(str);\n } catch {\n throw new MutorError(\"JSON.parse failed: invalid JSON string\");\n }\n },\n },\n\n Object: {\n keys(obj: Object) {\n if (!obj || typeof obj !== \"object\") {\n throw new MutorError(\"Object.keys expects an object\");\n }\n return Object.keys(obj);\n },\n\n values(obj: Object) {\n if (!obj || typeof obj !== \"object\") {\n throw new MutorError(\"Object.values expects an object\");\n }\n return Object.values(obj);\n },\n\n entries(obj: Object) {\n if (!obj || typeof obj !== \"object\") {\n throw new MutorError(\"Object.entries expects an object\");\n }\n return Object.entries(obj);\n },\n\n hasOwn(obj: Object, key: any) {\n if (!obj || typeof obj !== \"object\") {\n throw new MutorError(\"Object.hasOwn expects an object\");\n }\n return Object.hasOwn(obj, key);\n },\n\n freeze(obj: Object) {\n if (!obj || typeof obj !== \"object\") {\n throw new MutorError(\"Object.freeze expects an object\");\n }\n return Object.freeze(obj);\n },\n\n seal(obj: Object) {\n if (!obj || typeof obj !== \"object\") {\n throw new MutorError(\"Object.seal expects an object\");\n }\n return Object.seal(obj);\n },\n\n fromEntries(entries: any[]) {\n if (!Array.isArray(entries)) {\n throw new MutorError(\"Object.fromEntries expects an array\");\n }\n return Object.fromEntries(entries);\n },\n },\n\n Array: {\n isArray(value: any) {\n return Array.isArray(value);\n },\n\n from(value: any) {\n return Array.from(value);\n },\n },\n\n Number: {\n isFinite(value: number) {\n return Number.isFinite(value);\n },\n\n isNaN(value: any) {\n return Number.isNaN(value);\n },\n\n parseInt(value: string, radix = 10) {\n return Number.parseInt(value, radix);\n },\n\n parseFloat(value: string) {\n return Number.parseFloat(value);\n },\n },\n\n String: {\n fromCharCode(...args: number[]) {\n return String.fromCharCode(...args);\n },\n },\n\n Math: {\n abs(x: number) {\n return Math.abs(x);\n },\n\n floor(x: number) {\n return Math.floor(x);\n },\n\n ceil(x: number) {\n return Math.ceil(x);\n },\n\n round(x: number) {\n return Math.round(x);\n },\n\n max(...args: number[]) {\n return Math.max(...args);\n },\n\n min(...args: number[]) {\n return Math.min(...args);\n },\n\n random() {\n return Math.random(); // consider disabling in strict mode\n },\n },\n\n Date: {\n now() {\n return Date.now();\n },\n\n parse(str: string) {\n if (typeof str !== \"string\") {\n throw new MutorError(\"Date.parse expects a string\");\n }\n return Date.parse(str);\n },\n },\n\n Boolean: {\n valueOf(value: any) {\n return Boolean(value);\n },\n },\n};\n","import { ESCAPE_MAP } from \"../core/constants\";\n\n/**\n * Escapes HTML special characters in a string.\n * @param e The value to escape.\n * @returns The escaped string or the original value if not a string.\n */\nexport default function escapeFn(e: unknown): unknown {\n if (typeof e !== \"string\") return e;\n return /[&<>\"']/.test(e)\n ? e.replace(/[&<>\"']/g, (char) => ESCAPE_MAP[char])\n : e;\n}\n","import { MutorError } from \"../core/error\";\n\n/**\n * Validates access to computed properties against a whitelist and blacklist.\n * @param r The property name or index being accessed.\n * @param forbiddenProps A set of restricted property names.\n * @param allowedProps A set of explicitly permitted property names.\n * @returns The property name if valid.\n * @throws Error if access is forbidden.\n */\nexport default function validateComputedProp(\n r: string | number,\n forbiddenProps: Set<string | number>,\n allowedProps: Set<string | number>,\n): string | number {\n if (forbiddenProps.has(r) && !allowedProps.has(r)) {\n throw new MutorError(\n `Forbidden property access. Access to this computed property \"${r}\" is forbidden.`,\n );\n }\n return r;\n}\n","import { MutorError } from \"../core/error\";\n\nconst OBJECT = \"object\";\nexport const MUTOR_SAFE = Symbol(\"__mutor_safe_context\");\n\nexport default function validateContext(ctx: any) {\n // Allow non object contexts\n if (!ctx || typeof ctx !== OBJECT) {\n return ctx;\n }\n\n if (MUTOR_SAFE in ctx) {\n return ctx;\n }\n\n // vulnerability and prevent memory leaks across request lifecycles.\n const seen = new WeakSet();\n\n function walk(value: any, path = \"\") {\n if (!value || typeof value !== OBJECT) return value;\n\n if (seen.has(value)) return value;\n seen.add(value);\n\n // Block prototype pollution vectors early\n const proto = Object.getPrototypeOf(value);\n if (proto && proto !== Object.prototype && proto !== Array.prototype) {\n throw new MutorError(`Unsafe prototype detected at ${path || \"root\"}`);\n }\n\n // Arrays\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n value[i] = walk(value[i], `${path}[${i}]`);\n }\n return value;\n }\n\n // Maps\n if (value instanceof Map) {\n for (const [k, v] of value.entries()) {\n if (typeof k === OBJECT) walk(k, `${path}.mapKey`);\n value.set(k, walk(v, `${path}.mapValue`));\n }\n return value;\n }\n\n // Sets\n if (value instanceof Set) {\n const next = new Set();\n for (const v of value.values()) {\n next.add(walk(v, path));\n }\n value.clear();\n for (const v of next) value.add(v);\n return value;\n }\n\n // Plain object validation\n const descriptors = Object.getOwnPropertyDescriptors(value);\n\n for (const key of Object.keys(descriptors)) {\n const desc = descriptors[key];\n\n // Block getters/setters\n if (desc.get || desc.set) {\n throw new MutorError(`Getter/setter not allowed: ${path}.${key}`);\n }\n\n const prop = value[key];\n\n if (prop && typeof prop === OBJECT) {\n value[key] = walk(prop, `${path}.${key}`);\n }\n }\n\n return value;\n }\n\n const safeData = walk(ctx);\n\n if (safeData && typeof safeData === OBJECT) {\n Object.defineProperty(safeData, MUTOR_SAFE, {\n value: true,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n\n return safeData;\n}\n","/**\n * Counts the number of lines that comes before a given index, effectively returning the line and column numbers of the character at that index.\n * @param str The source string.\n * @param idx The index to find its line number.\n */\nexport default function getLineAndColumnNumbers(str: string, idx: number) {\n const lines = str.slice(0, idx).split(\"\\n\");\n const line = lines.length;\n // The index where the current line starts\n const lineIndex = str.lastIndexOf(\"\\n\", idx - 1) + 1;\n\n return { line, lineIndex };\n}\n","/**\n * Extracts the snapshot of a line from a given text.\n * @param str The source string.\n * @param lineIdx The index of the newline character to snap.\n * @param idx The index of point which caused the error.\n */\nexport default function getLineSnapshot(\n str: string,\n lineIdx: number,\n idx: number,\n) {\n const nextNewlineIdx = str.indexOf(\"\\n\", lineIdx);\n const line = str.slice(\n lineIdx,\n nextNewlineIdx === -1 ? undefined : nextNewlineIdx,\n );\n return { line, pos: idx - lineIdx };\n}\n","import { ExprType, LoopType } from \"../types/enums\";\nimport type {\n BuildContext,\n CallExpr,\n ElseIfExpr,\n Expr,\n ForExpr,\n IdentExpr,\n IfExpr,\n NamespaceExpr,\n PropAccessExpr,\n} from \"../types/types\";\nimport { MutorError } from \"./error\";\n\n/**\n * Builds JavaScript code from an AST.\n * Handles property access protection, scope-based ctx prefixing, control flow, and loops.\n * @param ast The abstract syntax tree\n * @param context The build context containing scope, forbidden/allowed properties\n * @returns Generated JavaScript code as a string\n */\nexport default function build(\n ast: Expr | any, // any to handle control flow nodes not yet in AST types\n context: BuildContext,\n): string {\n const { scope, forbiddenProps, allowedProps } = context;\n\n function prefixWithCtx(ident: string): string {\n return scope.includes(ident) ? ident : `ctx.${ident}`;\n }\n\n function buildExpr(expr: Expr): string {\n switch (expr.type) {\n case ExprType.END:\n return \"}\";\n\n case ExprType.NUMBER:\n return expr.value;\n\n case ExprType.STRING:\n return `\"${expr.value}\"`;\n\n case ExprType.BOOLEAN:\n return (expr as any).true ? \"true\" : \"false\";\n\n case ExprType.NULL:\n return \"null\";\n\n case ExprType.UNDEFINED:\n return \"undefined\";\n\n case ExprType.IDENT:\n return prefixWithCtx((expr as any).value);\n\n case ExprType.GROUP:\n return `(${buildExpr((expr as any).expr)})`;\n\n case ExprType.UNARY:\n return `${(expr as any).operator}${buildExpr((expr as any).expr)}`;\n\n case ExprType.BINARY:\n return `${buildExpr((expr as any).left)} ${(expr as any).operator} ${buildExpr((expr as any).right)}`;\n\n case ExprType.TERNARY:\n return `${buildExpr((expr as any).condition)} ? ${buildExpr((expr as any).left)} : ${buildExpr((expr as any).right)}`;\n\n case ExprType.PROP_ACCESS:\n return buildPropAccess(expr);\n\n case ExprType.CALL:\n return buildCall(expr);\n\n case ExprType.NAMESPACE:\n return buildNamespace(expr);\n\n case ExprType.FOR:\n return buildForLoop(expr);\n\n case ExprType.ELSE:\n return \"} else {\";\n\n case ExprType.IF:\n return buildIfBlock(expr);\n\n case ExprType.ELSE_IF:\n return buildElseIfBlock(expr);\n\n default:\n throw new MutorError(\n `Unsupported expression type: ${(expr as any).type}`,\n );\n }\n }\n\n function buildNamespace(expr: NamespaceExpr) {\n if (expr.left.type !== ExprType.IDENT) {\n throw {\n message: \"Invalid usage of namespace operator.\",\n pos: expr.pos,\n };\n }\n return `namespaces.${(expr.left as IdentExpr).value}.${(expr.right as IdentExpr).value}`;\n }\n\n function buildPropAccess(expr: PropAccessExpr): string {\n const left = buildExpr(expr.left);\n\n if (expr.bracketNotation) {\n // Bracket notation: evaluate the expression and check the resolved value at runtime\n const right = buildExpr(expr.right);\n const optionalChain = expr.optional ? \"?.\" : \"\";\n\n return expr.right.type !== ExprType.STRING &&\n expr.right.type !== ExprType.NUMBER\n ? `${left}${optionalChain}[${right}]`\n : `${left}${optionalChain}[validateComputedProps(${right}, allowedProps, forbiddenProps)]`;\n } else {\n // Dot notation: static property name - check at build time\n const propName = (expr.right as IdentExpr).value; // Assuming right is always IDENT in dot notation\n const optionalChain = expr.optional ? \"?.\" : \".\";\n\n // Block access to forbidden prototype properties at build time\n if (forbiddenProps.has(propName) && !allowedProps.has(propName)) {\n throw { message: \"Forbidden property access.\", pos: expr.right.pos };\n }\n\n return `${left}${optionalChain}${propName}`;\n }\n }\n\n function buildCall(expr: CallExpr): string {\n const func = buildExpr(expr.expr);\n const optionalChain = expr.optional ? \"?.\" : \"\";\n\n const args = (expr.args as Expr[])\n .map((arg: Expr) => buildExpr(arg))\n .join(\", \");\n\n return `${func}${optionalChain}(${args})`;\n }\n\n function buildForLoop(expr: ForExpr) {\n const { iterable, loopType, variable } = expr;\n return `for(const ${variable} ${loopType === LoopType.IN ? \"in\" : \"of\"} ${build(iterable, context)}){`;\n }\n\n function buildIfBlock(expr: IfExpr) {\n const { condition } = expr;\n return `if(${build(condition, context)}){`;\n }\n\n function buildElseIfBlock(expr: ElseIfExpr) {\n const { condition } = expr;\n return `}else if(${build(condition, context)}){`;\n }\n\n return buildExpr(ast);\n}\n","import { TokenType } from \"../types/enums\";\n\nexport function getTokenTypeWords(type: TokenType) {\n switch (type) {\n case TokenType.IDENT:\n return \"identifier\";\n\n case TokenType.KEYWORD:\n return \"keyword\";\n\n case TokenType.NUMBER:\n return \"number\";\n\n case TokenType.OPERATOR:\n return \"operator\";\n\n case TokenType.STRING:\n return \"string\";\n }\n}\n","import { ExprType, LoopType, TokenType } from \"../types/enums\";\nimport type {\n ElseExpr,\n ElseIfExpr,\n Expr,\n ForExpr,\n IfExpr,\n Token,\n} from \"../types/types\";\nimport { getTokenTypeWords } from \"../utils/get-token-type-words\";\nimport {\n additiveOperators,\n comparisonOperators,\n equalityOperators,\n multiplicativeOperators,\n propertyAccessOperators,\n unaryOperators,\n} from \"./constants\";\n\n/**\n * Generates an abstract syntax tree from a stream of tokens. Validating structure as it does so.\n * @param tokens The stream of tokens\n * @param config Configuration option\n * @returns\n */\nexport default function generateAst(\n tokens: Token[],\n config: { allowFnCalls: boolean },\n): Expr {\n let cursor = 0,\n generatingNamespace = false;\n\n /**\n * Asserts that a token at the cursor's current position is of the same type and value as the function arguments.\n * @param type The expected token's type\n * @param value THe expected token's value\n */\n function expectOrThrow(type: TokenType): Token;\n function expectOrThrow(type: TokenType, value: string): Token;\n function expectOrThrow(type: TokenType, value?: string): Token {\n const token = tokens[cursor];\n const lastToken = tokens[tokens.length - 1];\n\n if (!token) {\n throw {\n message: `Unexpected end of expression. Expected ${value ? `'${value}'` : `${type === TokenType.IDENT ? \"an\" : \"a\"} ${getTokenTypeWords(type)}`}.`,\n pos: lastToken.pos + lastToken.value.length - 1,\n };\n }\n\n if (token.type !== type) {\n throw {\n message: `Unexpected token type. Expected ${value ? `'${value}'` : getTokenTypeWords(type)} but got ${getTokenTypeWords(token.type)} instead.`,\n pos: token.pos,\n };\n }\n\n if (value !== undefined && token.value !== value) {\n throw {\n message: `Unexpected token '${token?.value}'. Expected ${type === TokenType.IDENT ? \"an\" : \"a\"} ${getTokenTypeWords(type)} instead.`,\n pos: token.pos,\n };\n }\n\n return tokens[cursor++];\n }\n\n /**\n * Parses a for loop contructor\n * Handles `{{ for prop in obj }}` and `{{ for item of arr }}`\n */\n function parseForLoop(): ForExpr {\n const pos = tokens[cursor - 1].pos;\n // Extract the variable\n const variable = expectOrThrow(TokenType.IDENT).value;\n let token: Token;\n\n try {\n token = expectOrThrow(TokenType.KEYWORD, \"in\");\n } catch {\n token = expectOrThrow(TokenType.KEYWORD, \"of\");\n }\n\n const loopType = token.value === \"in\" ? LoopType.IN : LoopType.OF;\n const iterable = parseTernaryExpr();\n\n return { type: ExprType.FOR, loopType, iterable, variable, pos };\n }\n\n /**\n * Parses an if expression.\n */\n function parseIfExpression(): IfExpr {\n const condition = parseTernaryExpr();\n return { condition, pos: condition.pos, type: ExprType.IF };\n }\n\n /**\n * Parses an `else` or `else if` expression.\n */\n function parseElseExpression(): ElseExpr | ElseIfExpr {\n const pos = tokens[cursor - 1].pos;\n\n try {\n // Try to parse `else if`\n expectOrThrow(TokenType.KEYWORD, \"if\");\n return { ...parseIfExpression(), type: ExprType.ELSE_IF, pos };\n } catch {\n return { type: ExprType.ELSE, pos };\n }\n }\n\n /**\n * Extracts the arguments of a function call.\n * Parses comma-separated expressions until the closing parenthesis is reached.\n * Returns an array of parsed argument expressions, which may be empty for calls with no arguments.\n */\n function extractFnArgs() {\n const args: Expr[] = [];\n\n const emptyArgs =\n tokens[cursor]?.type === TokenType.OPERATOR &&\n tokens[cursor]?.value === \")\";\n\n if (emptyArgs) {\n return args;\n }\n\n // Consume the first argument;\n args.push(parseTernaryExpr());\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n tokens[cursor]?.value === \",\" &&\n tokens[cursor]?.value !== \")\"\n ) {\n cursor++; // Skip the comma operator ','\n args.push(parseTernaryExpr());\n }\n\n return args;\n }\n\n /**\n * Parses primary expressions whose values can be resolved during compilation.\n * Handles literals (numbers, strings, booleans), keywords (null, undefined),\n * identifiers, parenthesized expressions, and unary prefix operators.\n * This is the base level of the expression parsing hierarchy.\n */\n function parsePrimaryExpr(): Expr {\n const token = tokens[cursor++];\n\n if (token?.type === TokenType.NUMBER) {\n return { type: ExprType.NUMBER, value: token.value, pos: token.pos };\n }\n\n if (token?.type === TokenType.STRING) {\n return { type: ExprType.STRING, value: token.value, pos: token.pos };\n }\n\n if (token?.type === TokenType.KEYWORD) {\n if (token.value === \"for\" && cursor === 1) {\n return parseForLoop();\n }\n\n if (token.value === \"true\" || token.value === \"false\") {\n return {\n type: ExprType.BOOLEAN,\n true: token.value === \"true\",\n pos: token.pos,\n };\n }\n\n if (token.value === \"undefined\") {\n return { type: ExprType.UNDEFINED, pos: token.pos };\n }\n\n if (token.value === \"null\") {\n return { type: ExprType.NULL, pos: token.pos };\n }\n\n if (token.value === \"end\" && tokens.length === 1) {\n return { type: ExprType.END, pos: token.pos };\n }\n\n if (token.value === \"if\" && cursor === 1) {\n return parseIfExpression();\n }\n\n if (token.value === \"else\" && cursor === 1) {\n return parseElseExpression();\n }\n }\n\n if (token?.type === TokenType.IDENT) {\n return { type: ExprType.IDENT, value: token.value, pos: token.pos };\n }\n\n if (token?.type === TokenType.OPERATOR && token.value === \"(\") {\n const expr = parseTernaryExpr();\n expectOrThrow(TokenType.OPERATOR, \")\");\n return { type: ExprType.GROUP, expr, pos: token.pos };\n }\n\n if (token?.type === TokenType.OPERATOR && unaryOperators.has(token.value)) {\n const operator = token.value;\n const expr = parseTernaryExpr();\n return { type: ExprType.UNARY, operator, expr, pos: token.pos };\n }\n\n if (cursor > tokens.length) {\n throw {\n message: `Unexpected end of expression.`,\n pos: tokens[tokens.length - 1].pos,\n };\n }\n\n throw {\n message: `Unexpected token '${token?.value}'.`,\n pos: token.pos,\n };\n }\n\n /**\n * Parses property access expressions or function calls.\n * Handles member access via dot notation (.prop), bracket notation ([expr]),\n * optional chaining (?.), optional bracket notation (?.[expr]), namespace access (::),\n * and function calls (() and ?.()).\n * This parser left-associates sequential property accesses and function calls.\n * @example\n * {{ obj?.prop }}\n * {{ obj.prop }}\n * {{ obj?.['prop']?.() }}\n */\n function parsePropertyAccess(): Expr {\n let left = parsePrimaryExpr();\n\n while (tokens[cursor]) {\n const token = tokens[cursor];\n\n // Check for function call: (\n if (token?.type === TokenType.OPERATOR && token?.value === \"(\") {\n cursor++; // Skip the opening parentheses\n\n if (!generatingNamespace && !config.allowFnCalls) {\n throw {\n message: \"Function calls are not allowed.\",\n pos: tokens[cursor - 1].pos,\n };\n }\n\n const args = extractFnArgs();\n expectOrThrow(TokenType.OPERATOR, \")\");\n\n left = {\n type: ExprType.CALL,\n expr: left,\n args,\n pos: tokens[cursor - 1].pos,\n };\n }\n // Check for optional call: ?.(\n else if (\n token?.type === TokenType.OPERATOR &&\n token?.value === \"?.\" &&\n tokens[cursor + 1]?.type === TokenType.OPERATOR &&\n tokens[cursor + 1]?.value === \"(\"\n ) {\n cursor++; // Skip ?.\n cursor++; // Skip (\n\n if (!generatingNamespace && !config.allowFnCalls) {\n throw {\n message: \"Function calls are not allowed.\",\n pos: tokens[cursor - 1].pos,\n };\n }\n\n const args = extractFnArgs();\n expectOrThrow(TokenType.OPERATOR, \")\");\n\n left = {\n type: ExprType.CALL,\n expr: left,\n args,\n optional: true,\n pos: tokens[cursor - 1].pos,\n };\n }\n // Check for property access: . or ?. or [ or ::\n // Handles all forms of member access with optional chaining support\n else if (\n token?.type === TokenType.OPERATOR &&\n propertyAccessOperators.has(token?.value)\n ) {\n const isNamespace = token?.value === \"::\";\n const isBracketNotation = token?.value === \"[\";\n const isOptional = token?.value === \"?.\";\n\n cursor++; // Skip operator\n\n // Enforce <IDENT>::<IDENT> syntax for namespaces\n if (\n isNamespace &&\n (tokens[cursor - 2]?.type !== TokenType.IDENT ||\n tokens[cursor]?.type !== TokenType.IDENT)\n ) {\n throw {\n message: `Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${tokens[cursor - 2]?.value}::${tokens[cursor]?.value}' instead.`,\n pos: tokens[cursor]?.pos,\n };\n }\n\n if (isNamespace) {\n generatingNamespace = true;\n\n const right = parsePrimaryExpr();\n\n left = {\n type: ExprType.NAMESPACE,\n left,\n right,\n pos: tokens[cursor - 1].pos,\n };\n } else if (isBracketNotation) {\n const right = parseTernaryExpr();\n expectOrThrow(TokenType.OPERATOR, \"]\");\n\n left = {\n type: ExprType.PROP_ACCESS,\n right,\n left,\n bracketNotation: true,\n pos: tokens[cursor - 1].pos,\n };\n } else if (isOptional) {\n // Check if optional bracket notation: ?.[\n if (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n tokens[cursor]?.value === \"[\"\n ) {\n cursor++; // Skip the opening bracket '['\n const right = parseTernaryExpr();\n expectOrThrow(TokenType.OPERATOR, \"]\");\n\n left = {\n type: ExprType.PROP_ACCESS,\n left,\n right,\n bracketNotation: true,\n optional: true,\n pos: tokens[cursor - 1].pos,\n };\n } else {\n const right = parsePrimaryExpr();\n left = {\n type: ExprType.PROP_ACCESS,\n left,\n right,\n optional: true,\n pos: tokens[cursor - 1].pos,\n };\n }\n } else {\n // Regular dot notation: .\n const right = parsePrimaryExpr();\n left = {\n type: ExprType.PROP_ACCESS,\n left,\n right,\n pos: tokens[cursor - 1].pos,\n };\n }\n } else {\n break;\n }\n }\n\n generatingNamespace = false;\n return left;\n }\n\n /**\n * Parses multiplicative expressions.\n * Handles operators: *, /, % with left-to-right associativity.\n * Higher precedence than additive operators.\n * @example\n * {{ a * b }}\n * {{ 1 / 2 }}\n * {{ 20 % 3 }}\n */\n function parseMultiplicativeExpr(): Expr {\n let left = parsePropertyAccess();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n multiplicativeOperators.has(tokens[cursor]?.value)\n ) {\n const operator = tokens[cursor++].value;\n const right = parsePropertyAccess();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses additive expressions.\n * Handles operators: +, - with left-to-right associativity.\n * Higher precedence than comparison operators, lower than multiplicative.\n * @example\n * {{ a + b }}\n * {{ 1 - 2 }}\n */\n function parseAdditiveExpr(): Expr {\n let left = parseMultiplicativeExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n additiveOperators.has(tokens[cursor]?.value)\n ) {\n const operator = tokens[cursor++].value;\n const right = parseMultiplicativeExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses bitwise shift expressions.\n * Handles operators: >>, <<, >>> with left-to-right associativity.\n * Higher precedence than comparison operators, lower than additive.\n * @example\n * {{ 22 >> 3 }}\n * {{ 12 << 3 }}\n */\n function parseBitwiseExpr(): Expr {\n let left = parseAdditiveExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n comparisonOperators.has(tokens[cursor]?.value)\n ) {\n const operator = tokens[cursor++].value;\n const right = parseAdditiveExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses comparison expressions.\n * Handles operators: <, >, <=, >= with left-to-right associativity.\n * Lower precedence than additive/bitwise operators, higher than equality.\n */\n function parseComparisonExpr(): Expr {\n let left = parseBitwiseExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n comparisonOperators.has(tokens[cursor]?.value)\n ) {\n const operator = tokens[cursor++].value;\n const right = parseBitwiseExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses equality expressions.\n * Handles operators: ==, !=, ===, !== with left-to-right associativity.\n * Lower precedence than comparison operators, higher than logical operators.\n */\n function parseEqualityExpr(): Expr {\n let left = parseComparisonExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n equalityOperators.has(tokens[cursor]?.value)\n ) {\n const operator = tokens[cursor++].value;\n const right = parseComparisonExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses logical OR expressions.\n * Handles operator: || with left-to-right associativity.\n * Lower precedence than logical AND, higher than ternary conditional.\n * Short-circuits on truthy left operand.\n */\n function parseLogicalOrExpr(): Expr {\n let left = parseLogicalAndExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n tokens[cursor]?.value === \"||\"\n ) {\n const operator = tokens[cursor++].value;\n const right = parseLogicalAndExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses logical AND expressions.\n * Handles operator: && with left-to-right associativity.\n * Lower precedence than equality operators, higher than logical OR.\n * Short-circuits on falsy left operand.\n */\n function parseLogicalAndExpr(): Expr {\n let left = parseNullishCoalesceExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n tokens[cursor]?.value === \"&&\"\n ) {\n const operator = tokens[cursor++].value;\n const right = parseNullishCoalesceExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses nullish coalescing expressions.\n * Handles operator: ?? with left-to-right associativity.\n * Returns left operand if not null/undefined, otherwise returns right operand.\n * Lower precedence than logical AND, higher than logical OR.\n */\n function parseNullishCoalesceExpr(): Expr {\n let left = parseEqualityExpr();\n\n while (\n tokens[cursor]?.type === TokenType.OPERATOR &&\n tokens[cursor]?.value === \"??\"\n ) {\n const operator = tokens[cursor++].value;\n const right = parseEqualityExpr();\n left = {\n type: ExprType.BINARY,\n left,\n right,\n operator,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n return left;\n }\n\n /**\n * Parses ternary conditional expressions.\n * Handles operator: ? : with right-to-left associativity.\n * Lowest precedence of all operators, allowing nested ternaries on the right side.\n * Format: condition ? trueExpr : falseExpr\n */\n function parseTernaryExpr(): Expr {\n const condition = parseLogicalOrExpr();\n\n if (\n tokens[cursor]?.type !== TokenType.OPERATOR ||\n tokens[cursor]?.value !== \"?\"\n ) {\n return condition;\n }\n\n cursor++; // consume ?\n const left = parseTernaryExpr();\n expectOrThrow(TokenType.OPERATOR, \":\");\n const right = parseTernaryExpr();\n\n return {\n type: ExprType.TERNARY,\n left,\n right,\n condition,\n pos: tokens[cursor - 1].pos,\n };\n }\n\n const ast = parseTernaryExpr();\n return ast;\n}\n","import type { MutorConfig } from \"../types/types\";\n\n/**\n * Parses a given template block by analyzing it for syntax correctness and whitespace control.\n * @param templateBlock A block of template code (`{{~ for user of users ~}}`)\n */\nexport default function parse(\n templateBlock: string,\n { delimiters }: Pick<MutorConfig, \"delimiters\">,\n) {\n const openingTagWithWhitespaceCtrl = `${delimiters.openingTag}${delimiters.whitespaceTrim}`;\n const closingTagWithWhitespaceCtrl = `${delimiters.whitespaceTrim}${delimiters.closingTag}`;\n\n const leftTrim = templateBlock.startsWith(openingTagWithWhitespaceCtrl);\n const rightTrim = templateBlock.endsWith(closingTagWithWhitespaceCtrl);\n\n const inner = templateBlock.slice(\n leftTrim\n ? openingTagWithWhitespaceCtrl.length\n : delimiters.openingTag.length,\n templateBlock.length -\n (rightTrim\n ? closingTagWithWhitespaceCtrl.length\n : delimiters.closingTag.length),\n );\n\n const trimmed = inner.trim();\n const isBlock =\n trimmed.startsWith(\"for\") ||\n trimmed.startsWith(\"if\") ||\n trimmed.startsWith(\"else\");\n const requiresBlockClose =\n trimmed.startsWith(\"for\") || trimmed.startsWith(\"if\");\n const isBlockEnd = trimmed === \"end\";\n const hasContext = trimmed.startsWith(\"for\");\n\n return {\n leftTrim,\n rightTrim,\n inner,\n isBlock,\n isBlockEnd,\n hasContext,\n requiresBlockClose,\n };\n}\n","import { TokenType } from \"../types/enums\";\nimport type { Token } from \"../types/types\";\nimport { keywords, operators } from \"./constants\";\n\n/**\n * Converts a given expression to a stream of allowed tokens.\n * @param expr A code expression (e.g `for user of users`).\n */\nexport default function tokenize(expr: string) {\n let cursor = 0,\n char = \"\";\n const tokens: Token[] = [];\n\n function accumulateKeywordOrIdentifier() {\n let buffer = \"\";\n if (/[a-zA-Z$_]/.test(char)) {\n let j = cursor;\n while (/[a-zA-Z$_0-9]/.test(expr[j]) && j < expr.length) {\n buffer += expr[j];\n j++;\n }\n\n tokens.push({\n type: keywords.has(buffer) ? TokenType.KEYWORD : TokenType.IDENT,\n value: buffer,\n pos: cursor,\n });\n\n cursor = j;\n char = expr[cursor];\n }\n }\n\n function accumulateStr() {\n let buffer = \"\";\n if (char === '\"' || char === \"'\" || char === \"`\") {\n let j = cursor + 1;\n\n while (expr[j] !== char && j < expr.length) {\n buffer += expr[j];\n j++;\n }\n\n if (j > expr.length) {\n throw { pos: cursor, message: `Found string without closing quote.` };\n }\n\n tokens.push({ type: TokenType.STRING, value: buffer, pos: cursor });\n cursor = j;\n }\n }\n\n function accumulateNumber() {\n if (/[0-9]/.test(char)) {\n let j = cursor,\n buffer = \"\";\n\n while (/[0-9.oxe]/.test(expr[j]) && j < expr.length) {\n buffer += expr[j];\n j++;\n }\n\n const numVal = Number(buffer);\n const isNan = Number.isNaN(numVal);\n\n if (isNan) {\n throw { pos: cursor, message: \"Found invalid number literal.\" };\n }\n\n tokens.push({ type: TokenType.NUMBER, value: `${numVal}`, pos: cursor });\n cursor = j - 1;\n char = expr[cursor];\n }\n }\n\n function accumulateOperator() {\n const op = `${char}${expr[cursor + 1]}`;\n if (operators.has(op)) {\n tokens.push({ type: TokenType.OPERATOR, value: op, pos: cursor });\n cursor++;\n return;\n }\n\n if (operators.has(char)) {\n tokens.push({ type: TokenType.OPERATOR, value: char, pos: cursor });\n return;\n }\n }\n\n while (cursor < expr.length) {\n char = expr[cursor];\n\n accumulateNumber();\n accumulateKeywordOrIdentifier();\n accumulateStr();\n accumulateOperator();\n\n if (\n !/[a-zA-Z$_0-9\\s\\t\\r\\n'\"`]/.test(char) &&\n !operators.has(char) &&\n !operators.has(expr[cursor - 1] + char)\n ) {\n throw {\n message: `Unexpected token '${char}' in expression.`,\n pos: cursor,\n };\n }\n\n cursor++;\n }\n\n return tokens;\n}\n","import { BlockType } from \"../types/enums\";\nimport type { CompileMetadata, ForExpr, MutorConfig } from \"../types/types\";\nimport getLineAndColumnNumbers from \"../utils/get-line-and-column-nums\";\nimport getLineSnapshot from \"../utils/get-line-snapshot\";\nimport build from \"./build\";\nimport { MutorCompilerError } from \"./error\";\nimport generateAst from \"./generate-ast\";\nimport parse from \"./parse\";\nimport tokenize from \"./tokenize\";\n\nexport default function compile(\n src: string,\n config: MutorConfig,\n meta: CompileMetadata,\n) {\n const scope: string[] = [];\n const blockOpeningStack: { type: BlockType; pos: number }[] = [];\n const {\n delimiters,\n keepOpeningTagEscapeDelimiter,\n allowFnCalls,\n allowedProps,\n forbiddenProps,\n autoEscape,\n } = config;\n\n // Whitespace control state\n let trimNext = false,\n cursor = 0,\n body = `let acc=\"\";`;\n\n while (cursor < src.length) {\n const templateOpenTagIdx = src.indexOf(delimiters.openingTag, cursor);\n\n // Handle Final Text Chunk\n if (templateOpenTagIdx === -1) {\n let lastChunk = src.slice(cursor);\n if (trimNext) lastChunk = lastChunk.trimStart();\n if (lastChunk) body += `acc+=\\`${lastChunk}\\`;`;\n break;\n }\n\n // Escape Logic\n function isEscaped() {\n let j = templateOpenTagIdx,\n count = 0;\n while (\n j >= delimiters.openingTagEscape.length &&\n src.slice(j - delimiters.openingTagEscape.length, j) ===\n delimiters.openingTagEscape\n ) {\n count++;\n j -= delimiters.openingTagEscape.length;\n }\n return count % 2 === 1;\n }\n\n if (isEscaped()) {\n let escapedChunk = src.slice(\n cursor,\n keepOpeningTagEscapeDelimiter\n ? templateOpenTagIdx + delimiters.openingTagEscape.length + 1\n : templateOpenTagIdx - delimiters.openingTag.length + 1,\n );\n\n if (trimNext) {\n escapedChunk = escapedChunk.trimStart();\n trimNext = false;\n }\n\n body += `acc+=\\`${escapedChunk}\\`;`;\n if (!keepOpeningTagEscapeDelimiter)\n body += `acc+=\\`${delimiters.openingTag}\\`;`;\n\n cursor = templateOpenTagIdx + delimiters.openingTag.length;\n continue;\n }\n\n // Parse Tag Metadata (to check for leftTrim BEFORE processing rawText)\n const templateEndTagIdx = src.indexOf(\n delimiters.closingTag,\n templateOpenTagIdx,\n );\n\n if (templateEndTagIdx === -1) {\n const { line, lineIndex } = getLineAndColumnNumbers(\n src,\n templateOpenTagIdx,\n );\n\n const { line: lineText, pos } = getLineSnapshot(\n src,\n lineIndex,\n templateOpenTagIdx,\n );\n\n throw new MutorCompilerError(\n \"No closing tag found.\",\n line,\n lineText,\n pos,\n meta.path,\n );\n }\n\n const template = src.slice(\n templateOpenTagIdx,\n templateEndTagIdx + delimiters.closingTag.length,\n );\n const {\n inner,\n leftTrim,\n rightTrim,\n isBlock,\n isBlockEnd,\n hasContext,\n requiresBlockClose,\n } = parse(template, { delimiters });\n\n // Process Raw Text (between cursor and current tag)\n let rawText = src.slice(cursor, templateOpenTagIdx);\n if (rawText) {\n if (trimNext) {\n rawText = rawText.trimStart();\n }\n\n if (leftTrim) {\n rawText = rawText.trimEnd();\n }\n\n if (rawText) {\n body += `acc+=\\`${rawText}\\`;`;\n }\n }\n\n // Reset after use\n trimNext = false;\n\n cursor = templateEndTagIdx + delimiters.closingTag.length;\n\n try {\n const tokens = tokenize(inner);\n const ast = generateAst(tokens, { allowFnCalls });\n\n if (isBlock && requiresBlockClose && hasContext) {\n scope.push((ast as ForExpr).variable);\n blockOpeningStack.push({\n type: BlockType.LOOP,\n pos: templateOpenTagIdx,\n });\n } else if (isBlock && requiresBlockClose && !hasContext) {\n blockOpeningStack.push({\n type: BlockType.NON_LOOP,\n pos: templateOpenTagIdx,\n });\n }\n\n if (isBlockEnd) {\n const lastBlockOpened = blockOpeningStack.pop();\n if (lastBlockOpened?.type === BlockType.LOOP) scope.pop();\n if (lastBlockOpened === undefined)\n throw { message: \"Unexpected end of block\", pos: templateOpenTagIdx };\n }\n\n const js = build(ast, { allowedProps, forbiddenProps, scope });\n\n if (isBlock || isBlockEnd) {\n body += js;\n } else {\n body += autoEscape ? `acc+=escapeFn(${js});` : `acc+=${js};`;\n }\n\n // Set state for the NEXT raw text chunk\n if (rightTrim) trimNext = true;\n } catch (e) {\n const { message, pos: relPos } = e as { message: string; pos: number };\n const { line, lineIndex } = getLineAndColumnNumbers(\n src,\n templateOpenTagIdx,\n );\n const { line: lineText, pos } = getLineSnapshot(\n src,\n lineIndex,\n templateOpenTagIdx,\n );\n throw new MutorCompilerError(\n message,\n line,\n lineText,\n pos +\n relPos +\n (leftTrim\n ? delimiters.openingTag.length + delimiters.whitespaceTrim.length\n : delimiters.openingTag.length),\n meta.path,\n );\n }\n }\n\n if (blockOpeningStack.length) {\n const lastPos = blockOpeningStack.pop()?.pos as number;\n const { line, lineIndex } = getLineAndColumnNumbers(src, lastPos);\n const { line: lineText, pos } = getLineSnapshot(src, lineIndex, lastPos);\n throw new MutorCompilerError(\n \"Unclosed block detected.\",\n line,\n lineText,\n pos + delimiters.openingTag.length,\n meta.path,\n );\n }\n\n body += `return acc;`;\n return new Function(\n \"ctx\",\n \"namespaces\",\n \"allowedProps\",\n \"forbiddenProps\",\n \"escapeFn\",\n \"validateComputedProps\",\n body,\n );\n}\n","import type { MutorConfig, PartialMutorConfig } from \"../types/types\";\nimport escapeFn from \"../utils/escape-fn\";\nimport validateComputedProp from \"../utils/validate-computed-prop\";\nimport validateContext from \"../utils/validate-context\";\nimport compile from \"./compile\";\nimport { defaultConfig, namespaces } from \"./constants\";\nimport { MutorError } from \"./error\";\n\nexport default class Mutor {\n protected __currentRenderedPath = \"\";\n protected __includeStack = new Set<string>();\n protected __cacheSize = 0;\n protected __config: MutorConfig = { ...defaultConfig };\n protected __compiledTemplatesMap: Map<\n string,\n { fn: Function; size: number }\n > = new Map();\n protected __currentContext: any = null;\n protected __namespaces: Record<any, any> = {\n ...namespaces,\n Mutor: {\n include: (path: string, ctx: Record<any, any>) => {\n if (this.__includeStack.has(path)) {\n throw new MutorError(\n `Circular include detected:\\n${Array.from(this.__includeStack).join(\"\\n\")}\\n${path}`,\n );\n }\n\n try {\n this.__includeStack.add(path);\n return this.renderComponent(path, ctx ?? this.__currentContext);\n } finally {\n this.__includeStack.delete(path);\n }\n },\n },\n };\n\n constructor(config: PartialMutorConfig) {\n this.addConfig(config);\n // Provide access to the currenct context via template\n Object.defineProperty(this.__namespaces.Mutor, \"$$context\", {\n get: () => {\n return this.__currentContext;\n },\n });\n }\n\n addConfig(conf: PartialMutorConfig): MutorConfig {\n const {\n autoEscape,\n delimiters: overrideDelimeters,\n allowedProps,\n forbiddenProps,\n keepOpeningTagEscapeDelimiter,\n allowFnCalls,\n cache,\n build,\n } = conf;\n\n this.__config = {\n build: {\n include: new Set([\n ...defaultConfig.build.include,\n ...(build?.include || []),\n ]),\n exclude: new Set([\n ...defaultConfig.build.exclude,\n ...(build?.exclude || []),\n ]),\n },\n autoEscape: autoEscape === true ? true : autoEscape !== false,\n allowedProps: allowedProps || new Set(),\n allowFnCalls: !!allowFnCalls,\n cache: { ...defaultConfig.cache, ...(cache || {}) },\n forbiddenProps: forbiddenProps || new Set(),\n keepOpeningTagEscapeDelimiter:\n keepOpeningTagEscapeDelimiter === true\n ? true\n : keepOpeningTagEscapeDelimiter !== false,\n delimiters: {\n ...defaultConfig.delimiters,\n ...(overrideDelimeters || {}),\n },\n };\n\n return this.__config;\n }\n\n restoreDefaultConfig() {\n this.__config = { ...defaultConfig };\n return this.__config;\n }\n\n compile(template: string, path = \"anonymous\"): Function {\n return compile(template, this.__config, { path });\n }\n\n render(template: string, context: any): string {\n const prevContext = this.__currentContext;\n\n if (prevContext !== context) {\n this.__currentContext = context;\n }\n\n const result = this.compile(template)(\n validateContext(context),\n this.__namespaces,\n this.__config.allowedProps,\n this.__config.forbiddenProps,\n escapeFn,\n validateComputedProp,\n );\n\n this.__currentContext = prevContext;\n return result;\n }\n\n renderComponent(identifier: string, context: any): string {\n if (!this.__compiledTemplatesMap.has(identifier)) {\n throw new MutorError(\n `No template exists with the identifier '${identifier}'`,\n );\n }\n\n const prevRenderComponentIdentifier = this.__currentRenderedPath;\n const prevContext = this.__currentContext;\n const compiled = this.__compiledTemplatesMap.get(identifier)!;\n\n this.__currentContext = context;\n this.__currentRenderedPath = identifier;\n\n const result = compiled.fn(\n validateContext(context),\n this.__namespaces,\n this.__config.allowedProps,\n this.__config.forbiddenProps,\n escapeFn,\n validateComputedProp,\n );\n\n this.__currentContext = prevContext;\n this.__currentRenderedPath = prevRenderComponentIdentifier;\n\n return result;\n }\n\n registerComponent(identifier: string, template: string) {\n const templateSize = template.length * 2 + 500;\n\n if (this.__cacheSize + templateSize > this.__config.cache.maxSize) {\n if (!this.createEntrySpaceForTemplate(templateSize)) {\n throw new MutorError(\n `The template for the component '${identifier}' is too large. Consider increasing 'cache.maxSize' in the config`,\n );\n }\n }\n\n this.__cacheSize += template.length * 2 + 500; // Approximate byte size\n this.__compiledTemplatesMap.set(identifier, {\n fn: this.compile(template),\n size: templateSize,\n });\n }\n\n reset() {\n this.__config = { ...defaultConfig };\n this.__compiledTemplatesMap.clear();\n this.__currentContext = null;\n this.__cacheSize = 0;\n }\n\n protected createEntrySpaceForTemplate(targetSize: number): boolean {\n if (this.__cacheSize + targetSize < this.__config.cache.maxSize) {\n return true;\n }\n\n if (targetSize > this.__config.cache.maxSize) {\n return false;\n }\n\n const firstEntry = this.__compiledTemplatesMap.entries().next().value;\n\n if (firstEntry) {\n const [oldestKey, oldestData] = firstEntry;\n this.__compiledTemplatesMap.delete(oldestKey);\n this.__cacheSize -= oldestData.size;\n }\n\n return this.createEntrySpaceForTemplate(targetSize);\n }\n\n public getDiagnostics() {\n const maxSize = this.__config.cache.maxSize;\n\n return {\n bytesUsed: this.__cacheSize,\n bytesMax: maxSize,\n readableUsed: `${(this.__cacheSize / 1024 / 1024).toFixed(2)} MB`,\n readableMax: `${(maxSize / 1024 / 1024).toFixed(2)} MB`,\n totalEntries: this.__compiledTemplatesMap.size,\n percentFull:\n maxSize > 0\n ? Math.min(100, Math.round((this.__cacheSize / maxSize) * 100))\n : 0,\n avgTemplateSize:\n this.__compiledTemplatesMap.size > 0\n ? Math.round(this.__cacheSize / this.__compiledTemplatesMap.size)\n : 0,\n };\n }\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,aAAAE,KAAA,eAAAC,GAAAH,ICMe,SAARI,EAAkCC,EAAaC,EAAgB,CAEpE,MAAO,GAAG,IAAI,OAAOD,EAAMC,EAAS,CAAC,CAAC,GACxC,CCPO,IAAMC,EAAN,MAAMC,UAAmB,KAAM,CAEpC,YAAYC,EAAiB,CAC3B,MAAMA,CAAO,EAFf,KAAO,KAAO,aAGZ,OAAO,eAAe,KAAMD,EAAW,SAAS,CAClD,CACF,EAEaE,EAAN,MAAMC,UAA2BJ,CAAW,CAGjD,YACEE,EACAG,EACAC,EACAC,EACAC,EACA,CAEA,IAAMC,EAAcJ,EAAK,SAAS,EAAE,OAAS,EACzCK,EAAS,GAAGR,CAAO;AAAA;AAAA,EAEvBQ,GAAU,MAAMF,CAAI,IAAIH,CAAI,IAAIE,EAAS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pC,MAAO,CACL,UAAW,KAAK,YAChB,SAAUA,EACV,aAAc,IAAI,KAAK,YAAc,KAAO,MAAM,QAAQ,CAAC,CAAC,MAC5D,YAAa,IAAIA,EAAU,KAAO,MAAM,QAAQ,CAAC,CAAC,MAClD,aAAc,KAAK,uBAAuB,KAC1C,YACEA,EAAU,EACN,KAAK,IAAI,IAAK,KAAK,MAAO,KAAK,YAAcA,EAAW,GAAG,CAAC,EAC5D,EACN,gBACE,KAAK,uBAAuB,KAAO,EAC/B,KAAK,MAAM,KAAK,YAAc,KAAK,uBAAuB,IAAI,EAC9D,CACR,CACF,CACF,EflNA,IAAOC,GAAQC","names":["index_exports","__export","index_default","__toCommonJS","constructPointer","pos","offset","MutorError","_MutorError","message","MutorCompilerError","_MutorCompilerError","line","lineText","column","file","gutterWidth","report","constructPointer","keywords","operators","equalityOperators","comparisonOperators","additiveOperators","multiplicativeOperators","propertyAccessOperators","unaryOperators","ESCAPE_MAP","defaultConfig","namespaces","value","MutorError","str","obj","key","entries","radix","args","x","escapeFn","char","ESCAPE_MAP","validateComputedProp","r","forbiddenProps","allowedProps","MutorError","OBJECT","MUTOR_SAFE","validateContext","ctx","seen","walk","value","path","proto","MutorError","i","k","v","next","descriptors","key","desc","prop","safeData","getLineAndColumnNumbers","str","idx","line","lineIndex","getLineSnapshot","str","lineIdx","idx","nextNewlineIdx","build","ast","context","scope","forbiddenProps","allowedProps","prefixWithCtx","ident","buildExpr","expr","buildPropAccess","buildCall","buildNamespace","buildForLoop","buildIfBlock","buildElseIfBlock","MutorError","left","right","optionalChain","propName","func","args","arg","iterable","loopType","variable","condition","getTokenTypeWords","type","generateAst","tokens","config","cursor","generatingNamespace","expectOrThrow","type","value","token","lastToken","getTokenTypeWords","parseForLoop","pos","variable","loopType","iterable","parseTernaryExpr","parseIfExpression","condition","parseElseExpression","extractFnArgs","args","parsePrimaryExpr","expr","unaryOperators","operator","parsePropertyAccess","left","propertyAccessOperators","isNamespace","isBracketNotation","isOptional","right","parseMultiplicativeExpr","multiplicativeOperators","parseAdditiveExpr","additiveOperators","parseBitwiseExpr","comparisonOperators","parseComparisonExpr","parseEqualityExpr","equalityOperators","parseLogicalOrExpr","parseLogicalAndExpr","parseNullishCoalesceExpr","parse","templateBlock","delimiters","openingTagWithWhitespaceCtrl","closingTagWithWhitespaceCtrl","leftTrim","rightTrim","inner","trimmed","isBlock","requiresBlockClose","isBlockEnd","hasContext","tokenize","expr","cursor","char","tokens","accumulateKeywordOrIdentifier","buffer","j","keywords","accumulateStr","accumulateNumber","numVal","accumulateOperator","op","operators","compile","src","config","meta","scope","blockOpeningStack","delimiters","keepOpeningTagEscapeDelimiter","allowFnCalls","allowedProps","forbiddenProps","autoEscape","trimNext","cursor","body","isEscaped","j","templateOpenTagIdx","count","lastChunk","escapedChunk","templateEndTagIdx","line","lineIndex","getLineAndColumnNumbers","lineText","pos","getLineSnapshot","MutorCompilerError","template","inner","leftTrim","rightTrim","isBlock","isBlockEnd","hasContext","requiresBlockClose","parse","rawText","tokens","tokenize","ast","generateAst","lastBlockOpened","js","build","e","message","relPos","lastPos","Mutor","config","defaultConfig","namespaces","path","ctx","MutorError","conf","autoEscape","overrideDelimeters","allowedProps","forbiddenProps","keepOpeningTagEscapeDelimiter","allowFnCalls","cache","build","template","compile","context","prevContext","result","validateContext","escapeFn","validateComputedProp","identifier","prevRenderComponentIdentifier","compiled","templateSize","targetSize","firstEntry","oldestKey","oldestData","maxSize","index_default","Mutor"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
interface MutorConfig {
|
|
2
|
+
cache: {
|
|
3
|
+
active: boolean;
|
|
4
|
+
maxSize: number;
|
|
5
|
+
};
|
|
6
|
+
keepOpeningTagEscapeDelimiter: boolean;
|
|
7
|
+
allowedProps: Set<string>;
|
|
8
|
+
forbiddenProps: Set<string>;
|
|
9
|
+
allowFnCalls: boolean;
|
|
10
|
+
autoEscape: boolean;
|
|
11
|
+
build: {
|
|
12
|
+
include: Set<string>;
|
|
13
|
+
exclude: Set<string>;
|
|
14
|
+
};
|
|
15
|
+
delimiters: {
|
|
16
|
+
openingTag: string;
|
|
17
|
+
closingTag: string;
|
|
18
|
+
whitespaceTrim: string;
|
|
19
|
+
openingTagEscape: string;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
type PartialMutorConfig = Partial<Omit<MutorConfig, "delimiters">> & {
|
|
23
|
+
delimiters?: Partial<MutorConfig["delimiters"]>;
|
|
24
|
+
cache?: Partial<MutorConfig["cache"]>;
|
|
25
|
+
build?: {
|
|
26
|
+
include?: Set<string>;
|
|
27
|
+
exclude?: Set<string>;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
declare class Mutor {
|
|
32
|
+
protected __currentRenderedPath: string;
|
|
33
|
+
protected __includeStack: Set<string>;
|
|
34
|
+
protected __cacheSize: number;
|
|
35
|
+
protected __config: MutorConfig;
|
|
36
|
+
protected __compiledTemplatesMap: Map<string, {
|
|
37
|
+
fn: Function;
|
|
38
|
+
size: number;
|
|
39
|
+
}>;
|
|
40
|
+
protected __currentContext: any;
|
|
41
|
+
protected __namespaces: Record<any, any>;
|
|
42
|
+
constructor(config: PartialMutorConfig);
|
|
43
|
+
addConfig(conf: PartialMutorConfig): MutorConfig;
|
|
44
|
+
restoreDefaultConfig(): MutorConfig;
|
|
45
|
+
compile(template: string, path?: string): Function;
|
|
46
|
+
render(template: string, context: any): string;
|
|
47
|
+
renderComponent(identifier: string, context: any): string;
|
|
48
|
+
registerComponent(identifier: string, template: string): void;
|
|
49
|
+
reset(): void;
|
|
50
|
+
protected createEntrySpaceForTemplate(targetSize: number): boolean;
|
|
51
|
+
getDiagnostics(): {
|
|
52
|
+
bytesUsed: number;
|
|
53
|
+
bytesMax: number;
|
|
54
|
+
readableUsed: string;
|
|
55
|
+
readableMax: string;
|
|
56
|
+
totalEntries: number;
|
|
57
|
+
percentFull: number;
|
|
58
|
+
avgTemplateSize: number;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { Mutor as default };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
interface MutorConfig {
|
|
2
|
+
cache: {
|
|
3
|
+
active: boolean;
|
|
4
|
+
maxSize: number;
|
|
5
|
+
};
|
|
6
|
+
keepOpeningTagEscapeDelimiter: boolean;
|
|
7
|
+
allowedProps: Set<string>;
|
|
8
|
+
forbiddenProps: Set<string>;
|
|
9
|
+
allowFnCalls: boolean;
|
|
10
|
+
autoEscape: boolean;
|
|
11
|
+
build: {
|
|
12
|
+
include: Set<string>;
|
|
13
|
+
exclude: Set<string>;
|
|
14
|
+
};
|
|
15
|
+
delimiters: {
|
|
16
|
+
openingTag: string;
|
|
17
|
+
closingTag: string;
|
|
18
|
+
whitespaceTrim: string;
|
|
19
|
+
openingTagEscape: string;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
type PartialMutorConfig = Partial<Omit<MutorConfig, "delimiters">> & {
|
|
23
|
+
delimiters?: Partial<MutorConfig["delimiters"]>;
|
|
24
|
+
cache?: Partial<MutorConfig["cache"]>;
|
|
25
|
+
build?: {
|
|
26
|
+
include?: Set<string>;
|
|
27
|
+
exclude?: Set<string>;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
declare class Mutor {
|
|
32
|
+
protected __currentRenderedPath: string;
|
|
33
|
+
protected __includeStack: Set<string>;
|
|
34
|
+
protected __cacheSize: number;
|
|
35
|
+
protected __config: MutorConfig;
|
|
36
|
+
protected __compiledTemplatesMap: Map<string, {
|
|
37
|
+
fn: Function;
|
|
38
|
+
size: number;
|
|
39
|
+
}>;
|
|
40
|
+
protected __currentContext: any;
|
|
41
|
+
protected __namespaces: Record<any, any>;
|
|
42
|
+
constructor(config: PartialMutorConfig);
|
|
43
|
+
addConfig(conf: PartialMutorConfig): MutorConfig;
|
|
44
|
+
restoreDefaultConfig(): MutorConfig;
|
|
45
|
+
compile(template: string, path?: string): Function;
|
|
46
|
+
render(template: string, context: any): string;
|
|
47
|
+
renderComponent(identifier: string, context: any): string;
|
|
48
|
+
registerComponent(identifier: string, template: string): void;
|
|
49
|
+
reset(): void;
|
|
50
|
+
protected createEntrySpaceForTemplate(targetSize: number): boolean;
|
|
51
|
+
getDiagnostics(): {
|
|
52
|
+
bytesUsed: number;
|
|
53
|
+
bytesMax: number;
|
|
54
|
+
readableUsed: string;
|
|
55
|
+
readableMax: string;
|
|
56
|
+
totalEntries: number;
|
|
57
|
+
percentFull: number;
|
|
58
|
+
avgTemplateSize: number;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { Mutor as default };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
function G(e,n){return`${" ".repeat(e+n+1)}^`}var d=class e extends Error{constructor(t){super(t);this.name="MutorError";Object.setPrototypeOf(this,e.prototype)}},I=class e extends d{constructor(t,a,o,p,f){let g=a.toString().length+2,i=`${t}
|
|
2
|
+
|
|
3
|
+
`;i+=`at ${f}:${a}:${p+1}
|
|
4
|
+
`,a>1&&(i+=`${(a-1).toString().padStart(g-2)} | ...
|
|
5
|
+
`),i+=`${a} | ${o}
|
|
6
|
+
`,i+=G(p,g);super(i);this.name="MutorCompilerError";Object.setPrototypeOf(this,e.prototype)}};var H=new Set(["for","if","else","true","false","null","undefined","end","in","of"]),M=new Set(["::","||","??","&&","**","^","|","&","!","-","%","+","*","/",">","<",">=","<=","==","!=",">>","<<",".","?.","(",")","[","]",",",":","?"]);var Q=new Set(["==","!="]),K=new Set([">","<",">=","<="]);var X=new Set(["+","-"]),k=new Set(["*","/","%"]),ee=new Set([".","?.","[","::"]),te=new Set(["-","+","!"]),re={"&":"&","<":"<",">":">",'"':""","'":"'"},A={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:"~"},keepOpeningTagEscapeDelimiter:!1,cache:{active:!0,maxSize:50*1024*1024}},ne={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,n){if(!e||typeof e!="object")throw new d("Object.hasOwn expects an object");return Object.hasOwn(e,n)},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,n=10){return Number.parseInt(e,n)},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 U(e){return typeof e!="string"?e:/[&<>"']/.test(e)?e.replace(/[&<>"']/g,n=>re[n]):e}function z(e,n,t){if(n.has(e)&&!t.has(e))throw new d(`Forbidden property access. Access to this computed property "${e}" is forbidden.`);return e}var F="object",oe=Symbol("__mutor_safe_context");function W(e){if(!e||typeof e!==F||oe in e)return e;let n=new WeakSet;function t(o,p=""){if(!o||typeof o!==F||n.has(o))return o;n.add(o);let f=Object.getPrototypeOf(o);if(f&&f!==Object.prototype&&f!==Array.prototype)throw new d(`Unsafe prototype detected at ${p||"root"}`);if(Array.isArray(o)){for(let i=0;i<o.length;i++)o[i]=t(o[i],`${p}[${i}]`);return o}if(o instanceof Map){for(let[i,u]of o.entries())typeof i===F&&t(i,`${p}.mapKey`),o.set(i,t(u,`${p}.mapValue`));return o}if(o instanceof Set){let i=new Set;for(let u of o.values())i.add(t(u,p));o.clear();for(let u of i)o.add(u);return o}let g=Object.getOwnPropertyDescriptors(o);for(let i of Object.keys(g)){let u=g[i];if(u.get||u.set)throw new d(`Getter/setter not allowed: ${p}.${i}`);let O=o[i];O&&typeof O===F&&(o[i]=t(O,`${p}.${i}`))}return o}let a=t(e);return a&&typeof a===F&&Object.defineProperty(a,oe,{value:!0,enumerable:!1,writable:!1,configurable:!1}),a}function D(e,n){let a=e.slice(0,n).split(`
|
|
7
|
+
`).length,o=e.lastIndexOf(`
|
|
8
|
+
`,n-1)+1;return{line:a,lineIndex:o}}function j(e,n,t){let a=e.indexOf(`
|
|
9
|
+
`,n);return{line:e.slice(n,a===-1?void 0:a),pos:t-n}}function v(e,n){let{scope:t,forbiddenProps:a,allowedProps:o}=n;function p(s){return t.includes(s)?s:`ctx.${s}`}function f(s){switch(s.type){case 17:return"}";case 5:return s.value;case 4:return`"${s.value}"`;case 10:return s.true?"true":"false";case 12:return"null";case 11:return"undefined";case 7:return p(s.value);case 9:return`(${f(s.expr)})`;case 2:return`${s.operator}${f(s.expr)}`;case 0:return`${f(s.left)} ${s.operator} ${f(s.right)}`;case 1:return`${f(s.condition)} ? ${f(s.left)} : ${f(s.right)}`;case 8:return i(s);case 3:return u(s);case 6:return g(s);case 13:return O(s);case 16:return"} else {";case 14:return b(s);case 15:return R(s);default:throw new d(`Unsupported expression type: ${s.type}`)}}function g(s){if(s.left.type!==7)throw{message:"Invalid usage of namespace operator.",pos:s.pos};return`namespaces.${s.left.value}.${s.right.value}`}function i(s){let y=f(s.left);if(s.bracketNotation){let h=f(s.right),w=s.optional?"?.":"";return s.right.type!==4&&s.right.type!==5?`${y}${w}[${h}]`:`${y}${w}[validateComputedProps(${h}, allowedProps, forbiddenProps)]`}else{let h=s.right.value,w=s.optional?"?.":".";if(a.has(h)&&!o.has(h))throw{message:"Forbidden property access.",pos:s.right.pos};return`${y}${w}${h}`}}function u(s){let y=f(s.expr),h=s.optional?"?.":"",w=s.args.map(N=>f(N)).join(", ");return`${y}${h}(${w})`}function O(s){let{iterable:y,loopType:h,variable:w}=s;return`for(const ${w} ${h===1?"in":"of"} ${v(y,n)}){`}function b(s){let{condition:y}=s;return`if(${v(y,n)}){`}function R(s){let{condition:y}=s;return`}else if(${v(y,n)}){`}return f(e)}function B(e){switch(e){case 0:return"identifier";case 1:return"keyword";case 2:return"number";case 4:return"operator";case 3:return"string"}}function J(e,n){let t=0,a=!1;function o(r,c){let l=e[t],S=e[e.length-1];if(!l)throw{message:`Unexpected end of expression. Expected ${c?`'${c}'`:`${r===0?"an":"a"} ${B(r)}`}.`,pos:S.pos+S.value.length-1};if(l.type!==r)throw{message:`Unexpected token type. Expected ${c?`'${c}'`:B(r)} but got ${B(l.type)} instead.`,pos:l.pos};if(c!==void 0&&l.value!==c)throw{message:`Unexpected token '${l?.value}'. Expected ${r===0?"an":"a"} ${B(r)} instead.`,pos:l.pos};return e[t++]}function p(){let r=e[t-1].pos,c=o(0).value,l;try{l=o(1,"in")}catch{l=o(1,"of")}let S=l.value==="in"?1:0,T=_();return{type:13,loopType:S,iterable:T,variable:c,pos:r}}function f(){let r=_();return{condition:r,pos:r.pos,type:14}}function g(){let r=e[t-1].pos;try{return o(1,"if"),{...f(),type:15,pos:r}}catch{return{type:16,pos:r}}}function i(){let r=[];if(e[t]?.type===4&&e[t]?.value===")")return r;for(r.push(_());e[t]?.type===4&&e[t]?.value===","&&e[t]?.value!==")";)t++,r.push(_());return r}function u(){let r=e[t++];if(r?.type===2)return{type:5,value:r.value,pos:r.pos};if(r?.type===3)return{type:4,value:r.value,pos:r.pos};if(r?.type===1){if(r.value==="for"&&t===1)return p();if(r.value==="true"||r.value==="false")return{type:10,true:r.value==="true",pos:r.pos};if(r.value==="undefined")return{type:11,pos:r.pos};if(r.value==="null")return{type:12,pos:r.pos};if(r.value==="end"&&e.length===1)return{type:17,pos:r.pos};if(r.value==="if"&&t===1)return f();if(r.value==="else"&&t===1)return g()}if(r?.type===0)return{type:7,value:r.value,pos:r.pos};if(r?.type===4&&r.value==="("){let c=_();return o(4,")"),{type:9,expr:c,pos:r.pos}}if(r?.type===4&&te.has(r.value)){let c=r.value,l=_();return{type:2,operator:c,expr:l,pos:r.pos}}throw t>e.length?{message:"Unexpected end of expression.",pos:e[e.length-1].pos}:{message:`Unexpected token '${r?.value}'.`,pos:r.pos}}function O(){let r=u();for(;e[t];){let c=e[t];if(c?.type===4&&c?.value==="("){if(t++,!a&&!n.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let l=i();o(4,")"),r={type:3,expr:r,args:l,pos:e[t-1].pos}}else if(c?.type===4&&c?.value==="?."&&e[t+1]?.type===4&&e[t+1]?.value==="("){if(t++,t++,!a&&!n.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let l=i();o(4,")"),r={type:3,expr:r,args:l,optional:!0,pos:e[t-1].pos}}else if(c?.type===4&&ee.has(c?.value)){let l=c?.value==="::",S=c?.value==="[",T=c?.value==="?.";if(t++,l&&(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(l){a=!0;let E=u();r={type:6,left:r,right:E,pos:e[t-1].pos}}else if(S){let E=_();o(4,"]"),r={type:8,right:E,left:r,bracketNotation:!0,pos:e[t-1].pos}}else if(T)if(e[t]?.type===4&&e[t]?.value==="["){t++;let E=_();o(4,"]"),r={type:8,left:r,right:E,bracketNotation:!0,optional:!0,pos:e[t-1].pos}}else{let E=u();r={type:8,left:r,right:E,optional:!0,pos:e[t-1].pos}}else{let E=u();r={type:8,left:r,right:E,pos:e[t-1].pos}}}else break}return a=!1,r}function b(){let r=O();for(;e[t]?.type===4&&k.has(e[t]?.value);){let c=e[t++].value,l=O();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function R(){let r=b();for(;e[t]?.type===4&&X.has(e[t]?.value);){let c=e[t++].value,l=b();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function s(){let r=R();for(;e[t]?.type===4&&K.has(e[t]?.value);){let c=e[t++].value,l=R();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function y(){let r=s();for(;e[t]?.type===4&&K.has(e[t]?.value);){let c=e[t++].value,l=s();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function h(){let r=y();for(;e[t]?.type===4&&Q.has(e[t]?.value);){let c=e[t++].value,l=y();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function w(){let r=N();for(;e[t]?.type===4&&e[t]?.value==="||";){let c=e[t++].value,l=N();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function N(){let r=x();for(;e[t]?.type===4&&e[t]?.value==="&&";){let c=e[t++].value,l=x();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function x(){let r=h();for(;e[t]?.type===4&&e[t]?.value==="??";){let c=e[t++].value,l=h();r={type:0,left:r,right:l,operator:c,pos:e[t-1].pos}}return r}function _(){let r=w();if(e[t]?.type!==4||e[t]?.value!=="?")return r;t++;let c=_();o(4,":");let l=_();return{type:1,left:c,right:l,condition:r,pos:e[t-1].pos}}return _()}function q(e,{delimiters:n}){let t=`${n.openingTag}${n.whitespaceTrim}`,a=`${n.whitespaceTrim}${n.closingTag}`,o=e.startsWith(t),p=e.endsWith(a),f=e.slice(o?t.length:n.openingTag.length,e.length-(p?a.length:n.closingTag.length)),g=f.trim(),i=g.startsWith("for")||g.startsWith("if")||g.startsWith("else"),u=g.startsWith("for")||g.startsWith("if"),O=g==="end",b=g.startsWith("for");return{leftTrim:o,rightTrim:p,inner:f,isBlock:i,isBlockEnd:O,hasContext:b,requiresBlockClose:u}}function Z(e){let n=0,t="",a=[];function o(){let i="";if(/[a-zA-Z$_]/.test(t)){let u=n;for(;/[a-zA-Z$_0-9]/.test(e[u])&&u<e.length;)i+=e[u],u++;a.push({type:H.has(i)?1:0,value:i,pos:n}),n=u,t=e[n]}}function p(){let i="";if(t==='"'||t==="'"||t==="`"){let u=n+1;for(;e[u]!==t&&u<e.length;)i+=e[u],u++;if(u>e.length)throw{pos:n,message:"Found string without closing quote."};a.push({type:3,value:i,pos:n}),n=u}}function f(){if(/[0-9]/.test(t)){let i=n,u="";for(;/[0-9.oxe]/.test(e[i])&&i<e.length;)u+=e[i],i++;let O=Number(u);if(Number.isNaN(O))throw{pos:n,message:"Found invalid number literal."};a.push({type:2,value:`${O}`,pos:n}),n=i-1,t=e[n]}}function g(){let i=`${t}${e[n+1]}`;if(M.has(i)){a.push({type:4,value:i,pos:n}),n++;return}if(M.has(t)){a.push({type:4,value:t,pos:n});return}}for(;n<e.length;){if(t=e[n],f(),o(),p(),g(),!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(t)&&!M.has(t)&&!M.has(e[n-1]+t))throw{message:`Unexpected token '${t}' in expression.`,pos:n};n++}return a}function V(e,n,t){let a=[],o=[],{delimiters:p,keepOpeningTagEscapeDelimiter:f,allowFnCalls:g,allowedProps:i,forbiddenProps:u,autoEscape:O}=n,b=!1,R=0,s='let acc="";';for(;R<e.length;){let w=function(){let m=h,P=0;for(;m>=p.openingTagEscape.length&&e.slice(m-p.openingTagEscape.length,m)===p.openingTagEscape;)P++,m-=p.openingTagEscape.length;return P%2===1};var y=w;let h=e.indexOf(p.openingTag,R);if(h===-1){let m=e.slice(R);b&&(m=m.trimStart()),m&&(s+=`acc+=\`${m}\`;`);break}if(w()){let m=e.slice(R,f?h+p.openingTagEscape.length+1:h-p.openingTag.length+1);b&&(m=m.trimStart(),b=!1),s+=`acc+=\`${m}\`;`,f||(s+=`acc+=\`${p.openingTag}\`;`),R=h+p.openingTag.length;continue}let N=e.indexOf(p.closingTag,h);if(N===-1){let{line:m,lineIndex:P}=D(e,h),{line:C,pos:$}=j(e,P,h);throw new I("No closing tag found.",m,C,$,t.path)}let x=e.slice(h,N+p.closingTag.length),{inner:_,leftTrim:Y,rightTrim:r,isBlock:c,isBlockEnd:l,hasContext:S,requiresBlockClose:T}=q(x,{delimiters:p}),E=e.slice(R,h);E&&(b&&(E=E.trimStart()),Y&&(E=E.trimEnd()),E&&(s+=`acc+=\`${E}\`;`)),b=!1,R=N+p.closingTag.length;try{let m=Z(_),P=J(m,{allowFnCalls:g});if(c&&T&&S?(a.push(P.variable),o.push({type:0,pos:h})):c&&T&&!S&&o.push({type:1,pos:h}),l){let $=o.pop();if($?.type===0&&a.pop(),$===void 0)throw{message:"Unexpected end of block",pos:h}}let C=v(P,{allowedProps:i,forbiddenProps:u,scope:a});c||l?s+=C:s+=O?`acc+=escapeFn(${C});`:`acc+=${C};`,r&&(b=!0)}catch(m){let{message:P,pos:C}=m,{line:$,lineIndex:ie}=D(e,h),{line:ae,pos:ce}=j(e,ie,h);throw new I(P,$,ae,ce+C+(Y?p.openingTag.length+p.whitespaceTrim.length:p.openingTag.length),t.path)}}if(o.length){let h=o.pop()?.pos,{line:w,lineIndex:N}=D(e,h),{line:x,pos:_}=j(e,N,h);throw new I("Unclosed block detected.",w,x,_+p.openingTag.length,t.path)}return s+="return acc;",new Function("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",s)}var L=class{constructor(n){this.__currentRenderedPath="";this.__includeStack=new Set;this.__cacheSize=0;this.__config={...A};this.__compiledTemplatesMap=new Map;this.__currentContext=null;this.__namespaces={...ne,Mutor:{include:(n,t)=>{if(this.__includeStack.has(n))throw new d(`Circular include detected:
|
|
10
|
+
${Array.from(this.__includeStack).join(`
|
|
11
|
+
`)}
|
|
12
|
+
${n}`);try{return this.__includeStack.add(n),this.renderComponent(n,t??this.__currentContext)}finally{this.__includeStack.delete(n)}}}};this.addConfig(n),Object.defineProperty(this.__namespaces.Mutor,"$$context",{get:()=>this.__currentContext})}addConfig(n){let{autoEscape:t,delimiters:a,allowedProps:o,forbiddenProps:p,keepOpeningTagEscapeDelimiter:f,allowFnCalls:g,cache:i,build:u}=n;return this.__config={build:{include:new Set([...A.build.include,...u?.include||[]]),exclude:new Set([...A.build.exclude,...u?.exclude||[]])},autoEscape:t===!0?!0:t!==!1,allowedProps:o||new Set,allowFnCalls:!!g,cache:{...A.cache,...i||{}},forbiddenProps:p||new Set,keepOpeningTagEscapeDelimiter:f===!0?!0:f!==!1,delimiters:{...A.delimiters,...a||{}}},this.__config}restoreDefaultConfig(){return this.__config={...A},this.__config}compile(n,t="anonymous"){return V(n,this.__config,{path:t})}render(n,t){let a=this.__currentContext;a!==t&&(this.__currentContext=t);let o=this.compile(n)(W(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,U,z);return this.__currentContext=a,o}renderComponent(n,t){if(!this.__compiledTemplatesMap.has(n))throw new d(`No template exists with the identifier '${n}'`);let a=this.__currentRenderedPath,o=this.__currentContext,p=this.__compiledTemplatesMap.get(n);this.__currentContext=t,this.__currentRenderedPath=n;let f=p.fn(W(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,U,z);return this.__currentContext=o,this.__currentRenderedPath=a,f}registerComponent(n,t){let a=t.length*2+500;if(this.__cacheSize+a>this.__config.cache.maxSize&&!this.createEntrySpaceForTemplate(a))throw new d(`The template for the component '${n}' is too large. Consider increasing 'cache.maxSize' in the config`);this.__cacheSize+=t.length*2+500,this.__compiledTemplatesMap.set(n,{fn:this.compile(t),size:a})}reset(){this.__config={...A},this.__compiledTemplatesMap.clear(),this.__currentContext=null,this.__cacheSize=0}createEntrySpaceForTemplate(n){if(this.__cacheSize+n<this.__config.cache.maxSize)return!0;if(n>this.__config.cache.maxSize)return!1;let t=this.__compiledTemplatesMap.entries().next().value;if(t){let[a,o]=t;this.__compiledTemplatesMap.delete(a),this.__cacheSize-=o.size}return this.createEntrySpaceForTemplate(n)}getDiagnostics(){let n=this.__config.cache.maxSize;return{bytesUsed:this.__cacheSize,bytesMax:n,readableUsed:`${(this.__cacheSize/1024/1024).toFixed(2)} MB`,readableMax:`${(n/1024/1024).toFixed(2)} MB`,totalEntries:this.__compiledTemplatesMap.size,percentFull:n>0?Math.min(100,Math.round(this.__cacheSize/n*100)):0,avgTemplateSize:this.__compiledTemplatesMap.size>0?Math.round(this.__cacheSize/this.__compiledTemplatesMap.size):0}}};var rt=L;export{rt as default};
|
|
13
|
+
//# sourceMappingURL=index.js.map
|