janja 1.0.0 → 2.0.0

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