janja 1.1.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,334 +1,952 @@
1
1
  'use strict';
2
2
 
3
- function highlightSource(message, source, ranges) {
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
- // Copy to avoid mutation
16
- ranges = [...ranges];
17
- let cursor = 0;
18
- let caretLinesCount = 0;
19
- lines.forEach((line, index) => {
20
- if (!line) {
21
- return;
22
- }
23
- output.push(`${`${index + 1}: `.padStart(indentWidth, ' ')}${line}`);
24
- ranges.forEach((tag) => {
25
- if (tag.start < cursor) {
26
- ranges.splice(ranges.indexOf(tag), 1);
27
- return;
28
- }
29
- if (tag.start >= cursor + line.length + 1) {
30
- return;
31
- }
32
- const offset = tag.start - cursor + indentWidth;
33
- const end = Math.min(tag.end, cursor + line.length);
34
- const count = end - tag.start;
35
- const caretLine = `${' '.repeat(offset)}${'^'.repeat(count)}`;
36
- if (/\S/.test(caretLine)) {
37
- output.push(caretLine);
38
- }
39
- if (end < tag.end) {
40
- tag.start += count + 1;
41
- }
42
- addCaretLine(++caretLinesCount + index);
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", {
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true,
33
+ value: null
43
34
  });
44
- cursor += line.length + 1;
45
- });
46
- const emptyLine = `${' '.repeat(indentWidth)}...`;
47
- return `${message}
48
-
49
- ${output
50
- .map((line, index) => (caretLines.has(index) ? line : emptyLine))
51
- .reduce((acc, line) => line === emptyLine && acc.at(-1) === line ? acc : [...acc, line], [])
52
- .join('\n')}
53
- `;
35
+ Object.defineProperty(this, "loc", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: null
40
+ });
41
+ Object.defineProperty(this, "body", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: void 0
46
+ });
47
+ }
48
+ traverse(cb) {
49
+ this.body?.forEach(cb);
50
+ }
54
51
  }
55
-
56
- class CompileError extends Error {
57
- constructor(message, token, filepath) {
58
- super(filepath ? `${message} at ${filepath}` : message);
59
- Object.defineProperty(this, "token", {
52
+ class RootNode extends Traversal {
53
+ constructor(body, loc) {
54
+ super();
55
+ Object.defineProperty(this, "body", {
60
56
  enumerable: true,
61
57
  configurable: true,
62
58
  writable: true,
63
- value: token
59
+ value: body
60
+ });
61
+ Object.defineProperty(this, "loc", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: loc
66
+ });
67
+ Object.defineProperty(this, "type", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: NodeType.TEMPLATE
64
72
  });
65
- this.name = 'CompileError';
66
- Error.captureStackTrace?.(this, this.constructor);
67
73
  }
68
- get details() {
69
- return highlightSource(this.message, this.token.raw, [this.token]);
74
+ }
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", {
97
+ enumerable: true,
98
+ configurable: true,
99
+ writable: true,
100
+ value: exp
101
+ });
102
+ Object.defineProperty(this, "type", {
103
+ enumerable: true,
104
+ configurable: true,
105
+ writable: true,
106
+ value: NodeType.OUTPUT
107
+ });
70
108
  }
71
109
  }
