janja 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1855,6 +1855,20 @@ ${suggestionText}`;
1855
1855
  writable: true,
1856
1856
  value: void 0
1857
1857
  });
1858
+ /** Stylesheet bodies keyed by include path (or `\0root` for the root template). */
1859
+ Object.defineProperty(this, "stylesheets", {
1860
+ enumerable: true,
1861
+ configurable: true,
1862
+ writable: true,
1863
+ value: void 0
1864
+ });
1865
+ /** Key used when collecting stylesheets from the template currently compiling. */
1866
+ Object.defineProperty(this, "stylesheetKey", {
1867
+ enumerable: true,
1868
+ configurable: true,
1869
+ writable: true,
1870
+ value: void 0
1871
+ });
1858
1872
  Object.defineProperty(this, "sources", {
1859
1873
  enumerable: true,
1860
1874
  configurable: true,
@@ -1885,11 +1899,13 @@ ${suggestionText}`;
1885
1899
  });
1886
1900
  this.cache = cache;
1887
1901
  }
1888
- async compile(template, root = true, partials = new Map(), blocks = new Map(), sources = new Map()) {
1902
+ async compile(template, root = true, partials = new Map(), blocks = new Map(), sources = new Map(), stylesheets = new Map(), stylesheetKey = '\0root') {
1889
1903
  this.template = template;
1890
1904
  this.isRoot = root;
1891
1905
  this.partials = partials;
1892
1906
  this.blocks = blocks;
1907
+ this.stylesheets = stylesheets;
1908
+ this.stylesheetKey = stylesheetKey;
1893
1909
  this.sources = sources;
1894
1910
  // Generate cache key from template and options
1895
1911
  const cacheKey = this.generateCacheKey(template);
@@ -1912,6 +1928,7 @@ ${suggestionText}`;
1912
1928
  this.start(this.isRoot);
1913
1929
  if (this.isRoot) {
1914
1930
  this.pushResourceLimitCounters();
1931
+ this.pushRaw(null, 'let ss_u=0;');
1915
1932
  }
1916
1933
  await this.parseTemplates();
1917
1934
  if (this.isRoot) {
@@ -1938,6 +1955,16 @@ ${suggestionText}`;
1938
1955
  }
1939
1956
  this.pushRaw(null, '};');
1940
1957
  }
1958
+ // Always emit ss_ so `{{ stylesheets }}` can run even when empty.
1959
+ this.pushRaw(null, 'const ss_=[');
1960
+ for (const [, nodes] of this.stylesheets) {
1961
+ this.pushRaw(null, 'async()=>{', 'let s="";');
1962
+ for (const node of nodes) {
1963
+ await this.compileNodes(node.body);
1964
+ }
1965
+ this.pushRaw(null, 'return s;', '},');
1966
+ }
1967
+ this.pushRaw(null, '];');
1941
1968
  }
1942
1969
  this.flushable = this.isRoot && this.stream;
1943
1970
  await this.compileNode(this.rootNode);
@@ -1998,7 +2025,7 @@ ${suggestionText}`;
1998
2025
  return true;
1999
2026
  }
2000
2027
  async parseTemplates() {
2001
- const { partials, blocks } = this.collectPartialsAndBlocks();
2028
+ const { partials, blocks, stylesheets } = this.collectPartialsAndBlocks();
2002
2029
  for (const [path, node] of partials) {
2003
2030
  if (!this.partials.has(path)) {
2004
2031
  let template;
@@ -2025,10 +2052,15 @@ ${suggestionText}`;
2025
2052
  }
2026
2053
  this.blocks.get(value).push(block);
2027
2054
  }
2055
+ // One entry per source file (Shopify: at most one stylesheet tag per file).
2056
+ if (stylesheets.length && !this.stylesheets.has(this.stylesheetKey)) {
2057
+ this.stylesheets.set(this.stylesheetKey, stylesheets);
2058
+ }
2028
2059
  }
