Debian Codegraph @

packages/babel-template/src/builder.ts

raw
1 import { merge, validate } from "./options";
2 import type { TemplateOpts, PublicOpts, PublicReplacements } from "./options";
3 import type { Formatter } from "./formatters";
4
5 import stringTemplate from "./string";
6 import literalTemplate from "./literal";
7
8 export type TemplateBuilder<T> = {
9 // Build a new builder, merging the given options with the previous ones.
10 (opts: PublicOpts): TemplateBuilder<T>;
11
12 // Building from a string produces an AST builder function by default.
13 (tpl: string, opts?: PublicOpts): (replacements?: PublicReplacements) => T;
14
15 // Building from a template literal produces an AST builder function by default.
16 (tpl: TemplateStringsArray, ...args: Array<unknown>): (
17 replacements?: PublicReplacements,
18 ) => T;
19
20 // Allow users to explicitly create templates that produce ASTs, skipping
21 // the need for an intermediate function.
22 ast: {
23 (tpl: string, opts?: PublicOpts): T;
24 (tpl: TemplateStringsArray, ...args: Array<unknown>): T;
25 };
26 };
27
28 // Prebuild the options that will be used when parsing a `.ast` template.
29 // These do not use a pattern because there is no way for users to pass in
30 // replacement patterns to begin with, and disabling pattern matching means
31 // users have more flexibility in what type of content they have in their
32 // template JS.
33 const NO_PLACEHOLDER: TemplateOpts = validate({
34 placeholderPattern: false,
35 });
36
37 export default function createTemplateBuilder<T>(
38 formatter: Formatter<T>,
39 defaultOpts?: TemplateOpts,
40 ): TemplateBuilder<T> {
41 const templateFnCache = new WeakMap();
42 const templateAstCache = new WeakMap();
43 const cachedOpts = defaultOpts || validate(null);
44
45 return Object.assign(
46 ((tpl, ...args) => {
47 if (typeof tpl === "string") {
48 if (args.length > 1) throw new Error("Unexpected extra params.");
49 return extendedTrace(
50 stringTemplate(formatter, tpl, merge(cachedOpts, validate(args[0]))),
51 );
52 } else if (Array.isArray(tpl)) {
53 let builder = templateFnCache.get(tpl);
54 if (!builder) {
55 builder = literalTemplate(formatter, tpl, cachedOpts);
56 templateFnCache.set(tpl, builder);
57 }
58 return extendedTrace(builder(args));
59 } else if (typeof tpl === "object" && tpl) {
60 if (args.length > 0) throw new Error("Unexpected extra params.");
61 return createTemplateBuilder(
62 formatter,
63 merge(cachedOpts, validate(tpl)),
64 );
65 }
66 throw new Error(`Unexpected template param ${typeof tpl}`);
67 }) as TemplateBuilder<T>,
68 {
69 ast: (tpl: string | Array<string>, ...args: Array<unknown>) => {
70 if (typeof tpl === "string") {
71 if (args.length > 1) throw new Error("Unexpected extra params.");
72 return stringTemplate(
73 formatter,
74 tpl,
75 merge(merge(cachedOpts, validate(args[0])), NO_PLACEHOLDER),
76 )();
77 } else if (Array.isArray(tpl)) {
78 let builder = templateAstCache.get(tpl);
79 if (!builder) {
80 builder = literalTemplate(
81 formatter,
82 tpl,
83 merge(cachedOpts, NO_PLACEHOLDER),
84 );
85 templateAstCache.set(tpl, builder);
86 }
87 return builder(args)();
88 }
89
90 throw new Error(`Unexpected template param ${typeof tpl}`);
91 },
92 },
93 );
94 }
95
96 function extendedTrace<Arg, Result>(
97 fn: (_: Arg) => Result,
98 ): (_: Arg) => Result {
99 // Since we lazy parse the template, we get the current stack so we have the
100 // original stack to append if it errors when parsing
101 let rootStack = "";
102 try {
103 // error stack gets populated in IE only on throw
104 // (https://msdn.microsoft.com/en-us/library/hh699850(v=vs.94).aspx)
105 throw new Error();
106 } catch (error) {
107 if (error.stack) {
108 // error.stack does not exists in IE <= 9
109 // We slice off the top 3 items in the stack to remove the call to
110 // 'extendedTrace', and the anonymous builder function, with the final
111 // stripped line being the error message itself since we threw it
112 // in the first place and it doesn't matter.
113 rootStack = error.stack.split("\n").slice(3).join("\n");
114 }
115 }
116
117 return (arg: Arg) => {
118 try {
119 return fn(arg);
120 } catch (err) {
121 err.stack += `\n =============\n${rootStack}`;
122 throw err;
123 }
124 };
125 }