janja 4.6.0 → 4.8.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.cjs CHANGED
@@ -1812,6 +1812,15 @@ class Parser extends Tokenizer {
1812
1812
  }
1813
1813
  }
1814
1814
 
1815
+ /**
1816
+ * Add the page-wide `include … last` registry and resolver to the root script.
1817
+ * The runtime walks rendered markers in reverse document order, so nested
1818
+ * partials and repeated includes inside loops are handled in render order.
1819
+ */
1820
+ function pushIncludeLastRuntime(compiler) {
1821
+ compiler.pushRaw(null, 'const il_=new Map();', 'let il_i_=0;', 'const il_n_=Math.random().toString(36).slice(2);', 'const il_re_=/\\u0000JLAST[a-z0-9]+:\\d+\\u0000/g;', 'const il_resolve_=async(v_,seen_=new Set())=>{', 'const matches_=[...v_.matchAll(il_re_)];', 'let cursor_=v_.length;', 'const parts_=[];', 'for(let i_=matches_.length-1;i_>=0;i_--){', 'const match_=matches_[i_],marker_=match_[0],start_=match_.index,item_=il_.get(marker_);', 'parts_.push(v_.slice(start_+marker_.length,cursor_));', 'if(item_&&!seen_.has(item_.path)){', 'const output_=await il_resolve_(await item_.render(),seen_);', 'if(!seen_.has(item_.path)){seen_.add(item_.path);parts_.push(output_);}', '}', 'cursor_=start_;', '}', 'parts_.push(v_.slice(0,cursor_));', 'return parts_.reverse().join("");', '};');
1822
+ }
1823
+
1815
1824
  function isStringLit(exp) {
1816
1825
  return exp.type === 'LIT' && typeof exp.value === 'string';
1817
1826
  }
