aboutsummaryrefslogtreecommitdiff
path: root/dev/lib/handlebars/src/visitor.ts
blob: 1842c8e5d6a2b325237d91621cc34aa2db71c848 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/*
 * Elasticsearch B.V licenses this file to you under the MIT License.
 * See `packages/kbn-handlebars/LICENSE` for more information.
 */

import Handlebars from 'handlebars';
import {
  createProtoAccessControl,
  resultIsAllowed,
  // @ts-expect-error: Could not find a declaration file for module
} from 'handlebars/dist/cjs/handlebars/internal/proto-access';
// @ts-expect-error: Could not find a declaration file for module
import AST from 'handlebars/dist/cjs/handlebars/compiler/ast';
// @ts-expect-error: Could not find a declaration file for module
import { indexOf, createFrame } from 'handlebars/dist/cjs/handlebars/utils';
// @ts-expect-error: Could not find a declaration file for module
import { moveHelperToHooks } from 'handlebars/dist/cjs/handlebars/helpers';

import type {
  AmbiguousHelperOptions,
  CompileOptions,
  Container,
  DecoratorDelegate,
  DecoratorsHash,
  HelperOptions,
  NodeType,
  NonBlockHelperOptions,
  ProcessableBlockStatementNode,
  ProcessableNode,
  ProcessableNodeWithPathParts,
  ProcessableNodeWithPathPartsOrLiteral,
  ProcessableStatementNode,
  ResolvePartialOptions,
  RuntimeOptions,
  Template,
  TemplateDelegate,
  VisitorHelper,
} from './types';
import { kAmbiguous, kHelper, kSimple } from './symbols';
import {
  initData,
  isBlock,
  isDecorator,
  noop,
  toDecoratorOptions,
  transformLiteralToPath,
} from './utils';

export class ElasticHandlebarsVisitor extends Handlebars.Visitor {
  private env: typeof Handlebars;
  private contexts: any[] = [];
  private output: any[] = [];
  private template?: string;
  private compileOptions: CompileOptions;
  private runtimeOptions?: RuntimeOptions;
  private blockParamNames: any[][] = [];
  private blockParamValues: any[][] = [];
  private ast?: hbs.AST.Program;
  private container: Container;
  private defaultHelperOptions: Pick<NonBlockHelperOptions, 'lookupProperty'>;
  private processedRootDecorators = false; // Root decorators should not have access to input arguments. This flag helps us detect them.
  private processedDecoratorsForProgram = new Set(); // It's important that a given program node only has its decorators run once, we use this Map to keep track of them

  constructor(
    env: typeof Handlebars,
    input: string | hbs.AST.Program,
    options: CompileOptions = {}
  ) {
    super();

    this.env = env;

    if (typeof input !== 'string' && input.type === 'Program') {
      this.ast = input;
    } else {
      this.template = input as string;
    }

    this.compileOptions = { data: true, ...options };
    this.compileOptions.knownHelpers = Object.assign(
      Object.create(null),
      {
        helperMissing: true,
        blockHelperMissing: true,
        each: true,
        if: true,
        unless: true,
        with: true,
        log: true,
        lookup: true,
      },
      this.compileOptions.knownHelpers
    );

    const protoAccessControl = createProtoAccessControl({});

    const container: Container = (this.container = {
      helpers: {},
      partials: {},
      decorators: {},
      strict(obj, name, loc) {
        if (!obj || !(name in obj)) {
          throw new Handlebars.Exception('"' + name + '" not defined in ' + obj, {
            loc,
          } as hbs.AST.Node);
        }
        return container.lookupProperty(obj, name);
      },
      // this function is lifted from the handlebars source and slightly modified (lib/handlebars/runtime.js)
      lookupProperty(parent, propertyName) {
        const result = parent[propertyName];
        if (result == null) {
          return result;
        }
        if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
          return result;
        }

        if (resultIsAllowed(result, protoAccessControl, propertyName)) {
          return result;
        }
        return undefined;
      },
      // this function is lifted from the handlebars source and slightly modified (lib/handlebars/runtime.js)
      lambda(current, context) {
        return typeof current === 'function' ? current.call(context) : current;
      },
      data(value: any, depth: number) {
        while (value && depth--) {
          value = value._parent;
        }
        return value;
      },
      hooks: {},
    });

