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