72
-
73
- const CONTEXT = 'c';
74
- const FILTERS = 'f'; // Filters can be async
75
- const ESCAPE = 'e';
76
- const RAW$1 = 'raw';
77
- const LAYOUT = 'layout';
78
- const INCLUDE = 'include';
79
- const BLOCK = 'block';
80
- const SUPER = 'super';
81
- const ENDBLOCK = 'endblock';
82
-
83
- class Context {
84
- constructor(options) {
85
- Object.defineProperty(this, "options", {
110
+ class TextNode extends Traversal {
111
+ constructor(val, loc, strip) {
112
+ super();
113
+ Object.defineProperty(this, "val", {
86
114
  enumerable: true,
87
115
  configurable: true,
88
116
  writable: true,
89
- value: options
117
+ value: val
90
118
  });
91
- Object.defineProperty(this, "context", {
119
+ Object.defineProperty(this, "loc", {
92
120
  enumerable: true,
93
121
  configurable: true,
94
122
  writable: true,
95
- value: CONTEXT
123
+ value: loc
96
124
  });
97
- Object.defineProperty(this, "index", {
125
+ Object.defineProperty(this, "strip", {
98
126
  enumerable: true,
99
127
  configurable: true,
100
128
  writable: true,
101
- value: 0
129
+ value: strip
102
130
  });
103
- Object.defineProperty(this, "contexts", {
131
+ Object.defineProperty(this, "type", {
104
132
  enumerable: true,
105
133
  configurable: true,
106
134
  writable: true,
107
- value: [CONTEXT]
135
+ value: NodeType.TEXT
108
136
  });
109
- Object.defineProperty(this, "expected", {
137
+ }
138
+ }
139
+ class IfNode extends Traversal {
140
+ constructor(test, body, alternatives, loc, strip) {
141
+ super();
142
+ Object.defineProperty(this, "test", {
110
143
  enumerable: true,
111
144
  configurable: true,
112
145
  writable: true,
113
- value: []
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", {
155
+ enumerable: true,
156
+ configurable: true,
157
+ writable: true,
158
+ value: alternatives
159
+ });
160
+ Object.defineProperty(this, "loc", {
161
+ enumerable: true,
162
+ configurable: true,
163
+ writable: true,
164
+ value: loc
165
+ });
166
+ Object.defineProperty(this, "strip", {
167
+ enumerable: true,
168
+ configurable: true,
169
+ writable: true,
170
+ value: strip
171
+ });
172
+ Object.defineProperty(this, "type", {
173
+ enumerable: true,
174
+ configurable: true,
175
+ writable: true,
176
+ value: NodeType.IF
114
177
  });
115
178
  }
116
- in() {
117
- this.context = `${this.context}_${this.index++}`;
118
- this.contexts.push(this.context);
119
- return this.context;
179
+ traverse(cb) {
180
+ this.body?.forEach(cb);
181
+ this.alternatives?.forEach(node => node.body?.forEach(cb));
120
182
  }
121
- out() {
122
- if (this.context === CONTEXT) {
123
- return;
124
- }
125
- this.contexts.pop();
126
- this.context = this.contexts.at(-1) ?? CONTEXT;
183
+ }
184
+ class ElseIfNode extends Traversal {
185
+ constructor(test, body, loc, strip) {
186
+ super();
187
+ Object.defineProperty(this, "test", {
188
+ enumerable: true,
189
+ configurable: true,
190
+ writable: true,
191
+ value: test
192
+ });
193
+ Object.defineProperty(this, "body", {
194
+ enumerable: true,
195
+ configurable: true,
196
+ writable: true,
197
+ value: body
198
+ });
199
+ Object.defineProperty(this, "loc", {
200
+ enumerable: true,
201
+ configurable: true,
202
+ writable: true,
203
+ value: loc
204
+ });
205
+ Object.defineProperty(this, "strip", {
206
+ enumerable: true,
207
+ configurable: true,
208
+ writable: true,
209
+ value: strip
210
+ });
211
+ Object.defineProperty(this, "type", {
212
+ enumerable: true,
213
+ configurable: true,
214
+ writable: true,
215
+ value: NodeType.ELSE_IF
216
+ });
127
217
  }
128
- expect(name) {
129
- this.expected.push(name);
218
+ }
219
+ class ElseNode extends Traversal {
220
+ constructor(body, loc, strip) {
221
+ super();
222
+ Object.defineProperty(this, "body", {
223
+ enumerable: true,
224
+ configurable: true,
225
+ writable: true,
226
+ value: body
227
+ });
228
+ Object.defineProperty(this, "loc", {
229
+ enumerable: true,
230
+ configurable: true,
231
+ writable: true,
232
+ value: loc
233
+ });
234
+ Object.defineProperty(this, "strip", {
235
+ enumerable: true,
236
+ configurable: true,
237
+ writable: true,
238
+ value: strip
239
+ });
240
+ Object.defineProperty(this, "type", {
241
+ enumerable: true,
242
+ configurable: true,
243
+ writable: true,
244
+ value: NodeType.ELSE
245
+ });
130
246
  }
131
- matchAny(name) {
132
- return this.expected.includes(name);
247
+ }
248
+ class ForNode extends Traversal {
249
+ constructor(loop, body, loc, strip) {
250
+ super();
251
+ Object.defineProperty(this, "loop", {
252
+ enumerable: true,
253
+ configurable: true,
254
+ writable: true,
255
+ value: loop
256
+ });
257
+ Object.defineProperty(this, "body", {
258
+ enumerable: true,
259
+ configurable: true,
260
+ writable: true,
261
+ value: body
262
+ });
263
+ Object.defineProperty(this, "loc", {
264
+ enumerable: true,
265
+ configurable: true,
266
+ writable: true,
267
+ value: loc
268
+ });
269
+ Object.defineProperty(this, "strip", {
270
+ enumerable: true,
271
+ configurable: true,
272
+ writable: true,
273
+ value: strip
274
+ });
275
+ Object.defineProperty(this, "type", {
276
+ enumerable: true,
277
+ configurable: true,
278
+ writable: true,
279
+ value: NodeType.FOR
280
+ });
133
281
  }
134
- match(name) {
135
- return this.expected.at(-1) === name;
282
+ }
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", {
299
+ enumerable: true,
300
+ configurable: true,
301
+ writable: true,
302
+ value: strip
303
+ });
304
+ Object.defineProperty(this, "type", {
305
+ enumerable: true,
306
+ configurable: true,
307
+ writable: true,
308
+ value: NodeType.BREAK
309
+ });
136
310
  }
137
- consume(name) {
138
- if (this.match(name)) {
139
- this.expected.pop();
140
- return true;
141
- }
142
- return false;
311
+ }
312
+ class ContinueNode extends Traversal {
313
+ constructor(val, loc, strip) {
314
+ super();
315
+ Object.defineProperty(this, "val", {
316
+ enumerable: true,
317
+ configurable: true,
318
+ writable: true,
319
+ value: val
320
+ });
321
+ Object.defineProperty(this, "loc", {
322
+ enumerable: true,
323
+ configurable: true,
324
+ writable: true,
325
+ value: loc
326
+ });
327
+ Object.defineProperty(this, "strip", {
328
+ enumerable: true,
329
+ configurable: true,
330
+ writable: true,
331
+ value: strip
332
+ });
333
+ Object.defineProperty(this, "type", {
334
+ enumerable: true,
335
+ configurable: true,
336
+ writable: true,
337
+ value: NodeType.CONTINUE
338
+ });
143
339
  }
144
- validate() {
145
- if (this.expected.length) {
146
- throw new Error(`expected tokens "${this.expected.join(', ')}", but got nothing`);
147
- }
340
+ }
341
+ class UnknownDirectiveNode extends Traversal {
342
+ constructor(name, val, loc, strip) {
343
+ super();
344
+ Object.defineProperty(this, "name", {
345
+ enumerable: true,
346
+ configurable: true,
347
+ writable: true,
348
+ value: name
349
+ });
350
+ Object.defineProperty(this, "val", {
351
+ enumerable: true,
352
+ configurable: true,
353
+ writable: true,
354
+ value: val
355
+ });
356
+ Object.defineProperty(this, "loc", {
357
+ enumerable: true,
358
+ configurable: true,
359
+ writable: true,
360
+ value: loc
361
+ });
362
+ Object.defineProperty(this, "strip", {
363
+ enumerable: true,
364
+ configurable: true,
365
+ writable: true,
366
+ value: strip
367
+ });
368
+ Object.defineProperty(this, "type", {
369
+ enumerable: true,
370
+ configurable: true,
371
+ writable: true,
372
+ value: NodeType.UNKNOWN
373
+ });
148
374
  }
149
375
  }
150
-
151
- class OutScript {
152
- constructor(options) {
153
- Object.defineProperty(this, "options", {
376
+ class UnexpectedDirectiveNode extends Traversal {
377
+ constructor(name, val, loc, strip) {
378
+ super();
379
+ Object.defineProperty(this, "name", {
380
+ enumerable: true,
381
+ configurable: true,
382
+ writable: true,
383
+ value: name
384
+ });
385
+ Object.defineProperty(this, "val", {
386
+ enumerable: true,
387
+ configurable: true,
388
+ writable: true,
389
+ value: val
390
+ });
391
+ Object.defineProperty(this, "loc", {
392
+ enumerable: true,
393
+ configurable: true,
394
+ writable: true,
395
+ value: loc
396
+ });
397
+ Object.defineProperty(this, "strip", {
398
+ enumerable: true,
399
+ configurable: true,
400
+ writable: true,
401
+ value: strip
402
+ });
403
+ Object.defineProperty(this, "type", {
404
+ enumerable: true,
405
+ configurable: true,
406
+ writable: true,
407
+ value: NodeType.UNEXPECTED
408
+ });
409
+ }
410
+ }
411
+ class CommentNode extends Traversal {
412
+ constructor(val, loc, strip) {
413
+ super();
414
+ Object.defineProperty(this, "val", {
415
+ enumerable: true,
416
+ configurable: true,
417
+ writable: true,
418
+ value: val
419
+ });
420
+ Object.defineProperty(this, "loc", {
421
+ enumerable: true,
422
+ configurable: true,
423
+ writable: true,
424
+ value: loc
425
+ });
426
+ Object.defineProperty(this, "strip", {
427
+ enumerable: true,
428
+ configurable: true,
429
+ writable: true,
430
+ value: strip
431
+ });
432
+ Object.defineProperty(this, "type", {
433
+ enumerable: true,
434
+ configurable: true,
435
+ writable: true,
436
+ value: NodeType.COMMENT
437
+ });
438
+ }
439
+ }
440
+ class IncludeNode extends Traversal {
441
+ constructor(val, loc, strip) {
442
+ super();
443
+ Object.defineProperty(this, "val", {
444
+ enumerable: true,
445
+ configurable: true,
446
+ writable: true,
447
+ value: val
448
+ });
449
+ Object.defineProperty(this, "loc", {
450
+ enumerable: true,
451
+ configurable: true,
452
+ writable: true,
453
+ value: loc
454
+ });
455
+ Object.defineProperty(this, "strip", {
456
+ enumerable: true,
457
+ configurable: true,
458
+ writable: true,
459
+ value: strip
460
+ });
461
+ Object.defineProperty(this, "type", {
462
+ enumerable: true,
463
+ configurable: true,
464
+ writable: true,
465
+ value: NodeType.INCLUDE
466
+ });
467
+ }
468
+ }
469
+ class BlockNode extends Traversal {
470
+ constructor(val, body, loc, strip) {
471
+ super();
472
+ Object.defineProperty(this, "val", {
473
+ enumerable: true,
474
+ configurable: true,
475
+ writable: true,
476
+ value: val
477
+ });
478
+ Object.defineProperty(this, "body", {
479
+ enumerable: true,
480
+ configurable: true,
481
+ writable: true,
482
+ value: body
483
+ });
484
+ Object.defineProperty(this, "loc", {
485
+ enumerable: true,
486
+ configurable: true,
487
+ writable: true,
488
+ value: loc
489
+ });
490
+ Object.defineProperty(this, "strip", {
491
+ enumerable: true,
492
+ configurable: true,
493
+ writable: true,
494
+ value: strip
495
+ });
496
+ Object.defineProperty(this, "type", {
497
+ enumerable: true,
498
+ configurable: true,
499
+ writable: true,
500
+ value: NodeType.BLOCK
501
+ });
502
+ }
503
+ }
504
+ class SuperNode extends Traversal {
505
+ constructor(val, loc, strip) {
506
+ super();
507
+ Object.defineProperty(this, "val", {
508
+ enumerable: true,
509
+ configurable: true,
510
+ writable: true,
511
+ value: val
512
+ });
513
+ Object.defineProperty(this, "loc", {
514
+ enumerable: true,
515
+ configurable: true,
516
+ writable: true,
517
+ value: loc
518
+ });
519
+ Object.defineProperty(this, "strip", {
520
+ enumerable: true,
521
+ configurable: true,
522
+ writable: true,
523
+ value: strip
524
+ });
525
+ Object.defineProperty(this, "type", {
526
+ enumerable: true,
527
+ configurable: true,
528
+ writable: true,
529
+ value: NodeType.SUPER
530
+ });
531
+ }
532
+ }
533
+ class MacroNode extends Traversal {
534
+ constructor(val, body, loc, strip) {
535
+ super();
536
+ Object.defineProperty(this, "val", {
537
+ enumerable: true,
538
+ configurable: true,
539
+ writable: true,
540
+ value: val
541
+ });
542
+ Object.defineProperty(this, "body", {
543
+ enumerable: true,
544
+ configurable: true,
545
+ writable: true,
546
+ value: body
547
+ });
548
+ Object.defineProperty(this, "loc", {
549
+ enumerable: true,
550
+ configurable: true,
551
+ writable: true,
552
+ value: loc
553
+ });
554
+ Object.defineProperty(this, "strip", {
555
+ enumerable: true,
556
+ configurable: true,
557
+ writable: true,
558
+ value: strip
559
+ });
560
+ Object.defineProperty(this, "type", {
561
+ enumerable: true,
562
+ configurable: true,
563
+ writable: true,
564
+ value: NodeType.MACRO
565
+ });
566
+ }
567
+ }
568
+ class CallerNode extends Traversal {
569
+ constructor(val, loc, strip) {
570
+ super();
571
+ Object.defineProperty(this, "val", {
572
+ enumerable: true,
573
+ configurable: true,
574
+ writable: true,
575
+ value: val
576
+ });
577
+ Object.defineProperty(this, "loc", {
578
+ enumerable: true,
579
+ configurable: true,
580
+ writable: true,
581
+ value: loc
582
+ });
583
+ Object.defineProperty(this, "strip", {
584
+ enumerable: true,
585
+ configurable: true,
586
+ writable: true,
587
+ value: strip
588
+ });
589
+ Object.defineProperty(this, "type", {
590
+ enumerable: true,
591
+ configurable: true,
592
+ writable: true,
593
+ value: NodeType.CALLER
594
+ });
595
+ }
596
+ }
597
+ class CallNode extends Traversal {
598
+ constructor(val, body, loc, strip) {
599
+ super();
600
+ Object.defineProperty(this, "val", {
601
+ enumerable: true,
602
+ configurable: true,
603
+ writable: true,
604
+ value: val
605
+ });
606
+ Object.defineProperty(this, "body", {
607
+ enumerable: true,
608
+ configurable: true,
609
+ writable: true,
610
+ value: body
611
+ });
612
+ Object.defineProperty(this, "loc", {
613
+ enumerable: true,
614
+ configurable: true,
615
+ writable: true,
616
+ value: loc
617
+ });
618
+ Object.defineProperty(this, "strip", {
619
+ enumerable: true,
620
+ configurable: true,
621
+ writable: true,
622
+ value: strip
623
+ });
624
+ Object.defineProperty(this, "type", {
625
+ enumerable: true,
626
+ configurable: true,
627
+ writable: true,
628
+ value: NodeType.CALL
629
+ });
630
+ }
631
+ }
632
+ class SetNode extends Traversal {
633
+ constructor(val, loc, strip) {
634
+ super();
635
+ Object.defineProperty(this, "val", {
636
+ enumerable: true,
637
+ configurable: true,
638
+ writable: true,
639
+ value: val
640
+ });
641
+ Object.defineProperty(this, "loc", {
642
+ enumerable: true,
643
+ configurable: true,
644
+ writable: true,
645
+ value: loc
646
+ });
647
+ Object.defineProperty(this, "strip", {
648
+ enumerable: true,
649
+ configurable: true,
650
+ writable: true,
651
+ value: strip
652
+ });
653
+ Object.defineProperty(this, "type", {
654
+ enumerable: true,
655
+ configurable: true,
656
+ writable: true,
657
+ value: NodeType.SET
658
+ });
659
+ }
660
+ }
661
+ class CaptureNode extends Traversal {
662
+ constructor(val, body, loc, strip) {
663
+ super();
664
+ Object.defineProperty(this, "val", {
154
665
  enumerable: true,
155
666
  configurable: true,
156
667
  writable: true,
157
- value: options
668
+ value: val
158
669
  });
159
- Object.defineProperty(this, "content", {
670
+ Object.defineProperty(this, "body", {
160
671
  enumerable: true,
161
672
  configurable: true,
162
673
  writable: true,
163
- value: ''
674
+ value: body
164
675
  });
165
- Object.defineProperty(this, "strOffset", {
676
+ Object.defineProperty(this, "loc", {
166
677
  enumerable: true,
167
678
  configurable: true,
168
679
  writable: true,
169
- value: 's+="'.length
680
+ value: loc
170
681
  });
171
- Object.defineProperty(this, "varOffset", {
682
+ Object.defineProperty(this, "strip", {
172
683
  enumerable: true,
173
684
  configurable: true,
174
685
  writable: true,
175
- value: `s+=${ESCAPE}(`.length
686
+ value: strip
687
+ });
688
+ Object.defineProperty(this, "type", {
689
+ enumerable: true,
690
+ configurable: true,
691
+ writable: true,
692
+ value: NodeType.CAPTURE
176
693
  });
177
694
  }
178
- get value() {
179
- return this.content;
180
- }
181
- get script() {
182
- // eslint-disable-next-line no-new-func
183
- return new Function(CONTEXT, FILTERS, ESCAPE, this.value);
184
- }
185
- start() {
186
- if (this.options.strictMode) {
187
- this.pushLine('"use strict";');
188
- }
189
- this.pushLine('return(async()=>{', 'let s="";');
190
- }
191
- end() {
192
- this.pushLine('return s;', '})();');
193
- }
194
- pushLine(...lines) {
195
- const start = this.content.length;
196
- for (const line of lines) {
197
- this.content += line;
695
+ }
696
+
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;
198
713
  }
199
- return {
200
- start,
201
- end: this.content.length,
202
- };
203
- }
204
- pushStr(s, o) {
205
- if (s) {
206
- if (o?.trimStart || this.options.trimWhitespace) {
207
- s = s.trimStart();
208
- }
209
- if (o?.trimEnd || this.options.trimWhitespace) {
210
- s = s.trimEnd();
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);
211
719
  }
720
+ addCaretLine(++caretLinesCount + index);
212
721
  }
213
- if (s) {
214
- this.pushLine(`s+="${s.replace(/\\/g, '\\\\')
215
- .replace(/"/g, '\\"')
216
- .replace(/[\n\r]/g, '\\n')}";`);
217
- return {
218
- start: this.content.length + this.strOffset,
219
- end: this.content.length - 2,
220
- };
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);
221
728
  }
222
- }
223
- pushVar(v) {
224
- const start = this.content.length + this.varOffset;
225
- this.pushLine(`s+=${ESCAPE}(${v});`);
226
- return {
227
- start,
228
- end: start + v.length,
229
- };
230
- }
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
+ `;
231
738
  }
232
739
 
233
- /**
234
- * Contains the source map information.
235
- * @example
236
- * - template:
237
- * {{ foo }}
238
- *
239
- * - compiled:
240
- * s+=e(foo);
241
- *
242
- * - sourceMap:
243
- * Mapping {
244
- * source: {
245
- * start: 3,
246
- * end: 6,
247
- * },
248
- * target: {
249
- * start: 3,
250
- * end: 8,
251
- * }
252
- * }
253
- */
254
- class SourceMap {
255
- constructor(options) {
256
- Object.defineProperty(this, "options", {
740
+ class CompileError extends SyntaxError {
741
+ constructor(message, src, loc) {
742
+ super(message);
743
+ Object.defineProperty(this, "src", {
257
744
  enumerable: true,
258
745
  configurable: true,
259
746
  writable: true,
260
- value: options
747
+ value: src
261
748
  });
262
- Object.defineProperty(this, "mappings", {
749
+ Object.defineProperty(this, "loc", {
263
750
  enumerable: true,
264
751
  configurable: true,
265
752
  writable: true,
266
- value: []
267
- });
268
- }
269
- addMapping(source, target) {
270
- this.mappings.push({
271
- source,
272
- target,
753
+ value: loc
273
754
  });
755
+ this.name = 'CompileError';
756
+ CompileError.captureStackTrace?.(this, this.constructor);
274
757
  }
275
- getRanges(offset) {
276
- return this.mappings
277
- .filter(({ target: { start, end } }) => start <= offset && end >= offset)
278
- .map(({ source }) => source);
758
+ get details() {
759
+ return this.loc
760
+ ? highlightSource(this.message, this.src, this.loc)
761
+ : this.message;
279
762
  }
280
763
  }
281
764
 
282
- class Compiler {
283
- constructor(options) {
284
- Object.defineProperty(this, "options", {
285
- enumerable: true,
286
- configurable: true,
287
- writable: true,
288
- value: options
289
- });
290
- }
291
- async compile(tag, filepath) {
292
- const ctx = new Context(this.options);
293
- const out = new OutScript(this.options);
294
- const sourcemap = new SourceMap(this.options);
295
- out.start();
296
- while (tag) {
297
- const compilers = (this.options.compilers[tag.name] ?? []);
298
- for (const compiler of compilers) {
299
- try {
300
- const r = await compiler.compile({
301
- tag,
302
- ctx,
303
- out,
304
- });
305
- if (r !== false) {
306
- if (r) {
307
- sourcemap.addMapping(tag, r);
308
- }
309
- break;
310
- }
311
- }
312
- catch (error) {
313
- throw new CompileError(error.message, tag, filepath);
314
- }
315
- }
316
- tag = tag.next;
317
- }
318
- try {
319
- ctx.validate();
320
- }
321
- catch (error) {
322
- throw new CompileError(error.message, {
323
- raw: '',
324
- start: 0,
325
- end: 0,
326
- }, filepath);
327
- }
328
- out.end();
329
- return { value: out.value, script: out.script, sourcemap };
330
- }
331
- }
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
+ };
332
950
 
333
951
  class Safe extends String {
334
952
  constructor(value) {
@@ -523,6 +1141,21 @@ var filters = /*#__PURE__*/Object.freeze({
523
1141
  values: values
524
1142
  });
525
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
+
526
1159
  const expTokenOperators = {
527
1160
  AND: '&&',
528
1161
  OR: '||',
@@ -554,6 +1187,10 @@ const expTokenOperators = {
554
1187
  ELSE: '',
555
1188
  };
556
1189
 
1190
+ const CONTEXT = 'c';
1191
+ const ESCAPE = 'e';
1192
+ const FILTERS = 'f';
1193
+
557
1194
  class ExpCompiler {
558
1195
  constructor() {
559
1196
  Object.defineProperty(this, "context", {
@@ -569,7 +1206,7 @@ class ExpCompiler {
569
1206
  value: void 0
570
1207
  });
571
1208
  }
572
- compile(expression, context, filters) {
1209
+ compile(expression, context = CONTEXT, filters = FILTERS) {
573
1210
  this.context = context;
574
1211
  this.filters = filters;
575
1212
  return expression ? this.compileExp(expression) : '""';
@@ -625,43 +1262,345 @@ class ExpCompiler {
625
1262
  }
626
1263
  return s;
627
1264
  }
628
- compileLit({ value }) {
629
- return value === undefined ? 'undefined' : JSON.stringify(value);
1265
+ compileLit({ value }) {
1266
+ return value === undefined ? 'undefined' : JSON.stringify(value);
1267
+ }
1268
+ compileSeq({ elements }) {
1269
+ return elements.map(element => this.compileExp(element)).toString();
1270
+ }
1271
+ compilePipe({ left, right }) {
1272
+ const { value: name, args = [] } = right;
1273
+ 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(',')}))`;
1274
+ }
1275
+ compileOf({ left, right }) {
1276
+ // destructuring
1277
+ if (left.type === 'SEQ') {
1278
+ return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
1279
+ }
1280
+ return `const ${left.value} of ${this.compileExp(right)}`;
1281
+ }
1282
+ compileSet({ left, right }) {
1283
+ if (left.type === 'ID') {
1284
+ return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
1285
+ }
1286
+ // destructuring
1287
+ return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
1288
+ }
1289
+ compileIs({ left, right }) {
1290
+ return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
1291
+ }
1292
+ compileBinary({ type, left, right }) {
1293
+ const ret = `${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)}`;
1294
+ return type === 'NI' ? `!${ret}` : ret;
1295
+ }
1296
+ compileTernary({ test, consequent, alternative }) {
1297
+ return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
1298
+ }
1299
+ }
1300
+
1301
+ async function compileCall({ val, body, loc }, compiler) {
1302
+ compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
1303
+ await compiler.compileNodes(body);
1304
+ compiler.pushRaw(null, `});`);
1305
+ }
1306
+ const compilers$a = {
1307
+ [NodeType.CALL]: compileCall,
1308
+ };
1309
+
1310
+ async function compileCapture({ val, body, loc }, compiler) {
1311
+ compiler.pushRaw(loc, `${compiler.context}.${val.value}=await(async(s)=>{`);
1312
+ await compiler.compileNodes(body);
1313
+ compiler.pushRaw(null, `return s;})("");`);
1314
+ }
1315
+ const compilers$9 = {
1316
+ [NodeType.CAPTURE]: compileCapture,
1317
+ };
1318
+
1319
+ async function compileComment({ val, loc }, compiler) {
1320
+ if (!compiler.options.stripComments) {
1321
+ compiler.pushStr(loc, `<!--${val}-->`);
1322
+ }
1323
+ }
1324
+ const compilers$8 = {
1325
+ [NodeType.COMMENT]: compileComment,
1326
+ };
1327
+
1328
+ async function compileFor({ loop, body }, compiler) {
1329
+ const { context } = compiler;
1330
+ if (loop.left.type === 'SEQ') {
1331
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.elements.map(({ value }) => value).join(',')},`, `};`);
1332
+ }
1333
+ else {
1334
+ compiler.pushRaw(loop.loc, `for(${new ExpCompiler().compile(loop, context)}){`, `const ${compiler.in()}={`, `...${context},`, `${loop.left.value},`, `};`);
1335
+ }
1336
+ await compiler.compileNodes(body);
1337
+ compiler.out();
1338
+ compiler.pushRaw(null, '}');
1339
+ }
1340
+ function compileBreak({ loc }, compiler) {
1341
+ compiler.pushRaw(loc, `break;`);
1342
+ }
1343
+ function compileContinue({ loc }, compiler) {
1344
+ compiler.pushRaw(loc, `continue;`);
1345
+ }
1346
+ const compilers$7 = {
1347
+ [NodeType.FOR]: compileFor,
1348
+ [NodeType.BREAK]: compileBreak,
1349
+ [NodeType.CONTINUE]: compileContinue,
1350
+ };
1351
+
1352
+ async function compileIf({ test, body, alternatives }, compiler) {
1353
+ compiler.pushRaw(test.loc, `if(${new ExpCompiler().compile(test, compiler.context)}){`);
1354
+ await compiler.compileNodes(body);
1355
+ compiler.pushRaw(null, '}');
1356
+ for (const branch of alternatives) {
1357
+ if (branch.type === NodeType.ELSE_IF) {
1358
+ compiler.pushRaw(branch.test.loc, `else if(${new ExpCompiler().compile(branch.test, compiler.context)}){`);
1359
+ }
1360
+ else {
1361
+ compiler.pushRaw(null, 'else{');
1362
+ }
1363
+ await compiler.compileNodes(branch.body);
1364
+ compiler.pushRaw(null, '}');
1365
+ }
1366
+ }
1367
+ const compilers$6 = {
1368
+ [NodeType.IF]: compileIf,
1369
+ };
1370
+
1371
+ async function compileInclude({ val: path, loc }, compiler) {
1372
+ compiler.pushRaw(loc, `s+=await p["${path.value}"]?.()??"";`);
1373
+ }
1374
+ const compilers$5 = {
1375
+ [NodeType.INCLUDE]: compileInclude,
1376
+ };
1377
+
1378
+ async function compileMacro({ val: { left, right }, loc, body }, compiler) {
1379
+ const { context } = compiler;
1380
+ const { elements } = right;
1381
+ const expCompiler = new ExpCompiler();
1382
+ compiler.pushRaw(loc, `${expCompiler.compile(left)}=(${(elements).map(el => el.type === 'SET' ? `${el.left.value}=${expCompiler.compile((el.right))}` : el.value).join(',')})=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, elements.map(el => el.type === 'SET'
1383
+ ? el.left.value
1384
+ : el.value).join(','), `};`);
1385
+ await compiler.compileNodes(body);
1386
+ compiler.out();
1387
+ compiler.pushRaw(null, '};');
1388
+ }
1389
+ function compileCaller({ loc }, compiler) {
1390
+ compiler.pushRaw(loc, `await _c?.();`);
1391
+ }
1392
+ const compilers$4 = {
1393
+ [NodeType.MACRO]: compileMacro,
1394
+ [NodeType.CALLER]: compileCaller,
1395
+ };
1396
+
1397
+ async function compileOutput({ exp }, compiler) {
1398
+ compiler.pushVar(exp.loc, new ExpCompiler().compile(exp, compiler.context));
1399
+ }
1400
+ const compilers$3 = {
1401
+ [NodeType.OUTPUT]: compileOutput,
1402
+ };
1403
+
1404
+ async function compileSet({ val, loc }, compiler) {
1405
+ compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
1406
+ }
1407
+ const compilers$2 = {
1408
+ [NodeType.SET]: compileSet,
1409
+ };
1410
+
1411
+ async function compileText({ val, loc, strip: { start, end } }, compiler) {
1412
+ if (start || compiler.options.trimWhitespace) {
1413
+ val = val.replace(/^\s+/, '');
1414
+ }
1415
+ if (end || compiler.options.trimWhitespace) {
1416
+ val = val.replace(/\s+$/, '');
1417
+ }
1418
+ compiler.pushStr(loc, val);
1419
+ }
1420
+ const compilers$1 = {
1421
+ [NodeType.TEXT]: compileText,
1422
+ };
1423
+
1424
+ const compilers = {
1425
+ ...compilers$6,
1426
+ ...compilers$7,
1427
+ ...compilers$5,
1428
+ ...compilers$b,
1429
+ ...compilers$1,
1430
+ ...compilers$3,
1431
+ ...compilers$8,
1432
+ ...compilers$4,
1433
+ ...compilers$a,
1434
+ ...compilers$2,
1435
+ ...compilers$9,
1436
+ };
1437
+
1438
+ const parserOptions = {
1439
+ commentOpen: '{{#',
1440
+ commentClose: '}}',
1441
+ directiveOpen: '{{',
1442
+ directiveClose: '}}',
1443
+ outputOpen: '{{=',
1444
+ outputClose: '}}',
1445
+ parsers,
1446
+ debug: () => { },
1447
+ };
1448
+ const compilerOptions = {
1449
+ ...parserOptions,
1450
+ trimWhitespace: false,
1451
+ stripComments: false,
1452
+ compilers,
1453
+ loader: async () => '',
1454
+ };
1455
+ const renderOptions = {
1456
+ ...compilerOptions,
1457
+ globals: {},
1458
+ filters,
1459
+ autoEscape: true,
1460
+ };
1461
+
1462
+ /**
1463
+ * Contains the source map information.
1464
+ * @example
1465
+ * - template:
1466
+ * {{ foo }}
1467
+ *
1468
+ * - compiled:
1469
+ * s+=e(foo);
1470
+ *
1471
+ * - sourceMap:
1472
+ * Mapping {
1473
+ * source: {
1474
+ * start: {
1475
+ * line: 2,
1476
+ * column: 4,
1477
+ * },
1478
+ * end: {
1479
+ * line: 3,
1480
+ * column: 5,
1481
+ * },
1482
+ * },
1483
+ * target: {
1484
+ * start: {
1485
+ * line: 2,
1486
+ * column: 3,
1487
+ * },
1488
+ * end: {
1489
+ * line: 3,
1490
+ * column: 8,
1491
+ * },
1492
+ * }
1493
+ * }
1494
+ */
1495
+ class SourceMap {
1496
+ constructor() {
1497
+ Object.defineProperty(this, "mappings", {
1498
+ enumerable: true,
1499
+ configurable: true,
1500
+ writable: true,
1501
+ value: []
1502
+ });
1503
+ }
1504
+ addMapping(source, target) {
1505
+ this.mappings.push({
1506
+ source,
1507
+ target,
1508
+ });
1509
+ }
1510
+ getSourceLoc({ line, column }) {
1511
+ return this.mappings
1512
+ .filter(({ target: { start, end } }) => start.line <= line
1513
+ && end.line >= line
1514
+ && (start.line < line || start.column <= column)
1515
+ && (end.line > line || end.column >= column))
1516
+ .map(({ source }) => source);
1517
+ }
1518
+ }
1519
+
1520
+ class OutScript extends SourceMap {
1521
+ constructor() {
1522
+ super(...arguments);
1523
+ Object.defineProperty(this, "code", {
1524
+ enumerable: true,
1525
+ configurable: true,
1526
+ writable: true,
1527
+ value: ''
1528
+ });
630
1529
  }
631
- compileSeq({ elements }) {
632
- return elements.map(element => this.compileExp(element)).toString();
1530
+ get script() {
1531
+ return new Function(CONTEXT, ESCAPE, FILTERS, this.code);
633
1532
  }
634
- compilePipe({ left, right }) {
635
- const { value: name, args = [] } = right;
636
- 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(',')}))`;
1533
+ start() {
1534
+ this.pushRaw(null, 'return(async()=>{', 'let s="";');
637
1535
  }
638
- compileOf({ left, right }) {
639
- // destructuring
640
- if (left.type === 'SEQ') {
641
- return `const {${left.elements.map(({ value }) => value).join(',')}} of ${this.compileExp(right)}`;
1536
+ end() {
1537
+ this.pushRaw(null, 'return s;', '})();');
1538
+ }
1539
+ pushRaw(loc, ...lines) {
1540
+ const start = this.code.length;
1541
+ for (const line of lines) {
1542
+ this.code += line;
642
1543
  }
643
- return `const ${left.value} of ${this.compileExp(right)}`;
1544
+ if (!loc) {
1545
+ return;
1546
+ }
1547
+ this.addMapping(loc, {
1548
+ start: {
1549
+ line: 1,
1550
+ column: start,
1551
+ },
1552
+ end: {
1553
+ line: 1,
1554
+ column: this.code.length,
1555
+ },
1556
+ });
644
1557
  }
645
- compileSet({ left, right }) {
646
- if (left.type === 'ID') {
647
- // for macros
648
- if (right.type === 'SEQ') {
649
- return `${this.compileExp(left)}=(${(right.elements).map(el => el.type === 'SET' ? `${el.left.value}=${this.compileExp((el.right))}` : el.value).join(',')})`;
650
- }
651
- return `Object.assign(${this.context},{${left.value}:${this.compileExp(right)}});`;
1558
+ pushStr(loc, s) {
1559
+ if (s) {
1560
+ this.pushRaw(loc, `s+="${s
1561
+ .replace(/\\/g, '\\\\')
1562
+ .replace(/"/g, '\\"')
1563
+ .replace(/[\n\r]/g, '\\n')}";`);
652
1564
  }
653
- // destructuring
654
- return `Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(right)},[${left.elements.map(({ value }) => `"${value}"`).join(',')}]));`;
655
1565
  }
656
- compileIs({ left, right }) {
657
- return `(typeof ${this.compileExp(left)}===${this.compileExp(right)})`;
1566
+ pushVar(loc, v) {
1567
+ this.pushRaw(loc, `s+=${ESCAPE}(${v});`);
658
1568
  }
659
- compileBinary({ type, left, right }) {
660
- const ret = `(${this.compileExp(left)}${expTokenOperators[type]}${this.compileExp(right)})`;
661
- return type === 'NI' ? `(!${ret})` : ret;
1569
+ }
1570
+
1571
+ class Context extends OutScript {
1572
+ constructor() {
1573
+ super();
1574
+ Object.defineProperty(this, "context", {
1575
+ enumerable: true,
1576
+ configurable: true,
1577
+ writable: true,
1578
+ value: CONTEXT
1579
+ });
1580
+ Object.defineProperty(this, "contexts", {
1581
+ enumerable: true,
1582
+ configurable: true,
1583
+ writable: true,
1584
+ value: [CONTEXT]
1585
+ });
1586
+ Object.defineProperty(this, "index", {
1587
+ enumerable: true,
1588
+ configurable: true,
1589
+ writable: true,
1590
+ value: 0
1591
+ });
662
1592
  }
663
- compileTernary({ test, consequent, alternative }) {
664
- return `(${this.compileExp(test)}?${this.compileExp(consequent)}:${alternative ? this.compileExp(alternative) : '""'})`;
1593
+ in() {
1594
+ this.context = `${this.context}_${this.index++}`;
1595
+ this.contexts.push(this.context);
1596
+ return this.context;
1597
+ }
1598
+ out() {
1599
+ if (this.context === CONTEXT) {
1600
+ return;
1601
+ }
1602
+ this.contexts.pop();
1603
+ this.context = this.contexts.at(-1) ?? CONTEXT;
665
1604
  }
666
1605
  }
667
1606
 
@@ -729,36 +1668,39 @@ const expTokenTypes = {
729
1668
  '.': 'DOT',
730
1669
  };
731
1670
 
732
- class ParseError extends SyntaxError {
733
- constructor(message, options) {
734
- super(message);
735
- Object.defineProperty(this, "options", {
736
- enumerable: true,
737
- configurable: true,
738
- writable: true,
739
- value: options
740
- });
741
- this.name = 'ParseError';
742
- Error.captureStackTrace?.(this, this.constructor);
743
- }
744
- get details() {
745
- return highlightSource(this.message, this.options.source, [this.options.range]);
746
- }
1671
+ /**
1672
+ * Update position by a given string, and return a new position with the
1673
+ * updated values.
1674
+ */
1675
+ function updatePosition(str, pos) {
1676
+ const newlines = (str.match(/\n/g) || []).length;
1677
+ if (newlines > 0) {
1678
+ pos.line += newlines;
1679
+ const lastNewline = str.lastIndexOf('\n');
1680
+ pos.column = str.length - lastNewline;
1681
+ }
1682
+ else {
1683
+ pos.column += str.length;
1684
+ }
1685
+ return {
1686
+ line: pos.line,
1687
+ column: pos.column,
1688
+ };
747
1689
  }
748
1690
 
749
1691
  class ExpTokenizer {
750
- constructor() {
1692
+ constructor(template) {
751
1693
  Object.defineProperty(this, "template", {
752
1694
  enumerable: true,
753
1695
  configurable: true,
754
1696
  writable: true,
755
- value: ''
1697
+ value: template
756
1698
  });
757
- Object.defineProperty(this, "length", {
1699
+ Object.defineProperty(this, "val", {
758
1700
  enumerable: true,
759
1701
  configurable: true,
760
1702
  writable: true,
761
- value: 0
1703
+ value: ''
762
1704
  });
763
1705
  Object.defineProperty(this, "tokens", {
764
1706
  enumerable: true,
@@ -766,22 +1708,42 @@ class ExpTokenizer {
766
1708
  writable: true,
767
1709
  value: []
768
1710
  });
769
- Object.defineProperty(this, "cursor", {
1711
+ Object.defineProperty(this, "index", {
770
1712
  enumerable: true,
771
1713
  configurable: true,
772
1714
  writable: true,
773
1715
  value: 0
774
1716
  });
1717
+ Object.defineProperty(this, "line", {
1718
+ enumerable: true,
1719
+ configurable: true,
1720
+ writable: true,
1721
+ value: 1
1722
+ });
1723
+ Object.defineProperty(this, "column", {
1724
+ enumerable: true,
1725
+ configurable: true,
1726
+ writable: true,
1727
+ value: 1
1728
+ });
775
1729
  }
776
- tokenize(template) {
777
- this.template = template;
778
- this.length = template.length;
1730
+ tokenize(val, loc) {
1731
+ this.val = val;
1732
+ this.index = 0;
1733
+ this.line = loc.start.line;
1734
+ this.column = loc.start.column;
779
1735
  this.tokens = [];
780
- this.cursor = 0;
781
- while (this.cursor < this.length) {
782
- const char = this.template[this.cursor];
1736
+ while (this.index < this.val.length) {
1737
+ const char = this.val[this.index];
783
1738
  if (isWhitespace(char)) {
784
- this.cursor++;
1739
+ if (char === '\n') {
1740
+ this.line++;
1741
+ this.column = 0;
1742
+ }
1743
+ else {
1744
+ this.column++;
1745
+ }
1746
+ this.index++;
785
1747
  continue;
786
1748
  }
787
1749
  if (char === '\'' || char === '"' || char === '`') {
@@ -800,21 +1762,21 @@ class ExpTokenizer {
800
1762
  this.readSymbol(char);
801
1763
  continue;
802
1764
  }
803
- throw new ParseError(`unexpect "${char}"`, { source: template, range: {
804
- start: this.cursor,
805
- end: this.cursor + 1,
806
- } });
1765
+ throw new CompileError(`Unexpect "${char}"`, this.template, {
1766
+ start: { line: this.line, column: this.column },
1767
+ end: { line: this.line, column: this.column + 1 },
1768
+ });
807
1769
  }
808
1770
  return this.tokens;
809
1771
  }
810
1772
  readString(quoteChar) {
811
1773
  let value = '';
812
1774
  let escaped = false;
813
- const start = this.cursor;
1775
+ const start = { line: this.line, column: this.column };
814
1776
  // Skip opening quote char
815
- this.cursor++;
816
- while (this.cursor < this.length) {
817
- const char = this.template[this.cursor];
1777
+ this.index++;
1778
+ while (this.index < this.val.length) {
1779
+ const char = this.val[this.index];
818
1780
  if (escaped) {
819
1781
  value += char;
820
1782
  escaped = false;
@@ -829,24 +1791,26 @@ class ExpTokenizer {
829
1791
  else {
830
1792
  value += char;
831
1793
  }
832
- this.cursor++;
1794
+ this.index++;
833
1795
  }
834
1796
  // skip closing quote char
835
- this.cursor++;
1797
+ this.index++;
836
1798
  this.tokens.push({
837
1799
  type: 'LIT',
838
1800
  value,
839
- start,
840
- end: this.cursor,
1801
+ loc: {
1802
+ start,
1803
+ end: updatePosition(value, this),
1804
+ },
841
1805
  raw: `${quoteChar}${value}${quoteChar}`,
842
1806
  });
843
1807
  }
844
1808
  readNumber() {
845
1809
  let value = '';
846
1810
  let hasDot = false;
847
- const start = this.cursor;
848
- while (this.cursor < this.length) {
849
- const char = this.template[this.cursor];
1811
+ const start = { line: this.line, column: this.column };
1812
+ while (this.index < this.val.length) {
1813
+ const char = this.val[this.index];
850
1814
  if (isDigit(char)) {
851
1815
  value += char;
852
1816
  }
@@ -857,24 +1821,26 @@ class ExpTokenizer {
857
1821
  else {
858
1822
  break;
859
1823
  }
860
- this.cursor++;
1824
+ this.index++;
861
1825
  }
862
1826
  this.tokens.push({
863
1827
  type: 'LIT',
864
1828
  value: Number.parseFloat(value),
865
- start,
866
- end: this.cursor,
1829
+ loc: {
1830
+ start,
1831
+ end: updatePosition(value, this),
1832
+ },
867
1833
  raw: value,
868
1834
  });
869
1835
  }
870
1836
  readIdentifier() {
871
1837
  let value = '';
872
- const start = this.cursor;
873
- while (this.cursor < this.length) {
874
- const char = this.template[this.cursor];
1838
+ const start = { line: this.line, column: this.column };
1839
+ while (this.index < this.val.length) {
1840
+ const char = this.val[this.index];
875
1841
  if (isIdentifierChar(char)) {
876
1842
  value += char;
877
- this.cursor++;
1843
+ this.index++;
878
1844
  continue;
879
1845
  }
880
1846
  break;
@@ -893,21 +1859,25 @@ class ExpTokenizer {
893
1859
  ? undefined
894
1860
  : value
895
1861
  : value,
896
- start,
897
- end: this.cursor,
1862
+ loc: {
1863
+ start,
1864
+ end: updatePosition(value, this),
1865
+ },
898
1866
  raw: value,
899
1867
  });
900
1868
  }
901
1869
  readSymbol(char) {
902
- const start = this.cursor;
1870
+ const start = { line: this.line, column: this.column };
1871
+ this.index++;
903
1872
  this.tokens.push({
904
1873
  type: expTokenTypes[char],
905
1874
  value: char,
906
- start,
907
- end: this.cursor,
1875
+ loc: {
1876
+ start,
1877
+ end: updatePosition(char, this),
1878
+ },
908
1879
  raw: char,
909
1880
  });
910
- this.cursor++;
911
1881
  }
912
1882
  }
913
1883
  function isWhitespace(char) {
@@ -927,8 +1897,14 @@ function isIdentifierChar(char) {
927
1897
  }
928
1898
 
929
1899
  class ExpParser {
930
- constructor() {
1900
+ constructor(template) {
931
1901
  Object.defineProperty(this, "template", {
1902
+ enumerable: true,
1903
+ configurable: true,
1904
+ writable: true,
1905
+ value: template
1906
+ });
1907
+ Object.defineProperty(this, "val", {
932
1908
  enumerable: true,
933
1909
  configurable: true,
934
1910
  writable: true,
@@ -940,25 +1916,32 @@ class ExpParser {
940
1916
  writable: true,
941
1917
  value: []
942
1918
  });
943
- Object.defineProperty(this, "length", {
1919
+ Object.defineProperty(this, "index", {
944
1920
  enumerable: true,
945
1921
  configurable: true,
946
1922
  writable: true,
947
1923
  value: 0
948
1924
  });
949
- Object.defineProperty(this, "cursor", {
1925
+ Object.defineProperty(this, "line", {
950
1926
  enumerable: true,
951
1927
  configurable: true,
952
1928
  writable: true,
953
- value: 0
1929
+ value: 1
1930
+ });
1931
+ Object.defineProperty(this, "column", {
1932
+ enumerable: true,
1933
+ configurable: true,
1934
+ writable: true,
1935
+ value: 1
954
1936
  });
955
1937
  }
956
- parse(template) {
957
- this.template = template;
958
- this.tokens = new ExpTokenizer().tokenize(template);
959
- this.length = this.tokens.length;
960
- this.cursor = 0;
961
- return this.template ? this.parseExp() : null;
1938
+ parse(val, loc) {
1939
+ this.val = val;
1940
+ this.index = 0;
1941
+ this.line = loc.start.line;
1942
+ this.column = loc.start.column;
1943
+ this.tokens = new ExpTokenizer(this.template).tokenize(val, loc);
1944
+ return this.val ? this.parseExp() : null;
962
1945
  }
963
1946
  parseExp(checker) {
964
1947
  let left = null;
@@ -977,42 +1960,27 @@ class ExpParser {
977
1960
  }
978
1961
  if (token.type === 'LP') {
979
1962
  if (!this.peek()) {
980
- throw new ParseError(`unexpected end of expression`, {
981
- source: this.template,
982
- range: {
983
- start: token.start,
984
- end: token.end,
985
- },
986
- });
1963
+ throw new CompileError(`unexpected end of expression`, this.template, token.loc);
987
1964
  }
988
1965
  const elements = this.parseSequence();
989
1966
  const rp = this.consume('RP');
990
1967
  if (!rp) {
991
- throw new ParseError(`expected "RP" after "LP"`, {
992
- source: this.template,
993
- range: {
994
- start: token.start,
995
- end: token.end,
996
- },
997
- });
1968
+ throw new CompileError(`expected "RP" after "LP"`, this.template, token.loc);
998
1969
  }
999
1970
  left = {
1000
1971
  ...token,
1001
1972
  type: 'SEQ',
1002
1973
  elements,
1003
- end: rp.end,
1974
+ loc: {
1975
+ start: token.loc.start,
1976
+ end: rp.loc.end,
1977
+ },
1004
1978
  };
1005
1979
  continue;
1006
1980
  }
1007
1981
  if (token.type === 'NOT') {
1008
1982
  if (!this.peek()) {
1009
- throw new ParseError(`unexpected end of expression`, {
1010
- source: this.template,
1011
- range: {
1012
- start: token.start,
1013
- end: token.end,
1014
- },
1015
- });
1983
+ throw new CompileError(`unexpected end of expression`, this.template, token.loc);
1016
1984
  }
1017
1985
  left = {
1018
1986
  ...token,
@@ -1030,17 +1998,11 @@ class ExpParser {
1030
1998
  if (this.check('DOT')) {
1031
1999
  left.path = this.parsePath();
1032
2000
  }
1033
- if (this.consume('LP')) {
2001
+ const lp = this.consume('LP');
2002
+ if (lp) {
1034
2003
  left.args = this.parseSequence();
1035
- const rp = this.consume('RP');
1036
- if (!rp) {
1037
- throw new ParseError(`expected "RP" after "LP"`, {
1038
- source: this.template,
1039
- range: {
1040
- start: token.start,
1041
- end: token.end,
1042
- },
1043
- });
2004
+ if (!this.consume('RP')) {
2005
+ throw new CompileError(`expected "RP" after "LP"`, this.template, lp.loc);
1044
2006
  }
1045
2007
  continue;
1046
2008
  }
@@ -1056,13 +2018,7 @@ class ExpParser {
1056
2018
  if (token.type === 'IF') {
1057
2019
  const test = this.parseExp(t => t.type === 'ELSE' ? 'BACK' : isHigher(token, t) ? 'BACK' : undefined);
1058
2020
  if (!test) {
1059
- throw new ParseError('expected test expression', {
1060
- source: this.template,
1061
- range: {
1062
- start: token.start,
1063
- end: token.end,
1064
- },
1065
- });
2021
+ throw new CompileError('expected test expression', this.template, token.loc);
1066
2022
  }
1067
2023
  left = {
1068
2024
  ...token,
@@ -1073,13 +2029,7 @@ class ExpParser {
1073
2029
  if (this.consume('ELSE')) {
1074
2030
  const alternative = this.parseExp(t => isHigher(token, t) ? 'BACK' : undefined);
1075
2031
  if (!alternative) {
1076
- throw new ParseError('expected alternative expression', {
1077
- source: this.template,
1078
- range: {
1079
- start: token.start,
1080
- end: token.end,
1081
- },
1082
- });
2032
+ throw new CompileError('expected alternative expression', this.template, token.loc);
1083
2033
  }
1084
2034
  left.alternative = alternative;
1085
2035
  }
@@ -1104,23 +2054,11 @@ class ExpParser {
1104
2054
  || token.type === 'MOD'
1105
2055
  || token.type === 'SET') {
1106
2056
  if (!left) {
1107
- throw new ParseError(`no left operand for "${token.type}"`, {
1108
- source: this.template,
1109
- range: {
1110
- start: token.start,
1111
- end: token.end,
1112
- },
1113
- });
2057
+ throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
1114
2058
  }
1115
2059
  const right = this.parseExp(t => isHigher(token, t) ? 'BACK' : undefined);
1116
2060
  if (!right) {
1117
- throw new ParseError(`no right operand for "${token.type}"`, {
1118
- source: this.template,
1119
- range: {
1120
- start: token.start,
1121
- end: token.end,
1122
- },
1123
- });
2061
+ throw new CompileError(`no right operand for "${token.type}"`, this.template, token.loc);
1124
2062
  }
1125
2063
  left = {
1126
2064
  ...token,
@@ -1132,22 +2070,10 @@ class ExpParser {
1132
2070
  }
1133
2071
  if (token.type === 'PIPE') {
1134
2072
  if (!left) {
1135
- throw new ParseError(`no left operand for "${token.type}"`, {
1136
- source: this.template,
1137
- range: {
1138
- start: token.start,
1139
- end: token.end,
1140
- },
1141
- });
2073
+ throw new CompileError(`no left operand for "${token.type}"`, this.template, token.loc);
1142
2074
  }
1143
2075
  if (!this.check('ID')) {
1144
- throw new ParseError(`expected "ID" after "PIPE"`, {
1145
- source: this.template,
1146
- range: {
1147
- start: token.start,
1148
- end: token.end,
1149
- },
1150
- });
2076
+ throw new CompileError(`expected "ID" after "PIPE"`, this.template, token.loc);
1151
2077
  }
1152
2078
  left = {
1153
2079
  ...token,
@@ -1170,713 +2096,627 @@ class ExpParser {
1170
2096
  break;
1171
2097
  }
1172
2098
  const token = this.next();
1173
- if (!token) {
1174
- throw new ParseError(`expected "ID" after "DOT"`, {
1175
- source: this.template,
1176
- range: {
1177
- start: dot.start,
1178
- end: dot.end,
1179
- },
1180
- });
1181
- }
1182
- if (token.type !== 'ID') {
1183
- throw new ParseError(`expected "ID" after "DOT"`, {
1184
- source: this.template,
1185
- range: {
1186
- start: token.start,
1187
- end: token.end,
1188
- },
1189
- });
1190
- }
1191
- ids.push({
1192
- ...token,
1193
- type: 'ID',
1194
- value: token.value,
1195
- });
1196
- }
1197
- return ids;
1198
- }
1199
- parseSequence() {
1200
- const elements = [];
1201
- while (!this.check('RP')) {
1202
- const element = this.parseExp(t => t.type === 'COMMA' ? 'BREAK' : undefined);
1203
- if (element) {
1204
- elements.push(element);
1205
- }
1206
- else {
1207
- break;
1208
- }
1209
- }
1210
- return elements;
1211
- }
1212
- parsePipe() {
1213
- const token = this.next();
1214
- const right = {
1215
- ...token,
1216
- type: 'ID',
1217
- value: token.value,
1218
- };
1219
- if (this.consume('LP')) {
1220
- const args = this.parseSequence();
1221
- if (args.length) {
1222
- right.args = args;
1223
- }
1224
- const rp = this.consume('RP');
1225
- if (!rp) {
1226
- throw new ParseError(`expected "RP" after "LP"`, {
1227
- source: this.template,
1228
- range: {
1229
- start: token.start,
1230
- end: token.end,
1231
- },
1232
- });
1233
- }
1234
- }
1235
- return right;
1236
- }
1237
- next() {
1238
- return this.tokens[this.cursor++] ?? null;
1239
- }
1240
- back() {
1241
- return this.tokens[this.cursor--];
1242
- }
1243
- peek() {
1244
- return this.tokens[this.cursor] ?? null;
1245
- }
1246
- check(type) {
1247
- return this.peek()?.type === type;
1248
- }
1249
- consume(type) {
1250
- if (this.check(type)) {
1251
- return this.next();
1252
- }
1253
- }
1254
- }
1255
- function isHigher(a, b) {
1256
- return expTokenPrecedences[a.type] > expTokenPrecedences[b.type];
1257
- }
1258
-
1259
- const compiler = new ExpCompiler();
1260
- const parser = new ExpParser();
1261
-
1262
- const CALL = 'call';
1263
- const ENDCALL = 'endcall';
1264
- /**
1265
- * @example {{ call my_macro(x, "a", 1) }}...{{ endcall }}
1266
- */
1267
- const tag$7 = {
1268
- names: [CALL, ENDCALL],
1269
- async compile({ tag: { name, value }, ctx, out }) {
1270
- if (name === CALL) {
1271
- if (value?.type !== 'ID') {
1272
- throw new Error(`"${CALL}" tag must specify a "macro" name`);
1273
- }
1274
- ctx.expect(ENDCALL);
1275
- const { context } = ctx;
1276
- return out.pushLine(`await ${compiler.compile(value, context, FILTERS)}(async()=>{`);
1277
- }
1278
- if (name === ENDCALL) {
1279
- if (!ctx.consume(ENDCALL)) {
1280
- throw new Error(`unexpected "${ENDCALL}"`);
1281
- }
1282
- return out.pushLine(`});`);
1283
- }
1284
- },
1285
- };
1286
-
1287
- const COMMENT = 'comment';
1288
- const ENDCOMMENT = 'endcomment';
1289
- /**
1290
- * @example {{# This is a comment }}
1291
- * @example {{ comment }} This is a comment {{ endcomment }}
1292
- */
1293
- const tag$6 = {
1294
- names: [COMMENT, '#', ENDCOMMENT],
1295
- async compile({ tag: { name, value }, ctx, out }) {
1296
- // inline comment
1297
- if (name === '#') {
1298
- if (!value.value || out.options.stripComments) {
1299
- return;
1300
- }
1301
- return out.pushStr(`<!--${value.value}-->`);
1302
- }
1303
- // block comment
1304
- if (name === COMMENT) {
1305
- ctx.expect(ENDCOMMENT);
1306
- return out.pushStr(`<!--`);
1307
- }
1308
- if (name === ENDCOMMENT) {
1309
- if (!ctx.consume(ENDCOMMENT)) {
1310
- throw new Error(`unexpected "${ENDCOMMENT}"`);
1311
- }
1312
- return out.pushStr(`-->`);
1313
- }
1314
- },
1315
- };
1316
-
1317
- const EXPRESSION = '=';
1318
- /**
1319
- * @example {{= x | f }}
1320
- * @example {{= 'a' if x else 'b' }}
1321
- */
1322
- const tag$5 = {
1323
- names: [EXPRESSION],
1324
- compile({ tag: { value }, ctx: { context }, out }) {
1325
- return out.pushVar(compiler.compile(value, context, FILTERS));
1326
- },
1327
- };
1328
-
1329
- const FOR = 'for';
1330
- const BREAK = 'break';
1331
- const CONTINUE = 'continue';
1332
- const ENDFOR = 'endfor';
1333
- /**
1334
- * @example {{ for item in items }}{{= item }}{{ endfor }}
1335
- * @example {{ for (x, y) in items }}{{= x }},{{= y }}{{ endfor }}
1336
- */
1337
- const tag$4 = {
1338
- names: [FOR, BREAK, CONTINUE, ENDFOR],
1339
- async compile({ tag: { name, value }, ctx, out }) {
1340
- if (name === FOR) {
1341
- if (!value) {
1342
- throw new Error(`"${FOR}" tag must have expression`);
1343
- }
1344
- ctx.expect(ENDFOR);
1345
- const { context } = ctx;
1346
- const { type, elements } = value.left;
1347
- if (type === 'SEQ') {
1348
- return out.pushLine(`{`, `for(${compiler.compile(value, context, FILTERS)}){`, `const ${ctx.in()}={`, `...${context},`, elements.map(({ value }) => value).join(','), `};`);
1349
- }
1350
- return out.pushLine(`{`, `for(${compiler.compile(value, context, FILTERS)}){`, `const ${ctx.in()}={`, `...${context},`, `${value.left.value},`, `};`);
1351
- }
1352
- if (name === BREAK) {
1353
- if (!ctx.matchAny(ENDFOR)) {
1354
- throw new Error(`"${BREAK}" tag must inside a "${FOR}" loop`);
1355
- }
1356
- return out.pushLine(`break;`);
1357
- }
1358
- if (name === CONTINUE) {
1359
- if (!ctx.matchAny(ENDFOR)) {
1360
- throw new Error(`"${CONTINUE}" tag must inside a "${FOR}" loop`);
1361
- }
1362
- return out.pushLine(`continue;`);
1363
- }
1364
- if (name === ENDFOR) {
1365
- if (!ctx.consume(ENDFOR)) {
1366
- throw new Error(`unexpected "${ENDFOR}"`);
1367
- }
1368
- ctx.out();
1369
- return out.pushLine(`}}`);
1370
- }
1371
- },
1372
- };
1373
-
1374
- const IF = 'if';
1375
- const ELIF = 'elif';
1376
- const ELSE = 'else';
1377
- const ENDIF = 'endif';
1378
- /**
1379
- * @example {{ if my_var | my_filter }}yes{{ else }}no{{ endif }}
1380
- */
1381
- const tag$3 = {
1382
- names: [IF, ELIF, ELSE, ENDIF],
1383
- async compile({ tag: { name, value }, ctx, out }) {
1384
- if (name === IF) {
1385
- if (!value) {
1386
- throw new Error(`"${IF}" tag must have expression`);
1387
- }
1388
- ctx.expect(ENDIF);
1389
- const { context } = ctx;
1390
- return out.pushLine(`if(${compiler.compile(value, context, FILTERS)}){`);
1391
- }
1392
- if (name === ELIF) {
1393
- if (!value) {
1394
- throw new Error(`"${ELIF}" tag must have expression`);
1395
- }
1396
- if (!ctx.match(ENDIF)) {
1397
- throw new Error(`"${ELIF}" tag must follow "${IF}" tag`);
1398
- }
1399
- const { context } = ctx;
1400
- return out.pushLine(`}else if(${compiler.compile(value, context, FILTERS)}){`);
1401
- }
1402
- if (name === ELSE) {
1403
- if (!ctx.match(ENDIF)) {
1404
- throw new Error(`"${ELSE}" tag must follow "${IF}" tag`);
1405
- }
1406
- return out.pushLine(`}else{`);
1407
- }
1408
- if (name === ENDIF) {
1409
- if (!ctx.consume(ENDIF)) {
1410
- throw new Error(`unexpected "${ENDIF}"`);
1411
- }
1412
- return out.pushLine(`}`);
1413
- }
1414
- },
1415
- };
1416
-
1417
- const MACRO = 'macro';
1418
- const CALLER = 'caller';
1419
- const ENDMACRO = 'endmacro';
1420
- const CALLER_PN = '_c';
1421
- /**
1422
- * @example {{ macro my_macro = (x, y) }}...{{ caller }}{{ endmacro }}{{ my_macro("foo", 1) }}
1423
- */
1424
- const tag$2 = {
1425
- names: [MACRO, CALLER, ENDMACRO],
1426
- async compile({ tag: { name, value }, ctx, out }) {
1427
- if (name === MACRO) {
1428
- if (value?.type !== 'SET') {
1429
- throw new Error(`"${MACRO}" tag must have "SET" expression`);
2099
+ if (!token) {
2100
+ throw new CompileError(`expected "ID" after "DOT"`, this.template, dot.loc);
1430
2101
  }
1431
- ctx.expect(ENDMACRO);
1432
- const { context } = ctx;
1433
- const { elements } = value.right;
1434
- return out.pushLine(`${compiler.compile(value, context, FILTERS)}=>async(${CALLER_PN})=>{`, `const ${ctx.in()}={`, `...${context},`, elements.map(el => el.type === 'SET'
1435
- ? el.left.value
1436
- : el.value).join(','), `};`);
1437
- }
1438
- if (name === CALLER) {
1439
- if (!ctx.matchAny(ENDMACRO)) {
1440
- throw new Error(`"${CALLER}" tag must inside a "${MACRO}" tag`);
2102
+ if (token.type !== 'ID') {
2103
+ throw new CompileError(`expected "ID" after "DOT"`, this.template, dot.loc);
1441
2104
  }
1442
- return out.pushLine(`await ${CALLER_PN}?.();`);
2105
+ ids.push({
2106
+ ...token,
2107
+ type: 'ID',
2108
+ value: token.value,
2109
+ });
1443
2110
  }
1444
- if (name === ENDMACRO) {
1445
- if (!ctx.consume(ENDMACRO)) {
1446
- throw new Error(`unexpected "${ENDMACRO}"`);
2111
+ return ids;
2112
+ }
2113
+ parseSequence() {
2114
+ const elements = [];
2115
+ while (!this.check('RP')) {
2116
+ const element = this.parseExp(t => t.type === 'COMMA' ? 'BREAK' : undefined);
2117
+ if (element) {
2118
+ elements.push(element);
2119
+ }
2120
+ else {
2121
+ break;
1447
2122
  }
1448
- ctx.out();
1449
- return out.pushLine(`};`);
1450
2123
  }
1451
- },
1452
- };
1453
-
1454
- const RAW = 'raw';
1455
- /**
1456
- * @example hello world
1457
- */
1458
- const tag$1 = {
1459
- names: [RAW],
1460
- async compile({ tag: { raw, previous, next }, out }) {
1461
- return out.pushStr(raw, {
1462
- trimStart: previous?.stripAfter,
1463
- trimEnd: next?.stripBefore,
1464
- });
1465
- },
1466
- };
1467
-
1468
- const SET = 'set';
1469
- const ENDSET = 'endset';
1470
- /**
1471
- * @example {{ set left = right }}
1472
- * @example {{ set variable }} this is {{= my_value }} {{ endset }}
1473
- */
1474
- const tag = {
1475
- names: [SET, ENDSET],
1476
- async compile({ tag: { name, value }, ctx, out }) {
1477
- if (name === SET) {
1478
- if (!value) {
1479
- throw new Error(`"${SET}" tag must have expression`);
2124
+ return elements;
2125
+ }
2126
+ parsePipe() {
2127
+ const token = this.next();
2128
+ const right = {
2129
+ ...token,
2130
+ type: 'ID',
2131
+ value: token.value,
2132
+ };
2133
+ const lp = this.consume('LP');
2134
+ if (lp) {
2135
+ const args = this.parseSequence();
2136
+ if (args.length) {
2137
+ right.args = args;
1480
2138
  }
1481
- const { context } = ctx;
1482
- // inline assignment
1483
- if (value.right) {
1484
- return out.pushLine(compiler.compile(value, CONTEXT, FILTERS));
2139
+ if (!this.consume('RP')) {
2140
+ throw new CompileError(`expected "RP" after "LP"`, this.template, lp.loc);
1485
2141
  }
1486
- ctx.expect(ENDSET);
1487
- // block assignment
1488
- return out.pushLine(`Object.assign(${context},{`, `${value.value}:await(async(s)=>{`);
1489
2142
  }
1490
- if (name === ENDSET) {
1491
- if (!ctx.consume(ENDSET)) {
1492
- throw new Error(`unexpected "${ENDSET}"`);
1493
- }
1494
- return out.pushLine(`return s;})("")});`);
2143
+ return right;
2144
+ }
2145
+ next() {
2146
+ return this.tokens[this.index++] ?? null;
2147
+ }
2148
+ back() {
2149
+ return this.tokens[this.index--];
2150
+ }
2151
+ peek() {
2152
+ return this.tokens.at(this.index) ?? null;
2153
+ }
2154
+ check(type) {
2155
+ return this.peek()?.type === type;
2156
+ }
2157
+ consume(type) {
2158
+ if (this.check(type)) {
2159
+ return this.next();
1495
2160
  }
1496
- },
1497
- };
1498
-
1499
- const compilers = [
1500
- tag,
1501
- tag$7,
1502
- tag$6,
1503
- tag$5,
1504
- tag$4,
1505
- tag$3,
1506
- tag$2,
1507
- tag$1,
1508
- ].reduce((acc, compiler) => {
1509
- for (const name of compiler.names) {
1510
- acc[name] = [...(acc[name] || []), compiler];
1511
- }
1512
- return acc;
1513
- }, {});
2161
+ }
2162
+ }
2163
+ function isHigher(a, b) {
2164
+ return expTokenPrecedences[a.type] > expTokenPrecedences[b.type];
2165
+ }
1514
2166
 
1515
- const config = {
1516
- globals: {
1517
- translations: {},
1518
- },
1519
- filters: { ...filters },
1520
- compilers: { ...compilers },
1521
- autoEscape: true,
1522
- strictMode: true,
1523
- stripComments: false,
1524
- trimWhitespace: false,
1525
- };
2167
+ var TokenType;
2168
+ (function (TokenType) {
2169
+ TokenType["TEXT"] = "TEXT";
2170
+ TokenType["OUTPUT"] = "OUTPUT";
2171
+ TokenType["DIRECTIVE"] = "DIRECTIVE";
2172
+ TokenType["COMMENT"] = "COMMENT";
2173
+ })(TokenType || (TokenType = {}));
1526
2174
 
1527
2175
  function unescapeTag(v) {
1528
- return v.replace(/\\(\{|\})/g, '$1');
2176
+ return v.replace(/\\([{}])/g, '$1');
1529
2177
  }
1530
2178
 
1531
- class Parser {
2179
+ class Tokenizer {
1532
2180
  constructor(options) {
1533
2181
  Object.defineProperty(this, "options", {
1534
2182
  enumerable: true,
1535
2183
  configurable: true,
1536
2184
  writable: true,
1537
- value: options
2185
+ value: void 0
1538
2186
  });
1539
2187
  Object.defineProperty(this, "template", {
1540
2188
  enumerable: true,
1541
2189
  configurable: true,
1542
2190
  writable: true,
1543
- value: ''
2191
+ value: void 0
2192
+ });
2193
+ Object.defineProperty(this, "length", {
2194
+ enumerable: true,
2195
+ configurable: true,
2196
+ writable: true,
2197
+ value: void 0
1544
2198
  });
1545
2199
  Object.defineProperty(this, "index", {
1546
2200
  enumerable: true,
1547
2201
  configurable: true,
1548
2202
  writable: true,
1549
- value: 0
2203
+ value: void 0
1550
2204
  });
1551
- Object.defineProperty(this, "first", {
2205
+ Object.defineProperty(this, "tokens", {
1552
2206
  enumerable: true,
1553
2207
  configurable: true,
1554
2208
  writable: true,
1555
- value: null
2209
+ value: void 0
1556
2210
  });
1557
- Object.defineProperty(this, "group", {
2211
+ Object.defineProperty(this, "tokenPatterns", {
1558
2212
  enumerable: true,
1559
2213
  configurable: true,
1560
2214
  writable: true,
1561
- value: ''
2215
+ value: void 0
1562
2216
  });
1563
- Object.defineProperty(this, "blocks", {
2217
+ Object.defineProperty(this, "line", {
1564
2218
  enumerable: true,
1565
2219
  configurable: true,
1566
2220
  writable: true,
1567
- value: {}
2221
+ value: 1
1568
2222
  });
1569
- Object.defineProperty(this, "cursor", {
2223
+ Object.defineProperty(this, "column", {
1570
2224
  enumerable: true,
1571
2225
  configurable: true,
1572
2226
  writable: true,
1573
- value: null
2227
+ value: 1
1574
2228
  });
2229
+ this.options = {
2230
+ ...parserOptions,
2231
+ ...options,
2232
+ };
2233
+ const { commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = this.options;
2234
+ this.tokenPatterns = ([
2235
+ [
2236
+ TokenType.COMMENT,
2237
+ commentOpen,
2238
+ commentClose,
2239
+ ],
2240
+ [
2241
+ TokenType.DIRECTIVE,
2242
+ directiveOpen,
2243
+ directiveClose,
2244
+ ],
2245
+ [
2246
+ TokenType.OUTPUT,
2247
+ outputOpen,
2248
+ outputClose,
2249
+ ],
2250
+ ].sort(([, open1], [, open2]) => open1.length > open2.length ? -1 : 1));
1575
2251
  }
1576
- async parse(template) {
2252
+ tokenize(template) {
1577
2253
  this.template = template;
2254
+ this.length = template.length;
1578
2255
  this.index = 0;
1579
- this.blocks = {};
1580
- const tagRe = /\{\{(-)?([=#])?((?:\\[{}]|(?!\{\}).)+?)(-)?\}\}/gs;
1581
- let match;
1582
- while ((match = tagRe.exec(template))) {
1583
- if (match.index > this.index) {
1584
- this.addRaw(this.index, match.index);
2256
+ this.line = 1;
2257
+ this.column = 1;
2258
+ this.tokens = [];
2259
+ while (this.index < this.length) {
2260
+ if (this.consumeSpecialTokens()) {
2261
+ continue;
1585
2262
  }
1586
- await this.addTag(match);
1587
- this.index = match.index + match[0].length;
1588
- }
1589
- if (this.index < template.length) {
1590
- this.addRaw(this.index, template.length);
1591
- }
1592
- this.cursor = this.first;
1593
- this.rebuildBlocks();
1594
- return this.cursor;
1595
- }
1596
- addRaw(start, end) {
1597
- this.push({
1598
- name: RAW$1,
1599
- raw: this.template.slice(start, end),
1600
- previous: null,
1601
- next: null,
1602
- start,
1603
- end,
1604
- });
1605
- }
1606
- async addTag(match) {
1607
- const start = match.index;
1608
- const end = start + match[0].length;
1609
- const base = {
1610
- raw: match[0],
1611
- previous: null,
1612
- next: null,
1613
- stripBefore: match[1] === '-',
1614
- stripAfter: match[4] === '-',
1615
- start,
1616
- end,
1617
- };
1618
- if (match[2] === '#') {
1619
- this.push({
1620
- ...base,
1621
- name: match[2],
1622
- value: {
1623
- type: 'LIT',
1624
- value: unescapeTag(match[3]),
1625
- },
1626
- });
1627
- }
1628
- else if (match[2] === '=') {
1629
- this.push({
1630
- ...base,
1631
- name: match[2],
1632
- value: parser.parse(unescapeTag(match[3])),
1633
- });
2263
+ this.consumeTextToken();
1634
2264
  }
1635
- else {
1636
- const [, name, value = ''] = match[3].trim().match(/^([a-z]+)(?: (.+))?$/) ?? [];
1637
- if (name === LAYOUT) {
1638
- await this.layout(value);
2265
+ return this.tokens;
2266
+ }
2267
+ consumeSpecialTokens() {
2268
+ return this.tokenPatterns.some(([type, openMarker, closeMarker]) => {
2269
+ if (!this.lookahead(openMarker)) {
2270
+ return false;
1639
2271
  }
1640
- else if (name === INCLUDE) {
1641
- await this.include(value);
2272
+ const start = {
2273
+ line: this.line,
2274
+ column: this.column,
2275
+ };
2276
+ const endIndex = this.template.indexOf(closeMarker, this.index + openMarker.length);
2277
+ if (endIndex === -1) {
2278
+ throw new CompileError(`Unclosed "${openMarker}"`, this.template, {
2279
+ start,
2280
+ end: updatePosition(openMarker, { ...start }),
2281
+ });
1642
2282
  }
1643
- else {
1644
- this.push({
1645
- ...base,
2283
+ const stripBefore = this.lookahead('-', openMarker.length);
2284
+ const stripAfter = this.template[endIndex - 1] === '-';
2285
+ const val = this.template.slice(this.index + openMarker.length + +stripBefore, endIndex - +stripAfter);
2286
+ const end = updatePosition(this.template.slice(this.index, (this.index = endIndex + closeMarker.length)), this);
2287
+ const token = {
2288
+ type,
2289
+ val: unescapeTag(val),
2290
+ strip: {
2291
+ before: stripBefore,
2292
+ after: stripAfter,
2293
+ },
2294
+ loc: {
2295
+ start,
2296
+ end,
2297
+ },
2298
+ };
2299
+ if (type === TokenType.DIRECTIVE) {
2300
+ let i = 0;
2301
+ let name = '';
2302
+ while (i < val.length) {
2303
+ const char = val[i];
2304
+ if (/\S/.test(char)) {
2305
+ name += char;
2306
+ }
2307
+ else if (name) {
2308
+ break;
2309
+ }
2310
+ i++;
2311
+ }
2312
+ Object.assign(token, {
1646
2313
  name,
1647
- value: parser.parse(unescapeTag(value)),
2314
+ expression: i === val.length || /^\s*$/m.test(val.slice(i + 1))
2315
+ ? null
2316
+ : {
2317
+ val: val.slice(i + 1),
2318
+ loc: {
2319
+ start: updatePosition(val.slice(0, i + 1), updatePosition(`${openMarker}${stripBefore ? '-' : ''}`, { ...start })),
2320
+ end: {
2321
+ line: this.line,
2322
+ column: this.column - closeMarker.length - +stripAfter,
2323
+ },
2324
+ },
2325
+ },
1648
2326
  });
1649
2327
  }
1650
- }
2328
+ this.tokens.push(token);
2329
+ return true;
2330
+ });
1651
2331
  }
1652
- async layout(value) {
1653
- const exp = parser.parse(value);
1654
- if (exp?.type !== 'LIT' || typeof exp.value !== 'string' || !exp.value) {
1655
- throw new ParseError(`"layout" tag must have a file path`, {
1656
- source: this.template,
1657
- range: {
1658
- start: this.index,
1659
- end: this.index + value.length,
2332
+ consumeTextToken() {
2333
+ const nextSpecialIndex = this.findNextSpecialIndex();
2334
+ if (nextSpecialIndex > this.index) {
2335
+ const start = {
2336
+ line: this.line,
2337
+ column: this.column,
2338
+ };
2339
+ const val = this.template.slice(this.index, nextSpecialIndex);
2340
+ this.tokens.push({
2341
+ type: TokenType.TEXT,
2342
+ val: unescapeTag(val),
2343
+ loc: {
2344
+ start,
2345
+ end: updatePosition(val, this),
1660
2346
  },
2347
+ strip: {},
1661
2348
  });
2349
+ this.index = nextSpecialIndex;
1662
2350
  }
1663
- await this.child(`layouts/${exp.value}.janja`);
1664
- }
1665
- async include(value) {
1666
- const exp = parser.parse(value.replace(/\?$/, ''));
1667
- if (exp?.type !== 'LIT' || typeof exp.value !== 'string' || !exp.value) {
1668
- throw new ParseError(`"include" tag must have a file path`, {
1669
- source: this.template,
1670
- range: {
1671
- start: this.index,
1672
- end: this.index + value.length,
1673
- },
1674
- });
2351
+ else {
2352
+ updatePosition(this.template[this.index++], this);
1675
2353
  }
1676
- await this.child(`partials/${exp.value}.janja`, value.endsWith('?'));
1677
2354
  }
1678
- async child(path, optional) {
1679
- let content;
1680
- try {
1681
- content = await this.options.loader(path);
1682
- }
1683
- catch (error) {
1684
- if (optional) {
1685
- return;
1686
- }
1687
- throw error;
1688
- }
1689
- if (!content) {
1690
- return;
1691
- }
1692
- let cursor = await new Parser(this.options).parse(content);
1693
- while (cursor) {
1694
- this.push(cursor);
1695
- cursor = cursor.next;
1696
- }
2355
+ lookahead(marker, offset = 0) {
2356
+ return this.template.startsWith(marker, this.index + offset);
1697
2357
  }
1698
- push(tag) {
1699
- if (tag.name === BLOCK) {
1700
- const { type, value } = tag.value;
1701
- if (type !== 'ID') {
1702
- throw new ParseError(`"${BLOCK}" tag must have a title`, {
1703
- source: this.template,
1704
- range: {
1705
- start: this.index,
1706
- end: this.index + value.length,
1707
- },
1708
- });
2358
+ findNextSpecialIndex() {
2359
+ const { outputOpen, directiveOpen, commentOpen, } = this.options;
2360
+ const commentIndex = this.template.indexOf(commentOpen, this.index);
2361
+ const directiveIndex = this.template.indexOf(directiveOpen, this.index);
2362
+ const outputIndex = this.template.indexOf(outputOpen, this.index);
2363
+ const indexes = [
2364
+ commentIndex,
2365
+ directiveIndex,
2366
+ outputIndex,
2367
+ ]
2368
+ .filter(index => index !== -1)
2369
+ .sort((a, b) => a - b);
2370
+ return indexes.length ? indexes[0] : this.length;
2371
+ }
2372
+ }
2373
+
2374
+ class Parser extends Tokenizer {
2375
+ constructor() {
2376
+ super(...arguments);
2377
+ Object.defineProperty(this, "expParser", {
2378
+ enumerable: true,
2379
+ configurable: true,
2380
+ writable: true,
2381
+ value: void 0
2382
+ });
2383
+ Object.defineProperty(this, "cursor", {
2384
+ enumerable: true,
2385
+ configurable: true,
2386
+ writable: true,
2387
+ value: void 0
2388
+ });
2389
+ }
2390
+ parse(template) {
2391
+ this.tokenize(template);
2392
+ const start = this.tokens[0]?.loc.start ?? { line: 1, column: 1 };
2393
+ const end = this.tokens.at(-1)?.loc.end ?? { line: 1, column: 1 };
2394
+ this.expParser = new ExpParser(template);
2395
+ this.cursor = 0;
2396
+ return new RootNode(this.parseUntil(), { start, end });
2397
+ }
2398
+ parseUntil(names) {
2399
+ const nodes = [];
2400
+ let prevToken = null;
2401
+ while (true) {
2402
+ const token = this.peek();
2403
+ if (!token
2404
+ || (token.type === TokenType.DIRECTIVE
2405
+ && names
2406
+ && this.match(names, token))) {
2407
+ break;
1709
2408
  }
1710
- this.group = value;
1711
- // child blocks
1712
- if (this.blocks[value]) {
1713
- this.blocks[value].push([tag]);
1714
- return;
2409
+ if (prevToken?.strip?.after && token.type === TokenType.TEXT) {
2410
+ token.strip.start = true;
1715
2411
  }
1716
- // parent block
1717
- this.blocks[value] = [[tag]];
1718
- }
1719
- else if (this.group) {
1720
- const chunks = this.blocks[this.group];
1721
- if (tag.name === ENDBLOCK) {
1722
- this.group = '';
2412
+ if (token.strip?.before && prevToken?.type === TokenType.TEXT) {
2413
+ prevToken.strip.end = true;
1723
2414
  }
1724
- chunks.at(-1).push(tag);
1725
- // child blocks
1726
- if (chunks.length > 1) {
1727
- return;
2415
+ switch (token.type) {
2416
+ case TokenType.COMMENT:
2417
+ nodes.push(this.createComment(token));
2418
+ break;
2419
+ case TokenType.DIRECTIVE:
2420
+ nodes.push(this.createDirective(token));
2421
+ break;
2422
+ case TokenType.OUTPUT:
2423
+ nodes.push(this.createOutput(token));
2424
+ break;
2425
+ case TokenType.TEXT:
2426
+ nodes.push(this.createText(token));
2427
+ break;
1728
2428
  }
2429
+ prevToken = token;
1729
2430
  }
1730
- if (this.cursor) {
1731
- tag.previous = this.cursor;
1732
- this.cursor.next = tag;
2431
+ return nodes;
2432
+ }
2433
+ createComment({ val, loc, strip }) {
2434
+ this.advance();
2435
+ return new CommentNode(val, loc, strip);
2436
+ }
2437
+ createOutput({ val, loc, strip }) {
2438
+ this.advance();
2439
+ return new OutputNode(val, loc, strip, this.parseExp({ val, loc }));
2440
+ }
2441
+ createText({ val, loc, strip }) {
2442
+ this.advance();
2443
+ return new TextNode(val, loc, strip);
2444
+ }
2445
+ createDirective(token) {
2446
+ return this.options.parsers[token.name.toLowerCase()]?.(token, this)
2447
+ ?? this.createUnknownDirective(token);
2448
+ }
2449
+ createUnexpectedDirective(token) {
2450
+ this.options.debug?.(new CompileError(`Unexpected "${token.name}" directive`, this.template, token.loc));
2451
+ this.advance();
2452
+ return new UnexpectedDirectiveNode(token.name, token.val, token.loc, token.strip);
2453
+ }
2454
+ createUnknownDirective(token) {
2455
+ this.options.debug?.(new CompileError(`Unknown "${token.name}" directive`, this.template, token.loc));
2456
+ this.advance();
2457
+ return new UnknownDirectiveNode(token.name, token.val, token.loc, token.strip);
2458
+ }
2459
+ parseExp({ val, loc }) {
2460
+ return this.expParser.parse(val, loc);
2461
+ }
2462
+ peek() {
2463
+ return this.tokens.at(this.cursor) ?? null;
2464
+ }
2465
+ advance() {
2466
+ this.cursor++;
2467
+ }
2468
+ match(names, token = this.peek()) {
2469
+ return names.includes(token?.name);
2470
+ }
2471
+ requireExpression({ expression, name, loc }) {
2472
+ if (!expression) {
2473
+ throw this.options.debug?.(new CompileError(`"${name}" requires expression`, this.template, loc));
1733
2474
  }
1734
- else {
1735
- this.first = tag;
2475
+ }
2476
+ requireNoExpression({ expression, name, loc }) {
2477
+ if (expression) {
2478
+ throw this.options.debug?.(new CompileError(`"${name}" should not have expression`, this.template, loc));
1736
2479
  }
1737
- this.cursor = tag;
1738
- }
1739
- /**
1740
- * @note Block tags are hoisted to top level
1741
- */
1742
- rebuildBlocks() {
1743
- for (const chunks of Object.values(this.blocks)) {
1744
- if (chunks.length < 2) {
1745
- continue;
1746
- }
1747
- const [[{ previous }]] = chunks;
1748
- const { next } = chunks[0].at(-1);
1749
- // break the chain
1750
- if (previous) {
1751
- if (previous.next) {
1752
- previous.next.previous = null;
2480
+ }
2481
+ }
2482
+
2483
+ class Compiler extends Context {
2484
+ constructor(options) {
2485
+ super();
2486
+ Object.defineProperty(this, "options", {
2487
+ enumerable: true,
2488
+ configurable: true,
2489
+ writable: true,
2490
+ value: void 0
2491
+ });
2492
+ Object.defineProperty(this, "template", {
2493
+ enumerable: true,
2494
+ configurable: true,
2495
+ writable: true,
2496
+ value: void 0
2497
+ });
2498
+ Object.defineProperty(this, "state", {
2499
+ enumerable: true,
2500
+ configurable: true,
2501
+ writable: true,
2502
+ value: void 0
2503
+ });
2504
+ Object.defineProperty(this, "isRoot", {
2505
+ enumerable: true,
2506
+ configurable: true,
2507
+ writable: true,
2508
+ value: void 0
2509
+ });
2510
+ Object.defineProperty(this, "rootNode", {
2511
+ enumerable: true,
2512
+ configurable: true,
2513
+ writable: true,
2514
+ value: void 0
2515
+ });
2516
+ Object.defineProperty(this, "partials", {
2517
+ enumerable: true,
2518
+ configurable: true,
2519
+ writable: true,
2520
+ value: void 0
2521
+ });
2522
+ Object.defineProperty(this, "blocks", {
2523
+ enumerable: true,
2524
+ configurable: true,
2525
+ writable: true,
2526
+ value: void 0
2527
+ });
2528
+ this.options = {
2529
+ ...compilerOptions,
2530
+ ...options,
2531
+ };
2532
+ }
2533
+ async compile(template, root = true, partials = new Map(), blocks = new Map()) {
2534
+ this.template = template;
2535
+ this.isRoot = root;
2536
+ this.partials = partials;
2537
+ this.blocks = blocks;
2538
+ this.rootNode = new Parser(this.options).parse(template);
2539
+ this.state = {};
2540
+ this.start();
2541
+ await this.parseTemplates();
2542
+ if (this.isRoot) {
2543
+ if (this.partials.size) {
2544
+ this.pushRaw(null, `const p={`);
2545
+ for (const [path, code] of this.partials) {
2546
+ this.pushRaw(null, `"${path}":async()=>{`, code, `},`);
1753
2547
  }
1754
- previous.next = null;
1755
- }
1756
- else {
1757
- this.first = null;
1758
- this.cursor = null;
1759
- }
1760
- if (next) {
1761
- if (next.previous) {
1762
- next.previous.next = null;
2548
+ this.pushRaw(null, `};`);
2549
+ }
2550
+ if (this.blocks.size) {
2551
+ this.pushRaw(null, `const b={`);
2552
+ for (const [name, blocks] of this.blocks) {
2553
+ this.pushRaw(null, `"${name}":{`, `u:0,`, `s:[`);
2554
+ this.state.block = name;
2555
+ for (const block of blocks) {
2556
+ this.pushRaw(null, `async()=>{`, `let s="";`);
2557
+ await this.compileNodes(block.body);
2558
+ this.pushRaw(null, `return s;`, `},`);
2559
+ }
2560
+ this.state.block = undefined;
2561
+ this.pushRaw(null, `],`, `},`);
1763
2562
  }
1764
- next.previous = null;
2563
+ this.pushRaw(null, `};`);
1765
2564
  }
1766
- const body = this.rebuildBlockBody(chunks.pop(), chunks);
1767
- this.rebuildBlockChain(body, previous, next);
1768
2565
  }
2566
+ await this.compileNode(this.rootNode);
2567
+ this.end();
2568
+ return this;
1769
2569
  }
1770
- rebuildBlockBody(child, parents) {
1771
- if (!child) {
1772
- return [];
2570
+ async parseTemplates() {
2571
+ const { partials, blocks } = this.collectPartialsAndBlocks();
2572
+ for (const [path, node] of partials) {
2573
+ if (!this.partials.has(path)) {
2574
+ let template;
2575
+ try {
2576
+ template = await this.options.loader(path);
2577
+ }
2578
+ catch {
2579
+ this.options.debug?.(new CompileError(`Failed to load template from "${path}"`, this.template, node.loc));
2580
+ return;
2581
+ }
2582
+ if (template) {
2583
+ await this.compilePartial(path, node, template);
2584
+ }
2585
+ }
1773
2586
  }
1774
- const chunk = [];
1775
- child.forEach((tag) => {
1776
- if (tag.name === SUPER) {
1777
- this.rebuildBlockBody(parents.pop(), parents).forEach(t => chunk.push(t));
2587
+ for (const block of blocks) {
2588
+ const { val: { value } } = block;
2589
+ if (!this.blocks.has(value)) {
2590
+ this.blocks.set(value, []);
1778
2591
  }
1779
- else {
1780
- chunk.push(tag);
2592
+ this.blocks.get(value).push(block);
2593
+ }
2594
+ }
2595
+ collectPartialsAndBlocks() {
2596
+ const partials = new Map();
2597
+ const blocks = [];
2598
+ const traverse = (node) => {
2599
+ if (node.type === NodeType.INCLUDE) {
2600
+ if (!partials.has(node.val.value)) {
2601
+ partials.set(node.val.value, node);
2602
+ }
1781
2603
  }
1782
- });
1783
- return chunk;
2604
+ if (node.type === NodeType.BLOCK) {
2605
+ blocks.push(node);
2606
+ }
2607
+ node.traverse(traverse);
2608
+ };
2609
+ traverse(this.rootNode);
2610
+ return {
2611
+ partials,
2612
+ blocks,
2613
+ };
1784
2614
  }
1785
- rebuildBlockChain(tags, previous, next) {
1786
- for (let i = 0; i < tags.length; i++) {
1787
- tags[i].previous = tags[i - 1] || previous;
1788
- tags[i].next = tags[i + 1] || next;
2615
+ async compileNode(node) {
2616
+ if (node.type === NodeType.TEMPLATE) {
2617
+ await this.compileNodes(node.body);
2618
+ return;
1789
2619
  }
1790
- if (previous) {
1791
- [previous.next] = tags;
2620
+ if (this.options.compilers[node.type]) {
2621
+ await this.options.compilers[node.type](node, this);
2622
+ return;
2623
+ }
2624
+ this.options.debug?.(new CompileError(`Unknown "${node.name}" directive`, this.template, node.loc));
2625
+ }
2626
+ async compileNodes(nodes) {
2627
+ for (const child of nodes) {
2628
+ await this.compileNode(child);
1792
2629
  }
1793
- if (next) {
1794
- next.previous = tags[tags.length - 1];
2630
+ }
2631
+ async compilePartial(path, node, template) {
2632
+ try {
2633
+ const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks);
2634
+ this.partials.set(path, code);
1795
2635
  }
1796
- if (!this.first) {
1797
- [this.first] = tags;
1798
- this.cursor = this.first;
2636
+ catch {
2637
+ this.options.debug?.(new CompileError(`Failed to compile template`, this.template, node.loc));
1799
2638
  }
1800
2639
  }
1801
2640
  }
1802
2641
 
1803
- class RenderError extends Error {
1804
- constructor(message, options) {
1805
- super(message);
1806
- Object.defineProperty(this, "options", {
2642
+ class RenderError extends CompileError {
2643
+ constructor(message, src, getLoc) {
2644
+ super(message, src);
2645
+ Object.defineProperty(this, "src", {
2646
+ enumerable: true,
2647
+ configurable: true,
2648
+ writable: true,
2649
+ value: src
2650
+ });
2651
+ Object.defineProperty(this, "getLoc", {
1807
2652
  enumerable: true,
1808
2653
  configurable: true,
1809
2654
  writable: true,
1810
- value: options
2655
+ value: getLoc
1811
2656
  });
1812
- this.name = 'RenderError';
1813
- Error.captureStackTrace?.(this, this.constructor);
2657
+ this.name = 'CompileError';
2658
+ RenderError.captureStackTrace?.(this, this.constructor);
1814
2659
  }
1815
2660
  get details() {
1816
- const ranges = this.options.sourcemap.getRanges(+(this.options.error.stack.match(/<anonymous>:\d:(\d+)\)/)?.[1] ?? 0));
1817
- return highlightSource(this.message, this.options.source, ranges);
2661
+ this.loc = this.getLoc();
2662
+ return super.details;
1818
2663
  }
1819
2664
  }
1820
2665
 
1821
- class Engine {
1822
- constructor({ globals, filters, compilers, ...options } = {}) {
2666
+ class Renderer {
2667
+ constructor({ globals, filters, parsers, compilers, ...options } = {}) {
1823
2668
  Object.defineProperty(this, "options", {
1824
2669
  enumerable: true,
1825
2670
  configurable: true,
1826
2671
  writable: true,
1827
2672
  value: void 0
1828
2673
  });
1829
- this.options = { ...config, ...options };
2674
+ this.options = { ...renderOptions, ...options };
1830
2675
  Object.assign(this.options.globals, globals);
1831
2676
  Object.assign(this.options.filters, filters);
2677
+ Object.assign(this.options.parsers, parsers);
1832
2678
  Object.assign(this.options.compilers, compilers);
1833
2679
  }
1834
2680
  async render(template, globals) {
1835
- const { script, sourcemap } = await this._compile(template);
1836
- return this._render(template, globals, script, sourcemap);
1837
- }
1838
- async renderFile(filepath, globals) {
1839
- if (this.options.cache?.has(filepath)) {
1840
- const { template, script, sourcemap } = this.options.cache.get(filepath);
1841
- return this._render(template, globals, script, sourcemap);
1842
- }
1843
- const template = await this.options.loader(filepath);
1844
- const { script, sourcemap } = await this._compile(template);
1845
- this.options.cache?.set(filepath, { template, script, sourcemap });
1846
- return this._render(template, globals, script, sourcemap);
1847
- }
1848
- async _compile(template, filepath) {
1849
- return new Compiler(this.options).compile(await new Parser(this.options).parse(template), filepath);
1850
- }
1851
- async _render(template, globals, script, sourcemap) {
2681
+ const compiler = new Compiler(this.options);
1852
2682
  try {
1853
- return await script({ ...this.options.globals, ...globals }, { ...this.options.filters, ...filters }, (v) => {
2683
+ await compiler.compile(template);
2684
+ return await compiler.script({ ...this.options.globals, ...globals }, (v) => {
1854
2685
  if (v instanceof Safe) {
1855
2686
  return `${v}`;
1856
2687
  }
1857
2688
  return this.options.autoEscape ? escape(v) : v;
1858
- });
2689
+ }, { ...this.options.filters, ...filters });
1859
2690
  }
1860
2691
  catch (error) {
1861
- throw new RenderError(error.message, {
1862
- source: template,
1863
- error,
1864
- sourcemap,
2692
+ if (error.name === 'CompileError') {
2693
+ throw error;
2694
+ }
2695
+ throw new RenderError(error.message, template, () => {
2696
+ const matched = error.stack.match(/<anonymous>:(\d+):(\d+)\)/);
2697
+ if (!matched) {
2698
+ return error.stack ?? '';
2699
+ }
2700
+ const [loc] = compiler.getSourceLoc({
2701
+ line: +matched[1] - 2,
2702
+ column: +matched[2],
2703
+ });
2704
+ return loc;
1865
2705
  });
1866
2706
  }
1867
2707
  }
2708
+ async renderFile(filepath, globals) {
2709
+ return this.render(await this.options.loader(filepath), globals);
2710
+ }
1868
2711
  }
2712
+
1869
2713
  async function render(template, data, options) {
1870
- return new Engine(options).render(template, data);
2714
+ return new Renderer(options).render(template, data);
1871
2715
  }
1872
2716
  async function renderFile(filepath, data, options) {
1873
- return new Engine(options).renderFile(filepath, data);
2717
+ return new Renderer(options).renderFile(filepath, data);
1874
2718
  }
1875
2719
 
1876
- exports.Engine = Engine;
1877
- exports.ExpCompiler = ExpCompiler;
1878
- exports.ExpParser = ExpParser;
1879
- exports.compiler = compiler;
1880
- exports.parser = parser;
2720
+ exports.Renderer = Renderer;
1881
2721
  exports.render = render;
1882
2722
  exports.renderFile = renderFile;