janja 4.2.0 → 4.4.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
@@ -334,6 +334,224 @@ class CompileError extends SyntaxError {
334
334
  }
335
335
  }
336
336
 
337
+ const special = /[&<>"']/;
338
+ const specials = /[&<>"']/g;
339
+ const entities = {
340
+ '&': '&amp;',
341
+ '"': '&#34;',
342
+ "'": '&#39;',
343
+ '<': '&lt;',
344
+ '>': '&gt;',
345
+ };
346
+ const entity = (char) => entities[char];
347
+ function escape(v) {
348
+ const str = typeof v === 'string' ? v : `${v}`;
349
+ // Most values contain nothing to escape; they are returned as they are,
350
+ // without allocating
351
+ return special.test(str) ? str.replace(specials, entity) : str;
352
+ }
353
+
354
+ class Safe extends String {
355
+ constructor(value) {
356
+ super(`${value}`);
357
+ }
358
+ }
359
+
360
+ /** Defaults and resolved limits used by the compiler and renderer. */
361
+ function resolveSecurityLimits(security = {}) {
362
+ return {
363
+ maxIncludeDepth: security.maxIncludeDepth ?? 100,
364
+ maxLoopIterations: security.maxLoopIterations,
365
+ maxCallDepth: security.maxCallDepth,
366
+ timeoutMs: security.timeoutMs,
367
+ };
368
+ }
369
+ class SecuritySandbox {
370
+ constructor(options = {}) {
371
+ Object.defineProperty(this, "allowedGlobals", {
372
+ enumerable: true,
373
+ configurable: true,
374
+ writable: true,
375
+ value: void 0
376
+ });
377
+ Object.defineProperty(this, "cspNonce", {
378
+ enumerable: true,
379
+ configurable: true,
380
+ writable: true,
381
+ value: void 0
382
+ });
383
+ this.allowedGlobals = new Set(options.allowedGlobals || []);
384
+ this.cspNonce = options.cspNonce;
385
+ }
386
+ sanitizeGlobals(globals) {
387
+ const sanitized = {};
388
+ for (const [key, value] of Object.entries(globals)) {
389
+ if (this.allowedGlobals.has(key)) {
390
+ sanitized[key] = value;
391
+ }
392
+ }
393
+ return sanitized;
394
+ }
395
+ validateExpression(expression) {
396
+ // Prevent access to dangerous globals
397
+ const dangerousPatterns = [
398
+ /\bprocess\b/,
399
+ /\brequire\b/,
400
+ /\bimport\b/,
401
+ /\bexport\b/,
402
+ /\beval\b/,
403
+ /\bFunction\b/,
404
+ /\b__proto__\b/,
405
+ /\bconstructor\b/,
406
+ ];
407
+ for (const pattern of dangerousPatterns) {
408
+ if (pattern.test(expression)) {
409
+ return false;
410
+ }
411
+ }
412
+ return true;
413
+ }
414
+ createSecureContext(globals) {
415
+ const sanitized = this.sanitizeGlobals(globals);
416
+ // Add safe utility functions
417
+ return {
418
+ ...sanitized,
419
+ Math,
420
+ Date,
421
+ JSON,
422
+ // Add other safe built-ins as needed
423
+ };
424
+ }
425
+ getCSPNonce() {
426
+ return this.cspNonce;
427
+ }
428
+ generateCSPHeaders() {
429
+ const headers = {};
430
+ if (this.cspNonce) {
431
+ headers['Content-Security-Policy'] =
432
+ `script-src 'nonce-${this.cspNonce}'`;
433
+ }
434
+ return headers;
435
+ }
436
+ }
437
+ function deepEscape(value, seen = new WeakSet()) {
438
+ if (value === null || value === undefined) {
439
+ return '';
440
+ }
441
+ if (value instanceof Safe) {
442
+ return `${value}`;
443
+ }
444
+ if (typeof value === 'object') {
445
+ // Guard against circular references
446
+ if (seen.has(value)) {
447
+ return '';
448
+ }
449
+ seen.add(value);
450
+ const values = Array.isArray(value)
451
+ ? value
452
+ : Object.values(value);
453
+ return values.map((v) => deepEscape(v, seen)).join('');
454
+ }
455
+ return escape(value);
456
+ }
457
+ class SecurityAuditor {
458
+ auditTemplate(template) {
459
+ const issues = [];
460
+ // Check for dangerous patterns
461
+ const dangerousPatterns = [
462
+ {
463
+ pattern: /\beval\s*\(/,
464
+ type: 'dangerous-eval',
465
+ message: 'Use of eval() is dangerous and should be avoided',
466
+ severity: 'critical',
467
+ },
468
+ {
469
+ pattern: /\bFunction\s*\(/,
470
+ type: 'dangerous-function',
471
+ message: 'Use of Function constructor is dangerous',
472
+ severity: 'critical',
473
+ },
474
+ {
475
+ pattern: /\brequire\s*\(/,
476
+ type: 'require-usage',
477
+ message: 'Direct require() usage in templates is unsafe',
478
+ severity: 'high',
479
+ },
480
+ {
481
+ pattern: /\bimport\s*\(/,
482
+ type: 'dynamic-import',
483
+ message: 'Dynamic import() usage in templates may be unsafe',
484
+ severity: 'high',
485
+ },
486
+ ];
487
+ for (const { pattern, type, message, severity } of dangerousPatterns) {
488
+ const match = template.match(pattern);
489
+ if (match) {
490
+ issues.push({
491
+ type,
492
+ message,
493
+ location: `at index ${match.index}`,
494
+ severity,
495
+ });
496
+ }
497
+ }
498
+ // Calculate overall severity
499
+ const overallSeverity = this.calculateOverallSeverity(issues);
500
+ return {
501
+ issues,
502
+ severity: overallSeverity,
503
+ };
504
+ }
505
+ calculateOverallSeverity(issues) {
506
+ if (issues.length === 0) {
507
+ return 'low';
508
+ }
509
+ const severityMap = {
510
+ critical: 4,
511
+ high: 3,
512
+ medium: 2,
513
+ low: 1,
514
+ };
515
+ const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
516
+ return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
517
+ }
518
+ }
519
+
520
+ const fingerprints = new WeakMap();
521
+ // How deep includes may nest while rendering. Only templates that include
522
+ // themselves get anywhere near it; the limit turns a cycle that never ends
523
+ // into an error instead of a stack overflow.
524
+ const MAX_INCLUDE_DEPTH = 100;
525
+ // The template itself is the key: one string that is hashed once, and two
526
+ // different templates can never share an entry
527
+ function templateCacheKey(template, stream = false) {
528
+ return stream ? `\0stream:${template}` : template;
529
+ }
530
+ function optionsFingerprint(options) {
531
+ let fingerprint = fingerprints.get(options);
532
+ if (fingerprint === undefined) {
533
+ const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, preloadIncludes, } = options;
534
+ // Limits that change the generated code must bust the compile cache
535
+ const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
536
+ fingerprint = JSON.stringify([
537
+ trimWhitespace,
538
+ stripComments,
539
+ commentOpen,
540
+ commentClose,
541
+ directiveOpen,
542
+ directiveClose,
543
+ outputOpen,
544
+ outputClose,
545
+ maxIncludeDepth,
546
+ maxLoopIterations ?? null,
547
+ maxCallDepth ?? null,
548
+ preloadIncludes,
549
+ ]);
550
+ fingerprints.set(options, fingerprint);
551
+ }
552
+ return fingerprint;
553
+ }
554
+
337
555
  const CONTEXT = 'c';
338
556
  const ESCAPE = 'e';
339
557
  const FILTERS = 'f';
@@ -342,6 +560,9 @@ const WRITE = 'w';
342
560
  const UNKNOWN_FILTER = 'u_';
343
561
  // Holds the result of a filter call while checking whether to await it
344
562
  const RESULT = 'r_';
563
+ // Top-level render context; plain include always receives this, even when
564
+ // nested inside a for/with or an `include … with` partial.
565
+ const TOP_CONTEXT = 'tc_';
345
566
 
346
567
  /**
347
568
  * Contains the source map information.
@@ -609,6 +830,7 @@ const expTokenTypes = {
609
830
  in: 'IN',
610
831
  ni: 'NI',
611
832
  of: 'OF',
833
+ with: 'WITH',
612
834
  '+': 'ADD',
613
835
  '-': 'SUB',
614
836
  '*': 'MUL',
@@ -900,6 +1122,7 @@ const expTokenPrecedences = {
900
1122
  IN: 40,
901
1123
  NI: 40,
902
1124
  OF: 40,
1125
+ WITH: 40,
903
1126
  ADD: 50,
904
1127
  SUB: 50,
905
1128
  MUL: 60,
@@ -1047,36 +1270,12 @@ class ExpParser {
1047
1270
  }
1048
1271
  continue;
1049
1272
  }
1050
- if (token.type === 'AND' ||
1051
- token.type === 'OR' ||
1052
- token.type === 'IS' ||
1053
- token.type === 'EQ' ||
1054
- token.type === 'NE' ||
1055
- token.type === 'GT' ||
1056
- token.type === 'LT' ||
1057
- token.type === 'GE' ||
1058
- token.type === 'LE' ||
1059
- token.type === 'IN' ||
1060
- token.type === 'NI' ||
1061
- token.type === 'OF' ||
1062
- token.type === 'ADD' ||
1063
- token.type === 'SUB' ||
1064
- token.type === 'MUL' ||
1065
- token.type === 'DIV' ||
1066
- token.type === 'MOD' ||
1067
- token.type === 'ASSIGN') {
1273
+ if (isBinaryOp(token.type)) {
1068
1274
  if (!left) {
1069
1275
  throw new ExpError(`No left operand for "${token.type}"`, token.loc);
1070
1276
  }
1071
1277
  if (token.type === 'ASSIGN') {
1072
- if (left.type === 'SEQ') {
1073
- if (left.elements.some((el) => el.type !== 'ID' || el.path || el.args)) {
1074
- throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1075
- }
1076
- }
1077
- else if (left.type !== 'ID' || left.path || left.args) {
1078
- throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1079
- }
1278
+ assertAssignableLeft(left, token);
1080
1279
  }
1081
1280
  const right = this.parseExp((t) => isHigher(token, t) ? 'BACK' : undefined);
1082
1281
  if (!right) {
@@ -1179,12 +1378,46 @@ class ExpParser {
1179
1378
  }
1180
1379
  }
1181
1380
  }
1381
+ const BINARY_OPS = new Set([
1382
+ 'AND',
1383
+ 'OR',
1384
+ 'IS',
1385
+ 'EQ',
1386
+ 'NE',
1387
+ 'GT',
1388
+ 'LT',
1389
+ 'GE',
1390
+ 'LE',
1391
+ 'IN',
1392
+ 'NI',
1393
+ 'OF',
1394
+ 'WITH',
1395
+ 'ADD',
1396
+ 'SUB',
1397
+ 'MUL',
1398
+ 'DIV',
1399
+ 'MOD',
1400
+ 'ASSIGN',
1401
+ ]);
1402
+ function isBinaryOp(type) {
1403
+ return BINARY_OPS.has(type);
1404
+ }
1182
1405
  // Two operands in a row, e.g. `a b`
1183
1406
  function assertNotOperand(token) {
1184
1407
  if (token.type === 'ID' || token.type === 'LIT' || token.type === 'LP') {
1185
1408
  throw new ExpError(`Unexpected "${token.raw ?? token.value}"`, token.loc);
1186
1409
  }
1187
1410
  }
1411
+ function assertAssignableLeft(left, token) {
1412
+ if (left.type === 'SEQ') {
1413
+ if (left.elements.some((el) => el.type !== 'ID' || el.path || el.args)) {
1414
+ throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1415
+ }
1416
+ }
1417
+ else if (left.type !== 'ID' || left.path || left.args) {
1418
+ throw new ExpError('Left operand of assignment must be an identifier or a sequence of identifiers', token.loc);
1419
+ }
1420
+ }
1188
1421
  function isHigher(a, b) {
1189
1422
  // "(" starts an operand; it is not an operator to compare against
1190
1423
  if (b.type === 'LP') {
@@ -1550,251 +1783,78 @@ class Parser extends Tokenizer {
1550
1783
  }
1551
1784
  return nodes;
1552
1785
  }
1553
- parseExp({ val, loc }) {
1554
- try {
1555
- return this.expParser.parse(val, loc);
1556
- }
1557
- catch (error) {
1558
- this.options.debug(error.loc
1559
- ? new CompileError(error.message, this.template, error.loc)
1560
- : error);
1561
- }
1562
- }
1563
- peek() {
1564
- return this.tokens.at(this.cursor) ?? null;
1565
- }
1566
- advance() {
1567
- this.cursor++;
1568
- }
1569
- match(names, token = this.peek()) {
1570
- // Directive names are case-insensitive, like the lookup of their parser
1571
- return names.includes(token?.name?.toLowerCase());
1572
- }
1573
- emitExpErr({ name, loc }, required = true) {
1574
- this.options.debug(new CompileError(required
1575
- ? `"${name}" requires expression`
1576
- : `"${name}" should not have expression`, this.template, loc));
1577
- }
1578
- }
1579
-
1580
- const special = /[&<>"']/;
1581
- const specials = /[&<>"']/g;
1582
- const entities = {
1583
- '&': '&amp;',
1584
- '"': '&#34;',
1585
- "'": '&#39;',
1586
- '<': '&lt;',
1587
- '>': '&gt;',
1588
- };
1589
- const entity = (char) => entities[char];
1590
- function escape(v) {
1591
- const str = typeof v === 'string' ? v : `${v}`;
1592
- // Most values contain nothing to escape; they are returned as they are,
1593
- // without allocating
1594
- return special.test(str) ? str.replace(specials, entity) : str;
1595
- }
1596
-
1597
- class Safe extends String {
1598
- constructor(value) {
1599
- super(`${value}`);
1600
- }
1601
- }
1602
-
1603
- /** Defaults and resolved limits used by the compiler and renderer. */
1604
- function resolveSecurityLimits(security = {}) {
1605
- return {
1606
- maxIncludeDepth: security.maxIncludeDepth ?? 100,
1607
- maxLoopIterations: security.maxLoopIterations,
1608
- maxCallDepth: security.maxCallDepth,
1609
- timeoutMs: security.timeoutMs,
1610
- };
1611
- }
1612
- class SecuritySandbox {
1613
- constructor(options = {}) {
1614
- Object.defineProperty(this, "allowedGlobals", {
1615
- enumerable: true,
1616
- configurable: true,
1617
- writable: true,
1618
- value: void 0
1619
- });
1620
- Object.defineProperty(this, "cspNonce", {
1621
- enumerable: true,
1622
- configurable: true,
1623
- writable: true,
1624
- value: void 0
1625
- });
1626
- this.allowedGlobals = new Set(options.allowedGlobals || []);
1627
- this.cspNonce = options.cspNonce;
1628
- }
1629
- sanitizeGlobals(globals) {
1630
- const sanitized = {};
1631
- for (const [key, value] of Object.entries(globals)) {
1632
- if (this.allowedGlobals.has(key)) {
1633
- sanitized[key] = value;
1634
- }
1635
- }
1636
- return sanitized;
1637
- }
1638
- validateExpression(expression) {
1639
- // Prevent access to dangerous globals
1640
- const dangerousPatterns = [
1641
- /\bprocess\b/,
1642
- /\brequire\b/,
1643
- /\bimport\b/,
1644
- /\bexport\b/,
1645
- /\beval\b/,
1646
- /\bFunction\b/,
1647
- /\b__proto__\b/,
1648
- /\bconstructor\b/,
1649
- ];
1650
- for (const pattern of dangerousPatterns) {
1651
- if (pattern.test(expression)) {
1652
- return false;
1653
- }
1654
- }
1655
- return true;
1656
- }
1657
- createSecureContext(globals) {
1658
- const sanitized = this.sanitizeGlobals(globals);
1659
- // Add safe utility functions
1660
- return {
1661
- ...sanitized,
1662
- Math,
1663
- Date,
1664
- JSON,
1665
- // Add other safe built-ins as needed
1666
- };
1667
- }
1668
- getCSPNonce() {
1669
- return this.cspNonce;
1670
- }
1671
- generateCSPHeaders() {
1672
- const headers = {};
1673
- if (this.cspNonce) {
1674
- headers['Content-Security-Policy'] =
1675
- `script-src 'nonce-${this.cspNonce}'`;
1676
- }
1677
- return headers;
1678
- }
1679
- }
1680
- function deepEscape(value, seen = new WeakSet()) {
1681
- if (value === null || value === undefined) {
1682
- return '';
1683
- }
1684
- if (value instanceof Safe) {
1685
- return `${value}`;
1686
- }
1687
- if (typeof value === 'object') {
1688
- // Guard against circular references
1689
- if (seen.has(value)) {
1690
- return '';
1691
- }
1692
- seen.add(value);
1693
- const values = Array.isArray(value)
1694
- ? value
1695
- : Object.values(value);
1696
- return values.map((v) => deepEscape(v, seen)).join('');
1697
- }
1698
- return escape(value);
1699
- }
1700
- class SecurityAuditor {
1701
- auditTemplate(template) {
1702
- const issues = [];
1703
- // Check for dangerous patterns
1704
- const dangerousPatterns = [
1705
- {
1706
- pattern: /\beval\s*\(/,
1707
- type: 'dangerous-eval',
1708
- message: 'Use of eval() is dangerous and should be avoided',
1709
- severity: 'critical',
1710
- },
1711
- {
1712
- pattern: /\bFunction\s*\(/,
1713
- type: 'dangerous-function',
1714
- message: 'Use of Function constructor is dangerous',
1715
- severity: 'critical',
1716
- },
1717
- {
1718
- pattern: /\brequire\s*\(/,
1719
- type: 'require-usage',
1720
- message: 'Direct require() usage in templates is unsafe',
1721
- severity: 'high',
1722
- },
1723
- {
1724
- pattern: /\bimport\s*\(/,
1725
- type: 'dynamic-import',
1726
- message: 'Dynamic import() usage in templates may be unsafe',
1727
- severity: 'high',
1728
- },
1729
- ];
1730
- for (const { pattern, type, message, severity } of dangerousPatterns) {
1731
- const match = template.match(pattern);
1732
- if (match) {
1733
- issues.push({
1734
- type,
1735
- message,
1736
- location: `at index ${match.index}`,
1737
- severity,
1738
- });
1739
- }
1740
- }
1741
- // Calculate overall severity
1742
- const overallSeverity = this.calculateOverallSeverity(issues);
1743
- return {
1744
- issues,
1745
- severity: overallSeverity,
1746
- };
1747
- }
1748
- calculateOverallSeverity(issues) {
1749
- if (issues.length === 0) {
1750
- return 'low';
1786
+ parseExp({ val, loc }) {
1787
+ try {
1788
+ return this.expParser.parse(val, loc);
1751
1789
  }
1752
- const severityMap = {
1753
- critical: 4,
1754
- high: 3,
1755
- medium: 2,
1756
- low: 1,
1757
- };
1758
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1759
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
1790
+ catch (error) {
1791
+ this.options.debug(error.loc
1792
+ ? new CompileError(error.message, this.template, error.loc)
1793
+ : error);
1794
+ }
1795
+ }
1796
+ peek() {
1797
+ return this.tokens.at(this.cursor) ?? null;
1798
+ }
1799
+ advance() {
1800
+ this.cursor++;
1801
+ }
1802
+ match(names, token = this.peek()) {
1803
+ // Directive names are case-insensitive, like the lookup of their parser
1804
+ return names.includes(token?.name?.toLowerCase());
1805
+ }
1806
+ emitExpErr({ name, loc }, required = true) {
1807
+ this.options.debug(new CompileError(required
1808
+ ? `"${name}" requires expression`
1809
+ : `"${name}" should not have expression`, this.template, loc));
1760
1810
  }
1761
1811
  }
1762
1812
 
1763
- const fingerprints = new WeakMap();
1764
- // How deep includes may nest while rendering. Only templates that include
1765
- // themselves get anywhere near it; the limit turns a cycle that never ends
1766
- // into an error instead of a stack overflow.
1767
- const MAX_INCLUDE_DEPTH = 100;
1768
- // Directives whose body is still the template's own top-level output
1769
- const transparent = new Set(['IF', 'FOR']);
1770
- // The template itself is the key: one string that is hashed once, and two
1771
- // different templates can never share an entry
1772
- function templateCacheKey(template, stream = false) {
1773
- return stream ? `\0stream:${template}` : template;
1813
+ function isStringLit(exp) {
1814
+ return exp.type === 'LIT' && typeof exp.value === 'string';
1774
1815
  }
1775
- function optionsFingerprint(options) {
1776
- let fingerprint = fingerprints.get(options);
1777
- if (fingerprint === undefined) {
1778
- const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1779
- // Limits that change the generated code must bust the compile cache
1780
- const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1781
- fingerprint = JSON.stringify([
1782
- trimWhitespace,
1783
- stripComments,
1784
- commentOpen,
1785
- commentClose,
1786
- directiveOpen,
1787
- directiveClose,
1788
- outputOpen,
1789
- outputClose,
1790
- maxIncludeDepth,
1791
- maxLoopIterations ?? null,
1792
- maxCallDepth ?? null,
1793
- ]);
1794
- fingerprints.set(options, fingerprint);
1816
+ class IncludeNode extends Traversal {
1817
+ constructor(val, loc, strip, withExp = null) {
1818
+ super();
1819
+ Object.defineProperty(this, "val", {
1820
+ enumerable: true,
1821
+ configurable: true,
1822
+ writable: true,
1823
+ value: val
1824
+ });
1825
+ Object.defineProperty(this, "loc", {
1826
+ enumerable: true,
1827
+ configurable: true,
1828
+ writable: true,
1829
+ value: loc
1830
+ });
1831
+ Object.defineProperty(this, "strip", {
1832
+ enumerable: true,
1833
+ configurable: true,
1834
+ writable: true,
1835
+ value: strip
1836
+ });
1837
+ Object.defineProperty(this, "withExp", {
1838
+ enumerable: true,
1839
+ configurable: true,
1840
+ writable: true,
1841
+ value: withExp
1842
+ });
1843
+ Object.defineProperty(this, "type", {
1844
+ enumerable: true,
1845
+ configurable: true,
1846
+ writable: true,
1847
+ value: 'INCLUDE'
1848
+ });
1795
1849
  }
1796
- return fingerprint;
1797
1850
  }
1851
+
1852
+ const PRELOAD_LOC = {
1853
+ start: { line: 1, column: 1 },
1854
+ end: { line: 1, column: 1 },
1855
+ };
1856
+ // Directives whose body is still the template's own top-level output
1857
+ const transparent = new Set(['IF', 'FOR']);
1798
1858
  class Compiler extends Context {
1799
1859
  constructor(options, cache, revalidate = true, stream = false) {
1800
1860
  super();
@@ -1884,6 +1944,13 @@ class Compiler extends Context {
1884
1944
  writable: true,
1885
1945
  value: void 0
1886
1946
  });
1947
+ /** True when the template uses a non-literal include path. */
1948
+ Object.defineProperty(this, "hasDynamicInclude", {
1949
+ enumerable: true,
1950
+ configurable: true,
1951
+ writable: true,
1952
+ value: false
1953
+ });
1887
1954
  /**
1888
1955
  * Whether the code being generated may write output to the stream. True
1889
1956
  * only in stream mode, for the template's own top-level output.
@@ -1904,6 +1971,7 @@ class Compiler extends Context {
1904
1971
  this.stylesheets = stylesheets;
1905
1972
  this.stylesheetKey = stylesheetKey;
1906
1973
  this.sources = sources;
1974
+ this.hasDynamicInclude = false;
1907
1975
  // Generate cache key from template and options
1908
1976
  const cacheKey = this.generateCacheKey(template);
1909
1977
  // Check cache first
@@ -1929,11 +1997,15 @@ class Compiler extends Context {
1929
1997
  }
1930
1998
  await this.parseTemplates();
1931
1999
  if (this.isRoot) {
1932
- if (this.partials.size) {
2000
+ if (this.partials.size || this.hasDynamicInclude) {
1933
2001
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1934
- this.pushRaw(null, 'let d_=0;', 'const p={');
2002
+ // Alias the render data before partials shadow `c` with their argument.
2003
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
1935
2004
  for (const [path, code] of this.partials) {
1936
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${maxIncludeDepth})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
2005
+ this.pushRaw(null,
2006
+ // Partials take the context they should render with: plain include
2007
+ // passes the top-level `tc_`; `include … with` passes a merged scope.
2008
+ `${JSON.stringify(path)}:async(c)=>{`, `if(d_>=${maxIncludeDepth})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
1937
2009
  }
1938
2010
  this.pushRaw(null, '};');
1939
2011
  }
@@ -2023,6 +2095,17 @@ class Compiler extends Context {
2023
2095
  }
2024
2096
  async parseTemplates() {
2025
2097
  const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
2098
+ if (this.isRoot) {
2099
+ for (const path of this.options.preloadIncludes) {
2100
+ if (!partials.has(path)) {
2101
+ partials.set(path, new IncludeNode({
2102
+ type: 'LIT',
2103
+ value: path,
2104
+ loc: PRELOAD_LOC,
2105
+ }, PRELOAD_LOC, { before: false, after: false }));
2106
+ }
2107
+ }
2108
+ }
2026
2109
  for (const [path, node] of partials) {
2027
2110
  if (!this.partials.has(path)) {
2028
2111
  let template;
@@ -2060,8 +2143,14 @@ class Compiler extends Context {
2060
2143
  const stylesheets = [];
2061
2144
  const traverse = (node) => {
2062
2145
  if (node.type === 'INCLUDE') {
2063
- if (!partials.has(node.val.value)) {
2064
- partials.set(node.val.value, node);
2146
+ const include = node;
2147
+ if (isStringLit(include.val)) {
2148
+ if (!partials.has(include.val.value)) {
2149
+ partials.set(include.val.value, include);
2150
+ }
2151
+ }
2152
+ else {
2153
+ this.hasDynamicInclude = true;
2065
2154
  }
2066
2155
  }
2067
2156
  if (node.type === 'BLOCK') {
@@ -2472,6 +2561,7 @@ const compilerOptions = {
2472
2561
  trimWhitespace: false,
2473
2562
  stripComments: false,
2474
2563
  loader: async () => '',
2564
+ preloadIncludes: [],
2475
2565
  };
2476
2566
  const renderOptions = {
2477
2567
  ...compilerOptions,
@@ -2650,6 +2740,7 @@ const expTokenOperators$1 = {
2650
2740
  IN: ' in ',
2651
2741
  NI: ' in ',
2652
2742
  OF: ' of ',
2743
+ WITH: ' with ',
2653
2744
  ADD: '+',
2654
2745
  SUB: '-',
2655
2746
  MUL: '*',
@@ -3535,50 +3626,39 @@ const plugin$9 = {
3535
3626
  parsers: parsers$9,
3536
3627
  };
3537
3628
 
3538
- async function compileInclude({ val: { value }, loc }, compiler) {
3539
- compiler.pushRaw(loc, `s+=await p[${JSON.stringify(value)}]?.()??"";`);
3629
+ async function compileInclude({ val, loc, withExp }, compiler) {
3630
+ const expCompiler = new ExpCompiler();
3631
+ const path = isStringLit(val)
3632
+ ? JSON.stringify(val.value)
3633
+ : expCompiler.compile(val, compiler.context);
3634
+ if (withExp) {
3635
+ const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3636
+ compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3637
+ return;
3638
+ }
3639
+ // Plain include always sees the top-level context, not loop/with scopes.
3640
+ compiler.pushRaw(loc, `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`);
3540
3641
  }
3541
3642
  const compilers$8 = {
3542
3643
  INCLUDE: compileInclude,
3543
3644
  };
3544
3645
 
3545
- class IncludeNode extends Traversal {
3546
- constructor(val, loc, strip) {
3547
- super();
3548
- Object.defineProperty(this, "val", {
3549
- enumerable: true,
3550
- configurable: true,
3551
- writable: true,
3552
- value: val
3553
- });
3554
- Object.defineProperty(this, "loc", {
3555
- enumerable: true,
3556
- configurable: true,
3557
- writable: true,
3558
- value: loc
3559
- });
3560
- Object.defineProperty(this, "strip", {
3561
- enumerable: true,
3562
- configurable: true,
3563
- writable: true,
3564
- value: strip
3565
- });
3566
- Object.defineProperty(this, "type", {
3567
- enumerable: true,
3568
- configurable: true,
3569
- writable: true,
3570
- value: 'INCLUDE'
3571
- });
3572
- }
3573
- }
3574
-
3575
3646
  function* parseInclude(token, parser) {
3576
3647
  if (!token.expression) {
3577
3648
  parser.emitExpErr(token);
3578
3649
  return;
3579
3650
  }
3580
3651
  yield 'NEXT';
3581
- yield new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
3652
+ const exp = parser.parseExp(token.expression);
3653
+ if (!exp) {
3654
+ return;
3655
+ }
3656
+ if (exp.type === 'WITH') {
3657
+ const { left, right } = exp;
3658
+ yield new IncludeNode(left, token.loc, token.strip, right);
3659
+ return;
3660
+ }
3661
+ yield new IncludeNode(exp, token.loc, token.strip);
3582
3662
  }
3583
3663
  const parsers$8 = {
3584
3664
  include: parseInclude,
@@ -3859,14 +3939,18 @@ async function compileStylesheet() {
3859
3939
  async function compileStylesheets({ loc }, compiler) {
3860
3940
  compiler.pushRaw(loc,
3861
3941
  // First `stylesheets` wins; later ones are ignored (same idea as blocks).
3862
- 'if(!ss_u++){', 's+="<style>";', 'for(const f_ of ss_)s+=await f_();', 's+="</style>";', '}');
3942
+ // Bodies are emitted as-is — authors wrap CSS in `<style>` for IDE highlighting.
3943
+ 'if(!ss_u++){', 'for(const f_ of ss_)s+=await f_();', '}');
3863
3944
  }
3864
3945
  const compilers$4 = {
3865
3946
  STYLESHEET: compileStylesheet,
3866
3947
  STYLESHEETS: compileStylesheets,
3867
3948
  };
3868
3949
 
3869
- /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
3950
+ /**
3951
+ * Co-located styles with a section/snippet (Shopify `{% stylesheet %}` analogue).
3952
+ * Body is usually a `<style>…</style>` block for native IDE CSS highlighting.
3953
+ */
3870
3954
  class StylesheetNode extends Traversal {
3871
3955
  constructor(body, loc, strip) {
3872
3956
  super();
@@ -3896,7 +3980,7 @@ class StylesheetNode extends Traversal {
3896
3980
  });
3897
3981
  }
3898
3982
  }
3899
- /** Emits every collected stylesheet into the document (typically in `<head>`). */
3983
+ /** Concatenates collected stylesheet bodies into the document (typically in `<head>`). */
3900
3984
  class StylesheetsNode extends Traversal {
3901
3985
  constructor(loc, strip) {
3902
3986
  super();
@@ -4614,7 +4698,13 @@ class Analyzer {
4614
4698
  await this.nodes(node.body, scope);
4615
4699
  break;
4616
4700
  case 'INCLUDE':
4617
- await this.include(node.val.value, scope);
4701
+ this.exp(node.val, scope);
4702
+ if (node.withExp) {
4703
+ this.exp(node.withExp, scope);
4704
+ }
4705
+ if (node.val.type === 'LIT' && typeof node.val.value === 'string') {
4706
+ await this.include(node.val.value, scope);
4707
+ }
4618
4708
  break;
4619
4709
  default:
4620
4710
  await this.nodes(node.body, scope);
@@ -5296,6 +5386,7 @@ const expTokenOperators = {
5296
5386
  IN: 'in',
5297
5387
  NI: 'ni',
5298
5388
  OF: 'of',
5389
+ WITH: 'with',
5299
5390
  ADD: '+',
5300
5391
  SUB: '-',
5301
5392
  MUL: '*',
@@ -5336,6 +5427,7 @@ class ExpFormatter {
5336
5427
  case 'IN':
5337
5428
  case 'NI':
5338
5429
  case 'OF':
5430
+ case 'WITH':
5339
5431
  case 'ADD':
5340
5432
  case 'SUB':
5341
5433
  case 'MUL':
@@ -5377,6 +5469,149 @@ class ExpFormatter {
5377
5469
  }
5378
5470
  }
5379
5471
 
5472
+ /**
5473
+ * Brace-depth reindent for co-located CSS. Only leading whitespace changes;
5474
+ * braces inside strings/comments are ignored.
5475
+ */
5476
+ function indentCss(source, tabWidth) {
5477
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5478
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5479
+ const lines = source.split(/\r?\n/);
5480
+ let depth = 0;
5481
+ const out = [];
5482
+ for (const line of lines) {
5483
+ const content = line.trim();
5484
+ if (content.length === 0) {
5485
+ out.push('');
5486
+ continue;
5487
+ }
5488
+ const { opens, closes } = countCssBraces(content);
5489
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5490
+ out.push(pad.repeat(lineDepth) + content);
5491
+ depth = Math.max(0, depth + opens - closes);
5492
+ }
5493
+ return out.join(eol);
5494
+ }
5495
+ function countCssBraces(line) {
5496
+ let opens = 0;
5497
+ let closes = 0;
5498
+ let quote = null;
5499
+ let i = 0;
5500
+ while (i < line.length) {
5501
+ const c = line[i];
5502
+ if (quote) {
5503
+ if (c === '\\') {
5504
+ i += 2;
5505
+ continue;
5506
+ }
5507
+ if (c === quote) {
5508
+ quote = null;
5509
+ }
5510
+ i += 1;
5511
+ continue;
5512
+ }
5513
+ if (c === '"' || c === "'") {
5514
+ quote = c;
5515
+ i += 1;
5516
+ continue;
5517
+ }
5518
+ if (c === '/' && line[i + 1] === '*') {
5519
+ const end = line.indexOf('*/', i + 2);
5520
+ i = end === -1 ? line.length : end + 2;
5521
+ continue;
5522
+ }
5523
+ if (c === '/' && line[i + 1] === '/') {
5524
+ break;
5525
+ }
5526
+ if (c === '{') {
5527
+ opens += 1;
5528
+ }
5529
+ else if (c === '}') {
5530
+ closes += 1;
5531
+ }
5532
+ i += 1;
5533
+ }
5534
+ return { opens, closes };
5535
+ }
5536
+
5537
+ /**
5538
+ * Brace-depth reindent for `<script>` bodies. Only leading whitespace changes;
5539
+ * braces inside strings, comments, template literals, and Janja tags are ignored.
5540
+ */
5541
+ function indentJs(source, tabWidth) {
5542
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5543
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5544
+ const lines = source.split(/\r?\n/);
5545
+ let depth = 0;
5546
+ const out = [];
5547
+ for (const line of lines) {
5548
+ const content = line.trim();
5549
+ if (content.length === 0) {
5550
+ out.push('');
5551
+ continue;
5552
+ }
5553
+ const { opens, closes } = countJsBraces(content);
5554
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5555
+ out.push(pad.repeat(lineDepth) + content);
5556
+ depth = Math.max(0, depth + opens - closes);
5557
+ }
5558
+ return out.join(eol);
5559
+ }
5560
+ function countJsBraces(line) {
5561
+ let opens = 0;
5562
+ let closes = 0;
5563
+ let quote = null;
5564
+ let i = 0;
5565
+ while (i < line.length) {
5566
+ const c = line[i];
5567
+ if (quote) {
5568
+ if (c === '\\') {
5569
+ i += 2;
5570
+ continue;
5571
+ }
5572
+ if (c === quote) {
5573
+ quote = null;
5574
+ }
5575
+ i += 1;
5576
+ continue;
5577
+ }
5578
+ if (c === '{' && line[i + 1] === '{') {
5579
+ i = endOfJanja(line, i);
5580
+ continue;
5581
+ }
5582
+ if (c === '"' || c === "'" || c === '`') {
5583
+ quote = c;
5584
+ i += 1;
5585
+ continue;
5586
+ }
5587
+ if (c === '/' && line[i + 1] === '*') {
5588
+ const end = line.indexOf('*/', i + 2);
5589
+ i = end === -1 ? line.length : end + 2;
5590
+ continue;
5591
+ }
5592
+ if (c === '/' && line[i + 1] === '/') {
5593
+ break;
5594
+ }
5595
+ if (c === '{') {
5596
+ opens += 1;
5597
+ }
5598
+ else if (c === '}') {
5599
+ closes += 1;
5600
+ }
5601
+ i += 1;
5602
+ }
5603
+ return { opens, closes };
5604
+ }
5605
+ /** Skip a Janja tag starting at `i` (`{{`, `{{=`, `{{#` …). */
5606
+ function endOfJanja(line, i) {
5607
+ if (line.startsWith('{{#', i)) {
5608
+ const end = line.indexOf('#}}', i + 3);
5609
+ return end === -1 ? line.length : end + 3;
5610
+ }
5611
+ const end = line.indexOf('}}', i + 2);
5612
+ return end === -1 ? line.length : end + 2;
5613
+ }
5614
+
5380
5615
  /** HTML void elements — never take children, so they do not change indent. */
5381
5616
  const VOID = new Set([
5382
5617
  'area',
@@ -5394,8 +5629,13 @@ const VOID = new Set([
5394
5629
  'track',
5395
5630
  'wbr',
5396
5631
  ]);
5397
- /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5632
+ /**
5633
+ * Mark open/close so the body can be buffered. `pre` / `textarea` keep
5634
+ * whitespace; `script` / `style` are reindented (see body buffer below).
5635
+ */
5398
5636
  const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5637
+ /** HTML elements whose bodies are reindented (not left raw). */
5638
+ const REINDENT_HTML = new Set(['script', 'style']);
5399
5639
  const DIR_OPEN = new Set([
5400
5640
  'if',
5401
5641
  'for',
@@ -5406,6 +5646,8 @@ const DIR_OPEN = new Set([
5406
5646
  'with',
5407
5647
  'stylesheet',
5408
5648
  ]);
5649
+ /** Directives whose bodies keep leading whitespace (like `<style>`). */
5650
+ const DIR_SENSITIVE = new Set(['stylesheet']);
5409
5651
  const DIR_MID = new Set(['else', 'elif', 'elseif', 'elsif']);
5410
5652
  const DIR_CLOSE = new Set([
5411
5653
  'endif',
@@ -5420,8 +5662,9 @@ const DIR_CLOSE = new Set([
5420
5662
  /**
5421
5663
  * Reindent a template that already had its Janja tags normalised.
5422
5664
  * Only leading whitespace on each line changes; line breaks and
5423
- * intra-line spacing stay put. Content inside pre/textarea/script/style
5424
- * is left alone; the closing tag of those elements is still reindented.
5665
+ * intra-line spacing stay put. Content inside pre/textarea is left alone;
5666
+ * `script` / `style` bodies are brace-reindented; `stylesheet` bodies are
5667
+ * formatted as an HTML fragment (so nested `<style>` gets CSS indent).
5425
5668
  */
5426
5669
  function indentHtml(source, options) {
5427
5670
  const tabWidth = options.tabWidth ?? 2;
@@ -5430,6 +5673,8 @@ function indentHtml(source, options) {
5430
5673
  const lines = source.split(/\r?\n/);
5431
5674
  let depth = 0;
5432
5675
  let sensitive = null;
5676
+ /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5677
+ let bodyBuf = null;
5433
5678
  const out = [];
5434
5679
  for (const line of lines) {
5435
5680
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
@@ -5438,7 +5683,28 @@ function indentHtml(source, options) {
5438
5683
  const activeSensitive = sensitive;
5439
5684
  const closesSensitive = activeSensitive !== null &&
5440
5685
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5441
- if (sensitive && !closesSensitive) {
5686
+ const reindentBody = activeSensitive === 'stylesheet' ||
5687
+ (activeSensitive !== null && REINDENT_HTML.has(activeSensitive));
5688
+ if (reindentBody && !closesSensitive) {
5689
+ // Do not applyDepth: bodies may contain nested Janja if/for tags.
5690
+ (bodyBuf ?? (bodyBuf = [])).push(line);
5691
+ continue;
5692
+ }
5693
+ if (bodyBuf && closesSensitive && reindentBody) {
5694
+ // stylesheet: same column as the tags; script/style: one level inside.
5695
+ const baseDepth = activeSensitive === 'stylesheet' ? Math.max(0, depth - 1) : depth;
5696
+ const raw = bodyBuf.join(eol);
5697
+ const formatted = activeSensitive === 'stylesheet'
5698
+ ? indentHtml(raw, options)
5699
+ : activeSensitive === 'style'
5700
+ ? indentCss(raw, tabWidth)
5701
+ : indentJs(raw, tabWidth);
5702
+ for (const bodyLine of formatted.split(/\r?\n/)) {
5703
+ out.push(bodyLine.length === 0 ? '' : pad.repeat(baseDepth) + bodyLine);
5704
+ }
5705
+ bodyBuf = null;
5706
+ }
5707
+ else if (sensitive && !closesSensitive) {
5442
5708
  out.push(line);
5443
5709
  applyDepth(pieces);
5444
5710
  continue;
@@ -5540,13 +5806,26 @@ function readDirective(line, start, options) {
5540
5806
  return { end };
5541
5807
  }
5542
5808
  if (DIR_CLOSE.has(name)) {
5543
- return { end, piece: { kind: 'close' } };
5809
+ const base = name.startsWith('end') ? name.slice(3) : name;
5810
+ return {
5811
+ end,
5812
+ piece: {
5813
+ kind: 'close',
5814
+ sensitive: DIR_SENSITIVE.has(base) ? base : undefined,
5815
+ },
5816
+ };
5544
5817
  }
5545
5818
  if (DIR_MID.has(name)) {
5546
5819
  return { end, piece: { kind: 'mid' } };
5547
5820
  }
5548
5821
  if (DIR_OPEN.has(name)) {
5549
- return { end, piece: { kind: 'open' } };
5822
+ return {
5823
+ end,
5824
+ piece: {
5825
+ kind: 'open',
5826
+ sensitive: DIR_SENSITIVE.has(name) ? name : undefined,
5827
+ },
5828
+ };
5550
5829
  }
5551
5830
  return { end };
5552
5831
  }