@@ -1864,7 +1873,7 @@ const PRELOAD_LOC = {
1864
1873
  // Directives whose body is still the template's own top-level output
1865
1874
  const transparent = new Set(['IF', 'FOR']);
1866
1875
  class Compiler extends Context {
1867
- constructor(options, cache, revalidate = true, stream = false) {
1876
+ constructor(options, cache, revalidate = true, stream = false, includeLastState = { active: false }) {
1868
1877
  super();
1869
1878
  Object.defineProperty(this, "options", {
1870
1879
  enumerable: true,
@@ -1884,6 +1893,12 @@ class Compiler extends Context {
1884
1893
  writable: true,
1885
1894
  value: stream
1886
1895
  });
1896
+ Object.defineProperty(this, "includeLastState", {
1897
+ enumerable: true,
1898
+ configurable: true,
1899
+ writable: true,
1900
+ value: includeLastState
1901
+ });
1887
1902
  Object.defineProperty(this, "template", {
1888
1903
  enumerable: true,
1889
1904
  configurable: true,
@@ -2005,12 +2020,15 @@ class Compiler extends Context {
2005
2020
  }
2006
2021
  await this.parseTemplates();
2007
2022
  if (this.isRoot) {
2023
+ if (this.includeLastState.active) {
2024
+ pushIncludeLastRuntime(this);
2025
+ }
2008
2026
  if (this.partials.size || this.hasDynamicInclude) {
2009
2027
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
2010
2028
  // Alias the render data before partials shadow `c` with their argument.
2011
2029
  // `inc_` tracks `include … once` occurrences across the whole render,
2012
2030
  // root template and partials alike (they share this closure).
2013
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
2031
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_=new Set();', 'const p={');
2014
2032
  for (const [path, code] of this.partials) {
2015
2033
  this.pushRaw(null,
2016
2034
  // Partials take the context they should render with: plain include
@@ -2045,9 +2063,15 @@ class Compiler extends Context {
2045
2063
  }
2046
2064
  this.pushRaw(null, '];');
2047
2065
  }
2048
- this.flushable = this.isRoot && this.stream;
2066
+ // Last includes are resolved after the complete page has rendered, so
2067
+ // streaming must buffer the page to avoid flushing unresolved markers.
2068
+ this.flushable =
2069
+ this.isRoot && this.stream && !this.includeLastState.active;
2049
2070
  await this.compileNode(this.rootNode);
2050
2071
  this.flushable = false;
2072
+ if (this.isRoot && this.includeLastState.active) {
2073
+ this.pushRaw(null, 's=await il_resolve_(s);');
2074
+ }
2051
2075
  this.end();
2052
2076
  // Store in cache
2053
2077
  if (this.cache && root) {
@@ -2151,7 +2175,6 @@ class Compiler extends Context {
2151
2175
  const partials = new Map();
2152
2176
  const blocks = [];
2153
2177
  const stylesheets = [];
2154
- const includeLast = new Map();
2155
2178
  const traverse = (node) => {
2156
2179
  if (node.type === 'INCLUDE') {
2157
2180
  const include = node;
@@ -2160,13 +2183,7 @@ class Compiler extends Context {
2160
2183
  partials.set(include.val.value, include);
2161
2184
  }
2162
2185
  if (include.modifier === 'last') {
2163
- const existing = includeLast.get(include.val.value);
2164
- if (existing) {
2165
- existing.total += 1;
2166
- }
2167
- else {
2168
- includeLast.set(include.val.value, { total: 1, emitted: 0 });
2169
- }
2186
+ this.includeLastState.active = true;
2170
2187
  }
2171
2188
  }
2172
2189
  else {
@@ -2182,7 +2199,6 @@ class Compiler extends Context {
2182
2199
  node.traverse(traverse);
2183
2200
  };
2184
2201
  traverse(this.rootNode);
2185
- this.state.includeLast = includeLast;
2186
2202
  return {
2187
2203
  partials,
2188
2204
  blocks,
@@ -2236,7 +2252,7 @@ class Compiler extends Context {
2236
2252
  }
2237
2253
  async compilePartial(path, node, template) {
2238
2254
  try {
2239
- const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2255
+ const { code } = await new Compiler(this.options, undefined, true, false, this.includeLastState).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2240
2256
  this.partials.set(path, code);
2241
2257
  }
2242
2258
  catch {
@@ -3652,32 +3668,23 @@ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3652
3668
  const path = isStringLit(val)
3653
3669
  ? JSON.stringify(val.value)
3654
3670
  : expCompiler.compile(val, compiler.context);
3655
- // Emit the partial call, against the top context for a plain include or a
3656
- // merged scope for `include … with`.
3657
- const emit = withExp
3658
- ? `s+=await p[${path}]?.({...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}})??"";`
3659
- : `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`;
3671
+ const context = withExp
3672
+ ? `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`
3673
+ : TOP_CONTEXT;
3674
+ if (modifier === 'last' && isStringLit(val)) {
3675
+ // Mark every runtime occurrence. The root script resolves these markers
3676
+ // after rendering and keeps only the last visible occurrence per path.
3677
+ compiler.pushRaw(loc, '{', 'const ilm_="\\u0000JLAST"+il_n_+":"+(il_i_++)+"\\u0000";', `const ilc_=${context};`, `il_.set(ilm_,{path:${JSON.stringify(val.value)},render:async()=>{return (await p[${path}]?.(ilc_))??"";}});`, 's+=ilm_;', '}');
3678
+ return;
3679
+ }
3680
+ const emit = `s+=await p[${path}]?.(${context})??"";`;
3660
3681
  // `once`: render the first occurrence only. The registry lives in the root
3661
- // script's closure, so occurrences spread across different files (a root
3682
+ // script's closure, so occurrences spread across different files (the root
3662
3683
  // template and its partials) still deduplicate at runtime.
3663
3684
  if (modifier === 'once') {
3664
- compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3685
+ compiler.pushRaw(loc, `{const inc_p_=${path};if(!inc_.has(inc_p_)){inc_.add(inc_p_);s+=await p[inc_p_]?.(${context})??"";}}`);
3665
3686
  return;
3666
3687
  }
3667
- // `last`: emit only at the final occurrence within the template file,
3668
- // determined at compile time from the counts collected alongside partials.
3669
- // Static string paths only — a dynamic path has no stable identity to count.
3670
- if (modifier === 'last' && isStringLit(val)) {
3671
- const counts = compiler.state.includeLast;
3672
- const entry = counts?.get(val.value);
3673
- if (entry) {
3674
- entry.emitted += 1;
3675
- if (entry.emitted < entry.total) {
3676
- // Not the last occurrence — emit nothing.
3677
- return;
3678
- }
3679
- }
3680
- }
3681
3688
  compiler.pushRaw(loc, emit);
3682
3689
  }
3683
3690
  const compilers$8 = {
@@ -5631,6 +5638,15 @@ const DIR_CLOSE = new Set([
5631
5638
  'endwith',
5632
5639
  'endstylesheet',
5633
5640
  ]);
5641
+ /** True when a line starts an HTML opening tag that continues on later lines. */
5642
+ function startsMultilineHtmlTag(line, options) {
5643
+ const start = line.match(/^\s*<[A-Za-z][A-Za-z0-9:-]*/);
5644
+ return Boolean(start && endOfHtmlTag(`${line} `, start[0].length, options) > line.length);
5645
+ }
5646
+ /** True when a continuation line contains the end of an HTML tag. */
5647
+ function endsHtmlTag(line, options) {
5648
+ return endOfHtmlTag(`${line} `, 0, options) <= line.length;
5649
+ }
5634
5650
  /** Scan one line for HTML and Janja constructs that affect indentation. */
5635
5651
  function scanLine(line, options, state) {
5636
5652
  const pieces = [];
@@ -5941,6 +5957,10 @@ function indentHtml(source, options) {
5941
5957
  const lines = source.split(/\r?\n/);
5942
5958
  let depth = 0;
5943
5959
  let sensitive = null;
5960
+ // Attribute lines sit one level under the tag; its closing delimiter aligns
5961
+ // with the opener. `openedElement` lets a split self-closing custom tag undo
5962
+ // the depth counted when its first line was scanned.
5963
+ let multilineTag = null;
5944
5964
  /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5945
5965
  let bodyBuf = null;
5946
5966
  const out = [];
@@ -5949,6 +5969,19 @@ function indentHtml(source, options) {
5949
5969
  for (const line of lines) {
5950
5970
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5951
5971
  const content = line.slice(leading);
5972
+ if (multilineTag) {
5973
+ const closesTag = endsHtmlTag(content, options);
5974
+ const delimiterOnly = /^(?:\/\s*)?>\s*$/.test(content);
5975
+ const lineDepth = multilineTag.baseDepth + (delimiterOnly ? 0 : 1);
5976
+ out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5977
+ if (closesTag) {
5978
+ if (multilineTag.openedElement && /\/\s*>\s*$/.test(content)) {
5979
+ depth = Math.max(0, depth - 1);
5980
+ }
5981
+ multilineTag = null;
5982
+ }
5983
+ continue;
5984
+ }
5952
5985
  const { pieces, prefixClosers } = scanLine(content, options, state);
5953
5986
  const activeSensitive = sensitive;
5954
5987
  const closesSensitive = activeSensitive !== null &&
@@ -5983,6 +6016,12 @@ function indentHtml(source, options) {
5983
6016
  const continuesSelfClosingTag = /^\/\s*>\s*$/.test(content);
5984
6017
  out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5985
6018
  applyDepth(pieces);
6019
+ if (!state.inComment && startsMultilineHtmlTag(content, options)) {
6020
+ multilineTag = {
6021
+ baseDepth: lineDepth,
6022
+ openedElement: pieces.some((piece) => piece.kind === 'open'),
6023
+ };
6024
+ }
5986
6025
  // The opening `<tag` was counted on an earlier line. A standalone `/>`
5987
6026
  // closes that element after this continuation line has been indented.
5988
6027
  if (continuesSelfClosingTag) {
package/dist/index.d.ts CHANGED
@@ -188,10 +188,14 @@ declare class StylesheetNode extends Traversal {
188
188
  constructor(body: SyntaxNode[], loc: Loc, strip: Strip);
189
189
  }
190
190
 
191
+ type IncludeLastState = {
192
+ active: boolean;
193
+ };
191
194
  declare class Compiler extends Context {
192
195
  options: Required<CompilerOptions>;
193
196
  private revalidate;
194
197
  private stream;
198
+ private includeLastState;
195
199
  template: string;
196
200
  state: Record<string, any>;
197
201
  private isRoot;
@@ -212,7 +216,7 @@ declare class Compiler extends Context {
212
216
  * only in stream mode, for the template's own top-level output.
213
217
  */
214
218
  flushable: boolean;
215
- constructor(options: Required<CompilerOptions>, cache?: LRUCache<CompiledTemplate>, revalidate?: boolean, stream?: boolean);
219
+ constructor(options: Required<CompilerOptions>, cache?: LRUCache<CompiledTemplate>, revalidate?: boolean, stream?: boolean, includeLastState?: IncludeLastState);
216
220
  compile(template: string, root?: boolean, partials?: Map<string, string>, blocks?: Map<string, BlockNode[]>, sources?: Map<string, string>, stylesheets?: Map<string, StylesheetNode[]>, stylesheetKey?: string): Promise<this>;
217
221
  get script(): Script;
218
222
  private generateCacheKey;
package/dist/index.esm.js CHANGED
@@ -1810,6 +1810,15 @@ class Parser extends Tokenizer {
1810
1810
  }
1811
1811
  }
1812
1812
 
1813
+ /**
1814
+ * Add the page-wide `include … last` registry and resolver to the root script.
1815
+ * The runtime walks rendered markers in reverse document order, so nested
1816
+ * partials and repeated includes inside loops are handled in render order.
1817
+ */
1818
+ function pushIncludeLastRuntime(compiler) {
1819
+ compiler.pushRaw(null, 'const il_=new Map();', 'let il_i_=0;', 'const il_n_=Math.random().toString(36).slice(2);', 'const il_re_=/\\u0000JLAST[a-z0-9]+:\\d+\\u0000/g;', 'const il_resolve_=async(v_,seen_=new Set())=>{', 'const matches_=[...v_.matchAll(il_re_)];', 'let cursor_=v_.length;', 'const parts_=[];', 'for(let i_=matches_.length-1;i_>=0;i_--){', 'const match_=matches_[i_],marker_=match_[0],start_=match_.index,item_=il_.get(marker_);', 'parts_.push(v_.slice(start_+marker_.length,cursor_));', 'if(item_&&!seen_.has(item_.path)){', 'const output_=await il_resolve_(await item_.render(),seen_);', 'if(!seen_.has(item_.path)){seen_.add(item_.path);parts_.push(output_);}', '}', 'cursor_=start_;', '}', 'parts_.push(v_.slice(0,cursor_));', 'return parts_.reverse().join("");', '};');
1820
+ }
1821
+
1813
1822
  function isStringLit(exp) {
1814
1823
  return exp.type === 'LIT' && typeof exp.value === 'string';
1815
1824
  }
@@ -1862,7 +1871,7 @@ const PRELOAD_LOC = {
1862
1871
  // Directives whose body is still the template's own top-level output
1863
1872
  const transparent = new Set(['IF', 'FOR']);
1864
1873
  class Compiler extends Context {
1865
- constructor(options, cache, revalidate = true, stream = false) {
1874
+ constructor(options, cache, revalidate = true, stream = false, includeLastState = { active: false }) {
1866
1875
  super();
1867
1876
  Object.defineProperty(this, "options", {
1868
1877
  enumerable: true,
@@ -1882,6 +1891,12 @@ class Compiler extends Context {
1882
1891
  writable: true,
1883
1892
  value: stream
1884
1893
  });
1894
+ Object.defineProperty(this, "includeLastState", {
1895
+ enumerable: true,
1896
+ configurable: true,
1897
+ writable: true,
1898
+ value: includeLastState
1899
+ });
1885
1900
  Object.defineProperty(this, "template", {
1886
1901
  enumerable: true,
1887
1902
  configurable: true,
@@ -2003,12 +2018,15 @@ class Compiler extends Context {
2003
2018
  }
2004
2019
  await this.parseTemplates();
2005
2020
  if (this.isRoot) {
2021
+ if (this.includeLastState.active) {
2022
+ pushIncludeLastRuntime(this);
2023
+ }
2006
2024
  if (this.partials.size || this.hasDynamicInclude) {
2007
2025
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
2008
2026
  // Alias the render data before partials shadow `c` with their argument.
2009
2027
  // `inc_` tracks `include … once` occurrences across the whole render,
2010
2028
  // root template and partials alike (they share this closure).
2011
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
2029
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_=new Set();', 'const p={');
2012
2030
  for (const [path, code] of this.partials) {
2013
2031
  this.pushRaw(null,
2014
2032
  // Partials take the context they should render with: plain include
@@ -2043,9 +2061,15 @@ class Compiler extends Context {
2043
2061
  }
2044
2062
  this.pushRaw(null, '];');
2045
2063
  }
2046
- this.flushable = this.isRoot && this.stream;
2064
+ // Last includes are resolved after the complete page has rendered, so
2065
+ // streaming must buffer the page to avoid flushing unresolved markers.
2066
+ this.flushable =
2067
+ this.isRoot && this.stream && !this.includeLastState.active;
2047
2068
  await this.compileNode(this.rootNode);
2048
2069
  this.flushable = false;
2070
+ if (this.isRoot && this.includeLastState.active) {
2071
+ this.pushRaw(null, 's=await il_resolve_(s);');
2072
+ }
2049
2073
  this.end();
2050
2074
  // Store in cache
2051
2075
  if (this.cache && root) {
@@ -2149,7 +2173,6 @@ class Compiler extends Context {
2149
2173
  const partials = new Map();
2150
2174
  const blocks = [];
2151
2175
  const stylesheets = [];
2152
- const includeLast = new Map();
2153
2176
  const traverse = (node) => {
2154
2177
  if (node.type === 'INCLUDE') {
2155
2178
  const include = node;
@@ -2158,13 +2181,7 @@ class Compiler extends Context {
2158
2181
  partials.set(include.val.value, include);
2159
2182
  }
2160
2183
  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
- }
2184
+ this.includeLastState.active = true;
2168
2185
  }
2169
2186
  }
2170
2187
  else {
@@ -2180,7 +2197,6 @@ class Compiler extends Context {
2180
2197
  node.traverse(traverse);
2181
2198
  };
2182
2199
  traverse(this.rootNode);
2183
- this.state.includeLast = includeLast;
2184
2200
  return {
2185
2201
  partials,
2186
2202
  blocks,
@@ -2234,7 +2250,7 @@ class Compiler extends Context {
2234
2250
  }
2235
2251
  async compilePartial(path, node, template) {
2236
2252
  try {
2237
- const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2253
+ const { code } = await new Compiler(this.options, undefined, true, false, this.includeLastState).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2238
2254
  this.partials.set(path, code);
2239
2255
  }
2240
2256
  catch {
@@ -3650,32 +3666,23 @@ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3650
3666
  const path = isStringLit(val)
3651
3667
  ? JSON.stringify(val.value)
3652
3668
  : 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})??"";`;
3669
+ const context = withExp
3670
+ ? `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`
3671
+ : TOP_CONTEXT;
3672
+ if (modifier === 'last' && isStringLit(val)) {
3673
+ // Mark every runtime occurrence. The root script resolves these markers
3674
+ // after rendering and keeps only the last visible occurrence per path.
3675
+ compiler.pushRaw(loc, '{', 'const ilm_="\\u0000JLAST"+il_n_+":"+(il_i_++)+"\\u0000";', `const ilc_=${context};`, `il_.set(ilm_,{path:${JSON.stringify(val.value)},render:async()=>{return (await p[${path}]?.(ilc_))??"";}});`, 's+=ilm_;', '}');
3676
+ return;
3677
+ }
3678
+ const emit = `s+=await p[${path}]?.(${context})??"";`;
3658
3679
  // `once`: render the first occurrence only. The registry lives in the root
3659
- // script's closure, so occurrences spread across different files (a root
3680
+ // script's closure, so occurrences spread across different files (the root
3660
3681
  // template and its partials) still deduplicate at runtime.
3661
3682
  if (modifier === 'once') {
3662
- compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3683
+ compiler.pushRaw(loc, `{const inc_p_=${path};if(!inc_.has(inc_p_)){inc_.add(inc_p_);s+=await p[inc_p_]?.(${context})??"";}}`);
3663
3684
  return;
3664
3685
  }
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
3686
  compiler.pushRaw(loc, emit);
3680
3687
  }
3681
3688
  const compilers$8 = {
@@ -5629,6 +5636,15 @@ const DIR_CLOSE = new Set([
5629
5636
  'endwith',
5630
5637
  'endstylesheet',
5631
5638
  ]);
5639
+ /** True when a line starts an HTML opening tag that continues on later lines. */
5640
+ function startsMultilineHtmlTag(line, options) {
5641
+ const start = line.match(/^\s*<[A-Za-z][A-Za-z0-9:-]*/);
5642
+ return Boolean(start && endOfHtmlTag(`${line} `, start[0].length, options) > line.length);
5643
+ }
5644
+ /** True when a continuation line contains the end of an HTML tag. */
5645
+ function endsHtmlTag(line, options) {
5646
+ return endOfHtmlTag(`${line} `, 0, options) <= line.length;
5647
+ }
5632
5648
  /** Scan one line for HTML and Janja constructs that affect indentation. */
5633
5649
  function scanLine(line, options, state) {
5634
5650
  const pieces = [];
@@ -5939,6 +5955,10 @@ function indentHtml(source, options) {
5939
5955
  const lines = source.split(/\r?\n/);
5940
5956
  let depth = 0;
5941
5957
  let sensitive = null;
5958
+ // Attribute lines sit one level under the tag; its closing delimiter aligns
5959
+ // with the opener. `openedElement` lets a split self-closing custom tag undo
5960
+ // the depth counted when its first line was scanned.
5961
+ let multilineTag = null;
5942
5962
  /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5943
5963
  let bodyBuf = null;
5944
5964
  const out = [];
@@ -5947,6 +5967,19 @@ function indentHtml(source, options) {
5947
5967
  for (const line of lines) {
5948
5968
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5949
5969
  const content = line.slice(leading);
5970
+ if (multilineTag) {
5971
+ const closesTag = endsHtmlTag(content, options);
5972
+ const delimiterOnly = /^(?:\/\s*)?>\s*$/.test(content);
5973
+ const lineDepth = multilineTag.baseDepth + (delimiterOnly ? 0 : 1);
5974
+ out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5975
+ if (closesTag) {
5976
+ if (multilineTag.openedElement && /\/\s*>\s*$/.test(content)) {
5977
+ depth = Math.max(0, depth - 1);
5978
+ }
5979
+ multilineTag = null;
5980
+ }
5981
+ continue;
5982
+ }
5950
5983
  const { pieces, prefixClosers } = scanLine(content, options, state);
5951
5984
  const activeSensitive = sensitive;
5952
5985
  const closesSensitive = activeSensitive !== null &&
@@ -5981,6 +6014,12 @@ function indentHtml(source, options) {
5981
6014
  const continuesSelfClosingTag = /^\/\s*>\s*$/.test(content);
5982
6015
  out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5983
6016
  applyDepth(pieces);
6017
+ if (!state.inComment && startsMultilineHtmlTag(content, options)) {
6018
+ multilineTag = {
6019
+ baseDepth: lineDepth,
6020
+ openedElement: pieces.some((piece) => piece.kind === 'open'),
6021
+ };
6022
+ }
5984
6023
  // The opening `<tag` was counted on an earlier line. A standalone `/>`
5985
6024
  // closes that element after this continuation line has been indented.
5986
6025
  if (continuesSelfClosingTag) {
package/dist/index.js CHANGED
@@ -1813,6 +1813,15 @@ ${suggestionText}`;
1813
1813
  }
1814
1814
  }
1815
1815
 
1816
+ /**
1817
+ * Add the page-wide `include … last` registry and resolver to the root script.
1818
+ * The runtime walks rendered markers in reverse document order, so nested
1819
+ * partials and repeated includes inside loops are handled in render order.
1820
+ */
1821
+ function pushIncludeLastRuntime(compiler) {
1822
+ compiler.pushRaw(null, 'const il_=new Map();', 'let il_i_=0;', 'const il_n_=Math.random().toString(36).slice(2);', 'const il_re_=/\\u0000JLAST[a-z0-9]+:\\d+\\u0000/g;', 'const il_resolve_=async(v_,seen_=new Set())=>{', 'const matches_=[...v_.matchAll(il_re_)];', 'let cursor_=v_.length;', 'const parts_=[];', 'for(let i_=matches_.length-1;i_>=0;i_--){', 'const match_=matches_[i_],marker_=match_[0],start_=match_.index,item_=il_.get(marker_);', 'parts_.push(v_.slice(start_+marker_.length,cursor_));', 'if(item_&&!seen_.has(item_.path)){', 'const output_=await il_resolve_(await item_.render(),seen_);', 'if(!seen_.has(item_.path)){seen_.add(item_.path);parts_.push(output_);}', '}', 'cursor_=start_;', '}', 'parts_.push(v_.slice(0,cursor_));', 'return parts_.reverse().join("");', '};');
1823
+ }
1824
+
1816
1825
  function isStringLit(exp) {
1817
1826
  return exp.type === 'LIT' && typeof exp.value === 'string';
1818
1827
  }
@@ -1865,7 +1874,7 @@ ${suggestionText}`;
1865
1874
  // Directives whose body is still the template's own top-level output
1866
1875
  const transparent = new Set(['IF', 'FOR']);
1867
1876
  class Compiler extends Context {
1868
- constructor(options, cache, revalidate = true, stream = false) {
1877
+ constructor(options, cache, revalidate = true, stream = false, includeLastState = { active: false }) {
1869
1878
  super();
1870
1879
  Object.defineProperty(this, "options", {
1871
1880
  enumerable: true,
@@ -1885,6 +1894,12 @@ ${suggestionText}`;
1885
1894
  writable: true,
1886
1895
  value: stream
1887
1896
  });
1897
+ Object.defineProperty(this, "includeLastState", {
1898
+ enumerable: true,
1899
+ configurable: true,
1900
+ writable: true,
1901
+ value: includeLastState
1902
+ });
1888
1903
  Object.defineProperty(this, "template", {
1889
1904
  enumerable: true,
1890
1905
  configurable: true,
@@ -2006,12 +2021,15 @@ ${suggestionText}`;
2006
2021
  }
2007
2022
  await this.parseTemplates();
2008
2023
  if (this.isRoot) {
2024
+ if (this.includeLastState.active) {
2025
+ pushIncludeLastRuntime(this);
2026
+ }
2009
2027
  if (this.partials.size || this.hasDynamicInclude) {
2010
2028
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
2011
2029
  // Alias the render data before partials shadow `c` with their argument.
2012
2030
  // `inc_` tracks `include … once` occurrences across the whole render,
2013
2031
  // root template and partials alike (they share this closure).
2014
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
2032
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_=new Set();', 'const p={');
2015
2033
  for (const [path, code] of this.partials) {
2016
2034
  this.pushRaw(null,
2017
2035
  // Partials take the context they should render with: plain include
@@ -2046,9 +2064,15 @@ ${suggestionText}`;
2046
2064
  }
2047
2065
  this.pushRaw(null, '];');
2048
2066
  }
2049
- this.flushable = this.isRoot && this.stream;
2067
+ // Last includes are resolved after the complete page has rendered, so
2068
+ // streaming must buffer the page to avoid flushing unresolved markers.
2069
+ this.flushable =
2070
+ this.isRoot && this.stream && !this.includeLastState.active;
2050
2071
  await this.compileNode(this.rootNode);
2051
2072
  this.flushable = false;
2073
+ if (this.isRoot && this.includeLastState.active) {
2074
+ this.pushRaw(null, 's=await il_resolve_(s);');
2075
+ }
2052
2076
  this.end();
2053
2077
  // Store in cache
2054
2078
  if (this.cache && root) {
@@ -2152,7 +2176,6 @@ ${suggestionText}`;
2152
2176
  const partials = new Map();
2153
2177
  const blocks = [];
2154
2178
  const stylesheets = [];
2155
- const includeLast = new Map();
2156
2179
  const traverse = (node) => {
2157
2180
  if (node.type === 'INCLUDE') {
2158
2181
  const include = node;
@@ -2161,13 +2184,7 @@ ${suggestionText}`;
2161
2184
  partials.set(include.val.value, include);
2162
2185
  }
2163
2186
  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
- }
2187
+ this.includeLastState.active = true;
2171
2188
  }
2172
2189
  }
2173
2190
  else {
@@ -2183,7 +2200,6 @@ ${suggestionText}`;
2183
2200
  node.traverse(traverse);
2184
2201
  };
2185
2202
  traverse(this.rootNode);
2186
- this.state.includeLast = includeLast;
2187
2203
  return {
2188
2204
  partials,
2189
2205
  blocks,
@@ -2237,7 +2253,7 @@ ${suggestionText}`;
2237
2253
  }
2238
2254
  async compilePartial(path, node, template) {
2239
2255
  try {
2240
- const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2256
+ const { code } = await new Compiler(this.options, undefined, true, false, this.includeLastState).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2241
2257
  this.partials.set(path, code);
2242
2258
  }
2243
2259
  catch {
@@ -3653,32 +3669,23 @@ ${suggestionText}`;
3653
3669
  const path = isStringLit(val)
3654
3670
  ? JSON.stringify(val.value)
3655
3671
  : 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})??"";`;
3672
+ const context = withExp
3673
+ ? `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`
3674
+ : TOP_CONTEXT;
3675
+ if (modifier === 'last' && isStringLit(val)) {
3676
+ // Mark every runtime occurrence. The root script resolves these markers
3677
+ // after rendering and keeps only the last visible occurrence per path.
3678
+ compiler.pushRaw(loc, '{', 'const ilm_="\\u0000JLAST"+il_n_+":"+(il_i_++)+"\\u0000";', `const ilc_=${context};`, `il_.set(ilm_,{path:${JSON.stringify(val.value)},render:async()=>{return (await p[${path}]?.(ilc_))??"";}});`, 's+=ilm_;', '}');
3679
+ return;
3680
+ }
3681
+ const emit = `s+=await p[${path}]?.(${context})??"";`;
3661
3682
  // `once`: render the first occurrence only. The registry lives in the root
3662
- // script's closure, so occurrences spread across different files (a root
3683
+ // script's closure, so occurrences spread across different files (the root
3663
3684
  // template and its partials) still deduplicate at runtime.
3664
3685
  if (modifier === 'once') {
3665
- compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3686
+ compiler.pushRaw(loc, `{const inc_p_=${path};if(!inc_.has(inc_p_)){inc_.add(inc_p_);s+=await p[inc_p_]?.(${context})??"";}}`);
3666
3687
  return;
3667
3688
  }
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
3689
  compiler.pushRaw(loc, emit);
3683
3690
  }
3684
3691
  const compilers$8 = {
@@ -5632,6 +5639,15 @@ export default script;
5632
5639
  'endwith',
5633
5640
  'endstylesheet',
5634
5641
  ]);
5642
+ /** True when a line starts an HTML opening tag that continues on later lines. */
5643
+ function startsMultilineHtmlTag(line, options) {
5644
+ const start = line.match(/^\s*<[A-Za-z][A-Za-z0-9:-]*/);
5645
+ return Boolean(start && endOfHtmlTag(`${line} `, start[0].length, options) > line.length);
5646
+ }
5647
+ /** True when a continuation line contains the end of an HTML tag. */
5648
+ function endsHtmlTag(line, options) {
5649
+ return endOfHtmlTag(`${line} `, 0, options) <= line.length;
5650
+ }
5635
5651
  /** Scan one line for HTML and Janja constructs that affect indentation. */
5636
5652
  function scanLine(line, options, state) {
5637
5653
  const pieces = [];
@@ -5942,6 +5958,10 @@ export default script;
5942
5958
  const lines = source.split(/\r?\n/);
5943
5959
  let depth = 0;
5944
5960
  let sensitive = null;
5961
+ // Attribute lines sit one level under the tag; its closing delimiter aligns
5962
+ // with the opener. `openedElement` lets a split self-closing custom tag undo
5963
+ // the depth counted when its first line was scanned.
5964
+ let multilineTag = null;
5945
5965
  /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5946
5966
  let bodyBuf = null;
5947
5967
  const out = [];
@@ -5950,6 +5970,19 @@ export default script;
5950
5970
  for (const line of lines) {
5951
5971
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5952
5972
  const content = line.slice(leading);
5973
+ if (multilineTag) {
5974
+ const closesTag = endsHtmlTag(content, options);
5975
+ const delimiterOnly = /^(?:\/\s*)?>\s*$/.test(content);
5976
+ const lineDepth = multilineTag.baseDepth + (delimiterOnly ? 0 : 1);
5977
+ out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5978
+ if (closesTag) {
5979
+ if (multilineTag.openedElement && /\/\s*>\s*$/.test(content)) {
5980
+ depth = Math.max(0, depth - 1);
5981
+ }
5982
+ multilineTag = null;
5983
+ }
5984
+ continue;
5985
+ }
5953
5986
  const { pieces, prefixClosers } = scanLine(content, options, state);
5954
5987
  const activeSensitive = sensitive;
5955
5988
  const closesSensitive = activeSensitive !== null &&
@@ -5984,6 +6017,12 @@ export default script;
5984
6017
  const continuesSelfClosingTag = /^\/\s*>\s*$/.test(content);
5985
6018
  out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5986
6019
  applyDepth(pieces);
6020
+ if (!state.inComment && startsMultilineHtmlTag(content, options)) {
6021
+ multilineTag = {
6022
+ baseDepth: lineDepth,
6023
+ openedElement: pieces.some((piece) => piece.kind === 'open'),
6024
+ };
6025
+ }
5987
6026
  // The opening `<tag` was counted on an earlier line. A standalone `/>`
5988
6027
  // closes that element after this continuation line has been indented.
5989
6028
  if (continuesSelfClosingTag) {
package/dist/index.min.js CHANGED
@@ -1 +1 @@
1
- !function(e){"use strict";class t{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=new Map,this.maxSize=e.maxSize??1e3,this.ttl=e.ttl??36e5,this.stats={hits:0,misses:0,evictions:0}}get(e){const t=this.cache.get(e);return t?this.ttl>0&&Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),this.stats.misses++,null):(this.cache.delete(e),this.cache.set(e,t),t.hits++,this.stats.hits++,t.value):(this.stats.misses++,null)}peek(e){const t=this.cache.get(e);return!t||this.ttl>0&&Date.now()-t.timestamp>this.ttl?null:t.value}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){const e=this.cache.keys().next().value;void 0!==e&&(this.cache.delete(e),this.stats.evictions++)}this.cache.set(e,{value:t,timestamp:Date.now(),hits:0})}has(e){const t=this.cache.get(e);return!!t&&(!(this.ttl>0&&Date.now()-t.timestamp>this.ttl)||(this.cache.delete(e),!1))}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.stats={hits:0,misses:0,evictions:0}}invalidate(e){if(e)for(const t of this.cache.keys())e(t)&&this.cache.delete(t);else this.clear()}getStats(){return{...this.stats,size:this.cache.size,hitRate:this.stats.hits+this.stats.misses>0?this.stats.hits/(this.stats.hits+this.stats.misses):0}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}}function n(e,t,n){const i=[];if("ExpError"===e&&(t.includes("Unexpected end of expression")&&i.push({message:"The expression is incomplete. Make sure you have closed all parentheses, brackets, and quotes.",fix:"Check for missing closing characters: ), ], }"}),t.includes('Expected "RP" after "LP"')&&i.push({message:"Missing closing parenthesis in your expression.",fix:"Add a closing parenthesis ) to match the opening one.",example:"(foo.bar) instead of (foo.bar"}),t.includes("No left operand")&&i.push({message:"An operator is missing its left operand.",fix:"Add a value or variable before the operator.",example:"x + 1 instead of + 1"}),t.includes("No right operand")&&i.push({message:"An operator is missing its right operand.",fix:"Add a value or variable after the operator.",example:"x + 1 instead of x +"}),t.includes('Expected "ID" after "PIPE"')&&i.push({message:"The pipe operator | must be followed by a filter name.",fix:"Add a filter name after the pipe.",example:"value|upper instead of value|"}),t.includes('Expected "ID" after "DOT"')&&i.push({message:"The dot operator . must be followed by a property name.",fix:"Add a property name after the dot.",example:"object.property instead of object."}),t.includes("Left operand of assignment must be an identifier")&&i.push({message:"Assignment targets must be valid identifiers.",fix:"Use a simple variable name or sequence of variable names.",example:"x = 1 or (a, b) = [1, 2]"}),t.includes("Expected test expression")&&i.push({message:"The conditional expression is missing its test condition.",fix:"Add a condition after the if keyword.",example:"if x > 0 then y else z"}),t.includes("Expected alternative expression")&&i.push({message:"The conditional expression is missing its else clause.",fix:"Add an alternative expression after then.",example:"if x > 0 then y else z"}),t.startsWith("Unexpect")&&i.push({message:"An unexpected character was found in the expression.",fix:"Check for typos or invalid characters in your expression."})),"CompileError"===e){if(t.includes("Unclosed")){const e=t.match(/Unclosed "([^"]+)"/),n=e?e[1]:"marker";i.push({message:`The ${n} marker is not closed properly.`,fix:`Add the closing marker for ${n}.`,example:"{%"===n?"{% ... %}":"{#"===n?"{# ... #}":"{{ ... }}"})}t.includes("Unexpected")&&i.push({message:"An unexpected token was found in the template.",fix:"Check your template syntax and ensure all markers are properly formatted."})}return n&&i.push({message:"Context information:",fix:n}),i}class i extends SyntaxError{constructor(e,t,n,r){super(e),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:r}),this.name="CompileError",i.captureStackTrace?.(this,this.constructor)}get details(){const e=this.loc?function(e,t,{start:{line:n,column:i},end:{line:r,column:s}}){const o=[],a=new Set,l=e=>{a.add(e-2),a.add(e-1),a.add(e),a.add(e+1),a.add(e+2)},c=t.split("\n"),u=String(c.length).length+2;let p=0;c.forEach((e,t)=>{if(e){if(o.push(`${`${t+1}│ `.padStart(u," ")}${e}`),n===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(i-1)}^${n===r&&s>i+1?`${" ".repeat(s-i-2)}^`:""}`;/\S/.test(e)&&o.push(e),l(++p+t)}if(n!==r&&r===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(s-1)}${"^".repeat(1)}`;/\S/.test(e)&&o.push(e),l(++p+t)}}});const h=`${" ".repeat(u)}...`;return`${e}\n\n${o.map((e,t)=>a.has(t)?e:h).reduce((e,t)=>t===h&&e.at(-1)===t?e:[...e,t],[]).join("\n")}\n`}(this.message,this.src,this.loc):this.message;return function(e,t,i,r){const s=n(e,t,r);return 0===s.length?i:`${i}\n\nSuggestions:\n${s.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n")}`}(this.name,this.message,e,this.context)}get suggestions(){return n(this.name,this.message,this.context)}}const r=/[&<>"']/,s=/[&<>"']/g,o={"&":"&amp;",'"':"&#34;","'":"&#39;","<":"&lt;",">":"&gt;"},a=e=>o[e];function l(e){const t="string"==typeof e?e:`${e}`;return r.test(t)?t.replace(s,a):t}class c extends String{constructor(e){super(`${e}`)}}function u(e={}){return{maxIncludeDepth:e.maxIncludeDepth??100,maxLoopIterations:e.maxLoopIterations,maxCallDepth:e.maxCallDepth,timeoutMs:e.timeoutMs}}class p{constructor(e={}){Object.defineProperty(this,"allowedGlobals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cspNonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.allowedGlobals=new Set(e.allowedGlobals||[]),this.cspNonce=e.cspNonce}sanitizeGlobals(e){const t={};for(const[n,i]of Object.entries(e))this.allowedGlobals.has(n)&&(t[n]=i);return t}validateExpression(e){const t=[/\bprocess\b/,/\brequire\b/,/\bimport\b/,/\bexport\b/,/\beval\b/,/\bFunction\b/,/\b__proto__\b/,/\bconstructor\b/];for(const n of t)if(n.test(e))return!1;return!0}createSecureContext(e){return{...this.sanitizeGlobals(e),Math:Math,Date:Date,JSON:JSON}}getCSPNonce(){return this.cspNonce}generateCSPHeaders(){const e={};return this.cspNonce&&(e["Content-Security-Policy"]=`script-src 'nonce-${this.cspNonce}'`),e}}function h(e,t=new WeakSet){if(null==e)return"";if(e instanceof c)return`${e}`;if("object"==typeof e){if(t.has(e))return"";t.add(e);return(Array.isArray(e)?e:Object.values(e)).map(e=>h(e,t)).join("")}return l(e)}class f{auditTemplate(e){const t=[],n=[{pattern:/\beval\s*\(/,type:"dangerous-eval",message:"Use of eval() is dangerous and should be avoided",severity:"critical"},{pattern:/\bFunction\s*\(/,type:"dangerous-function",message:"Use of Function constructor is dangerous",severity:"critical"},{pattern:/\brequire\s*\(/,type:"require-usage",message:"Direct require() usage in templates is unsafe",severity:"high"},{pattern:/\bimport\s*\(/,type:"dynamic-import",message:"Dynamic import() usage in templates may be unsafe",severity:"high"}];for(const{pattern:i,type:r,message:s,severity:o}of n){const n=e.match(i);n&&t.push({type:r,message:s,location:`at index ${n.index}`,severity:o})}return{issues:t,severity:this.calculateOverallSeverity(t)}}calculateOverallSeverity(e){if(0===e.length)return"low";const t={critical:4,high:3,medium:2,low:1},n=Math.max(...e.map(e=>t[e.severity]));return Object.entries(t).find(([,e])=>e===n)[0]}}const d=new WeakMap;function b(e,t=!1){return t?`\0stream:${e}`:e}function m(e){let t=d.get(e);if(void 0===t){const{trimWhitespace:n,stripComments:i,commentOpen:r,commentClose:s,directiveOpen:o,directiveClose:a,outputOpen:l,outputClose:c,preloadIncludes:p}=e,{maxIncludeDepth:h,maxLoopIterations:f,maxCallDepth:b}=u(e.security);t=JSON.stringify([n,i,r,s,o,a,l,c,h,f??null,b??null,p]),d.set(e,t)}return t}const y="c",g="f",w="r_";class v{constructor(){Object.defineProperty(this,"mappings",{enumerable:!0,configurable:!0,writable:!0,value:[]})}addMapping(e,t){this.mappings.push({source:e,target:t})}getSourceLoc({line:e,column:t}){return this.mappings.filter(({target:{start:n,end:i}})=>n.line<=e&&i.line>=e&&(n.line<e||n.column<=t)&&(i.line>e||i.column>=t)).map(({source:e})=>e)}}class x extends v{constructor(){super(...arguments),Object.defineProperty(this,"codeParts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"codeLength",{enumerable:!0,configurable:!0,writable:!0,value:0})}get code(){return this.codeParts.join("")}set code(e){this.codeParts=[e],this.codeLength=e.length}get script(){return new Function(y,"e",g,"w",this.code)}checkpoint(){return[this.codeParts.length,this.mappings.length,this.codeLength]}rollback(e){const[t,n,i]=e;this.codeParts.length=t,this.mappings.length=n,this.codeLength=i}start(e=!0){this.pushRaw(null,"return(async()=>{",`let s="",${w};`),e&&this.pushRaw(null,"const u_=(n)=>{throw new Error('Unknown filter \"'+n+'\"')};")}end(){this.pushRaw(null,"return s;","})();")}pushRaw(e,...t){const n=this.codeLength;for(const e of t)this.codeParts.push(e),this.codeLength+=e.length;e&&this.addMapping(e,{start:{line:1,column:n},end:{line:1,column:this.codeLength}})}pushStr(e,t){t&&this.pushRaw(e,`s+=${JSON.stringify(t)};`)}pushFlush(){this.pushRaw(null,'if(s.length>1024){await w(s);s="";}')}pushVar(e,t){this.pushRaw(e,`s+=e(${t});`)}}class O extends x{constructor(){super(...arguments),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:y}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:[y]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0})}checkpoint(){return[super.checkpoint(),this.context,[...this.stack]]}rollback(e){const[t,n,i]=e;super.rollback(t),this.context=n,this.stack=i}in(){return this.context=`${this.context}_${this.index++}`,this.stack.push(this.context),this.context}out(){this.context!==y&&(this.stack.pop(),this.context=this.stack.at(-1))}}class E extends SyntaxError{constructor(e,t,n){super(e),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="ExpError",E.captureStackTrace?.(this,this.constructor)}get suggestions(){return n(this.name,this.message,this.context)}get details(){const{suggestions:e}=this;if(0===e.length)return this.message;const t=e.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n");return`${this.message}\n\nSuggestions:\n${t}`}}function P(e,t){const n=(e.match(/\n/g)||[]).length;if(n>0){t.line+=n;const i=e.lastIndexOf("\n");t.column=e.length-i}else t.column+=e.length;return{line:t.line,column:t.column}}const j={and:"AND",or:"OR",not:"NOT",is:"IS",eq:"EQ",ne:"NE",gt:"GT",lt:"LT",ge:"GE",le:"LE",in:"IN",ni:"NI",of:"OF",with:"WITH","+":"ADD","-":"SUB","*":"MUL","/":"DIV","%":"MOD",if:"IF",else:"ELSE",true:"LIT",false:"LIT",null:"LIT",undefined:"LIT","|":"PIPE","=":"ASSIGN","(":"LP",")":"RP",",":"COMMA",".":"DOT"},T=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(e){return"string"==typeof e&&T.has(e)}const k={n:"\n",t:"\t",r:"\r","\\":"\\",'"':'"',"'":"'","`":"`"};function S(e){switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return;default:return e}}class I{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}tokenize(e,t){for(this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=[];this.index<this.val.length;){const e=this.val[this.index];if(N(e))"\n"===e?(this.line++,this.column=1):this.column++,this.index++;else if("'"!==e&&'"'!==e&&"`"!==e)if(L(e)||"-"===e&&L(this.val[this.index+1]??"")&&!this.afterOperand())this.readNumber(e);else if(R(e))this.readIdentifier(e);else{if(!C(e))throw new E(`Unexpected "${e}"`,{start:{line:this.line,column:this.column},end:{line:this.line,column:this.column+1}});this.readSymbol(e)}else this.readString(e)}return this.tokens}afterOperand(){const e=this.tokens.at(-1)?.type;return"ID"===e||"LIT"===e||"RP"===e}readString(e){let t="",n="",i=!1;const r={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const r=this.val[this.index];if(i)t+=k[r]??`\\${r}`,n+=r,i=!1;else if("\\"===r)n+=r,i=!0;else{if(r===e)break;t+=r,n+=r}this.index++}this.index++,this.tokens.push({type:"LIT",value:t,loc:{start:r,end:P(`${e}${n}${e}`,this)},raw:`${e}${n}${e}`})}readNumber(e){let t=e,n=!1;const i={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(L(e))t+=e;else{if("."!==e||n)break;t+=e,n=!0}this.index++}this.tokens.push({type:"LIT",value:Number.parseFloat(t),loc:{start:i,end:P(t,this)},raw:t})}readIdentifier(e){let t=e;const n={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(!D(e))break;t+=e,this.index++}if($(t))throw new E(`"${t}" is not allowed in expressions`,{start:n,end:{line:this.line,column:this.column+t.length}});const i=Object.prototype.hasOwnProperty.call(j,t)?j[t]:"ID";this.tokens.push({type:i,value:"LIT"===i?S(t):t,loc:{start:n,end:P(t,this)},raw:t})}readSymbol(e){const t={line:this.line,column:this.column};this.index++,this.tokens.push({type:j[e],value:e,loc:{start:t,end:P(e,this)},raw:e})}}function N(e){return/\s/.test(e)}function C(e){return/[+\-*/%|=(),.]/.test(e)}function L(e){return/\d/.test(e)}function R(e){return/[a-z_$]/i.test(e)}function D(e){return/[\w$]/.test(e)}const A={COMMA:5,IF:10,ELSE:10,ASSIGN:15,LP:20,RP:20,OR:25,AND:30,IS:40,EQ:40,NE:40,GT:40,LT:40,GE:40,LE:40,IN:40,NI:40,OF:40,WITH:40,ADD:50,SUB:50,MUL:60,DIV:60,MOD:60,NOT:70,PIPE:80,DOT:90,ID:90,LIT:90};class M{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}parse(e,t){return this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=(new I).tokenize(e,t),this.val?this.parseExp():null}parseExp(e){let t=null;for(;;){const n=this.next();if(!n)break;const i=e?.(n);if("BACK"===i){this.back();break}if("BREAK"===i)break;if(t&&F(n),"LP"===n.type){if(!this.peek())throw new E("Unexpected end of expression",n.loc);const e=this.parseSequence(),i=this.consume("RP");if(!i)throw new E('Expected "RP" after "LP"',n.loc);t={...n,type:"SEQ",elements:e,loc:{start:n.loc.start,end:i.loc.end}};continue}if("NOT"!==n.type){if("ID"===n.type){t={...n,type:"ID",value:n.value},this.match("DOT")&&(t.path=this.parsePath());const e=this.consume("LP");if(e){if(t.args=this.parseSequence(),!this.consume("RP"))throw new E('Expected "RP" after "LP"',e.loc);continue}continue}if("LIT"!==n.type){if("IF"===n.type){const e=this.parseExp(e=>"ELSE"===e.type||X(n,e)?"BACK":void 0);if(!e)throw new E("Expected test expression",n.loc);if(t={...n,type:"IF",test:e,consequent:t},this.consume("ELSE")){const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E("Expected alternative expression",n.loc);t.alternative=e}continue}if(_(n.type)){if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);"ASSIGN"===n.type&&W(t,n);const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E(`No right operand for "${n.type}"`,n.loc);t={...n,type:n.type,left:t,right:e};continue}if("PIPE"!==n.type){this.back();break}if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);if(!this.match("ID"))throw new E('Expected "ID" after "PIPE"',n.loc);t={...n,type:"PIPE",left:t,right:this.parsePipe()}}else t={...n,type:"LIT"}}else{if(!this.peek())throw new E("Unexpected end of expression",n.loc);t={...n,type:"NOT",argument:this.parseExp(e=>X(n,e)?"BACK":void 0)}}}return t}parsePath(){const e=[];for(;;){const t=this.consume("DOT");if(!t)break;const n=this.next();if(!n)throw new E('Expected "ID" after "DOT"',t.loc);if("ID"!==n.type)throw new E('Expected "ID" after "DOT"',t.loc);e.push({...n,type:"ID",value:n.value})}return e}parseSequence(){const e=[];for(;!this.match("RP");){const t=this.parseExp(e=>"COMMA"===e.type?"BREAK":void 0);if(!t)break;e.push(t)}return e}parsePipe(){const e=this.next(),t={...e,type:"ID",value:e.value},n=this.consume("LP");if(n&&(t.args=this.parseSequence(),!this.consume("RP")))throw new E('Expected "RP" after "LP"',n.loc);return t}next(){return this.tokens[this.index++]??null}back(){return this.tokens[this.index--]}peek(){return this.tokens.at(this.index)??null}match(e){return this.peek()?.type===e}consume(e){if(this.match(e))return this.next()}}const U=new Set(["AND","OR","IS","EQ","NE","GT","LT","GE","LE","IN","NI","OF","WITH","ADD","SUB","MUL","DIV","MOD","ASSIGN"]);function _(e){return U.has(e)}function F(e){if("ID"===e.type||"LIT"===e.type||"LP"===e.type)throw new E(`Unexpected "${e.raw??e.value}"`,e.loc)}function W(e,t){if("SEQ"===e.type){if(e.elements.some(e=>"ID"!==e.type||e.path||e.args))throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}else if("ID"!==e.type||e.path||e.args)throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}function X(e,t){return"LP"!==t.type&&A[e.type]>A[t.type]}class G{constructor(){Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}traverse(e){this.body?.forEach(e)}}class z extends G{constructor(e,t){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEMPLATE"})}}var B;function q(e){return e.replace(/\\([{}])/g,"$1")}e.TokenType=void 0,(B=e.TokenType||(e.TokenType={})).TEXT="TEXT",B.OUTPUT="OUTPUT",B.DIRECTIVE="DIRECTIVE",B.COMMENT="COMMENT";class K{constructor(t){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenPatterns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"markerIndices",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1});const{commentOpen:n,commentClose:i,directiveOpen:r,directiveClose:s,outputOpen:o,outputClose:a}=this.options;this.tokenPatterns=[[e.TokenType.COMMENT,n,i],[e.TokenType.DIRECTIVE,r,s],[e.TokenType.OUTPUT,o,a]].sort(([,e],[,t])=>e.length>t.length?-1:1),this.markerIndices=new Map;for(const[,e]of this.tokenPatterns)e.length>0&&this.markerIndices.set(e[0],this.markerIndices.get(e[0])||0)}tokenize(e){for(this.template=e,this.length=e.length,this.index=0,this.line=1,this.column=1,this.tokens=[];this.index<this.length;)this.consumeSpecialTokens()||this.consumeTextToken();return this.tokens}consumeSpecialTokens(){return this.tokenPatterns.some(([t,n,r])=>{if(!this.lookahead(n))return!1;const s={line:this.line,column:this.column},o=this.template.indexOf(r,this.index+n.length);if(-1===o)throw new i(`Unclosed "${n}"`,this.template,{start:s,end:P(n,{...s})});const a=this.lookahead("-",n.length),l="-"===this.template[o-1],c=this.template.slice(this.index+n.length+ +a,o-+l),u=P(this.template.slice(this.index,this.index=o+r.length),this),p={type:t,val:q(c),strip:{before:a,after:l},loc:{start:s,end:u}};if(t===e.TokenType.DIRECTIVE){let e=0,t="";for(;e<c.length;){const n=c[e];if(/\S/.test(n))t+=n;else if(t)break;e++}Object.assign(p,{name:t,expression:e===c.length||/^\s*$/m.test(c.slice(e+1))?null:{val:c.slice(e+1),loc:{start:P(c.slice(0,e+1),P(`${n}${a?"-":""}`,{...s})),end:{line:this.line,column:this.column-r.length-+l}}}})}return this.tokens.push(p),!0})}consumeTextToken(){const t=this.findNextSpecialIndex(),n={line:this.line,column:this.column},i=this.template.slice(this.index,t);this.tokens.push({type:e.TokenType.TEXT,val:q(i),loc:{start:n,end:P(i,this)},strip:{}}),this.index=t}lookahead(e,t=0){return this.template.startsWith(e,this.index+t)}findNextSpecialIndex(){const{outputOpen:e,directiveOpen:t,commentOpen:n}=this.options;let i=this.length;for(let r=this.index;r<this.length;r++){if(this.template.startsWith(n,r)){i=r;break}if(this.template.startsWith(t,r)){i=r;break}if(this.template.startsWith(e,r)){i=r;break}}return i}}class H extends K{constructor(){super(...arguments),Object.defineProperty(this,"expParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}parse(t){this.tokenize(t),this.tokens.forEach((t,n)=>{t.type===e.TokenType.TEXT&&(this.tokens[n-1]?.strip?.after&&(t.strip.start=!0),this.tokens[n+1]?.strip?.before&&(t.strip.end=!0))});const n=this.tokens[0]?.loc.start??{line:1,column:1},i=this.tokens.at(-1)?.loc.end??{line:1,column:1};return this.expParser=new M,this.cursor=0,new z(this.parseUntil(),{start:n,end:i})}parseUntil(t){const n=[];let i=null;for(;;){const r=this.peek();if(!r||r.type===e.TokenType.DIRECTIVE&&t&&this.match(t,r))break;i?.strip?.after&&r.type===e.TokenType.TEXT&&(r.strip.start=!0),r.strip?.before&&i?.type===e.TokenType.TEXT&&(i.strip.end=!0);let s=this.options.parsers[r.name?.toLowerCase()??r.type?.toLowerCase()];"string"==typeof s&&(s=this.options.parsers[s]),s||(s=this.options.parsers.unknown);const{cursor:o}=this,a=s?.(r,this);if(a)for(;;){const{value:e,done:t}=a.next();if(t)break;"NEXT"===e?this.advance():e&&n.push(e)}this.cursor===o&&this.advance(),i=r}return n}parseExp({val:e,loc:t}){try{return this.expParser.parse(e,t)}catch(e){this.options.debug(e.loc?new i(e.message,this.template,e.loc):e)}}peek(){return this.tokens.at(this.cursor)??null}advance(){this.cursor++}match(e,t=this.peek()){return e.includes(t?.name?.toLowerCase())}emitExpErr({name:e,loc:t},n=!0){this.options.debug(new i(n?`"${e}" requires expression`:`"${e}" should not have expression`,this.template,t))}}function J(e){return"LIT"===e.type&&"string"==typeof e.value}class V extends G{constructor(e,t,n,i=null,r=null){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"withExp",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"modifier",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"INCLUDE"})}}const Q={start:{line:1,column:1},end:{line:1,column:1}},Y=new Set(["IF","FOR"]);class Z extends O{constructor(e,t,n=!0,i=!1){super(),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"revalidate",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isRoot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rootNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partials",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheets",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheetKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sources",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hasDynamicInclude",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"flushable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.cache=t}async compile(e,t=!0,n=new Map,i=new Map,r=new Map,s=new Map,o="\0root"){this.template=e,this.isRoot=t,this.partials=n,this.blocks=i,this.stylesheets=s,this.stylesheetKey=o,this.sources=r,this.hasDynamicInclude=!1;const a=this.generateCacheKey(e);if(this.cache&&t){const e=this.cache.get(a);if(e){if(e.fingerprint===this.fingerprint()&&await this.isFresh(e))return this.code=e.code,this.mappings=e.mappings,this.compiled=e,this;this.cache.delete(a)}}if(this.rootNode=new H(this.options).parse(e),this.state={},this.start(this.isRoot),this.isRoot&&(this.pushResourceLimitCounters(),this.pushRaw(null,"let ss_u=0;")),await this.parseTemplates(),this.isRoot){if(this.partials.size||this.hasDynamicInclude){const{maxIncludeDepth:e}=u(this.options.security);this.pushRaw(null,`const tc_=${y};`,"let d_=0;","const inc_={};","const p={");for(const[t,n]of this.partials)this.pushRaw(null,`${JSON.stringify(t)}:async(c)=>{`,`if(d_>=${e})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(t)} are nested too deeply`)});`,"d_++;","try{return await(async()=>{",n,"})();}finally{d_--;}","},");this.pushRaw(null,"};")}if(this.blocks.size){this.pushRaw(null,"const b={");for(const[e,t]of this.blocks){this.pushRaw(null,`${JSON.stringify(e)}:{`,"u:0,","s:["),this.state.block=e;for(const e of t)this.pushRaw(null,"async()=>{",'let s="";'),await this.compileNodes(e.body),this.pushRaw(null,"return s;","},");this.state.block=void 0,this.pushRaw(null,"],","},")}this.pushRaw(null,"};")}this.pushRaw(null,"const ss_=[");for(const[,e]of this.stylesheets){this.pushRaw(null,"async()=>{",'let s="";');for(const t of e)await this.compileNodes(t.body);this.pushRaw(null,"return s;","},")}this.pushRaw(null,"];")}return this.flushable=this.isRoot&&this.stream,await this.compileNode(this.rootNode),this.flushable=!1,this.end(),this.cache&&t&&(this.compiled={code:this.code,mappings:this.mappings,sources:this.sources,fingerprint:this.fingerprint()},this.cache.set(a,this.compiled)),this}get script(){var e;return this.compiled?(e=this.compiled).script??(e.script=super.script):super.script}generateCacheKey(e){return b(e,this.stream)}fingerprint(){return m(this.options)}pushResourceLimitCounters(){const{maxLoopIterations:e,maxCallDepth:t}=u(this.options.security);null!=e&&this.pushRaw(null,"let li_=0;"),null!=t&&this.pushRaw(null,"let cd_=0;")}async isFresh({sources:e}){if(!this.revalidate)return!0;try{for(const[t,n]of e)if(await this.options.loader(t)!==n)return!1}catch{return!1}return!0}async parseTemplates(){const{partials:e,blocks:t,stylesheets:n}=this.collectPartialsAndBlocks();if(this.isRoot)for(const t of this.options.preloadIncludes)e.has(t)||e.set(t,new V({type:"LIT",value:t,loc:Q},Q,{before:!1,after:!1}));for(const[t,n]of e)if(!this.partials.has(t)){let e;try{e=await this.options.loader(t)}catch{throw new i(`Failed to load template from "${t}"`,this.template,n.loc)}this.sources.set(t,e??""),this.partials.set(t,""),e&&await this.compilePartial(t,n,e)}for(const e of t){const{val:{value:t}}=e;this.blocks.has(t)||this.blocks.set(t,[]),this.blocks.get(t).push(e)}n.length&&!this.stylesheets.has(this.stylesheetKey)&&this.stylesheets.set(this.stylesheetKey,n)}collectPartialsAndBlocks(){const e=new Map,t=[],n=[],i=new Map,r=s=>{if("INCLUDE"===s.type){const t=s;if(J(t.val)){if(e.has(t.val.value)||e.set(t.val.value,t),"last"===t.modifier){const e=i.get(t.val.value);e?e.total+=1:i.set(t.val.value,{total:1,emitted:0})}}else this.hasDynamicInclude=!0}"BLOCK"===s.type&&t.push(s),"STYLESHEET"===s.type&&n.push(s),s.traverse(r)};return r(this.rootNode),this.state.includeLast=i,{partials:e,blocks:t,stylesheets:n}}async compileNode(e){if("TEMPLATE"===e.type){for(const t of e.body)await this.compileNode(t),this.flushable&&"TEXT"!==t.type&&this.pushFlush();return}let t=this.options.compilers[e.type];"string"==typeof t&&(t=this.options.compilers[t]),t||(t=this.options.compilers.UNKNOWN);const n=this.checkpoint(),{flushable:r}=this;Y.has(e.type)||(this.flushable=!1);try{await(t?.(e,this))}catch(t){if(this.flushable=r,"CompileError"===t?.name)throw t;this.rollback(n),this.options.debug(new i(`Invalid "${e.type.toLowerCase()}" directive`,this.template,e.loc))}this.flushable=r}async compileNodes(e){for(const t of e)await this.compileNode(t)}async compilePartial(e,t,n){try{const{code:t}=await new Z(this.options).compile(n,!1,this.partials,this.blocks,this.sources,this.stylesheets,e);this.partials.set(e,t)}catch{this.options.debug(new i("Failed to compile template",this.template,t.loc))}}}var ee=Object.freeze({__proto__:null,abs:function(e=0){return Math.abs(e)},add:function(e=0,t=0){return e+t},capitalize:function(e=""){return e.replace(/\b\w/g,e=>e.toUpperCase())},ceil:function(e=0){return Math.ceil(e)},chunk:function(e,t){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},compact:function(e=[]){return e.filter(e=>null!=e)},currency:function(e,t="USD",n="en-US"){return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(e)},date:function(e,t="ISO"){const n=e instanceof Date?e:new Date(e);if(isNaN(n.getTime()))return"";switch(t){case"ISO":default:return n.toISOString();case"date":return n.toISOString().split("T")[0];case"time":return n.toTimeString().split(" ")[0];case"locale":return n.toLocaleDateString();case"locale-time":return n.toLocaleTimeString();case"locale-datetime":return n.toLocaleString()}},defaults:function(e,t){return{...t,...e}},delay:async function(e,t){return await new Promise(e=>setTimeout(e,t)),e},div:function(e=0,t=1){return e/t},entries:function(e={}){return Object.entries(e)},escape:l,even:function(e=0){return+e%2==0},fallback:function(e,t,n=!1){return n?e||t:e??t},fetchUrl:async function(e,t={}){return(await fetch(e,t)).text()},first:function(e=[]){return[...e][0]},fixed:function(e,t=2){return Number(e).toFixed(t)},get:function(e,...t){return t.reduce((e,t)=>e&&"object"==typeof e&&!$(t)&&t in e?e[t]:void 0,e)},groupby:function(e=[],t){return e.reduce((e,n)=>{const i=n[t];return{...e,[i]:[...e[i]||[],n]}},{})},invert:function(e){return Object.entries(e).reduce((e,[t,n])=>({...e,[String(n)]:t}),{})},join:function(e=[],t=""){return[...e].join(t)},json:function(e=null,t=0){return new c(JSON.stringify(e,null,t))},keys:function(e={}){return Object.keys(e)},last:function(e=[]){return[...e].reverse()[0]},length:function(e=""){return e.length},lower:function(e=""){return e.toLowerCase()},map:function(e=[],t,n){return e.map(e=>$(t)?n:e[t]??n)},max:function(e=0,...t){return Math.max(e,...t)},merge:function(e,...t){return Object.assign({},e,...t)},min:function(e=0,...t){return Math.min(e,...t)},mul:function(e=0,t=1){return e*t},odd:function(e=0){return+e%2==1},omit:function(e={},...t){return Object.entries(e).reduce((e,[n,i])=>t.includes(n)?e:{...e,[n]:i},{})},percent:function(e,t=0){return`${(100*e).toFixed(t)}%`},pick:function(e={},...t){return t.reduce((t,n)=>$(n)?t:{...t,[n]:e[n]},{})},pluck:function(e,t){return e.map(e=>e[t])},repeat:function(e="",t=0){return e.repeat(t)},replace:function(e="",t,n){return e.replace(new RegExp(t,"g"),n)},reverse:function(e=[]){return Array.isArray(e)?[...e].reverse():[...e].reverse().join("")},round:function(e,t=0){return Number(`${Math.round(Number(`${e}e${t}`))}e-${t}`)},safe:function(e=""){return new c(e)},shuffle:function(e){const t=[...e];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t},slice:function(e="",t=0,n){return e.slice(t,n)},slugify:function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")},sort:function(e=[]){return Array.isArray(e)?[...e].sort():[...e].sort().join("")},split:function(e="",t=""){return e.split(t)},stripTags:function(e){return e.replace(/<[^>]*>/g,"")},sub:function(e=0,t=0){return e-t},sum:function(e=[]){return e.reduce((e,t)=>e+t,0)},timeAgo:function(e){const t=e instanceof Date?e:new Date(e),n=new Date,i=Math.floor((n.getTime()-t.getTime())/1e3),r=[{label:"year",seconds:31536e3},{label:"month",seconds:2592e3},{label:"day",seconds:86400},{label:"hour",seconds:3600},{label:"minute",seconds:60}];for(const e of r){const t=Math.floor(i/e.seconds);if(t>=1)return`${t} ${e.label}${t>1?"s":""} ago`}return"just now"},trim:function(e=""){return e.trim()},truncate:function(e="",t=0,n="..."){return e.slice(0,t)+(e.length>t?n:"")},unique:function(e=""){return Array.isArray(e)?Array.from(new Set(e)):Array.from(new Set(e)).join("")},upper:function(e=""){return e.toUpperCase()},urldecode:function(e=""){return decodeURIComponent(e)},urlencode:function(e=""){return encodeURIComponent(e)},values:function(e={}){return Object.values(e)},wordCount:function(e){return e.trim().split(/\s+/).filter(Boolean).length}});const te={filters:{},parsers:{},compilers:{},plugins:[],debug:e=>{throw e}},ne={...te,commentOpen:"{{#",commentClose:"#}}",directiveOpen:"{{",directiveClose:"}}",outputOpen:"{{=",outputClose:"}}"},ie={...ne,trimWhitespace:!1,stripComments:!1,loader:async()=>"",preloadIncludes:[]},re={...ie,globals:{},autoEscape:!0,cache:{enabled:!0,maxSize:1e3,ttl:36e5,revalidate:!0},security:{}},se=(e,...t)=>{const n={...e},i=e=>{n.filters={...n.filters,...e.filters},n.parsers={...n.parsers,...e.parsers},n.compilers={...n.compilers,...e.compilers}};return e.plugins?.forEach(i),t.forEach(({plugins:e,filters:t,parsers:r,compilers:s,...o})=>{for(const[e,t]of Object.entries(o))void 0!==t&&(n[e]=t);i({filters:t,parsers:r,compilers:s}),e?.forEach(i)}),n};const oe={BLOCK:async function({val:{value:e},loc:t},n){const i=JSON.stringify(e);n.pushRaw(t,`if(b[${i}]&&!(b[${i}].u++)){`,`s+=await b[${i}].s?.pop()?.()??"";`,"}")},SUPER:async function({loc:e},t){t.state.block?t.pushRaw(e,`s+=await b[${JSON.stringify(t.state.block)}]?.s?.pop()?.()??"";`):t.options.debug?.(new i('"super" should be used inside a block',t.template,e))}};class ae extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BLOCK"})}}class le extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SUPER"})}}const ce={compilers:oe,parsers:{block:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endblock"]);t.match(["endblock"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ae(t.parseExp(e.expression),n,e.loc,e.strip)},super:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new le(e.val,e.loc,e.strip))},endblock:"unexpected"}},ue={AND:"&&",OR:"||",IS:"",NOT:"!",EQ:"===",NE:"!==",GT:">",LT:"<",GE:">=",LE:"<=",IN:" in ",NI:" in ",OF:" of ",WITH:" with ",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",ID:"",LIT:"",IF:"",ELSE:""},pe=new Set(Object.getOwnPropertyNames(Object.prototype));class he{constructor(){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}compile(e,t=y,n=g){return this.context=t,this.filters=n,e?this.compileExp(e):'""'}compileExp(e){switch(e.type){case"NOT":return this.compileNot(e);case"ID":return this.compileId(e);case"LIT":return this.compileLit(e);case"PIPE":return this.compilePipe(e);case"ASSIGN":return this.compileAssign(e);case"IS":return this.compileIs(e);case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.compileBinary(e);case"IF":return this.compileTernary(e);case"SEQ":return this.compileSeq(e);default:return""}}compileNot({argument:e}){return`!${this.compileExp(e)}`}compileId({value:e,path:t,args:n}){let i=pe.has(e)?`(Object.hasOwn(${this.context},"${e}")?${this.context}.${e}:undefined)`:`${this.context}.${e}`;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=`(${this.compileArgs(n).join(",")})`),i}compileArgs(e){const t=[],n=[];for(const i of e)if("ASSIGN"===i.type){const{left:e,right:t}=i;n.push(`${e.value}:${this.compileExp(t)}`)}else t.push(this.compileExp(i));return n.length&&t.push(`{${n.join(",")}}`),t}compileLit({value:e}){return void 0===e?"undefined":"number"==typeof e&&e<0?`(${e})`:JSON.stringify(e)}compileSeq({elements:e}){return`(${e.map(e=>this.compileExp(e)).join(",")})`}compilePipe({left:e,right:t}){const{value:n,args:i=[]}=t,r=`(${this.filters}.${n}||u_("${n}")).call(${[this.context,this.compileExp(e),...this.compileArgs(i)].join(",")})`;return`(${w}=${r},${w} instanceof Promise?await ${w}:${w})`}compileAssign({left:e,right:t}){return"ID"===e.type?`Object.assign(${this.context},{${e.value}:${this.compileExp(t)}});`:`Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(t)},${e.elements.map(({value:e})=>`"${e}"`).join(",")}));`}compileIs({left:e,right:t}){return`typeof ${this.compileExp(e)}===${this.compileExp(t)}`}compileBinary({type:e,left:t,right:n}){const i=`${this.compileExp(t)}${ue[e]}${this.compileExp(n)}`;return"NI"===e?`!(${i})`:i}compileTernary({test:e,consequent:t,alternative:n}){return`${this.compileExp(e)}?${this.compileExp(t)}:${n?this.compileExp(n):'""'}`}}const fe={CALL:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`s+=await ${(new he).compile(e,i.context)}(async()=>{`,'let s="";'),await i.compileNodes(t),i.pushRaw(null,"return s;",'})??"";')}};class de extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALL"})}}const be={compilers:fe,parsers:{call:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcall"]);t.match(["endcall"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new de(t.parseExp(e.expression),n,e.loc,e.strip)},endcall:"unexpected"}};const me={CAPTURE:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`${i.context}.${e.value}=${g}.safe.call(${i.context},await(async(s)=>{`),await i.compileNodes(t),i.pushRaw(null,'return s;})(""));')}};class ye extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CAPTURE"})}}const ge={compilers:me,parsers:{capture:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcapture"]);t.match(["endcapture"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ye(t.parseExp(e.expression),n,e.loc,e.strip)},endcapture:"unexpected"}};const we={COMMENT:async function({val:e,loc:t},n){n.options.stripComments||n.pushStr(t,`\x3c!--${e}--\x3e`)}};class ve extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"COMMENT"})}}const xe={compilers:we,parsers:{comment:function*({val:e,loc:t,strip:n}){yield"NEXT",yield new ve(e,t,n)}}},Oe="loop:{first:i_===0,index:i_++,last:i_===n_}";function Ee(e,t=new Set){return!(!e||"object"!=typeof e||t.has(e))&&(t.add(e),"ASSIGN"===e.type||Object.entries(e).some(([e,n])=>"args"===e&&Array.isArray(n)?n.some(e=>Ee("ASSIGN"===e.type?e.right:e,t)):Ee(n,t)))}function Pe(e){return e.every(e=>{switch(e.type){case"TEXT":case"COMMENT":case"BREAK":case"CONTINUE":return!0;case"OUTPUT":return!Ee(e.val);case"IF":return!Ee(e.test)&&Pe(e.body)&&e.alternatives.every(e=>!Ee(e.test)&&Pe(e.body));case"FOR":return!Ee(e.loop.right)&&Pe(e.alternative?.body??[]);default:return!1}})}const je={FOR:async function({loop:{left:e,right:t,loc:n},body:i,alternative:r},s){const{context:o}=s,a=new he;s.pushRaw(n,"{",`const t_=${a.compile(t,o)},`,"a_=Array.isArray(t_)?t_:Array.from(t_??[]),n_=a_.length;"),r&&(s.pushRaw(n,"if(!n_){"),await s.compileNodes(r.body),s.pushRaw(n,"}else{"));const l="SEQ"===e.type?e.elements.map(e=>"ASSIGN"===e.type?[e.left.value,`v_.${e.left.value}===undefined?${a.compile(e.right,o)}:v_.${e.left.value}`]:[e.value,`v_.${e.value}`]):[[e.value,"v_"]],c=s.in();s.pushRaw(n,"let i_=0;");const{maxLoopIterations:p}=u(s.options.security),h=null==p?[]:[`if(++li_>${p})throw new Error(${JSON.stringify(`Loop iteration limit of ${p} exceeded`)});`];Pe(i)?s.pushRaw(n,`const ${c}={...${o}};`,"for(const v_ of a_){",...h,`${c}.loop={${Oe.slice(6)};`,...l.map(([e,t])=>`${c}.${e}=${t};`)):s.pushRaw(n,"for(const v_ of a_){",...h,`const ${c}={`,`...${o},`,`${Oe},`,...l.map(([e,t])=>`${e}:${t},`),"};"),await s.compileNodes(i),s.out(),s.flushable&&s.pushFlush(),s.pushRaw(null,r?"}}}":"}}")},BREAK:function({loc:e},t){t.pushRaw(e,"break;")},CONTINUE:function({loc:e},t){t.pushRaw(e,"continue;")}};class Te extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternative",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"FOR"})}traverse(e){this.body.forEach(e),this.alternative?.body.forEach(e)}}let $e=class extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}};class ke extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BREAK"})}}class Se extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CONTINUE"})}}const Ie=new WeakMap;const Ne={for:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Ie.set(t,!0),yield"NEXT";const n=t.parseUntil(["else","endfor"]);Ie.set(t,!1);let r=null;if(t.match(["else"])){const e=function*(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endfor"]);yield"NEXT",yield new $e(t.parseUntil(["endfor"]),e.loc,e.strip)}(t.peek(),t);for(;;){const{value:t,done:n}=e.next();if(n)break;if(t){if("NEXT"===t){yield"NEXT";continue}r=t}}}t.match(["endfor"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const s=t.parseExp(e.expression);"OF"===s?.type?yield new Te(s,n,r,e.loc,e.strip):s&&t.options.debug?.(new i(`"${e.name}" expects "item of items"`,t.template,e.loc))},break:function*(e,t){e.expression?t.emitExpErr(e,!1):Ie.get(t)?(yield"NEXT",yield new ke(e.val,e.loc,e.strip)):t.options.debug?.(new i('"break" directive used outside of a loop',t.template,e.loc))},continue:function*(e,t){e.expression?t.emitExpErr(e,!1):Ie.get(t)?(yield"NEXT",yield new Se(e.val,e.loc,e.strip)):t.options.debug?.(new i('"continue" directive used outside of a loop',t.template,e.loc))},endfor:"unexpected"},Ce={compilers:je,parsers:Ne};const Le={IF:async function({test:e,body:t,alternatives:n},i){i.pushRaw(e.loc,`if(${(new he).compile(e,i.context)}){`),await i.compileNodes(t),i.pushRaw(null,"}");for(const e of n)"ELSE_IF"===e.type?i.pushRaw(e.test.loc,`else if(${(new he).compile(e.test,i.context)}){`):i.pushRaw(null,"else{"),await i.compileNodes(e.body),i.pushRaw(null,"}")}};class Re extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternatives",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"IF"})}traverse(e){this.body?.forEach(e),this.alternatives?.forEach(t=>t.body?.forEach(e))}}class De extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE_IF"})}}class Ae extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}}function*Me(e,t){if(!e.expression)return t.emitExpErr(e),yield"NEXT",void t.parseUntil(["else","elseif","elsif","elif","endif"]);yield"NEXT",yield new De(t.parseExp(e.expression),t.parseUntil(["else","elseif","elsif","elif","endif"]),e.loc,e.strip)}function*Ue(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endif"]);yield"NEXT",yield new Ae(t.parseUntil(["endif"]),e.loc,e.strip)}const _e={compilers:Le,parsers:{if:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["else","elseif","elsif","elif","endif"]),r=[];for(;t.match(["else","elseif","elsif","elif"]);){const e=t.peek();if("else"===e.name.toLowerCase()){const n=Ue(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}else{const n=Me(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}}t.match(["endif"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new Re(t.parseExp(e.expression),n,r,e.loc,e.strip)},elseif:"unexpected",elsif:"unexpected",elif:"unexpected",endif:"unexpected"}};const Fe=/\s+(once|last)\s*$/;const We={compilers:{INCLUDE:async function({val:e,loc:t,withExp:n,modifier:i},r){const s=new he,o=J(e)?JSON.stringify(e.value):s.compile(e,r.context),a=n?`s+=await p[${o}]?.({...${r.context},...${s.compile(n,r.context)}})??"";`:`s+=await p[${o}]?.(tc_)??"";`;if("once"!==i){if("last"===i&&J(e)){const t=r.state.includeLast,n=t?.get(e.value);if(n&&(n.emitted+=1,n.emitted<n.total))return}r.pushRaw(t,a)}else r.pushRaw(t,`if(!inc_[${o}]){inc_[${o}]=1;${a}}`)}},parsers:{include:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";let n=e.expression.val,i=null;const r=Fe.exec(n);r&&(i=r[1],n=n.slice(0,r.index));const s=t.parseExp({val:n,loc:e.expression.loc});if(s){if("WITH"===s.type){const{left:t,right:n}=s;return void(yield new V(t,e.loc,e.strip,n,i))}yield new V(s,e.loc,e.strip,null,i)}}}};const Xe={MACRO:async function({val:{value:e,args:t},loc:n,body:i},r){const{context:s}=r,o=new he,{maxCallDepth:a}=u(r.options.security);r.pushRaw(n,`${s}.${e}=(...a_)=>async(_c)=>{`,...null==a?[]:[`if(cd_>=${a})throw new Error(${JSON.stringify(`Macro call depth limit of ${a} exceeded`)});`,"cd_++;","try{"],'let s="";',`const ${r.in()}={`,`...${s},`,...(t??[]).map((e,t)=>"ASSIGN"===e.type?`${e.left.value}:a_[${t}]===undefined?${o.compile(e.right)}:a_[${t}],`:`${e.value}:a_[${t}],`),"};"),await r.compileNodes(i),r.out(),r.pushRaw(null,"return s;",...null==a?[]:["}finally{cd_--;}"],"};")},CALLER:function({loc:e},t){t.pushRaw(e,'s+=await _c?.()??"";')}};class Ge extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"MACRO"})}}class ze extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALLER"})}}const Be=new WeakMap;const qe={compilers:Xe,parsers:{macro:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Be.set(t,!0),yield"NEXT";const n=t.parseUntil(["endmacro"]);Be.set(t,!1),t.match(["endmacro"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const r=t.parseExp(e.expression);if("ID"===r.type){if(r.args?.length)for(const n of r.args)if("ASSIGN"===n.type){if("ID"!==n.left.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc))}else if("ID"!==n.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc));yield new Ge(r,n,e.loc,e.strip)}else t.options.debug?.(new i("Invalid macro definition",t.template,e.loc))},caller:function*(e,t){e.expression?t.emitExpErr(e,!1):Be.get(t)?(yield"NEXT",yield new ze(e.val,e.loc,e.strip)):t.options.debug?.(new i('"caller" directive used outside of a macro',t.template,e.loc))},endmacro:"unexpected"}};const Ke={OUTPUT:async function({val:e},t){t.pushVar(e.loc,(new he).compile(e,t.context))}};class He extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"OUTPUT"})}}const Je={compilers:Ke,parsers:{output:function*(e,t){yield"NEXT";const n=P(`${t.options.outputOpen}${e.strip.before?"-":""}`,{...e.loc.start});yield new He(t.parseExp({val:e.val,loc:{start:n,end:e.loc.end}}),e.loc,e.strip)}}};const Ve={SET:async function({val:e,loc:t},n){n.pushRaw(t,(new he).compile(e,n.context))}};class Qe extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SET"})}}const Ye={compilers:Ve,parsers:{set:function*(e,t){e.expression?(yield"NEXT",yield new Qe(t.parseExp(e.expression),e.loc,e.strip)):t.emitExpErr(e)}}};const Ze={STYLESHEET:async function(){},STYLESHEETS:async function({loc:e},t){t.pushRaw(e,"if(!ss_u++){","for(const f_ of ss_)s+=await f_();","}")}};class et extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEET"})}}class tt extends G{constructor(e,t){super(),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEETS"})}}const nt={compilers:Ze,parsers:{stylesheet:function*(e,t){if(e.expression)return void t.emitExpErr(e,!1);yield"NEXT";const n=t.parseUntil(["endstylesheet"]);t.match(["endstylesheet"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new et(n,e.loc,e.strip)},endstylesheet:"unexpected",stylesheets:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new tt(e.loc,e.strip))}}};const it={TEXT:async function({val:e,loc:t,strip:{start:n,end:i}},r){(n||r.options.trimWhitespace)&&(e=e.replace(/^\s+/,"")),(i||r.options.trimWhitespace)&&(e=e.replace(/\s+$/,"")),r.pushStr(t,e)}};class rt extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEXT"})}}const st={compilers:it,parsers:{text:function*(e){yield"NEXT",yield new rt(e.val,e.loc,e.strip)}}};const ot={UNEXPECTED:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unexpected "${e}"--\x3e`)}};class at extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNEXPECTED"})}}const lt={compilers:ot,parsers:{unexpected:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unexpected "${n}"`,t.template,e.loc)),yield"NEXT",yield new at(n,e.val,e.loc,e.strip)}}};const ct={UNKNOWN:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unknown "${e}"--\x3e`)}};class ut extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNKNOWN"})}}const pt={compilers:ct,parsers:{unknown:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unknown "${n}"`,t.template,e.loc)),yield"NEXT",yield new ut(n,e.val,e.loc,e.strip)}}};const ht={WITH:async function(e,t){const{context:n}=t,i=new he;t.pushRaw(e.loc,`const ${t.in()}={...${i.compile(e.expression,n)}};`),await t.compileNodes(e.body),t.out()}};class ft extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"expression",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"WITH"})}traverse(e){this.body?.forEach(e)}}const dt=[ce,be,xe,ge,Ce,_e,We,qe,Ye,nt,st,Je,lt,pt,{parsers:{with:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endwith"]);t.match(["endwith"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ft(t.parseExp(e.expression),n,e.loc,e.strip)},endwith:"unexpected"},compilers:ht}];class bt extends i{constructor(e,t,n,i){super(e,t,void 0,i),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"getLoc",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="RenderError",bt.captureStackTrace?.(this,this.constructor)}get details(){return this.loc=this.getLoc(),super.details}}const mt=new Error("Stream cancelled");class yt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sandbox",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"escape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiling",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.options=se(re,{filters:ee,plugins:dt},e),this.filters=Object.assign(Object.create(null),this.options.filters);const n=this.options.security?.deepEscape?h:l,{autoEscape:i}=this.options;this.escape=e=>"string"==typeof e?i?l(e):e:null==e?"":e instanceof c?`${e}`:i?n(e):e,!1!==this.options.cache?.enabled&&(this.cache=new t(this.options.cache)),this.options.security?.sandbox&&(this.sandbox=new p(this.options.security))}async render(e,t){const n=this.cache?.peek(b(e));if(n?.script&&0===n.sources.size&&n.fingerprint===m(this.options)){this.cache.get(b(e));try{return await this.run(n.script,t)}catch(t){const i=new v;return i.mappings=n.mappings,this.options.debug(this.wrapError(t,e,i)),""}}let i;try{return i=await this.compile(e),await this.run(i.script,t)}catch(t){this.options.debug(this.wrapError(t,e,i??new v))}return""}template(e){return t=>this.render(e,t)}async renderCompiled(e,t={}){try{return await this.run(e,t)}catch(e){this.options.debug(e)}return""}renderStream(e,t={}){let n,i=!1;return new ReadableStream({start:r=>{const s=e=>{if(i)throw mt;if(r.enqueue(e),(r.desiredSize??1)<=0)return new Promise(e=>{n=e})};let o;(async()=>{try{o=await this.compile(e,!0);const n=await this.run(o.script,t,s);n&&!i&&r.enqueue(n),r.close()}catch(t){if(t===mt)return;try{this.options.debug(this.wrapError(t,e,o??new v)),r.close()}catch(e){r.error(e)}}})()},pull:()=>{n?.(),n=void 0},cancel:()=>{i=!0,n?.()}})}compile(e,t=!1){const n=b(e,t);let i=this.compiling.get(n);return i||(i=new Z(this.options,this.cache,this.options.cache?.revalidate??!0,t).compile(e).finally(()=>this.compiling.delete(n)),this.compiling.set(n,i)),i}wrapError(e,t,n){return"CompileError"===e?.name?e:new bt(`${e?.message??e}`,t,()=>{const t=e?.stack?.match(/<anonymous>:(\d+):(\d+)\)/);if(!t)return e?.stack??"";const[i]=n.getSourceLoc({line:+t[1]-2,column:+t[2]});return i})}run(e,t,n){const i=e(this.sandbox?{...this.sandbox.createSecureContext(this.options.globals),...t}:{...this.options.globals,...t},this.escape,this.filters,n),{timeoutMs:r}=this.options.security??{};if(null==r)return i;let s;return Promise.race([Promise.resolve(i).finally(()=>{clearTimeout(s)}),new Promise((e,t)=>{s=setTimeout(()=>{t(new Error(`Render timed out after ${r}ms`))},r)})])}async renderFile(e,t){return this.render(await this.options.loader(e),t)}clearCache(){this.cache?.clear()}invalidateCache(e){this.cache?.invalidate(e)}getCacheStats(){return this.cache?this.cache.getStats():null}resetCacheStats(){this.cache?.resetStats()}auditTemplate(e){return(new f).auditTemplate(e)}getCSPHeaders(){return new p(this.options.security).generateCSPHeaders()}}class gt{constructor(e){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"variables",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"includes",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"macros",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}async analyze(e,t=new Set){const n=new H(this.options).parse(e);await this.nodes(n.body,t)}async nodes(e=[],t){for(const n of e)await this.node(n,t)}async node(e,t){switch(e.type){case"OUTPUT":this.exp(e.val,t);break;case"IF":this.exp(e.test,t),await this.nodes(e.body,t);for(const n of e.alternatives)this.exp(n.test,t),await this.nodes(n.body,t);break;case"FOR":{this.exp(e.loop.right,t),await this.nodes(e.alternative?.body,t);const n=new Set(t).add("loop");this.bind(e.loop.left,n,t),await this.nodes(e.body,n);break}case"SET":this.exp(e.val.right,t),this.bind(e.val.left,t,t);break;case"CAPTURE":await this.nodes(e.body,t),t.add(e.val.value);break;case"MACRO":{const n=new Set(t);for(const i of e.val.args??[])this.bind(i,n,t);t.add(e.val.value),this.macros.add(e.val.value),await this.nodes(e.body,n);break}case"CALL":this.exp(e.val,t),await this.nodes(e.body,t);break;case"WITH":this.exp(e.expression,t),await this.nodes(e.body,wt);break;case"BLOCK":this.blocks.add(e.val.value),await this.nodes(e.body,t);break;case"STYLESHEET":default:await this.nodes(e.body,t);break;case"INCLUDE":this.exp(e.val,t),e.withExp&&this.exp(e.withExp,t),"LIT"===e.val.type&&"string"==typeof e.val.value&&await this.include(e.val.value,t)}}async include(e,t){if(this.includes.has(e))return;let n;this.includes.add(e);try{n=await this.options.loader(e)}catch{}n&&await this.analyze(n,new Set(t))}bind(e,t,n){"ID"===e.type?t.add(e.value):"SEQ"===e.type?e.elements.forEach(e=>this.bind(e,t,n)):"ASSIGN"===e.type&&(this.exp(e.right,n),this.bind(e.left,t,n))}exp(e,t){if(e)switch(e.type){case"ID":t===wt||t.has(e.value)||this.variables.add(e.value),e.args?.forEach(e=>this.exp(e,t));break;case"LIT":break;case"NOT":this.exp(e.argument,t);break;case"IF":this.exp(e.test,t),this.exp(e.consequent,t),this.exp(e.alternative,t);break;case"SEQ":e.elements.forEach(e=>this.exp(e,t));break;case"PIPE":{const{left:n,right:i}=e;this.exp(n,t),this.filters.add(i.value);for(const e of i.args??[])this.exp("ASSIGN"===e.type?e.right:e,t);break}default:this.exp(e.left,t),this.exp(e.right,t)}}}const wt=new Set;async function vt(e,t={}){const n=new gt(se(ie,{filters:ee,plugins:dt},t));await n.analyze(e);const i=e=>[...e].sort();return{variables:i(n.variables),filters:i(n.filters),includes:i(n.includes),blocks:i(n.blocks),macros:i(n.macros)}}function xt({variables:e},{includeRuntime:t=!1}={}){const n=e.map(e=>` ${e}?: unknown;`).join("\n");return`// Generated by the Janja precompiler. Do not edit.\nimport type { ${t?"RendererOptions, ":""}Script } from 'janja';\n\n/** The data this template reads. */\nexport interface TemplateData {${n?`\n${n}\n`:""}}\n\nexport declare const script: Script;\n\n${t?"export default function render(\n data?: TemplateData,\n options?: RendererOptions,\n): Promise<string>;":"export default script;"}\n`}function Ot(e){let t=e<0?-e<<1|1:e<<1,n="";do{let e=31&t;t>>>=5,t>0&&(e|=32),n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]}while(t>0);return n}function Et(e,{file:t,source:n,sourceContent:i,line:r}){const s=new Map;for(const t of e)s.set(t.target.start.column,t.source.start);let o=0,a=0,l=0;const c=[...s.entries()].sort(([e],[t])=>e-t).map(([e,t])=>{const n=t.line-1,i=t.column-1,r=Ot(e-o)+Ot(0)+Ot(n-a)+Ot(i-l);return o=e,a=n,l=i,r}).join(",");return{version:3,...t?{file:t}:{},sources:[n],sourcesContent:[i],names:[],mappings:`${";".repeat(r)}${c}`}}async function Pt(e,{includeRuntime:t,sourceMap:n,filename:i,dts:r,...s}={}){const o=new Z(se(ie,{filters:ee,plugins:dt},s));await o.compile(e);const a=`// Generated by the Janja precompiler. Do not edit.${t?"\nimport { renderCompiled } from 'janja';\n":""}\nexport function script(${y}, e, ${g}, w) {\n`,l=t?"\n}\n\nexport default function render(globals = {}, options) {\n return renderCompiled(script, globals, options);\n}\n":"\n}\n\nexport default script;\n";return{code:`${a}${o.code}${l}`,map:n?Et(o.mappings,{source:i??"template.janja",sourceContent:e,line:a.split("\n").length-1}):void 0,dts:r?xt(await vt(e,s),{includeRuntime:t}):void 0}}class jt{constructor(e={}){Object.defineProperty(this,"defaultLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"translations",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pluralRules",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.locale||this.defaultLocale,this.translations=e.translations||{},this.pluralRules=e.pluralRules||this.getDefaultPluralRules()}setLocale(e){this.currentLocale=e}getLocale(){return this.currentLocale}addTranslations(e,t){this.translations[e]||(this.translations[e]={}),this.translations[e]=this.mergeDeep(this.translations[e],t)}translate(e,t={}){const n=this.getTranslation(e);return n?this.interpolate(n,t):e}t(e,t={}){return this.translate(e,t)}pluralize(e,t,n={}){const i=`${e}.${this.getPluralForm(t)}`,r=this.getTranslation(i);if(r)return this.interpolate(r,{...n,count:t});const s=this.getTranslation(e);return s?this.interpolate(s,{...n,count:t}):e}formatDate(e,t){const n="string"==typeof e?new Date(e):e;return new Intl.DateTimeFormat(this.currentLocale,t).format(n)}formatNumber(e,t){return new Intl.NumberFormat(this.currentLocale,t).format(e)}formatCurrency(e,t,n){return new Intl.NumberFormat(this.currentLocale,{...n,style:"currency",currency:t}).format(e)}getTranslation(e){const t=e.split(".");let n=this.translations[this.currentLocale];for(const e of t){if(!n||"object"!=typeof n||!(e in n))return null;n=n[e]}return"string"==typeof n?n:null}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>void 0!==t[n]?String(t[n]):n)}getPluralForm(e){const t=this.pluralRules[this.currentLocale];return t?t(e):this.pluralRules[this.defaultLocale](e)}getDefaultPluralRules(){return{en:e=>1===e?"one":"other",es:e=>1===e?"one":"other",fr:e=>0===e||1===e?"one":"other",de:e=>1===e?"one":"other",ru:e=>{const t=e%10,n=e%100;return 1===t&&11!==n?"one":t>=2&&t<=4&&!(n>=12&&n<=14)?"few":0===t||t>=5&&t<=9?"many":"other"},ja:()=>"other",zh:()=>"other",ar:e=>0===e?"zero":1===e?"one":2===e?"two":e%100>=3&&e%100<=10?"few":e%100>=11&&e%100<=99?"many":"other"}}mergeDeep(e,t){const n={...e};return this.isObject(e)&&this.isObject(t)&&Object.keys(t).forEach(i=>{this.isObject(t[i])?i in e?n[i]=this.mergeDeep(e[i],t[i]):Object.assign(n,{[i]:t[i]}):Object.assign(n,{[i]:t[i]})}),n}isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}}const Tt=new jt;async function $t(e,t={}){let n="";const{data:i={},options:r}=t,s=new yt(r);for(const t of e)n=await s.render(t,{...i,_content:n});return n}const kt={trim:!1,stripComments:!1,collapseWhitespace:!1,preserveNewlines:!0};function St(e){return{...kt,...e}}class It{constructor(){Object.defineProperty(this,"mixins",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}register(e){this.mixins.set(e.name,e)}registerMultiple(e){for(const t of e)this.register(t)}get(e){return this.mixins.get(e)}has(e){return this.mixins.has(e)}delete(e){return this.mixins.delete(e)}clear(){this.mixins.clear()}list(){return Array.from(this.mixins.keys())}}const Nt=new It;async function Ct(e,t={},n=Nt){const i=n.get(e);if(!i)throw new Error(`Mixin "${e}" not found in registry`);const{data:r={},options:s}=t,o={...i.data,...r};return new yt(s).render(i.template,o)}class Lt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e})}async validate(e){const t=[],n=[],i=e=>{const[n]=e?.suggestions??[];t.push({type:"error",message:`${e?.message??e}`,line:e?.loc?.start.line,column:e?.loc?.start.column,suggestion:n?.fix??n?.message})},r=se(ie,{filters:ee,plugins:dt},this.options,{debug:i});try{const t=new H(r).parse(e);this.checkFilters(t,r.filters,n)}catch(e){i(e)}return{valid:0===t.length,errors:t,warnings:n}}checkFilters(e,t,n,i=new Set){if(e&&"object"==typeof e&&!i.has(e)){i.add(e),"PIPE"!==e.type||"ID"!==e.right?.type||Object.prototype.hasOwnProperty.call(t,e.right.value)||n.push({type:"warning",message:`Unknown filter "${e.right.value}"`,line:e.right.loc?.start.line,column:e.right.loc?.start.column});for(const r of Object.values(e))this.checkFilters(r,t,n,i)}}}const Rt={AND:"and",OR:"or",IS:"is",NOT:"not",EQ:"eq",NE:"ne",GT:"gt",LT:"lt",GE:"ge",LE:"le",IN:"in",NI:"ni",OF:"of",WITH:"with",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"|",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",IF:"if",ELSE:"else"};class Dt{format(e){return e?this.formatExp(e):'""'}formatExp(e){switch(e.type){case"NOT":return this.formatNot(e);case"ID":return this.formatId(e);case"LIT":return this.formatLit(e);case"PIPE":case"IS":case"ASSIGN":case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"OF":case"WITH":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.formatBinary(e);case"IF":return this.formatTernary(e);case"SEQ":return this.formatSeq(e);default:return""}}formatNot({argument:e}){return`${Rt.NOT} ${this.formatExp(e)}`}formatId({value:e,path:t,args:n}){let i=e;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=this.formatSeq({elements:n})),i}formatLit({value:e}){return void 0===e?"undefined":JSON.stringify(e)}formatSeq({elements:e}){return`(${e.map(e=>this.formatExp(e)).join(", ")})`}formatBinary({type:e,left:t,right:n}){return`${this.formatExp(t)} ${Rt[e]} ${this.formatExp(n)}`}formatTernary({test:e,consequent:t,alternative:n}){return`${this.formatExp(t)} ${Rt.IF} ${this.formatExp(e)}${n?` ${Rt.ELSE} ${this.formatExp(n)}`:""}`}}function At(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=Mt(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function Mt(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if('"'!==s&&"'"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1}return{opens:t,closes:n}}const Ut=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),_t=new Set(["pre","textarea","script","style"]),Ft=new Set(["if","for","macro","block","call","capture","with","stylesheet"]),Wt=new Set(["stylesheet"]),Xt=new Set(["else","elif","elseif","elsif"]),Gt=new Set(["endif","endfor","endmacro","endblock","endcall","endcapture","endwith","endstylesheet"]);function zt(e,t,n){const i=[];let r=0,s=!0,o=0;if(n.inComment){const s=e.indexOf(t.commentClose);if(-1===s)return{pieces:i,prefixClosers:r};n.inComment=!1,o=s+t.commentClose.length}for(;o<e.length;){if(/\s/.test(e[o])){o+=1;continue}if(e.startsWith(t.commentOpen,o)){const a=e.indexOf(t.commentClose,o+t.commentOpen.length);if(-1===a)return n.inComment=!0,{pieces:i,prefixClosers:r};s=!1,o=a+t.commentClose.length;continue}const a=Bt(e,o,t);a?(a.piece?(i.push(a.piece),!s||"close"!==a.piece.kind&&"mid"!==a.piece.kind?s=!1:r+=1):s=!1,o=a.end):(s=!1,o+=1)}return{pieces:i,prefixClosers:r}}function Bt(e,t,n){const{directiveOpen:i,outputOpen:r}=n;if(e.startsWith(r,t))return{end:Ht(e,t+r.length,n.outputClose)};if(e.startsWith(i,t))return function(e,t,n){const{directiveOpen:i,directiveClose:r}=n,s=Ht(e,t+i.length,r),o=e.slice(t+i.length,s-r.length),a=o.replace(/^\s*-?\s*/,"").match(/^([A-Za-z_]\w*)/)?.[1]?.toLowerCase();if(!a)return{end:s};if(Gt.has(a)){const e=a.startsWith("end")?a.slice(3):a;return{end:s,piece:{kind:"close",sensitive:Wt.has(e)?e:void 0}}}if(Xt.has(a))return{end:s,piece:{kind:"mid"}};if(Ft.has(a))return{end:s,piece:{kind:"open",sensitive:Wt.has(a)?a:void 0}};return{end:s}}(e,t,n);if(e.startsWith("\x3c!--",t)){const n=e.indexOf("--\x3e",t+4);return{end:-1===n?e.length:n+3}}return"<"===e[t]?function(e,t,n){if(e.startsWith("</",t)){let i=t+2;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=qt(e,i,n);return!s||Ut.has(s)?{end:o}:{end:o,piece:{kind:"close",sensitive:_t.has(s)?s:void 0}}}if(e.startsWith("<!",t)||e.startsWith("<?",t))return{end:qt(e,t+2,n)};let i=t+1;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=qt(e,i,n),a=e.slice(t,o),l=/\/\s*>$/.test(a)||Ut.has(s);if(!s||l)return{end:o};return{end:o,piece:{kind:"open",sensitive:_t.has(s)?s:void 0}}}(e,t,n):null}function qt(e,t,n){let i=t,r=null;for(;i<e.length;){const t=e[i];if(r){if(t===r)r=null;else{const t=Kt(e,i,n);if(null!==t){i=t;continue}}i+=1;continue}const s=Kt(e,i,n);if(null===s)if('"'!==t&&"'"!==t){if(">"===t)return i+1;i+=1}else r=t,i+=1;else i=s}return e.length}function Kt(e,t,n){const{commentOpen:i,commentClose:r,outputOpen:s,outputClose:o,directiveOpen:a,directiveClose:l}=n;return e.startsWith(i,t)?Ht(e,t+i.length,r):e.startsWith(s,t)?Ht(e,t+s.length,o):e.startsWith(a,t)?Ht(e,t+a.length,l):null}function Ht(e,t,n){const i=e.indexOf(n,t);return-1===i?e.length:i+n.length}function Jt(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=Vt(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function Vt(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if("{"!==s||"{"!==e[r+1])if('"'!==s&&"'"!==s&&"`"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1;else r=Qt(e,r)}return{opens:t,closes:n}}function Qt(e,t){if(e.startsWith("{{#",t)){const n=e.indexOf("#}}",t+3);return-1===n?e.length:n+3}const n=e.indexOf("}}",t+2);return-1===n?e.length:n+2}const Yt=new Set(["script","style"]);function Zt(e,t){const n=t.tabWidth??2,i=" ".repeat(Math.max(0,n)),r=e.includes("\r\n")?"\r\n":"\n",s=e.split(/\r?\n/);let o=0,a=null,l=null;const c=[],u={inComment:!1};for(const e of s){const s=e.match(/^[ \t]*/)?.[0].length??0,h=e.slice(s),{pieces:f,prefixClosers:d}=zt(h,t,u),b=a,m=null!==b&&f.some(e=>"close"===e.kind&&e.sensitive===b),y="stylesheet"===b||null!==b&&Yt.has(b);if(y&&!m){(l??(l=[])).push(e);continue}if(l&&m&&y){const e="stylesheet"===b?Math.max(0,o-1):o,s=l.join(r),a="stylesheet"===b?Zt(s,t):"style"===b?At(s,n):Jt(s,n);for(const t of a.split(/\r?\n/))c.push(0===t.length?"":i.repeat(e)+t);l=null}else if(a&&!m){c.push(e),p(f);continue}const g=Math.max(0,o-d),w=/^\/\s*>\s*$/.test(h);c.push(0===h.length?"":i.repeat(g)+h),p(f),w&&(o=Math.max(0,o-1))}return c.join(r);function p(e){for(const t of e)"open"===t.kind?(o+=1,t.sensitive&&!a&&({sensitive:a}=t)):"close"===t.kind?(o=Math.max(0,o-1),t.sensitive&&a===t.sensitive&&(a=null)):t.kind}}const en=e=>JSON.stringify(e,(e,t)=>"loc"===e||"raw"===e?void 0:t??null);class tn{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options={continueOnError:!1,undefinedFallback:"",ignoreMissingFilters:!1,onError:()=>{},...e}}safeEvaluate(e,t,n={}){try{const n=this.evaluateExpression(e,t);return void 0===n&&void 0!==this.options.undefinedFallback?this.options.undefinedFallback:n}catch(i){const r={template:n.template||"",data:t,expression:e},s=this.options.onError(i,r);if(this.options.continueOnError)return s;throw i}}safeApplyFilter(e,t,n,i=[],r={}){try{if(!n){if(this.options.ignoreMissingFilters)return e;throw new Error(`Filter "${t}" is not defined`)}return n(e,...i)}catch(e){const n={template:r.template||"",data:r.data||{},filter:t},i=this.options.onError(e,n);if(this.options.continueOnError)return i;throw e}}wrapRender(e,t={}){return(...n)=>{try{return e(...n)}catch(e){const i={template:t.template||"",data:n[1]||{}},r=this.options.onError(e,i);if(this.options.continueOnError)return r;throw e}}}evaluateExpression(e,t){try{const n=e.split(".");let i=t;for(const e of n){if(null==i)return;i=i[e]}return i}catch{return}}createSafeAccessor(e){return t=>{try{const n=t.split(".");let i=e;for(const e of n){if(null==i)return this.options.undefinedFallback;i=i[e]}return void 0===i?this.options.undefinedFallback:i}catch{return this.options.undefinedFallback}}}}let nn;const rn=new WeakMap;function sn(e){if(!e)return nn??(nn=new yt);let t=rn.get(e);return t||(t=new yt(e),rn.set(e,t)),t}e.CompileError=i,e.Compiler=Z,e.ErrorRecovery=tn,e.ExpCompiler=he,e.ExpError=E,e.ExpParser=M,e.ExpTokenizer=I,e.I18n=jt,e.MAX_INCLUDE_DEPTH=100,e.MixinRegistry=It,e.Parser=H,e.RenderError=bt,e.Renderer=yt,e.RootNode=z,e.Safe=c,e.SecurityAuditor=f,e.SecuritySandbox=p,e.TemplatePipeline=class{constructor(e){Object.defineProperty(this,"templates",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options=e}addTemplate(e){return this.templates.push(e),this}setData(e){return this.data={...this.data,...e},this}setOptions(e){return this.options={...this.options,...e},this}async execute(){return $t(this.templates,{data:this.data,options:this.options})}},e.TemplateValidator=Lt,e.Tokenizer=K,e.Traversal=G,e.analyzeTemplate=vt,e.applyMixin=Ct,e.applyMixins=async function(e,t={},n=Nt){const i=[];for(const r of e){const e=await Ct(r,t,n);i.push(e)}return i},e.applyWhitespaceControl=function(e,t){let n=e;return t.stripComments&&(n=n.replace(/<!--[\s\S]*?-->/g,"")),t.collapseWhitespace&&(n=t.preserveNewlines?n.replace(/[ \t]+/g," "):n.replace(/\s+/g," ")),t.trim&&(n=n.trim()),n},e.baseOptions=te,e.compilerOptions=ie,e.composeLayout=async function(e,t,n={}){const{data:i={},options:r}=n,s=new yt({...r,autoEscape:!1}),o=await s.render(t,i);return s.render(e,{...i,content:o})},e.composeTemplates=$t,e.composeTemplatesWithData=async function(e,t={}){let n="";const{options:i}=t,r=new yt(i);for(const t of e){const e={...t.data,_content:n};n=await r.render(t.template,e)}return n},e.composeWithSlots=async function(e,t,n={}){const{data:i={},options:r}=n,s=new yt({...r,autoEscape:!1}),o={};for(const[e,n]of Object.entries(t))o[e]=await s.render(n,i);return s.render(e,{...i,slots:o})},e.createErrorRecovery=function(e={}){return new tn(e)},e.createFileLoader=function(e,{extensions:t=[".janja",".html"]}={}){return async n=>{const{readFile:i}=await(import("node:fs/promises")),r=await(import("node:path")),s=r.resolve(e),o=r.extname(n)?[n]:[...t.map(e=>`${n}${e}`),n];for(const e of o){const t=r.resolve(s,e);if(!t.startsWith(s+r.sep))break;try{return await i(t,"utf-8")}catch{}}throw new Error(`Template "${n}" not found in ${e}`)}},e.createMixin=function(e,t,n){return{name:e,template:t,data:n}},e.deepEscape=h,e.defaultErrorHandler=function(e,t){console.error("[Janja Error]",e.message),t.expression&&console.error(" Expression:",t.expression),t.filter&&console.error(" Filter:",t.filter)},e.defaultWhitespaceOptions=kt,e.defineFilters=function(e){return e},e.definePlugin=function(e){return e},e.expTokenTypes=j,e.extendTemplateWithMixin=async function(e,t,n={},i=Nt){const r=await Ct(t,n,i);return new yt({...n.options,autoEscape:!1}).render(e,{_mixin:r})},e.filters=ee,e.formatTemplate=function(t,n={}){const i={...ne,...n},r=new K(i).tokenize(t),s=[0];for(let e=0;e<t.length;e++)"\n"===t[e]&&s.push(e+1);const o=({line:e,column:t})=>s[e-1]+t-1,a=new M,l=new Dt,c=(e,t)=>{try{const n=a.parse(e,t),i=l.format(n);return en(a.parse(i,t))!==en(n)?null:i.replace(/[{}]/g,"\\$&")}catch{return null}},u=r.map(n=>{const r=t.slice(o(n.loc.start),o(n.loc.end));return n.type===e.TokenType.TEXT||n.type===e.TokenType.COMMENT&&n.val.includes("\n")?r:(t=>{const n=t.strip.before?"-":"",r=t.strip.after?"-":"";if(t.type===e.TokenType.COMMENT)return`${i.commentOpen}${n} ${t.val.trim()} ${r}${i.commentClose}`;if(t.type===e.TokenType.OUTPUT){const e=c(t.val,t.loc);return e&&`${i.outputOpen}${n} ${e} ${r}${i.outputClose}`}const{name:s,expression:o}=t;if(!s)return null;const a=o?c(o.val,o.loc):"";return null!==a&&`${i.directiveOpen}${n} ${s}${a&&` ${a}`} ${r}${i.directiveClose}`})(n)||r}).join("");return!1===n.html?u:Zt(u,{tabWidth:n.tabWidth,commentOpen:i.commentOpen,commentClose:i.commentClose,directiveOpen:i.directiveOpen,directiveClose:i.directiveClose,outputOpen:i.outputOpen,outputClose:i.outputClose})},e.generateDeclarations=xt,e.generateSourceMap=Et,e.getWhitespaceCompilerOptions=function(e){const t=St(e);return{trimWhitespace:t.trim,stripComments:t.stripComments}},e.getWhitespaceRendererOptions=function(e){const t=St(e),n={};return t.trim!==kt.trim&&(n.trimWhitespace=t.trim),t.stripComments!==kt.stripComments&&(n.stripComments=t.stripComments),n},e.globalMixinRegistry=Nt,e.i18n=Tt,e.isForbiddenIdentifier=$,e.mergeOptions=se,e.mergeWhitespaceOptions=St,e.optionsFingerprint=m,e.parserOptions=ne,e.precompile=Pt,e.precompileTemplate=async function(e,t={}){return(await Pt(e,t)).code},e.render=async function(e,t,n){return sn(n).render(e,t)},e.renderCompiled=async function(e,t={},n){return sn(n).renderCompiled(e,t)},e.renderFile=async function(e,t,n){return sn(n).renderFile(e,t)},e.renderOptions=re,e.renderStream=function(e,t={},n){return sn(n).renderStream(e,t)},e.resolveSecurityLimits=u,e.templateCacheKey=b,e.validateTemplate=async function(e,t){return new Lt(t).validate(e)}}(this.janja=this.janja||{});
1
+ !function(e){"use strict";class t{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=new Map,this.maxSize=e.maxSize??1e3,this.ttl=e.ttl??36e5,this.stats={hits:0,misses:0,evictions:0}}get(e){const t=this.cache.get(e);return t?this.ttl>0&&Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),this.stats.misses++,null):(this.cache.delete(e),this.cache.set(e,t),t.hits++,this.stats.hits++,t.value):(this.stats.misses++,null)}peek(e){const t=this.cache.get(e);return!t||this.ttl>0&&Date.now()-t.timestamp>this.ttl?null:t.value}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){const e=this.cache.keys().next().value;void 0!==e&&(this.cache.delete(e),this.stats.evictions++)}this.cache.set(e,{value:t,timestamp:Date.now(),hits:0})}has(e){const t=this.cache.get(e);return!!t&&(!(this.ttl>0&&Date.now()-t.timestamp>this.ttl)||(this.cache.delete(e),!1))}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.stats={hits:0,misses:0,evictions:0}}invalidate(e){if(e)for(const t of this.cache.keys())e(t)&&this.cache.delete(t);else this.clear()}getStats(){return{...this.stats,size:this.cache.size,hitRate:this.stats.hits+this.stats.misses>0?this.stats.hits/(this.stats.hits+this.stats.misses):0}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}}function n(e,t,n){const i=[];if("ExpError"===e&&(t.includes("Unexpected end of expression")&&i.push({message:"The expression is incomplete. Make sure you have closed all parentheses, brackets, and quotes.",fix:"Check for missing closing characters: ), ], }"}),t.includes('Expected "RP" after "LP"')&&i.push({message:"Missing closing parenthesis in your expression.",fix:"Add a closing parenthesis ) to match the opening one.",example:"(foo.bar) instead of (foo.bar"}),t.includes("No left operand")&&i.push({message:"An operator is missing its left operand.",fix:"Add a value or variable before the operator.",example:"x + 1 instead of + 1"}),t.includes("No right operand")&&i.push({message:"An operator is missing its right operand.",fix:"Add a value or variable after the operator.",example:"x + 1 instead of x +"}),t.includes('Expected "ID" after "PIPE"')&&i.push({message:"The pipe operator | must be followed by a filter name.",fix:"Add a filter name after the pipe.",example:"value|upper instead of value|"}),t.includes('Expected "ID" after "DOT"')&&i.push({message:"The dot operator . must be followed by a property name.",fix:"Add a property name after the dot.",example:"object.property instead of object."}),t.includes("Left operand of assignment must be an identifier")&&i.push({message:"Assignment targets must be valid identifiers.",fix:"Use a simple variable name or sequence of variable names.",example:"x = 1 or (a, b) = [1, 2]"}),t.includes("Expected test expression")&&i.push({message:"The conditional expression is missing its test condition.",fix:"Add a condition after the if keyword.",example:"if x > 0 then y else z"}),t.includes("Expected alternative expression")&&i.push({message:"The conditional expression is missing its else clause.",fix:"Add an alternative expression after then.",example:"if x > 0 then y else z"}),t.startsWith("Unexpect")&&i.push({message:"An unexpected character was found in the expression.",fix:"Check for typos or invalid characters in your expression."})),"CompileError"===e){if(t.includes("Unclosed")){const e=t.match(/Unclosed "([^"]+)"/),n=e?e[1]:"marker";i.push({message:`The ${n} marker is not closed properly.`,fix:`Add the closing marker for ${n}.`,example:"{%"===n?"{% ... %}":"{#"===n?"{# ... #}":"{{ ... }}"})}t.includes("Unexpected")&&i.push({message:"An unexpected token was found in the template.",fix:"Check your template syntax and ensure all markers are properly formatted."})}return n&&i.push({message:"Context information:",fix:n}),i}class i extends SyntaxError{constructor(e,t,n,r){super(e),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:r}),this.name="CompileError",i.captureStackTrace?.(this,this.constructor)}get details(){const e=this.loc?function(e,t,{start:{line:n,column:i},end:{line:r,column:s}}){const o=[],a=new Set,l=e=>{a.add(e-2),a.add(e-1),a.add(e),a.add(e+1),a.add(e+2)},c=t.split("\n"),u=String(c.length).length+2;let p=0;c.forEach((e,t)=>{if(e){if(o.push(`${`${t+1}│ `.padStart(u," ")}${e}`),n===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(i-1)}^${n===r&&s>i+1?`${" ".repeat(s-i-2)}^`:""}`;/\S/.test(e)&&o.push(e),l(++p+t)}if(n!==r&&r===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(s-1)}${"^".repeat(1)}`;/\S/.test(e)&&o.push(e),l(++p+t)}}});const h=`${" ".repeat(u)}...`;return`${e}\n\n${o.map((e,t)=>a.has(t)?e:h).reduce((e,t)=>t===h&&e.at(-1)===t?e:[...e,t],[]).join("\n")}\n`}(this.message,this.src,this.loc):this.message;return function(e,t,i,r){const s=n(e,t,r);return 0===s.length?i:`${i}\n\nSuggestions:\n${s.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n")}`}(this.name,this.message,e,this.context)}get suggestions(){return n(this.name,this.message,this.context)}}const r=/[&<>"']/,s=/[&<>"']/g,o={"&":"&amp;",'"':"&#34;","'":"&#39;","<":"&lt;",">":"&gt;"},a=e=>o[e];function l(e){const t="string"==typeof e?e:`${e}`;return r.test(t)?t.replace(s,a):t}class c extends String{constructor(e){super(`${e}`)}}function u(e={}){return{maxIncludeDepth:e.maxIncludeDepth??100,maxLoopIterations:e.maxLoopIterations,maxCallDepth:e.maxCallDepth,timeoutMs:e.timeoutMs}}class p{constructor(e={}){Object.defineProperty(this,"allowedGlobals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cspNonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.allowedGlobals=new Set(e.allowedGlobals||[]),this.cspNonce=e.cspNonce}sanitizeGlobals(e){const t={};for(const[n,i]of Object.entries(e))this.allowedGlobals.has(n)&&(t[n]=i);return t}validateExpression(e){const t=[/\bprocess\b/,/\brequire\b/,/\bimport\b/,/\bexport\b/,/\beval\b/,/\bFunction\b/,/\b__proto__\b/,/\bconstructor\b/];for(const n of t)if(n.test(e))return!1;return!0}createSecureContext(e){return{...this.sanitizeGlobals(e),Math:Math,Date:Date,JSON:JSON}}getCSPNonce(){return this.cspNonce}generateCSPHeaders(){const e={};return this.cspNonce&&(e["Content-Security-Policy"]=`script-src 'nonce-${this.cspNonce}'`),e}}function h(e,t=new WeakSet){if(null==e)return"";if(e instanceof c)return`${e}`;if("object"==typeof e){if(t.has(e))return"";t.add(e);return(Array.isArray(e)?e:Object.values(e)).map(e=>h(e,t)).join("")}return l(e)}class f{auditTemplate(e){const t=[],n=[{pattern:/\beval\s*\(/,type:"dangerous-eval",message:"Use of eval() is dangerous and should be avoided",severity:"critical"},{pattern:/\bFunction\s*\(/,type:"dangerous-function",message:"Use of Function constructor is dangerous",severity:"critical"},{pattern:/\brequire\s*\(/,type:"require-usage",message:"Direct require() usage in templates is unsafe",severity:"high"},{pattern:/\bimport\s*\(/,type:"dynamic-import",message:"Dynamic import() usage in templates may be unsafe",severity:"high"}];for(const{pattern:i,type:r,message:s,severity:o}of n){const n=e.match(i);n&&t.push({type:r,message:s,location:`at index ${n.index}`,severity:o})}return{issues:t,severity:this.calculateOverallSeverity(t)}}calculateOverallSeverity(e){if(0===e.length)return"low";const t={critical:4,high:3,medium:2,low:1},n=Math.max(...e.map(e=>t[e.severity]));return Object.entries(t).find(([,e])=>e===n)[0]}}const d=new WeakMap;function b(e,t=!1){return t?`\0stream:${e}`:e}function m(e){let t=d.get(e);if(void 0===t){const{trimWhitespace:n,stripComments:i,commentOpen:r,commentClose:s,directiveOpen:o,directiveClose:a,outputOpen:l,outputClose:c,preloadIncludes:p}=e,{maxIncludeDepth:h,maxLoopIterations:f,maxCallDepth:b}=u(e.security);t=JSON.stringify([n,i,r,s,o,a,l,c,h,f??null,b??null,p]),d.set(e,t)}return t}const y="c",g="f",w="r_";class v{constructor(){Object.defineProperty(this,"mappings",{enumerable:!0,configurable:!0,writable:!0,value:[]})}addMapping(e,t){this.mappings.push({source:e,target:t})}getSourceLoc({line:e,column:t}){return this.mappings.filter(({target:{start:n,end:i}})=>n.line<=e&&i.line>=e&&(n.line<e||n.column<=t)&&(i.line>e||i.column>=t)).map(({source:e})=>e)}}class x extends v{constructor(){super(...arguments),Object.defineProperty(this,"codeParts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"codeLength",{enumerable:!0,configurable:!0,writable:!0,value:0})}get code(){return this.codeParts.join("")}set code(e){this.codeParts=[e],this.codeLength=e.length}get script(){return new Function(y,"e",g,"w",this.code)}checkpoint(){return[this.codeParts.length,this.mappings.length,this.codeLength]}rollback(e){const[t,n,i]=e;this.codeParts.length=t,this.mappings.length=n,this.codeLength=i}start(e=!0){this.pushRaw(null,"return(async()=>{",`let s="",${w};`),e&&this.pushRaw(null,"const u_=(n)=>{throw new Error('Unknown filter \"'+n+'\"')};")}end(){this.pushRaw(null,"return s;","})();")}pushRaw(e,...t){const n=this.codeLength;for(const e of t)this.codeParts.push(e),this.codeLength+=e.length;e&&this.addMapping(e,{start:{line:1,column:n},end:{line:1,column:this.codeLength}})}pushStr(e,t){t&&this.pushRaw(e,`s+=${JSON.stringify(t)};`)}pushFlush(){this.pushRaw(null,'if(s.length>1024){await w(s);s="";}')}pushVar(e,t){this.pushRaw(e,`s+=e(${t});`)}}class O extends x{constructor(){super(...arguments),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:y}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:[y]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0})}checkpoint(){return[super.checkpoint(),this.context,[...this.stack]]}rollback(e){const[t,n,i]=e;super.rollback(t),this.context=n,this.stack=i}in(){return this.context=`${this.context}_${this.index++}`,this.stack.push(this.context),this.context}out(){this.context!==y&&(this.stack.pop(),this.context=this.stack.at(-1))}}class E extends SyntaxError{constructor(e,t,n){super(e),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="ExpError",E.captureStackTrace?.(this,this.constructor)}get suggestions(){return n(this.name,this.message,this.context)}get details(){const{suggestions:e}=this;if(0===e.length)return this.message;const t=e.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n");return`${this.message}\n\nSuggestions:\n${t}`}}function P(e,t){const n=(e.match(/\n/g)||[]).length;if(n>0){t.line+=n;const i=e.lastIndexOf("\n");t.column=e.length-i}else t.column+=e.length;return{line:t.line,column:t.column}}const j={and:"AND",or:"OR",not:"NOT",is:"IS",eq:"EQ",ne:"NE",gt:"GT",lt:"LT",ge:"GE",le:"LE",in:"IN",ni:"NI",of:"OF",with:"WITH","+":"ADD","-":"SUB","*":"MUL","/":"DIV","%":"MOD",if:"IF",else:"ELSE",true:"LIT",false:"LIT",null:"LIT",undefined:"LIT","|":"PIPE","=":"ASSIGN","(":"LP",")":"RP",",":"COMMA",".":"DOT"},T=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(e){return"string"==typeof e&&T.has(e)}const S={n:"\n",t:"\t",r:"\r","\\":"\\",'"':'"',"'":"'","`":"`"};function k(e){switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return;default:return e}}class N{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}tokenize(e,t){for(this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=[];this.index<this.val.length;){const e=this.val[this.index];if(I(e))"\n"===e?(this.line++,this.column=1):this.column++,this.index++;else if("'"!==e&&'"'!==e&&"`"!==e)if(L(e)||"-"===e&&L(this.val[this.index+1]??"")&&!this.afterOperand())this.readNumber(e);else if(C(e))this.readIdentifier(e);else{if(!_(e))throw new E(`Unexpected "${e}"`,{start:{line:this.line,column:this.column},end:{line:this.line,column:this.column+1}});this.readSymbol(e)}else this.readString(e)}return this.tokens}afterOperand(){const e=this.tokens.at(-1)?.type;return"ID"===e||"LIT"===e||"RP"===e}readString(e){let t="",n="",i=!1;const r={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const r=this.val[this.index];if(i)t+=S[r]??`\\${r}`,n+=r,i=!1;else if("\\"===r)n+=r,i=!0;else{if(r===e)break;t+=r,n+=r}this.index++}this.index++,this.tokens.push({type:"LIT",value:t,loc:{start:r,end:P(`${e}${n}${e}`,this)},raw:`${e}${n}${e}`})}readNumber(e){let t=e,n=!1;const i={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(L(e))t+=e;else{if("."!==e||n)break;t+=e,n=!0}this.index++}this.tokens.push({type:"LIT",value:Number.parseFloat(t),loc:{start:i,end:P(t,this)},raw:t})}readIdentifier(e){let t=e;const n={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(!R(e))break;t+=e,this.index++}if($(t))throw new E(`"${t}" is not allowed in expressions`,{start:n,end:{line:this.line,column:this.column+t.length}});const i=Object.prototype.hasOwnProperty.call(j,t)?j[t]:"ID";this.tokens.push({type:i,value:"LIT"===i?k(t):t,loc:{start:n,end:P(t,this)},raw:t})}readSymbol(e){const t={line:this.line,column:this.column};this.index++,this.tokens.push({type:j[e],value:e,loc:{start:t,end:P(e,this)},raw:e})}}function I(e){return/\s/.test(e)}function _(e){return/[+\-*/%|=(),.]/.test(e)}function L(e){return/\d/.test(e)}function C(e){return/[a-z_$]/i.test(e)}function R(e){return/[\w$]/.test(e)}const D={COMMA:5,IF:10,ELSE:10,ASSIGN:15,LP:20,RP:20,OR:25,AND:30,IS:40,EQ:40,NE:40,GT:40,LT:40,GE:40,LE:40,IN:40,NI:40,OF:40,WITH:40,ADD:50,SUB:50,MUL:60,DIV:60,MOD:60,NOT:70,PIPE:80,DOT:90,ID:90,LIT:90};class A{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}parse(e,t){return this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=(new N).tokenize(e,t),this.val?this.parseExp():null}parseExp(e){let t=null;for(;;){const n=this.next();if(!n)break;const i=e?.(n);if("BACK"===i){this.back();break}if("BREAK"===i)break;if(t&&F(n),"LP"===n.type){if(!this.peek())throw new E("Unexpected end of expression",n.loc);const e=this.parseSequence(),i=this.consume("RP");if(!i)throw new E('Expected "RP" after "LP"',n.loc);t={...n,type:"SEQ",elements:e,loc:{start:n.loc.start,end:i.loc.end}};continue}if("NOT"!==n.type){if("ID"===n.type){t={...n,type:"ID",value:n.value},this.match("DOT")&&(t.path=this.parsePath());const e=this.consume("LP");if(e){if(t.args=this.parseSequence(),!this.consume("RP"))throw new E('Expected "RP" after "LP"',e.loc);continue}continue}if("LIT"!==n.type){if("IF"===n.type){const e=this.parseExp(e=>"ELSE"===e.type||X(n,e)?"BACK":void 0);if(!e)throw new E("Expected test expression",n.loc);if(t={...n,type:"IF",test:e,consequent:t},this.consume("ELSE")){const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E("Expected alternative expression",n.loc);t.alternative=e}continue}if(U(n.type)){if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);"ASSIGN"===n.type&&W(t,n);const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E(`No right operand for "${n.type}"`,n.loc);t={...n,type:n.type,left:t,right:e};continue}if("PIPE"!==n.type){this.back();break}if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);if(!this.match("ID"))throw new E('Expected "ID" after "PIPE"',n.loc);t={...n,type:"PIPE",left:t,right:this.parsePipe()}}else t={...n,type:"LIT"}}else{if(!this.peek())throw new E("Unexpected end of expression",n.loc);t={...n,type:"NOT",argument:this.parseExp(e=>X(n,e)?"BACK":void 0)}}}return t}parsePath(){const e=[];for(;;){const t=this.consume("DOT");if(!t)break;const n=this.next();if(!n)throw new E('Expected "ID" after "DOT"',t.loc);if("ID"!==n.type)throw new E('Expected "ID" after "DOT"',t.loc);e.push({...n,type:"ID",value:n.value})}return e}parseSequence(){const e=[];for(;!this.match("RP");){const t=this.parseExp(e=>"COMMA"===e.type?"BREAK":void 0);if(!t)break;e.push(t)}return e}parsePipe(){const e=this.next(),t={...e,type:"ID",value:e.value},n=this.consume("LP");if(n&&(t.args=this.parseSequence(),!this.consume("RP")))throw new E('Expected "RP" after "LP"',n.loc);return t}next(){return this.tokens[this.index++]??null}back(){return this.tokens[this.index--]}peek(){return this.tokens.at(this.index)??null}match(e){return this.peek()?.type===e}consume(e){if(this.match(e))return this.next()}}const M=new Set(["AND","OR","IS","EQ","NE","GT","LT","GE","LE","IN","NI","OF","WITH","ADD","SUB","MUL","DIV","MOD","ASSIGN"]);function U(e){return M.has(e)}function F(e){if("ID"===e.type||"LIT"===e.type||"LP"===e.type)throw new E(`Unexpected "${e.raw??e.value}"`,e.loc)}function W(e,t){if("SEQ"===e.type){if(e.elements.some(e=>"ID"!==e.type||e.path||e.args))throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}else if("ID"!==e.type||e.path||e.args)throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}function X(e,t){return"LP"!==t.type&&D[e.type]>D[t.type]}class G{constructor(){Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}traverse(e){this.body?.forEach(e)}}class z extends G{constructor(e,t){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEMPLATE"})}}var B;function q(e){return e.replace(/\\([{}])/g,"$1")}e.TokenType=void 0,(B=e.TokenType||(e.TokenType={})).TEXT="TEXT",B.OUTPUT="OUTPUT",B.DIRECTIVE="DIRECTIVE",B.COMMENT="COMMENT";class K{constructor(t){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenPatterns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"markerIndices",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1});const{commentOpen:n,commentClose:i,directiveOpen:r,directiveClose:s,outputOpen:o,outputClose:a}=this.options;this.tokenPatterns=[[e.TokenType.COMMENT,n,i],[e.TokenType.DIRECTIVE,r,s],[e.TokenType.OUTPUT,o,a]].sort(([,e],[,t])=>e.length>t.length?-1:1),this.markerIndices=new Map;for(const[,e]of this.tokenPatterns)e.length>0&&this.markerIndices.set(e[0],this.markerIndices.get(e[0])||0)}tokenize(e){for(this.template=e,this.length=e.length,this.index=0,this.line=1,this.column=1,this.tokens=[];this.index<this.length;)this.consumeSpecialTokens()||this.consumeTextToken();return this.tokens}consumeSpecialTokens(){return this.tokenPatterns.some(([t,n,r])=>{if(!this.lookahead(n))return!1;const s={line:this.line,column:this.column},o=this.template.indexOf(r,this.index+n.length);if(-1===o)throw new i(`Unclosed "${n}"`,this.template,{start:s,end:P(n,{...s})});const a=this.lookahead("-",n.length),l="-"===this.template[o-1],c=this.template.slice(this.index+n.length+ +a,o-+l),u=P(this.template.slice(this.index,this.index=o+r.length),this),p={type:t,val:q(c),strip:{before:a,after:l},loc:{start:s,end:u}};if(t===e.TokenType.DIRECTIVE){let e=0,t="";for(;e<c.length;){const n=c[e];if(/\S/.test(n))t+=n;else if(t)break;e++}Object.assign(p,{name:t,expression:e===c.length||/^\s*$/m.test(c.slice(e+1))?null:{val:c.slice(e+1),loc:{start:P(c.slice(0,e+1),P(`${n}${a?"-":""}`,{...s})),end:{line:this.line,column:this.column-r.length-+l}}}})}return this.tokens.push(p),!0})}consumeTextToken(){const t=this.findNextSpecialIndex(),n={line:this.line,column:this.column},i=this.template.slice(this.index,t);this.tokens.push({type:e.TokenType.TEXT,val:q(i),loc:{start:n,end:P(i,this)},strip:{}}),this.index=t}lookahead(e,t=0){return this.template.startsWith(e,this.index+t)}findNextSpecialIndex(){const{outputOpen:e,directiveOpen:t,commentOpen:n}=this.options;let i=this.length;for(let r=this.index;r<this.length;r++){if(this.template.startsWith(n,r)){i=r;break}if(this.template.startsWith(t,r)){i=r;break}if(this.template.startsWith(e,r)){i=r;break}}return i}}class J extends K{constructor(){super(...arguments),Object.defineProperty(this,"expParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}parse(t){this.tokenize(t),this.tokens.forEach((t,n)=>{t.type===e.TokenType.TEXT&&(this.tokens[n-1]?.strip?.after&&(t.strip.start=!0),this.tokens[n+1]?.strip?.before&&(t.strip.end=!0))});const n=this.tokens[0]?.loc.start??{line:1,column:1},i=this.tokens.at(-1)?.loc.end??{line:1,column:1};return this.expParser=new A,this.cursor=0,new z(this.parseUntil(),{start:n,end:i})}parseUntil(t){const n=[];let i=null;for(;;){const r=this.peek();if(!r||r.type===e.TokenType.DIRECTIVE&&t&&this.match(t,r))break;i?.strip?.after&&r.type===e.TokenType.TEXT&&(r.strip.start=!0),r.strip?.before&&i?.type===e.TokenType.TEXT&&(i.strip.end=!0);let s=this.options.parsers[r.name?.toLowerCase()??r.type?.toLowerCase()];"string"==typeof s&&(s=this.options.parsers[s]),s||(s=this.options.parsers.unknown);const{cursor:o}=this,a=s?.(r,this);if(a)for(;;){const{value:e,done:t}=a.next();if(t)break;"NEXT"===e?this.advance():e&&n.push(e)}this.cursor===o&&this.advance(),i=r}return n}parseExp({val:e,loc:t}){try{return this.expParser.parse(e,t)}catch(e){this.options.debug(e.loc?new i(e.message,this.template,e.loc):e)}}peek(){return this.tokens.at(this.cursor)??null}advance(){this.cursor++}match(e,t=this.peek()){return e.includes(t?.name?.toLowerCase())}emitExpErr({name:e,loc:t},n=!0){this.options.debug(new i(n?`"${e}" requires expression`:`"${e}" should not have expression`,this.template,t))}}function H(e){return"LIT"===e.type&&"string"==typeof e.value}class V extends G{constructor(e,t,n,i=null,r=null){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"withExp",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"modifier",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"INCLUDE"})}}const Q={start:{line:1,column:1},end:{line:1,column:1}},Y=new Set(["IF","FOR"]);class Z extends O{constructor(e,t,n=!0,i=!1,r={active:!1}){super(),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"revalidate",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"includeLastState",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isRoot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rootNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partials",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheets",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheetKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sources",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hasDynamicInclude",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"flushable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.cache=t}async compile(e,t=!0,n=new Map,i=new Map,r=new Map,s=new Map,o="\0root"){this.template=e,this.isRoot=t,this.partials=n,this.blocks=i,this.stylesheets=s,this.stylesheetKey=o,this.sources=r,this.hasDynamicInclude=!1;const a=this.generateCacheKey(e);if(this.cache&&t){const e=this.cache.get(a);if(e){if(e.fingerprint===this.fingerprint()&&await this.isFresh(e))return this.code=e.code,this.mappings=e.mappings,this.compiled=e,this;this.cache.delete(a)}}if(this.rootNode=new J(this.options).parse(e),this.state={},this.start(this.isRoot),this.isRoot&&(this.pushResourceLimitCounters(),this.pushRaw(null,"let ss_u=0;")),await this.parseTemplates(),this.isRoot){if(this.includeLastState.active&&this.pushRaw(null,"const il_=new Map();","let il_i_=0;","const il_n_=Math.random().toString(36).slice(2);","const il_re_=/\\u0000JLAST[a-z0-9]+:\\d+\\u0000/g;","const il_resolve_=async(v_,seen_=new Set())=>{","const matches_=[...v_.matchAll(il_re_)];","let cursor_=v_.length;","const parts_=[];","for(let i_=matches_.length-1;i_>=0;i_--){","const match_=matches_[i_],marker_=match_[0],start_=match_.index,item_=il_.get(marker_);","parts_.push(v_.slice(start_+marker_.length,cursor_));","if(item_&&!seen_.has(item_.path)){","const output_=await il_resolve_(await item_.render(),seen_);","if(!seen_.has(item_.path)){seen_.add(item_.path);parts_.push(output_);}","}","cursor_=start_;","}","parts_.push(v_.slice(0,cursor_));",'return parts_.reverse().join("");',"};"),this.partials.size||this.hasDynamicInclude){const{maxIncludeDepth:e}=u(this.options.security);this.pushRaw(null,`const tc_=${y};`,"let d_=0;","const inc_=new Set();","const p={");for(const[t,n]of this.partials)this.pushRaw(null,`${JSON.stringify(t)}:async(c)=>{`,`if(d_>=${e})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(t)} are nested too deeply`)});`,"d_++;","try{return await(async()=>{",n,"})();}finally{d_--;}","},");this.pushRaw(null,"};")}if(this.blocks.size){this.pushRaw(null,"const b={");for(const[e,t]of this.blocks){this.pushRaw(null,`${JSON.stringify(e)}:{`,"u:0,","s:["),this.state.block=e;for(const e of t)this.pushRaw(null,"async()=>{",'let s="";'),await this.compileNodes(e.body),this.pushRaw(null,"return s;","},");this.state.block=void 0,this.pushRaw(null,"],","},")}this.pushRaw(null,"};")}this.pushRaw(null,"const ss_=[");for(const[,e]of this.stylesheets){this.pushRaw(null,"async()=>{",'let s="";');for(const t of e)await this.compileNodes(t.body);this.pushRaw(null,"return s;","},")}this.pushRaw(null,"];")}return this.flushable=this.isRoot&&this.stream&&!this.includeLastState.active,await this.compileNode(this.rootNode),this.flushable=!1,this.isRoot&&this.includeLastState.active&&this.pushRaw(null,"s=await il_resolve_(s);"),this.end(),this.cache&&t&&(this.compiled={code:this.code,mappings:this.mappings,sources:this.sources,fingerprint:this.fingerprint()},this.cache.set(a,this.compiled)),this}get script(){var e;return this.compiled?(e=this.compiled).script??(e.script=super.script):super.script}generateCacheKey(e){return b(e,this.stream)}fingerprint(){return m(this.options)}pushResourceLimitCounters(){const{maxLoopIterations:e,maxCallDepth:t}=u(this.options.security);null!=e&&this.pushRaw(null,"let li_=0;"),null!=t&&this.pushRaw(null,"let cd_=0;")}async isFresh({sources:e}){if(!this.revalidate)return!0;try{for(const[t,n]of e)if(await this.options.loader(t)!==n)return!1}catch{return!1}return!0}async parseTemplates(){const{partials:e,blocks:t,stylesheets:n}=this.collectPartialsAndBlocks();if(this.isRoot)for(const t of this.options.preloadIncludes)e.has(t)||e.set(t,new V({type:"LIT",value:t,loc:Q},Q,{before:!1,after:!1}));for(const[t,n]of e)if(!this.partials.has(t)){let e;try{e=await this.options.loader(t)}catch{throw new i(`Failed to load template from "${t}"`,this.template,n.loc)}this.sources.set(t,e??""),this.partials.set(t,""),e&&await this.compilePartial(t,n,e)}for(const e of t){const{val:{value:t}}=e;this.blocks.has(t)||this.blocks.set(t,[]),this.blocks.get(t).push(e)}n.length&&!this.stylesheets.has(this.stylesheetKey)&&this.stylesheets.set(this.stylesheetKey,n)}collectPartialsAndBlocks(){const e=new Map,t=[],n=[],i=r=>{if("INCLUDE"===r.type){const t=r;H(t.val)?(e.has(t.val.value)||e.set(t.val.value,t),"last"===t.modifier&&(this.includeLastState.active=!0)):this.hasDynamicInclude=!0}"BLOCK"===r.type&&t.push(r),"STYLESHEET"===r.type&&n.push(r),r.traverse(i)};return i(this.rootNode),{partials:e,blocks:t,stylesheets:n}}async compileNode(e){if("TEMPLATE"===e.type){for(const t of e.body)await this.compileNode(t),this.flushable&&"TEXT"!==t.type&&this.pushFlush();return}let t=this.options.compilers[e.type];"string"==typeof t&&(t=this.options.compilers[t]),t||(t=this.options.compilers.UNKNOWN);const n=this.checkpoint(),{flushable:r}=this;Y.has(e.type)||(this.flushable=!1);try{await(t?.(e,this))}catch(t){if(this.flushable=r,"CompileError"===t?.name)throw t;this.rollback(n),this.options.debug(new i(`Invalid "${e.type.toLowerCase()}" directive`,this.template,e.loc))}this.flushable=r}async compileNodes(e){for(const t of e)await this.compileNode(t)}async compilePartial(e,t,n){try{const{code:t}=await new Z(this.options,void 0,!0,!1,this.includeLastState).compile(n,!1,this.partials,this.blocks,this.sources,this.stylesheets,e);this.partials.set(e,t)}catch{this.options.debug(new i("Failed to compile template",this.template,t.loc))}}}var ee=Object.freeze({__proto__:null,abs:function(e=0){return Math.abs(e)},add:function(e=0,t=0){return e+t},capitalize:function(e=""){return e.replace(/\b\w/g,e=>e.toUpperCase())},ceil:function(e=0){return Math.ceil(e)},chunk:function(e,t){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},compact:function(e=[]){return e.filter(e=>null!=e)},currency:function(e,t="USD",n="en-US"){return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(e)},date:function(e,t="ISO"){const n=e instanceof Date?e:new Date(e);if(isNaN(n.getTime()))return"";switch(t){case"ISO":default:return n.toISOString();case"date":return n.toISOString().split("T")[0];case"time":return n.toTimeString().split(" ")[0];case"locale":return n.toLocaleDateString();case"locale-time":return n.toLocaleTimeString();case"locale-datetime":return n.toLocaleString()}},defaults:function(e,t){return{...t,...e}},delay:async function(e,t){return await new Promise(e=>setTimeout(e,t)),e},div:function(e=0,t=1){return e/t},entries:function(e={}){return Object.entries(e)},escape:l,even:function(e=0){return+e%2==0},fallback:function(e,t,n=!1){return n?e||t:e??t},fetchUrl:async function(e,t={}){return(await fetch(e,t)).text()},first:function(e=[]){return[...e][0]},fixed:function(e,t=2){return Number(e).toFixed(t)},get:function(e,...t){return t.reduce((e,t)=>e&&"object"==typeof e&&!$(t)&&t in e?e[t]:void 0,e)},groupby:function(e=[],t){return e.reduce((e,n)=>{const i=n[t];return{...e,[i]:[...e[i]||[],n]}},{})},invert:function(e){return Object.entries(e).reduce((e,[t,n])=>({...e,[String(n)]:t}),{})},join:function(e=[],t=""){return[...e].join(t)},json:function(e=null,t=0){return new c(JSON.stringify(e,null,t))},keys:function(e={}){return Object.keys(e)},last:function(e=[]){return[...e].reverse()[0]},length:function(e=""){return e.length},lower:function(e=""){return e.toLowerCase()},map:function(e=[],t,n){return e.map(e=>$(t)?n:e[t]??n)},max:function(e=0,...t){return Math.max(e,...t)},merge:function(e,...t){return Object.assign({},e,...t)},min:function(e=0,...t){return Math.min(e,...t)},mul:function(e=0,t=1){return e*t},odd:function(e=0){return+e%2==1},omit:function(e={},...t){return Object.entries(e).reduce((e,[n,i])=>t.includes(n)?e:{...e,[n]:i},{})},percent:function(e,t=0){return`${(100*e).toFixed(t)}%`},pick:function(e={},...t){return t.reduce((t,n)=>$(n)?t:{...t,[n]:e[n]},{})},pluck:function(e,t){return e.map(e=>e[t])},repeat:function(e="",t=0){return e.repeat(t)},replace:function(e="",t,n){return e.replace(new RegExp(t,"g"),n)},reverse:function(e=[]){return Array.isArray(e)?[...e].reverse():[...e].reverse().join("")},round:function(e,t=0){return Number(`${Math.round(Number(`${e}e${t}`))}e-${t}`)},safe:function(e=""){return new c(e)},shuffle:function(e){const t=[...e];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t},slice:function(e="",t=0,n){return e.slice(t,n)},slugify:function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")},sort:function(e=[]){return Array.isArray(e)?[...e].sort():[...e].sort().join("")},split:function(e="",t=""){return e.split(t)},stripTags:function(e){return e.replace(/<[^>]*>/g,"")},sub:function(e=0,t=0){return e-t},sum:function(e=[]){return e.reduce((e,t)=>e+t,0)},timeAgo:function(e){const t=e instanceof Date?e:new Date(e),n=new Date,i=Math.floor((n.getTime()-t.getTime())/1e3),r=[{label:"year",seconds:31536e3},{label:"month",seconds:2592e3},{label:"day",seconds:86400},{label:"hour",seconds:3600},{label:"minute",seconds:60}];for(const e of r){const t=Math.floor(i/e.seconds);if(t>=1)return`${t} ${e.label}${t>1?"s":""} ago`}return"just now"},trim:function(e=""){return e.trim()},truncate:function(e="",t=0,n="..."){return e.slice(0,t)+(e.length>t?n:"")},unique:function(e=""){return Array.isArray(e)?Array.from(new Set(e)):Array.from(new Set(e)).join("")},upper:function(e=""){return e.toUpperCase()},urldecode:function(e=""){return decodeURIComponent(e)},urlencode:function(e=""){return encodeURIComponent(e)},values:function(e={}){return Object.values(e)},wordCount:function(e){return e.trim().split(/\s+/).filter(Boolean).length}});const te={filters:{},parsers:{},compilers:{},plugins:[],debug:e=>{throw e}},ne={...te,commentOpen:"{{#",commentClose:"#}}",directiveOpen:"{{",directiveClose:"}}",outputOpen:"{{=",outputClose:"}}"},ie={...ne,trimWhitespace:!1,stripComments:!1,loader:async()=>"",preloadIncludes:[]},re={...ie,globals:{},autoEscape:!0,cache:{enabled:!0,maxSize:1e3,ttl:36e5,revalidate:!0},security:{}},se=(e,...t)=>{const n={...e},i=e=>{n.filters={...n.filters,...e.filters},n.parsers={...n.parsers,...e.parsers},n.compilers={...n.compilers,...e.compilers}};return e.plugins?.forEach(i),t.forEach(({plugins:e,filters:t,parsers:r,compilers:s,...o})=>{for(const[e,t]of Object.entries(o))void 0!==t&&(n[e]=t);i({filters:t,parsers:r,compilers:s}),e?.forEach(i)}),n};const oe={BLOCK:async function({val:{value:e},loc:t},n){const i=JSON.stringify(e);n.pushRaw(t,`if(b[${i}]&&!(b[${i}].u++)){`,`s+=await b[${i}].s?.pop()?.()??"";`,"}")},SUPER:async function({loc:e},t){t.state.block?t.pushRaw(e,`s+=await b[${JSON.stringify(t.state.block)}]?.s?.pop()?.()??"";`):t.options.debug?.(new i('"super" should be used inside a block',t.template,e))}};class ae extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BLOCK"})}}class le extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SUPER"})}}const ce={compilers:oe,parsers:{block:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endblock"]);t.match(["endblock"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ae(t.parseExp(e.expression),n,e.loc,e.strip)},super:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new le(e.val,e.loc,e.strip))},endblock:"unexpected"}},ue={AND:"&&",OR:"||",IS:"",NOT:"!",EQ:"===",NE:"!==",GT:">",LT:"<",GE:">=",LE:"<=",IN:" in ",NI:" in ",OF:" of ",WITH:" with ",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",ID:"",LIT:"",IF:"",ELSE:""},pe=new Set(Object.getOwnPropertyNames(Object.prototype));class he{constructor(){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}compile(e,t=y,n=g){return this.context=t,this.filters=n,e?this.compileExp(e):'""'}compileExp(e){switch(e.type){case"NOT":return this.compileNot(e);case"ID":return this.compileId(e);case"LIT":return this.compileLit(e);case"PIPE":return this.compilePipe(e);case"ASSIGN":return this.compileAssign(e);case"IS":return this.compileIs(e);case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.compileBinary(e);case"IF":return this.compileTernary(e);case"SEQ":return this.compileSeq(e);default:return""}}compileNot({argument:e}){return`!${this.compileExp(e)}`}compileId({value:e,path:t,args:n}){let i=pe.has(e)?`(Object.hasOwn(${this.context},"${e}")?${this.context}.${e}:undefined)`:`${this.context}.${e}`;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=`(${this.compileArgs(n).join(",")})`),i}compileArgs(e){const t=[],n=[];for(const i of e)if("ASSIGN"===i.type){const{left:e,right:t}=i;n.push(`${e.value}:${this.compileExp(t)}`)}else t.push(this.compileExp(i));return n.length&&t.push(`{${n.join(",")}}`),t}compileLit({value:e}){return void 0===e?"undefined":"number"==typeof e&&e<0?`(${e})`:JSON.stringify(e)}compileSeq({elements:e}){return`(${e.map(e=>this.compileExp(e)).join(",")})`}compilePipe({left:e,right:t}){const{value:n,args:i=[]}=t,r=`(${this.filters}.${n}||u_("${n}")).call(${[this.context,this.compileExp(e),...this.compileArgs(i)].join(",")})`;return`(${w}=${r},${w} instanceof Promise?await ${w}:${w})`}compileAssign({left:e,right:t}){return"ID"===e.type?`Object.assign(${this.context},{${e.value}:${this.compileExp(t)}});`:`Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(t)},${e.elements.map(({value:e})=>`"${e}"`).join(",")}));`}compileIs({left:e,right:t}){return`typeof ${this.compileExp(e)}===${this.compileExp(t)}`}compileBinary({type:e,left:t,right:n}){const i=`${this.compileExp(t)}${ue[e]}${this.compileExp(n)}`;return"NI"===e?`!(${i})`:i}compileTernary({test:e,consequent:t,alternative:n}){return`${this.compileExp(e)}?${this.compileExp(t)}:${n?this.compileExp(n):'""'}`}}const fe={CALL:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`s+=await ${(new he).compile(e,i.context)}(async()=>{`,'let s="";'),await i.compileNodes(t),i.pushRaw(null,"return s;",'})??"";')}};class de extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALL"})}}const be={compilers:fe,parsers:{call:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcall"]);t.match(["endcall"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new de(t.parseExp(e.expression),n,e.loc,e.strip)},endcall:"unexpected"}};const me={CAPTURE:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`${i.context}.${e.value}=${g}.safe.call(${i.context},await(async(s)=>{`),await i.compileNodes(t),i.pushRaw(null,'return s;})(""));')}};class ye extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CAPTURE"})}}const ge={compilers:me,parsers:{capture:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcapture"]);t.match(["endcapture"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ye(t.parseExp(e.expression),n,e.loc,e.strip)},endcapture:"unexpected"}};const we={COMMENT:async function({val:e,loc:t},n){n.options.stripComments||n.pushStr(t,`\x3c!--${e}--\x3e`)}};class ve extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"COMMENT"})}}const xe={compilers:we,parsers:{comment:function*({val:e,loc:t,strip:n}){yield"NEXT",yield new ve(e,t,n)}}},Oe="loop:{first:i_===0,index:i_++,last:i_===n_}";function Ee(e,t=new Set){return!(!e||"object"!=typeof e||t.has(e))&&(t.add(e),"ASSIGN"===e.type||Object.entries(e).some(([e,n])=>"args"===e&&Array.isArray(n)?n.some(e=>Ee("ASSIGN"===e.type?e.right:e,t)):Ee(n,t)))}function Pe(e){return e.every(e=>{switch(e.type){case"TEXT":case"COMMENT":case"BREAK":case"CONTINUE":return!0;case"OUTPUT":return!Ee(e.val);case"IF":return!Ee(e.test)&&Pe(e.body)&&e.alternatives.every(e=>!Ee(e.test)&&Pe(e.body));case"FOR":return!Ee(e.loop.right)&&Pe(e.alternative?.body??[]);default:return!1}})}const je={FOR:async function({loop:{left:e,right:t,loc:n},body:i,alternative:r},s){const{context:o}=s,a=new he;s.pushRaw(n,"{",`const t_=${a.compile(t,o)},`,"a_=Array.isArray(t_)?t_:Array.from(t_??[]),n_=a_.length;"),r&&(s.pushRaw(n,"if(!n_){"),await s.compileNodes(r.body),s.pushRaw(n,"}else{"));const l="SEQ"===e.type?e.elements.map(e=>"ASSIGN"===e.type?[e.left.value,`v_.${e.left.value}===undefined?${a.compile(e.right,o)}:v_.${e.left.value}`]:[e.value,`v_.${e.value}`]):[[e.value,"v_"]],c=s.in();s.pushRaw(n,"let i_=0;");const{maxLoopIterations:p}=u(s.options.security),h=null==p?[]:[`if(++li_>${p})throw new Error(${JSON.stringify(`Loop iteration limit of ${p} exceeded`)});`];Pe(i)?s.pushRaw(n,`const ${c}={...${o}};`,"for(const v_ of a_){",...h,`${c}.loop={${Oe.slice(6)};`,...l.map(([e,t])=>`${c}.${e}=${t};`)):s.pushRaw(n,"for(const v_ of a_){",...h,`const ${c}={`,`...${o},`,`${Oe},`,...l.map(([e,t])=>`${e}:${t},`),"};"),await s.compileNodes(i),s.out(),s.flushable&&s.pushFlush(),s.pushRaw(null,r?"}}}":"}}")},BREAK:function({loc:e},t){t.pushRaw(e,"break;")},CONTINUE:function({loc:e},t){t.pushRaw(e,"continue;")}};class Te extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternative",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"FOR"})}traverse(e){this.body.forEach(e),this.alternative?.body.forEach(e)}}let $e=class extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}};class Se extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BREAK"})}}class ke extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CONTINUE"})}}const Ne=new WeakMap;const Ie={for:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Ne.set(t,!0),yield"NEXT";const n=t.parseUntil(["else","endfor"]);Ne.set(t,!1);let r=null;if(t.match(["else"])){const e=function*(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endfor"]);yield"NEXT",yield new $e(t.parseUntil(["endfor"]),e.loc,e.strip)}(t.peek(),t);for(;;){const{value:t,done:n}=e.next();if(n)break;if(t){if("NEXT"===t){yield"NEXT";continue}r=t}}}t.match(["endfor"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const s=t.parseExp(e.expression);"OF"===s?.type?yield new Te(s,n,r,e.loc,e.strip):s&&t.options.debug?.(new i(`"${e.name}" expects "item of items"`,t.template,e.loc))},break:function*(e,t){e.expression?t.emitExpErr(e,!1):Ne.get(t)?(yield"NEXT",yield new Se(e.val,e.loc,e.strip)):t.options.debug?.(new i('"break" directive used outside of a loop',t.template,e.loc))},continue:function*(e,t){e.expression?t.emitExpErr(e,!1):Ne.get(t)?(yield"NEXT",yield new ke(e.val,e.loc,e.strip)):t.options.debug?.(new i('"continue" directive used outside of a loop',t.template,e.loc))},endfor:"unexpected"},_e={compilers:je,parsers:Ie};const Le={IF:async function({test:e,body:t,alternatives:n},i){i.pushRaw(e.loc,`if(${(new he).compile(e,i.context)}){`),await i.compileNodes(t),i.pushRaw(null,"}");for(const e of n)"ELSE_IF"===e.type?i.pushRaw(e.test.loc,`else if(${(new he).compile(e.test,i.context)}){`):i.pushRaw(null,"else{"),await i.compileNodes(e.body),i.pushRaw(null,"}")}};class Ce extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternatives",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"IF"})}traverse(e){this.body?.forEach(e),this.alternatives?.forEach(t=>t.body?.forEach(e))}}class Re extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE_IF"})}}class De extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}}function*Ae(e,t){if(!e.expression)return t.emitExpErr(e),yield"NEXT",void t.parseUntil(["else","elseif","elsif","elif","endif"]);yield"NEXT",yield new Re(t.parseExp(e.expression),t.parseUntil(["else","elseif","elsif","elif","endif"]),e.loc,e.strip)}function*Me(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endif"]);yield"NEXT",yield new De(t.parseUntil(["endif"]),e.loc,e.strip)}const Ue={compilers:Le,parsers:{if:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["else","elseif","elsif","elif","endif"]),r=[];for(;t.match(["else","elseif","elsif","elif"]);){const e=t.peek();if("else"===e.name.toLowerCase()){const n=Me(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}else{const n=Ae(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}}t.match(["endif"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new Ce(t.parseExp(e.expression),n,r,e.loc,e.strip)},elseif:"unexpected",elsif:"unexpected",elif:"unexpected",endif:"unexpected"}};const Fe=/\s+(once|last)\s*$/;const We={compilers:{INCLUDE:async function({val:e,loc:t,withExp:n,modifier:i},r){const s=new he,o=H(e)?JSON.stringify(e.value):s.compile(e,r.context),a=n?`{...${r.context},...${s.compile(n,r.context)}}`:"tc_";if("last"===i&&H(e))return void r.pushRaw(t,"{",'const ilm_="\\u0000JLAST"+il_n_+":"+(il_i_++)+"\\u0000";',`const ilc_=${a};`,`il_.set(ilm_,{path:${JSON.stringify(e.value)},render:async()=>{return (await p[${o}]?.(ilc_))??"";}});`,"s+=ilm_;","}");const l=`s+=await p[${o}]?.(${a})??"";`;"once"!==i?r.pushRaw(t,l):r.pushRaw(t,`{const inc_p_=${o};if(!inc_.has(inc_p_)){inc_.add(inc_p_);s+=await p[inc_p_]?.(${a})??"";}}`)}},parsers:{include:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";let n=e.expression.val,i=null;const r=Fe.exec(n);r&&(i=r[1],n=n.slice(0,r.index));const s=t.parseExp({val:n,loc:e.expression.loc});if(s){if("WITH"===s.type){const{left:t,right:n}=s;return void(yield new V(t,e.loc,e.strip,n,i))}yield new V(s,e.loc,e.strip,null,i)}}}};const Xe={MACRO:async function({val:{value:e,args:t},loc:n,body:i},r){const{context:s}=r,o=new he,{maxCallDepth:a}=u(r.options.security);r.pushRaw(n,`${s}.${e}=(...a_)=>async(_c)=>{`,...null==a?[]:[`if(cd_>=${a})throw new Error(${JSON.stringify(`Macro call depth limit of ${a} exceeded`)});`,"cd_++;","try{"],'let s="";',`const ${r.in()}={`,`...${s},`,...(t??[]).map((e,t)=>"ASSIGN"===e.type?`${e.left.value}:a_[${t}]===undefined?${o.compile(e.right)}:a_[${t}],`:`${e.value}:a_[${t}],`),"};"),await r.compileNodes(i),r.out(),r.pushRaw(null,"return s;",...null==a?[]:["}finally{cd_--;}"],"};")},CALLER:function({loc:e},t){t.pushRaw(e,'s+=await _c?.()??"";')}};class Ge extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"MACRO"})}}class ze extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALLER"})}}const Be=new WeakMap;const qe={compilers:Xe,parsers:{macro:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Be.set(t,!0),yield"NEXT";const n=t.parseUntil(["endmacro"]);Be.set(t,!1),t.match(["endmacro"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const r=t.parseExp(e.expression);if("ID"===r.type){if(r.args?.length)for(const n of r.args)if("ASSIGN"===n.type){if("ID"!==n.left.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc))}else if("ID"!==n.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc));yield new Ge(r,n,e.loc,e.strip)}else t.options.debug?.(new i("Invalid macro definition",t.template,e.loc))},caller:function*(e,t){e.expression?t.emitExpErr(e,!1):Be.get(t)?(yield"NEXT",yield new ze(e.val,e.loc,e.strip)):t.options.debug?.(new i('"caller" directive used outside of a macro',t.template,e.loc))},endmacro:"unexpected"}};const Ke={OUTPUT:async function({val:e},t){t.pushVar(e.loc,(new he).compile(e,t.context))}};class Je extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"OUTPUT"})}}const He={compilers:Ke,parsers:{output:function*(e,t){yield"NEXT";const n=P(`${t.options.outputOpen}${e.strip.before?"-":""}`,{...e.loc.start});yield new Je(t.parseExp({val:e.val,loc:{start:n,end:e.loc.end}}),e.loc,e.strip)}}};const Ve={SET:async function({val:e,loc:t},n){n.pushRaw(t,(new he).compile(e,n.context))}};class Qe extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SET"})}}const Ye={compilers:Ve,parsers:{set:function*(e,t){e.expression?(yield"NEXT",yield new Qe(t.parseExp(e.expression),e.loc,e.strip)):t.emitExpErr(e)}}};const Ze={STYLESHEET:async function(){},STYLESHEETS:async function({loc:e},t){t.pushRaw(e,"if(!ss_u++){","for(const f_ of ss_)s+=await f_();","}")}};class et extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEET"})}}class tt extends G{constructor(e,t){super(),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEETS"})}}const nt={compilers:Ze,parsers:{stylesheet:function*(e,t){if(e.expression)return void t.emitExpErr(e,!1);yield"NEXT";const n=t.parseUntil(["endstylesheet"]);t.match(["endstylesheet"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new et(n,e.loc,e.strip)},endstylesheet:"unexpected",stylesheets:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new tt(e.loc,e.strip))}}};const it={TEXT:async function({val:e,loc:t,strip:{start:n,end:i}},r){(n||r.options.trimWhitespace)&&(e=e.replace(/^\s+/,"")),(i||r.options.trimWhitespace)&&(e=e.replace(/\s+$/,"")),r.pushStr(t,e)}};class rt extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEXT"})}}const st={compilers:it,parsers:{text:function*(e){yield"NEXT",yield new rt(e.val,e.loc,e.strip)}}};const ot={UNEXPECTED:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unexpected "${e}"--\x3e`)}};class at extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNEXPECTED"})}}const lt={compilers:ot,parsers:{unexpected:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unexpected "${n}"`,t.template,e.loc)),yield"NEXT",yield new at(n,e.val,e.loc,e.strip)}}};const ct={UNKNOWN:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unknown "${e}"--\x3e`)}};class ut extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNKNOWN"})}}const pt={compilers:ct,parsers:{unknown:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unknown "${n}"`,t.template,e.loc)),yield"NEXT",yield new ut(n,e.val,e.loc,e.strip)}}};const ht={WITH:async function(e,t){const{context:n}=t,i=new he;t.pushRaw(e.loc,`const ${t.in()}={...${i.compile(e.expression,n)}};`),await t.compileNodes(e.body),t.out()}};class ft extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"expression",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"WITH"})}traverse(e){this.body?.forEach(e)}}const dt=[ce,be,xe,ge,_e,Ue,We,qe,Ye,nt,st,He,lt,pt,{parsers:{with:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endwith"]);t.match(["endwith"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ft(t.parseExp(e.expression),n,e.loc,e.strip)},endwith:"unexpected"},compilers:ht}];class bt extends i{constructor(e,t,n,i){super(e,t,void 0,i),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"getLoc",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="RenderError",bt.captureStackTrace?.(this,this.constructor)}get details(){return this.loc=this.getLoc(),super.details}}const mt=new Error("Stream cancelled");class yt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sandbox",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"escape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiling",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.options=se(re,{filters:ee,plugins:dt},e),this.filters=Object.assign(Object.create(null),this.options.filters);const n=this.options.security?.deepEscape?h:l,{autoEscape:i}=this.options;this.escape=e=>"string"==typeof e?i?l(e):e:null==e?"":e instanceof c?`${e}`:i?n(e):e,!1!==this.options.cache?.enabled&&(this.cache=new t(this.options.cache)),this.options.security?.sandbox&&(this.sandbox=new p(this.options.security))}async render(e,t){const n=this.cache?.peek(b(e));if(n?.script&&0===n.sources.size&&n.fingerprint===m(this.options)){this.cache.get(b(e));try{return await this.run(n.script,t)}catch(t){const i=new v;return i.mappings=n.mappings,this.options.debug(this.wrapError(t,e,i)),""}}let i;try{return i=await this.compile(e),await this.run(i.script,t)}catch(t){this.options.debug(this.wrapError(t,e,i??new v))}return""}template(e){return t=>this.render(e,t)}async renderCompiled(e,t={}){try{return await this.run(e,t)}catch(e){this.options.debug(e)}return""}renderStream(e,t={}){let n,i=!1;return new ReadableStream({start:r=>{const s=e=>{if(i)throw mt;if(r.enqueue(e),(r.desiredSize??1)<=0)return new Promise(e=>{n=e})};let o;(async()=>{try{o=await this.compile(e,!0);const n=await this.run(o.script,t,s);n&&!i&&r.enqueue(n),r.close()}catch(t){if(t===mt)return;try{this.options.debug(this.wrapError(t,e,o??new v)),r.close()}catch(e){r.error(e)}}})()},pull:()=>{n?.(),n=void 0},cancel:()=>{i=!0,n?.()}})}compile(e,t=!1){const n=b(e,t);let i=this.compiling.get(n);return i||(i=new Z(this.options,this.cache,this.options.cache?.revalidate??!0,t).compile(e).finally(()=>this.compiling.delete(n)),this.compiling.set(n,i)),i}wrapError(e,t,n){return"CompileError"===e?.name?e:new bt(`${e?.message??e}`,t,()=>{const t=e?.stack?.match(/<anonymous>:(\d+):(\d+)\)/);if(!t)return e?.stack??"";const[i]=n.getSourceLoc({line:+t[1]-2,column:+t[2]});return i})}run(e,t,n){const i=e(this.sandbox?{...this.sandbox.createSecureContext(this.options.globals),...t}:{...this.options.globals,...t},this.escape,this.filters,n),{timeoutMs:r}=this.options.security??{};if(null==r)return i;let s;return Promise.race([Promise.resolve(i).finally(()=>{clearTimeout(s)}),new Promise((e,t)=>{s=setTimeout(()=>{t(new Error(`Render timed out after ${r}ms`))},r)})])}async renderFile(e,t){return this.render(await this.options.loader(e),t)}clearCache(){this.cache?.clear()}invalidateCache(e){this.cache?.invalidate(e)}getCacheStats(){return this.cache?this.cache.getStats():null}resetCacheStats(){this.cache?.resetStats()}auditTemplate(e){return(new f).auditTemplate(e)}getCSPHeaders(){return new p(this.options.security).generateCSPHeaders()}}class gt{constructor(e){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"variables",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"includes",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"macros",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}async analyze(e,t=new Set){const n=new J(this.options).parse(e);await this.nodes(n.body,t)}async nodes(e=[],t){for(const n of e)await this.node(n,t)}async node(e,t){switch(e.type){case"OUTPUT":this.exp(e.val,t);break;case"IF":this.exp(e.test,t),await this.nodes(e.body,t);for(const n of e.alternatives)this.exp(n.test,t),await this.nodes(n.body,t);break;case"FOR":{this.exp(e.loop.right,t),await this.nodes(e.alternative?.body,t);const n=new Set(t).add("loop");this.bind(e.loop.left,n,t),await this.nodes(e.body,n);break}case"SET":this.exp(e.val.right,t),this.bind(e.val.left,t,t);break;case"CAPTURE":await this.nodes(e.body,t),t.add(e.val.value);break;case"MACRO":{const n=new Set(t);for(const i of e.val.args??[])this.bind(i,n,t);t.add(e.val.value),this.macros.add(e.val.value),await this.nodes(e.body,n);break}case"CALL":this.exp(e.val,t),await this.nodes(e.body,t);break;case"WITH":this.exp(e.expression,t),await this.nodes(e.body,wt);break;case"BLOCK":this.blocks.add(e.val.value),await this.nodes(e.body,t);break;case"STYLESHEET":default:await this.nodes(e.body,t);break;case"INCLUDE":this.exp(e.val,t),e.withExp&&this.exp(e.withExp,t),"LIT"===e.val.type&&"string"==typeof e.val.value&&await this.include(e.val.value,t)}}async include(e,t){if(this.includes.has(e))return;let n;this.includes.add(e);try{n=await this.options.loader(e)}catch{}n&&await this.analyze(n,new Set(t))}bind(e,t,n){"ID"===e.type?t.add(e.value):"SEQ"===e.type?e.elements.forEach(e=>this.bind(e,t,n)):"ASSIGN"===e.type&&(this.exp(e.right,n),this.bind(e.left,t,n))}exp(e,t){if(e)switch(e.type){case"ID":t===wt||t.has(e.value)||this.variables.add(e.value),e.args?.forEach(e=>this.exp(e,t));break;case"LIT":break;case"NOT":this.exp(e.argument,t);break;case"IF":this.exp(e.test,t),this.exp(e.consequent,t),this.exp(e.alternative,t);break;case"SEQ":e.elements.forEach(e=>this.exp(e,t));break;case"PIPE":{const{left:n,right:i}=e;this.exp(n,t),this.filters.add(i.value);for(const e of i.args??[])this.exp("ASSIGN"===e.type?e.right:e,t);break}default:this.exp(e.left,t),this.exp(e.right,t)}}}const wt=new Set;async function vt(e,t={}){const n=new gt(se(ie,{filters:ee,plugins:dt},t));await n.analyze(e);const i=e=>[...e].sort();return{variables:i(n.variables),filters:i(n.filters),includes:i(n.includes),blocks:i(n.blocks),macros:i(n.macros)}}function xt({variables:e},{includeRuntime:t=!1}={}){const n=e.map(e=>` ${e}?: unknown;`).join("\n");return`// Generated by the Janja precompiler. Do not edit.\nimport type { ${t?"RendererOptions, ":""}Script } from 'janja';\n\n/** The data this template reads. */\nexport interface TemplateData {${n?`\n${n}\n`:""}}\n\nexport declare const script: Script;\n\n${t?"export default function render(\n data?: TemplateData,\n options?: RendererOptions,\n): Promise<string>;":"export default script;"}\n`}function Ot(e){let t=e<0?-e<<1|1:e<<1,n="";do{let e=31&t;t>>>=5,t>0&&(e|=32),n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]}while(t>0);return n}function Et(e,{file:t,source:n,sourceContent:i,line:r}){const s=new Map;for(const t of e)s.set(t.target.start.column,t.source.start);let o=0,a=0,l=0;const c=[...s.entries()].sort(([e],[t])=>e-t).map(([e,t])=>{const n=t.line-1,i=t.column-1,r=Ot(e-o)+Ot(0)+Ot(n-a)+Ot(i-l);return o=e,a=n,l=i,r}).join(",");return{version:3,...t?{file:t}:{},sources:[n],sourcesContent:[i],names:[],mappings:`${";".repeat(r)}${c}`}}async function Pt(e,{includeRuntime:t,sourceMap:n,filename:i,dts:r,...s}={}){const o=new Z(se(ie,{filters:ee,plugins:dt},s));await o.compile(e);const a=`// Generated by the Janja precompiler. Do not edit.${t?"\nimport { renderCompiled } from 'janja';\n":""}\nexport function script(${y}, e, ${g}, w) {\n`,l=t?"\n}\n\nexport default function render(globals = {}, options) {\n return renderCompiled(script, globals, options);\n}\n":"\n}\n\nexport default script;\n";return{code:`${a}${o.code}${l}`,map:n?Et(o.mappings,{source:i??"template.janja",sourceContent:e,line:a.split("\n").length-1}):void 0,dts:r?xt(await vt(e,s),{includeRuntime:t}):void 0}}class jt{constructor(e={}){Object.defineProperty(this,"defaultLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"translations",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pluralRules",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.locale||this.defaultLocale,this.translations=e.translations||{},this.pluralRules=e.pluralRules||this.getDefaultPluralRules()}setLocale(e){this.currentLocale=e}getLocale(){return this.currentLocale}addTranslations(e,t){this.translations[e]||(this.translations[e]={}),this.translations[e]=this.mergeDeep(this.translations[e],t)}translate(e,t={}){const n=this.getTranslation(e);return n?this.interpolate(n,t):e}t(e,t={}){return this.translate(e,t)}pluralize(e,t,n={}){const i=`${e}.${this.getPluralForm(t)}`,r=this.getTranslation(i);if(r)return this.interpolate(r,{...n,count:t});const s=this.getTranslation(e);return s?this.interpolate(s,{...n,count:t}):e}formatDate(e,t){const n="string"==typeof e?new Date(e):e;return new Intl.DateTimeFormat(this.currentLocale,t).format(n)}formatNumber(e,t){return new Intl.NumberFormat(this.currentLocale,t).format(e)}formatCurrency(e,t,n){return new Intl.NumberFormat(this.currentLocale,{...n,style:"currency",currency:t}).format(e)}getTranslation(e){const t=e.split(".");let n=this.translations[this.currentLocale];for(const e of t){if(!n||"object"!=typeof n||!(e in n))return null;n=n[e]}return"string"==typeof n?n:null}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>void 0!==t[n]?String(t[n]):n)}getPluralForm(e){const t=this.pluralRules[this.currentLocale];return t?t(e):this.pluralRules[this.defaultLocale](e)}getDefaultPluralRules(){return{en:e=>1===e?"one":"other",es:e=>1===e?"one":"other",fr:e=>0===e||1===e?"one":"other",de:e=>1===e?"one":"other",ru:e=>{const t=e%10,n=e%100;return 1===t&&11!==n?"one":t>=2&&t<=4&&!(n>=12&&n<=14)?"few":0===t||t>=5&&t<=9?"many":"other"},ja:()=>"other",zh:()=>"other",ar:e=>0===e?"zero":1===e?"one":2===e?"two":e%100>=3&&e%100<=10?"few":e%100>=11&&e%100<=99?"many":"other"}}mergeDeep(e,t){const n={...e};return this.isObject(e)&&this.isObject(t)&&Object.keys(t).forEach(i=>{this.isObject(t[i])?i in e?n[i]=this.mergeDeep(e[i],t[i]):Object.assign(n,{[i]:t[i]}):Object.assign(n,{[i]:t[i]})}),n}isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}}const Tt=new jt;async function $t(e,t={}){let n="";const{data:i={},options:r}=t,s=new yt(r);for(const t of e)n=await s.render(t,{...i,_content:n});return n}const St={trim:!1,stripComments:!1,collapseWhitespace:!1,preserveNewlines:!0};function kt(e){return{...St,...e}}class Nt{constructor(){Object.defineProperty(this,"mixins",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}register(e){this.mixins.set(e.name,e)}registerMultiple(e){for(const t of e)this.register(t)}get(e){return this.mixins.get(e)}has(e){return this.mixins.has(e)}delete(e){return this.mixins.delete(e)}clear(){this.mixins.clear()}list(){return Array.from(this.mixins.keys())}}const It=new Nt;async function _t(e,t={},n=It){const i=n.get(e);if(!i)throw new Error(`Mixin "${e}" not found in registry`);const{data:r={},options:s}=t,o={...i.data,...r};return new yt(s).render(i.template,o)}class Lt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e})}async validate(e){const t=[],n=[],i=e=>{const[n]=e?.suggestions??[];t.push({type:"error",message:`${e?.message??e}`,line:e?.loc?.start.line,column:e?.loc?.start.column,suggestion:n?.fix??n?.message})},r=se(ie,{filters:ee,plugins:dt},this.options,{debug:i});try{const t=new J(r).parse(e);this.checkFilters(t,r.filters,n)}catch(e){i(e)}return{valid:0===t.length,errors:t,warnings:n}}checkFilters(e,t,n,i=new Set){if(e&&"object"==typeof e&&!i.has(e)){i.add(e),"PIPE"!==e.type||"ID"!==e.right?.type||Object.prototype.hasOwnProperty.call(t,e.right.value)||n.push({type:"warning",message:`Unknown filter "${e.right.value}"`,line:e.right.loc?.start.line,column:e.right.loc?.start.column});for(const r of Object.values(e))this.checkFilters(r,t,n,i)}}}const Ct={AND:"and",OR:"or",IS:"is",NOT:"not",EQ:"eq",NE:"ne",GT:"gt",LT:"lt",GE:"ge",LE:"le",IN:"in",NI:"ni",OF:"of",WITH:"with",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"|",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",IF:"if",ELSE:"else"};class Rt{format(e){return e?this.formatExp(e):'""'}formatExp(e){switch(e.type){case"NOT":return this.formatNot(e);case"ID":return this.formatId(e);case"LIT":return this.formatLit(e);case"PIPE":case"IS":case"ASSIGN":case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"OF":case"WITH":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.formatBinary(e);case"IF":return this.formatTernary(e);case"SEQ":return this.formatSeq(e);default:return""}}formatNot({argument:e}){return`${Ct.NOT} ${this.formatExp(e)}`}formatId({value:e,path:t,args:n}){let i=e;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=this.formatSeq({elements:n})),i}formatLit({value:e}){return void 0===e?"undefined":JSON.stringify(e)}formatSeq({elements:e}){return`(${e.map(e=>this.formatExp(e)).join(", ")})`}formatBinary({type:e,left:t,right:n}){return`${this.formatExp(t)} ${Ct[e]} ${this.formatExp(n)}`}formatTernary({test:e,consequent:t,alternative:n}){return`${this.formatExp(t)} ${Ct.IF} ${this.formatExp(e)}${n?` ${Ct.ELSE} ${this.formatExp(n)}`:""}`}}function Dt(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=At(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function At(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if('"'!==s&&"'"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1}return{opens:t,closes:n}}const Mt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Ut=new Set(["pre","textarea","script","style"]),Ft=new Set(["if","for","macro","block","call","capture","with","stylesheet"]),Wt=new Set(["stylesheet"]),Xt=new Set(["else","elif","elseif","elsif"]),Gt=new Set(["endif","endfor","endmacro","endblock","endcall","endcapture","endwith","endstylesheet"]);function zt(e,t){const n=e.match(/^\s*<[A-Za-z][A-Za-z0-9:-]*/);return Boolean(n&&Jt(`${e} `,n[0].length,t)>e.length)}function Bt(e,t){return Jt(`${e} `,0,t)<=e.length}function qt(e,t,n){const i=[];let r=0,s=!0,o=0;if(n.inComment){const s=e.indexOf(t.commentClose);if(-1===s)return{pieces:i,prefixClosers:r};n.inComment=!1,o=s+t.commentClose.length}for(;o<e.length;){if(/\s/.test(e[o])){o+=1;continue}if(e.startsWith(t.commentOpen,o)){const a=e.indexOf(t.commentClose,o+t.commentOpen.length);if(-1===a)return n.inComment=!0,{pieces:i,prefixClosers:r};s=!1,o=a+t.commentClose.length;continue}const a=Kt(e,o,t);a?(a.piece?(i.push(a.piece),!s||"close"!==a.piece.kind&&"mid"!==a.piece.kind?s=!1:r+=1):s=!1,o=a.end):(s=!1,o+=1)}return{pieces:i,prefixClosers:r}}function Kt(e,t,n){const{directiveOpen:i,outputOpen:r}=n;if(e.startsWith(r,t))return{end:Vt(e,t+r.length,n.outputClose)};if(e.startsWith(i,t))return function(e,t,n){const{directiveOpen:i,directiveClose:r}=n,s=Vt(e,t+i.length,r),o=e.slice(t+i.length,s-r.length),a=o.replace(/^\s*-?\s*/,"").match(/^([A-Za-z_]\w*)/)?.[1]?.toLowerCase();if(!a)return{end:s};if(Gt.has(a)){const e=a.startsWith("end")?a.slice(3):a;return{end:s,piece:{kind:"close",sensitive:Wt.has(e)?e:void 0}}}if(Xt.has(a))return{end:s,piece:{kind:"mid"}};if(Ft.has(a))return{end:s,piece:{kind:"open",sensitive:Wt.has(a)?a:void 0}};return{end:s}}(e,t,n);if(e.startsWith("\x3c!--",t)){const n=e.indexOf("--\x3e",t+4);return{end:-1===n?e.length:n+3}}return"<"===e[t]?function(e,t,n){if(e.startsWith("</",t)){let i=t+2;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=Jt(e,i,n);return!s||Mt.has(s)?{end:o}:{end:o,piece:{kind:"close",sensitive:Ut.has(s)?s:void 0}}}if(e.startsWith("<!",t)||e.startsWith("<?",t))return{end:Jt(e,t+2,n)};let i=t+1;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=Jt(e,i,n),a=e.slice(t,o),l=/\/\s*>$/.test(a)||Mt.has(s);if(!s||l)return{end:o};return{end:o,piece:{kind:"open",sensitive:Ut.has(s)?s:void 0}}}(e,t,n):null}function Jt(e,t,n){let i=t,r=null;for(;i<e.length;){const t=e[i];if(r){if(t===r)r=null;else{const t=Ht(e,i,n);if(null!==t){i=t;continue}}i+=1;continue}const s=Ht(e,i,n);if(null===s)if('"'!==t&&"'"!==t){if(">"===t)return i+1;i+=1}else r=t,i+=1;else i=s}return e.length}function Ht(e,t,n){const{commentOpen:i,commentClose:r,outputOpen:s,outputClose:o,directiveOpen:a,directiveClose:l}=n;return e.startsWith(i,t)?Vt(e,t+i.length,r):e.startsWith(s,t)?Vt(e,t+s.length,o):e.startsWith(a,t)?Vt(e,t+a.length,l):null}function Vt(e,t,n){const i=e.indexOf(n,t);return-1===i?e.length:i+n.length}function Qt(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=Yt(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function Yt(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if("{"!==s||"{"!==e[r+1])if('"'!==s&&"'"!==s&&"`"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1;else r=Zt(e,r)}return{opens:t,closes:n}}function Zt(e,t){if(e.startsWith("{{#",t)){const n=e.indexOf("#}}",t+3);return-1===n?e.length:n+3}const n=e.indexOf("}}",t+2);return-1===n?e.length:n+2}const en=new Set(["script","style"]);function tn(e,t){const n=t.tabWidth??2,i=" ".repeat(Math.max(0,n)),r=e.includes("\r\n")?"\r\n":"\n",s=e.split(/\r?\n/);let o=0,a=null,l=null,c=null;const u=[],p={inComment:!1};for(const e of s){const s=e.match(/^[ \t]*/)?.[0].length??0,f=e.slice(s);if(l){const e=Bt(f,t),n=/^(?:\/\s*)?>\s*$/.test(f),r=l.baseDepth+(n?0:1);u.push(0===f.length?"":i.repeat(r)+f),e&&(l.openedElement&&/\/\s*>\s*$/.test(f)&&(o=Math.max(0,o-1)),l=null);continue}const{pieces:d,prefixClosers:b}=qt(f,t,p),m=a,y=null!==m&&d.some(e=>"close"===e.kind&&e.sensitive===m),g="stylesheet"===m||null!==m&&en.has(m);if(g&&!y){(c??(c=[])).push(e);continue}if(c&&y&&g){const e="stylesheet"===m?Math.max(0,o-1):o,s=c.join(r),a="stylesheet"===m?tn(s,t):"style"===m?Dt(s,n):Qt(s,n);for(const t of a.split(/\r?\n/))u.push(0===t.length?"":i.repeat(e)+t);c=null}else if(a&&!y){u.push(e),h(d);continue}const w=Math.max(0,o-b),v=/^\/\s*>\s*$/.test(f);u.push(0===f.length?"":i.repeat(w)+f),h(d),!p.inComment&&zt(f,t)&&(l={baseDepth:w,openedElement:d.some(e=>"open"===e.kind)}),v&&(o=Math.max(0,o-1))}return u.join(r);function h(e){for(const t of e)"open"===t.kind?(o+=1,t.sensitive&&!a&&({sensitive:a}=t)):"close"===t.kind?(o=Math.max(0,o-1),t.sensitive&&a===t.sensitive&&(a=null)):t.kind}}const nn=e=>JSON.stringify(e,(e,t)=>"loc"===e||"raw"===e?void 0:t??null);class rn{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options={continueOnError:!1,undefinedFallback:"",ignoreMissingFilters:!1,onError:()=>{},...e}}safeEvaluate(e,t,n={}){try{const n=this.evaluateExpression(e,t);return void 0===n&&void 0!==this.options.undefinedFallback?this.options.undefinedFallback:n}catch(i){const r={template:n.template||"",data:t,expression:e},s=this.options.onError(i,r);if(this.options.continueOnError)return s;throw i}}safeApplyFilter(e,t,n,i=[],r={}){try{if(!n){if(this.options.ignoreMissingFilters)return e;throw new Error(`Filter "${t}" is not defined`)}return n(e,...i)}catch(e){const n={template:r.template||"",data:r.data||{},filter:t},i=this.options.onError(e,n);if(this.options.continueOnError)return i;throw e}}wrapRender(e,t={}){return(...n)=>{try{return e(...n)}catch(e){const i={template:t.template||"",data:n[1]||{}},r=this.options.onError(e,i);if(this.options.continueOnError)return r;throw e}}}evaluateExpression(e,t){try{const n=e.split(".");let i=t;for(const e of n){if(null==i)return;i=i[e]}return i}catch{return}}createSafeAccessor(e){return t=>{try{const n=t.split(".");let i=e;for(const e of n){if(null==i)return this.options.undefinedFallback;i=i[e]}return void 0===i?this.options.undefinedFallback:i}catch{return this.options.undefinedFallback}}}}let sn;const on=new WeakMap;function an(e){if(!e)return sn??(sn=new yt);let t=on.get(e);return t||(t=new yt(e),on.set(e,t)),t}e.CompileError=i,e.Compiler=Z,e.ErrorRecovery=rn,e.ExpCompiler=he,e.ExpError=E,e.ExpParser=A,e.ExpTokenizer=N,e.I18n=jt,e.MAX_INCLUDE_DEPTH=100,e.MixinRegistry=Nt,e.Parser=J,e.RenderError=bt,e.Renderer=yt,e.RootNode=z,e.Safe=c,e.SecurityAuditor=f,e.SecuritySandbox=p,e.TemplatePipeline=class{constructor(e){Object.defineProperty(this,"templates",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options=e}addTemplate(e){return this.templates.push(e),this}setData(e){return this.data={...this.data,...e},this}setOptions(e){return this.options={...this.options,...e},this}async execute(){return $t(this.templates,{data:this.data,options:this.options})}},e.TemplateValidator=Lt,e.Tokenizer=K,e.Traversal=G,e.analyzeTemplate=vt,e.applyMixin=_t,e.applyMixins=async function(e,t={},n=It){const i=[];for(const r of e){const e=await _t(r,t,n);i.push(e)}return i},e.applyWhitespaceControl=function(e,t){let n=e;return t.stripComments&&(n=n.replace(/<!--[\s\S]*?-->/g,"")),t.collapseWhitespace&&(n=t.preserveNewlines?n.replace(/[ \t]+/g," "):n.replace(/\s+/g," ")),t.trim&&(n=n.trim()),n},e.baseOptions=te,e.compilerOptions=ie,e.composeLayout=async function(e,t,n={}){const{data:i={},options:r}=n,s=new yt({...r,autoEscape:!1}),o=await s.render(t,i);return s.render(e,{...i,content:o})},e.composeTemplates=$t,e.composeTemplatesWithData=async function(e,t={}){let n="";const{options:i}=t,r=new yt(i);for(const t of e){const e={...t.data,_content:n};n=await r.render(t.template,e)}return n},e.composeWithSlots=async function(e,t,n={}){const{data:i={},options:r}=n,s=new yt({...r,autoEscape:!1}),o={};for(const[e,n]of Object.entries(t))o[e]=await s.render(n,i);return s.render(e,{...i,slots:o})},e.createErrorRecovery=function(e={}){return new rn(e)},e.createFileLoader=function(e,{extensions:t=[".janja",".html"]}={}){return async n=>{const{readFile:i}=await(import("node:fs/promises")),r=await(import("node:path")),s=r.resolve(e),o=r.extname(n)?[n]:[...t.map(e=>`${n}${e}`),n];for(const e of o){const t=r.resolve(s,e);if(!t.startsWith(s+r.sep))break;try{return await i(t,"utf-8")}catch{}}throw new Error(`Template "${n}" not found in ${e}`)}},e.createMixin=function(e,t,n){return{name:e,template:t,data:n}},e.deepEscape=h,e.defaultErrorHandler=function(e,t){console.error("[Janja Error]",e.message),t.expression&&console.error(" Expression:",t.expression),t.filter&&console.error(" Filter:",t.filter)},e.defaultWhitespaceOptions=St,e.defineFilters=function(e){return e},e.definePlugin=function(e){return e},e.expTokenTypes=j,e.extendTemplateWithMixin=async function(e,t,n={},i=It){const r=await _t(t,n,i);return new yt({...n.options,autoEscape:!1}).render(e,{_mixin:r})},e.filters=ee,e.formatTemplate=function(t,n={}){const i={...ne,...n},r=new K(i).tokenize(t),s=[0];for(let e=0;e<t.length;e++)"\n"===t[e]&&s.push(e+1);const o=({line:e,column:t})=>s[e-1]+t-1,a=new A,l=new Rt,c=(e,t)=>{try{const n=a.parse(e,t),i=l.format(n);return nn(a.parse(i,t))!==nn(n)?null:i.replace(/[{}]/g,"\\$&")}catch{return null}},u=r.map(n=>{const r=t.slice(o(n.loc.start),o(n.loc.end));return n.type===e.TokenType.TEXT||n.type===e.TokenType.COMMENT&&n.val.includes("\n")?r:(t=>{const n=t.strip.before?"-":"",r=t.strip.after?"-":"";if(t.type===e.TokenType.COMMENT)return`${i.commentOpen}${n} ${t.val.trim()} ${r}${i.commentClose}`;if(t.type===e.TokenType.OUTPUT){const e=c(t.val,t.loc);return e&&`${i.outputOpen}${n} ${e} ${r}${i.outputClose}`}const{name:s,expression:o}=t;if(!s)return null;const a=o?c(o.val,o.loc):"";return null!==a&&`${i.directiveOpen}${n} ${s}${a&&` ${a}`} ${r}${i.directiveClose}`})(n)||r}).join("");return!1===n.html?u:tn(u,{tabWidth:n.tabWidth,commentOpen:i.commentOpen,commentClose:i.commentClose,directiveOpen:i.directiveOpen,directiveClose:i.directiveClose,outputOpen:i.outputOpen,outputClose:i.outputClose})},e.generateDeclarations=xt,e.generateSourceMap=Et,e.getWhitespaceCompilerOptions=function(e){const t=kt(e);return{trimWhitespace:t.trim,stripComments:t.stripComments}},e.getWhitespaceRendererOptions=function(e){const t=kt(e),n={};return t.trim!==St.trim&&(n.trimWhitespace=t.trim),t.stripComments!==St.stripComments&&(n.stripComments=t.stripComments),n},e.globalMixinRegistry=It,e.i18n=Tt,e.isForbiddenIdentifier=$,e.mergeOptions=se,e.mergeWhitespaceOptions=kt,e.optionsFingerprint=m,e.parserOptions=ne,e.precompile=Pt,e.precompileTemplate=async function(e,t={}){return(await Pt(e,t)).code},e.render=async function(e,t,n){return an(n).render(e,t)},e.renderCompiled=async function(e,t={},n){return an(n).renderCompiled(e,t)},e.renderFile=async function(e,t,n){return an(n).renderFile(e,t)},e.renderOptions=re,e.renderStream=function(e,t={},n){return an(n).renderStream(e,t)},e.resolveSecurityLimits=u,e.templateCacheKey=b,e.validateTemplate=async function(e,t){return new Lt(t).validate(e)}}(this.janja=this.janja||{});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "janja",
3
- "version": "4.6.0",
3
+ "version": "4.8.0",
4
4
  "description": "A simple, fast, lightweight, and extensible template engine for Node.js and browsers.",
5
5
  "type": "module",
6
6
  "license": "MIT",