janja 3.0.0 → 4.0.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
@@ -1581,6 +1581,10 @@ ${suggestionText}`;
1581
1581
  }
1582
1582
 
1583
1583
  const fingerprints = new WeakMap();
1584
+ // How deep includes may nest while rendering. Only templates that include
1585
+ // themselves get anywhere near it; the limit turns a cycle that never ends
1586
+ // into an error instead of a stack overflow.
1587
+ const MAX_INCLUDE_DEPTH = 100;
1584
1588
  // Directives whose body is still the template's own top-level output
1585
1589
  const transparent = new Set(['IF', 'FOR']);
1586
1590
  // The template itself is the key: one string that is hashed once, and two
@@ -1721,9 +1725,9 @@ ${suggestionText}`;
1721
1725
  await this.parseTemplates();
1722
1726
  if (this.isRoot) {
1723
1727
  if (this.partials.size) {
1724
- this.pushRaw(null, 'const p={');
1728
+ this.pushRaw(null, 'let d_=0;', 'const p={');
1725
1729
  for (const [path, code] of this.partials) {
1726
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, code, '},');
1730
+ this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${MAX_INCLUDE_DEPTH})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
1727
1731
  }
1728
1732
  this.pushRaw(null, '};');
1729
1733
  }
@@ -1800,6 +1804,10 @@ ${suggestionText}`;
1800
1804
  throw new CompileError(`Failed to load template from "${path}"`, this.template, node.loc);
1801
1805
  }
1802
1806
  this.sources.set(path, template ?? '');
1807
+ // Reserved before compiling, so that a template that includes itself,
1808
+ // directly or through others, refers to the partial being compiled
1809
+ // instead of compiling it again without end
1810
+ this.partials.set(path, '');
1803
1811
  if (template) {
1804
1812
  await this.compilePartial(path, node, template);
1805
1813
  }
@@ -1889,37 +1897,21 @@ ${suggestionText}`;
1889
1897
  }
1890
1898
  }
1891
1899
 
1900
+ const special = /[&<>"']/;
1901
+ const specials = /[&<>"']/g;
1902
+ const entities = {
1903
+ '&': '&amp;',
1904
+ '"': '&#34;',
1905
+ "'": '&#39;',
1906
+ '<': '&lt;',
1907
+ '>': '&gt;',
1908
+ };
1909
+ const entity = (char) => entities[char];
1892
1910
  function escape(v) {
1893
1911
  const str = typeof v === 'string' ? v : `${v}`;
1894
- // A single scan without regular expressions. Most values contain nothing
1895
- // to escape; they are returned as they are, without allocating.
1896
- let result = '';
1897
- let last = 0;
1898
- for (let i = 0; i < str.length; i++) {
1899
- let entity;
1900
- switch (str.charCodeAt(i)) {
1901
- case 38:
1902
- entity = '&amp;';
1903
- break;
1904
- case 34:
1905
- entity = '&#34;';
1906
- break;
1907
- case 39:
1908
- entity = '&#39;';
1909
- break;
1910
- case 60:
1911
- entity = '&lt;';
1912
- break;
1913
- case 62:
1914
- entity = '&gt;';
1915
- break;
1916
- default:
1917
- continue;
1918
- }
1919
- result += str.slice(last, i) + entity;
1920
- last = i + 1;
1921
- }
1922
- return last === 0 ? str : result + str.slice(last);
1912
+ // Most values contain nothing to escape; they are returned as they are,
1913
+ // without allocating
1914
+ return special.test(str) ? str.replace(specials, entity) : str;
1923
1915
  }
1924
1916
 
1925
1917
  class Safe extends String {
@@ -2459,6 +2451,10 @@ ${suggestionText}`;
2459
2451
  IF: '',
2460
2452
  ELSE: '',
2461
2453
  };
2454
+ // Names every object inherits (`toString`, `valueOf`, ...). The context is a
2455
+ // plain object, so these are only read from it when it has them itself;
2456
+ // otherwise a name nobody defined would resolve to a built-in function.
2457
+ const inherited = new Set(Object.getOwnPropertyNames(Object.prototype));
2462
2458
  class ExpCompiler {
2463
2459
  constructor() {
2464
2460
  Object.defineProperty(this, "context", {
@@ -2521,15 +2517,38 @@ ${suggestionText}`;
2521
2517
  return `!${this.compileExp(argument)}`;
2522
2518
  }
2523
2519
  compileId({ value, path, args }) {
2524
- let s = `${this.context}.${value}`;
2520
+ let s = inherited.has(value)
2521
+ ? `(Object.hasOwn(${this.context},"${value}")?${this.context}.${value}:undefined)`
2522
+ : `${this.context}.${value}`;
2525
2523
  if (path) {
2526
2524
  s += path.map((p) => `.${p.value}`).join('');
2527
2525
  }
2528
2526
  if (args) {
2529
- s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
2527
+ s += `(${this.compileArgs(args).join(',')})`;
2530
2528
  }
2531
2529
  return s;
2532
2530
  }
2531
+ /**
2532
+ * Positional arguments in the order they are written, followed by one
2533
+ * object holding the named ones: `f(1, a=2, b=3)` calls `f(1, {a:2,b:3})`.
2534
+ */
2535
+ compileArgs(args) {
2536
+ const positional = [];
2537
+ const named = [];
2538
+ for (const arg of args) {
2539
+ if (arg.type === 'ASSIGN') {
2540
+ const { left, right } = arg;
2541
+ named.push(`${left.value}:${this.compileExp(right)}`);
2542
+ }
2543
+ else {
2544
+ positional.push(this.compileExp(arg));
2545
+ }
2546
+ }
2547
+ if (named.length) {
2548
+ positional.push(`{${named.join(',')}}`);
2549
+ }
2550
+ return positional;
2551
+ }
2533
2552
  compileLit({ value }) {
2534
2553
  if (value === undefined) {
2535
2554
  return 'undefined';
@@ -2546,7 +2565,7 @@ ${suggestionText}`;
2546
2565
  }
2547
2566
  compilePipe({ left, right }) {
2548
2567
  const { value: name, args = [] } = right;
2549
- const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...args.map((arg) => (arg.type === 'ASSIGN' ? `${this.context}.${arg.left.value}=${this.compileExp(arg.right)}` : this.compileExp(arg)))].join(',')})`;
2568
+ const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...this.compileArgs(args)].join(',')})`;
2550
2569
  // Awaiting a plain value still costs a trip through the microtask queue,
2551
2570
  // so only promises returned by async filters are awaited
2552
2571
  return `(${RESULT}=${call},${RESULT} instanceof Promise?await ${RESULT}:${RESULT})`;
@@ -2571,9 +2590,9 @@ ${suggestionText}`;
2571
2590
  }
