janja 4.0.0 → 4.2.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
@@ -1577,6 +1577,189 @@ class Parser extends Tokenizer {
1577
1577
  }
1578
1578
  }
1579
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';
1751
+ }
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];
1760
+ }
1761
+ }
1762
+
1580
1763
  const fingerprints = new WeakMap();
1581
1764
  // How deep includes may nest while rendering. Only templates that include
1582
1765
  // themselves get anywhere near it; the limit turns a cycle that never ends
@@ -1593,6 +1776,8 @@ function optionsFingerprint(options) {
1593
1776
  let fingerprint = fingerprints.get(options);
1594
1777
  if (fingerprint === undefined) {
1595
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);
1596
1781
  fingerprint = JSON.stringify([
1597
1782
  trimWhitespace,
1598
1783
  stripComments,
@@ -1602,6 +1787,9 @@ function optionsFingerprint(options) {
1602
1787
  directiveClose,
1603
1788
  outputOpen,
1604
1789
  outputClose,
1790
+ maxIncludeDepth,
1791
+ maxLoopIterations ?? null,
1792
+ maxCallDepth ?? null,
1605
1793
  ]);
1606
1794
  fingerprints.set(options, fingerprint);
1607
1795
  }
@@ -1664,6 +1852,20 @@ class Compiler extends Context {
1664
1852
  writable: true,
1665
1853
  value: void 0
1666
1854
  });
1855
+ /** Stylesheet bodies keyed by include path (or `\0root` for the root template). */
1856
+ Object.defineProperty(this, "stylesheets", {
1857
+ enumerable: true,
1858
+ configurable: true,
1859
+ writable: true,
1860
+ value: void 0
1861
+ });
1862
+ /** Key used when collecting stylesheets from the template currently compiling. */
1863
+ Object.defineProperty(this, "stylesheetKey", {
1864
+ enumerable: true,
1865
+ configurable: true,
1866
+ writable: true,
1867
+ value: void 0
1868
+ });
1667
1869
  Object.defineProperty(this, "sources", {
1668
1870
  enumerable: true,
1669
1871
  configurable: true,
@@ -1694,11 +1896,13 @@ class Compiler extends Context {
1694
1896
  });
1695
1897
  this.cache = cache;
1696
1898
  }
1697
- async compile(template, root = true, partials = new Map(), blocks = new Map(), sources = new Map()) {
1899
+ async compile(template, root = true, partials = new Map(), blocks = new Map(), sources = new Map(), stylesheets = new Map(), stylesheetKey = '\0root') {
1698
1900
  this.template = template;
1699
1901
  this.isRoot = root;
1700
1902
  this.partials = partials;
1701
1903
  this.blocks = blocks;
1904
+ this.stylesheets = stylesheets;
1905
+ this.stylesheetKey = stylesheetKey;
1702
1906
  this.sources = sources;
1703
1907
  // Generate cache key from template and options
1704
1908
  const cacheKey = this.generateCacheKey(template);
@@ -1719,12 +1923,17 @@ class Compiler extends Context {
1719
1923
  this.rootNode = new Parser(this.options).parse(template);
1720
1924
  this.state = {};
1721
1925
  this.start(this.isRoot);
1926
+ if (this.isRoot) {
1927
+ this.pushResourceLimitCounters();
1928
+ this.pushRaw(null, 'let ss_u=0;');
1929
+ }
1722
1930
  await this.parseTemplates();
1723
1931
  if (this.isRoot) {
1724
1932
  if (this.partials.size) {
1933
+ const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1725
1934
  this.pushRaw(null, 'let d_=0;', 'const p={');
1726
1935
  for (const [path, code] of this.partials) {
1727
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${MAX_INCLUDE_DEPTH})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
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_--;}', '},');
1728
1937
  }
1729
1938
  this.pushRaw(null, '};');
1730
1939
  }
@@ -1743,6 +1952,16 @@ class Compiler extends Context {
1743
1952
  }
1744
1953
  this.pushRaw(null, '};');
1745
1954
  }
1955
+ // Always emit ss_ so `{{ stylesheets }}` can run even when empty.
1956
+ this.pushRaw(null, 'const ss_=[');
1957
+ for (const [, nodes] of this.stylesheets) {
1958
+ this.pushRaw(null, 'async()=>{', 'let s="";');
1959
+ for (const node of nodes) {
1960
+ await this.compileNodes(node.body);
1961
+ }
1962
+ this.pushRaw(null, 'return s;', '},');
1963
+ }
1964
+ this.pushRaw(null, '];');
1746
1965
  }
1747
1966
  this.flushable = this.isRoot && this.stream;
1748
1967
  await this.compileNode(this.rootNode);