    this.defaultHelperOptions = {
      lookupProperty: container.lookupProperty,
    };
  }

  render(context: any, options: RuntimeOptions = {}): string {
    this.contexts = [context];
    this.output = [];
    this.runtimeOptions = { ...options };
    this.container.helpers = { ...this.env.helpers, ...options.helpers };
    this.container.partials = { ...this.env.partials, ...options.partials };
    this.container.decorators = {
      ...(this.env.decorators as DecoratorsHash),
      ...options.decorators,
    };
    this.container.hooks = {};
    this.processedRootDecorators = false;
    this.processedDecoratorsForProgram.clear();

    if (this.compileOptions.data) {
      this.runtimeOptions.data = initData(context, this.runtimeOptions.data);
    }

    const keepHelperInHelpers = false;
    moveHelperToHooks(this.container, 'helperMissing', keepHelperInHelpers);
    moveHelperToHooks(this.container, 'blockHelperMissing', keepHelperInHelpers);

    if (!this.ast) {
      this.ast = Handlebars.parse(this.template!);
    }

    // The `defaultMain` function contains the default behavior:
    //
    // Generate a "program" function based on the root `Program` in the AST and
    // call it. This will start the processing of all the child nodes in the
    // AST.
    const defaultMain: TemplateDelegate = (_context) => {
      const prog = this.generateProgramFunction(this.ast!);
      return prog(_context, this.runtimeOptions);
    };

    // Run any decorators that might exist on the root:
    //
    // The `defaultMain` function is passed in, and if there are no root
    // decorators, or if the decorators chooses to do so, the same function is
    // returned from `processDecorators` and the default behavior is retained.
    //
    // Alternatively any of the root decorators might call the `defaultMain`
    // function themselves, process its return value, and return a completely
    // different `main` function.
    const main = this.processDecorators(this.ast, defaultMain);
    this.processedRootDecorators = true;

    // Call the `main` function and add the result to the final output.
    const result = main(this.context, options);

    if (main === defaultMain) {
      this.output.push(result);
      return this.output.join('');
    } else {
      // We normally expect the return value of `main` to be a string. However,
      // if a decorator is used to override the `defaultMain` function, the
      // return value can be any type. To match the upstream handlebars project
      // behavior, we want the result of rendering the template to be the
      // literal value returned by the decorator.
      //
      // Since the output array in this case always will be empty, we just
      // return that single value instead of attempting to join all the array
      // elements as strings.
      return result;
    }
  }

  // ********************************************** //
  // ***    Visitor AST Traversal Functions     *** //
  // ********************************************** //

  Program(program: hbs.AST.Program) {
    this.blockParamNames.unshift(program.blockParams);
    super.Program(program);
    this.blockParamNames.shift();
  }

  MustacheStatement(mustache: hbs.AST.MustacheStatement) {
    this.processStatementOrExpression(mustache);
  }

  BlockStatement(block: hbs.AST.BlockStatement) {
    this.processStatementOrExpression(block);
  }

  PartialStatement(partial: hbs.AST.PartialStatement) {
    this.invokePartial(partial);
  }

  PartialBlockStatement(partial: hbs.AST.PartialBlockStatement) {
    this.invokePartial(partial);
  }

  // This space is intentionally left blank: We want to override the Visitor
  // class implementation of this method, but since we handle decorators
  // separately before traversing the nodes, we just want to make this a no-op.
  DecoratorBlock(decorator: hbs.AST.DecoratorBlock) {}

  // This space is intentionally left blank: We want to override the Visitor
  // class implementation of this method, but since we handle decorators
  // separately before traversing the nodes, we just want to make this a no-op.
  Decorator(decorator: hbs.AST.Decorator) {}

  SubExpression(sexpr: hbs.AST.SubExpression) {
    this.processStatementOrExpression(sexpr);
  }

  PathExpression(path: hbs.AST.PathExpression) {
    const blockParamId =
      !path.depth && !AST.helpers.scopedId(path) && this.blockParamIndex(path.parts[0]);

    let result;
    if (blockParamId) {
      result = this.lookupBlockParam(blockParamId, path);
    } else if (path.data) {
      result = this.lookupData(this.runtimeOptions!.data, path);
    } else {
      result = this.resolvePath(this.contexts[path.depth], path);
    }

    this.output.push(result);
  }

  ContentStatement(content: hbs.AST.ContentStatement) {
    this.output.push(content.value);
  }

  StringLiteral(string: hbs.AST.StringLiteral) {
    this.output.push(string.value);
  }

  NumberLiteral(number: hbs.AST.NumberLiteral) {
    this.output.push(number.value);
  }

  BooleanLiteral(bool: hbs.AST.BooleanLiteral) {
    this.output.push(bool.value);
  }

  UndefinedLiteral() {
    this.output.push(undefined);
  }

  NullLiteral() {
    this.output.push(null);
  }

  // ********************************************** //
  // ***      Visitor AST Helper Functions      *** //
  // ********************************************** //

  /**
   * Special code for decorators, since they have to be executed ahead of time (before the wrapping program).
   * So we have to look into the program AST body and see if it contains any decorators that we have to process
   * before we can finish processing of the wrapping program.
   */
  private processDecorators(program: hbs.AST.Program, prog: TemplateDelegate) {
    if (!this.processedDecoratorsForProgram.has(program)) {
      this.processedDecoratorsForProgram.add(program);
      const props = {};
      for (const node of program.body) {
        if (isDecorator(node)) {
          prog = this.processDecorator(node, prog, props);
        }
      }
    }

    return prog;
  }

  private processDecorator(
    decorator: hbs.AST.DecoratorBlock | hbs.AST.Decorator,
    prog: TemplateDelegate,
    props: Record<string, any>
  ) {
    const options = this.setupDecoratorOptions(decorator);

    const result = this.container.lookupProperty<DecoratorDelegate>(
      this.container.decorators,
      options.name
    )(prog, props, this.container, options);

    return Object.assign(result || prog, props);
  }

  private processStatementOrExpression(node: ProcessableNodeWithPathPartsOrLiteral) {
    // Calling `transformLiteralToPath` has side-effects!
    // It converts a node from type `ProcessableNodeWithPathPartsOrLiteral` to `ProcessableNodeWithPathParts`
    transformLiteralToPath(node);

    switch (this.classifyNode(node as ProcessableNodeWithPathParts)) {
      case kSimple:
        this.processSimpleNode(node as ProcessableNodeWithPathParts);
        break;
      case kHelper:
        this.processHelperNode(node as ProcessableNodeWithPathParts);
        break;
      case kAmbiguous:
        this.processAmbiguousNode(node as ProcessableNodeWithPathParts);
        break;
    }
  }

  // Liftet from lib/handlebars/compiler/compiler.js (original name: classifySexpr)
  private classifyNode(node: { path: hbs.AST.PathExpression }): NodeType {
    const isSimple = AST.helpers.simpleId(node.path);
    const isBlockParam = isSimple && !!this.blockParamIndex(node.path.parts[0]);

    // a mustache is an eligible helper if:
    // * its id is simple (a single part, not `this` or `..`)
    let isHelper = !isBlockParam && AST.helpers.helperExpression(node);

    // if a mustache is an eligible helper but not a definite
    // helper, it is ambiguous, and will be resolved in a later
    // pass or at runtime.
    let isEligible = !isBlockParam && (isHelper || isSimple);

    // if ambiguous, we can possibly resolve the ambiguity now
    // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
    if (isEligible && !isHelper) {
      const name = node.path.parts[0];
      const options = this.compileOptions;
      if (options.knownHelpers && options.knownHelpers[name]) {
        isHelper = true;
      } else if (options.knownHelpersOnly) {
        isEligible = false;
      }
    }

    if (isHelper) {
      return kHelper;
    } else if (isEligible) {
      return kAmbiguous;
    } else {
      return kSimple;
    }
  }

  // Liftet from lib/handlebars/compiler/compiler.js
  private blockParamIndex(name: string): [number, any] | undefined {
    for (let depth = 0, len = this.blockParamNames.length; depth < len; depth++) {
      const blockParams = this.blockParamNames[depth];
      const param = blockParams && indexOf(blockParams, name);
      if (blockParams && param >= 0) {
        return [depth, param];
      }
    }
  }

  // Looks up the value of `parts` on the given block param and pushes
  // it onto the stack.
  private lookupBlockParam(blockParamId: [number, any], path: hbs.AST.PathExpression) {
    const value = this.blockParamValues[blockParamId[0]][blockParamId[1]];
    return this.resolvePath(value, path, 1);
  }

  // Push the data lookup operator
  private lookupData(data: any, path: hbs.AST.PathExpression) {
    if (path.depth) {
      data = this.container.data(data, path.depth);
    }

    return this.resolvePath(data, path);
  }

  private processSimpleNode(node: ProcessableNodeWithPathParts) {
    const path = node.path;
    // @ts-expect-error strict is not a valid property on PathExpression, but we used in the same way it's also used in the original handlebars
    path.strict = true;
    const result = this.resolveNodes(path)[0];
    const lambdaResult = this.container.lambda(result, this.context);

    if (isBlock(node)) {
      this.blockValue(node, lambdaResult);
    } else {
      this.output.push(lambdaResult);
    }
  }

  // The purpose of this opcode is to take a block of the form
  // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  // replace it on the stack with the result of properly
  // invoking blockHelperMissing.
  private blockValue(node: hbs.AST.BlockStatement, value: any) {
    const name = node.path.original;
    const options = this.setupParams(node, name);

    const result = this.container.hooks.blockHelperMissing!.call(this.context, value, options);

    this.output.push(result);
  }

  private processHelperNode(node: ProcessableNodeWithPathParts) {
    const path = node.path;
    const name = path.parts[0];

    if (this.compileOptions.knownHelpers && this.compileOptions.knownHelpers[name]) {
      this.invokeKnownHelper(node);
    } else if (this.compileOptions.knownHelpersOnly) {
      throw new Handlebars.Exception(
        'You specified knownHelpersOnly, but used the unknown helper ' + name,
        node
      );
    } else {
      this.invokeHelper(node);
    }
  }

  // This operation is used when the helper is known to exist,
  // so a `helperMissing` fallback is not required.
  private invokeKnownHelper(node: ProcessableNodeWithPathParts) {
    const name = node.path.parts[0];
    const helper = this.setupHelper(node, name);
    // TypeScript: `helper.fn` might be `undefined` at this point, but to match the upstream behavior we call it without any guards
    const result = helper.fn!.call(helper.context, ...helper.params, helper.options);
    this.output.push(result);
  }

  // Pops off the helper's parameters, invokes the helper,
  // and pushes the helper's return value onto the stack.
  //
  // If the helper is not found, `helperMissing` is called.
  private invokeHelper(node: ProcessableNodeWithPathParts) {
    const path = node.path;
    const name = path.original;
    const isSimple = AST.helpers.simpleId(path);
    const helper = this.setupHelper(node, name);

    const loc = isSimple && helper.fn ? node.loc : path.loc;
    helper.fn = (isSimple && helper.fn) || this.resolveNodes(path)[0];

    if (!helper.fn) {
      if (this.compileOptions.strict) {
        helper.fn = this.container.strict(helper.context, name, loc);
      } else {
        helper.fn = this.container.hooks.helperMissing;
      }
    }

    // TypeScript: `helper.fn` might be `undefined` at this point, but to match the upstream behavior we call it without any guards
    const result = helper.fn!.call(helper.context, ...helper.params, helper.options);

    this.output.push(result);
  }

  private invokePartial(partial: hbs.AST.PartialStatement | hbs.AST.PartialBlockStatement) {
    const { params } = partial;
    if (params.length > 1) {
      throw new Handlebars.Exception(
        `Unsupported number of partial arguments: ${params.length}`,
        partial
      );
    }

    const isDynamic = partial.name.type === 'SubExpression';
    const name = isDynamic
      ? this.resolveNodes(partial.name).join('')
      : (partial.name as hbs.AST.PathExpression).original;

    const options: AmbiguousHelperOptions & ResolvePartialOptions = this.setupParams(partial, name);
    options.helpers = this.container.helpers;
    options.partials = this.container.partials;
    options.decorators = this.container.decorators;

    let partialBlock;
    if ('fn' in options && options.fn !== noop) {
      const { fn } = options;
      const currentPartialBlock = options.data?.['partial-block'];
      options.data = createFrame(options.data);

      // Wrapper function to get access to currentPartialBlock from the closure
      partialBlock = options.data['partial-block'] = function partialBlockWrapper(
        context: any,
        wrapperOptions: { data?: HelperOptions['data'] } = {}
      ) {
        // Restore the partial-block from the closure for the execution of the block
        // i.e. the part inside the block of the partial call.
        wrapperOptions.data = createFrame(wrapperOptions.data);
        wrapperOptions.data['partial-block'] = currentPartialBlock;
        return fn(context, wrapperOptions);
      };

      if (fn.partials) {
        options.partials = { ...options.partials, ...fn.partials };
      }
    }

    let context = {};
    if (params.length === 0 && !this.compileOptions.explicitPartialContext) {
      context = this.context;
    } else if (params.length === 1) {
      context = this.resolveNodes(params[0])[0];
    }

    if (Object.keys(options.hash).length > 0) {
      // TODO: context can be an array, but maybe never when we have a hash???
      context = Object.assign({}, context, options.hash);
    }

    const partialTemplate: Template | undefined =
      this.container.partials[name] ??
      partialBlock ??
      // TypeScript note: We extend ResolvePartialOptions in our types.ts file
      // to fix an error in the upstream type. When calling back into the
      // upstream code, we just cast back to the non-extended type
      Handlebars.VM.resolvePartial(
        undefined,
        undefined,
        options as Handlebars.ResolvePartialOptions
      );

    if (partialTemplate === undefined) {
      throw new Handlebars.Exception(`The partial ${name} could not be found`);
    }

    let render;
    if (typeof partialTemplate === 'string') {
      render = this.env.compileAST(partialTemplate, this.compileOptions);
      if (name in this.container.partials) {
        this.container.partials[name] = render;
      }
    } else {
      render = partialTemplate;
    }

    let result = render(context, options);

    if ('indent' in partial) {
      result =
        partial.indent +
        (this.compileOptions.preventIndent
          ? result
          : result.replace(/\n(?!$)/g, `\n${partial.indent}`)); // indent each line, ignoring any trailing linebreak
    }

    this.output.push(result);
  }

  private processAmbiguousNode(node: ProcessableNodeWithPathParts) {
    const name = node.path.parts[0];
    const helper = this.setupHelper(node, name);
    let { fn: helperFn } = helper;

    const loc = helperFn ? node.loc : node.path.loc;
    helperFn = helperFn ?? this.resolveNodes(node.path)[0];

    if (helperFn === undefined) {
      if (this.compileOptions.strict) {
        helperFn = this.container.strict(helper.context, name, loc);
      } else {
        helperFn =
          helper.context != null
            ? this.container.lookupProperty(helper.context, name)
            : helper.context;
        if (helperFn == null) helperFn = this.container.hooks.helperMissing;
      }
    }

    const helperResult =
      typeof helperFn === 'function'
        ? helperFn.call(helper.context, ...helper.params, helper.options)
        : helperFn;

    if (isBlock(node)) {
      const result = helper.fn
        ? helperResult
        : this.container.hooks.blockHelperMissing!.call(this.context, helperResult, helper.options);
      if (result != null) {
        this.output.push(result);
      }
    } else {
      if (
        (node as hbs.AST.MustacheStatement).escaped === false ||
        this.compileOptions.noEscape === true ||
        typeof helperResult !== 'string'
      ) {
        this.output.push(helperResult);
      } else {
        this.output.push(Handlebars.escapeExpression(helperResult));
      }
    }
  }

  private setupHelper(node: ProcessableNode, helperName: string): VisitorHelper {
    return {
      fn: this.container.lookupProperty(this.container.helpers, helperName),
      context: this.context,
      params: this.resolveNodes(node.params),
      options: this.setupParams(node, helperName),
    };
  }

  private setupDecoratorOptions(decorator: hbs.AST.Decorator | hbs.AST.DecoratorBlock) {
    // TypeScript: The types indicate that `decorator.path` technically can be an `hbs.AST.Literal`. However, the upstream codebase always treats it as an `hbs.AST.PathExpression`, so we do too.
    const name = (decorator.path as hbs.AST.PathExpression).original;
    const options = toDecoratorOptions(this.setupParams(decorator, name));

    if (decorator.params.length > 0) {
      if (!this.processedRootDecorators) {
        // When processing the root decorators, temporarily remove the root context so it's not accessible to the decorator
        const context = this.contexts.shift();
        options.args = this.resolveNodes(decorator.params);
        this.contexts.unshift(context);
      } else {
        options.args = this.resolveNodes(decorator.params);
      }
    } else {
      options.args = [];
    }

    return options;
  }

  private setupParams(node: ProcessableBlockStatementNode, name: string): HelperOptions;
  private setupParams(node: ProcessableStatementNode, name: string): NonBlockHelperOptions;
  private setupParams(node: ProcessableNode, name: string): AmbiguousHelperOptions;
  private setupParams(node: ProcessableNode, name: string) {
    const options: AmbiguousHelperOptions = {
      name,
      hash: this.getHash(node),
      data: this.runtimeOptions!.data,
      loc: { start: node.loc.start, end: node.loc.end },
      ...this.defaultHelperOptions,
    };

    if (isBlock(node)) {
      (options as HelperOptions).fn = node.program
        ? this.processDecorators(node.program, this.generateProgramFunction(node.program))
        : noop;
      (options as HelperOptions).inverse = node.inverse
        ? this.processDecorators(node.inverse, this.generateProgramFunction(node.inverse))
        : noop;
    }

    return options;
  }

  private generateProgramFunction(program: hbs.AST.Program) {
    if (!program) return noop;

    const prog: TemplateDelegate = (nextContext: any, runtimeOptions: RuntimeOptions = {}) => {
      runtimeOptions = { ...runtimeOptions };

      // inherit data in blockParams from parent program
      runtimeOptions.data = runtimeOptions.data || this.runtimeOptions!.data;
      if (runtimeOptions.blockParams) {
        runtimeOptions.blockParams = runtimeOptions.blockParams.concat(
          this.runtimeOptions!.blockParams
        );
      }

      // inherit partials from parent program
      runtimeOptions.partials = runtimeOptions.partials || this.runtimeOptions!.partials;

      // stash parent program data
      const tmpRuntimeOptions = this.runtimeOptions;
      this.runtimeOptions = runtimeOptions;
      const shiftContext = nextContext !== this.context;
      if (shiftContext) this.contexts.unshift(nextContext);
      this.blockParamValues.unshift(runtimeOptions.blockParams || []);

      // execute child program
      const result = this.resolveNodes(program).join('');

      // unstash parent program data
      this.blockParamValues.shift();
      if (shiftContext) this.contexts.shift();
      this.runtimeOptions = tmpRuntimeOptions;

      // return result of child program
      return result;
    };

    prog.blockParams = program.blockParams?.length ?? 0;
    return prog;
  }

  private getHash(statement: { hash?: hbs.AST.Hash }) {
    const result: { [key: string]: any } = {};
    if (!statement.hash) return result;
    for (const { key, value } of statement.hash.pairs) {
      result[key] = this.resolveNodes(value)[0];
    }
    return result;
  }

  private resolvePath(obj: any, path: hbs.AST.PathExpression, index = 0) {
    if (this.compileOptions.strict || this.compileOptions.assumeObjects) {
      return this.strictLookup(obj, path);
    }

    for (; index < path.parts.length; index++) {
      if (obj == null) return;
      obj = this.container.lookupProperty(obj, path.parts[index]);
    }

    return obj;
  }

  private strictLookup(obj: any, path: hbs.AST.PathExpression) {
    // @ts-expect-error strict is not a valid property on PathExpression, but we used in the same way it's also used in the original handlebars
    const requireTerminal = this.compileOptions.strict && path.strict;
    const len = path.parts.length - (requireTerminal ? 1 : 0);

    for (let i = 0; i < len; i++) {
      obj = this.container.lookupProperty(obj, path.parts[i]);
    }

    if (requireTerminal) {
      return this.container.strict(obj, path.parts[len], path.loc);
    } else {
      return obj;
    }
  }

  private resolveNodes(nodes: hbs.AST.Node | hbs.AST.Node[]): any[] {
    const currentOutput = this.output;
    this.output = [];

    if (Array.isArray(nodes)) {
      this.acceptArray(nodes);
    } else {
      this.accept(nodes);
    }

    const result = this.output;

    this.output = currentOutput;

    return result;
  }

  private get context() {
    return this.contexts[0];
  }
}