2572
2591
 
2573
2592
  async function compileCall({ val, body, loc }, compiler) {
2574
- compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
2593
+ compiler.pushRaw(loc, `s+=await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`, 'let s="";');
2575
2594
  await compiler.compileNodes(body);
2576
- compiler.pushRaw(null, '});');
2595
+ compiler.pushRaw(null, 'return s;', '})??"";');
2577
2596
  }
2578
2597
  const compilers$c = {
2579
2598
  CALL: compileCall,
@@ -2770,8 +2789,14 @@ ${suggestionText}`;
2770
2789
  return false;
2771
2790
  }
2772
2791
  seen.add(exp);
2773
- return (exp.type === 'ASSIGN' ||
2774
- Object.values(exp).some((value) => hasAssignment(value, seen)));
2792
+ if (exp.type === 'ASSIGN') {
2793
+ return true;
2794
+ }
2795
+ return Object.entries(exp).some(([key, value]) =>
2796
+ // `f(name=value)` passes a named argument; only its value matters
2797
+ key === 'args' && Array.isArray(value)
2798
+ ? value.some((arg) => hasAssignment(arg.type === 'ASSIGN' ? arg.right : arg, seen))
2799
+ : hasAssignment(value, seen));
2775
2800
  }
2776
2801
  /**
2777
2802
  * Whether nothing in `nodes` can write to, or keep a reference to, the
@@ -3346,15 +3371,18 @@ ${suggestionText}`;
3346
3371
  async function compileMacro({ val: { value, args }, loc, body }, compiler) {
3347
3372
  const { context } = compiler;
3348
3373
  const expCompiler = new ExpCompiler();
3349
- compiler.pushRaw(loc, `${context}.${value}=(...a_)=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3374
+ compiler.pushRaw(loc,
3375
+ // A macro collects its own output and returns it, so that it ends up
3376
+ // where the macro is called rather than where it was defined
3377
+ `${context}.${value}=(...a_)=>async(_c)=>{`, 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3350
3378
  ? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
3351
3379
  : `${el.value}:a_[${i}],`), '};');
3352
3380
  await compiler.compileNodes(body);
3353
3381
  compiler.out();
3354
- compiler.pushRaw(null, '};');
3382
+ compiler.pushRaw(null, 'return s;', '};');
3355
3383
  }
3356
3384
  function compileCaller({ loc }, compiler) {
3357
- compiler.pushRaw(loc, 'await _c?.();');
3385
+ compiler.pushRaw(loc, 's+=await _c?.()??"";');
3358
3386
  }
3359
3387
  const compilers$6 = {
3360
3388
  MACRO: compileMacro,
@@ -4069,6 +4097,14 @@ ${suggestionText}`;
4069
4097
  writable: true,
4070
4098
  value: void 0
4071
4099
  });
4100
+ // Compilations in progress, so that renders of the same template that
4101
+ // start together share one instead of each compiling it
4102
+ Object.defineProperty(this, "compiling", {
4103
+ enumerable: true,
4104
+ configurable: true,
4105
+ writable: true,
4106
+ value: new Map()
4107
+ });
4072
4108
  this.options = mergeOptions(renderOptions, {
4073
4109
  filters,
4074
4110
  plugins,
@@ -4077,6 +4113,11 @@ ${suggestionText}`;
4077
4113
  const escapeValue = this.options.security?.deepEscape ? deepEscape : escape;
4078
4114
  const { autoEscape } = this.options;
4079
4115
  this.escape = (v) => {
4116
+ // Strings are by far the most common value, so they are handled before
4117
+ // anything else is checked
4118
+ if (typeof v === 'string') {
4119
+ return autoEscape ? escape(v) : v;
4120
+ }
4080
4121
  if (v === null || v === undefined) {
4081
4122
  return '';
4082
4123
  }
@@ -4111,13 +4152,13 @@ ${suggestionText}`;
4111
4152
  return '';
4112
4153
  }
4113
4154
  }
4114
- const compiler = this.createCompiler();
4155
+ let compiler;
4115
4156
  try {
4116
- await compiler.compile(template);
4157
+ compiler = await this.compile(template);
4117
4158
  return await this.run(compiler.script, globals);
4118
4159
  }
4119
4160
  catch (error) {
4120
- this.options.debug(this.wrapError(error, template, compiler));
4161
+ this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
4121
4162
  }
4122
4163
  return '';
4123
4164
  }
@@ -4162,12 +4203,12 @@ ${suggestionText}`;
4162
4203
  });
4163
4204
  }
4164
4205
  };
4165
- const compiler = this.createCompiler(true);
4206
+ let compiler;
4166
4207
  // Not awaited: `start` returns right away and chunks are enqueued as
4167
4208
  // they are produced
4168
4209
  void (async () => {
4169
4210
  try {
4170
- await compiler.compile(template);
4211
+ compiler = await this.compile(template, true);
4171
4212
  const rest = await this.run(compiler.script, globals, write);
4172
4213
  if (rest && !cancelled) {
4173
4214
  controller.enqueue(rest);
@@ -4179,7 +4220,7 @@ ${suggestionText}`;
4179
4220
  return;
4180
4221
  }
