All files / tr8-script/domain metadata-subs.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 6/6
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  2x 8x     6x               6x   6x   6x   28x 11x 11x   6x 6x     6x 6x          
import { Eta } from "eta";
import { autoInjectable } from "tsyringe";
 
import { amountToDecimalString } from "./utils/math-low-level.js";
import { Amount } from "./value.js";
 
import type { Metadata } from "./ast.js";
 
@autoInjectable()
class MetadataSubs {
  #eta: Eta;
 
  constructor() {
    this.#eta = new Eta({
      tags: ["{{", "}}"],
      parse: { exec: "=", interpolate: "", raw: "~" },
      useWith: true,
    });
  }
 
  substitute(metadata: Metadata, vars: Record<string, Amount>): Metadata {
    const data = JSON.stringify(metadata);
 
    const stringVars: Record<string, string> = {};
 
    this.#eta
      .parse(data)
      .filter((x) => x instanceof Object)
      .map((x) => (x as { val: string }).val)
      .forEach((x) => (stringVars[x] = `{{ ${x} }}`));
 
    Object.entries(vars).forEach(([key, value]) => {
      stringVars[key] = amountToDecimalString(value);
    });
 
    const dataWithVars = this.#eta.renderString(data, stringVars);
    return JSON.parse(dataWithVars);
  }
}
 
export { MetadataSubs };