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