4181
4222
  try {
4182
- this.options.debug(this.wrapError(error, template, compiler));
4223
+ this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
4183
4224
  controller.close();
4184
4225
  }
4185
4226
  catch (reported) {
@@ -4198,8 +4239,16 @@ ${suggestionText}`;
4198
4239
  },
4199
4240
  });
4200
4241
  }
4201
- createCompiler(stream = false) {
4202
- return new Compiler(this.options, this.cache, this.options.cache?.revalidate ?? true, stream);
4242
+ compile(template, stream = false) {
4243
+ const key = templateCacheKey(template, stream);
4244
+ let compiling = this.compiling.get(key);
4245
+ if (!compiling) {
4246
+ compiling = new Compiler(this.options, this.cache, this.options.cache?.revalidate ?? true, stream)
4247
+ .compile(template)
4248
+ .finally(() => this.compiling.delete(key));
4249
+ this.compiling.set(key, compiling);
4250
+ }
4251
+ return compiling;
4203
4252
  }
4204
4253
  wrapError(error, template, sourceMap) {
4205
4254
  if (error?.name === 'CompileError') {
@@ -5434,6 +5483,7 @@ export default script;
5434
5483
  exports.ExpParser = ExpParser;
5435
5484
  exports.ExpTokenizer = ExpTokenizer;
5436
5485
  exports.I18n = I18n;
5486
+ exports.MAX_INCLUDE_DEPTH = MAX_INCLUDE_DEPTH;
5437
5487
  exports.MixinRegistry = MixinRegistry;
5438
5488
  exports.Parser = Parser;
5439
5489
  exports.RenderError = RenderError;