@@ -1773,6 +1992,19 @@ class Compiler extends Context {
1773
1992
  fingerprint() {
1774
1993
  return optionsFingerprint(this.options);
1775
1994
  }
1995
+ /**
1996
+ * Shared counters for optional security limits. Declared once on the root
1997
+ * template so nested includes, macros and loops all see the same budget.
1998
+ */
1999
+ pushResourceLimitCounters() {
2000
+ const { maxLoopIterations, maxCallDepth } = resolveSecurityLimits(this.options.security);
2001
+ if (maxLoopIterations != null) {
2002
+ this.pushRaw(null, 'let li_=0;');
2003
+ }
2004
+ if (maxCallDepth != null) {
2005
+ this.pushRaw(null, 'let cd_=0;');
2006
+ }
2007
+ }
1776
2008
  async isFresh({ sources }) {
1777
2009
  if (!this.revalidate) {
1778
2010
  return true;
@@ -1790,7 +2022,7 @@ class Compiler extends Context {
1790
2022
  return true;
1791
2023
  }
1792
2024
  async parseTemplates() {
1793
- const { partials, blocks } = this.collectPartialsAndBlocks();
2025
+ const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
1794
2026
  for (const [path, node] of partials) {
1795
2027
  if (!this.partials.has(path)) {
1796
2028
  let template;
@@ -1817,10 +2049,15 @@ class Compiler extends Context {
1817
2049
  }
1818
2050
  this.blocks.get(value).push(block);
1819
2051
  }
2052
+ // One entry per source file (Shopify: at most one stylesheet tag per file).
2053
+ if (stylesheets.length && !this.stylesheets.has(this.stylesheetKey)) {
2054
+ this.stylesheets.set(this.stylesheetKey, stylesheets);
2055
+ }
1820
2056
  }
1821
2057
  collectPartialsAndBlocks() {
1822
2058
  const partials = new Map();
1823
2059
  const blocks = [];
2060
+ const stylesheets = [];
1824
2061
  const traverse = (node) => {
1825
2062
  if (node.type === 'INCLUDE') {
1826
2063
  if (!partials.has(node.val.value)) {
@@ -1830,12 +2067,16 @@ class Compiler extends Context {
1830
2067
  if (node.type === 'BLOCK') {
1831
2068
  blocks.push(node);
1832
2069
  }
2070
+ if (node.type === 'STYLESHEET') {
2071
+ stylesheets.push(node);
2072
+ }
1833
2073
  node.traverse(traverse);
1834
2074
  };
1835
2075
  traverse(this.rootNode);
1836
2076
  return {
1837
2077
  partials,
1838
2078
  blocks,
2079
+ stylesheets,
1839
2080
  };
1840
2081
  }
1841
2082
  async compileNode(node) {
@@ -1885,7 +2126,7 @@ class Compiler extends Context {
1885
2126
  }
1886
2127
  async compilePartial(path, node, template) {
1887
2128
  try {
1888
- const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources);
2129
+ const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
1889
2130
  this.partials.set(path, code);
1890
2131
  }
1891
2132
  catch {
@@ -1894,29 +2135,6 @@ class Compiler extends Context {
1894
2135
  }
1895
2136
  }
1896
2137
 
1897
- const special = /[&<>"']/;
1898
- const specials = /[&<>"']/g;
1899
- const entities = {
1900
- '&': '&amp;',
1901
- '"': '&#34;',
1902
- "'": '&#39;',
1903
- '<': '&lt;',
1904
- '>': '&gt;',
1905
- };
1906
- const entity = (char) => entities[char];
1907
- function escape(v) {
1908
- const str = typeof v === 'string' ? v : `${v}`;
1909
- // Most values contain nothing to escape; they are returned as they are,
1910
- // without allocating
1911
- return special.test(str) ? str.replace(specials, entity) : str;
1912
- }
1913
-
1914
- class Safe extends String {
1915
- constructor(value) {
1916
- super(`${value}`);
1917
- }
1918
- }
1919
-
1920
2138
  function abs(value = 0) {
1921
2139
  return Math.abs(value);
1922
2140
  }
@@ -2314,7 +2532,7 @@ async function compileSuper({ loc }, compiler) {
2314
2532
  // Each super() call pops the next level from the stack
2315
2533
  compiler.pushRaw(loc, `s+=await b[${JSON.stringify(compiler.state.block)}]?.s?.pop()?.()??"";`);
2316
2534
  }
2317
- const compilers$d = {
2535
+ const compilers$e = {
2318
2536
  BLOCK: compileBlock,
2319
2537
  SUPER: compileSuper,
2320
2538
  };
@@ -2407,15 +2625,15 @@ function* parseSuper(token, parser) {
2407
2625
  yield 'NEXT';
2408
2626
  yield new SuperNode(token.val, token.loc, token.strip);
2409
2627
  }
2410
- const parsers$d = {
2628
+ const parsers$e = {
2411
2629
  block: parseBlock,
2412
2630
  super: parseSuper,
2413
2631
  endblock: 'unexpected',
2414
2632
  };
2415
2633
 
2416
- const plugin$d = {
2417
- compilers: compilers$d,
2418
- parsers: parsers$d,
2634
+ const plugin$e = {
2635
+ compilers: compilers$e,
2636
+ parsers: parsers$e,
2419
2637
  };
2420
2638
 
2421
2639
  const expTokenOperators$1 = {
@@ -2591,7 +2809,7 @@ async function compileCall({ val, body, loc }, compiler) {
2591
2809
  await compiler.compileNodes(body);
2592
2810
  compiler.pushRaw(null, 'return s;', '})??"";');
2593
2811
  }
2594
- const compilers$c = {
2812
+ const compilers$d = {
2595
2813
  CALL: compileCall,
2596
2814
  };
2597
2815
 
@@ -2646,14 +2864,14 @@ function* parseCall(token, parser) {
2646
2864
  }
2647
2865
  yield new CallNode(parser.parseExp(token.expression), body, token.loc, token.strip);
2648
2866
  }
2649
- const parsers$c = {
2867
+ const parsers$d = {
2650
2868
  call: parseCall,
2651
2869
  endcall: 'unexpected',
2652
2870
  };
2653
2871
 
2654
- const plugin$c = {
2655
- compilers: compilers$c,
2656
- parsers: parsers$c,
2872
+ const plugin$d = {
2873
+ compilers: compilers$d,
2874
+ parsers: parsers$d,
2657
2875
  };
2658
2876
 
2659
2877
  async function compileCapture({ val, body, loc }, compiler) {
@@ -2663,7 +2881,7 @@ async function compileCapture({ val, body, loc }, compiler) {
2663
2881
  await compiler.compileNodes(body);
2664
2882
  compiler.pushRaw(null, 'return s;})(""));');
2665
2883
  }
2666
- const compilers$b = {
2884
+ const compilers$c = {
2667
2885
  CAPTURE: compileCapture,
2668
2886
  };
2669
2887
 
@@ -2718,14 +2936,14 @@ function* parseCapture(token, parser) {
2718
2936
  }
2719
2937
  yield new CaptureNode(parser.parseExp(token.expression), body, token.loc, token.strip);
2720
2938
  }
2721
- const parsers$b = {
2939
+ const parsers$c = {
2722
2940
  capture: parseCapture,
2723
2941
  endcapture: 'unexpected',
2724
2942
  };
2725
2943
 
2726
- const plugin$b = {
2727
- compilers: compilers$b,
2728
- parsers: parsers$b,
2944
+ const plugin$c = {
2945
+ compilers: compilers$c,
2946
+ parsers: parsers$c,
2729
2947
  };
2730
2948
 
2731
2949
  async function compileComment({ val, loc }, compiler) {
@@ -2733,7 +2951,7 @@ async function compileComment({ val, loc }, compiler) {
2733
2951
  compiler.pushStr(loc, `<!--${val}-->`);
2734
2952
  }
2735
2953
  }
2736
- const compilers$a = {
2954
+ const compilers$b = {
2737
2955
  COMMENT: compileComment,
2738
2956
  };
2739
2957
 
@@ -2771,13 +2989,13 @@ function* parseComment({ val, loc, strip }) {
2771
2989
  yield 'NEXT';
2772
2990
  yield new CommentNode(val, loc, strip);
2773
2991
  }
2774
- const parsers$a = {
2992
+ const parsers$b = {
2775
2993
  comment: parseComment,
2776
2994
  };
2777
2995
 
2778
- const plugin$a = {
2779
- compilers: compilers$a,
2780
- parsers: parsers$a,
2996
+ const plugin$b = {
2997
+ compilers: compilers$b,
2998
+ parsers: parsers$b,
2781
2999
  };
2782
3000
 
2783
3001
  const loop = 'loop:{first:i_===0,index:i_++,last:i_===n_}';
@@ -2847,13 +3065,19 @@ async function compileFor({ loop: { left, right, loc }, body, alternative }, com
2847
3065
  : [[left.value, 'v_']];
2848
3066
  const scope = compiler.in();
2849
3067
  compiler.pushRaw(loc, 'let i_=0;');
3068
+ const { maxLoopIterations } = resolveSecurityLimits(compiler.options.security);
3069
+ const loopGuard = maxLoopIterations == null
3070
+ ? []
3071
+ : [
3072
+ `if(++li_>${maxLoopIterations})throw new Error(${JSON.stringify(`Loop iteration limit of ${maxLoopIterations} exceeded`)});`,
3073
+ ];
2850
3074
  if (isReadOnly(body)) {
2851
3075
  // Nothing in the body can modify the scope, so a single one is shared by
2852
3076
  // all iterations instead of copying the outer context for each of them
2853
- compiler.pushRaw(loc, `const ${scope}={...${context}};`, 'for(const v_ of a_){', `${scope}.loop={${loop.slice(6)};`, ...variables.map(([name, value]) => `${scope}.${name}=${value};`));
3077
+ compiler.pushRaw(loc, `const ${scope}={...${context}};`, 'for(const v_ of a_){', ...loopGuard, `${scope}.loop={${loop.slice(6)};`, ...variables.map(([name, value]) => `${scope}.${name}=${value};`));
2854
3078
  }
2855
3079
  else {
2856
- compiler.pushRaw(loc, 'for(const v_ of a_){', `const ${scope}={`, `...${context},`, `${loop},`, ...variables.map(([name, value]) => `${name}:${value},`), '};');
3080
+ compiler.pushRaw(loc, 'for(const v_ of a_){', ...loopGuard, `const ${scope}={`, `...${context},`, `${loop},`, ...variables.map(([name, value]) => `${name}:${value},`), '};');
2857
3081
  }
2858
3082
  await compiler.compileNodes(body);
2859
3083
  compiler.out();
@@ -2868,7 +3092,7 @@ function compileBreak({ loc }, compiler) {
2868
3092
  function compileContinue({ loc }, compiler) {
2869
3093
  compiler.pushRaw(loc, 'continue;');
2870
3094
  }
2871
- const compilers$9 = {
3095
+ const compilers$a = {
2872
3096
  FOR: compileFor,
2873
3097
  BREAK: compileBreak,
2874
3098
  CONTINUE: compileContinue,
@@ -3084,16 +3308,16 @@ function* parseContinue(token, parser) {
3084
3308
  yield 'NEXT';
3085
3309
  yield new ContinueNode(token.val, token.loc, token.strip);
3086
3310
  }
3087
- const parsers$9 = {
3311
+ const parsers$a = {
3088
3312
  for: parseFor,
3089
3313
  break: parseBreak,
3090
3314
  continue: parseContinue,
3091
3315
  endfor: 'unexpected',
3092
3316
  };
3093
3317
 
3094
- const plugin$9 = {
3095
- compilers: compilers$9,
3096
- parsers: parsers$9,
3318
+ const plugin$a = {
3319
+ compilers: compilers$a,
3320
+ parsers: parsers$a,
3097
3321
  };
3098
3322
 
3099
3323
  async function compileIf({ test, body, alternatives }, compiler) {
@@ -3111,7 +3335,7 @@ async function compileIf({ test, body, alternatives }, compiler) {
3111
3335
  compiler.pushRaw(null, '}');
3112
3336
  }
3113
3337
  }
3114
- const compilers$8 = {
3338
+ const compilers$9 = {
3115
3339
  IF: compileIf,
3116
3340
  };
3117
3341
 
@@ -3298,7 +3522,7 @@ function* parseElse(token, parser) {
3298
3522
  yield 'NEXT';
3299
3523
  yield new ElseNode(parser.parseUntil(['endif']), token.loc, token.strip);
3300
3524
  }
3301
- const parsers$8 = {
3525
+ const parsers$9 = {
3302
3526
  if: parseIf,
3303
3527
  elseif: 'unexpected',
3304
3528
  elsif: 'unexpected',
@@ -3306,15 +3530,15 @@ const parsers$8 = {
3306
3530
  endif: 'unexpected',
3307
3531
  };
3308
3532
 
3309
- const plugin$8 = {
3310
- compilers: compilers$8,
3311
- parsers: parsers$8,
3533
+ const plugin$9 = {
3534
+ compilers: compilers$9,
3535
+ parsers: parsers$9,
3312
3536
  };
3313
3537
 
3314
3538
  async function compileInclude({ val: { value }, loc }, compiler) {
3315
3539
  compiler.pushRaw(loc, `s+=await p[${JSON.stringify(value)}]?.()??"";`);
3316
3540
  }
3317
- const compilers$7 = {
3541
+ const compilers$8 = {
3318
3542
  INCLUDE: compileInclude,
3319
3543
  };
3320
3544
 
@@ -3356,32 +3580,39 @@ function* parseInclude(token, parser) {
3356
3580
  yield 'NEXT';
3357
3581
  yield new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
3358
3582
  }
3359
- const parsers$7 = {
3583
+ const parsers$8 = {
3360
3584
  include: parseInclude,
3361
3585
  };
3362
3586
 
3363
- const plugin$7 = {
3364
- compilers: compilers$7,
3365
- parsers: parsers$7,
3587
+ const plugin$8 = {
3588
+ compilers: compilers$8,
3589
+ parsers: parsers$8,
3366
3590
  };
3367
3591
 
3368
3592
  async function compileMacro({ val: { value, args }, loc, body }, compiler) {
3369
3593
  const { context } = compiler;
3370
3594
  const expCompiler = new ExpCompiler();
3595
+ const { maxCallDepth } = resolveSecurityLimits(compiler.options.security);
3371
3596
  compiler.pushRaw(loc,
3372
3597
  // A macro collects its own output and returns it, so that it ends up
3373
3598
  // where the macro is called rather than where it was defined
3374
- `${context}.${value}=(...a_)=>async(_c)=>{`, 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3599
+ `${context}.${value}=(...a_)=>async(_c)=>{`, ...(maxCallDepth == null
3600
+ ? []
3601
+ : [
3602
+ `if(cd_>=${maxCallDepth})throw new Error(${JSON.stringify(`Macro call depth limit of ${maxCallDepth} exceeded`)});`,
3603
+ 'cd_++;',
3604
+ 'try{',
3605
+ ]), 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3375
3606
  ? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
3376
3607
  : `${el.value}:a_[${i}],`), '};');
3377
3608
  await compiler.compileNodes(body);
3378
3609
  compiler.out();
3379
- compiler.pushRaw(null, 'return s;', '};');
3610
+ compiler.pushRaw(null, 'return s;', ...(maxCallDepth == null ? [] : ['}finally{cd_--;}']), '};');
3380
3611
  }
3381
3612
  function compileCaller({ loc }, compiler) {
3382
3613
  compiler.pushRaw(loc, 's+=await _c?.()??"";');
3383
3614
  }
3384
- const compilers$6 = {
3615
+ const compilers$7 = {
3385
3616
  MACRO: compileMacro,
3386
3617
  CALLER: compileCaller,
3387
3618
  };
@@ -3500,21 +3731,21 @@ function* parseCaller(token, parser) {
3500
3731
  yield 'NEXT';
3501
3732
  yield new CallerNode(token.val, token.loc, token.strip);
3502
3733
  }
3503
- const parsers$6 = {
3734
+ const parsers$7 = {
3504
3735
  macro: parseMacro,
3505
3736
  caller: parseCaller,
3506
3737
  endmacro: 'unexpected',
3507
3738
  };
3508
3739
 
3509
- const plugin$6 = {
3510
- compilers: compilers$6,
3511
- parsers: parsers$6,
3740
+ const plugin$7 = {
3741
+ compilers: compilers$7,
3742
+ parsers: parsers$7,
3512
3743
  };
3513
3744
 
3514
3745
  async function compileOutput({ val }, compiler) {
3515
3746
  compiler.pushVar(val.loc, new ExpCompiler().compile(val, compiler.context));
3516
3747
  }
3517
- const compilers$5 = {
3748
+ const compilers$6 = {
3518
3749
  OUTPUT: compileOutput,
3519
3750
  };
3520
3751
 
@@ -3554,19 +3785,19 @@ function* parseOutput(token, parser) {
3554
3785
  const start = updatePosition(`${parser.options.outputOpen}${token.strip.before ? '-' : ''}`, { ...token.loc.start });
3555
3786
  yield new OutputNode(parser.parseExp({ val: token.val, loc: { start, end: token.loc.end } }), token.loc, token.strip);
3556
3787
  }
3557
- const parsers$5 = {
3788
+ const parsers$6 = {
3558
3789
  output: parseOutput,
3559
3790
  };
3560
3791
 
3561
- const plugin$5 = {
3562
- compilers: compilers$5,
3563
- parsers: parsers$5,
3792
+ const plugin$6 = {
3793
+ compilers: compilers$6,
3794
+ parsers: parsers$6,
3564
3795
  };
3565
3796
 
3566
3797
  async function compileSet({ val, loc }, compiler) {
3567
3798
  compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
3568
3799
  }
3569
- const compilers$4 = {
3800
+ const compilers$5 = {
3570
3801
  SET: compileSet,
3571
3802
  };
3572
3803
 
@@ -3577,8 +3808,98 @@ class SetNode extends Traversal {
3577
3808
  enumerable: true,
3578
3809
  configurable: true,
3579
3810
  writable: true,
3580
- value: val
3811
+ value: val
3812
+ });
3813
+ Object.defineProperty(this, "loc", {
3814
+ enumerable: true,
3815
+ configurable: true,
3816
+ writable: true,
3817
+ value: loc
3818
+ });
3819
+ Object.defineProperty(this, "strip", {
3820
+ enumerable: true,
3821
+ configurable: true,
3822
+ writable: true,
3823
+ value: strip
3824
+ });
3825
+ Object.defineProperty(this, "type", {
3826
+ enumerable: true,
3827
+ configurable: true,
3828
+ writable: true,
3829
+ value: 'SET'
3830
+ });
3831
+ }
3832
+ }
3833
+
3834
+ function* parseSet(token, parser) {
3835
+ if (!token.expression) {
3836
+ parser.emitExpErr(token);
3837
+ return;
3838
+ }
3839
+ yield 'NEXT';
3840
+ yield new SetNode(parser.parseExp(token.expression), token.loc, token.strip);
3841
+ }
3842
+ const parsers$5 = {
3843
+ set: parseSet,
3844
+ };
3845
+
3846
+ const plugin$5 = {
3847
+ compilers: compilers$5,
3848
+ parsers: parsers$5,
3849
+ };
3850
+
3851
+ /**
3852
+ * Stylesheet bodies are collected at compile time (like blocks) and emitted
3853
+ * only by `{{ stylesheets }}`. The site of `{{ stylesheet }}` itself writes
3854
+ * nothing.
3855
+ */
3856
+ async function compileStylesheet() {
3857
+ // no-op: collected into Compiler.stylesheets
3858
+ }
3859
+ async function compileStylesheets({ loc }, compiler) {
3860
+ compiler.pushRaw(loc,
3861
+ // 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>";', '}');
3863
+ }
3864
+ const compilers$4 = {
3865
+ STYLESHEET: compileStylesheet,
3866
+ STYLESHEETS: compileStylesheets,
3867
+ };
3868
+
3869
+ /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
3870
+ class StylesheetNode extends Traversal {
3871
+ constructor(body, loc, strip) {
3872
+ super();
3873
+ Object.defineProperty(this, "body", {
3874
+ enumerable: true,
3875
+ configurable: true,
3876
+ writable: true,
3877
+ value: body
3878
+ });
3879
+ Object.defineProperty(this, "loc", {
3880
+ enumerable: true,
3881
+ configurable: true,
3882
+ writable: true,
3883
+ value: loc
3884
+ });
3885
+ Object.defineProperty(this, "strip", {
3886
+ enumerable: true,
3887
+ configurable: true,
3888
+ writable: true,
3889
+ value: strip
3890
+ });
3891
+ Object.defineProperty(this, "type", {
3892
+ enumerable: true,
3893
+ configurable: true,
3894
+ writable: true,
3895
+ value: 'STYLESHEET'
3581
3896
  });
3897
+ }
3898
+ }
3899
+ /** Emits every collected stylesheet into the document (typically in `<head>`). */
3900
+ class StylesheetsNode extends Traversal {
3901
+ constructor(loc, strip) {
3902
+ super();
3582
3903
  Object.defineProperty(this, "loc", {
3583
3904
  enumerable: true,
3584
3905
  configurable: true,
@@ -3595,21 +3916,38 @@ class SetNode extends Traversal {
3595
3916
  enumerable: true,
3596
3917
  configurable: true,
3597
3918
  writable: true,
3598
- value: 'SET'
3919
+ value: 'STYLESHEETS'
3599
3920
  });
3600
3921
  }
3601
3922
  }
3602
3923
 
3603
- function* parseSet(token, parser) {
3604
- if (!token.expression) {
3605
- parser.emitExpErr(token);
3924
+ function* parseStylesheet(token, parser) {
3925
+ if (token.expression) {
3926
+ parser.emitExpErr(token, false);
3606
3927
  return;
3607
3928
  }
3608
3929
  yield 'NEXT';
3609
- yield new SetNode(parser.parseExp(token.expression), token.loc, token.strip);
3930
+ const body = parser.parseUntil(['endstylesheet']);
3931
+ if (parser.match(['endstylesheet'])) {
3932
+ yield 'NEXT';
3933
+ }
3934
+ else {
3935
+ parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
3936
+ }
3937
+ yield new StylesheetNode(body, token.loc, token.strip);
3938
+ }
3939
+ function* parseStylesheets(token, parser) {
3940
+ if (token.expression) {
3941
+ parser.emitExpErr(token, false);
3942
+ return;
3943
+ }
3944
+ yield 'NEXT';
3945
+ yield new StylesheetsNode(token.loc, token.strip);
3610
3946
  }
3611
3947
  const parsers$4 = {
3612
- set: parseSet,
3948
+ stylesheet: parseStylesheet,
3949
+ endstylesheet: 'unexpected',
3950
+ stylesheets: parseStylesheets,
3613
3951
  };
3614
3952
 
3615
3953
  const plugin$4 = {
@@ -3868,17 +4206,18 @@ const plugin = {
3868
4206
  };
3869
4207
 
3870
4208
  const plugins = [
4209
+ plugin$e,
3871
4210
  plugin$d,
4211
+ plugin$b,
3872
4212
  plugin$c,
3873
4213
  plugin$a,
3874
- plugin$b,
3875
4214
  plugin$9,
3876
4215
  plugin$8,
3877
4216
  plugin$7,
3878
- plugin$6,
4217
+ plugin$5,
3879
4218
  plugin$4,
3880
4219
  plugin$3,
3881
- plugin$5,
4220
+ plugin$6,
3882
4221
  plugin$2,
3883
4222
  plugin$1,
3884
4223
  plugin,
@@ -3908,157 +4247,6 @@ class RenderError extends CompileError {
3908
4247
  }
3909
4248
  }
3910
4249
 
3911
- class SecuritySandbox {
3912
- constructor(options = {}) {
3913
- Object.defineProperty(this, "allowedGlobals", {
3914
- enumerable: true,
3915
- configurable: true,
3916
- writable: true,
3917
- value: void 0
3918
- });
3919
- Object.defineProperty(this, "cspNonce", {
3920
- enumerable: true,
3921
- configurable: true,
3922
- writable: true,
3923
- value: void 0
3924
- });
3925
- this.allowedGlobals = new Set(options.allowedGlobals || []);
3926
- this.cspNonce = options.cspNonce;
3927
- }
3928
- sanitizeGlobals(globals) {
3929
- const sanitized = {};
3930
- for (const [key, value] of Object.entries(globals)) {
3931
- if (this.allowedGlobals.has(key)) {
3932
- sanitized[key] = value;
3933
- }
3934
- }
3935
- return sanitized;
3936
- }
3937
- validateExpression(expression) {
3938
- // Prevent access to dangerous globals
3939
- const dangerousPatterns = [
3940
- /\bprocess\b/,
3941
- /\brequire\b/,
3942
- /\bimport\b/,
3943
- /\bexport\b/,
3944
- /\beval\b/,
3945
- /\bFunction\b/,
3946
- /\b__proto__\b/,
3947
- /\bconstructor\b/,
3948
- ];
3949
- for (const pattern of dangerousPatterns) {
3950
- if (pattern.test(expression)) {
3951
- return false;
3952
- }
3953
- }
3954
- return true;
3955
- }
3956
- createSecureContext(globals) {
3957
- const sanitized = this.sanitizeGlobals(globals);
3958
- // Add safe utility functions
3959
- return {
3960
- ...sanitized,
3961
- Math,
3962
- Date,
3963
- JSON,
3964
- // Add other safe built-ins as needed
3965
- };
3966
- }
3967
- getCSPNonce() {
3968
- return this.cspNonce;
3969
- }
3970
- generateCSPHeaders() {
3971
- const headers = {};
3972
- if (this.cspNonce) {
3973
- headers['Content-Security-Policy'] =
3974
- `script-src 'nonce-${this.cspNonce}'`;
3975
- }
3976
- return headers;
3977
- }
3978
- }
3979
- function deepEscape(value, seen = new WeakSet()) {
3980
- if (value === null || value === undefined) {
3981
- return '';
3982
- }
3983
- if (value instanceof Safe) {
3984
- return `${value}`;
3985
- }
3986
- if (typeof value === 'object') {
3987
- // Guard against circular references
3988
- if (seen.has(value)) {
3989
- return '';
3990
- }
3991
- seen.add(value);
3992
- const values = Array.isArray(value)
3993
- ? value
3994
- : Object.values(value);
3995
- return values.map((v) => deepEscape(v, seen)).join('');
3996
- }
3997
- return escape(value);
3998
- }
3999
- class SecurityAuditor {
4000
- auditTemplate(template) {
4001
- const issues = [];
4002
- // Check for dangerous patterns
4003
- const dangerousPatterns = [
4004
- {
4005
- pattern: /\beval\s*\(/,
4006
- type: 'dangerous-eval',
4007
- message: 'Use of eval() is dangerous and should be avoided',
4008
- severity: 'critical',
4009
- },
4010
- {
4011
- pattern: /\bFunction\s*\(/,
4012
- type: 'dangerous-function',
4013
- message: 'Use of Function constructor is dangerous',
4014
- severity: 'critical',
4015
- },
4016
- {
4017
- pattern: /\brequire\s*\(/,
4018
- type: 'require-usage',
4019
- message: 'Direct require() usage in templates is unsafe',
4020
- severity: 'high',
4021
- },
4022
- {
4023
- pattern: /\bimport\s*\(/,
4024
- type: 'dynamic-import',
4025
- message: 'Dynamic import() usage in templates may be unsafe',
4026
- severity: 'high',
4027
- },
4028
- ];
4029
- for (const { pattern, type, message, severity } of dangerousPatterns) {
4030
- const match = template.match(pattern);
4031
- if (match) {
4032
- issues.push({
4033
- type,
4034
- message,
4035
- location: `at index ${match.index}`,
4036
- severity,
4037
- });
4038
- }
4039
- }
4040
- // Calculate overall severity
4041
- const overallSeverity = this.calculateOverallSeverity(issues);
4042
- return {
4043
- issues,
4044
- severity: overallSeverity,
4045
- };
4046
- }
4047
- calculateOverallSeverity(issues) {
4048
- if (issues.length === 0) {
4049
- return 'low';
4050
- }
4051
- const severityMap = {
4052
- critical: 4,
4053
- high: 3,
4054
- medium: 2,
4055
- low: 1,
4056
- };
4057
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
4058
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
4059
- }
4060
- }
4061
-
4062
4250
  // Thrown inside a template to stop rendering a stream nobody reads anymore
4063
4251
  const cancellation = new Error('Stream cancelled');
4064
4252
  class Renderer {
@@ -4272,7 +4460,24 @@ class Renderer {
4272
4460
  ...globals,
4273
4461
  }
4274
4462
  : { ...this.options.globals, ...globals };
4275
- return script(context, this.escape, this.filters, write);
4463
+ const result = script(context, this.escape, this.filters, write);
4464
+ const { timeoutMs } = this.options.security ?? {};
4465
+ if (timeoutMs == null) {
4466
+ return result;
4467
+ }
4468
+ // The script keeps running after the budget; only the promise rejects.
4469
+ // Use a separate process when templates must be forcibly stopped.
4470
+ let timer;
4471
+ return Promise.race([
4472
+ Promise.resolve(result).finally(() => {
4473
+ clearTimeout(timer);
4474
+ }),
4475
+ new Promise((_, reject) => {
4476
+ timer = setTimeout(() => {
4477
+ reject(new Error(`Render timed out after ${timeoutMs}ms`));
4478
+ }, timeoutMs);
4479
+ }),
4480
+ ]);
4276
4481
  }
4277
4482
  async renderFile(filepath, globals) {
4278
4483
  return this.render(await this.options.loader(filepath), globals);
@@ -4405,6 +4610,9 @@ class Analyzer {
4405
4610
  this.blocks.add(node.val.value);
4406
4611
  await this.nodes(node.body, scope);
4407
4612
  break;
4613
+ case 'STYLESHEET':
4614
+ await this.nodes(node.body, scope);
4615
+ break;
4408
4616
  case 'INCLUDE':
4409
4617
  await this.include(node.val.value, scope);
4410
4618
  break;
@@ -5169,18 +5377,303 @@ class ExpFormatter {
5169
5377
  }
5170
5378
  }
5171
5379
 
5380
+ /** HTML void elements — never take children, so they do not change indent. */
5381
+ const VOID = new Set([
5382
+ 'area',
5383
+ 'base',
5384
+ 'br',
5385
+ 'col',
5386
+ 'embed',
5387
+ 'hr',
5388
+ 'img',
5389
+ 'input',
5390
+ 'link',
5391
+ 'meta',
5392
+ 'param',
5393
+ 'source',
5394
+ 'track',
5395
+ 'wbr',
5396
+ ]);
5397
+ /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5398
+ const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5399
+ const DIR_OPEN = new Set([
5400
+ 'if',
5401
+ 'for',
5402
+ 'macro',
5403
+ 'block',
5404
+ 'call',
5405
+ 'capture',
5406
+ 'with',
5407
+ 'stylesheet',
5408
+ ]);
5409
+ const DIR_MID = new Set(['else', 'elif', 'elseif', 'elsif']);
5410
+ const DIR_CLOSE = new Set([
5411
+ 'endif',
5412
+ 'endfor',
5413
+ 'endmacro',
5414
+ 'endblock',
5415
+ 'endcall',
5416
+ 'endcapture',
5417
+ 'endwith',
5418
+ 'endstylesheet',
5419
+ ]);
5420
+ /**
5421
+ * Reindent a template that already had its Janja tags normalised.
5422
+ * 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.
5425
+ */
5426
+ function indentHtml(source, options) {
5427
+ const tabWidth = options.tabWidth ?? 2;
5428
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5429
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5430
+ const lines = source.split(/\r?\n/);
5431
+ let depth = 0;
5432
+ let sensitive = null;
5433
+ const out = [];
5434
+ for (const line of lines) {
5435
+ const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5436
+ const content = line.slice(leading);
5437
+ const { pieces, prefixClosers } = scanLine(content, options);
5438
+ const activeSensitive = sensitive;
5439
+ const closesSensitive = activeSensitive !== null &&
5440
+ pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5441
+ if (sensitive && !closesSensitive) {
5442
+ out.push(line);
5443
+ applyDepth(pieces);
5444
+ continue;
5445
+ }
5446
+ const lineDepth = Math.max(0, depth - prefixClosers);
5447
+ out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5448
+ applyDepth(pieces);
5449
+ }
5450
+ // split() keeps a final empty string when the source already ends in a
5451
+ // newline, so join() alone preserves that trailing newline — do not add
5452
+ // another one or each format grows an extra blank line.
5453
+ return out.join(eol);
5454
+ function applyDepth(pieces) {
5455
+ for (const piece of pieces) {
5456
+ if (piece.kind === 'open') {
5457
+ depth += 1;
5458
+ if (piece.sensitive && !sensitive) {
5459
+ ({ sensitive } = piece);
5460
+ }
5461
+ }
5462
+ else if (piece.kind === 'close') {
5463
+ depth = Math.max(0, depth - 1);
5464
+ if (piece.sensitive && sensitive === piece.sensitive) {
5465
+ sensitive = null;
5466
+ }
5467
+ }
5468
+ else if (piece.kind === 'mid') ;
5469
+ }
5470
+ }
5471
+ }
5472
+ function scanLine(line, options) {
5473
+ const pieces = [];
5474
+ let prefixClosers = 0;
5475
+ let atPrefix = true;
5476
+ let i = 0;
5477
+ while (i < line.length) {
5478
+ if (/\s/.test(line[i])) {
5479
+ i += 1;
5480
+ continue;
5481
+ }
5482
+ const next = readAt(line, i, options);
5483
+ if (!next) {
5484
+ // Plain text ends the leading-closer prefix
5485
+ atPrefix = false;
5486
+ i += 1;
5487
+ continue;
5488
+ }
5489
+ if (next.piece) {
5490
+ pieces.push(next.piece);
5491
+ if (atPrefix &&
5492
+ (next.piece.kind === 'close' || next.piece.kind === 'mid')) {
5493
+ prefixClosers += 1;
5494
+ }
5495
+ else {
5496
+ atPrefix = false;
5497
+ }
5498
+ }
5499
+ else {
5500
+ // Comment / output / unknown directive sitting in the prefix
5501
+ atPrefix = false;
5502
+ }
5503
+ i = next.end;
5504
+ }
5505
+ return { pieces, prefixClosers };
5506
+ }
5507
+ function readAt(line, i, options) {
5508
+ const { commentOpen, directiveOpen, outputOpen } = options;
5509
+ if (line.startsWith(commentOpen, i)) {
5510
+ return {
5511
+ end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5512
+ };
5513
+ }
5514
+ if (line.startsWith(outputOpen, i)) {
5515
+ return {
5516
+ end: endOfDelimited(line, i + outputOpen.length, options.outputClose),
5517
+ };
5518
+ }
5519
+ if (line.startsWith(directiveOpen, i)) {
5520
+ return readDirective(line, i, options);
5521
+ }
5522
+ if (line.startsWith('<!--', i)) {
5523
+ const close = line.indexOf('-->', i + 4);
5524
+ return { end: close === -1 ? line.length : close + 3 };
5525
+ }
5526
+ if (line[i] === '<') {
5527
+ return readHtmlTag(line, i, options);
5528
+ }
5529
+ return null;
5530
+ }
5531
+ function readDirective(line, start, options) {
5532
+ const { directiveOpen, directiveClose } = options;
5533
+ const end = endOfDelimited(line, start + directiveOpen.length, directiveClose);
5534
+ const inner = line.slice(start + directiveOpen.length, end - directiveClose.length);
5535
+ const name = inner
5536
+ .replace(/^\s*-?\s*/, '')
5537
+ .match(/^([A-Za-z_]\w*)/)?.[1]
5538
+ ?.toLowerCase();
5539
+ if (!name) {
5540
+ return { end };
5541
+ }
5542
+ if (DIR_CLOSE.has(name)) {
5543
+ return { end, piece: { kind: 'close' } };
5544
+ }
5545
+ if (DIR_MID.has(name)) {
5546
+ return { end, piece: { kind: 'mid' } };
5547
+ }
5548
+ if (DIR_OPEN.has(name)) {
5549
+ return { end, piece: { kind: 'open' } };
5550
+ }
5551
+ return { end };
5552
+ }
5553
+ function readHtmlTag(line, start, options) {
5554
+ if (line.startsWith('</', start)) {
5555
+ let i = start + 2;
5556
+ while (i < line.length && /\s/.test(line[i])) {
5557
+ i += 1;
5558
+ }
5559
+ const nameStart = i;
5560
+ while (i < line.length && /[A-Za-z0-9:-]/.test(line[i])) {
5561
+ i += 1;
5562
+ }
5563
+ const name = line.slice(nameStart, i).toLowerCase();
5564
+ const end = endOfHtmlTag(line, i, options);
5565
+ if (!name || VOID.has(name)) {
5566
+ return { end };
5567
+ }
5568
+ return {
5569
+ end,
5570
+ piece: {
5571
+ kind: 'close',
5572
+ sensitive: SENSITIVE.has(name) ? name : undefined,
5573
+ },
5574
+ };
5575
+ }
5576
+ if (line.startsWith('<!', start) || line.startsWith('<?', start)) {
5577
+ return { end: endOfHtmlTag(line, start + 2, options) };
5578
+ }
5579
+ let i = start + 1;
5580
+ while (i < line.length && /\s/.test(line[i])) {
5581
+ i += 1;
5582
+ }
5583
+ const nameStart = i;
5584
+ while (i < line.length && /[A-Za-z0-9:-]/.test(line[i])) {
5585
+ i += 1;
5586
+ }
5587
+ const name = line.slice(nameStart, i).toLowerCase();
5588
+ const end = endOfHtmlTag(line, i, options);
5589
+ const raw = line.slice(start, end);
5590
+ const selfClosing = /\/\s*>$/.test(raw) || VOID.has(name);
5591
+ if (!name || selfClosing) {
5592
+ return { end };
5593
+ }
5594
+ return {
5595
+ end,
5596
+ piece: {
5597
+ kind: 'open',
5598
+ sensitive: SENSITIVE.has(name) ? name : undefined,
5599
+ },
5600
+ };
5601
+ }
5602
+ /**
5603
+ * Find the `>` that ends an HTML tag, skipping quotes and Janja tags
5604
+ * (so `class="{{ if a > b }}x{{ endif }}"` does not end early).
5605
+ */
5606
+ function endOfHtmlTag(line, from, options) {
5607
+ let i = from;
5608
+ let quote = null;
5609
+ while (i < line.length) {
5610
+ const c = line[i];
5611
+ if (quote) {
5612
+ if (c === quote) {
5613
+ quote = null;
5614
+ }
5615
+ else {
5616
+ const skipped = trySkipJanja(line, i, options);
5617
+ if (skipped !== null) {
5618
+ i = skipped;
5619
+ continue;
5620
+ }
5621
+ }
5622
+ i += 1;
5623
+ continue;
5624
+ }
5625
+ const skipped = trySkipJanja(line, i, options);
5626
+ if (skipped !== null) {
5627
+ i = skipped;
5628
+ continue;
5629
+ }
5630
+ if (c === '"' || c === "'") {
5631
+ quote = c;
5632
+ i += 1;
5633
+ continue;
5634
+ }
5635
+ if (c === '>') {
5636
+ return i + 1;
5637
+ }
5638
+ i += 1;
5639
+ }
5640
+ return line.length;
5641
+ }
5642
+ function trySkipJanja(line, i, options) {
5643
+ const { commentOpen, commentClose, outputOpen, outputClose, directiveOpen, directiveClose, } = options;
5644
+ if (line.startsWith(commentOpen, i)) {
5645
+ return endOfDelimited(line, i + commentOpen.length, commentClose);
5646
+ }
5647
+ if (line.startsWith(outputOpen, i)) {
5648
+ return endOfDelimited(line, i + outputOpen.length, outputClose);
5649
+ }
5650
+ if (line.startsWith(directiveOpen, i)) {
5651
+ return endOfDelimited(line, i + directiveOpen.length, directiveClose);
5652
+ }
5653
+ return null;
5654
+ }
5655
+ function endOfDelimited(line, from, close) {
5656
+ const idx = line.indexOf(close, from);
5657
+ return idx === -1 ? line.length : idx + close.length;
5658
+ }
5659
+
5172
5660
  // An expression without the positions and spellings that formatting changes
5173
5661
  const shape = (exp) => JSON.stringify(exp, (key, value) => key === 'loc' || key === 'raw' ? undefined : (value ?? null));
5174
5662
  /**
5175
- * Normalise the tags of a template:
5663
+ * Format a template:
5664
+ *
5665
+ * 1. Normalise spacing inside tags:
5176
5666
  *
5177
- * {{=name|upper}} -> {{= name | upper }}
5178
- * {{if a eq 1}} -> {{ if a eq 1 }}
5179
- * {{#note#}} -> {{# note #}}
5667
+ * {{=name|upper}} -> {{= name | upper }}
5668
+ * {{if a eq 1}} -> {{ if a eq 1 }}
5669
+ * {{#note#}} -> {{# note #}}
5180
5670
  *
5181
- * Only what is inside tags changes. Text between tags, where whitespace may
5182
- * matter, is kept byte for byte, as are whitespace-control markers. A tag is
5183
- * left exactly as written whenever its expression does not parse or
5671
+ * 2. Unless `html: false`, reindent HTML elements and block directives
5672
+ * (`if` / `for` / …). Only leading whitespace on each line changes;
5673
+ * attribute values (including embedded tags) and whitespace-sensitive
5674
+ * elements (`pre`, `script`, …) are left alone.
5675
+ *
5676
+ * A tag is left exactly as written whenever its expression does not parse or
5184
5677
  * reformatting would not provably keep its meaning. Formatting twice gives
5185
5678
  * the same result as formatting once.
5186
5679
  *
@@ -5237,7 +5730,7 @@ function formatTemplate(template, options = {}) {
5237
5730
  return (formatted !== null &&
5238
5731
  `${merged.directiveOpen}${before} ${name}${formatted && ` ${formatted}`} ${after}${merged.directiveClose}`);
5239
5732
  };
5240
- return tokens
5733
+ const tagged = tokens
5241
5734
  .map((token) => {
5242
5735
  const source = template.slice(offset(token.loc.start), offset(token.loc.end));
5243
5736
  if (token.type === TokenType.TEXT) {
@@ -5250,6 +5743,18 @@ function formatTemplate(template, options = {}) {
5250
5743
  return formatTag(token) || source;
5251
5744
  })
5252
5745
  .join('');
5746
+ if (options.html === false) {
5747
+ return tagged;
5748
+ }
5749
+ return indentHtml(tagged, {
5750
+ tabWidth: options.tabWidth,
5751
+ commentOpen: merged.commentOpen,
5752
+ commentClose: merged.commentClose,
5753
+ directiveOpen: merged.directiveOpen,
5754
+ directiveClose: merged.directiveClose,
5755
+ outputOpen: merged.outputOpen,
5756
+ outputClose: merged.outputClose,
5757
+ });
5253
5758
  }
5254
5759
 
5255
5760
  /**
@@ -5472,4 +5977,4 @@ function renderStream(template, data = {}, options) {
5472
5977
  return getRenderer(options).renderStream(template, data);
5473
5978
  }
5474
5979
 
5475
- export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MAX_INCLUDE_DEPTH, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
5980
+ export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MAX_INCLUDE_DEPTH, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, SecurityAuditor, SecuritySandbox, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, deepEscape, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, resolveSecurityLimits, templateCacheKey, validateTemplate };