-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.js
424 lines (360 loc) 路 13.2 KB
/
index.js
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
import * as t from "@babel/types";
import _generator from "../../babel-generator/lib/index.js";
import _template from "../lib/index.js";
const generator = _generator.default;
const template = _template.default;
const comments = "// Sum two numbers\nconst add = (a, b) => a + b;";
describe("@babel/template", function () {
it("import statements are allowed by default", function () {
expect(function () {
template("import foo from 'foo'")({});
}).not.toThrow();
});
it("with statements are allowed with sourceType: script", function () {
expect(function () {
template("with({}){}", { sourceType: "script" })({});
}).not.toThrow();
});
it("should strip comments by default", function () {
const code = "const add = (a, b) => a + b;";
const output = template(comments)();
expect(generator(output).code).toBe(code);
});
it("should preserve comments with a flag", function () {
const output = template(comments, { preserveComments: true })();
expect(generator(output).code).toBe(comments);
});
it("should preserve comments with a flag", function () {
const output = template(comments, { preserveComments: true })();
expect(generator(output).code).toBe(comments);
});
it("should preserve comments with a flag when using .ast", function () {
const output1 = template.ast(comments, { preserveComments: true });
const output2 = template({ preserveComments: true }).ast(comments);
expect(generator(output1).code).toBe(comments);
expect(generator(output2).code).toBe(comments);
});
describe("string-based", () => {
it("should handle replacing values from an object", () => {
const value = t.stringLiteral("some string value");
const result = template(`
if (SOME_VAR === "") {}
`)({
SOME_VAR: value,
});
expect(result.type).toBe("IfStatement");
expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).toBe(value);
});
it("should handle replacing values given an array", () => {
const value = t.stringLiteral("some string value");
const result = template(`
if ($0 === "") {}
`)([value]);
expect(result.type).toBe("IfStatement");
expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).toBe(value);
});
it("should handle replacing values with null to remove them", () => {
const result = template(`
callee(ARG);
`)({ ARG: null });
expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).toBe("CallExpression");
expect(result.expression.arguments).toEqual([]);
});
it("should handle replacing values that are string content", () => {
const result = template(`
("ARG");
`)({ ARG: "some new content" });
expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).toBe("StringLiteral");
expect(result.expression.value).toBe("some new content");
});
it("should automatically clone nodes if they are injected twice", () => {
const id = t.identifier("someIdent");
const result = template(`
ID;
ID;
`)({ ID: id });
expect(result[0].type).toBe("ExpressionStatement");
expect(result[0].expression).toBe(id);
expect(result[1].type).toBe("ExpressionStatement");
expect(result[1].expression).not.toBe(id);
expect(result[1].expression).toEqual(id);
});
it("should allow passing in a whitelist of replacement names", () => {
const id = t.identifier("someIdent");
const result = template(
`
some_id;
`,
{ placeholderWhitelist: new Set(["some_id"]) },
)({ some_id: id });
expect(result.type).toBe("ExpressionStatement");
expect(result.expression).toBe(id);
});
it("should allow passing in a RegExp to match replacement patterns", () => {
const id = t.identifier("someIdent");
const result = template(
`
ID;
ANOTHER_ID;
`,
{ placeholderPattern: /^ID$/ },
)({ ID: id });
expect(result[0].type).toBe("ExpressionStatement");
expect(result[0].expression).toBe(id);
expect(result[1].type).toBe("ExpressionStatement");
expect(result[1].expression.type).toBe("Identifier");
expect(result[1].expression.name).toBe("ANOTHER_ID");
});
it("should throw if unknown replacements are provided", () => {
expect(() => {
template(`
ID;
`)({ ID: t.identifier("someIdent"), ANOTHER_ID: null });
}).toThrow('Unknown substitution "ANOTHER_ID" given');
});
it("should throw if placeholders are not given explicit values", () => {
expect(() => {
template(`
ID;
ANOTHER_ID;
`)({ ID: t.identifier("someIdent") });
}).toThrow(
`Error: No substitution given for "ANOTHER_ID". If this is not meant to be a
placeholder you may want to consider passing one of the following options to @babel/template:
- { placeholderPattern: false, placeholderWhitelist: new Set(['ANOTHER_ID'])}
- { placeholderPattern: /^ANOTHER_ID$/ }`,
);
});
it("should return the AST directly when using .ast", () => {
const result = template.ast(`
if ("some string value" === "") {}
`);
expect(result.type).toBe("IfStatement");
expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left.type).toBe("StringLiteral");
expect(result.test.left.value).toBe("some string value");
});
});
describe("literal-based", () => {
it("should handle replacing values from an object", () => {
const value = t.stringLiteral("some string value");
const result = template`
if (${value} === "") {}
`();
expect(result.type).toBe("IfStatement");
expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).toBe(value);
});
it("should handle replacing values with null to remove them", () => {
const result = template`
callee(${null});
`();
expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).toBe("CallExpression");
expect(result.expression.arguments).toEqual([]);
});
it("should handle replacing values that are string content", () => {
const result = template`
("${"some new content"}");
`();
expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).toBe("StringLiteral");
expect(result.expression.value).toBe("some new content");
});
it("should allow setting options by passing an object", () => {
const result = template({ sourceType: "script" })`
with({}){}
`();
expect(result.type).toBe("WithStatement");
});
it("should return the AST directly when using .ast", () => {
const value = t.stringLiteral("some string value");
const result = template.ast`
if (${value} === "") {}
`;
expect(result.type).toBe("IfStatement");
expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).toBe(value);
});
it("should return assertions in ImportDeclaration when using .ast", () => {
const result = template.ast(
`import json from "./foo.json" assert { type: "json" };`,
{
plugins: ["importAssertions"],
},
);
expect(result.assertions[0].type).toBe("ImportAttribute");
});
it("should return assertions in ExportNamedDeclaration when using .ast", () => {
const result = template.ast(
`export { default as foo2 } from "foo.json" assert { type: "json" };`,
{
plugins: ["importAssertions"],
},
);
expect(result.assertions[0].type).toBe("ImportAttribute");
});
it("should return assertions in ExportDefaultDeclaration when using .ast", () => {
const result = template.ast(
`export foo2 from "foo.json" assert { type: "json" };`,
{
plugins: ["importAssertions", "exportDefaultFrom"],
},
);
expect(result.assertions[0].type).toBe("ImportAttribute");
});
it("should return assertions in ExportAllDeclaration when using .ast", () => {
const result = template.ast(
`export * from "foo.json" assert { type: "json" };`,
{
plugins: ["importAssertions"],
},
);
expect(result.assertions[0].type).toBe("ImportAttribute");
});
it("should replace JSX placeholder", () => {
const result = template.expression(
`
<TAG>{'content'}</TAG>
`,
{
plugins: ["jsx"],
},
)({
TAG: t.jsxIdentifier("div"),
});
expect(generator(result).code).toEqual("<div>{'content'}</div>");
});
});
describe(".syntacticPlaceholders", () => {
it("works in function body", () => {
const output = template(`function f() %%A%%`)({
A: t.blockStatement([]),
});
expect(generator(output).code).toMatchInlineSnapshot(`"function f() {}"`);
});
it("works in class body", () => {
const output = template(`class C %%A%%`)({
A: t.classBody([]),
});
expect(generator(output).code).toMatchInlineSnapshot(`"class C {}"`);
});
it("replaces lowercase names", () => {
const output = template(`%%foo%%`)({
foo: t.numericLiteral(1),
});
expect(generator(output).code).toMatchInlineSnapshot(`"1;"`);
});
it("pattern", () => {
expect(() => {
template(`%%A%% + %%B%%`, {
placeholderPattern: /B/,
})();
}).toThrow(/aren't compatible with '.syntacticPlaceholders: true'/);
});
it("whitelist", () => {
expect(() => {
template(`%%A%% + %%B%%`, {
placeholderPattern: false,
placeholderWhitelist: new Set(["B"]),
})();
}).toThrow(/aren't compatible with '.syntacticPlaceholders: true'/);
});
describe("option value", () => {
describe("true", () => {
it("allows placeholders", () => {
const output = template(`%%FOO%%`, { syntacticPlaceholders: true })({
FOO: t.numericLiteral(1),
});
expect(generator(output).code).toMatchInlineSnapshot(`"1;"`);
});
it("doesn't replace identifiers", () => {
expect(() => {
template(`FOO`, { syntacticPlaceholders: true })({
FOO: t.numericLiteral(1),
});
}).toThrow(/Unknown substitution/);
});
});
describe("false", () => {
it("disallow placeholders", () => {
expect(() => {
template(`%%FOO%%`, { syntacticPlaceholders: false })({
FOO: t.numericLiteral(1),
});
}).toThrow(/Unexpected token.*/);
});
it("disallow manually enabled placeholders", () => {
expect(() => {
template(`%%FOO%%`, {
syntacticPlaceholders: false,
plugins: ["placeholders"],
})({
FOO: t.numericLiteral(1),
});
}).toThrow(/%%.*placeholders can't be used/);
});
it("replaces identifiers", () => {
const output = template(`FOO`, { syntacticPlaceholders: false })({
FOO: t.numericLiteral(1),
});
expect(generator(output).code).toMatchInlineSnapshot(`"1;"`);
});
it("allows v8intrinsics", () => {
const output = template(`%DebugPrint(1)`, {
syntacticPlaceholders: false,
plugins: ["v8intrinsic"],
})();
expect(generator(output).code).toMatchInlineSnapshot(
`"%DebugPrint(1);"`,
);
});
});
describe("undefined", () => {
it("allows placeholders", () => {
const output = template(`%%FOO%%`)({
FOO: t.numericLiteral(1),
});
expect(generator(output).code).toMatchInlineSnapshot(`"1;"`);
});
it("replaces identifiers", () => {
const output = template(`FOO`)({
FOO: t.numericLiteral(1),
});
expect(generator(output).code).toMatchInlineSnapshot(`"1;"`);
});
it("doesn't mix placeholder styles", () => {
const output = template(`FOO + %%FOO%%`)({
FOO: t.numericLiteral(1),
});
expect(generator(output).code).toMatchInlineSnapshot(`"FOO + 1;"`);
});
});
});
it("works in var declaration", () => {
const output = template("var %%LHS%% = %%RHS%%")({
LHS: t.identifier("x"),
RHS: t.numericLiteral(7),
});
expect(generator(output).code).toMatchInlineSnapshot(`"var x = 7;"`);
});
it("works in const declaration", () => {
const output = template("const %%LHS%% = %%RHS%%")({
LHS: t.identifier("x"),
RHS: t.numericLiteral(7),
});
expect(generator(output).code).toMatchInlineSnapshot(`"const x = 7;"`);
});
it("works in let declaration", () => {
const output = template("let %%LHS%% = %%RHS%%")({
LHS: t.identifier("x"),
RHS: t.numericLiteral(7),
});
expect(generator(output).code).toMatchInlineSnapshot(`"let x = 7;"`);
});
});
});