2029
2060
  collectPartialsAndBlocks() {
2030
2061
  const partials = new Map();
2031
2062
  const blocks = [];
2063
+ const stylesheets = [];
2032
2064
  const traverse = (node) => {
2033
2065
  if (node.type === 'INCLUDE') {
2034
2066
  if (!partials.has(node.val.value)) {
@@ -2038,12 +2070,16 @@ ${suggestionText}`;
2038
2070
  if (node.type === 'BLOCK') {
2039
2071
  blocks.push(node);
2040
2072
  }
2073
+ if (node.type === 'STYLESHEET') {
2074
+ stylesheets.push(node);
2075
+ }
2041
2076
  node.traverse(traverse);
2042
2077
  };
2043
2078
  traverse(this.rootNode);
2044
2079
  return {
2045
2080
  partials,
2046
2081
  blocks,
2082
+ stylesheets,
2047
2083
  };
2048
2084
  }
2049
2085
  async compileNode(node) {
@@ -2093,7 +2129,7 @@ ${suggestionText}`;
2093
2129
  }
2094
2130
  async compilePartial(path, node, template) {
2095
2131
  try {
2096
- const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources);
2132
+ const { code } = await new Compiler(this.options).compile(template, false, this.partials, this.blocks, this.sources, this.stylesheets, path);
2097
2133
  this.partials.set(path, code);
2098
2134
  }
2099
2135
  catch {
@@ -2499,7 +2535,7 @@ ${suggestionText}`;
2499
2535
  // Each super() call pops the next level from the stack
2500
2536
  compiler.pushRaw(loc, `s+=await b[${JSON.stringify(compiler.state.block)}]?.s?.pop()?.()??"";`);
2501
2537
  }
2502
- const compilers$d = {
2538
+ const compilers$e = {
2503
2539
  BLOCK: compileBlock,
2504
2540
  SUPER: compileSuper,
2505
2541
  };
@@ -2592,15 +2628,15 @@ ${suggestionText}`;
2592
2628
  yield 'NEXT';
2593
2629
  yield new SuperNode(token.val, token.loc, token.strip);
2594
2630
  }
2595
- const parsers$d = {
2631
+ const parsers$e = {
2596
2632
  block: parseBlock,
2597
2633
  super: parseSuper,
2598
2634
  endblock: 'unexpected',
2599
2635
  };
2600
2636
 
2601
- const plugin$d = {
2602
- compilers: compilers$d,
2603
- parsers: parsers$d,
2637
+ const plugin$e = {
2638
+ compilers: compilers$e,
2639
+ parsers: parsers$e,
2604
2640
  };
2605
2641
 
2606
2642
  const expTokenOperators$1 = {
@@ -2776,7 +2812,7 @@ ${suggestionText}`;
2776
2812
  await compiler.compileNodes(body);
2777
2813
  compiler.pushRaw(null, 'return s;', '})??"";');
2778
2814
  }
2779
- const compilers$c = {
2815
+ const compilers$d = {
2780
2816
  CALL: compileCall,
2781
2817
  };
2782
2818
 
@@ -2831,14 +2867,14 @@ ${suggestionText}`;
2831
2867
  }
2832
2868
  yield new CallNode(parser.parseExp(token.expression), body, token.loc, token.strip);
2833
2869
  }
2834
- const parsers$c = {
2870
+ const parsers$d = {
2835
2871
  call: parseCall,
2836
2872
  endcall: 'unexpected',
2837
2873
  };
2838
2874
 
2839
- const plugin$c = {
2840
- compilers: compilers$c,
2841
- parsers: parsers$c,
2875
+ const plugin$d = {
2876
+ compilers: compilers$d,
2877
+ parsers: parsers$d,
2842
2878
  };
2843
2879
 
2844
2880
  async function compileCapture({ val, body, loc }, compiler) {
@@ -2848,7 +2884,7 @@ ${suggestionText}`;
2848
2884
  await compiler.compileNodes(body);
2849
2885
  compiler.pushRaw(null, 'return s;})(""));');
2850
2886
  }
2851
- const compilers$b = {
2887
+ const compilers$c = {
2852
2888
  CAPTURE: compileCapture,
2853
2889
  };
2854
2890
 
@@ -2903,14 +2939,14 @@ ${suggestionText}`;
2903
2939
  }
2904
2940
  yield new CaptureNode(parser.parseExp(token.expression), body, token.loc, token.strip);
2905
2941
  }
2906
- const parsers$b = {
2942
+ const parsers$c = {
2907
2943
  capture: parseCapture,
2908
2944
  endcapture: 'unexpected',
2909
2945
  };
2910
2946
 
2911
- const plugin$b = {
2912
- compilers: compilers$b,
2913
- parsers: parsers$b,
2947
+ const plugin$c = {
2948
+ compilers: compilers$c,
2949
+ parsers: parsers$c,
2914
2950
  };
2915
2951
 
2916
2952
  async function compileComment({ val, loc }, compiler) {
@@ -2918,7 +2954,7 @@ ${suggestionText}`;
2918
2954
  compiler.pushStr(loc, `<!--${val}-->`);
2919
2955
  }
2920
2956
  }
2921
- const compilers$a = {
2957
+ const compilers$b = {
2922
2958
  COMMENT: compileComment,
2923
2959
  };
2924
2960
 
@@ -2956,13 +2992,13 @@ ${suggestionText}`;
2956
2992
  yield 'NEXT';
2957
2993
  yield new CommentNode(val, loc, strip);
2958
2994
  }
2959
- const parsers$a = {
2995
+ const parsers$b = {
2960
2996
  comment: parseComment,
2961
2997
  };
2962
2998
 
2963
- const plugin$a = {
2964
- compilers: compilers$a,
2965
- parsers: parsers$a,
2999
+ const plugin$b = {
3000
+ compilers: compilers$b,
3001
+ parsers: parsers$b,
2966
3002
  };
2967
3003
 
2968
3004
  const loop = 'loop:{first:i_===0,index:i_++,last:i_===n_}';
@@ -3059,7 +3095,7 @@ ${suggestionText}`;
3059
3095
  function compileContinue({ loc }, compiler) {
3060
3096
  compiler.pushRaw(loc, 'continue;');
3061
3097
  }
3062
- const compilers$9 = {
3098
+ const compilers$a = {
3063
3099
  FOR: compileFor,
3064
3100
  BREAK: compileBreak,
3065
3101
  CONTINUE: compileContinue,
@@ -3275,16 +3311,16 @@ ${suggestionText}`;
3275
3311
  yield 'NEXT';
3276
3312
  yield new ContinueNode(token.val, token.loc, token.strip);
3277
3313
  }
3278
- const parsers$9 = {
3314
+ const parsers$a = {
3279
3315
  for: parseFor,
3280
3316
  break: parseBreak,
3281
3317
  continue: parseContinue,
3282
3318
  endfor: 'unexpected',
3283
3319
  };
3284
3320
 
3285
- const plugin$9 = {
3286
- compilers: compilers$9,
3287
- parsers: parsers$9,
3321
+ const plugin$a = {
3322
+ compilers: compilers$a,
3323
+ parsers: parsers$a,
3288
3324
  };
3289
3325
 
3290
3326
  async function compileIf({ test, body, alternatives }, compiler) {
@@ -3302,7 +3338,7 @@ ${suggestionText}`;
3302
3338
  compiler.pushRaw(null, '}');
3303
3339
  }
3304
3340
  }
3305
- const compilers$8 = {
3341
+ const compilers$9 = {
3306
3342
  IF: compileIf,
3307
3343
  };
3308
3344
 
@@ -3489,7 +3525,7 @@ ${suggestionText}`;
3489
3525
  yield 'NEXT';
3490
3526
  yield new ElseNode(parser.parseUntil(['endif']), token.loc, token.strip);
3491
3527
  }
3492
- const parsers$8 = {
3528
+ const parsers$9 = {
3493
3529
  if: parseIf,
3494
3530
  elseif: 'unexpected',
3495
3531
  elsif: 'unexpected',
@@ -3497,15 +3533,15 @@ ${suggestionText}`;
3497
3533
  endif: 'unexpected',
3498
3534
  };
3499
3535
 
3500
- const plugin$8 = {
3501
- compilers: compilers$8,
3502
- parsers: parsers$8,
3536
+ const plugin$9 = {
3537
+ compilers: compilers$9,
3538
+ parsers: parsers$9,
3503
3539
  };
3504
3540
 
3505
3541
  async function compileInclude({ val: { value }, loc }, compiler) {
3506
3542
  compiler.pushRaw(loc, `s+=await p[${JSON.stringify(value)}]?.()??"";`);
3507
3543
  }
3508
- const compilers$7 = {
3544
+ const compilers$8 = {
3509
3545
  INCLUDE: compileInclude,
3510
3546
  };
3511
3547
 
@@ -3547,13 +3583,13 @@ ${suggestionText}`;
3547
3583
  yield 'NEXT';
3548
3584
  yield new IncludeNode(parser.parseExp(token.expression), token.loc, token.strip);
3549
3585
  }
3550
- const parsers$7 = {
3586
+ const parsers$8 = {
3551
3587
  include: parseInclude,
3552
3588
  };
3553
3589
 
3554
- const plugin$7 = {
3555
- compilers: compilers$7,
3556
- parsers: parsers$7,
3590
+ const plugin$8 = {
3591
+ compilers: compilers$8,
3592
+ parsers: parsers$8,
3557
3593
  };
3558
3594
 
3559
3595
  async function compileMacro({ val: { value, args }, loc, body }, compiler) {
@@ -3579,7 +3615,7 @@ ${suggestionText}`;
3579
3615
  function compileCaller({ loc }, compiler) {
3580
3616
  compiler.pushRaw(loc, 's+=await _c?.()??"";');
3581
3617
  }
3582
- const compilers$6 = {
3618
+ const compilers$7 = {
3583
3619
  MACRO: compileMacro,
3584
3620
  CALLER: compileCaller,
3585
3621
  };
@@ -3698,21 +3734,21 @@ ${suggestionText}`;
3698
3734
  yield 'NEXT';
3699
3735
  yield new CallerNode(token.val, token.loc, token.strip);
3700
3736
  }
3701
- const parsers$6 = {
3737
+ const parsers$7 = {
3702
3738
  macro: parseMacro,
3703
3739
  caller: parseCaller,
3704
3740
  endmacro: 'unexpected',
3705
3741
  };
3706
3742
 
3707
- const plugin$6 = {
3708
- compilers: compilers$6,
3709
- parsers: parsers$6,
3743
+ const plugin$7 = {
3744
+ compilers: compilers$7,
3745
+ parsers: parsers$7,
3710
3746
  };
3711
3747
 
3712
3748
  async function compileOutput({ val }, compiler) {
3713
3749
  compiler.pushVar(val.loc, new ExpCompiler().compile(val, compiler.context));
3714
3750
  }
3715
- const compilers$5 = {
3751
+ const compilers$6 = {
3716
3752
  OUTPUT: compileOutput,
3717
3753
  };
3718
3754
 
@@ -3752,19 +3788,19 @@ ${suggestionText}`;
3752
3788
  const start = updatePosition(`${parser.options.outputOpen}${token.strip.before ? '-' : ''}`, { ...token.loc.start });
3753
3789
  yield new OutputNode(parser.parseExp({ val: token.val, loc: { start, end: token.loc.end } }), token.loc, token.strip);
3754
3790
  }
3755
- const parsers$5 = {
3791
+ const parsers$6 = {
3756
3792
  output: parseOutput,
3757
3793
  };
3758
3794
 
3759
- const plugin$5 = {
3760
- compilers: compilers$5,
3761
- parsers: parsers$5,
3795
+ const plugin$6 = {
3796
+ compilers: compilers$6,
3797
+ parsers: parsers$6,
3762
3798
  };
3763
3799
 
3764
3800
  async function compileSet({ val, loc }, compiler) {
3765
3801
  compiler.pushRaw(loc, new ExpCompiler().compile(val, compiler.context));
3766
3802
  }
3767
- const compilers$4 = {
3803
+ const compilers$5 = {
3768
3804
  SET: compileSet,
3769
3805
  };
3770
3806
 
@@ -3806,10 +3842,117 @@ ${suggestionText}`;
3806
3842
  yield 'NEXT';
3807
3843
  yield new SetNode(parser.parseExp(token.expression), token.loc, token.strip);
3808
3844
  }
3809
- const parsers$4 = {
3845
+ const parsers$5 = {
3810
3846
  set: parseSet,
3811
3847
  };
3812
3848
 
3849
+ const plugin$5 = {
3850
+ compilers: compilers$5,
3851
+ parsers: parsers$5,
3852
+ };
3853
+
3854
+ /**
3855
+ * Stylesheet bodies are collected at compile time (like blocks) and emitted
3856
+ * only by `{{ stylesheets }}`. The site of `{{ stylesheet }}` itself writes
3857
+ * nothing.
3858
+ */
3859
+ async function compileStylesheet() {
3860
+ // no-op: collected into Compiler.stylesheets
3861
+ }
3862
+ async function compileStylesheets({ loc }, compiler) {
3863
+ compiler.pushRaw(loc,
3864
+ // First `stylesheets` wins; later ones are ignored (same idea as blocks).
3865
+ 'if(!ss_u++){', 's+="<style>";', 'for(const f_ of ss_)s+=await f_();', 's+="</style>";', '}');
3866
+ }
3867
+ const compilers$4 = {
3868
+ STYLESHEET: compileStylesheet,
3869
+ STYLESHEETS: compileStylesheets,
3870
+ };
3871
+
3872
+ /** CSS co-located with a section/snippet (Shopify `{% stylesheet %}` analogue). */
3873
+ class StylesheetNode extends Traversal {
3874
+ constructor(body, loc, strip) {
3875
+ super();
3876
+ Object.defineProperty(this, "body", {
3877
+ enumerable: true,
3878
+ configurable: true,
3879
+ writable: true,
3880
+ value: body
3881
+ });
3882
+ Object.defineProperty(this, "loc", {
3883
+ enumerable: true,
3884
+ configurable: true,
3885
+ writable: true,
3886
+ value: loc
3887
+ });
3888
+ Object.defineProperty(this, "strip", {
3889
+ enumerable: true,
3890
+ configurable: true,
3891
+ writable: true,
3892
+ value: strip
3893
+ });
3894
+ Object.defineProperty(this, "type", {
3895
+ enumerable: true,
3896
+ configurable: true,
3897
+ writable: true,
3898
+ value: 'STYLESHEET'
3899
+ });
3900
+ }
3901
+ }
3902
+ /** Emits every collected stylesheet into the document (typically in `<head>`). */
3903
+ class StylesheetsNode extends Traversal {
3904
+ constructor(loc, strip) {
3905
+ super();
3906
+ Object.defineProperty(this, "loc", {
3907
+ enumerable: true,
3908
+ configurable: true,
3909
+ writable: true,
3910
+ value: loc
3911
+ });
3912
+ Object.defineProperty(this, "strip", {
3913
+ enumerable: true,
3914
+ configurable: true,
3915
+ writable: true,
3916
+ value: strip
3917
+ });
3918
+ Object.defineProperty(this, "type", {
3919
+ enumerable: true,
3920
+ configurable: true,
3921
+ writable: true,
3922
+ value: 'STYLESHEETS'
3923
+ });
3924
+ }
3925
+ }
3926
+
3927
+ function* parseStylesheet(token, parser) {
3928
+ if (token.expression) {
3929
+ parser.emitExpErr(token, false);
3930
+ return;
3931
+ }
3932
+ yield 'NEXT';
3933
+ const body = parser.parseUntil(['endstylesheet']);
3934
+ if (parser.match(['endstylesheet'])) {
3935
+ yield 'NEXT';
3936
+ }
3937
+ else {
3938
+ parser.options.debug?.(new CompileError(`Unclosed "${token.name}"`, parser.template, token.loc));
3939
+ }
3940
+ yield new StylesheetNode(body, token.loc, token.strip);
3941
+ }
3942
+ function* parseStylesheets(token, parser) {
3943
+ if (token.expression) {
3944
+ parser.emitExpErr(token, false);
3945
+ return;
3946
+ }
3947
+ yield 'NEXT';
3948
+ yield new StylesheetsNode(token.loc, token.strip);
3949
+ }
3950
+ const parsers$4 = {
3951
+ stylesheet: parseStylesheet,
3952
+ endstylesheet: 'unexpected',
3953
+ stylesheets: parseStylesheets,
3954
+ };
3955
+
3813
3956
  const plugin$4 = {
3814
3957
  compilers: compilers$4,
3815
3958
  parsers: parsers$4,
@@ -4066,17 +4209,18 @@ ${suggestionText}`;
4066
4209
  };
4067
4210
 
4068
4211
  const plugins = [
4212
+ plugin$e,
4069
4213
  plugin$d,
4214
+ plugin$b,
4070
4215
  plugin$c,
4071
4216
  plugin$a,
4072
- plugin$b,
4073
4217
  plugin$9,
4074
4218
  plugin$8,
4075
4219
  plugin$7,
4076
- plugin$6,
4220
+ plugin$5,
4077
4221
  plugin$4,
4078
4222
  plugin$3,
4079
- plugin$5,
4223
+ plugin$6,
4080
4224
  plugin$2,
4081
4225
  plugin$1,
4082
4226
  plugin,
@@ -4469,6 +4613,9 @@ ${suggestionText}`;
4469
4613
  this.blocks.add(node.val.value);
4470
4614
  await this.nodes(node.body, scope);
4471
4615
  break;
4616
+ case 'STYLESHEET':
4617
+ await this.nodes(node.body, scope);
4618
+ break;
4472
4619
  case 'INCLUDE':
4473
4620
  await this.include(node.val.value, scope);
4474
4621
  break;
@@ -5233,18 +5380,303 @@ export default script;
5233
5380
  }
5234
5381
  }
5235
5382
 
5383
+ /** HTML void elements — never take children, so they do not change indent. */
5384
+ const VOID = new Set([
5385
+ 'area',
5386
+ 'base',
5387
+ 'br',
5388
+ 'col',
5389
+ 'embed',
5390
+ 'hr',
5391
+ 'img',
5392
+ 'input',
5393
+ 'link',
5394
+ 'meta',
5395
+ 'param',
5396
+ 'source',
5397
+ 'track',
5398
+ 'wbr',
5399
+ ]);
5400
+ /** Preserve inner whitespace exactly (like Prettier raw nodes). */
5401
+ const SENSITIVE = new Set(['pre', 'textarea', 'script', 'style']);
5402
+ const DIR_OPEN = new Set([
5403
+ 'if',
5404
+ 'for',
5405
+ 'macro',
5406
+ 'block',
5407
+ 'call',
5408
+ 'capture',
5409
+ 'with',
5410
+ 'stylesheet',
5411
+ ]);
5412
+ const DIR_MID = new Set(['else', 'elif', 'elseif', 'elsif']);
5413
+ const DIR_CLOSE = new Set([
5414
+ 'endif',
5415
+ 'endfor',
5416
+ 'endmacro',
5417
+ 'endblock',
5418
+ 'endcall',
5419
+ 'endcapture',
5420
+ 'endwith',
5421
+ 'endstylesheet',
5422
+ ]);
5423
+ /**
5424
+ * Reindent a template that already had its Janja tags normalised.
5425
+ * Only leading whitespace on each line changes; line breaks and
5426
+ * intra-line spacing stay put. Content inside pre/textarea/script/style
5427
+ * is left alone; the closing tag of those elements is still reindented.
5428
+ */
5429
+ function indentHtml(source, options) {
5430
+ const tabWidth = options.tabWidth ?? 2;
5431
+ const pad = ' '.repeat(Math.max(0, tabWidth));
5432
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
5433
+ const lines = source.split(/\r?\n/);
5434
+ let depth = 0;
5435
+ let sensitive = null;
5436
+ const out = [];
5437
+ for (const line of lines) {
5438
+ const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5439
+ const content = line.slice(leading);
5440
+ const { pieces, prefixClosers } = scanLine(content, options);
5441
+ const activeSensitive = sensitive;
5442
+ const closesSensitive = activeSensitive !== null &&
5443
+ pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
5444
+ if (sensitive && !closesSensitive) {
5445
+ out.push(line);
5446
+ applyDepth(pieces);
5447
+ continue;
5448
+ }
5449
+ const lineDepth = Math.max(0, depth - prefixClosers);
5450
+ out.push(content.length === 0 ? '' : pad.repeat(lineDepth) + content);
5451
+ applyDepth(pieces);
5452
+ }
5453
+ // split() keeps a final empty string when the source already ends in a
5454
+ // newline, so join() alone preserves that trailing newline — do not add
5455
+ // another one or each format grows an extra blank line.
5456
+ return out.join(eol);
5457
+ function applyDepth(pieces) {
5458
+ for (const piece of pieces) {
5459
+ if (piece.kind === 'open') {
5460
+ depth += 1;
5461
+ if (piece.sensitive && !sensitive) {
5462
+ ({ sensitive } = piece);
5463
+ }
5464
+ }
5465
+ else if (piece.kind === 'close') {
5466
+ depth = Math.max(0, depth - 1);
5467
+ if (piece.sensitive && sensitive === piece.sensitive) {
5468
+ sensitive = null;
5469
+ }
5470
+ }
5471
+ else if (piece.kind === 'mid') ;
5472
+ }
5473
+ }
5474
+ }
5475
+ function scanLine(line, options) {
5476
+ const pieces = [];
5477
+ let prefixClosers = 0;
5478
+ let atPrefix = true;
5479
+ let i = 0;
5480
+ while (i < line.length) {
5481
+ if (/\s/.test(line[i])) {
5482
+ i += 1;
5483
+ continue;
5484
+ }
5485
+ const next = readAt(line, i, options);
5486
+ if (!next) {
5487
+ // Plain text ends the leading-closer prefix
5488
+ atPrefix = false;
5489
+ i += 1;
5490
+ continue;
5491
+ }
5492
+ if (next.piece) {
5493
+ pieces.push(next.piece);
5494
+ if (atPrefix &&
5495
+ (next.piece.kind === 'close' || next.piece.kind === 'mid')) {
5496
+ prefixClosers += 1;
5497
+ }
5498
+ else {
5499
+ atPrefix = false;
5500
+ }
5501
+ }
5502
+ else {
5503
+ // Comment / output / unknown directive sitting in the prefix
5504
+ atPrefix = false;
5505
+ }
5506
+ i = next.end;
5507
+ }
5508
+ return { pieces, prefixClosers };
5509
+ }
5510
+ function readAt(line, i, options) {
5511
+ const { commentOpen, directiveOpen, outputOpen } = options;
5512
+ if (line.startsWith(commentOpen, i)) {
5513
+ return {
5514
+ end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5515
+ };
5516
+ }
5517
+ if (line.startsWith(outputOpen, i)) {
5518
+ return {
5519
+ end: endOfDelimited(line, i + outputOpen.length, options.outputClose),
5520
+ };
5521
+ }
5522
+ if (line.startsWith(directiveOpen, i)) {
5523
+ return readDirective(line, i, options);
5524
+ }
5525
+ if (line.startsWith('<!--', i)) {
5526
+ const close = line.indexOf('-->', i + 4);
5527
+ return { end: close === -1 ? line.length : close + 3 };
5528
+ }
5529
+ if (line[i] === '<') {
5530
+ return readHtmlTag(line, i, options);
5531
+ }
5532
+ return null;
5533
+ }
5534
+ function readDirective(line, start, options) {
5535
+ const { directiveOpen, directiveClose } = options;
5536
+ const end = endOfDelimited(line, start + directiveOpen.length, directiveClose);
5537
+ const inner = line.slice(start + directiveOpen.length, end - directiveClose.length);
5538
+ const name = inner
5539
+ .replace(/^\s*-?\s*/, '')
5540
+ .match(/^([A-Za-z_]\w*)/)?.[1]
5541
+ ?.toLowerCase();
5542
+ if (!name) {
5543
+ return { end };
5544
+ }
5545
+ if (DIR_CLOSE.has(name)) {
5546
+ return { end, piece: { kind: 'close' } };
5547
+ }
5548
+ if (DIR_MID.has(name)) {
5549
+ return { end, piece: { kind: 'mid' } };
5550
+ }
5551
+ if (DIR_OPEN.has(name)) {
5552
+ return { end, piece: { kind: 'open' } };
5553
+ }
5554
+ return { end };
5555
+ }
5556
+ function readHtmlTag(line, start, options) {
5557
+ if (line.startsWith('</', start)) {
5558
+ let i = start + 2;
5559
+ while (i < line.length && /\s/.test(line[i])) {
5560
+ i += 1;
5561
+ }
5562
+ const nameStart = i;
5563
+ while (i < line.length && /[A-Za-z0-9:-]/.test(line[i])) {
5564
+ i += 1;
5565
+ }
5566
+ const name = line.slice(nameStart, i).toLowerCase();
5567
+ const end = endOfHtmlTag(line, i, options);
5568
+ if (!name || VOID.has(name)) {
5569
+ return { end };
5570
+ }
5571
+ return {
5572
+ end,
5573
+ piece: {
5574
+ kind: 'close',
5575
+ sensitive: SENSITIVE.has(name) ? name : undefined,
5576
+ },
5577
+ };
5578
+ }
5579
+ if (line.startsWith('<!', start) || line.startsWith('<?', start)) {
5580
+ return { end: endOfHtmlTag(line, start + 2, options) };
5581
+ }
5582
+ let i = start + 1;
5583
+ while (i < line.length && /\s/.test(line[i])) {
5584
+ i += 1;
5585
+ }
5586
+ const nameStart = i;
5587
+ while (i < line.length && /[A-Za-z0-9:-]/.test(line[i])) {
5588
+ i += 1;
5589
+ }
5590
+ const name = line.slice(nameStart, i).toLowerCase();
5591
+ const end = endOfHtmlTag(line, i, options);
5592
+ const raw = line.slice(start, end);
5593
+ const selfClosing = /\/\s*>$/.test(raw) || VOID.has(name);
5594
+ if (!name || selfClosing) {
5595
+ return { end };
5596
+ }
5597
+ return {
5598
+ end,
5599
+ piece: {
5600
+ kind: 'open',
5601
+ sensitive: SENSITIVE.has(name) ? name : undefined,
5602
+ },
5603
+ };
5604
+ }
5605
+ /**
5606
+ * Find the `>` that ends an HTML tag, skipping quotes and Janja tags
5607
+ * (so `class="{{ if a > b }}x{{ endif }}"` does not end early).
5608
+ */
5609
+ function endOfHtmlTag(line, from, options) {
5610
+ let i = from;
5611
+ let quote = null;
5612
+ while (i < line.length) {
5613
+ const c = line[i];
5614
+ if (quote) {
5615
+ if (c === quote) {
5616
+ quote = null;
5617
+ }
5618
+ else {
5619
+ const skipped = trySkipJanja(line, i, options);
5620
+ if (skipped !== null) {
5621
+ i = skipped;
5622
+ continue;
5623
+ }
5624
+ }
5625
+ i += 1;
5626
+ continue;
5627
+ }
5628
+ const skipped = trySkipJanja(line, i, options);
5629
+ if (skipped !== null) {
5630
+ i = skipped;
5631
+ continue;
5632
+ }
5633
+ if (c === '"' || c === "'") {
5634
+ quote = c;
5635
+ i += 1;
5636
+ continue;
5637
+ }
5638
+ if (c === '>') {
5639
+ return i + 1;
5640
+ }
5641
+ i += 1;
5642
+ }
5643
+ return line.length;
5644
+ }
5645
+ function trySkipJanja(line, i, options) {
5646
+ const { commentOpen, commentClose, outputOpen, outputClose, directiveOpen, directiveClose, } = options;
5647
+ if (line.startsWith(commentOpen, i)) {
5648
+ return endOfDelimited(line, i + commentOpen.length, commentClose);
5649
+ }
5650
+ if (line.startsWith(outputOpen, i)) {
5651
+ return endOfDelimited(line, i + outputOpen.length, outputClose);
5652
+ }
5653
+ if (line.startsWith(directiveOpen, i)) {
5654
+ return endOfDelimited(line, i + directiveOpen.length, directiveClose);
5655
+ }
5656
+ return null;
5657
+ }
5658
+ function endOfDelimited(line, from, close) {
5659
+ const idx = line.indexOf(close, from);
5660
+ return idx === -1 ? line.length : idx + close.length;
5661
+ }
5662
+
5236
5663
  // An expression without the positions and spellings that formatting changes
5237
5664
  const shape = (exp) => JSON.stringify(exp, (key, value) => key === 'loc' || key === 'raw' ? undefined : (value ?? null));
5238
5665
  /**
5239
- * Normalise the tags of a template:
5666
+ * Format a template:
5667
+ *
5668
+ * 1. Normalise spacing inside tags:
5240
5669
  *
5241
- * {{=name|upper}} -> {{= name | upper }}
5242
- * {{if a eq 1}} -> {{ if a eq 1 }}
5243
- * {{#note#}} -> {{# note #}}
5670
+ * {{=name|upper}} -> {{= name | upper }}
5671
+ * {{if a eq 1}} -> {{ if a eq 1 }}
5672
+ * {{#note#}} -> {{# note #}}
5244
5673
  *
5245
- * Only what is inside tags changes. Text between tags, where whitespace may
5246
- * matter, is kept byte for byte, as are whitespace-control markers. A tag is
5247
- * left exactly as written whenever its expression does not parse or
5674
+ * 2. Unless `html: false`, reindent HTML elements and block directives
5675
+ * (`if` / `for` / …). Only leading whitespace on each line changes;
5676
+ * attribute values (including embedded tags) and whitespace-sensitive
5677
+ * elements (`pre`, `script`, …) are left alone.
5678
+ *
5679
+ * A tag is left exactly as written whenever its expression does not parse or
5248
5680
  * reformatting would not provably keep its meaning. Formatting twice gives
5249
5681
  * the same result as formatting once.
5250
5682
  *
@@ -5301,7 +5733,7 @@ export default script;
5301
5733
  return (formatted !== null &&
5302
5734
  `${merged.directiveOpen}${before} ${name}${formatted && ` ${formatted}`} ${after}${merged.directiveClose}`);
5303
5735
  };
5304
- return tokens
5736
+ const tagged = tokens
5305
5737
  .map((token) => {
5306
5738
  const source = template.slice(offset(token.loc.start), offset(token.loc.end));
5307
5739
  if (token.type === exports.TokenType.TEXT) {
@@ -5314,6 +5746,18 @@ export default script;
5314
5746
  return formatTag(token) || source;
5315
5747
  })
5316
5748
  .join('');
5749
+ if (options.html === false) {
5750
+ return tagged;
5751
+ }
5752
+ return indentHtml(tagged, {
5753
+ tabWidth: options.tabWidth,
5754
+ commentOpen: merged.commentOpen,
5755
+ commentClose: merged.commentClose,
5756
+ directiveOpen: merged.directiveOpen,
5757
+ directiveClose: merged.directiveClose,
5758
+ outputOpen: merged.outputOpen,
5759
+ outputClose: merged.outputClose,
5760
+ });
5317
5761
  }
5318
5762
 
5319
5763
  /**