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