janja 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,201 +1,496 @@
1
1
  (function (exports) {
2
2
  'use strict';
3
3
 
4
- var NodeType;
5
- (function (NodeType) {
6
- NodeType["TEMPLATE"] = "TEMPLATE";
7
- NodeType["COMMENT"] = "COMMENT";
8
- NodeType["OUTPUT"] = "OUTPUT";
9
- NodeType["TEXT"] = "TEXT";
10
- NodeType["IF"] = "IF";
11
- NodeType["ELSE"] = "ELSE";
12
- NodeType["ELSE_IF"] = "ELSE_IF";
13
- NodeType["FOR"] = "FOR";
14
- NodeType["BREAK"] = "BREAK";
15
- NodeType["CONTINUE"] = "CONTINUE";
16
- NodeType["EXP"] = "EXP";
17
- NodeType["INCLUDE"] = "INCLUDE";
18
- NodeType["BLOCK"] = "BLOCK";
19
- NodeType["SUPER"] = "SUPER";
20
- NodeType["MACRO"] = "MACRO";
21
- NodeType["CALLER"] = "CALLER";
22
- NodeType["CALL"] = "CALL";
23
- NodeType["SET"] = "SET";
24
- NodeType["CAPTURE"] = "CAPTURE";
25
- NodeType["UNKNOWN"] = "UNKNOWN";
26
- NodeType["UNEXPECTED"] = "UNEXPECTED";
27
- })(NodeType || (NodeType = {}));
28
- class Traversal {
29
- constructor() {
30
- Object.defineProperty(this, "type", {
4
+ function highlightSource(message, source, { start: { line: l1, column: c1 }, end: { line: l2, column: c2 } }) {
5
+ const output = [];
6
+ const caretLines = new Set();
7
+ const addCaretLine = (index) => {
8
+ caretLines.add(index - 2);
9
+ caretLines.add(index - 1);
10
+ caretLines.add(index);
11
+ caretLines.add(index + 1);
12
+ caretLines.add(index + 2);
13
+ };
14
+ const lines = source.split('\n');
15
+ const indentWidth = String(lines.length).length + 2;
16
+ let caretLinesCount = 0;
17
+ lines.forEach((line, index) => {
18
+ if (!line) {
19
+ return;
20
+ }
21
+ output.push(`${`${index + 1}| `.padStart(indentWidth, ' ')}${line}`);
22
+ if (l1 === index + 1) {
23
+ const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c1 - 1)}^${l1 === l2 && c2 > c1 + 1 ? `${' '.repeat(c2 - c1 - 2)}^` : ''}`;
24
+ if (/\S/.test(caretLine)) {
25
+ output.push(caretLine);
26
+ }
27
+ addCaretLine(++caretLinesCount + index);
28
+ }
29
+ if (l1 !== l2 && l2 === index + 1) {
30
+ const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c2 - 1)}${'^'.repeat(1)}`;
31
+ if (/\S/.test(caretLine)) {
32
+ output.push(caretLine);
33
+ }
34
+ addCaretLine(++caretLinesCount + index);
35
+ }
36
+ });
37
+ const emptyLine = `${' '.repeat(indentWidth)}...`;
38
+ return `${message}
39
+
40
+ ${output
41
+ .map((line, index) => (caretLines.has(index) ? line : emptyLine))
42
+ .reduce((acc, line) => line === emptyLine && acc.at(-1) === line ? acc : [...acc, line], [])
43
+ .join('\n')}
44
+ `;
45
+ }
46
+
47
+ class CompileError extends SyntaxError {
48
+ constructor(message, src, loc) {
49
+ super(message);
50
+ Object.defineProperty(this, "src", {
31
51
  enumerable: true,
32
52
  configurable: true,
33
53
  writable: true,
34
- value: null
54
+ value: src
35
55
  });
36
56
  Object.defineProperty(this, "loc", {
37
57
  enumerable: true,
38
58
  configurable: true,
39
59
  writable: true,
40
- value: null
41
- });
42
- Object.defineProperty(this, "body", {
43
- enumerable: true,
44
- configurable: true,
45
- writable: true,
46
- value: void 0
60
+ value: loc
47
61
  });
62
+ this.name = 'CompileError';
63
+ CompileError.captureStackTrace?.(this, this.constructor);
48
64
  }
49
- traverse(cb) {
50
- this.body?.forEach(cb);
65
+ get details() {
66
+ return this.loc
67
+ ? highlightSource(this.message, this.src, this.loc)
68
+ : this.message;
51
69
  }
52
70
  }
53
- class RootNode extends Traversal {
54
- constructor(body, loc) {
55
- super();
56
- Object.defineProperty(this, "body", {
57
- enumerable: true,
58
- configurable: true,
59
- writable: true,
60
- value: body
61
- });
62
- Object.defineProperty(this, "loc", {
71
+
72
+ const CONTEXT = 'c';
73
+ const ESCAPE = 'e';
74
+ const FILTERS = 'f';
75
+
76
+ /**
77
+ * Contains the source map information.
78
+ * @example
79
+ * - template:
80
+ * {{ foo }}
81
+ *
82
+ * - compiled:
83
+ * s+=e(foo);
84
+ *
85
+ * - sourceMap:
86
+ * Mapping {
87
+ * source: {
88
+ * start: {
89
+ * line: 2,
90
+ * column: 4,
91
+ * },
92
+ * end: {
93
+ * line: 3,
94
+ * column: 5,
95
+ * },
96
+ * },
97
+ * target: {
98
+ * start: {
99
+ * line: 2,
100
+ * column: 3,
101
+ * },
102
+ * end: {
103
+ * line: 3,
104
+ * column: 8,
105
+ * },
106
+ * }
107
+ * }
108
+ */
109
+ class SourceMap {
110
+ constructor() {
111
+ Object.defineProperty(this, "mappings", {
63
112
  enumerable: true,
64
113
  configurable: true,
65
114
  writable: true,
66
- value: loc
115
+ value: []
67
116
  });
68
- Object.defineProperty(this, "type", {
69
- enumerable: true,
70
- configurable: true,
71
- writable: true,
72
- value: NodeType.TEMPLATE
117
+ }
118
+ addMapping(source, target) {
119
+ this.mappings.push({
120
+ source,
121
+ target,
73
122
  });
74
123
  }
124
+ getSourceLoc({ line, column }) {
125
+ return this.mappings
126
+ .filter(({ target: { start, end } }) => start.line <= line &&
127
+ end.line >= line &&
128
+ (start.line < line || start.column <= column) &&
129
+ (end.line > line || end.column >= column))
130
+ .map(({ source }) => source);
131
+ }
75
132
  }
76
- class OutputNode extends Traversal {
77
- constructor(val, loc, strip, exp) {
78
- super();
79
- Object.defineProperty(this, "val", {
80
- enumerable: true,
81
- configurable: true,
82
- writable: true,
83
- value: val
84
- });
85
- Object.defineProperty(this, "loc", {
86
- enumerable: true,
87
- configurable: true,
88
- writable: true,
89
- value: loc
90
- });
91
- Object.defineProperty(this, "strip", {
92
- enumerable: true,
93
- configurable: true,
94
- writable: true,
95
- value: strip
96
- });
97
- Object.defineProperty(this, "exp", {
133
+
134
+ class OutScript extends SourceMap {
135
+ constructor() {
136
+ super(...arguments);
137
+ Object.defineProperty(this, "code", {
98
138
  enumerable: true,
99
139
  configurable: true,
100
140
  writable: true,
101
- value: exp
141
+ value: ''
102
142
  });
103
- Object.defineProperty(this, "type", {
104
- enumerable: true,
105
- configurable: true,
106
- writable: true,
107
- value: NodeType.OUTPUT
143
+ }
144
+ get script() {
145
+ // eslint-disable-next-line no-new-func
146
+ return new Function(CONTEXT, ESCAPE, FILTERS, this.code);
147
+ }
148
+ start() {
149
+ this.pushRaw(null, 'return(async()=>{', 'let s="";');
150
+ }
151
+ end() {
152
+ this.pushRaw(null, 'return s;', '})();');
153
+ }
154
+ pushRaw(loc, ...lines) {
155
+ const start = this.code.length;
156
+ for (const line of lines) {
157
+ this.code += line;
158
+ }
159
+ if (!loc) {
160
+ return;
161
+ }
162
+ this.addMapping(loc, {
163
+ start: {
164
+ line: 1,
165
+ column: start,
166
+ },
167
+ end: {
168
+ line: 1,
169
+ column: this.code.length,
170
+ },
108
171
  });
109
172
  }
173
+ pushStr(loc, s) {
174
+ if (s) {
175
+ this.pushRaw(loc, `s+="${s
176
+ .replace(/\\/g, '\\\\')
177
+ .replace(/"/g, '\\"')
178
+ .replace(/[\n\r]/g, '\\n')}";`);
179
+ }
180
+ }
181
+ pushVar(loc, v) {
182
+ this.pushRaw(loc, `s+=${ESCAPE}(${v});`);
183
+ }
110
184
  }
111
- class TextNode extends Traversal {
112
- constructor(val, loc, strip) {
113
- super();
114
- Object.defineProperty(this, "val", {
115
- enumerable: true,
116
- configurable: true,
117
- writable: true,
118
- value: val
119
- });
120
- Object.defineProperty(this, "loc", {
185
+
186
+ class Context extends OutScript {
187
+ constructor() {
188
+ super(...arguments);
189
+ Object.defineProperty(this, "context", {
121
190
  enumerable: true,
122
191
  configurable: true,
123
192
  writable: true,
124
- value: loc
193
+ value: CONTEXT
125
194
  });
126
- Object.defineProperty(this, "strip", {
195
+ Object.defineProperty(this, "contexts", {
127
196
  enumerable: true,
128
197
  configurable: true,
129
198
  writable: true,
130
- value: strip
199
+ value: [CONTEXT]
131
200
  });
132
- Object.defineProperty(this, "type", {
201
+ Object.defineProperty(this, "index", {
133
202
  enumerable: true,
134
203
  configurable: true,
135
204
  writable: true,
136
- value: NodeType.TEXT
205
+ value: 0
137
206
  });
138
207
  }
208
+ in() {
209
+ this.context = `${this.context}_${this.index++}`;
210
+ this.contexts.push(this.context);
211
+ return this.context;
212
+ }
213
+ out() {
214
+ if (this.context === CONTEXT) {
215
+ return;
216
+ }
217
+ this.contexts.pop();
218
+ this.context = this.contexts.at(-1);
219
+ }
139
220
  }
140
- class IfNode extends Traversal {
141
- constructor(test, body, alternatives, loc, strip) {
142
- super();
143
- Object.defineProperty(this, "test", {
144
- enumerable: true,
145
- configurable: true,
146
- writable: true,
147
- value: test
148
- });
149
- Object.defineProperty(this, "body", {
221
+
222
+ class Safe extends String {
223
+ constructor(value) {
224
+ super(`${value}`);
225
+ }
226
+ }
227
+
228
+ function escape(v) {
229
+ return `${v}`
230
+ .replace(/&/g, '&amp;')
231
+ .replace(/"/g, '&#34;')
232
+ .replace(/'/g, '&#39;')
233
+ .replace(/</g, '&lt;')
234
+ .replace(/>/g, '&gt;');
235
+ }
236
+
237
+ function abs(value = 0) {
238
+ return Math.abs(value);
239
+ }
240
+ function add(value = 0, addend = 0) {
241
+ return value + addend;
242
+ }
243
+ function capitalize(value = '') {
244
+ return value.replace(/\b\w/g, (match) => match.toUpperCase());
245
+ }
246
+ function ceil(value = 0) {
247
+ return Math.ceil(value);
248
+ }
249
+ function compact(value = []) {
250
+ return value.filter((v) => v != null);
251
+ }
252
+ function div(value = 0, divisor = 1) {
253
+ return value / divisor;
254
+ }
255
+ function entries(value = {}) {
256
+ return Object.entries(value);
257
+ }
258
+ function even(value = 0) {
259
+ return +value % 2 === 0;
260
+ }
261
+ function fallback(value, defaultValue, anyFalsy = false) {
262
+ return anyFalsy ? value || defaultValue : (value ?? defaultValue);
263
+ }
264
+ function first(value = []) {
265
+ return [...value][0];
266
+ }
267
+ function get(value, ...path) {
268
+ return path.reduce((acc, cur) => acc && typeof acc === 'object' && cur in acc ? acc[cur] : undefined, value);
269
+ }
270
+ function groupby(value = [], key) {
271
+ return value.reduce((o, v) => {
272
+ const k = v[key];
273
+ return {
274
+ ...o,
275
+ [k]: [...(o[k] || []), v],
276
+ };
277
+ }, {});
278
+ }
279
+ function join(value = [], separator = '') {
280
+ return [...value].join(separator);
281
+ }
282
+ function json(value = null, indent = 0) {
283
+ return new Safe(JSON.stringify(value, null, indent));
284
+ }
285
+ function keys(value = {}) {
286
+ return Object.keys(value);
287
+ }
288
+ function last(value = []) {
289
+ return [...value].reverse()[0];
290
+ }
291
+ function length(value = '') {
292
+ return value.length;
293
+ }
294
+ function lower(value = '') {
295
+ return value.toLowerCase();
296
+ }
297
+ function map(value = [], key, defaultValue) {
298
+ return value.map((o) => o[key] ?? defaultValue);
299
+ }
300
+ function max(value = 0, ...rest) {
301
+ return Math.max(value, ...rest);
302
+ }
303
+ function min(value = 0, ...rest) {
304
+ return Math.min(value, ...rest);
305
+ }
306
+ function mul(value = 0, multiplier = 1) {
307
+ return value * multiplier;
308
+ }
309
+ function odd(value = 0) {
310
+ return +value % 2 === 1;
311
+ }
312
+ function omit(value = {}, ...omitKeys) {
313
+ return Object.entries(value).reduce((o, [k, v]) => (omitKeys.includes(k) ? o : { ...o, [k]: v }), {});
314
+ }
315
+ function pick(value = {}, ...pickKeys) {
316
+ return pickKeys.reduce((o, k) => ({ ...o, [k]: value[k] }), {});
317
+ }
318
+ function repeat(value = '', count = 0) {
319
+ return value.repeat(count);
320
+ }
321
+ function replace(value = '', search, replacement) {
322
+ return value.replace(new RegExp(search, 'g'), replacement);
323
+ }
324
+ function reverse(value = []) {
325
+ return Array.isArray(value) ? value.reverse() : [...value].reverse().join('');
326
+ }
327
+ function safe(value = '') {
328
+ return new Safe(value);
329
+ }
330
+ function slice(value = '', start = 0, end) {
331
+ return value.slice(start, end);
332
+ }
333
+ function sort(value = []) {
334
+ return Array.isArray(value) ? value.sort() : [...value].sort().join('');
335
+ }
336
+ function split(value = '', separator = '') {
337
+ return value.split(separator);
338
+ }
339
+ function sub(value = 0, subtrahend = 0) {
340
+ return value - subtrahend;
341
+ }
342
+ function sum(value = []) {
343
+ return value.reduce((a, b) => a + b, 0);
344
+ }
345
+ function trim(value = '') {
346
+ return value.trim();
347
+ }
348
+ function truncate(value = '', maxLength = 0, truncateStr = '...') {
349
+ return (value.slice(0, maxLength) + (value.length > maxLength ? truncateStr : ''));
350
+ }
351
+ function unique(value = '') {
352
+ return Array.isArray(value)
353
+ ? Array.from(new Set(value))
354
+ : Array.from(new Set(value)).join('');
355
+ }
356
+ function upper(value = '') {
357
+ return value.toUpperCase();
358
+ }
359
+ function urldecode(value = '') {
360
+ return decodeURIComponent(value);
361
+ }
362
+ function urlencode(value = '') {
363
+ return encodeURIComponent(value);
364
+ }
365
+ function values(value = {}) {
366
+ return Object.values(value);
367
+ }
368
+
369
+ var _filters = /*#__PURE__*/Object.freeze({
370
+ __proto__: null,
371
+ abs: abs,
372
+ add: add,
373
+ capitalize: capitalize,
374
+ ceil: ceil,
375
+ compact: compact,
376
+ div: div,
377
+ entries: entries,
378
+ escape: escape,
379
+ even: even,
380
+ fallback: fallback,
381
+ first: first,
382
+ get: get,
383
+ groupby: groupby,
384
+ join: join,
385
+ json: json,
386
+ keys: keys,
387
+ last: last,
388
+ length: length,
389
+ lower: lower,
390
+ map: map,
391
+ max: max,
392
+ min: min,
393
+ mul: mul,
394
+ odd: odd,
395
+ omit: omit,
396
+ pick: pick,
397
+ repeat: repeat,
398
+ replace: replace,
399
+ reverse: reverse,
400
+ safe: safe,
401
+ slice: slice,
402
+ sort: sort,
403
+ split: split,
404
+ sub: sub,
405
+ sum: sum,
406
+ trim: trim,
407
+ truncate: truncate,
408
+ unique: unique,
409
+ upper: upper,
410
+ urldecode: urldecode,
411
+ urlencode: urlencode,
412
+ values: values
413
+ });
414
+
415
+ async function compileBlock({ val: { value }, loc }, compiler) {
416
+ compiler.pushRaw(loc, `if(b["${value}"]&&!(b["${value}"].u++)){`, `s+=await b["${value}"].s?.pop()?.()??"";`, '}');
417
+ }
418
+ async function compileSuper({ loc }, compiler) {
419
+ if (!compiler.state.block) {
420
+ compiler.options.debug?.(new CompileError('"super" should be used inside a block', compiler.template, loc));
421
+ return;
422
+ }
423
+ compiler.pushRaw(loc, `s+=await b["${compiler.state.block}"]?.s?.pop()?.()??"";`);
424
+ }
425
+ const compilers$a = {
426
+ BLOCK: compileBlock,
427
+ SUPER: compileSuper,
428
+ };
429
+
430
+ const createUnexpected = (token, parser) => parser.createUnexpectedNode(token);
431
+
432
+ class Traversal {
433
+ constructor() {
434
+ Object.defineProperty(this, "type", {
150
435
  enumerable: true,
151
436
  configurable: true,
152
437
  writable: true,
153
- value: body
438
+ value: null
154
439
  });
155
- Object.defineProperty(this, "alternatives", {
440
+ Object.defineProperty(this, "loc", {
156
441
  enumerable: true,
157
442
  configurable: true,
158
443
  writable: true,
159
- value: alternatives
444
+ value: null
160
445
  });
161
- Object.defineProperty(this, "loc", {
446
+ Object.defineProperty(this, "body", {
162
447
  enumerable: true,
163
448
  configurable: true,
164
449
  writable: true,
165
- value: loc
450
+ value: void 0
166
451
  });
167
- Object.defineProperty(this, "strip", {
452
+ }
453
+ traverse(cb) {
454
+ this.body?.forEach(cb);
455
+ }
456
+ }
457
+ class RootNode extends Traversal {
458
+ constructor(body, loc) {
459
+ super();
460
+ Object.defineProperty(this, "body", {
168
461
  enumerable: true,
169
462
  configurable: true,
170
463
  writable: true,
171
- value: strip
464
+ value: body
465
+ });
466
+ Object.defineProperty(this, "loc", {
467
+ enumerable: true,
468
+ configurable: true,
469
+ writable: true,
470
+ value: loc
172
471
  });
173
472
  Object.defineProperty(this, "type", {
174
473
  enumerable: true,
175
474
  configurable: true,
176
475
  writable: true,
177
- value: NodeType.IF
476
+ value: 'TEMPLATE'
178
477
  });
179
478
  }
180
- traverse(cb) {
181
- this.body?.forEach(cb);
182
- this.alternatives?.forEach((node) => node.body?.forEach(cb));
183
- }
184
479
  }
185
- class ElseIfNode extends Traversal {
186
- constructor(test, body, loc, strip) {
480
+ class UnknownNode extends Traversal {
481
+ constructor(name, val, loc, strip) {
187
482
  super();
188
- Object.defineProperty(this, "test", {
483
+ Object.defineProperty(this, "name", {
189
484
  enumerable: true,
190
485
  configurable: true,
191
486
  writable: true,
192
- value: test
487
+ value: name
193
488
  });
194
- Object.defineProperty(this, "body", {
489
+ Object.defineProperty(this, "val", {
195
490
  enumerable: true,
196
491
  configurable: true,
197
492
  writable: true,
198
- value: body
493
+ value: val
199
494
  });
200
495
  Object.defineProperty(this, "loc", {
201
496
  enumerable: true,
@@ -213,18 +508,24 @@
213
508
  enumerable: true,
214
509
  configurable: true,
215
510
  writable: true,
216
- value: NodeType.ELSE_IF
511
+ value: 'UNKNOWN'
217
512
  });
218
513
  }
219
514
  }
220
- class ElseNode extends Traversal {
221
- constructor(body, loc, strip) {
515
+ class UnexpectedNode extends Traversal {
516
+ constructor(name, val, loc, strip) {
222
517
  super();
223
- Object.defineProperty(this, "body", {
518
+ Object.defineProperty(this, "name", {
224
519
  enumerable: true,
225
520
  configurable: true,
226
521
  writable: true,
227
- value: body
522
+ value: name
523
+ });
524
+ Object.defineProperty(this, "val", {
525
+ enumerable: true,
526
+ configurable: true,
527
+ writable: true,
528
+ value: val
228
529
  });
229
530
  Object.defineProperty(this, "loc", {
230
531
  enumerable: true,
@@ -242,18 +543,19 @@
242
543
  enumerable: true,
243
544
  configurable: true,
244
545
  writable: true,
245
- value: NodeType.ELSE
546
+ value: 'UNEXPECTED'
246
547
  });
247
548
  }
248
549
  }
249
- class ForNode extends Traversal {
250
- constructor(loop, body, loc, strip) {
550
+
551
+ class BlockNode extends Traversal {
552
+ constructor(val, body, loc, strip) {
251
553
  super();
252
- Object.defineProperty(this, "loop", {
554
+ Object.defineProperty(this, "val", {
253
555
  enumerable: true,
254
556
  configurable: true,
255
557
  writable: true,
256
- value: loop
558
+ value: val
257
559
  });
258
560
  Object.defineProperty(this, "body", {
259
561
  enumerable: true,
@@ -277,11 +579,11 @@
277
579
  enumerable: true,
278
580
  configurable: true,
279
581
  writable: true,
280
- value: NodeType.FOR
582
+ value: 'BLOCK'
281
583
  });
282
584
  }
283
585
  }
284
- class BreakNode extends Traversal {
586
+ class SuperNode extends Traversal {
285
587
  constructor(val, loc, strip) {
286
588
  super();
287
589
  Object.defineProperty(this, "val", {
@@ -306,53 +608,206 @@
306
608
  enumerable: true,
307
609
  configurable: true,
308
610
  writable: true,
309
- value: NodeType.BREAK
611
+ value: 'SUPER'
310
612
  });
311
613
  }
312
614
  }
313
- class ContinueNode extends Traversal {
314
- constructor(val, loc, strip) {
315
- super();
316
- Object.defineProperty(this, "val", {
317
- enumerable: true,
318
- configurable: true,
319
- writable: true,
320
- value: val
321
- });
322
- Object.defineProperty(this, "loc", {
323
- enumerable: true,
324
- configurable: true,
325
- writable: true,
326
- value: loc
327
- });
328
- Object.defineProperty(this, "strip", {
615
+
616
+ function parseBlock(token, parser) {
617
+ if (!token.expression) {
618
+ parser.emitExpErr(token);
619
+ return;
620
+ }
621
+ parser.advance();
622
+ const body = parser.parseUntil(['endblock']);
623
+ if (parser.match(['endblock'])) {
624
+ parser.advance();
625
+ }
626
+ else {
627
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
628
+ }
629
+ return new BlockNode(parser.parseExp(token.expression), body, token.loc, token.strip);
630
+ }
631
+ function parseSuper(token, parser) {
632
+ if (token.expression) {
633
+ parser.emitExpErr(token, false);
634
+ return;
635
+ }
636
+ parser.advance();
637
+ return new SuperNode(token.val, token.loc, token.strip);
638
+ }
639
+ const parsers$a = {
640
+ block: parseBlock,
641
+ super: parseSuper,
642
+ endblock: createUnexpected,
643
+ };
644
+
645
+ const plugin$a = {
646
+ compilers: compilers$a,
647
+ parsers: parsers$a,
648
+ };
649
+
650
+ const expTokenOperators = {
651
+ AND: '&&',
652
+ OR: '||',
653
+ IS: '',
654
+ NOT: '!',
655
+ EQ: '===',
656
+ NE: '!==',
657
+ GT: '>',
658
+ LT: '<',
659
+ GE: '>=',
660
+ LE: '<=',
661
+ IN: ' in ',
662
+ NI: ' in ',
663
+ OF: ' of ',
664
+ ADD: '+',
665
+ SUB: '-',
666
+ MUL: '*',
667
+ DIV: '/',
668
+ MOD: '%',
669
+ PIPE: '',
670
+ ASSIGN: '=',
671
+ LP: '(',
672
+ RP: ')',
673
+ COMMA: ',',
674
+ DOT: '.',
675
+ ID: '',
676
+ LIT: '',
677
+ IF: '',
678
+ ELSE: '',
679
+ };
680
+ class ExpCompiler {
681
+ constructor() {
682
+ Object.defineProperty(this, "context", {
329
683
  enumerable: true,
330
684
  configurable: true,
331
685
  writable: true,
332
- value: strip
686
+ value: void 0
333
687
  });
334
- Object.defineProperty(this, "type", {
688
+ Object.defineProperty(this, "filters", {
335
689
  enumerable: true,
336
690
  configurable: true,
337
691
  writable: true,
338
- value: NodeType.CONTINUE
692
+ value: void 0
339
693
  });
340
694
  }
695
+ compile(expression, context = CONTEXT, filters = FILTERS) {
696
+ this.context = context;
697
+ this.filters = filters;
698
+ return expression ? this.compileExp(expression) : '""';
699
+ }
700
+ compileExp(expression) {
701
+ switch (expression.type) {
702
+ case 'NOT':
703
+ return this.compileNot(expression);
704
+ case 'ID':
705
+ return this.compileId(expression);
706
+ case 'LIT':
707
+ return this.compileLit(expression);
708
+ case 'PIPE':
709
+ return this.compilePipe(expression);
710
+ case 'OF':
711
+ return this.compileOf(expression);
712
+ case 'ASSIGN':
713
+ return this.compileAssign(expression);
714
+ case 'IS':
715
+ return this.compileIs(expression);
716
+ case 'AND':
717
+ case 'OR':
718
+ case 'EQ':
719
+ case 'NE':
720
+ case 'GT':
721
+ case 'LT':
722
+ case 'GE':
723
+ case 'LE':
724
+ case 'IN':
725
+ case 'NI':
726
+ case 'ADD':
727
+ case 'SUB':
728
+ case 'MUL':
729
+ case 'DIV':
730
+ case 'MOD':
731
+ return this.compileBinary(expression);
732
+ case 'IF':
733
+ return this.compileTernary(expression);
734
+ case 'SEQ':
735
+ return this.compileSeq(expression);
736
+ // no default
737
+ }
738
+ }
739
+ compileNot({ argument }) {
740
+ return `!${this.compileExp(argument)}`;
741
+ }
742
+ compileId({ value, path, args }) {
743
+ let s = `${this.context}.${value}`;
744
+ if (path) {
745
+ s += path.map((p) => `.${p.value}`).join('');
746
+ }
747
+ if (args) {
748
+ s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
749
+ }
750
+ return s;
751
+ }
752
+ compileLit({ value }) {
753
+ return value === undefined ? 'undefined' : JSON.stringify(value);
754
+ }
755
+ compileSeq({ elements }) {
756
+ return elements.map((element) => this.compileExp(element)).toString();
757
+ }
758
+ compilePipe({ left, right }) {
759
+ const { value: name, args = [] } = right;
760
+ return `(await ${this.filters}.${name}.call(${[this.context, this.compileExp(left), ...args.map((arg) => (arg.type === 'ASSIGN' ? `${this.context}.${arg.left.value}=${this.compileExp(arg.right)}` : this.compileExp(arg)))].join(',')}))`;
761
+ }
762
+ compileOf({ left, right }) {
763
+ // destructuring
764
+ if (left.type === 'SEQ') {
765
+ return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
766
+ }
767
+ return `const ${left.value} of ${this.compileExp(right)}`;
768
+ }
769
+ compileAssign({ left, right }) {
770
+ if (left.type === 'ID') {
771
+ return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
772
+ }
773
+ // destructuring
774
+ return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
775
+ }
776
+ compileIs({ left, right }) {
777
+ return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
778
+ }
779
+ compileBinary({ type, left, right }) {
780
+ const ret = `${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)}`;
781
+ return type === 'NI' ? `!${ret}` : ret;
782
+ }
783
+ compileTernary({ test, consequent, alternative }) {
784
+ return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
785
+ }
341
786
  }
342
- class UnknownDirectiveNode extends Traversal {
343
- constructor(name, val, loc, strip) {
787
+
788
+ async function compileCall({ val, body, loc }, compiler) {
789
+ compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
790
+ await compiler.compileNodes(body);
791
+ compiler.pushRaw(null, '});');
792
+ }
793
+ const compilers$9 = {
794
+ CALL: compileCall,
795
+ };
796
+
797
+ class CallNode extends Traversal {
798
+ constructor(val, body, loc, strip) {
344
799
  super();
345
- Object.defineProperty(this, "name", {
800
+ Object.defineProperty(this, "val", {
346
801
  enumerable: true,
347
802
  configurable: true,
348
803
  writable: true,
349
- value: name
804
+ value: val
350
805
  });
351
- Object.defineProperty(this, "val", {
806
+ Object.defineProperty(this, "body", {
352
807
  enumerable: true,
353
808
  configurable: true,
354
809
  writable: true,
355
- value: val
810
+ value: body
356
811
  });
357
812
  Object.defineProperty(this, "loc", {
358
813
  enumerable: true,
@@ -370,24 +825,59 @@
370
825
  enumerable: true,
371
826
  configurable: true,
372
827
  writable: true,
373
- value: NodeType.UNKNOWN
828
+ value: 'CALL'
374
829
  });
375
830
  }
376
831
  }
377
- class UnexpectedDirectiveNode extends Traversal {
378
- constructor(name, val, loc, strip) {
832
+
833
+ function parseCall(token, parser) {
834
+ if (!token.expression) {
835
+ parser.emitExpErr(token);
836
+ return;
837
+ }
838
+ parser.advance();
839
+ const body = parser.parseUntil(['endcall']);
840
+ if (parser.match(['endcall'])) {
841
+ parser.advance();
842
+ }
843
+ else {
844
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
845
+ }
846
+ return new CallNode(parser.parseExp(token.expression), body, token.loc, token.strip);
847
+ }
848
+ const parsers$9 = {
849
+ call: parseCall,
850
+ endcall: createUnexpected,
851
+ };
852
+
853
+ const plugin$9 = {
854
+ compilers: compilers$9,
855
+ parsers: parsers$9,
856
+ };
857
+
858
+ async function compileCapture({ val, body, loc }, compiler) {
859
+ compiler.pushRaw(loc, `${compiler.context}.${val.value}=await(async(s)=>{`);
860
+ await compiler.compileNodes(body);
861
+ compiler.pushRaw(null, 'return s;})("");');
862
+ }
863
+ const compilers$8 = {
864
+ CAPTURE: compileCapture,
865
+ };
866
+
867
+ class CaptureNode extends Traversal {
868
+ constructor(val, body, loc, strip) {
379
869
  super();
380
- Object.defineProperty(this, "name", {
870
+ Object.defineProperty(this, "val", {
381
871
  enumerable: true,
382
872
  configurable: true,
383
873
  writable: true,
384
- value: name
874
+ value: val
385
875
  });
386
- Object.defineProperty(this, "val", {
876
+ Object.defineProperty(this, "body", {
387
877
  enumerable: true,
388
878
  configurable: true,
389
879
  writable: true,
390
- value: val
880
+ value: body
391
881
  });
392
882
  Object.defineProperty(this, "loc", {
393
883
  enumerable: true,
@@ -405,40 +895,46 @@
405
895
  enumerable: true,
406
896
  configurable: true,
407
897
  writable: true,
408
- value: NodeType.UNEXPECTED
898
+ value: 'CAPTURE'
409
899
  });
410
900
  }
411
901
  }
412
- class CommentNode extends Traversal {
413
- constructor(val, loc, strip) {
414
- super();
415
- Object.defineProperty(this, "val", {
416
- enumerable: true,
417
- configurable: true,
418
- writable: true,
419
- value: val
420
- });
421
- Object.defineProperty(this, "loc", {
422
- enumerable: true,
423
- configurable: true,
424
- writable: true,
425
- value: loc
426
- });
427
- Object.defineProperty(this, "strip", {
428
- enumerable: true,
429
- configurable: true,
430
- writable: true,
431
- value: strip
432
- });
433
- Object.defineProperty(this, "type", {
434
- enumerable: true,
435
- configurable: true,
436
- writable: true,
437
- value: NodeType.COMMENT
438
- });
902
+
903
+ function parseCapture(token, parser) {
904
+ if (!token.expression) {
905
+ parser.emitExpErr(token);
906
+ return;
439
907
  }
908
+ parser.advance();
909
+ const body = parser.parseUntil(['endcapture']);
910
+ if (parser.match(['endcapture'])) {
911
+ parser.advance();
912
+ }
913
+ else {
914
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
915
+ }
916
+ return new CaptureNode(parser.parseExp(token.expression), body, token.loc, token.strip);
440
917
  }
441
- class IncludeNode extends Traversal {
918
+ const parsers$8 = {
919
+ capture: parseCapture,
920
+ endcapture: createUnexpected,
921
+ };
922
+
923
+ const plugin$8 = {
924
+ compilers: compilers$8,
925
+ parsers: parsers$8,
926
+ };
927
+
928
+ async function compileComment({ val, loc }, compiler) {
929
+ if (!compiler.options.stripComments) {
930
+ compiler.pushStr(loc, `<!--${val}-->`);
931
+ }
932
+ }
933
+ const compilers$7 = {
934
+ COMMENT: compileComment,
935
+ };
936
+
937
+ class CommentNode extends Traversal {
442
938
  constructor(val, loc, strip) {
443
939
  super();
444
940
  Object.defineProperty(this, "val", {
@@ -463,18 +959,56 @@
463
959
  enumerable: true,
464
960
  configurable: true,
465
961
  writable: true,
466
- value: NodeType.INCLUDE
962
+ value: 'COMMENT'
467
963
  });
468
964
  }
469
965
  }
470
- class BlockNode extends Traversal {
471
- constructor(val, body, loc, strip) {
966
+
967
+ function parseComment({ val, loc, strip }, parser) {
968
+ parser.advance();
969
+ return new CommentNode(val, loc, strip);
970
+ }
971
+ const parsers$7 = {
972
+ comment: parseComment,
973
+ };
974
+
975
+ const plugin$7 = {
976
+ compilers: compilers$7,
977
+ parsers: parsers$7,
978
+ };
979
+
980
+ async function compileFor({ loop, body }, compiler) {
981
+ const { context } = compiler;
982
+ if (loop.left.type === 'SEQ') {
983
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.elements.map(({ value }) => value).join(',')},`, '};');
984
+ }
985
+ else {
986
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, '};');
987
+ }
988
+ await compiler.compileNodes(body);
989
+ compiler.out();
990
+ compiler.pushRaw(null, '}');
991
+ }
992
+ function compileBreak({ loc }, compiler) {
993
+ compiler.pushRaw(loc, 'break;');
994
+ }
995
+ function compileContinue({ loc }, compiler) {
996
+ compiler.pushRaw(loc, 'continue;');
997
+ }
998
+ const compilers$6 = {
999
+ FOR: compileFor,
1000
+ BREAK: compileBreak,
1001
+ CONTINUE: compileContinue,
1002
+ };
1003
+
1004
+ class ForNode extends Traversal {
1005
+ constructor(loop, body, loc, strip) {
472
1006
  super();
473
- Object.defineProperty(this, "val", {
1007
+ Object.defineProperty(this, "loop", {
474
1008
  enumerable: true,
475
1009
  configurable: true,
476
1010
  writable: true,
477
- value: val
1011
+ value: loop
478
1012
  });
479
1013
  Object.defineProperty(this, "body", {
480
1014
  enumerable: true,
@@ -498,11 +1032,11 @@
498
1032
  enumerable: true,
499
1033
  configurable: true,
500
1034
  writable: true,
501
- value: NodeType.BLOCK
1035
+ value: 'FOR'
502
1036
  });
503
1037
  }
504
1038
  }
505
- class SuperNode extends Traversal {
1039
+ class BreakNode extends Traversal {
506
1040
  constructor(val, loc, strip) {
507
1041
  super();
508
1042
  Object.defineProperty(this, "val", {
@@ -527,12 +1061,12 @@
527
1061
  enumerable: true,
528
1062
  configurable: true,
529
1063
  writable: true,
530
- value: NodeType.SUPER
1064
+ value: 'BREAK'
531
1065
  });
532
1066
  }
533
1067
  }
534
- class MacroNode extends Traversal {
535
- constructor(val, body, loc, strip) {
1068
+ class ContinueNode extends Traversal {
1069
+ constructor(val, loc, strip) {
536
1070
  super();
537
1071
  Object.defineProperty(this, "val", {
538
1072
  enumerable: true,
@@ -540,12 +1074,6 @@
540
1074
  writable: true,
541
1075
  value: val
542
1076
  });
543
- Object.defineProperty(this, "body", {
544
- enumerable: true,
545
- configurable: true,
546
- writable: true,
547
- value: body
548
- });
549
1077
  Object.defineProperty(this, "loc", {
550
1078
  enumerable: true,
551
1079
  configurable: true,
@@ -562,18 +1090,104 @@
562
1090
  enumerable: true,
563
1091
  configurable: true,
564
1092
  writable: true,
565
- value: NodeType.MACRO
1093
+ value: 'CONTINUE'
566
1094
  });
567
1095
  }
568
1096
  }
569
- class CallerNode extends Traversal {
570
- constructor(val, loc, strip) {
1097
+
1098
+ const wm$1 = new WeakMap();
1099
+ function parseFor(token, parser) {
1100
+ if (!token.expression) {
1101
+ parser.emitExpErr(token);
1102
+ return;
1103
+ }
1104
+ wm$1.set(parser, true);
1105
+ parser.advance();
1106
+ const body = parser.parseUntil(['endfor']);
1107
+ wm$1.set(parser, false);
1108
+ if (parser.match(['endfor'])) {
1109
+ parser.advance();
1110
+ }
1111
+ else {
1112
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1113
+ }
1114
+ return new ForNode(parser.parseExp(token.expression), body, token.loc, token.strip);
1115
+ }
1116
+ function parseBreak(token, parser) {
1117
+ if (token.expression) {
1118
+ parser.emitExpErr(token, false);
1119
+ return;
1120
+ }
1121
+ if (!wm$1.get(parser)) {
1122
+ parser.options.debug?.(new CompileError('"break" directive used outside of a loop', parser.template, token.loc));
1123
+ return;
1124
+ }
1125
+ parser.advance();
1126
+ return new BreakNode(token.val, token.loc, token.strip);
1127
+ }
1128
+ function parseContinue(token, parser) {
1129
+ if (token.expression) {
1130
+ parser.emitExpErr(token, false);
1131
+ return;
1132
+ }
1133
+ if (!wm$1.get(parser)) {
1134
+ parser.options.debug?.(new CompileError('"continue" directive used outside of a loop', parser.template, token.loc));
1135
+ return;
1136
+ }
1137
+ parser.advance();
1138
+ return new ContinueNode(token.val, token.loc, token.strip);
1139
+ }
1140
+ const parsers$6 = {
1141
+ for: parseFor,
1142
+ break: parseBreak,
1143
+ continue: parseContinue,
1144
+ endfor: createUnexpected,
1145
+ };
1146
+
1147
+ const plugin$6 = {
1148
+ compilers: compilers$6,
1149
+ parsers: parsers$6,
1150
+ };
1151
+
1152
+ async function compileIf({ test, body, alternatives }, compiler) {
1153
+ compiler.pushRaw(test.loc, `if(${new ExpCompiler().compile(test, compiler.context)}){`);
1154
+ await compiler.compileNodes(body);
1155
+ compiler.pushRaw(null, '}');
1156
+ for (const branch of alternatives) {
1157
+ if (branch.type === 'ELSE_IF') {
1158
+ compiler.pushRaw(branch.test.loc, `else if(${new ExpCompiler().compile(branch.test, compiler.context)}){`);
1159
+ }
1160
+ else {
1161
+ compiler.pushRaw(null, 'else{');
1162
+ }
1163
+ await compiler.compileNodes(branch.body);
1164
+ compiler.pushRaw(null, '}');
1165
+ }
1166
+ }
1167
+ const compilers$5 = {
1168
+ IF: compileIf,
1169
+ };
1170
+
1171
+ class IfNode extends Traversal {
1172
+ constructor(test, body, alternatives, loc, strip) {
571
1173
  super();
572
- Object.defineProperty(this, "val", {
1174
+ Object.defineProperty(this, "test", {
573
1175
  enumerable: true,
574
1176
  configurable: true,
575
1177
  writable: true,
576
- value: val
1178
+ value: test
1179
+ });
1180
+ Object.defineProperty(this, "body", {
1181
+ enumerable: true,
1182
+ configurable: true,
1183
+ writable: true,
1184
+ value: body
1185
+ });
1186
+ Object.defineProperty(this, "alternatives", {
1187
+ enumerable: true,
1188
+ configurable: true,
1189
+ writable: true,
1190
+ value: alternatives
577
1191
  });
578
1192
  Object.defineProperty(this, "loc", {
579
1193
  enumerable: true,
@@ -591,18 +1205,22 @@
591
1205
  enumerable: true,
592
1206
  configurable: true,
593
1207
  writable: true,
594
- value: NodeType.CALLER
1208
+ value: 'IF'
595
1209
  });
596
1210
  }
1211
+ traverse(cb) {
1212
+ this.body?.forEach(cb);
1213
+ this.alternatives?.forEach((node) => node.body?.forEach(cb));
1214
+ }
597
1215
  }
598
- class CallNode extends Traversal {
599
- constructor(val, body, loc, strip) {
1216
+ class ElseIfNode extends Traversal {
1217
+ constructor(test, body, loc, strip) {
600
1218
  super();
601
- Object.defineProperty(this, "val", {
1219
+ Object.defineProperty(this, "test", {
602
1220
  enumerable: true,
603
1221
  configurable: true,
604
1222
  writable: true,
605
- value: val
1223
+ value: test
606
1224
  });
607
1225
  Object.defineProperty(this, "body", {
608
1226
  enumerable: true,
@@ -626,18 +1244,18 @@
626
1244
  enumerable: true,
627
1245
  configurable: true,
628
1246
  writable: true,
629
- value: NodeType.CALL
1247
+ value: 'ELSE_IF'
630
1248
  });
631
1249
  }
632
1250
  }
633
- class SetNode extends Traversal {
634
- constructor(val, loc, strip) {
1251
+ class ElseNode extends Traversal {
1252
+ constructor(body, loc, strip) {
635
1253
  super();
636
- Object.defineProperty(this, "val", {
1254
+ Object.defineProperty(this, "body", {
637
1255
  enumerable: true,
638
1256
  configurable: true,
639
1257
  writable: true,
640
- value: val
1258
+ value: body
641
1259
  });
642
1260
  Object.defineProperty(this, "loc", {
643
1261
  enumerable: true,
@@ -655,12 +1273,80 @@
655
1273
  enumerable: true,
656
1274
  configurable: true,
657
1275
  writable: true,
658
- value: NodeType.SET
1276
+ value: 'ELSE'
659
1277
  });
660
1278
  }
661
1279
  }
662
- class CaptureNode extends Traversal {
663
- constructor(val, body, loc, strip) {
1280
+
1281
+ function parseIf(token, parser) {
1282
+ if (!token.expression) {
1283
+ parser.emitExpErr(token);
1284
+ return;
1285
+ }
1286
+ parser.advance();
1287
+ const body = parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']);
1288
+ const alternatives = [];
1289
+ while (parser.match(['else', 'elseif', 'elsif', 'elif'])) {
1290
+ const branchToken = parser.peek();
1291
+ if (branchToken.name.toLowerCase() === 'else') {
1292
+ const elseNode = parseElse(branchToken, parser);
1293
+ if (elseNode) {
1294
+ alternatives.push(elseNode);
1295
+ }
1296
+ }
1297
+ else {
1298
+ const elseIfNode = parseElseIf(branchToken, parser);
1299
+ if (elseIfNode) {
1300
+ alternatives.push(elseIfNode);
1301
+ }
1302
+ }
1303
+ }
1304
+ if (parser.match(['endif'])) {
1305
+ parser.advance();
1306
+ }
1307
+ else {
1308
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1309
+ }
1310
+ return new IfNode(parser.parseExp(token.expression), body, alternatives, token.loc, token.strip);
1311
+ }
1312
+ function parseElseIf(token, parser) {
1313
+ if (!token.expression) {
1314
+ parser.emitExpErr(token);
1315
+ return;
1316
+ }
1317
+ parser.advance();
1318
+ return new ElseIfNode(parser.parseExp(token.expression), parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']), token.loc, token.strip);
1319
+ }
1320
+ function parseElse(token, parser) {
1321
+ if (token.expression) {
1322
+ parser.emitExpErr(token, false);
1323
+ return;
1324
+ }
1325
+ parser.advance();
1326
+ return new ElseNode(parser.parseUntil(['endif']), token.loc, token.strip);
1327
+ }
1328
+ const parsers$5 = {
1329
+ if: parseIf,
1330
+ elseif: createUnexpected,
1331
+ elsif: createUnexpected,
1332
+ elif: createUnexpected,
1333
+ endif: createUnexpected,
1334
+ };
1335
+
1336
+ const plugin$5 = {
1337
+ compilers: compilers$5,
1338
+ parsers: parsers$5,
1339
+ };
1340
+
1341
+ async function compileInclude({ val: { value }, loc }, compiler) {
1342
+ compiler.pushRaw(loc, `s+=await p["${value}"]?.()??"";`);
1343
+ }
1344
+ const compilers$4 = {
1345
+ INCLUDE: compileInclude,
1346
+ };
1347
+
1348
+ class IncludeNode extends Traversal {
1349
+ constructor(val, loc, strip) {
664
1350
  super();
665
1351
  Object.defineProperty(this, "val", {
666
1352
  enumerable: true,
@@ -668,12 +1354,6 @@
668
1354
  writable: true,
669
1355
  value: val
670
1356
  });
671
- Object.defineProperty(this, "body", {
672
- enumerable: true,
673
- configurable: true,
674
- writable: true,
675
- value: body
676
- });
677
1357
  Object.defineProperty(this, "loc", {
678
1358
  enumerable: true,
679
1359
  configurable: true,
@@ -684,698 +1364,32 @@
684
1364
  enumerable: true,
685
1365
  configurable: true,
686
1366
  writable: true,
687
- value: strip
688
- });
689
- Object.defineProperty(this, "type", {
690
- enumerable: true,
691
- configurable: true,
692
- writable: true,
693
- value: NodeType.CAPTURE
694
- });
695
- }
696
- }
697
-
698
- function highlightSource(message, source, { start: { line: l1, column: c1 }, end: { line: l2, column: c2 } }) {
699
- const output = [];
700
- const caretLines = new Set();
701
- const addCaretLine = (index) => {
702
- caretLines.add(index - 2);
703
- caretLines.add(index - 1);
704
- caretLines.add(index);
705
- caretLines.add(index + 1);
706
- caretLines.add(index + 2);
707
- };
708
- const lines = source.split('\n');
709
- const indentWidth = String(lines.length).length + 2;
710
- let caretLinesCount = 0;
711
- lines.forEach((line, index) => {
712
- if (!line) {
713
- return;
714
- }
715
- output.push(`${`${index + 1}| `.padStart(indentWidth, ' ')}${line}`);
716
- if (l1 === index + 1) {
717
- const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c1 - 1)}^${l1 === l2 && c2 > c1 + 1 ? `${' '.repeat(c2 - c1 - 2)}^` : ''}`;
718
- if (/\S/.test(caretLine)) {
719
- output.push(caretLine);
720
- }
721
- addCaretLine(++caretLinesCount + index);
722
- }
723
- if (l1 !== l2 && l2 === index + 1) {
724
- const caretLine = `${' '.repeat(indentWidth - 2)}| ${' '.repeat(c2 - 1)}${'^'.repeat(1)}`;
725
- if (/\S/.test(caretLine)) {
726
- output.push(caretLine);
727
- }
728
- addCaretLine(++caretLinesCount + index);
729
- }
730
- });
731
- const emptyLine = `${' '.repeat(indentWidth)}...`;
732
- return `${message}
733
-
734
- ${output
735
- .map((line, index) => (caretLines.has(index) ? line : emptyLine))
736
- .reduce((acc, line) => line === emptyLine && acc.at(-1) === line ? acc : [...acc, line], [])
737
- .join('\n')}
738
- `;
739
- }
740
-
741
- class CompileError extends SyntaxError {
742
- constructor(message, src, loc) {
743
- super(message);
744
- Object.defineProperty(this, "src", {
745
- enumerable: true,
746
- configurable: true,
747
- writable: true,
748
- value: src
749
- });
750
- Object.defineProperty(this, "loc", {
751
- enumerable: true,
752
- configurable: true,
753
- writable: true,
754
- value: loc
755
- });
756
- this.name = 'CompileError';
757
- CompileError.captureStackTrace?.(this, this.constructor);
758
- }
759
- get details() {
760
- return this.loc
761
- ? highlightSource(this.message, this.src, this.loc)
762
- : this.message;
763
- }
764
- }
765
-
766
- const parseUnexpected = (token, parser) => parser.createUnexpectedDirective(token);
767
-
768
- function parseBlock(token, parser) {
769
- parser.requireExpression(token);
770
- const val = parser.parseExp(token.expression);
771
- parser.advance();
772
- const body = parser.parseUntil(['endblock']);
773
- if (parser.match(['endblock'])) {
774
- parser.advance();
775
- }
776
- else {
777
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
778
- }
779
- return new BlockNode(val, body, token.loc, token.strip);
780
- }
781
- function parseSuper(token, parser) {
782
- parser.requireNoExpression(token);
783
- parser.advance();
784
- return new SuperNode(token.val, token.loc, token.strip);
785
- }
786
- const parsers$8 = {
787
- block: parseBlock,
788
- super: parseSuper,
789
- endblock: parseUnexpected,
790
- };
791
-
792
- function parseCall(token, parser) {
793
- parser.requireExpression(token);
794
- const val = parser.parseExp(token.expression);
795
- parser.advance();
796
- const body = parser.parseUntil(['endcall']);
797
- if (parser.match(['endcall'])) {
798
- parser.advance();
799
- }
800
- else {
801
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
802
- }
803
- return new CallNode(val, body, token.loc, token.strip);
804
- }
805
- const parsers$7 = {
806
- call: parseCall,
807
- endcall: parseUnexpected,
808
- };
809
-
810
- function parseCapture(token, parser) {
811
- parser.requireExpression(token);
812
- const val = parser.parseExp(token.expression);
813
- parser.advance();
814
- const body = parser.parseUntil(['endcapture']);
815
- if (parser.match(['endcapture'])) {
816
- parser.advance();
817
- }
818
- else {
819
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
820
- }
821
- return new CaptureNode(val, body, token.loc, token.strip);
822
- }
823
- const parsers$6 = {
824
- capture: parseCapture,
825
- endcapture: parseUnexpected,
826
- };
827
-
828
- function parseFor(token, parser) {
829
- parser.requireExpression(token);
830
- const loop = parser.parseExp(token.expression);
831
- parser.advance();
832
- const body = parser.parseUntil(['endfor']);
833
- if (parser.match(['endfor'])) {
834
- parser.advance();
835
- }
836
- else {
837
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
838
- }
839
- return new ForNode(loop, body, token.loc, token.strip);
840
- }
841
- function parseBreak(token, parser) {
842
- parser.requireNoExpression(token);
843
- parser.advance();
844
- return new BreakNode(token.val, token.loc, token.strip);
845
- }
846
- function parseContinue(token, parser) {
847
- parser.requireNoExpression(token);
848
- parser.advance();
849
- return new ContinueNode(token.val, token.loc, token.strip);
850
- }
851
- const parsers$5 = {
852
- for: parseFor,
853
- break: parseBreak,
854
- continue: parseContinue,
855
- endfor: parseUnexpected,
856
- };
857
-
858
- function parseIf(token, parser) {
859
- parser.requireExpression(token);
860
- parser.advance();
861
- const body = parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']);
862
- const alternatives = [];
863
- while (parser.match(['else', 'elseif', 'elsif', 'elif'])) {
864
- const branchToken = parser.peek();
865
- alternatives.push(branchToken.name.toLowerCase() === 'else'
866
- ? parseElse(branchToken, parser)
867
- : parseElseIf(branchToken, parser));
868
- }
869
- if (parser.match(['endif'])) {
870
- parser.advance();
871
- }
872
- else {
873
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
874
- }
875
- return new IfNode(parser.parseExp(token.expression), body, alternatives, token.loc, token.strip);
876
- }
877
- function parseElseIf(token, parser) {
878
- parser.requireExpression(token);
879
- parser.advance();
880
- const body = parser.parseUntil(['else', 'elseif', 'elsif', 'elif', 'endif']);
881
- return new ElseIfNode(parser.parseExp(token.expression), body, token.loc, token.strip);
882
- }
883
- function parseElse(token, parser) {
884
- parser.requireNoExpression(token);
885
- parser.advance();
886
- const body = parser.parseUntil(['endif']);
887
- return new ElseNode(body, token.loc, token.strip);
888
- }
889
- const parsers$4 = {
890
- if: parseIf,
891
- elseif: parseUnexpected,
892
- elsif: parseUnexpected,
893
- elif: parseUnexpected,
894
- endif: parseUnexpected,
895
- };
896
-
897
- function parseInclude(token, parser) {
898
- parser.requireExpression(token);
899
- const val = parser.parseExp(token.expression);
900
- parser.advance();
901
- return new IncludeNode(val, token.loc, token.strip);
902
- }
903
- const parsers$3 = {
904
- include: parseInclude,
905
- };
906
-
907
- function parseMacro(token, parser) {
908
- parser.requireExpression(token);
909
- const name = parser.parseExp(token.expression);
910
- parser.advance();
911
- const body = parser.parseUntil(['endmacro']);
912
- if (parser.match(['endmacro'])) {
913
- parser.advance();
914
- }
915
- else {
916
- throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
917
- }
918
- return new MacroNode(name, body, token.loc, token.strip);
919
- }
920
- function parseCaller(token, parser) {
921
- parser.requireNoExpression(token);
922
- parser.advance();
923
- return new CallerNode(token.val, token.loc, token.strip);
924
- }
925
- const parsers$2 = {
926
- macro: parseMacro,
927
- caller: parseCaller,
928
- endmacro: parseUnexpected,
929
- };
930
-
931
- function parseSet(token, parser) {
932
- parser.requireExpression(token);
933
- const val = parser.parseExp(token.expression);
934
- parser.advance();
935
- return new SetNode(val, token.loc, token.strip);
936
- }
937
- const parsers$1 = {
938
- set: parseSet,
939
- };
940
-
941
- const parsers = {
942
- ...parsers$4,
943
- ...parsers$5,
944
- ...parsers$3,
945
- ...parsers$8,
946
- ...parsers$2,
947
- ...parsers$7,
948
- ...parsers$1,
949
- ...parsers$6,
950
- };
951
-
952
- class Safe extends String {
953
- constructor(value) {
954
- super(`${value}`);
955
- }
956
- }
957
-
958
- function escape(v) {
959
- return `${v}`
960
- .replace(/&/g, '&amp;')
961
- .replace(/"/g, '&#34;')
962
- .replace(/'/g, '&#39;')
963
- .replace(/</g, '&lt;')
964
- .replace(/>/g, '&gt;');
965
- }
966
-
967
- function abs(value = 0) {
968
- return Math.abs(value);
969
- }
970
- function add(value = 0, addend = 0) {
971
- return value + addend;
972
- }
973
- function capitalize(value = '') {
974
- return value.replace(/\b\w/g, (match) => match.toUpperCase());
975
- }
976
- function ceil(value = 0) {
977
- return Math.ceil(value);
978
- }
979
- function compact(value = []) {
980
- return value.filter((v) => v != null);
981
- }
982
- function div(value = 0, divisor = 1) {
983
- return value / divisor;
984
- }
985
- function entries(value = {}) {
986
- return Object.entries(value);
987
- }
988
- function even(value = 0) {
989
- return +value % 2 === 0;
990
- }
991
- function fallback(value, defaultValue, anyFalsy = false) {
992
- return anyFalsy ? value || defaultValue : (value ?? defaultValue);
993
- }
994
- function first(value = []) {
995
- return [...value][0];
996
- }
997
- function get(value, ...path) {
998
- return path.reduce((acc, cur) => acc && typeof acc === 'object' && cur in acc ? acc[cur] : undefined, value);
999
- }
1000
- function groupby(value = [], key) {
1001
- return value.reduce((o, v) => {
1002
- const k = v[key];
1003
- return {
1004
- ...o,
1005
- [k]: [...(o[k] || []), v],
1006
- };
1007
- }, {});
1008
- }
1009
- function join(value = [], separator = '') {
1010
- return [...value].join(separator);
1011
- }
1012
- function json(value = null, indent = 0) {
1013
- return new Safe(JSON.stringify(value, null, indent));
1014
- }
1015
- function keys(value = {}) {
1016
- return Object.keys(value);
1017
- }
1018
- function last(value = []) {
1019
- return [...value].reverse()[0];
1020
- }
1021
- function length(value = '') {
1022
- return value.length;
1023
- }
1024
- function lower(value = '') {
1025
- return value.toLowerCase();
1026
- }
1027
- function map(value = [], key, defaultValue) {
1028
- return value.map((o) => o[key] ?? defaultValue);
1029
- }
1030
- function max(value = 0, ...rest) {
1031
- return Math.max(value, ...rest);
1032
- }
1033
- function min(value = 0, ...rest) {
1034
- return Math.min(value, ...rest);
1035
- }
1036
- function mul(value = 0, multiplier = 1) {
1037
- return value * multiplier;
1038
- }
1039
- function odd(value = 0) {
1040
- return +value % 2 === 1;
1041
- }
1042
- function omit(value = {}, ...omitKeys) {
1043
- return Object.entries(value).reduce((o, [k, v]) => (omitKeys.includes(k) ? o : { ...o, [k]: v }), {});
1044
- }
1045
- function pick(value = {}, ...pickKeys) {
1046
- return pickKeys.reduce((o, k) => ({ ...o, [k]: value[k] }), {});
1047
- }
1048
- function repeat(value = '', count = 0) {
1049
- return value.repeat(count);
1050
- }
1051
- function replace(value = '', search, replacement) {
1052
- return value.replace(new RegExp(search, 'g'), replacement);
1053
- }
1054
- function reverse(value = []) {
1055
- return Array.isArray(value) ? value.reverse() : [...value].reverse().join('');
1056
- }
1057
- function safe(value = '') {
1058
- return new Safe(value);
1059
- }
1060
- function slice(value = '', start = 0, end) {
1061
- return value.slice(start, end);
1062
- }
1063
- function sort(value = []) {
1064
- return Array.isArray(value) ? value.sort() : [...value].sort().join('');
1065
- }
1066
- function split(value = '', separator = '') {
1067
- return value.split(separator);
1068
- }
1069
- function sub(value = 0, subtrahend = 0) {
1070
- return value - subtrahend;
1071
- }
1072
- function sum(value = []) {
1073
- return value.reduce((a, b) => a + b, 0);
1074
- }
1075
- function trim(value = '') {
1076
- return value.trim();
1077
- }
1078
- function truncate(value = '', maxLength = 0, truncateStr = '...') {
1079
- return (value.slice(0, maxLength) + (value.length > maxLength ? truncateStr : ''));
1080
- }
1081
- function unique(value = '') {
1082
- return Array.isArray(value)
1083
- ? Array.from(new Set(value))
1084
- : Array.from(new Set(value)).join('');
1085
- }
1086
- function upper(value = '') {
1087
- return value.toUpperCase();
1088
- }
1089
- function urldecode(value = '') {
1090
- return decodeURIComponent(value);
1091
- }
1092
- function urlencode(value = '') {
1093
- return encodeURIComponent(value);
1094
- }
1095
- function values(value = {}) {
1096
- return Object.values(value);
1097
- }
1098
-
1099
- var _filters = /*#__PURE__*/Object.freeze({
1100
- __proto__: null,
1101
- abs: abs,
1102
- add: add,
1103
- capitalize: capitalize,
1104
- ceil: ceil,
1105
- compact: compact,
1106
- div: div,
1107
- entries: entries,
1108
- escape: escape,
1109
- even: even,
1110
- fallback: fallback,
1111
- first: first,
1112
- get: get,
1113
- groupby: groupby,
1114
- join: join,
1115
- json: json,
1116
- keys: keys,
1117
- last: last,
1118
- length: length,
1119
- lower: lower,
1120
- map: map,
1121
- max: max,
1122
- min: min,
1123
- mul: mul,
1124
- odd: odd,
1125
- omit: omit,
1126
- pick: pick,
1127
- repeat: repeat,
1128
- replace: replace,
1129
- reverse: reverse,
1130
- safe: safe,
1131
- slice: slice,
1132
- sort: sort,
1133
- split: split,
1134
- sub: sub,
1135
- sum: sum,
1136
- trim: trim,
1137
- truncate: truncate,
1138
- unique: unique,
1139
- upper: upper,
1140
- urldecode: urldecode,
1141
- urlencode: urlencode,
1142
- values: values
1143
- });
1144
-
1145
- async function compileBlock({ val: { value }, loc }, compiler) {
1146
- compiler.pushRaw(loc, `if(b["${value}"]&&!(b["${value}"].u++)){`, `s+=await b["${value}"].s?.pop()?.()??"";`, '}');
1147
- }
1148
- async function compileSuper({ loc }, compiler) {
1149
- if (!compiler.state.block) {
1150
- compiler.options.debug?.(new CompileError('"super" should be used inside a block', compiler.template, loc));
1151
- return;
1152
- }
1153
- compiler.pushRaw(loc, `s+=await b["${compiler.state.block}"]?.s?.pop()?.()??"";`);
1154
- }
1155
- const compilers$b = {
1156
- [NodeType.BLOCK]: compileBlock,
1157
- [NodeType.SUPER]: compileSuper,
1158
- };
1159
-
1160
- const expTokenOperators = {
1161
- AND: '&&',
1162
- OR: '||',
1163
- IS: '',
1164
- NOT: '!',
1165
- EQ: '===',
1166
- NE: '!==',
1167
- GT: '>',
1168
- LT: '<',
1169
- GE: '>=',
1170
- LE: '<=',
1171
- IN: ' in ',
1172
- NI: ' in ',
1173
- OF: ' of ',
1174
- ADD: '+',
1175
- SUB: '-',
1176
- MUL: '*',
1177
- DIV: '/',
1178
- MOD: '%',
1179
- PIPE: '',
1180
- SET: '=',
1181
- LP: '(',
1182
- RP: ')',
1183
- COMMA: ',',
1184
- DOT: '.',
1185
- ID: '',
1186
- LIT: '',
1187
- IF: '',
1188
- ELSE: '',
1189
- };
1190
-
1191
- const CONTEXT = 'c';
1192
- const ESCAPE = 'e';
1193
- const FILTERS = 'f';
1194
-
1195
- class ExpCompiler {
1196
- constructor() {
1197
- Object.defineProperty(this, "context", {
1198
- enumerable: true,
1199
- configurable: true,
1200
- writable: true,
1201
- value: void 0
1202
- });
1203
- Object.defineProperty(this, "filters", {
1204
- enumerable: true,
1205
- configurable: true,
1206
- writable: true,
1207
- value: void 0
1208
- });
1209
- }
1210
- compile(expression, context = CONTEXT, filters = FILTERS) {
1211
- this.context = context;
1212
- this.filters = filters;
1213
- return expression ? this.compileExp(expression) : '""';
1214
- }
1215
- compileExp(expression) {
1216
- switch (expression.type) {
1217
- case 'NOT':
1218
- return this.compileNot(expression);
1219
- case 'ID':
1220
- return this.compileId(expression);
1221
- case 'LIT':
1222
- return this.compileLit(expression);
1223
- case 'PIPE':
1224
- return this.compilePipe(expression);
1225
- case 'OF':
1226
- return this.compileOf(expression);
1227
- case 'SET':
1228
- return this.compileSet(expression);
1229
- case 'IS':
1230
- return this.compileIs(expression);
1231
- case 'AND':
1232
- case 'OR':
1233
- case 'EQ':
1234
- case 'NE':
1235
- case 'GT':
1236
- case 'LT':
1237
- case 'GE':
1238
- case 'LE':
1239
- case 'IN':
1240
- case 'NI':
1241
- case 'ADD':
1242
- case 'SUB':
1243
- case 'MUL':
1244
- case 'DIV':
1245
- case 'MOD':
1246
- return this.compileBinary(expression);
1247
- case 'IF':
1248
- return this.compileTernary(expression);
1249
- case 'SEQ':
1250
- return this.compileSeq(expression);
1251
- default:
1252
- return '';
1253
- }
1254
- }
1255
- compileNot({ argument }) {
1256
- return `!${this.compileExp(argument)}`;
1257
- }
1258
- compileId({ value, path, args }) {
1259
- let s = `${this.context}.${value}`;
1260
- if (path) {
1261
- s += path.map((p) => `.${p.value}`).join('');
1262
- }
1263
- if (args) {
1264
- s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
1265
- }
1266
- return s;
1267
- }
1268
- compileLit({ value }) {
1269
- return value === undefined ? 'undefined' : JSON.stringify(value);
1270
- }
1271
- compileSeq({ elements }) {
1272
- return elements.map((element) => this.compileExp(element)).toString();
1273
- }
1274
- compilePipe({ left, right }) {
1275
- const { value: name, args = [] } = right;
1276
- return `(await ${this.filters}.${name}.call(${[this.context, this.compileExp(left), ...args.map((arg) => (arg.type === 'SET' ? `${this.context}.${arg.left.value}=${this.compileExp(arg.right)}` : this.compileExp(arg)))].join(',')}))`;
1277
- }
1278
- compileOf({ left, right }) {
1279
- // destructuring
1280
- if (left.type === 'SEQ') {
1281
- return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
1282
- }
1283
- return `const ${left.value} of ${this.compileExp(right)}`;
1284
- }
1285
- compileSet({ left, right }) {
1286
- if (left.type === 'ID') {
1287
- return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
1288
- }
1289
- // destructuring
1290
- return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
1291
- }
1292
- compileIs({ left, right }) {
1293
- return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
1294
- }
1295
- compileBinary({ type, left, right }) {
1296
- const ret = `${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)}`;
1297
- return type === 'NI' ? `!${ret}` : ret;
1298
- }
1299
- compileTernary({ test, consequent, alternative }) {
1300
- return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
1301
- }
1302
- }
1303
-
1304
- async function compileCall({ val, body, loc }, compiler) {
1305
- compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
1306
- await compiler.compileNodes(body);
1307
- compiler.pushRaw(null, '});');
1308
- }
1309
- const compilers$a = {
1310
- [NodeType.CALL]: compileCall,
1311
- };
1312
-
1313
- async function compileCapture({ val, body, loc }, compiler) {
1314
- compiler.pushRaw(loc, `${compiler.context}.${val.value}=await(async(s)=>{`);
1315
- await compiler.compileNodes(body);
1316
- compiler.pushRaw(null, 'return s;})("");');
1317
- }
1318
- const compilers$9 = {
1319
- [NodeType.CAPTURE]: compileCapture,
1320
- };
1321
-
1322
- async function compileComment({ val, loc }, compiler) {
1323
- if (!compiler.options.stripComments) {
1324
- compiler.pushStr(loc, `<!--${val}-->`);
1325
- }
1326
- }
1327
- const compilers$8 = {
1328
- [NodeType.COMMENT]: compileComment,
1329
- };
1330
-
1331
- async function compileFor({ loop, body }, compiler) {
1332
- const { context } = compiler;
1333
- if (loop.left.type === 'SEQ') {
1334
- compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.elements.map(({ value }) => value).join(',')},`, '};');
1335
- }
1336
- else {
1337
- compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, '};');
1338
- }
1339
- await compiler.compileNodes(body);
1340
- compiler.out();
1341
- compiler.pushRaw(null, '}');
1342
- }
1343
- function compileBreak({ loc }, compiler) {
1344
- compiler.pushRaw(loc, 'break;');
1345
- }
1346
- function compileContinue({ loc }, compiler) {
1347
- compiler.pushRaw(loc, 'continue;');
1367
+ value: strip
1368
+ });
1369
+ Object.defineProperty(this, "type", {
1370
+ enumerable: true,
1371
+ configurable: true,
1372
+ writable: true,
1373
+ value: 'INCLUDE'
1374
+ });
1375
+ }
1348
1376
  }
1349
- const compilers$7 = {
1350
- [NodeType.FOR]: compileFor,
1351
- [NodeType.BREAK]: compileBreak,
1352
- [NodeType.CONTINUE]: compileContinue,
1353
- };
1354
1377
 
1355
- async function compileIf({ test, body, alternatives }, compiler) {
1356
- compiler.pushRaw(test.loc, `if(${new ExpCompiler().compile(test, compiler.context)}){`);
1357
- await compiler.compileNodes(body);
1358
- compiler.pushRaw(null, '}');
1359
- for (const branch of alternatives) {
1360
- if (branch.type === NodeType.ELSE_IF) {
1361
- compiler.pushRaw(branch.test.loc, `else if(${new ExpCompiler().compile(branch.test, compiler.context)}){`);
1362
- }
1363
- else {
1364
- compiler.pushRaw(null, 'else{');
1365
- }
1366
- await compiler.compileNodes(branch.body);
1367
- compiler.pushRaw(null, '}');
1378
+ function parseInclude(token, parser) {
1379
+ if (!token.expression) {
1380
+ parser.emitExpErr(token);
1381
+ return;
1368
1382
  }
1383
+ parser.advance();
1384
+ return new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
1369
1385
  }
1370
- const compilers$6 = {
1371
- [NodeType.IF]: compileIf,
1386
+ const parsers$4 = {
1387
+ include: parseInclude,
1372
1388
  };
1373
1389
 
1374
- async function compileInclude({ val: { value }, loc }, compiler) {
1375
- compiler.pushRaw(loc, `s+=await p["${value}"]?.()??"";`);
1376
- }
1377
- const compilers$5 = {
1378
- [NodeType.INCLUDE]: compileInclude,
1390
+ const plugin$4 = {
1391
+ compilers: compilers$4,
1392
+ parsers: parsers$4,
1379
1393
  };
1380
1394
 
1381
1395
  async function compileMacro({ val: { left, right }, loc, body }, compiler) {
@@ -1383,11 +1397,11 @@ ${output
1383
1397
  const { elements } = right;
1384
1398
  const expCompiler = new ExpCompiler();
1385
1399
  compiler.pushRaw(loc, `${expCompiler.compile(left)}=(${elements
1386
- .map((el) => el.type === 'SET'
1400
+ .map((el) => el.type === 'ASSIGN'
1387
1401
  ? `${el.left.value}=${expCompiler.compile(el.right)}`
1388
1402
  : el.value)
1389
1403
  .join(',')})=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, elements
1390
- .map((el) => el.type === 'SET' ? el.left.value : el.value)
1404
+ .map((el) => el.type === 'ASSIGN' ? el.left.value : el.value)
1391
1405
  .join(','), '};');
1392
1406
  await compiler.compileNodes(body);
1393
1407
  compiler.out();
@@ -1396,254 +1410,358 @@ ${output
1396
1410
  function compileCaller({ loc }, compiler) {
1397
1411
  compiler.pushRaw(loc, 'await _c?.();');
1398
1412
  }
1399
- const compilers$4 = {
1400
- [NodeType.MACRO]: compileMacro,
1401
- [NodeType.CALLER]: compileCaller,
1413
+ const compilers$3 = {
1414
+ MACRO: compileMacro,
1415
+ CALLER: compileCaller,
1402
1416
  };
1403
1417
 
1404
- async function compileOutput({ exp }, compiler) {
1405
- compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1418
+ class MacroNode extends Traversal {
1419
+ constructor(val, body, loc, strip) {
1420
+ super();
1421
+ Object.defineProperty(this, "val", {
1422
+ enumerable: true,
1423
+ configurable: true,
1424
+ writable: true,
1425
+ value: val
1426
+ });
1427
+ Object.defineProperty(this, "body", {
1428
+ enumerable: true,
1429
+ configurable: true,
1430
+ writable: true,
1431
+ value: body
1432
+ });
1433
+ Object.defineProperty(this, "loc", {
1434
+ enumerable: true,
1435
+ configurable: true,
1436
+ writable: true,
1437
+ value: loc
1438
+ });
1439
+ Object.defineProperty(this, "strip", {
1440
+ enumerable: true,
1441
+ configurable: true,
1442
+ writable: true,
1443
+ value: strip
1444
+ });
1445
+ Object.defineProperty(this, "type", {
1446
+ enumerable: true,
1447
+ configurable: true,
1448
+ writable: true,
1449
+ value: 'MACRO'
1450
+ });
1451
+ }
1406
1452
  }
1407
- const compilers$3 = {
1408
- [NodeType.OUTPUT]: compileOutput,
1453
+ class CallerNode extends Traversal {
1454
+ constructor(val, loc, strip) {
1455
+ super();
1456
+ Object.defineProperty(this, "val", {
1457
+ enumerable: true,
1458
+ configurable: true,
1459
+ writable: true,
1460
+ value: val
1461
+ });
1462
+ Object.defineProperty(this, "loc", {
1463
+ enumerable: true,
1464
+ configurable: true,
1465
+ writable: true,
1466
+ value: loc
1467
+ });
1468
+ Object.defineProperty(this, "strip", {
1469
+ enumerable: true,
1470
+ configurable: true,
1471
+ writable: true,
1472
+ value: strip
1473
+ });
1474
+ Object.defineProperty(this, "type", {
1475
+ enumerable: true,
1476
+ configurable: true,
1477
+ writable: true,
1478
+ value: 'CALLER'
1479
+ });
1480
+ }
1481
+ }
1482
+
1483
+ const wm = new WeakMap();
1484
+ function parseMacro(token, parser) {
1485
+ if (!token.expression) {
1486
+ parser.emitExpErr(token);
1487
+ return;
1488
+ }
1489
+ wm.set(parser, true);
1490
+ parser.advance();
1491
+ const body = parser.parseUntil(['endmacro']);
1492
+ wm.set(parser, false);
1493
+ if (parser.match(['endmacro'])) {
1494
+ parser.advance();
1495
+ }
1496
+ else {
1497
+ throw parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
1498
+ }
1499
+ return new MacroNode(parser.parseExp(token.expression), body, token.loc, token.strip);
1500
+ }
1501
+ function parseCaller(token, parser) {
1502
+ if (token.expression) {
1503
+ parser.emitExpErr(token, false);
1504
+ return;
1505
+ }
1506
+ if (!wm.get(parser)) {
1507
+ parser.options.debug?.(new CompileError('"caller" directive used outside of a macro', parser.template, token.loc));
1508
+ return;
1509
+ }
1510
+ parser.advance();
1511
+ return new CallerNode(token.val, token.loc, token.strip);
1512
+ }
1513
+ const parsers$3 = {
1514
+ macro: parseMacro,
1515
+ caller: parseCaller,
1516
+ endmacro: createUnexpected,
1409
1517
  };
1410
1518
 
1411
- async function compileSet({ val, loc }, compiler) {
1412
- compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
1519
+ const plugin$3 = {
1520
+ compilers: compilers$3,
1521
+ parsers: parsers$3,
1522
+ };
1523
+
1524
+ async function compileOutput({ exp }, compiler) {
1525
+ compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1413
1526
  }
1414
1527
  const compilers$2 = {
1415
- [NodeType.SET]: compileSet,
1528
+ OUTPUT: compileOutput,
1416
1529
  };
1417
1530
 
1418
- async function compileText({ val, loc, strip: { start, end } }, compiler) {
1419
- if (start || compiler.options.trimWhitespace) {
1420
- val = val.replace(/^\s+/, '');
1421
- }
1422
- if (end || compiler.options.trimWhitespace) {
1423
- val = val.replace(/\s+$/, '');
1531
+ class OutputNode extends Traversal {
1532
+ constructor(val, loc, strip, exp) {
1533
+ super();
1534
+ Object.defineProperty(this, "val", {
1535
+ enumerable: true,
1536
+ configurable: true,
1537
+ writable: true,
1538
+ value: val
1539
+ });
1540
+ Object.defineProperty(this, "loc", {
1541
+ enumerable: true,
1542
+ configurable: true,
1543
+ writable: true,
1544
+ value: loc
1545
+ });
1546
+ Object.defineProperty(this, "strip", {
1547
+ enumerable: true,
1548
+ configurable: true,
1549
+ writable: true,
1550
+ value: strip
1551
+ });
1552
+ Object.defineProperty(this, "exp", {
1553
+ enumerable: true,
1554
+ configurable: true,
1555
+ writable: true,
1556
+ value: exp
1557
+ });
1558
+ Object.defineProperty(this, "type", {
1559
+ enumerable: true,
1560
+ configurable: true,
1561
+ writable: true,
1562
+ value: 'OUTPUT'
1563
+ });
1424
1564
  }
1425
- compiler.pushStr(loc, val);
1426
1565
  }
1427
- const compilers$1 = {
1428
- [NodeType.TEXT]: compileText,
1429
- };
1430
1566
 
1431
- const compilers = {
1432
- ...compilers$6,
1433
- ...compilers$7,
1434
- ...compilers$5,
1435
- ...compilers$b,
1436
- ...compilers$1,
1437
- ...compilers$3,
1438
- ...compilers$8,
1439
- ...compilers$4,
1440
- ...compilers$a,
1441
- ...compilers$2,
1442
- ...compilers$9,
1567
+ function parseOutput(token, parser) {
1568
+ parser.advance();
1569
+ return new OutputNode(token.val, token.loc, token.strip, parser.parseExp(token));
1570
+ }
1571
+ const parsers$2 = {
1572
+ output: parseOutput,
1443
1573
  };
1444
1574
 
1445
- const parserOptions = {
1446
- commentOpen: '{{#',
1447
- commentClose: '}}',
1448
- directiveOpen: '{{',
1449
- directiveClose: '}}',
1450
- outputOpen: '{{=',
1451
- outputClose: '}}',
1452
- parsers,
1453
- debug: () => { },
1454
- };
1455
- const compilerOptions = {
1456
- ...parserOptions,
1457
- trimWhitespace: false,
1458
- stripComments: false,
1459
- compilers,
1460
- loader: async () => '',
1575
+ const plugin$2 = {
1576
+ compilers: compilers$2,
1577
+ parsers: parsers$2,
1461
1578
  };
1462
- const renderOptions = {
1463
- ...compilerOptions,
1464
- globals: {},
1465
- filters: _filters,
1466
- autoEscape: true,
1467
- plugins: [],
1579
+
1580
+ async function compileSet({ val, loc }, compiler) {
1581
+ compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
1582
+ }
1583
+ const compilers$1 = {
1584
+ SET: compileSet,
1468
1585
  };
1469
1586
 
1470
- /**
1471
- * Contains the source map information.
1472
- * @example
1473
- * - template:
1474
- * {{ foo }}
1475
- *
1476
- * - compiled:
1477
- * s+=e(foo);
1478
- *
1479
- * - sourceMap:
1480
- * Mapping {
1481
- * source: {
1482
- * start: {
1483
- * line: 2,
1484
- * column: 4,
1485
- * },
1486
- * end: {
1487
- * line: 3,
1488
- * column: 5,
1489
- * },
1490
- * },
1491
- * target: {
1492
- * start: {
1493
- * line: 2,
1494
- * column: 3,
1495
- * },
1496
- * end: {
1497
- * line: 3,
1498
- * column: 8,
1499
- * },
1500
- * }
1501
- * }
1502
- */
1503
- class SourceMap {
1504
- constructor() {
1505
- Object.defineProperty(this, "mappings", {
1587
+ class SetNode extends Traversal {
1588
+ constructor(val, loc, strip) {
1589
+ super();
1590
+ Object.defineProperty(this, "val", {
1591
+ enumerable: true,
1592
+ configurable: true,
1593
+ writable: true,
1594
+ value: val
1595
+ });
1596
+ Object.defineProperty(this, "loc", {
1597
+ enumerable: true,
1598
+ configurable: true,
1599
+ writable: true,
1600
+ value: loc
1601
+ });
1602
+ Object.defineProperty(this, "strip", {
1603
+ enumerable: true,
1604
+ configurable: true,
1605
+ writable: true,
1606
+ value: strip
1607
+ });
1608
+ Object.defineProperty(this, "type", {
1506
1609
  enumerable: true,
1507
1610
  configurable: true,
1508
1611
  writable: true,
1509
- value: []
1612
+ value: 'SET'
1510
1613
  });
1511
1614
  }
1512
- addMapping(source, target) {
1513
- this.mappings.push({
1514
- source,
1515
- target,
1516
- });
1615
+ }
1616
+
1617
+ function parseSet(token, parser) {
1618
+ if (!token.expression) {
1619
+ parser.emitExpErr(token);
1620
+ return;
1517
1621
  }
1518
- getSourceLoc({ line, column }) {
1519
- return this.mappings
1520
- .filter(({ target: { start, end } }) => start.line <= line &&
1521
- end.line >= line &&
1522
- (start.line < line || start.column <= column) &&
1523
- (end.line > line || end.column >= column))
1524
- .map(({ source }) => source);
1622
+ parser.advance();
1623
+ return new SetNode(parser.parseExp(token.expression), token.loc, token.strip);
1624
+ }
1625
+ const parsers$1 = {
1626
+ set: parseSet,
1627
+ };
1628
+
1629
+ const plugin$1 = {
1630
+ compilers: compilers$1,
1631
+ parsers: parsers$1,
1632
+ };
1633
+
1634
+ async function compileText({ val, loc, strip: { start, end } }, compiler) {
1635
+ if (start || compiler.options.trimWhitespace) {
1636
+ val = val.replace(/^\s+/, '');
1637
+ }
1638
+ if (end || compiler.options.trimWhitespace) {
1639
+ val = val.replace(/\s+$/, '');
1525
1640
  }
1641
+ compiler.pushStr(loc, val);
1526
1642
  }
1643
+ const compilers = {
1644
+ TEXT: compileText,
1645
+ };
1527
1646
 
1528
- class OutScript extends SourceMap {
1529
- constructor() {
1530
- super(...arguments);
1531
- Object.defineProperty(this, "code", {
1647
+ class TextNode extends Traversal {
1648
+ constructor(val, loc, strip) {
1649
+ super();
1650
+ Object.defineProperty(this, "val", {
1532
1651
  enumerable: true,
1533
1652
  configurable: true,
1534
1653
  writable: true,
1535
- value: ''
1536
- });
1537
- }
1538
- get script() {
1539
- // eslint-disable-next-line no-new-func
1540
- return new Function(CONTEXT, ESCAPE, FILTERS, this.code);
1541
- }
1542
- start() {
1543
- this.pushRaw(null, 'return(async()=>{', 'let s="";');
1544
- }
1545
- end() {
1546
- this.pushRaw(null, 'return s;', '})();');
1547
- }
1548
- pushRaw(loc, ...lines) {
1549
- const start = this.code.length;
1550
- for (const line of lines) {
1551
- this.code += line;
1552
- }
1553
- if (!loc) {
1554
- return;
1555
- }
1556
- this.addMapping(loc, {
1557
- start: {
1558
- line: 1,
1559
- column: start,
1560
- },
1561
- end: {
1562
- line: 1,
1563
- column: this.code.length,
1564
- },
1654
+ value: val
1565
1655
  });
1566
- }
1567
- pushStr(loc, s) {
1568
- if (s) {
1569
- this.pushRaw(loc, `s+="${s
1570
- .replace(/\\/g, '\\\\')
1571
- .replace(/"/g, '\\"')
1572
- .replace(/[\n\r]/g, '\\n')}";`);
1573
- }
1574
- }
1575
- pushVar(loc, v) {
1576
- this.pushRaw(loc, `s+=${ESCAPE}(${v});`);
1577
- }
1578
- }
1579
-
1580
- class Context extends OutScript {
1581
- constructor() {
1582
- super(...arguments);
1583
- Object.defineProperty(this, "context", {
1656
+ Object.defineProperty(this, "loc", {
1584
1657
  enumerable: true,
1585
1658
  configurable: true,
1586
1659
  writable: true,
1587
- value: CONTEXT
1660
+ value: loc
1588
1661
  });
1589
- Object.defineProperty(this, "contexts", {
1662
+ Object.defineProperty(this, "strip", {
1590
1663
  enumerable: true,
1591
1664
  configurable: true,
1592
1665
  writable: true,
1593
- value: [CONTEXT]
1666
+ value: strip
1594
1667
  });
1595
- Object.defineProperty(this, "index", {
1668
+ Object.defineProperty(this, "type", {
1596
1669
  enumerable: true,
1597
1670
  configurable: true,
1598
1671
  writable: true,
1599
- value: 0
1672
+ value: 'TEXT'
1600
1673
  });
1601
1674
  }
1602
- in() {
1603
- this.context = `${this.context}_${this.index++}`;
1604
- this.contexts.push(this.context);
1605
- return this.context;
1606
- }
1607
- out() {
1608
- if (this.context === CONTEXT) {
1609
- return;
1610
- }
1611
- this.contexts.pop();
1612
- this.context = this.contexts.at(-1);
1613
- }
1614
1675
  }
1615
1676
 
1616
- const expTokenPrecedences = {
1617
- COMMA: 5,
1618
- IF: 10,
1619
- ELSE: 10,
1620
- SET: 15,
1621
- LP: 20,
1622
- RP: 20,
1623
- OR: 25,
1624
- AND: 30,
1625
- IS: 40,
1626
- EQ: 40,
1627
- NE: 40,
1628
- GT: 40,
1629
- LT: 40,
1630
- GE: 40,
1631
- LE: 40,
1632
- IN: 40,
1633
- NI: 40,
1634
- OF: 40,
1635
- ADD: 50,
1636
- SUB: 50,
1637
- MUL: 60,
1638
- DIV: 60,
1639
- MOD: 60,
1640
- NOT: 70,
1641
- PIPE: 80,
1642
- DOT: 90,
1643
- ID: 90,
1644
- LIT: 90,
1677
+ function parseText(token, parser) {
1678
+ parser.advance();
1679
+ return new TextNode(token.val, token.loc, token.strip);
1680
+ }
1681
+ const parsers = {
1682
+ text: parseText,
1683
+ };
1684
+
1685
+ const plugin = {
1686
+ compilers,
1687
+ parsers,
1688
+ };
1689
+
1690
+ const plugins = [
1691
+ plugin$a,
1692
+ plugin$9,
1693
+ plugin$7,
1694
+ plugin$8,
1695
+ plugin$6,
1696
+ plugin$5,
1697
+ plugin$4,
1698
+ plugin$3,
1699
+ plugin$1,
1700
+ plugin,
1701
+ plugin$2,
1702
+ ];
1703
+
1704
+ const baseOptions = {
1705
+ filters: _filters,
1706
+ parsers: {},
1707
+ compilers: {},
1708
+ plugins,
1709
+ debug: () => { },
1710
+ };
1711
+ const parserOptions = {
1712
+ ...baseOptions,
1713
+ commentOpen: '{{#',
1714
+ commentClose: '}}',
1715
+ directiveOpen: '{{',
1716
+ directiveClose: '}}',
1717
+ outputOpen: '{{=',
1718
+ outputClose: '}}',
1719
+ };
1720
+ const compilerOptions = {
1721
+ ...parserOptions,
1722
+ trimWhitespace: false,
1723
+ stripComments: false,
1724
+ loader: async () => '',
1725
+ };
1726
+ const renderOptions = {
1727
+ ...compilerOptions,
1728
+ globals: {},
1729
+ autoEscape: true,
1730
+ };
1731
+ const mergeOptions = (defaultOptions, options) => {
1732
+ const mergedOptions = {
1733
+ ...defaultOptions,
1734
+ ...options,
1735
+ };
1736
+ defaultOptions.plugins?.forEach((plugin) => {
1737
+ Object.assign(mergedOptions.filters, plugin.filters ?? {});
1738
+ Object.assign(mergedOptions.parsers, plugin.parsers ?? {});
1739
+ Object.assign(mergedOptions.compilers, plugin.compilers ?? {});
1740
+ });
1741
+ options?.plugins?.forEach((plugin) => {
1742
+ Object.assign(mergedOptions.filters, plugin.filters ?? {});
1743
+ Object.assign(mergedOptions.parsers, plugin.parsers ?? {});
1744
+ Object.assign(mergedOptions.compilers, plugin.compilers ?? {});
1745
+ });
1746
+ return mergedOptions;
1645
1747
  };
1646
1748
 
1749
+ function updatePosition(str, pos) {
1750
+ const newlines = (str.match(/\n/g) || []).length;
1751
+ if (newlines > 0) {
1752
+ pos.line += newlines;
1753
+ const lastNewline = str.lastIndexOf('\n');
1754
+ pos.column = str.length - lastNewline;
1755
+ }
1756
+ else {
1757
+ pos.column += str.length;
1758
+ }
1759
+ return {
1760
+ line: pos.line,
1761
+ column: pos.column,
1762
+ };
1763
+ }
1764
+
1647
1765
  const expTokenTypes = {
1648
1766
  and: 'AND',
1649
1767
  or: 'OR',
@@ -1670,33 +1788,12 @@ ${output
1670
1788
  null: 'LIT',
1671
1789
  undefined: 'LIT',
1672
1790
  '|': 'PIPE',
1673
- '=': 'SET',
1791
+ '=': 'ASSIGN',
1674
1792
  '(': 'LP',
1675
1793
  ')': 'RP',
1676
1794
  ',': 'COMMA',
1677
1795
  '.': 'DOT',
1678
1796
  };
1679
-
1680
- /**
1681
- * Update position by a given string, and return a new position with the
1682
- * updated values.
1683
- */
1684
- function updatePosition(str, pos) {
1685
- const newlines = (str.match(/\n/g) || []).length;
1686
- if (newlines > 0) {
1687
- pos.line += newlines;
1688
- const lastNewline = str.lastIndexOf('\n');
1689
- pos.column = str.length - lastNewline;
1690
- }
1691
- else {
1692
- pos.column += str.length;
1693
- }
1694
- return {
1695
- line: pos.line,
1696
- column: pos.column,
1697
- };
1698
- }
1699
-
1700
1797
  class ExpTokenizer {
1701
1798
  constructor(template) {
1702
1799
  Object.defineProperty(this, "template", {
@@ -1907,6 +2004,36 @@ ${output
1907
2004
  return /[\w$]/.test(char);
1908
2005
  }
1909
2006
 
2007
+ const expTokenPrecedences = {
2008
+ COMMA: 5,
2009
+ IF: 10,
2010
+ ELSE: 10,
2011
+ ASSIGN: 15,
2012
+ LP: 20,
2013
+ RP: 20,
2014
+ OR: 25,
2015
+ AND: 30,
2016
+ IS: 40,
2017
+ EQ: 40,
2018
+ NE: 40,
2019
+ GT: 40,
2020
+ LT: 40,
2021
+ GE: 40,
2022
+ LE: 40,
2023
+ IN: 40,
2024
+ NI: 40,
2025
+ OF: 40,
2026
+ ADD: 50,
2027
+ SUB: 50,
2028
+ MUL: 60,
2029
+ DIV: 60,
2030
+ MOD: 60,
2031
+ NOT: 70,
2032
+ PIPE: 80,
2033
+ DOT: 90,
2034
+ ID: 90,
2035
+ LIT: 90,
2036
+ };
1910
2037
  class ExpParser {
1911
2038
  constructor(template) {
1912
2039
  Object.defineProperty(this, "template", {
@@ -2006,7 +2133,7 @@ ${output
2006
2133
  type: 'ID',
2007
2134
  value: token.value,
2008
2135
  };
2009
- if (this.check('DOT')) {
2136
+ if (this.match('DOT')) {
2010
2137
  left.path = this.parsePath();
2011
2138
  }
2012
2139
  const lp = this.consume('LP');
@@ -2063,7 +2190,7 @@ ${output
2063
2190
  token.type === 'MUL' ||
2064
2191
  token.type === 'DIV' ||
2065
2192
  token.type === 'MOD' ||
2066
- token.type === 'SET') {
2193
+ token.type === 'ASSIGN') {
2067
2194
  if (!left) {
2068
2195
  throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
2069
2196
  }
@@ -2083,7 +2210,7 @@ ${output
2083
2210
  if (!left) {
2084
2211
  throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
2085
2212
  }
2086
- if (!this.check('ID')) {
2213
+ if (!this.match('ID')) {
2087
2214
  throw new CompileError('expected "ID" after "PIPE"', this.template, token.loc);
2088
2215
  }
2089
2216
  left = {
@@ -2123,7 +2250,7 @@ ${output
2123
2250
  }
2124
2251
  parseSequence() {
2125
2252
  const elements = [];
2126
- while (!this.check('RP')) {
2253
+ while (!this.match('RP')) {
2127
2254
  const element = this.parseExp((t) => t.type === 'COMMA' ? 'BREAK' : undefined);
2128
2255
  if (element) {
2129
2256
  elements.push(element);
@@ -2162,11 +2289,11 @@ ${output
2162
2289
  peek() {
2163
2290
  return this.tokens.at(this.index) ?? null;
2164
2291
  }
2165
- check(type) {
2292
+ match(type) {
2166
2293
  return this.peek()?.type === type;
2167
2294
  }
2168
2295
  consume(type) {
2169
- if (this.check(type)) {
2296
+ if (this.match(type)) {
2170
2297
  return this.next();
2171
2298
  }
2172
2299
  }
@@ -2237,10 +2364,7 @@ ${output
2237
2364
  writable: true,
2238
2365
  value: 1
2239
2366
  });
2240
- this.options = {
2241
- ...parserOptions,
2242
- ...options,
2243
- };
2367
+ this.options = mergeOptions(parserOptions, options);
2244
2368
  const { commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = this.options;
2245
2369
  this.tokenPatterns = [
2246
2370
  [TokenType.COMMENT, commentOpen, commentClose],
@@ -2404,49 +2528,23 @@ ${output
2404
2528
  if (token.strip?.before && prevToken?.type === TokenType.TEXT) {
2405
2529
  prevToken.strip.end = true;
2406
2530
  }
2407
- switch (token.type) {
2408
- case TokenType.COMMENT:
2409
- nodes.push(this.createComment(token));
2410
- break;
2411
- case TokenType.DIRECTIVE:
2412
- nodes.push(this.createDirective(token));
2413
- break;
2414
- case TokenType.OUTPUT:
2415
- nodes.push(this.createOutput(token));
2416
- break;
2417
- case TokenType.TEXT:
2418
- nodes.push(this.createText(token));
2419
- break;
2420
- }
2531
+ nodes.push(this.options.parsers[token.name?.toLowerCase() ??
2532
+ token.type?.toLowerCase()]?.(token, this) ?? this.createUnknownNode(token));
2421
2533
  prevToken = token;
2422
2534
  }
2423
2535
  return nodes;
2424
2536
  }
2425
- createComment({ val, loc, strip }) {
2426
- this.advance();
2427
- return new CommentNode(val, loc, strip);
2428
- }
2429
- createOutput({ val, loc, strip }) {
2430
- this.advance();
2431
- return new OutputNode(val, loc, strip, this.parseExp({ val, loc }));
2432
- }
2433
- createText({ val, loc, strip }) {
2434
- this.advance();
2435
- return new TextNode(val, loc, strip);
2436
- }
2437
- createDirective(token) {
2438
- return (this.options.parsers[token.name.toLowerCase()]?.(token, this) ??
2439
- this.createUnknownDirective(token));
2440
- }
2441
- createUnexpectedDirective(token) {
2442
- this.options.debug?.(new CompileError(`Unexpected "${token.name}" directive`, this.template, token.loc));
2537
+ createUnexpectedNode(token) {
2538
+ const name = token.name ?? token.type;
2539
+ this.options.debug?.(new CompileError(`Unexpected "${name}" directive`, this.template, token.loc));
2443
2540
  this.advance();
2444
- return new UnexpectedDirectiveNode(token.name, token.val, token.loc, token.strip);
2541
+ return new UnexpectedNode(name, token.val, token.loc, token.strip);
2445
2542
  }
2446
- createUnknownDirective(token) {
2447
- this.options.debug?.(new CompileError(`Unknown "${token.name}" directive`, this.template, token.loc));
2543
+ createUnknownNode(token) {
2544
+ const name = token.name ?? token.type;
2545
+ this.options.debug?.(new CompileError(`Unknown "${name}" node`, this.template, token.loc));
2448
2546
  this.advance();
2449
- return new UnknownDirectiveNode(token.name, token.val, token.loc, token.strip);
2547
+ return new UnknownNode(name, token.val, token.loc, token.strip);
2450
2548
  }
2451
2549
  parseExp({ val, loc }) {
2452
2550
  return this.expParser.parse(val, loc);
@@ -2460,15 +2558,10 @@ ${output
2460
2558
  match(names, token = this.peek()) {
2461
2559
  return names.includes(token?.name);
2462
2560
  }
2463
- requireExpression({ expression, name, loc }) {
2464
- if (!expression) {
2465
- throw this.options.debug?.(new CompileError(`"${name}" requires expression`, this.template, loc));
2466
- }
2467
- }
2468
- requireNoExpression({ expression, name, loc }) {
2469
- if (expression) {
2470
- throw this.options.debug?.(new CompileError(`"${name}" should not have expression`, this.template, loc));
2471
- }
2561
+ emitExpErr({ name, loc }, required = true) {
2562
+ this.options.debug?.(new CompileError(required
2563
+ ? `"${name}" requires expression`
2564
+ : `"${name}" should not have expression`, this.template, loc));
2472
2565
  }
2473
2566
  }
2474
2567
 
@@ -2517,10 +2610,7 @@ ${output
2517
2610
  writable: true,
2518
2611
  value: void 0
2519
2612
  });
2520
- this.options = {
2521
- ...compilerOptions,
2522
- ...options,
2523
- };
2613
+ this.options = mergeOptions(compilerOptions, options);
2524
2614
  }
2525
2615
  async compile(template, root = true, partials = new Map(), blocks = new Map()) {
2526
2616
  this.template = template;
@@ -2588,12 +2678,12 @@ ${output
2588
2678
  const partials = new Map();
2589
2679
  const blocks = [];
2590
2680
  const traverse = (node) => {
2591
- if (node.type === NodeType.INCLUDE) {
2681
+ if (node.type === 'INCLUDE') {
2592
2682
  if (!partials.has(node.val.value)) {
2593
2683
  partials.set(node.val.value, node);
2594
2684
  }
2595
2685
  }
2596
- if (node.type === NodeType.BLOCK) {
2686
+ if (node.type === 'BLOCK') {
2597
2687
  blocks.push(node);
2598
2688
  }
2599
2689
  node.traverse(traverse);
@@ -2605,7 +2695,7 @@ ${output
2605
2695
  };
2606
2696
  }
2607
2697
  async compileNode(node) {
2608
- if (node.type === NodeType.TEMPLATE) {
2698
+ if (node.type === 'TEMPLATE') {
2609
2699
  await this.compileNodes(node.body);
2610
2700
  return;
2611
2701
  }
@@ -2613,7 +2703,7 @@ ${output
2613
2703
  await this.options.compilers[node.type](node, this);
2614
2704
  return;
2615
2705
  }
2616
- this.options.debug?.(new CompileError(`Unknown "${node.name}" directive`, this.template, node.loc));
2706
+ this.options.debug?.(new CompileError(`Unknown "${node.name}" node`, this.template, node.loc));
2617
2707
  }
2618
2708
  async compileNodes(nodes) {
2619
2709
  for (const child of nodes) {
@@ -2656,23 +2746,14 @@ ${output
2656
2746
  }
2657
2747
 
2658
2748
  class Renderer {
2659
- constructor({ globals, filters, parsers, compilers, plugins, ...options } = {}) {
2749
+ constructor(options) {
2660
2750
  Object.defineProperty(this, "options", {
2661
2751
  enumerable: true,
2662
2752
  configurable: true,
2663
2753
  writable: true,
2664
2754
  value: void 0
2665
2755
  });
2666
- this.options = { ...renderOptions, ...options };
2667
- Object.assign(this.options.globals, globals);
2668
- Object.assign(this.options.filters, filters);
2669
- Object.assign(this.options.parsers, parsers);
2670
- Object.assign(this.options.compilers, compilers);
2671
- plugins?.forEach((plugin) => {
2672
- Object.assign(this.options.filters, plugin.filters);
2673
- Object.assign(this.options.parsers, plugin.parsers);
2674
- Object.assign(this.options.compilers, plugin.compilers);
2675
- });
2756
+ this.options = mergeOptions(renderOptions, options);
2676
2757
  }
2677
2758
  async render(template, globals) {
2678
2759
  const compiler = new Compiler(this.options);