janja 4.0.0 → 4.1.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/README.md CHANGED
@@ -54,8 +54,10 @@ The documentation lives at **[janja.wenfu.dev](https://janja.wenfu.dev)**. The s
54
54
  - [Language specification](./SPEC.md) - Syntax and semantics, backed by a conformance suite
55
55
  - [Documentation](./documentation.md) - API, CLI and tooling
56
56
  - [Filters](./FILTERS.md) - Built-in filter reference
57
+ - [Migration](./MIGRATION.md) - From Nunjucks, Jinja2, Handlebars or EJS
57
58
  - [Security](./SECURITY.md) - What is protected, what is not, and how to report issues
58
59
  - [Performance](./PERFORMANCE.md) - Caching, pre-compilation and benchmarks
60
+ - [Contributing](./CONTRIBUTING.md) / [Code of Conduct](./CODE_OF_CONDUCT.md)
59
61
 
60
62
  ## Ecosystem
61
63
 
package/dist/index.cjs CHANGED
@@ -1579,6 +1579,189 @@ class Parser extends Tokenizer {
1579
1579
  }
1580
1580
  }
1581
1581
 
1582
+ const special = /[&<>"']/;
1583
+ const specials = /[&<>"']/g;
1584
+ const entities = {
1585
+ '&': '&amp;',
1586
+ '"': '&#34;',
1587
+ "'": '&#39;',
1588
+ '<': '&lt;',
1589
+ '>': '&gt;',
1590
+ };
1591
+ const entity = (char) => entities[char];
1592
+ function escape(v) {
1593
+ const str = typeof v === 'string' ? v : `${v}`;
1594
+ // Most values contain nothing to escape; they are returned as they are,
1595
+ // without allocating
1596
+ return special.test(str) ? str.replace(specials, entity) : str;
1597
+ }
1598
+
1599
+ class Safe extends String {
1600
+ constructor(value) {
1601
+ super(`${value}`);
1602
+ }
1603
+ }
1604
+
1605
+ /** Defaults and resolved limits used by the compiler and renderer. */
1606
+ function resolveSecurityLimits(security = {}) {
1607
+ return {
1608
+ maxIncludeDepth: security.maxIncludeDepth ?? 100,
1609
+ maxLoopIterations: security.maxLoopIterations,
1610
+ maxCallDepth: security.maxCallDepth,
1611
+ timeoutMs: security.timeoutMs,
1612
+ };
1613
+ }
1614
+ class SecuritySandbox {
1615
+ constructor(options = {}) {
1616
+ Object.defineProperty(this, "allowedGlobals", {
1617
+ enumerable: true,
1618
+ configurable: true,
1619
+ writable: true,
1620
+ value: void 0
1621
+ });
1622
+ Object.defineProperty(this, "cspNonce", {
1623
+ enumerable: true,
1624
+ configurable: true,
1625
+ writable: true,
1626
+ value: void 0
1627
+ });
1628
+ this.allowedGlobals = new Set(options.allowedGlobals || []);
1629
+ this.cspNonce = options.cspNonce;
1630
+ }
1631
+ sanitizeGlobals(globals) {
1632
+ const sanitized = {};
1633
+ for (const [key, value] of Object.entries(globals)) {
1634
+ if (this.allowedGlobals.has(key)) {
1635
+ sanitized[key] = value;
1636
+ }
1637
+ }
1638
+ return sanitized;
1639
+ }
1640
+ validateExpression(expression) {
1641
+ // Prevent access to dangerous globals
1642
+ const dangerousPatterns = [
1643
+ /\bprocess\b/,
1644
+ /\brequire\b/,
1645
+ /\bimport\b/,
1646
+ /\bexport\b/,
1647
+ /\beval\b/,
1648
+ /\bFunction\b/,
1649
+ /\b__proto__\b/,
1650
+ /\bconstructor\b/,
1651
+ ];
1652
+ for (const pattern of dangerousPatterns) {
1653
+ if (pattern.test(expression)) {
1654
+ return false;
1655
+ }
1656
+ }
1657
+ return true;
1658
+ }
1659
+ createSecureContext(globals) {
1660
+ const sanitized = this.sanitizeGlobals(globals);
1661
+ // Add safe utility functions
1662
+ return {
1663
+ ...sanitized,
1664
+ Math,
1665
+ Date,
1666
+ JSON,
1667
+ // Add other safe built-ins as needed
1668
+ };
1669
+ }
1670
+ getCSPNonce() {
1671
+ return this.cspNonce;
1672
+ }
1673
+ generateCSPHeaders() {
1674
+ const headers = {};
1675
+ if (this.cspNonce) {
1676
+ headers['Content-Security-Policy'] =
1677
+ `script-src 'nonce-${this.cspNonce}'`;
1678
+ }
1679
+ return headers;
1680
+ }
1681
+ }
1682
+ function deepEscape(value, seen = new WeakSet()) {
1683
+ if (value === null || value === undefined) {
1684
+ return '';
1685
+ }
1686
+ if (value instanceof Safe) {
1687
+ return `${value}`;
1688
+ }
1689
+ if (typeof value === 'object') {
1690
+ // Guard against circular references
1691
+ if (seen.has(value)) {
1692
+ return '';
1693
+ }
1694
+ seen.add(value);
1695
+ const values = Array.isArray(value)
1696
+ ? value
1697
+ : Object.values(value);
1698
+ return values.map((v) => deepEscape(v, seen)).join('');
1699
+ }
1700
+ return escape(value);
1701
+ }
1702
+ class SecurityAuditor {
1703
+ auditTemplate(template) {
1704
+ const issues = [];
1705
+ // Check for dangerous patterns
1706
+ const dangerousPatterns = [
1707
+ {
1708
+ pattern: /\beval\s*\(/,
1709
+ type: 'dangerous-eval',
1710
+ message: 'Use of eval() is dangerous and should be avoided',
1711
+ severity: 'critical',
1712
+ },
1713
+ {
1714
+ pattern: /\bFunction\s*\(/,
1715
+ type: 'dangerous-function',
1716
+ message: 'Use of Function constructor is dangerous',
1717
+ severity: 'critical',
1718
+ },
1719
+ {
1720
+ pattern: /\brequire\s*\(/,
1721
+ type: 'require-usage',
1722
+ message: 'Direct require() usage in templates is unsafe',
1723
+ severity: 'high',
1724
+ },
1725
+ {
1726
+ pattern: /\bimport\s*\(/,
1727
+ type: 'dynamic-import',
1728
+ message: 'Dynamic import() usage in templates may be unsafe',
1729
+ severity: 'high',
1730
+ },
1731
+ ];
1732
+ for (const { pattern, type, message, severity } of dangerousPatterns) {
1733
+ const match = template.match(pattern);
1734
+ if (match) {
1735
+ issues.push({
1736
+ type,
1737
+ message,
1738
+ location: `at index ${match.index}`,
1739
+ severity,
1740
+ });
1741
+ }
1742
+ }
1743
+ // Calculate overall severity
1744
+ const overallSeverity = this.calculateOverallSeverity(issues);
1745
+ return {
1746
+ issues,
1747
+ severity: overallSeverity,
1748
+ };
1749
+ }
1750
+ calculateOverallSeverity(issues) {
1751
+ if (issues.length === 0) {
1752
+ return 'low';
1753
+ }
1754
+ const severityMap = {
1755
+ critical: 4,
1756
+ high: 3,
1757
+ medium: 2,
1758
+ low: 1,
1759
+ };
1760
+ const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1761
+ return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
1762
+ }
1763
+ }
1764
+
1582
1765
  const fingerprints = new WeakMap();
1583
1766
  // How deep includes may nest while rendering. Only templates that include
1584
1767
  // themselves get anywhere near it; the limit turns a cycle that never ends
@@ -1595,6 +1778,8 @@ function optionsFingerprint(options) {
1595
1778
  let fingerprint = fingerprints.get(options);
1596
1779
  if (fingerprint === undefined) {
1597
1780
  const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1781
+ // Limits that change the generated code must bust the compile cache
1782
+ const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1598
1783
  fingerprint = JSON.stringify([
1599
1784
  trimWhitespace,
1600
1785
  stripComments,
@@ -1604,6 +1789,9 @@ function optionsFingerprint(options) {
1604
1789
  directiveClose,
1605
1790
  outputOpen,
1606
1791
  outputClose,
1792
+ maxIncludeDepth,
1793
+ maxLoopIterations ?? null,
1794
+ maxCallDepth ?? null,
1607
1795
  ]);
1608
1796
  fingerprints.set(options, fingerprint);
1609
1797
  }
@@ -1721,12 +1909,16 @@ class Compiler extends Context {
1721
1909
  this.rootNode = new Parser(this.options).parse(template);
1722
1910
  this.state = {};
1723
1911
  this.start(this.isRoot);
1912
+ if (this.isRoot) {
1913
+ this.pushResourceLimitCounters();
1914
+ }
1724
1915
  await this.parseTemplates();
1725
1916
  if (this.isRoot) {
1726
1917
  if (this.partials.size) {
1918
+ const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1727
1919
  this.pushRaw(null, 'let d_=0;', 'const p={');
1728
1920
  for (const [path, code] of this.partials) {
1729
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${MAX_INCLUDE_DEPTH})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
1921
+ this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${maxIncludeDepth})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
1730
1922
  }
1731
1923
  this.pushRaw(null, '};');
1732
1924
  }
@@ -1775,6 +1967,19 @@ class Compiler extends Context {
1775
1967
  fingerprint() {
1776
1968
  return optionsFingerprint(this.options);
1777
1969
  }
1970
+ /**
1971
+ * Shared counters for optional security limits. Declared once on the root
1972
+ * template so nested includes, macros and loops all see the same budget.
1973
+ */
1974
+ pushResourceLimitCounters() {
1975
+ const { maxLoopIterations, maxCallDepth } = resolveSecurityLimits(this.options.security);
1976
+ if (maxLoopIterations != null) {
1977
+ this.pushRaw(null, 'let li_=0;');
1978
+ }
1979
+ if (maxCallDepth != null) {
1980
+ this.pushRaw(null, 'let cd_=0;');
1981
+ }
1982
+ }
1778
1983
  async isFresh({ sources }) {
1779
1984
  if (!this.revalidate) {
1780
1985
  return true;
@@ -1896,29 +2101,6 @@ class Compiler extends Context {
1896
2101
  }
1897
2102
  }
1898
2103
 
1899
- const special = /[&<>"']/;
1900
- const specials = /[&<>"']/g;
1901
- const entities = {
1902
- '&': '&amp;',
1903
- '"': '&#34;',
1904
- "'": '&#39;',
1905
- '<': '&lt;',
1906
- '>': '&gt;',
1907
- };
1908
- const entity = (char) => entities[char];
1909
- function escape(v) {
1910
- const str = typeof v === 'string' ? v : `${v}`;
1911
- // Most values contain nothing to escape; they are returned as they are,
1912
- // without allocating
1913
- return special.test(str) ? str.replace(specials, entity) : str;
1914
- }
1915
-
1916
- class Safe extends String {
1917
- constructor(value) {
1918
- super(`${value}`);
1919
- }
1920
- }
1921
-
1922
2104
  function abs(value = 0) {
1923
2105
  return Math.abs(value);
1924
2106
  }
@@ -2849,13 +3031,19 @@ async function compileFor({ loop: { left, right, loc }, body, alternative }, com
2849
3031
  : [[left.value, 'v_']];
2850
3032
  const scope = compiler.in();
2851
3033
  compiler.pushRaw(loc, 'let i_=0;');
3034
+ const { maxLoopIterations } = resolveSecurityLimits(compiler.options.security);
3035
+ const loopGuard = maxLoopIterations == null
3036
+ ? []
3037
+ : [
3038
+ `if(++li_>${maxLoopIterations})throw new Error(${JSON.stringify(`Loop iteration limit of ${maxLoopIterations} exceeded`)});`,
3039
+ ];
2852
3040
  if (isReadOnly(body)) {
2853
3041
  // Nothing in the body can modify the scope, so a single one is shared by
2854
3042
  // all iterations instead of copying the outer context for each of them
2855
- compiler.pushRaw(loc, `const ${scope}={...${context}};`, 'for(const v_ of a_){', `${scope}.loop={${loop.slice(6)};`, ...variables.map(([name, value]) => `${scope}.${name}=${value};`));
3043
+ compiler.pushRaw(loc, `const ${scope}={...${context}};`, 'for(const v_ of a_){', ...loopGuard, `${scope}.loop={${loop.slice(6)};`, ...variables.map(([name, value]) => `${scope}.${name}=${value};`));
2856
3044
  }
2857
3045
  else {
2858
- compiler.pushRaw(loc, 'for(const v_ of a_){', `const ${scope}={`, `...${context},`, `${loop},`, ...variables.map(([name, value]) => `${name}:${value},`), '};');
3046
+ compiler.pushRaw(loc, 'for(const v_ of a_){', ...loopGuard, `const ${scope}={`, `...${context},`, `${loop},`, ...variables.map(([name, value]) => `${name}:${value},`), '};');
2859
3047
  }
2860
3048
  await compiler.compileNodes(body);
2861
3049
  compiler.out();
@@ -3370,15 +3558,22 @@ const plugin$7 = {
3370
3558
  async function compileMacro({ val: { value, args }, loc, body }, compiler) {
3371
3559
  const { context } = compiler;
3372
3560
  const expCompiler = new ExpCompiler();
3561
+ const { maxCallDepth } = resolveSecurityLimits(compiler.options.security);
3373
3562
  compiler.pushRaw(loc,
3374
3563
  // A macro collects its own output and returns it, so that it ends up
3375
3564
  // where the macro is called rather than where it was defined
3376
- `${context}.${value}=(...a_)=>async(_c)=>{`, 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3565
+ `${context}.${value}=(...a_)=>async(_c)=>{`, ...(maxCallDepth == null
3566
+ ? []
3567
+ : [
3568
+ `if(cd_>=${maxCallDepth})throw new Error(${JSON.stringify(`Macro call depth limit of ${maxCallDepth} exceeded`)});`,
3569
+ 'cd_++;',
3570
+ 'try{',
3571
+ ]), 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3377
3572
  ? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
3378
3573
  : `${el.value}:a_[${i}],`), '};');
3379
3574
  await compiler.compileNodes(body);
3380
3575
  compiler.out();
3381
- compiler.pushRaw(null, 'return s;', '};');
3576
+ compiler.pushRaw(null, 'return s;', ...(maxCallDepth == null ? [] : ['}finally{cd_--;}']), '};');
3382
3577
  }
3383
3578
  function compileCaller({ loc }, compiler) {
3384
3579
  compiler.pushRaw(loc, 's+=await _c?.()??"";');
@@ -3910,157 +4105,6 @@ class RenderError extends CompileError {
3910
4105
  }
3911
4106
  }
3912
4107
 
3913
- class SecuritySandbox {
3914
- constructor(options = {}) {
3915
- Object.defineProperty(this, "allowedGlobals", {
3916
- enumerable: true,
3917
- configurable: true,
3918
- writable: true,
3919
- value: void 0
3920
- });
3921
- Object.defineProperty(this, "cspNonce", {
3922
- enumerable: true,
3923
- configurable: true,
3924
- writable: true,
3925
- value: void 0
3926
- });
3927
- this.allowedGlobals = new Set(options.allowedGlobals || []);
3928
- this.cspNonce = options.cspNonce;
3929
- }
3930
- sanitizeGlobals(globals) {
3931
- const sanitized = {};
3932
- for (const [key, value] of Object.entries(globals)) {
3933
- if (this.allowedGlobals.has(key)) {
3934
- sanitized[key] = value;
3935
- }
3936
- }
3937
- return sanitized;
3938
- }
3939
- validateExpression(expression) {
3940
- // Prevent access to dangerous globals
3941
- const dangerousPatterns = [
3942
- /\bprocess\b/,
3943
- /\brequire\b/,
3944
- /\bimport\b/,
3945
- /\bexport\b/,
3946
- /\beval\b/,
3947
- /\bFunction\b/,
3948
- /\b__proto__\b/,
3949
- /\bconstructor\b/,
3950
- ];
3951
- for (const pattern of dangerousPatterns) {
3952
- if (pattern.test(expression)) {
3953
- return false;
3954
- }
3955
- }
3956
- return true;
3957
- }
3958
- createSecureContext(globals) {
3959
- const sanitized = this.sanitizeGlobals(globals);
3960
- // Add safe utility functions
3961
- return {
3962
- ...sanitized,
3963
- Math,
3964
- Date,
3965
- JSON,
3966
- // Add other safe built-ins as needed
3967
- };
3968
- }
3969
- getCSPNonce() {
3970
- return this.cspNonce;
3971
- }
3972
- generateCSPHeaders() {
3973
- const headers = {};
3974
- if (this.cspNonce) {
3975
- headers['Content-Security-Policy'] =
3976
- `script-src 'nonce-${this.cspNonce}'`;
3977
- }
3978
- return headers;
3979
- }
3980
- }
3981
- function deepEscape(value, seen = new WeakSet()) {
3982
- if (value === null || value === undefined) {
3983
- return '';
3984
- }
3985
- if (value instanceof Safe) {
3986
- return `${value}`;
3987
- }
3988
- if (typeof value === 'object') {
3989
- // Guard against circular references
3990
- if (seen.has(value)) {
3991
- return '';
3992
- }
3993
- seen.add(value);
3994
- const values = Array.isArray(value)
3995
- ? value
3996
- : Object.values(value);
3997
- return values.map((v) => deepEscape(v, seen)).join('');
3998
- }
3999
- return escape(value);
4000
- }
4001
- class SecurityAuditor {
4002
- auditTemplate(template) {
4003
- const issues = [];
4004
- // Check for dangerous patterns
4005
- const dangerousPatterns = [
4006
- {
4007
- pattern: /\beval\s*\(/,
4008
- type: 'dangerous-eval',
4009
- message: 'Use of eval() is dangerous and should be avoided',
4010
- severity: 'critical',
4011
- },
4012
- {
4013
- pattern: /\bFunction\s*\(/,
4014
- type: 'dangerous-function',
4015
- message: 'Use of Function constructor is dangerous',
4016
- severity: 'critical',
4017
- },
4018
- {
4019
- pattern: /\brequire\s*\(/,
4020
- type: 'require-usage',
4021
- message: 'Direct require() usage in templates is unsafe',
4022
- severity: 'high',
4023
- },
4024
- {
4025
- pattern: /\bimport\s*\(/,
4026
- type: 'dynamic-import',
4027
- message: 'Dynamic import() usage in templates may be unsafe',
4028
- severity: 'high',
4029
- },
4030
- ];
4031
- for (const { pattern, type, message, severity } of dangerousPatterns) {
4032
- const match = template.match(pattern);
4033
- if (match) {
4034
- issues.push({
4035
- type,
4036
- message,
4037
- location: `at index ${match.index}`,
4038
- severity,
4039
- });
4040
- }
4041
- }
4042
- // Calculate overall severity
4043
- const overallSeverity = this.calculateOverallSeverity(issues);
4044
- return {
4045
- issues,
4046
- severity: overallSeverity,
4047
- };
4048
- }
4049
- calculateOverallSeverity(issues) {
4050
- if (issues.length === 0) {
4051
- return 'low';
4052
- }
4053
- const severityMap = {
4054
- critical: 4,
4055
- high: 3,
4056
- medium: 2,
4057
- low: 1,
4058
- };
4059
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
4060
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
4061
- }
4062
- }
4063
-
4064
4108
  // Thrown inside a template to stop rendering a stream nobody reads anymore
4065
4109
  const cancellation = new Error('Stream cancelled');
4066
4110
  class Renderer {
@@ -4274,7 +4318,24 @@ class Renderer {
4274
4318
  ...globals,
4275
4319
  }
4276
4320
  : { ...this.options.globals, ...globals };
4277
- return script(context, this.escape, this.filters, write);
4321
+ const result = script(context, this.escape, this.filters, write);
4322
+ const { timeoutMs } = this.options.security ?? {};
4323
+ if (timeoutMs == null) {
4324
+ return result;
4325
+ }
4326
+ // The script keeps running after the budget; only the promise rejects.
4327
+ // Use a separate process when templates must be forcibly stopped.
4328
+ let timer;
4329
+ return Promise.race([
4330
+ Promise.resolve(result).finally(() => {
4331
+ clearTimeout(timer);
4332
+ }),
4333
+ new Promise((_, reject) => {
4334
+ timer = setTimeout(() => {
4335
+ reject(new Error(`Render timed out after ${timeoutMs}ms`));
4336
+ }, timeoutMs);
4337
+ }),
4338
+ ]);
4278
4339
  }
4279
4340
  async renderFile(filepath, globals) {
4280
4341
  return this.render(await this.options.loader(filepath), globals);
@@ -5489,6 +5550,8 @@ exports.RenderError = RenderError;
5489
5550
  exports.Renderer = Renderer;
5490
5551
  exports.RootNode = RootNode;
5491
5552
  exports.Safe = Safe;
5553
+ exports.SecurityAuditor = SecurityAuditor;
5554
+ exports.SecuritySandbox = SecuritySandbox;
5492
5555
  exports.TemplatePipeline = TemplatePipeline;
5493
5556
  exports.TemplateValidator = TemplateValidator;
5494
5557
  exports.Tokenizer = Tokenizer;
@@ -5506,6 +5569,7 @@ exports.composeWithSlots = composeWithSlots;
5506
5569
  exports.createErrorRecovery = createErrorRecovery;
5507
5570
  exports.createFileLoader = createFileLoader;
5508
5571
  exports.createMixin = createMixin;
5572
+ exports.deepEscape = deepEscape;
5509
5573
  exports.defaultErrorHandler = defaultErrorHandler;
5510
5574
  exports.defaultWhitespaceOptions = defaultWhitespaceOptions;
5511
5575
  exports.defineFilters = defineFilters;
@@ -5532,5 +5596,6 @@ exports.renderCompiled = renderCompiled;
5532
5596
  exports.renderFile = renderFile;
5533
5597
  exports.renderOptions = renderOptions;
5534
5598
  exports.renderStream = renderStream;
5599
+ exports.resolveSecurityLimits = resolveSecurityLimits;
5535
5600
  exports.templateCacheKey = templateCacheKey;
5536
5601
  exports.validateTemplate = validateTemplate;
package/dist/index.d.ts CHANGED
@@ -198,6 +198,11 @@ declare class Compiler extends Context {
198
198
  get script(): Script;
199
199
  private generateCacheKey;
200
200
  private fingerprint;
201
+ /**
202
+ * Shared counters for optional security limits. Declared once on the root
203
+ * template so nested includes, macros and loops all see the same budget.
204
+ */
205
+ private pushResourceLimitCounters;
201
206
  private isFresh;
202
207
  private parseTemplates;
203
208
  private collectPartialsAndBlocks;
@@ -242,7 +247,46 @@ interface SecurityOptions {
242
247
  deepEscape?: boolean;
243
248
  cspNonce?: string;
244
249
  cspHeaders?: Record<string, string>;
245
- }
250
+ /**
251
+ * Maximum nest depth of `include` while rendering. Defaults to 100.
252
+ * Cycles that never end become an error instead of a stack overflow.
253
+ */
254
+ maxIncludeDepth?: number;
255
+ /**
256
+ * Maximum number of `for` loop iterations across one render. Off by default.
257
+ * Enable when templates may be untrusted.
258
+ */
259
+ maxLoopIterations?: number;
260
+ /**
261
+ * Maximum nest depth of macro invocations across one render. Off by default.
262
+ */
263
+ maxCallDepth?: number;
264
+ /**
265
+ * Wall-clock budget for one `render` / `renderCompiled` call, in
266
+ * milliseconds. Off by default. The running script is not aborted; the
267
+ * promise rejects when the budget is exceeded. Prefer a separate process
268
+ * for truly hostile templates.
269
+ */
270
+ timeoutMs?: number;
271
+ }
272
+ /** Defaults and resolved limits used by the compiler and renderer. */
273
+ declare function resolveSecurityLimits(security?: SecurityOptions): {
274
+ maxIncludeDepth: number;
275
+ maxLoopIterations: number | undefined;
276
+ maxCallDepth: number | undefined;
277
+ timeoutMs: number | undefined;
278
+ };
279
+ declare class SecuritySandbox {
280
+ private allowedGlobals;
281
+ private cspNonce?;
282
+ constructor(options?: SecurityOptions);
283
+ sanitizeGlobals(globals: ObjectType): ObjectType;
284
+ validateExpression(expression: string): boolean;
285
+ createSecureContext(globals: ObjectType): ObjectType;
286
+ getCSPNonce(): string | undefined;
287
+ generateCSPHeaders(): Record<string, string>;
288
+ }
289
+ declare function deepEscape(value: unknown, seen?: WeakSet<object>): string;
246
290
  interface SecurityAuditResult {
247
291
  issues: SecurityIssue[];
248
292
  severity: 'low' | 'medium' | 'high' | 'critical';
@@ -253,6 +297,10 @@ interface SecurityIssue {
253
297
  location?: string;
254
298
  severity: 'low' | 'medium' | 'high' | 'critical';
255
299
  }
300
+ declare class SecurityAuditor {
301
+ auditTemplate(template: string): SecurityAuditResult;
302
+ private calculateOverallSeverity;
303
+ }
256
304
 
257
305
  type MaybePromise<T> = T | Promise<T>;
258
306
  type ObjectType<T = any> = Record<string, T>;
@@ -958,7 +1006,7 @@ interface FileLoaderOptions {
958
1006
  * Paths are resolved against `root`, with or without an extension, and may
959
1007
  * not lead outside of it, so that a template cannot include arbitrary files.
960
1008
  */
961
- declare function createFileLoader(root: string, { extensions }?: FileLoaderOptions): (name: string) => Promise<string>;
1009
+ declare function createFileLoader(root: string, { extensions }?: FileLoaderOptions): (name: string) => Promise<any>;
962
1010
 
963
1011
  interface ErrorRecoveryOptions {
964
1012
  /**
@@ -1028,5 +1076,5 @@ declare function renderCompiled(script: Script, data?: ObjectType, options?: Ren
1028
1076
  */
1029
1077
  declare function renderStream(template: string, data?: ObjectType, options?: RendererOptions): ReadableStream<string>;
1030
1078
 
1031
- export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MAX_INCLUDE_DEPTH, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
1032
- export type { BaseOptions, BinaryExp, BinaryExpTokenType, BinaryExpType, CacheOptions, Checker, CommentToken, CompiledTemplate, CompilerFn, CompilerMap, CompilerOptions, CompositionOptions, DirectiveExpression, DirectiveToken, ErrorContext, ErrorRecoveryOptions, Exp, ExpBase, ExpToken, ExpTokenType, ExpType, FileLoaderOptions, Filter, Filters, FormatOptions, FormatterFn, FormatterMap, FormatterOptions, I18nOptions, IdExp, IfExp, LitExp, Loc, MaybePromise, MixinDefinition, MixinOptions, NotExp, ObjectType, OutputToken, ParserFn, ParserMap, ParserOptions, Plugin, PluralRules, Pos, PrecompileOptions, PrecompileResult, Primitive, RendererOptions, Script, SeqExp, SourceMapOptions, SourceMapV3, Strip, SyntaxNode, TemplateAnalysis, TernaryExpTokenType, TernaryExpType, TextToken, Token, TokenBase, TranslationDict, UnaryExpTokenType, UnaryExpType, ValidationError, ValidationResult, WhitespaceOptions };
1079
+ export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MAX_INCLUDE_DEPTH, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, SecurityAuditor, SecuritySandbox, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, deepEscape, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, resolveSecurityLimits, templateCacheKey, validateTemplate };
1080
+ export type { BaseOptions, BinaryExp, BinaryExpTokenType, BinaryExpType, CacheOptions, Checker, CommentToken, CompiledTemplate, CompilerFn, CompilerMap, CompilerOptions, CompositionOptions, DirectiveExpression, DirectiveToken, ErrorContext, ErrorRecoveryOptions, Exp, ExpBase, ExpToken, ExpTokenType, ExpType, FileLoaderOptions, Filter, Filters, FormatOptions, FormatterFn, FormatterMap, FormatterOptions, I18nOptions, IdExp, IfExp, LitExp, Loc, MaybePromise, MixinDefinition, MixinOptions, NotExp, ObjectType, OutputToken, ParserFn, ParserMap, ParserOptions, Plugin, PluralRules, Pos, PrecompileOptions, PrecompileResult, Primitive, RendererOptions, Script, SecurityAuditResult, SecurityIssue, SecurityOptions, SeqExp, SourceMapOptions, SourceMapV3, Strip, SyntaxNode, TemplateAnalysis, TernaryExpTokenType, TernaryExpType, TextToken, Token, TokenBase, TranslationDict, UnaryExpTokenType, UnaryExpType, ValidationError, ValidationResult, WhitespaceOptions };