1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.default = createTemplateBuilder;
|
7 |
|
8 | var _options = require("./options");
|
9 |
|
10 | var _string = _interopRequireDefault(require("./string"));
|
11 |
|
12 | var _literal = _interopRequireDefault(require("./literal"));
|
13 |
|
14 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
15 |
|
16 | const NO_PLACEHOLDER = (0, _options.validate)({
|
17 | placeholderPattern: false
|
18 | });
|
19 |
|
20 | function createTemplateBuilder(formatter, defaultOpts) {
|
21 | const templateFnCache = new WeakMap();
|
22 | const templateAstCache = new WeakMap();
|
23 | const cachedOpts = defaultOpts || (0, _options.validate)(null);
|
24 | return Object.assign((tpl, ...args) => {
|
25 | if (typeof tpl === "string") {
|
26 | if (args.length > 1) throw new Error("Unexpected extra params.");
|
27 | return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0]))));
|
28 | } else if (Array.isArray(tpl)) {
|
29 | let builder = templateFnCache.get(tpl);
|
30 |
|
31 | if (!builder) {
|
32 | builder = (0, _literal.default)(formatter, tpl, cachedOpts);
|
33 | templateFnCache.set(tpl, builder);
|
34 | }
|
35 |
|
36 | return extendedTrace(builder(args));
|
37 | } else if (typeof tpl === "object" && tpl) {
|
38 | if (args.length > 0) throw new Error("Unexpected extra params.");
|
39 | return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl)));
|
40 | }
|
41 |
|
42 | throw new Error(`Unexpected template param ${typeof tpl}`);
|
43 | }, {
|
44 | ast: (tpl, ...args) => {
|
45 | if (typeof tpl === "string") {
|
46 | if (args.length > 1) throw new Error("Unexpected extra params.");
|
47 | return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))();
|
48 | } else if (Array.isArray(tpl)) {
|
49 | let builder = templateAstCache.get(tpl);
|
50 |
|
51 | if (!builder) {
|
52 | builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER));
|
53 | templateAstCache.set(tpl, builder);
|
54 | }
|
55 |
|
56 | return builder(args)();
|
57 | }
|
58 |
|
59 | throw new Error(`Unexpected template param ${typeof tpl}`);
|
60 | }
|
61 | });
|
62 | }
|
63 |
|
64 | function extendedTrace(fn) {
|
65 | let rootStack = "";
|
66 |
|
67 | try {
|
68 | throw new Error();
|
69 | } catch (error) {
|
70 | if (error.stack) {
|
71 | rootStack = error.stack.split("\n").slice(3).join("\n");
|
72 | }
|
73 | }
|
74 |
|
75 | return arg => {
|
76 | try {
|
77 | return fn(arg);
|
78 | } catch (err) {
|
79 | err.stack += `\n =============\n${rootStack}`;
|
80 | throw err;
|
81 | }
|
82 | };
|
83 | } |
\ | No newline at end of file |