janja 4.3.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -334,6 +334,224 @@ class CompileError extends SyntaxError {
334
334
  }
335
335
  }
336
336
 
337
+ const special = /[&<>"']/;
338
+ const specials = /[&<>"']/g;
339
+ const entities = {
340
+ '&': '&amp;',
341
+ '"': '&#34;',
342
+ "'": '&#39;',
343
+ '<': '&lt;',
344
+ '>': '&gt;',
345
+ };
346
+ const entity = (char) => entities[char];
347
+ function escape(v) {
348
+ const str = typeof v === 'string' ? v : `${v}`;
349
+ // Most values contain nothing to escape; they are returned as they are,
350
+ // without allocating
351
+ return special.test(str) ? str.replace(specials, entity) : str;
352
+ }
353
+
354
+ class Safe extends String {
355
+ constructor(value) {
356
+ super(`${value}`);
357
+ }
358
+ }
359
+
360
+ /** Defaults and resolved limits used by the compiler and renderer. */
361
+ function resolveSecurityLimits(security = {}) {
362
+ return {
363
+ maxIncludeDepth: security.maxIncludeDepth ?? 100,
364
+ maxLoopIterations: security.maxLoopIterations,
365
+ maxCallDepth: security.maxCallDepth,
366
+ timeoutMs: security.timeoutMs,
367
+ };
368
+ }
369
+ class SecuritySandbox {
370
+ constructor(options = {}) {
371
+ Object.defineProperty(this, "allowedGlobals", {
372
+ enumerable: true,
373
+ configurable: true,
374
+ writable: true,
375
+ value: void 0
376
+ });
377
+ Object.defineProperty(this, "cspNonce", {
378
+ enumerable: true,
379
+ configurable: true,
380
+ writable: true,
381
+ value: void 0
382
+ });
383
+ this.allowedGlobals = new Set(options.allowedGlobals || []);
384
+ this.cspNonce = options.cspNonce;
385
+ }
386
+ sanitizeGlobals(globals) {
387
+ const sanitized = {};
388
+ for (const [key, value] of Object.entries(globals)) {
389
+ if (this.allowedGlobals.has(key)) {
390
+ sanitized[key] = value;
391
+ }
392
+ }
393
+ return sanitized;
394
+ }
395
+ validateExpression(expression) {
396
+ // Prevent access to dangerous globals
397
+ const dangerousPatterns = [
398
+ /\bprocess\b/,
399
+ /\brequire\b/,
400
+ /\bimport\b/,
401
+ /\bexport\b/,
402
+ /\beval\b/,
403
+ /\bFunction\b/,
404
+ /\b__proto__\b/,
405
+ /\bconstructor\b/,
406
+ ];
407
+ for (const pattern of dangerousPatterns) {
408
+ if (pattern.test(expression)) {
409
+ return false;
410
+ }
411
+ }
412
+ return true;
413
+ }
414
+ createSecureContext(globals) {
415
+ const sanitized = this.sanitizeGlobals(globals);
416
+ // Add safe utility functions
417
+ return {
418
+ ...sanitized,
419
+ Math,
420
+ Date,
421
+ JSON,
422
+ // Add other safe built-ins as needed
423
+ };
424
+ }
425
+ getCSPNonce() {
426
+ return this.cspNonce;
427
+ }
428
+ generateCSPHeaders() {
429
+ const headers = {};
430
+ if (this.cspNonce) {
431
+ headers['Content-Security-Policy'] =
432
+ `script-src 'nonce-${this.cspNonce}'`;
433
+ }
434
+ return headers;
435
+ }
436
+ }
437
+ function deepEscape(value, seen = new WeakSet()) {
438
+ if (value === null || value === undefined) {
439
+ return '';
440
+ }
441
+ if (value instanceof Safe) {
442
+ return `${value}`;
443
+ }
444
+ if (typeof value === 'object') {
445
+ // Guard against circular references
446
+ if (seen.has(value)) {
447
+ return '';
448
+ }
449
+ seen.add(value);
450
+ const values = Array.isArray(value)
451
+ ? value
452
+ : Object.values(value);
453
+ return values.map((v) => deepEscape(v, seen)).join('');
454
+ }
455
+ return escape(value);
456
+ }
457
+ class SecurityAuditor {
458
+ auditTemplate(template) {
459
+ const issues = [];
460
+ // Check for dangerous patterns
461
+ const dangerousPatterns = [
462
+ {
463
+ pattern: /\beval\s*\(/,
464
+ type: 'dangerous-eval',
465
+ message: 'Use of eval() is dangerous and should be avoided',
466
+ severity: 'critical',
467
+ },
468
+ {
469
+ pattern: /\bFunction\s*\(/,
470
+ type: 'dangerous-function',
471
+ message: 'Use of Function constructor is dangerous',
472
+ severity: 'critical',
473
+ },
474
+ {
475
+ pattern: /\brequire\s*\(/,
476
+ type: 'require-usage',
477
+ message: 'Direct require() usage in templates is unsafe',
478
+ severity: 'high',
479
+ },
480
+ {
481
+ pattern: /\bimport\s*\(/,
482
+ type: 'dynamic-import',
483
+ message: 'Dynamic import() usage in templates may be unsafe',
484
+ severity: 'high',
485
+ },
486
+ ];
487
+ for (const { pattern, type, message, severity } of dangerousPatterns) {
488
+ const match = template.match(pattern);
489
+ if (match) {
490
+ issues.push({
491
+ type,
492
+ message,
493
+ location: `at index ${match.index}`,
494
+ severity,
495
+ });
496
+ }
497
+ }
498
+ // Calculate overall severity
499
+ const overallSeverity = this.calculateOverallSeverity(issues);
500
+ return {
501
+ issues,
502
+ severity: overallSeverity,
503
+ };
504
+ }
505
+ calculateOverallSeverity(issues) {
506
+ if (issues.length === 0) {
507
+ return 'low';
508
+ }
509
+ const severityMap = {
510
+ critical: 4,
511
+ high: 3,
512
+ medium: 2,
513
+ low: 1,
514
+ };
515
+ const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
516
+ return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
517
+ }
518
+ }
519
+
520
+ const fingerprints = new WeakMap();
521
+ // How deep includes may nest while rendering. Only templates that include
522
+ // themselves get anywhere near it; the limit turns a cycle that never ends
523
+ // into an error instead of a stack overflow.
524
+ const MAX_INCLUDE_DEPTH = 100;
525
+ // The template itself is the key: one string that is hashed once, and two
526
+ // different templates can never share an entry
527
+ function templateCacheKey(template, stream = false) {
528
+ return stream ? `\0stream:${template}` : template;
529
+ }
530
+ function optionsFingerprint(options) {
531
+ let fingerprint = fingerprints.get(options);
532
+ if (fingerprint === undefined) {
533
+ const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, preloadIncludes, } = options;
534
+ // Limits that change the generated code must bust the compile cache
535
+ const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
536
+ fingerprint = JSON.stringify([
537
+ trimWhitespace,
538
+ stripComments,
539
+ commentOpen,
540
+ commentClose,
541
+ directiveOpen,
542
+ directiveClose,
543
+ outputOpen,
544
+ outputClose,
545
+ maxIncludeDepth,
546
+ maxLoopIterations ?? null,
547
+ maxCallDepth ?? null,
548
+ preloadIncludes,
549
+ ]);
550
+ fingerprints.set(options, fingerprint);
551
+ }
552
+ return fingerprint;
553
+ }
554
+
337
555
  const CONTEXT = 'c';
338
556
  const ESCAPE = 'e';
339
557
  const FILTERS = 'f';
@@ -1575,241 +1793,74 @@ class Parser extends Tokenizer {
1575
1793
  : error);
1576
1794
  }
1577
1795
  }
1578
- peek() {
1579
- return this.tokens.at(this.cursor) ?? null;
1580
- }
1581
- advance() {
1582
- this.cursor++;
1583
- }
1584
- match(names, token = this.peek()) {
1585
- // Directive names are case-insensitive, like the lookup of their parser
1586
- return names.includes(token?.name?.toLowerCase());
1587
- }
1588
- emitExpErr({ name, loc }, required = true) {
1589
- this.options.debug(new CompileError(required
1590
- ? `"${name}" requires expression`
1591
- : `"${name}" should not have expression`, this.template, loc));
1592
- }
1593
- }
1594
-
1595
- const special = /[&<>"']/;
1596
- const specials = /[&<>"']/g;
1597
- const entities = {
1598
- '&': '&amp;',
1599
- '"': '&#34;',
1600
- "'": '&#39;',
1601
- '<': '&lt;',
1602
- '>': '&gt;',
1603
- };
1604
- const entity = (char) => entities[char];
1605
- function escape(v) {
1606
- const str = typeof v === 'string' ? v : `${v}`;
1607
- // Most values contain nothing to escape; they are returned as they are,
1608
- // without allocating
1609
- return special.test(str) ? str.replace(specials, entity) : str;
1610
- }
1611
-
1612
- class Safe extends String {
1613
- constructor(value) {
1614
- super(`${value}`);
1615
- }
1616
- }
1617
-
1618
- /** Defaults and resolved limits used by the compiler and renderer. */
1619
- function resolveSecurityLimits(security = {}) {
1620
- return {
1621
- maxIncludeDepth: security.maxIncludeDepth ?? 100,
1622
- maxLoopIterations: security.maxLoopIterations,
1623
- maxCallDepth: security.maxCallDepth,
1624
- timeoutMs: security.timeoutMs,
1625
- };
1626
- }
1627
- class SecuritySandbox {
1628
- constructor(options = {}) {
1629
- Object.defineProperty(this, "allowedGlobals", {
1630
- enumerable: true,
1631
- configurable: true,
1632
- writable: true,
1633
- value: void 0
1634
- });
1635
- Object.defineProperty(this, "cspNonce", {
1636
- enumerable: true,
1637
- configurable: true,
1638
- writable: true,
1639
- value: void 0
1640
- });
1641
- this.allowedGlobals = new Set(options.allowedGlobals || []);
1642
- this.cspNonce = options.cspNonce;
1643
- }
1644
- sanitizeGlobals(globals) {
1645
- const sanitized = {};
1646
- for (const [key, value] of Object.entries(globals)) {
1647
- if (this.allowedGlobals.has(key)) {
1648
- sanitized[key] = value;
1649
- }
1650
- }
1651
- return sanitized;
1652
- }
1653
- validateExpression(expression) {
1654
- // Prevent access to dangerous globals
1655
- const dangerousPatterns = [
1656
- /\bprocess\b/,
1657
- /\brequire\b/,
1658
- /\bimport\b/,
1659
- /\bexport\b/,
1660
- /\beval\b/,
1661
- /\bFunction\b/,
1662
- /\b__proto__\b/,
1663
- /\bconstructor\b/,
1664
- ];
1665
- for (const pattern of dangerousPatterns) {
1666
- if (pattern.test(expression)) {
1667
- return false;
1668
- }
1669
- }
1670
- return true;
1671
- }
1672
- createSecureContext(globals) {
1673
- const sanitized = this.sanitizeGlobals(globals);
1674
- // Add safe utility functions
1675
- return {
1676
- ...sanitized,
1677
- Math,
1678
- Date,
1679
- JSON,
1680
- // Add other safe built-ins as needed
1681
- };
1682
- }
1683
- getCSPNonce() {
1684
- return this.cspNonce;
1685
- }
1686
- generateCSPHeaders() {
1687
- const headers = {};
1688
- if (this.cspNonce) {
1689
- headers['Content-Security-Policy'] =
1690
- `script-src 'nonce-${this.cspNonce}'`;
1691
- }
1692
- return headers;
1693
- }
1694
- }
1695
- function deepEscape(value, seen = new WeakSet()) {
1696
- if (value === null || value === undefined) {
1697
- return '';
1698
- }
1699
- if (value instanceof Safe) {
1700
- return `${value}`;
1701
- }
1702
- if (typeof value === 'object') {
1703
- // Guard against circular references
1704
- if (seen.has(value)) {
1705
- return '';
1706
- }
1707
- seen.add(value);
1708
- const values = Array.isArray(value)
1709
- ? value
1710
- : Object.values(value);
1711
- return values.map((v) => deepEscape(v, seen)).join('');
1712
- }
1713
- return escape(value);
1714
- }
1715
- class SecurityAuditor {
1716
- auditTemplate(template) {
1717
- const issues = [];
1718
- // Check for dangerous patterns
1719
- const dangerousPatterns = [
1720
- {
1721
- pattern: /\beval\s*\(/,
1722
- type: 'dangerous-eval',
1723
- message: 'Use of eval() is dangerous and should be avoided',
1724
- severity: 'critical',
1725
- },
1726
- {
1727
- pattern: /\bFunction\s*\(/,
1728
- type: 'dangerous-function',
1729
- message: 'Use of Function constructor is dangerous',
1730
- severity: 'critical',
1731
- },
1732
- {
1733
- pattern: /\brequire\s*\(/,
1734
- type: 'require-usage',
1735
- message: 'Direct require() usage in templates is unsafe',
1736
- severity: 'high',
1737
- },
1738
- {
1739
- pattern: /\bimport\s*\(/,
1740
- type: 'dynamic-import',
1741
- message: 'Dynamic import() usage in templates may be unsafe',
1742
- severity: 'high',
1743
- },
1744
- ];
1745
- for (const { pattern, type, message, severity } of dangerousPatterns) {
1746
- const match = template.match(pattern);
1747
- if (match) {
1748
- issues.push({
1749
- type,
1750
- message,
1751
- location: `at index ${match.index}`,
1752
- severity,
1753
- });
1754
- }
1755
- }
1756
- // Calculate overall severity
1757
- const overallSeverity = this.calculateOverallSeverity(issues);
1758
- return {
1759
- issues,
1760
- severity: overallSeverity,
1761
- };
1762
- }
1763
- calculateOverallSeverity(issues) {
1764
- if (issues.length === 0) {
1765
- return 'low';
1766
- }
1767
- const severityMap = {
1768
- critical: 4,
1769
- high: 3,
1770
- medium: 2,
1771
- low: 1,
1772
- };
1773
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1774
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
1775
- }
1796
+ peek() {
1797
+ return this.tokens.at(this.cursor) ?? null;
1798
+ }
1799
+ advance() {
1800
+ this.cursor++;
1801
+ }
1802
+ match(names, token = this.peek()) {
1803
+ // Directive names are case-insensitive, like the lookup of their parser
1804
+ return names.includes(token?.name?.toLowerCase());
1805
+ }
1806
+ emitExpErr({ name, loc }, required = true) {
1807
+ this.options.debug(new CompileError(required
1808
+ ? `"${name}" requires expression`
1809
+ : `"${name}" should not have expression`, this.template, loc));
1810
+ }
1776
1811
  }
1777
1812
 
1778
- const fingerprints = new WeakMap();
1779
- // How deep includes may nest while rendering. Only templates that include
1780
- // themselves get anywhere near it; the limit turns a cycle that never ends
1781
- // into an error instead of a stack overflow.
1782
- const MAX_INCLUDE_DEPTH = 100;
1783
- // Directives whose body is still the template's own top-level output
1784
- const transparent = new Set(['IF', 'FOR']);
1785
- // The template itself is the key: one string that is hashed once, and two
1786
- // different templates can never share an entry
1787
- function templateCacheKey(template, stream = false) {
1788
- return stream ? `\0stream:${template}` : template;
1813
+ function isStringLit(exp) {
1814
+ return exp.type === 'LIT' && typeof exp.value === 'string';
1789
1815
  }
1790
- function optionsFingerprint(options) {
1791
- let fingerprint = fingerprints.get(options);
1792
- if (fingerprint === undefined) {
1793
- const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1794
- // Limits that change the generated code must bust the compile cache
1795
- const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1796
- fingerprint = JSON.stringify([
1797
- trimWhitespace,
1798
- stripComments,
1799
- commentOpen,
1800
- commentClose,
1801
- directiveOpen,
1802
- directiveClose,
1803
- outputOpen,
1804
- outputClose,
1805
- maxIncludeDepth,
1806
- maxLoopIterations ?? null,
1807
- maxCallDepth ?? null,
1808
- ]);
1809
- fingerprints.set(options, fingerprint);
1816
+ class IncludeNode extends Traversal {
1817
+ constructor(val, loc, strip, withExp = null, modifier = null) {
1818
+ super();
1819
+ Object.defineProperty(this, "val", {
1820
+ enumerable: true,
1821
+ configurable: true,
1822
+ writable: true,
1823
+ value: val
1824
+ });
1825
+ Object.defineProperty(this, "loc", {
1826
+ enumerable: true,
1827
+ configurable: true,
1828
+ writable: true,
1829
+ value: loc
1830
+ });
1831
+ Object.defineProperty(this, "strip", {
1832
+ enumerable: true,
1833
+ configurable: true,
1834
+ writable: true,
1835
+ value: strip
1836
+ });
1837
+ Object.defineProperty(this, "withExp", {
1838
+ enumerable: true,
1839
+ configurable: true,
1840
+ writable: true,
1841
+ value: withExp
1842
+ });
1843
+ Object.defineProperty(this, "modifier", {
1844
+ enumerable: true,
1845
+ configurable: true,
1846
+ writable: true,
1847
+ value: modifier
1848
+ });
1849
+ Object.defineProperty(this, "type", {
1850
+ enumerable: true,
1851
+ configurable: true,
1852
+ writable: true,
1853
+ value: 'INCLUDE'
1854
+ });
1810
1855
  }
1811
- return fingerprint;
1812
1856
  }
1857
+
1858
+ const PRELOAD_LOC = {
1859
+ start: { line: 1, column: 1 },
1860
+ end: { line: 1, column: 1 },
1861
+ };
1862
+ // Directives whose body is still the template's own top-level output
1863
+ const transparent = new Set(['IF', 'FOR']);
1813
1864
  class Compiler extends Context {
1814
1865
  constructor(options, cache, revalidate = true, stream = false) {
1815
1866
  super();
@@ -1899,6 +1950,13 @@ class Compiler extends Context {
1899
1950
  writable: true,
1900
1951
  value: void 0
1901
1952
  });
1953
+ /** True when the template uses a non-literal include path. */
1954
+ Object.defineProperty(this, "hasDynamicInclude", {
1955
+ enumerable: true,
1956
+ configurable: true,
1957
+ writable: true,
1958
+ value: false
1959
+ });
1902
1960
  /**
1903
1961
  * Whether the code being generated may write output to the stream. True
1904
1962
  * only in stream mode, for the template's own top-level output.
@@ -1919,6 +1977,7 @@ class Compiler extends Context {
1919
1977
  this.stylesheets = stylesheets;
1920
1978
  this.stylesheetKey = stylesheetKey;
1921
1979
  this.sources = sources;
1980
+ this.hasDynamicInclude = false;
1922
1981
  // Generate cache key from template and options
1923
1982
  const cacheKey = this.generateCacheKey(template);
1924
1983
  // Check cache first
@@ -1944,10 +2003,12 @@ class Compiler extends Context {
1944
2003
  }
1945
2004
  await this.parseTemplates();
1946
2005
  if (this.isRoot) {
1947
- if (this.partials.size) {
2006
+ if (this.partials.size || this.hasDynamicInclude) {
1948
2007
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1949
2008
  // Alias the render data before partials shadow `c` with their argument.
1950
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
2009
+ // `inc_` tracks `include … once` occurrences across the whole render,
2010
+ // root template and partials alike (they share this closure).
2011
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
1951
2012
  for (const [path, code] of this.partials) {
1952
2013
  this.pushRaw(null,
1953
2014
  // Partials take the context they should render with: plain include
@@ -2042,6 +2103,17 @@ class Compiler extends Context {
2042
2103
  }
2043
2104
  async parseTemplates() {
2044
2105
  const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
2106
+ if (this.isRoot) {
2107
+ for (const path of this.options.preloadIncludes) {
2108
+ if (!partials.has(path)) {
2109
+ partials.set(path, new IncludeNode({
2110
+ type: 'LIT',
2111
+ value: path,
2112
+ loc: PRELOAD_LOC,
2113
+ }, PRELOAD_LOC, { before: false, after: false }));
2114
+ }
2115
+ }
2116
+ }
2045
2117
  for (const [path, node] of partials) {
2046
2118
  if (!this.partials.has(path)) {
2047
2119
  let template;
@@ -2077,10 +2149,26 @@ class Compiler extends Context {
2077
2149
  const partials = new Map();
2078
2150
  const blocks = [];
2079
2151
  const stylesheets = [];
2152
+ const includeLast = new Map();
2080
2153
  const traverse = (node) => {
2081
2154
  if (node.type === 'INCLUDE') {
2082
- if (!partials.has(node.val.value)) {
2083
- partials.set(node.val.value, node);
2155
+ const include = node;
2156
+ if (isStringLit(include.val)) {
2157
+ if (!partials.has(include.val.value)) {
2158
+ partials.set(include.val.value, include);
2159
+ }
2160
+ if (include.modifier === 'last') {
2161
+ const existing = includeLast.get(include.val.value);
2162
+ if (existing) {
2163
+ existing.total += 1;
2164
+ }
2165
+ else {
2166
+ includeLast.set(include.val.value, { total: 1, emitted: 0 });
2167
+ }
2168
+ }
2169
+ }
2170
+ else {
2171
+ this.hasDynamicInclude = true;
2084
2172
  }
2085
2173
  }
2086
2174
  if (node.type === 'BLOCK') {
@@ -2092,6 +2180,7 @@ class Compiler extends Context {
2092
2180
  node.traverse(traverse);
2093
2181
  };
2094
2182
  traverse(this.rootNode);
2183
+ this.state.includeLast = includeLast;
2095
2184
  return {
2096
2185
  partials,
2097
2186
  blocks,
@@ -2491,6 +2580,7 @@ const compilerOptions = {
2491
2580
  trimWhitespace: false,
2492
2581
  stripComments: false,
2493
2582
  loader: async () => '',
2583
+ preloadIncludes: [],
2494
2584
  };
2495
2585
  const renderOptions = {
2496
2586
  ...compilerOptions,
@@ -3555,82 +3645,71 @@ const plugin$9 = {
3555
3645
  parsers: parsers$9,
3556
3646
  };
3557
3647
 
3558
- async function compileInclude({ val: { value }, loc, withExp }, compiler) {
3559
- const path = JSON.stringify(value);
3560
- if (withExp) {
3561
- const expCompiler = new ExpCompiler();
3562
- const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3563
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3648
+ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3649
+ const expCompiler = new ExpCompiler();
3650
+ const path = isStringLit(val)
3651
+ ? JSON.stringify(val.value)
3652
+ : expCompiler.compile(val, compiler.context);
3653
+ // Emit the partial call, against the top context for a plain include or a
3654
+ // merged scope for `include … with`.
3655
+ const emit = withExp
3656
+ ? `s+=await p[${path}]?.({...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}})??"";`
3657
+ : `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`;
3658
+ // `once`: render the first occurrence only. The registry lives in the root
3659
+ // script's closure, so occurrences spread across different files (a root
3660
+ // template and its partials) still deduplicate at runtime.
3661
+ if (modifier === 'once') {
3662
+ compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3564
3663
  return;
3565
3664
  }
3566
- // Plain include always sees the top-level context, not loop/with scopes.
3567
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`);
3665
+ // `last`: emit only at the final occurrence within the template file,
3666
+ // determined at compile time from the counts collected alongside partials.
3667
+ // Static string paths only — a dynamic path has no stable identity to count.
3668
+ if (modifier === 'last' && isStringLit(val)) {
3669
+ const counts = compiler.state.includeLast;
3670
+ const entry = counts?.get(val.value);
3671
+ if (entry) {
3672
+ entry.emitted += 1;
3673
+ if (entry.emitted < entry.total) {
3674
+ // Not the last occurrence — emit nothing.
3675
+ return;
3676
+ }
3677
+ }
3678
+ }
3679
+ compiler.pushRaw(loc, emit);
3568
3680
  }
3569
3681
  const compilers$8 = {
3570
3682
  INCLUDE: compileInclude,
3571
3683
  };
3572
3684
 
3573
- class IncludeNode extends Traversal {
3574
- constructor(val, loc, strip, withExp = null) {
3575
- super();
3576
- Object.defineProperty(this, "val", {
3577
- enumerable: true,
3578
- configurable: true,
3579
- writable: true,
3580
- value: val
3581
- });
3582
- Object.defineProperty(this, "loc", {
3583
- enumerable: true,
3584
- configurable: true,
3585
- writable: true,
3586
- value: loc
3587
- });
3588
- Object.defineProperty(this, "strip", {
3589
- enumerable: true,
3590
- configurable: true,
3591
- writable: true,
3592
- value: strip
3593
- });
3594
- Object.defineProperty(this, "withExp", {
3595
- enumerable: true,
3596
- configurable: true,
3597
- writable: true,
3598
- value: withExp
3599
- });
3600
- Object.defineProperty(this, "type", {
3601
- enumerable: true,
3602
- configurable: true,
3603
- writable: true,
3604
- value: 'INCLUDE'
3605
- });
3606
- }
3607
- }
3608
-
3609
- function isStringLit(exp) {
3610
- return exp.type === 'LIT' && typeof exp.value === 'string';
3611
- }
3685
+ // Modifier keywords that may appear after the path expression.
3686
+ // e.g. `{{ include "foo" once }}` or `{{ include "foo" last }}`
3687
+ const MODIFIER_RE = /\s+(once|last)\s*$/;
3612
3688
  function* parseInclude(token, parser) {
3613
3689
  if (!token.expression) {
3614
3690
  parser.emitExpErr(token);
3615
3691
  return;
3616
3692
  }
3617
3693
  yield 'NEXT';
3618
- const exp = parser.parseExp(token.expression);
3694
+ // Strip a trailing `once` or `last` keyword before parsing the expression,
3695
+ // so the expression parser does not trip over an unknown identifier.
3696
+ let rawVal = token.expression.val;
3697
+ let modifier = null;
3698
+ const modifierMatch = MODIFIER_RE.exec(rawVal);
3699
+ if (modifierMatch) {
3700
+ modifier = modifierMatch[1];
3701
+ rawVal = rawVal.slice(0, modifierMatch.index);
3702
+ }
3703
+ const exp = parser.parseExp({ val: rawVal, loc: token.expression.loc });
3619
3704
  if (!exp) {
3620
3705
  return;
3621
3706
  }
3622
- if (isStringLit(exp)) {
3623
- yield new IncludeNode(exp, token.loc, token.strip);
3624
- return;
3625
- }
3626
3707
  if (exp.type === 'WITH') {
3627
3708
  const { left, right } = exp;
3628
- if (isStringLit(left)) {
3629
- yield new IncludeNode(left, token.loc, token.strip, right);
3630
- return;
3631
- }
3709
+ yield new IncludeNode(left, token.loc, token.strip, right, modifier);
3710
+ return;
3632
3711
  }
3633
- parser.options.debug?.(new CompileError('"include" expects "path" or "path" with expr', parser.template, token.loc));
3712
+ yield new IncludeNode(exp, token.loc, token.strip, null, modifier);
3634
3713
  }
3635
3714
  const parsers$8 = {
3636
3715
  include: parseInclude,
@@ -3911,14 +3990,18 @@ async function compileStylesheet() {
3911
3990
  async function compileStylesheets({ loc }, compiler) {
3912
3991
  compiler.pushRaw(loc,
3913
3992
  // First `stylesheets` wins; later ones are ignored (same idea as blocks).
3914
- 'if(!ss_u++){', 's+="<style>";', 'for(const f_ of ss_)s+=await f_();', 's+="</style>";', '}');
3993
+ // Bodies are emitted as-is — authors wrap CSS in `<style>` for IDE highlighting.
3994
+ 'if(!ss_u++){', 'for(const f_ of ss_)s+=await f_();', '}');
3915
3995
  }
3916
3996
  const compilers$4 = {
3917
3997
  STYLESHEET: compileStylesheet,
3918
3998
  STYLESHEETS: compileStylesheets,
3919
3999
  };
3920
4000
 
3921
- /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
4001
+ /**
4002
+ * Co-located styles with a section/snippet (Shopify `{% stylesheet %}` analogue).
4003
+ * Body is usually a `<style>…</style>` block for native IDE CSS highlighting.
4004
+ */
3922
4005
  class StylesheetNode extends Traversal {
3923
4006
  constructor(body, loc, strip) {
3924
4007
  super();
@@ -3948,7 +4031,7 @@ class StylesheetNode extends Traversal {
3948
4031
  });
3949
4032
  }
3950
4033
  }
3951
- /** Emits every collected stylesheet into the document (typically in `<head>`). */
4034
+ /** Concatenates collected stylesheet bodies into the document (typically in `<head>`). */
3952
4035
  class StylesheetsNode extends Traversal {
3953
4036
  constructor(loc, strip) {
3954
4037
  super();
@@ -4666,10 +4749,13 @@ class Analyzer {
4666
4749
  await this.nodes(node.body, scope);
4667
4750
  break;
4668
4751
  case 'INCLUDE':
4752
+ this.exp(node.val, scope);
4669
4753
  if (node.withExp) {
4670
4754
  this.exp(node.withExp, scope);
4671
4755
  }
4672
- await this.include(node.val.value, scope);
4756
+ if (node.val.type === 'LIT' && typeof node.val.value === 'string') {
4757
+ await this.include(node.val.value, scope);
4758
+ }
4673
4759
  break;
4674
4760
  default:
4675
4761
  await this.nodes(node.body, scope);
@@ -5434,6 +5520,149 @@ class ExpFormatter {
5434
5520
  }
5435
5521
  }
5436
5522
 
5523
+ /**
5524
+ * Brace-depth reindent for co-located CSS. Only leading whitespace changes;
5525
+ * braces inside strings/comments are ignored.
5526
+ */
5527
+ function indentCss(source, tabWidth) {
5528
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5529
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5530
+ const lines = source.split(/\r?\n/);
5531
+ let depth = 0;
5532
+ const out = [];
5533
+ for (const line of lines) {
5534
+ const content = line.trim();
5535
+ if (content.length === 0) {
5536
+ out.push('');
5537
+ continue;
5538
+ }
5539
+ const { opens, closes } = countCssBraces(content);
5540
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5541
+ out.push(pad.repeat(lineDepth) + content);
5542
+ depth = Math.max(0, depth + opens - closes);
5543
+ }
5544
+ return out.join(eol);
5545
+ }
5546
+ function countCssBraces(line) {
5547
+ let opens = 0;
5548
+ let closes = 0;
5549
+ let quote = null;
5550
+ let i = 0;
5551
+ while (i < line.length) {
5552
+ const c = line[i];
5553
+ if (quote) {
5554
+ if (c === '\\') {
5555
+ i += 2;
5556
+ continue;
5557
+ }
5558
+ if (c === quote) {
5559
+ quote = null;
5560
+ }
5561
+ i += 1;
5562
+ continue;
5563
+ }
5564
+ if (c === '"' || c === "'") {
5565
+ quote = c;
5566
+ i += 1;
5567
+ continue;
5568
+ }
5569
+ if (c === '/' && line[i + 1] === '*') {
5570
+ const end = line.indexOf('*/', i + 2);
5571
+ i = end === -1 ? line.length : end + 2;
5572
+ continue;
5573
+ }
5574
+ if (c === '/' && line[i + 1] === '/') {
5575
+ break;
5576
+ }
5577
+ if (c === '{') {
5578
+ opens += 1;
5579
+ }
5580
+ else if (c === '}') {
5581
+ closes += 1;
5582
+ }
5583
+ i += 1;
5584
+ }
5585
+ return { opens, closes };
5586
+ }
5587
+
5588
+ /**
5589
+ * Brace-depth reindent for `<script>` bodies. Only leading whitespace changes;
5590
+ * braces inside strings, comments, template literals, and Janja tags are ignored.
5591
+ */
5592
+ function indentJs(source, tabWidth) {
5593
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5594
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5595
+ const lines = source.split(/\r?\n/);
5596
+ let depth = 0;
5597
+ const out = [];
5598
+ for (const line of lines) {
5599
+ const content = line.trim();
5600
+ if (content.length === 0) {
5601
+ out.push('');
5602
+ continue;
5603
+ }
5604
+ const { opens, closes } = countJsBraces(content);
5605
+ const lineDepth = closes > opens ? Math.max(0, depth - (closes - opens)) : depth;
5606
+ out.push(pad.repeat(lineDepth) + content);
5607
+ depth = Math.max(0, depth + opens - closes);
5608
+ }
5609
+ return out.join(eol);
5610
+ }
5611
+ function countJsBraces(line) {
5612
+ let opens = 0;
5613
+ let closes = 0;
5614
+ let quote = null;
5615
+ let i = 0;
5616
+ while (i < line.length) {
5617
+ const c = line[i];
5618
+ if (quote) {
5619
+ if (c === '\\') {
5620
+ i += 2;
5621
+ continue;
5622
+ }
5623
+ if (c === quote) {
5624
+ quote = null;
5625
+ }
5626
+ i += 1;
5627
+ continue;
5628
+ }
5629
+ if (c === '{' && line[i + 1] === '{') {
5630
+ i = endOfJanja(line, i);
5631
+ continue;
5632
+ }
5633
+ if (c === '"' || c === "'" || c === '`') {
5634
+ quote = c;
5635
+ i += 1;
5636
+ continue;
5637
+ }
5638
+ if (c === '/' && line[i + 1] === '*') {
5639
+ const end = line.indexOf('*/', i + 2);
5640
+ i = end === -1 ? line.length : end + 2;
5641
+ continue;
5642
+ }
5643
+ if (c === '/' && line[i + 1] === '/') {
5644
+ break;
5645
+ }
5646
+ if (c === '{') {
5647
+ opens += 1;
5648
+ }
5649
+ else if (c === '}') {
5650
+ closes += 1;
5651
+ }
5652
+ i += 1;
5653
+ }
5654
+ return { opens, closes };
5655
+ }
5656
+ /** Skip a Janja tag starting at `i` (`{{`, `{{=`, `{{#` …). */
5657
+ function endOfJanja(line, i) {
5658
+ if (line.startsWith('{{#', i)) {
5659
+ const end = line.indexOf('#}}', i + 3);
5660
+ return end === -1 ? line.length : end + 3;
5661
+ }
5662
+ const end = line.indexOf('}}', i + 2);
5663
+ return end === -1 ? line.length : end + 2;
5664
+ }
5665
+
5437
5666
  /** HTML void elements — never take children, so they do not change indent. */
5438
5667
  const VOID = new Set([
5439
5668
  'area',
@@ -5451,8 +5680,13 @@ const VOID = new Set([
5451
5680
  'track',
5452
5681
  'wbr',
5453
5682
  ]);
5454
- /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5683
+ /**
5684
+ * Mark open/close so the body can be buffered. `pre` / `textarea` keep
5685
+ * whitespace; `script` / `style` are reindented (see body buffer below).
5686
+ */
5455
5687
  const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5688
+ /** HTML elements whose bodies are reindented (not left raw). */
5689
+ const REINDENT_HTML = new Set(['script', 'style']);
5456
5690
  const DIR_OPEN = new Set([
5457
5691
  'if',
5458
5692
  'for',
@@ -5479,8 +5713,9 @@ const DIR_CLOSE = new Set([
5479
5713
  /**
5480
5714
  * Reindent a template that already had its Janja tags normalised.
5481
5715
  * Only leading whitespace on each line changes; line breaks and
5482
- * intra-line spacing stay put. Content inside pre/textarea/script/style
5483
- * is left alone; the closing tag of those elements is still reindented.
5716
+ * intra-line spacing stay put. Content inside pre/textarea is left alone;
5717
+ * `script` / `style` bodies are brace-reindented; `stylesheet` bodies are
5718
+ * formatted as an HTML fragment (so nested `<style>` gets CSS indent).
5484
5719
  */
5485
5720
  function indentHtml(source, options) {
5486
5721
  const tabWidth = options.tabWidth ?? 2;
@@ -5489,15 +5724,40 @@ function indentHtml(source, options) {
5489
5724
  const lines = source.split(/\r?\n/);
5490
5725
  let depth = 0;
5491
5726
  let sensitive = null;
5727
+ /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5728
+ let bodyBuf = null;
5492
5729
  const out = [];
5730
+ /** Open `{{#` comment: inner lines are never scanned for pieces. */
5731
+ const state = { inComment: false };
5493
5732
  for (const line of lines) {
5494
5733
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5495
5734
  const content = line.slice(leading);
5496
- const { pieces, prefixClosers } = scanLine(content, options);
5735
+ const { pieces, prefixClosers } = scanLine(content, options, state);
5497
5736
  const activeSensitive = sensitive;
5498
5737
  const closesSensitive = activeSensitive !== null &&
5499
5738
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5500
- if (sensitive && !closesSensitive) {
5739
+ const reindentBody = activeSensitive === 'stylesheet' ||
5740
+ (activeSensitive !== null && REINDENT_HTML.has(activeSensitive));
5741
+ if (reindentBody && !closesSensitive) {
5742
+ // Do not applyDepth: bodies may contain nested Janja if/for tags.
5743
+ (bodyBuf ?? (bodyBuf = [])).push(line);
5744
+ continue;
5745
+ }
5746
+ if (bodyBuf && closesSensitive && reindentBody) {
5747
+ // stylesheet: same column as the tags; script/style: one level inside.
5748
+ const baseDepth = activeSensitive === 'stylesheet' ? Math.max(0, depth - 1) : depth;
5749
+ const raw = bodyBuf.join(eol);
5750
+ const formatted = activeSensitive === 'stylesheet'
5751
+ ? indentHtml(raw, options)
5752
+ : activeSensitive === 'style'
5753
+ ? indentCss(raw, tabWidth)
5754
+ : indentJs(raw, tabWidth);
5755
+ for (const bodyLine of formatted.split(/\r?\n/)) {
5756
+ out.push(bodyLine.length === 0 ? '' : pad.repeat(baseDepth) + bodyLine);
5757
+ }
5758
+ bodyBuf = null;
5759
+ }
5760
+ else if (sensitive && !closesSensitive) {
5501
5761
  out.push(line);
5502
5762
  applyDepth(pieces);
5503
5763
  continue;
@@ -5528,16 +5788,35 @@ function indentHtml(source, options) {
5528
5788
  }
5529
5789
  }
5530
5790
  }
5531
- function scanLine(line, options) {
5791
+ function scanLine(line, options, state) {
5532
5792
  const pieces = [];
5533
5793
  let prefixClosers = 0;
5534
5794
  let atPrefix = true;
5535
5795
  let i = 0;
5796
+ if (state.inComment) {
5797
+ const close = line.indexOf(options.commentClose);
5798
+ if (close === -1) {
5799
+ return { pieces, prefixClosers };
5800
+ }
5801
+ state.inComment = false;
5802
+ i = close + options.commentClose.length;
5803
+ }
5536
5804
  while (i < line.length) {
5537
5805
  if (/\s/.test(line[i])) {
5538
5806
  i += 1;
5539
5807
  continue;
5540
5808
  }
5809
+ if (line.startsWith(options.commentOpen, i)) {
5810
+ const close = line.indexOf(options.commentClose, i + options.commentOpen.length);
5811
+ // Comment runs past this line; the rest is comment text
5812
+ if (close === -1) {
5813
+ state.inComment = true;
5814
+ return { pieces, prefixClosers };
5815
+ }
5816
+ atPrefix = false;
5817
+ i = close + options.commentClose.length;
5818
+ continue;
5819
+ }
5541
5820
  const next = readAt(line, i, options);
5542
5821
  if (!next) {
5543
5822
  // Plain text ends the leading-closer prefix
@@ -5564,12 +5843,7 @@ function scanLine(line, options) {
5564
5843
  return { pieces, prefixClosers };
5565
5844
  }
5566
5845
  function readAt(line, i, options) {
5567
- const { commentOpen, directiveOpen, outputOpen } = options;
5568
- if (line.startsWith(commentOpen, i)) {
5569
- return {
5570
- end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5571
- };
5572
- }
5846
+ const { directiveOpen, outputOpen } = options;
5573
5847
  if (line.startsWith(outputOpen, i)) {
5574
5848
  return {
5575
5849
  end: endOfDelimited(line, i + outputOpen.length, options.outputClose),