miki-template 1.2.0 → 1.3.6

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.
Files changed (105) hide show
  1. package/.github/release-notes/v1.3.1.md +55 -0
  2. package/.github/release-notes/v1.3.3.md +77 -0
  3. package/.github/workflows/ci.yml +38 -54
  4. package/.github/workflows/release.yml +106 -0
  5. package/AGENT.md +71 -71
  6. package/API_REFERENCE.md +314 -314
  7. package/CHANGELOG.md +173 -97
  8. package/CODE_OF_CONDUCT.md +14 -14
  9. package/CONTRIBUTING.md +27 -27
  10. package/README.md +342 -304
  11. package/ROADMAP.md +40 -40
  12. package/assets/banner.png +0 -0
  13. package/benchmarks/report.json +16 -16
  14. package/benchmarks/run.js +49 -49
  15. package/benchmarks/stress.mjs +647 -0
  16. package/benchmarks/templates/large.dtpl +7 -7
  17. package/benchmarks/templates/medium.dtpl +3 -3
  18. package/benchmarks/templates/small.dtpl +7 -7
  19. package/context/component.md +109 -109
  20. package/context/prd.md +131 -131
  21. package/context/project-structure.md +33 -33
  22. package/dir/base.html +23 -0
  23. package/dir/cmpnt.html +11 -0
  24. package/dir/footer.html +3 -0
  25. package/dir/home.html +80 -0
  26. package/dir/index.html +80 -0
  27. package/dir/navbar.html +9 -0
  28. package/docs/README.md +18 -18
  29. package/docs/advanced_usage.md +71 -71
  30. package/docs/api.md +119 -102
  31. package/docs/filters.md +708 -540
  32. package/docs/installation.md +106 -106
  33. package/docs/overview.md +57 -57
  34. package/docs/partialdef.md +70 -41
  35. package/docs/security.md +27 -27
  36. package/docs/tags.md +673 -610
  37. package/docs/usage.md +646 -599
  38. package/eslint.config.mjs +42 -34
  39. package/ex.mjs +33 -0
  40. package/miki-template-extension/.github/workflows/ci.yml +116 -0
  41. package/miki-template-extension/.vscodeignore +7 -0
  42. package/miki-template-extension/CHANGELOG.md +99 -0
  43. package/miki-template-extension/LICENSE +21 -21
  44. package/miki-template-extension/README.md +273 -82
  45. package/miki-template-extension/extension.js +1013 -0
  46. package/miki-template-extension/icon.png +0 -0
  47. package/miki-template-extension/icon.svg +10 -10
  48. package/miki-template-extension/miki-template-1.7.1.vsix +0 -0
  49. package/miki-template-extension/package.json +280 -46
  50. package/miki-template-extension/snippets/miki-template.json +717 -177
  51. package/miki-template-extension/syntaxes/language-configuration.json +114 -26
  52. package/miki-template-extension/syntaxes/miki-template.tmLanguage.json +355 -146
  53. package/miki-template-extension/tests/grammar-tests.json +162 -0
  54. package/miki-template-extension/tests/run-grammar-tests.js +82 -0
  55. package/package.json +37 -31
  56. package/sample-app/package-lock.json +901 -0
  57. package/sample-app/package.json +9 -0
  58. package/sample-app/server.js +14 -0
  59. package/sample-app/views/index.html +1 -0
  60. package/scripts/build-vsix.js +129 -0
  61. package/scripts/build-vsix.ps1 +15 -0
  62. package/snippets/miki-template.json +177 -177
  63. package/src/asyncRender.js +20 -20
  64. package/src/cache.js +80 -41
  65. package/src/context.js +126 -122
  66. package/src/context_processors.js +48 -41
  67. package/src/esm.mjs +84 -72
  68. package/src/filters.js +975 -527
  69. package/src/i18n.js +171 -171
  70. package/src/index.js +974 -454
  71. package/src/lexer.js +114 -92
  72. package/src/libraries.js +371 -240
  73. package/src/parser.js +270 -250
  74. package/src/security.js +53 -51
  75. package/src/tags/control.js +719 -590
  76. package/src/tags/extra.js +154 -0
  77. package/src/tags/helpers.js +26 -26
  78. package/src/tags/i18n.js +256 -230
  79. package/src/tags/inheritance.js +335 -216
  80. package/src/tags/registry.js +18 -18
  81. package/src/tags/util.js +400 -322
  82. package/src/types.d.ts +107 -107
  83. package/syntaxes/language-configuration.json +26 -26
  84. package/syntaxes/miki-template.tmLanguage.json +146 -146
  85. package/tests/asyncRender.test.js +17 -17
  86. package/tests/base.html +6 -6
  87. package/tests/child.html +3 -3
  88. package/tests/context_processors.test.js +13 -13
  89. package/tests/esm.test.mjs +61 -26
  90. package/tests/filters.test.js +254 -99
  91. package/tests/include_security.test.js +9 -9
  92. package/tests/integration/README.md +32 -0
  93. package/tests/integration/features.test.cjs +1681 -0
  94. package/tests/integration/features.test.mjs +1697 -0
  95. package/tests/integration/templates/base.miki +6 -0
  96. package/tests/integration/templates/child.miki +6 -0
  97. package/tests/integration/templates/index.html +17 -0
  98. package/tests/lexer.test.js +45 -45
  99. package/tests/parser.test.js +57 -55
  100. package/tests/partial.html +1 -1
  101. package/tests/partialdef.test.js +79 -40
  102. package/tests/production_checks.js +57 -57
  103. package/tests/security.test.js +28 -28
  104. package/tests/tags.test.js +233 -203
  105. package/miki-template-1.2.0.vsix +0 -0
