Debian Codegraph @

packages/babel-template/src/literal.ts

raw
1 import type { Formatter } from "./formatters";
2 import type { TemplateReplacements, TemplateOpts } from "./options";
3 import { normalizeReplacements } from "./options";
4 import parseAndBuildMetadata from "./parse";
5 import populatePlaceholders from "./populate";
6
7 export default function literalTemplate<T>(
8 formatter: Formatter<T>,
9 tpl: Array<string>,
10 opts: TemplateOpts,
11 ): (_: Array<unknown>) => (_: unknown) => T {
12 const { metadata, names } = buildLiteralData(formatter, tpl, opts);
13
14 return arg => {
15 const defaultReplacements: TemplateReplacements = {};
16 arg.forEach((replacement, i) => {
17 defaultReplacements[names[i]] = replacement;
18 });
19
20 return (arg: unknown) => {
21 const replacements = normalizeReplacements(arg);
22
23 if (replacements) {
24 Object.keys(replacements).forEach(key => {
25 if (Object.prototype.hasOwnProperty.call(defaultReplacements, key)) {
26 throw new Error("Unexpected replacement overlap.");
27 }
28 });
29 }
30
31 return formatter.unwrap(
32 populatePlaceholders(
33 metadata,
34 replacements
35 ? Object.assign(replacements, defaultReplacements)
36 : defaultReplacements,
37 ),
38 );
39 };
40 };
41 }
42
43 function buildLiteralData<T>(
44 formatter: Formatter<T>,
45 tpl: Array<string>,
46 opts: TemplateOpts,
47 ) {
48 let names;
49 let nameSet: Set<string>;
50 let metadata;
51 let prefix = "";
52
53 do {
54 // If there are cases where the template already contains $0 or any other
55 // matching pattern, we keep adding "$" characters until a unique prefix
56 // is found.
57 prefix += "$";
58 const result = buildTemplateCode(tpl, prefix);
59
60 names = result.names;
61 nameSet = new Set(names);
62 metadata = parseAndBuildMetadata(formatter, formatter.code(result.code), {
63 parser: opts.parser,
64
65 // Explicitly include our generated names in the whitelist so users never
66 // have to think about whether their placeholder pattern will match.
67 placeholderWhitelist: new Set(
68 result.names.concat(
69 opts.placeholderWhitelist
70 ? Array.from(opts.placeholderWhitelist)
71 : [],
72 ),
73 ),
74 placeholderPattern: opts.placeholderPattern,
75 preserveComments: opts.preserveComments,
76 syntacticPlaceholders: opts.syntacticPlaceholders,
77 });
78 } while (
79 metadata.placeholders.some(
80 placeholder => placeholder.isDuplicate && nameSet.has(placeholder.name),
81 )
82 );
83
84 return { metadata, names };
85 }
86
87 function buildTemplateCode(
88 tpl: Array<string>,
89 prefix: string,
90 ): { names: Array<string>; code: string } {
91 const names = [];
92
93 let code = tpl[0];
94
95 for (let i = 1; i < tpl.length; i++) {
96 const value = `${prefix}${i - 1}`;
97 names.push(value);
98
99 code += value + tpl[i];
100 }
101
102 return { names, code };
103 }