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