package/src/tags/util.js CHANGED
@@ -1,322 +1,400 @@
1
- /**
2
- * Utility template tags: static, url, regroup, spaceless.
3
- */
4
-
5
- // Helper to resolve expression values
6
- function resolveValue(token, context) {
7
- if (!token) return '';
8
- if ((token.startsWith('"') && token.endsWith('"')) || (token.startsWith('\'') && token.endsWith('\''))) {
9
- return token.slice(1, -1);
10
- }
11
- return context.get(token);
12
- }
13
-
14
- class StaticNode {
15
- constructor(pathExpr) {
16
- this.pathExpr = pathExpr;
17
- }
18
-
19
- render(context) {
20
- const resolvedPath = resolveValue(this.pathExpr, context);
21
-
22
- // Resolve static prefix
23
- let prefix = '/static/';
24
- if (context.options && context.options.staticUrl) {
25
- prefix = context.options.staticUrl;
26
- } else if (context.options && context.options.settings && context.options.settings.staticUrl) {
27
- prefix = context.options.settings.staticUrl;
28
- }
29
-
30
- // Ensure double-slash doesn't occur and ends/starts correctly
31
- const base = prefix.endsWith('/') ? prefix : prefix + '/';
32
- const relative = resolvedPath.startsWith('/') ? resolvedPath.slice(1) : resolvedPath;
33
-
34
- return base + relative;
35
- }
36
- }
37
-
38
- class UrlNode {
39
- constructor(routeNameExpr, argsExprs) {
40
- this.routeNameExpr = routeNameExpr;
41
- this.argsExprs = argsExprs || [];
42
- }
43
-
44
- render(context) {
45
- const routeName = resolveValue(this.routeNameExpr, context);
46
- const resolvedArgs = this.argsExprs.map(arg => resolveValue(arg, context));
47
-
48
- // If an Express urlHelper is provided, use it
49
- if (context.options && typeof context.options.urlHelper === 'function') {
50
- return context.options.urlHelper(routeName, ...resolvedArgs);
51
- }
52
-
53
- // Fallback URL generator
54
- return '/' + [routeName, ...resolvedArgs].filter(Boolean).join('/');
55
- }
56
- }
57
-
58
- class RegroupNode {
59
- constructor(listPath, attr, targetName) {
60
- this.listPath = listPath;
61
- this.attr = attr;
62
- this.targetName = targetName;
63
- }
64
-
65
- render(context) {
66
- const list = context.get(this.listPath);
67
- if (!Array.isArray(list)) {
68
- context.scopes[0][this.targetName] = [];
69
- return '';
70
- }
71
-
72
- const groups = [];
73
- const groupMap = new Map();
74
-
75
- for (const item of list) {
76
- // Resolve attribute (support nested lookup on item)
77
- let val = '';
78
- if (item && typeof item === 'object') {
79
- const parts = this.attr.split('.');
80
- let current = item;
81
- for (const part of parts) {
82
- if (current && typeof current === 'object' && part in current) {
83
- current = current[part];
84
- } else {
85
- current = undefined;
86
- break;
87
- }
88
- }
89
- val = current !== undefined ? current : '';
90
- }
91
-
92
- if (!groupMap.has(val)) {
93
- const newGroup = { grouper: val, list: [] };
94
- groupMap.set(val, newGroup);
95
- groups.push(newGroup);
96
- }
97
- groupMap.get(val).list.push(item);
98
- }
99
-
100
- // Store in the current context scope
101
- context.scopes[0][this.targetName] = groups;
102
- return '';
103
- }
104
- }
105
-
106
- class SpacelessNode {
107
- constructor(body) {
108
- this.body = body;
109
- }
110
-
111
- render(context) {
112
- const content = this.body.map(n => n.render(context)).join('');
113
- // Remove space between HTML tags
114
- return content.replace(/>\s+</g, '><');
115
- }
116
- }
117
-
118
- class CsrfTokenNode {
119
- render(context) {
120
- const token = context.get('csrf_token') || '';
121
- const html = `<input type="hidden" name="csrfmiddlewaretoken" value="${token}">`;
122
- const { markSafe } = require('../security');
123
- return markSafe(html);
124
- }
125
- }
126
-
127
- class CspNonceAttrNode {
128
- render(context) {
129
- const nonce = context.get('csp_nonce') || '';
130
- if (!nonce) return '';
131
- const html = `nonce="${nonce}"`;
132
- const { markSafe } = require('../security');
133
- return markSafe(html);
134
- }
135
- }
136
-
137
- // --- Tag Registry Parsers ---
138
-
139
- function parseStatic(tagContent, _parser) {
140
- // tagContent: "static 'css/style.css'"
141
- const pathExpr = tagContent.slice(6).trim();
142
- return new StaticNode(pathExpr);
143
- }
144
-
145
- function parseUrl(tagContent, _parser) {
146
- // tagContent: "url 'route_name' arg1 arg2"
147
- const content = tagContent.slice(3).trim();
148
-
149
- // Extract route name and arguments
150
- const argRegex = /(".*?"|'.*?'|[^\s]+)/g;
151
- const matches = content.match(argRegex) || [];
152
-
153
- const routeNameExpr = matches[0];
154
- const argsExprs = matches.slice(1);
155
-
156
- return new UrlNode(routeNameExpr, argsExprs);
157
- }
158
-
159
- function parseRegroup(tagContent, _parser) {
160
- // tagContent: "regroup people by gender as grouped"
161
- const match = tagContent.match(/^regroup\s+(.+?)\s+by\s+(.+?)\s+as\s+(.+)$/);
162
- if (!match) {
163
- throw new Error(`Invalid regroup tag format: '${tagContent}'`);
164
- }
165
-
166
- const listPath = match[1].trim();
167
- const attr = match[2].trim();
168
- const targetName = match[3].trim();
169
-
170
- return new RegroupNode(listPath, attr, targetName);
171
- }
172
-
173
- function parseSpaceless(tagContent, parser) {
174
- const body = parser.parse(['endspaceless']);
175
- const next = parser.peek();
176
- if (next && next.type === 'block' && next.content.split(/\s+/)[0] === 'endspaceless') {
177
- parser.advance();
178
- }
179
- return new SpacelessNode(body);
180
- }
181
-
182
- function parseCsrfToken(_tagContent, _parser) {
183
- return new CsrfTokenNode();
184
- }
185
-
186
- class WidthRatioNode {
187
- constructor(value, maxValue, maxWidth) {
188
- this.value = parseFloat(value);
189
- this.maxValue = parseFloat(maxValue);
190
- this.maxWidth = parseInt(maxWidth, 10);
191
- }
192
-
193
- render(_context) {
194
- if (!isFinite(this.value) || !isFinite(this.maxValue) || this.maxValue === 0) {
195
- return '0';
196
- }
197
- const ratio = Math.floor((this.value / this.maxValue) * this.maxWidth);
198
- return String(Math.max(0, Math.min(ratio, this.maxWidth)));
199
- }
200
- }
201
-
202
- class DebugNode {
203
- render(context) {
204
- // Dump the current context (scopes) for debugging
205
- const dump = {
206
- scopes: context.scopes.map(s => {
207
- if (s && typeof s === 'object') {
208
- const out = {};
209
- for (const k of Object.keys(s)) {
210
- if (k.startsWith('__')) continue;
211
- try {
212
- const v = s[k];
213
- out[k] = typeof v === 'function' ? '[function]' : v;
214
- } catch {
215
- out[k] = '[unreadable]';
216
- }
217
- }
218
- return out;
219
- }
220
- return String(s);
221
- })
222
- };
223
- const { escapeHtml, markSafe } = require('../security');
224
- return markSafe('<pre>' + escapeHtml(JSON.stringify(dump, null, 2)) + '</pre>');
225
- }
226
- }
227
-
228
- function parseWidthRatio(tagContent, _parser) {
229
- // {% widthratio this_value max_value max_width %}
230
- const parts = tagContent.replace(/^widthratio\s+/, '').trim().split(/\s+/);
231
- if (parts.length < 3) {
232
- throw new Error('\'widthratio\' tag requires 3 arguments: value, max_value, max_width');
233
- }
234
- return new WidthRatioNode(parts[0], parts[1], parts[2]);
235
- }
236
-
237
- function parseDebug(_tagContent, _parser) {
238
- return new DebugNode();
239
- }
240
-
241
- function parseCspNonceAttr(_tagContent, _parser) {
242
- return new CspNonceAttrNode();
243
- }
244
-
245
- class LoadNode {
246
- constructor(libraries) {
247
- this.libraries = Array.isArray(libraries) ? libraries : [libraries];
248
- }
249
-
250
- render(_context) {
251
- const { activateLibrary, hasLibrary } = require('../libraries');
252
- for (const lib of this.libraries) {
253
- if (hasLibrary(lib)) {
254
- activateLibrary(lib);
255
- } else {
256
- // Emit a comment-style warning for missing library
257
- console.warn(`[miki-template] Library not found: '${lib}'`);
258
- }
259
- }
260
- return '';
261
- }
262
- }
263
-
264
- class TemplatetagNode {
265
- constructor(token) {
266
- this.token = token;
267
- }
268
-
269
- render(_context) {
270
- const map = {
271
- 'openblock': '{%',
272
- 'closeblock': '%}',
273
- 'openvariable': '{{',
274
- 'closevariable': '}}',
275
- 'openbrace': '{',
276
- 'closebrace': '}',
277
- 'opencomment': '{#',
278
- 'closecomment': '#}'
279
- };
280
- return map[this.token] || this.token;
281
- }
282
- }
283
-
284
- function parseLoad(tagContent, _parser) {
285
- const parts = tagContent.trim().split(/\s+/);
286
- if (parts.length === 0) {
287
- throw new Error('\'load\' tag requires at least one argument');
288
- }
289
- return new LoadNode(parts);
290
- }
291
-
292
- function parseTemplatetag(tagContent, _parser) {
293
- const parts = tagContent.trim().split(/\s+/);
294
- // First part is the tag name, rest is the argument
295
- const token = parts.length > 1 ? parts.slice(1).join(' ') : parts[0];
296
- return new TemplatetagNode(token);
297
- }
298
-
299
- module.exports = {
300
- StaticNode,
301
- UrlNode,
302
- RegroupNode,
303
- SpacelessNode,
304
- CsrfTokenNode,
305
- CspNonceAttrNode,
306
- LoadNode,
307
- TemplatetagNode,
308
- WidthRatioNode,
309
- DebugNode,
310
- parsers: {
311
- static: parseStatic,
312
- url: parseUrl,
313
- regroup: parseRegroup,
314
- spaceless: parseSpaceless,
315
- csrf_token: parseCsrfToken,
316
- csp_nonce_attr: parseCspNonceAttr,
317
- load: parseLoad,
318
- templatetag: parseTemplatetag,
319
- widthratio: parseWidthRatio,
320
- debug: parseDebug
321
- }
322
- };
1
+ /**
2
+ * Utility template tags: static, url, regroup, spaceless.
3
+ */
4
+
5
+ // Helper to resolve expression values (literals, numbers, booleans, or context lookups)
6
+ function resolveValue(token, context) {
7
+ if (token === undefined || token === null) return '';
8
+ if (typeof token !== 'string') return token;
9
+ if (token === '') return '';
10
+ if ((token.startsWith('"') && token.endsWith('"')) || (token.startsWith('\'') && token.endsWith('\''))) {
11
+ return token.slice(1, -1);
12
+ }
13
+ if (token === 'true' || token === 'True') return true;
14
+ if (token === 'false' || token === 'False') return false;
15
+ if (token === 'none' || token === 'None' || token === 'null') return null;
16
+ // Numeric literal (integer or float)
17
+ if (/^-?\d+(\.\d+)?$/.test(token)) return Number(token);
18
+ // Otherwise treat as a context variable lookup
19
+ return context.get(token);
20
+ }
21
+
22
+ class StaticNode {
23
+ constructor(pathExpr) {
24
+ this.pathExpr = pathExpr;
25
+ }
26
+
27
+ render(context) {
28
+ const resolvedPath = resolveValue(this.pathExpr, context);
29
+
30
+ // Resolve static prefix
31
+ let prefix = '/static/';
32
+ if (context.options && context.options.staticUrl) {
33
+ prefix = context.options.staticUrl;
34
+ } else if (context.options && context.options.settings && context.options.settings.staticUrl) {
35
+ prefix = context.options.settings.staticUrl;
36
+ }
37
+
38
+ // Ensure double-slash doesn't occur and ends/starts correctly
39
+ const base = prefix.endsWith('/') ? prefix : prefix + '/';
40
+ const relative = (typeof resolvedPath === 'string' && resolvedPath.startsWith('/'))
41
+ ? resolvedPath.slice(1)
42
+ : String(resolvedPath);
43
+
44
+ return base + relative;
45
+ }
46
+ }
47
+
48
+ class UrlNode {
49
+ constructor(routeNameExpr, positionalArgs, kwargs) {
50
+ this.routeNameExpr = routeNameExpr;
51
+ this.positionalArgs = positionalArgs || [];
52
+ // Each kwarg is { name, valueExpr } where valueExpr is the raw
53
+ // expression token (may be a number, a quoted string, or a var).
54
+ this.kwargs = kwargs || [];
55
+ }
56
+
57
+ render(context) {
58
+ const routeName = resolveValue(this.routeNameExpr, context);
59
+ const resolvedPositional = this.positionalArgs.map(arg => resolveValue(arg, context));
60
+ const resolvedKwargs = {};
61
+ for (const kw of this.kwargs) {
62
+ resolvedKwargs[kw.name] = resolveValue(kw.valueExpr, context);
63
+ }
64
+ const hasKwargs = Object.keys(resolvedKwargs).length > 0;
65
+
66
+ // If an Express urlHelper is provided, call it. We pass positional
67
+ // args spread, and (only when kwargs are present) a kwargs object
68
+ // as the last argument. This keeps the common `{{ url 'r' 42 }}`
69
+ // case with a `(name, ...args) => string` helper simple.
70
+ if (context.options && typeof context.options.urlHelper === 'function') {
71
+ if (hasKwargs) {
72
+ return context.options.urlHelper(routeName, ...resolvedPositional, resolvedKwargs);
73
+ }
74
+ return context.options.urlHelper(routeName, ...resolvedPositional);
75
+ }
76
+
77
+ // Fallback URL builder: convert dotted route names into deep paths
78
+ // (e.g. "user.profile.posts.show" -> "/user/profile/posts/show")
79
+ // and append positional args. Kwargs are appended as query string.
80
+ const deepPath = String(routeName).split('.').map(seg => seg).join('/');
81
+ const parts = ['/' + deepPath, ...resolvedPositional
82
+ .filter(v => v !== '' && v !== null && v !== undefined)
83
+ .map(v => String(v))];
84
+ let url = parts.join('/');
85
+ if (hasKwargs) {
86
+ const qs = Object.keys(resolvedKwargs)
87
+ .filter(k => resolvedKwargs[k] !== undefined)
88
+ .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(String(resolvedKwargs[k]))}`)
89
+ .join('&');
90
+ if (qs) url += '?' + qs;
91
+ }
92
+ return url;
93
+ }
94
+ }
95
+
96
+ class RegroupNode {
97
+ constructor(listPath, attr, targetName) {
98
+ this.listPath = listPath;
99
+ this.attr = attr;
100
+ this.targetName = targetName;
101
+ }
102
+
103
+ render(context) {
104
+ const list = context.get(this.listPath);
105
+ if (!Array.isArray(list)) {
106
+ context.scopes[0][this.targetName] = [];
107
+ return '';
108
+ }
109
+
110
+ const groups = [];
111
+ const groupMap = new Map();
112
+
113
+ for (const item of list) {
114
+ // Resolve attribute (support nested lookup on item)
115
+ let val = '';
116
+ if (item && typeof item === 'object') {
117
+ const parts = this.attr.split('.');
118
+ let current = item;
119
+ for (const part of parts) {
120
+ if (current && typeof current === 'object' && part in current) {
121
+ current = current[part];
122
+ } else {
123
+ current = undefined;
124
+ break;
125
+ }
126
+ }
127
+ val = current !== undefined ? current : '';
128
+ }
129
+
130
+ if (!groupMap.has(val)) {
131
+ const newGroup = { grouper: val, list: [] };
132
+ groupMap.set(val, newGroup);
133
+ groups.push(newGroup);
134
+ }
135
+ groupMap.get(val).list.push(item);
136
+ }
137
+
138
+ // Store in the current context scope
139
+ context.scopes[0][this.targetName] = groups;
140
+ return '';
141
+ }
142
+ }
143
+
144
+ class SpacelessNode {
145
+ constructor(body) {
146
+ this.body = body;
147
+ }
148
+
149
+ render(context) {
150
+ const content = this.body.map(n => n.render(context)).join('');
151
+ // Remove space between HTML tags
152
+ return content.replace(/>\s+</g, '><');
153
+ }
154
+ }
155
+
156
+ class CsrfTokenNode {
157
+ render(context) {
158
+ const token = context.get('csrf_token') || '';
159
+ // Escape the token for safe interpolation into an HTML attribute.
160
+ // CSRF tokens are typically alphanumeric, but defending against
161
+ // malicious or malformed token values is required to prevent
162
+ // attribute injection (" onerror=... etc).
163
+ const { escapeHtml, markSafe } = require('../security');
164
+ return markSafe(
165
+ `<input type="hidden" name="csrfmiddlewaretoken" value="${escapeHtml(String(token), true)}">`
166
+ );
167
+ }
168
+ }
169
+
170
+ class CspNonceAttrNode {
171
+ render(context) {
172
+ const nonce = context.get('csp_nonce') || '';
173
+ if (!nonce) return '';
174
+ // Escape the nonce for safe interpolation into an attribute value.
175
+ const { escapeHtml, markSafe } = require('../security');
176
+ return markSafe(`nonce="${escapeHtml(String(nonce), true)}"`);
177
+ }
178
+ }
179
+
180
+ // --- Tag Registry Parsers ---
181
+
182
+ function parseStatic(tagContent, _parser) {
183
+ // tagContent: "static 'css/style.css'"
184
+ const pathExpr = tagContent.slice(6).trim();
185
+ return new StaticNode(pathExpr);
186
+ }
187
+
188
+ function parseUrl(tagContent, _parser) {
189
+ // tagContent examples:
190
+ // "url 'route_name' arg1 arg2"
191
+ // "url 'route.name' 34"
192
+ // "url 'user.show' 34 email phone"
193
+ // "url 'user.show' userId=34 tab='posts'"
194
+ // "url 'user.show' 34 tab='posts'"
195
+ const content = tagContent.slice(3).trim();
196
+
197
+ // Tokenize respecting quoted strings.
198
+ const argRegex = /(".*?"|'.*?'|[^\s]+)/g;
199
+ const matches = content.match(argRegex) || [];
200
+
201
+ if (matches.length === 0) {
202
+ throw new Error('url tag requires a route name');
203
+ }
204
+ const routeNameExpr = matches[0];
205
+ const positionalArgs = [];
206
+ const kwargs = [];
207
+
208
+ for (let i = 1; i < matches.length; i++) {
209
+ const tok = matches[i];
210
+ // Detect `key=value` pattern (not a quoted string)
211
+ const isQuoted = (tok.startsWith('"') && tok.endsWith('"')) ||
212
+ (tok.startsWith('\'') && tok.endsWith('\''));
213
+ if (!isQuoted) {
214
+ const eq = tok.indexOf('=');
215
+ if (eq > 0) {
216
+ const name = tok.slice(0, eq);
217
+ const valueExpr = tok.slice(eq + 1);
218
+ kwargs.push({ name, valueExpr });
219
+ continue;
220
+ }
221
+ }
222
+ positionalArgs.push(tok);
223
+ }
224
+
225
+ return new UrlNode(routeNameExpr, positionalArgs, kwargs);
226
+ }
227
+
228
+ function parseRegroup(tagContent, _parser) {
229
+ // tagContent: "regroup people by gender as grouped"
230
+ const match = tagContent.match(/^regroup\s+(.+?)\s+by\s+(.+?)\s+as\s+(.+)$/);
231
+ if (!match) {
232
+ throw new Error(`Invalid regroup tag format: '${tagContent}'`);
233
+ }
234
+
235
+ const listPath = match[1].trim();
236
+ const attr = match[2].trim();
237
+ const targetName = match[3].trim();
238
+
239
+ return new RegroupNode(listPath, attr, targetName);
240
+ }
241
+
242
+ function parseSpaceless(tagContent, parser) {
243
+ const body = parser.parse(['endspaceless']);
244
+ const next = parser.peek();
245
+ if (next && next.type === 'block' && next.content.split(/\s+/)[0] === 'endspaceless') {
246
+ parser.advance();
247
+ }
248
+ return new SpacelessNode(body);
249
+ }
250
+
251
+ function parseCsrfToken(_tagContent, _parser) {
252
+ return new CsrfTokenNode();
253
+ }
254
+
255
+ class WidthRatioNode {
256
+ constructor(value, maxValue, maxWidth) {
257
+ this.value = parseFloat(value);
258
+ this.maxValue = parseFloat(maxValue);
259
+ this.maxWidth = parseInt(maxWidth, 10);
260
+ }
261
+
262
+ render(_context) {
263
+ if (!isFinite(this.value) || !isFinite(this.maxValue) || this.maxValue === 0) {
264
+ return '0';
265
+ }
266
+ const ratio = Math.floor((this.value / this.maxValue) * this.maxWidth);
267
+ return String(Math.max(0, Math.min(ratio, this.maxWidth)));
268
+ }
269
+ }
270
+
271
+ class DebugNode {
272
+ render(context) {
273
+ // Dump the current context (scopes) for debugging
274
+ const dump = {
275
+ scopes: context.scopes.map(s => {
276
+ if (s && typeof s === 'object') {
277
+ const out = {};
278
+ for (const k of Object.keys(s)) {
279
+ if (k.startsWith('__')) continue;
280
+ try {
281
+ const v = s[k];
282
+ out[k] = typeof v === 'function' ? '[function]' : v;
283
+ } catch {
284
+ out[k] = '[unreadable]';
285
+ }
286
+ }
287
+ return out;
288
+ }
289
+ return String(s);
290
+ })
291
+ };
292
+ const { escapeHtml, markSafe } = require('../security');
293
+ return markSafe('<pre>' + escapeHtml(JSON.stringify(dump, null, 2)) + '</pre>');
294
+ }
295
+ }
296
+
297
+ function parseWidthRatio(tagContent, _parser) {
298
+ // {% widthratio this_value max_value max_width %}
299
+ const parts = tagContent.replace(/^widthratio\s+/, '').trim().split(/\s+/);
300
+ if (parts.length < 3) {
301
+ throw new Error('\'widthratio\' tag requires 3 arguments: value, max_value, max_width');
302
+ }
303
+ return new WidthRatioNode(parts[0], parts[1], parts[2]);
304
+ }
305
+
306
+ function parseDebug(_tagContent, _parser) {
307
+ return new DebugNode();
308
+ }
309
+
310
+ function parseCspNonceAttr(_tagContent, _parser) {
311
+ return new CspNonceAttrNode();
312
+ }
313
+
314
+ class LoadNode {
315
+ constructor(libraries) {
316
+ this.libraries = Array.isArray(libraries) ? libraries : [libraries];
317
+ }
318
+
319
+ render(_context) {
320
+ const { activateLibrary, hasLibrary } = require('../libraries');
321
+ for (const lib of this.libraries) {
322
+ if (hasLibrary(lib)) {
323
+ activateLibrary(lib);
324
+ } else {
325
+ // Emit a comment-style warning for missing library
326
+ console.warn(`[miki-template] Library not found: '${lib}'`);
327
+ }
328
+ }
329
+ return '';
330
+ }
331
+ }
332
+
333
+ class TemplatetagNode {
334
+ constructor(token) {
335
+ this.token = token;
336
+ }
337
+
338
+ render(_context) {
339
+ const map = {
340
+ 'openblock': '{%',
341
+ 'closeblock': '%}',
342
+ 'openvariable': '{{',
343
+ 'closevariable': '}}',
344
+ 'openbrace': '{',
345
+ 'closebrace': '}',
346
+ 'opencomment': '{#',
347
+ 'closecomment': '#}'
348
+ };
349
+ return map[this.token] || this.token;
350
+ }
351
+ }
352
+
353
+ function parseLoad(tagContent, _parser) {
354
+ const parts = tagContent.trim().split(/\s+/);
355
+ if (parts.length === 0) {
356
+ throw new Error('\'load\' tag requires at least one argument');
357
+ }
358
+ // Pre-activate the library now so any tags it provides are available
359
+ // to the rest of the parser. The render-time activation in LoadNode
360
+ // is a no-op if the library is already active.
361
+ const { activateLibrary, hasLibrary } = require('../libraries');
362
+ for (const lib of parts) {
363
+ if (hasLibrary(lib)) {
364
+ activateLibrary(lib);
365
+ }
366
+ }
367
+ return new LoadNode(parts);
368
+ }
369
+
370
+ function parseTemplatetag(tagContent, _parser) {
371
+ const parts = tagContent.trim().split(/\s+/);
372
+ // First part is the tag name, rest is the argument
373
+ const token = parts.length > 1 ? parts.slice(1).join(' ') : parts[0];
374
+ return new TemplatetagNode(token);
375
+ }
376
+
377
+ module.exports = {
378
+ StaticNode,
379
+ UrlNode,
380
+ RegroupNode,
381
+ SpacelessNode,
382
+ CsrfTokenNode,
383
+ CspNonceAttrNode,
384
+ LoadNode,
385
+ TemplatetagNode,
386
+ WidthRatioNode,
387
+ DebugNode,
388
+ parsers: {
389
+ static: parseStatic,
390
+ url: parseUrl,
391
+ regroup: parseRegroup,
392
+ spaceless: parseSpaceless,
393
+ csrf_token: parseCsrfToken,
394
+ csp_nonce_attr: parseCspNonceAttr,
395
+ load: parseLoad,
396
+ templatetag: parseTemplatetag,
397
+ widthratio: parseWidthRatio,
398
+ debug: parseDebug
399
+ }
400
+ };