janja 2.1.0 → 2.1.2

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