This repository has been archived by the owner on Dec 8, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathindex.js
550 lines (438 loc) · 16.9 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
'use strict';
const { replaceTemplateLiteralProposal } = require('./src/template-literal-transform');
const { replaceTemplateTagProposal } = require('./src/template-tag-transform');
const { registerRefs } = require('./src/util');
const { setupState, processImportDeclaration } = require('babel-plugin-ember-modules-api-polyfill');
module.exports = function (babel) {
let t = babel.types;
const runtimeErrorIIFE = babel.template(
`(function() {\n throw new Error('ERROR_MESSAGE');\n})();`
);
function parseExpression(state, buildError, name, node) {
switch (node.type) {
case 'ObjectExpression':
return parseObjectExpression(state, buildError, name, node);
case 'ArrayExpression': {
return parseArrayExpression(state, buildError, name, node);
}
case 'StringLiteral':
case 'BooleanLiteral':
case 'NumericLiteral':
return node.value;
default:
throw buildError(
`${name} can only accept static options but you passed ${JSON.stringify(node)}`
);
}
}
function parseArrayExpression(state, buildError, name, node) {
let result = node.elements.map((element) => parseExpression(state, buildError, name, element));
return result;
}
function parseScope(state, buildError, name, node) {
let body;
if (node.type === 'ObjectMethod') {
body = node.body;
} else if (node.value.type === 'ObjectExpression') {
console.warn(
`Passing an object as the \`scope\` property to inline templates has been deprecated. Please pass a function that returns an object expression instead. Usage in: ${state.file.opts.filename}`
);
body = node.value;
} else {
body = node.value.body;
}
let objExpression;
if (body && body.type === 'ObjectExpression') {
objExpression = body;
} else if (body && body.type === 'BlockStatement') {
let returnStatement = body.body[0];
if (body.body.length !== 1 || returnStatement.type !== 'ReturnStatement') {
throw new Error(
'Scope functions can only consist of a single return statement which returns an object expression containing references to in-scope values'
);
}
objExpression = returnStatement.argument;
}
if (!objExpression || objExpression.type !== 'ObjectExpression') {
throw buildError(
`Scope objects for \`${name}\` must be an object expression containing only references to in-scope values, or a function that returns an object expression containing only references to in-scope values`
);
}
return objExpression.properties.map((prop) => {
let { key, value } = prop;
if (value.type !== 'Identifier' || value.name !== key.name) {
throw buildError(
`Scope objects for \`${name}\` may only contain direct references to in-scope values, e.g. { ${key.name} } or { ${key.name}: ${key.name} }`
);
}
return key.name;
});
}
function parseObjectExpression(state, buildError, name, node, shouldParseScope = false) {
let result = {};
node.properties.forEach((property) => {
if (property.computed || !['Identifier', 'StringLiteral'].includes(property.key.type)) {
throw buildError(`${name} can only accept static options`);
}
let propertyName =
property.key.type === 'Identifier' ? property.key.name : property.key.value;
if (shouldParseScope && propertyName === 'scope') {
result.locals = parseScope(state, buildError, name, property);
} else {
result[propertyName] = parseExpression(state, buildError, name, property.value);
}
});
return result;
}
function compileTemplate(precompile, template, templateCompilerIdentifier, _options) {
let options = Object.assign({ contents: template }, _options);
let precompileResultString;
if (options.insertRuntimeErrors) {
try {
precompileResultString = precompile(template, options);
} catch (error) {
return runtimeErrorIIFE({ ERROR_MESSAGE: error.message });
}
} else {
precompileResultString = precompile(template, options);
}
let precompileResultAST = babel.parse(`var precompileResult = ${precompileResultString};`, {
babelrc: false,
configFile: false,
});
let templateExpression = precompileResultAST.program.body[0].declarations[0].init;
t.addComment(
templateExpression,
'leading',
`\n ${template.replace(/\*\//g, '*\\/')}\n`,
/* line comment? */ false
);
return t.callExpression(templateCompilerIdentifier, [templateExpression]);
}
function getScope(scope) {
let names = [];
while (scope) {
for (let binding in scope.bindings) {
names.push(binding);
}
scope = scope.parent;
}
return names;
}
function shouldUseAutomaticScope(options) {
return options.useTemplateLiteralProposalSemantics || options.useTemplateTagProposalSemantics;
}
function shouldUseStrictMode(options) {
return (
Boolean(options.useTemplateLiteralProposalSemantics) ||
Boolean(options.useTemplateTagProposalSemantics)
);
}
function replacePath(path, state, compiled, options) {
if (options.useTemplateLiteralProposalSemantics) {
replaceTemplateLiteralProposal(t, path, state, compiled, options);
} else if (options.useTemplateTagProposalSemantics) {
replaceTemplateTagProposal(t, path, state, compiled, options);
} else {
registerRefs(path.replaceWith(compiled), (newPath) => {
// If we use `insertRuntimeErrors` then the node won't exist
return newPath.node ? [newPath.get('callee')] : [];
});
}
if (state.opts.ensureModuleApiPolyfill) {
processModuleApiPolyfill(state);
}
}
function processModuleApiPolyfill(state) {
for (let module in state.allAddedImports) {
let addedImports = state.allAddedImports[module];
for (let addedImport in addedImports) {
let { path } = addedImports[addedImport];
if (path && path.node) {
processImportDeclaration(t, path, state);
if (path.removed) {
delete addedImports[addedImport];
}
}
}
}
}
let precompile;
let visitor = {
Program(path, state) {
state.opts.ensureModuleApiPolyfill =
'ensureModuleApiPolyfill' in state.opts ? state.opts.ensureModuleApiPolyfill : true;
if (state.opts.templateCompilerPath) {
let templateCompiler = require(state.opts.templateCompilerPath);
precompile = templateCompiler.precompile;
} else {
precompile = state.opts.precompile;
}
if (state.opts.ensureModuleApiPolyfill) {
// Setup state for the module API polyfill
setupState(t, path, state);
}
let options = state.opts || {};
// Find/setup Ember global identifier
let useEmberModule = Boolean(options.useEmberModule);
let moduleOverrides = options.moduleOverrides;
state.allAddedImports = Object.create(null);
state.ensureImport = (exportName, moduleName) => {
let addedImports = (state.allAddedImports[moduleName] =
state.allAddedImports[moduleName] || {});
if (addedImports[exportName]) return t.identifier(addedImports[exportName].id.name);
if (moduleOverrides) {
let glimmerModule = moduleOverrides[moduleName];
let glimmerExport = glimmerModule && glimmerModule[exportName];
if (glimmerExport) {
exportName = glimmerExport[0];
moduleName = glimmerExport[1];
}
}
if (exportName === 'default' && moduleName === 'ember' && !useEmberModule) {
addedImports[exportName] = { id: t.identifier('Ember') };
return addedImports[exportName].id;
}
let importDeclarations = path.get('body').filter((n) => n.type === 'ImportDeclaration');
let preexistingImportDeclaration = importDeclarations.find(
(n) => n.get('source').get('value').node === moduleName
);
if (preexistingImportDeclaration) {
let importSpecifier = preexistingImportDeclaration.get('specifiers').find(({ node }) => {
return exportName === 'default'
? t.isImportDefaultSpecifier(node)
: node.imported && node.imported.name === exportName;
});
if (importSpecifier) {
addedImports[exportName] = { id: importSpecifier.node.local };
}
}
if (!addedImports[exportName]) {
let uid = path.scope.generateUidIdentifier(
exportName === 'default' ? moduleName : exportName
);
let newImportSpecifier =
exportName === 'default'
? t.importDefaultSpecifier(uid)
: t.importSpecifier(uid, t.identifier(exportName));
let newImport = t.importDeclaration([newImportSpecifier], t.stringLiteral(moduleName));
path.unshiftContainer('body', newImport);
path.scope.registerBinding('module', path.get('body.0.specifiers.0'));
addedImports[exportName] = {
id: uid,
path: path.get('body.0'),
};
}
return t.identifier(addedImports[exportName].id.name);
};
// Setup other module options and create cache for values
let modules = state.opts.modules || {
'htmlbars-inline-precompile': { export: 'default', shouldParseScope: false },
};
if (state.opts.modulePaths) {
let modulePaths = state.opts.modulePaths;
modulePaths.forEach((path) => (modules[path] = { export: 'default' }));
}
let presentModules = new Map();
let importDeclarations = path.get('body').filter((n) => n.type === 'ImportDeclaration');
for (let module in modules) {
let options = modules[module];
if (options.useTemplateTagProposalSemantics) {
if (options.useTemplateLiteralProposalSemantics) {
throw path.buildCodeFrameError(
'Cannot use both the template literal and template tag syntax proposals together'
);
}
// template tags don't have an import
presentModules.set(
options.export,
Object.assign({}, options, {
modulePath: module,
originalName: options.export,
})
);
continue;
}
let paths = importDeclarations.filter(
(path) => !path.removed && path.get('source').get('value').node === module
);
for (let path of paths) {
let options = modules[module];
if (typeof options === 'string') {
// Normalize 'moduleName': 'importSpecifier'
options = { export: options };
} else {
// else clone options so we don't mutate it
options = Object.assign({}, options);
}
let modulePathExport = options.export;
let importSpecifierPath = path
.get('specifiers')
.find(({ node }) =>
modulePathExport === 'default'
? t.isImportDefaultSpecifier(node)
: node.imported && node.imported.name === modulePathExport
);
if (importSpecifierPath) {
let localName = importSpecifierPath.node.local.name;
options.modulePath = module;
options.originalName = localName;
let localImportId = path.scope.generateUidIdentifierBasedOnNode(path.node.id);
path.scope.rename(localName, localImportId);
// If it was the only specifier, remove the whole import, else
// remove the specifier
if (path.node.specifiers.length === 1) {
path.remove();
} else {
importSpecifierPath.remove();
}
presentModules.set(localImportId, options);
}
}
}
state.presentModules = presentModules;
},
Class(path, state) {
// Processing classes this way allows us to process ClassProperty nodes
// before other transforms, such as the class-properties transform
path.get('body.body').forEach((path) => {
if (path.type !== 'ClassProperty') return;
let keyPath = path.get('key');
let valuePath = path.get('value');
if (keyPath && visitor[keyPath.type]) {
visitor[keyPath.type](keyPath, state);
}
if (valuePath && visitor[valuePath.type]) {
visitor[valuePath.type](valuePath, state);
}
});
},
TaggedTemplateExpression(path, state) {
let tagPath = path.get('tag');
let options = state.presentModules.get(tagPath.node.name);
if (!options) {
return;
}
if (options.disableTemplateLiteral) {
throw path.buildCodeFrameError(
`Attempted to use \`${options.originalName}\` as a template tag, but it can only be called as a function with a string passed to it: ${options.originalName}('content here')`
);
}
if (path.node.quasi.expressions.length) {
throw path.buildCodeFrameError(
'placeholders inside a tagged template string are not supported'
);
}
let template = path.node.quasi.quasis.map((quasi) => quasi.value.cooked).join('');
let { isProduction } = state.opts;
let locals = shouldUseAutomaticScope(options) ? getScope(path.scope) : null;
let strictMode = shouldUseStrictMode(options);
let emberIdentifier = state.ensureImport('createTemplateFactory', '@ember/template-factory');
replacePath(
path,
state,
compileTemplate(precompile, template, emberIdentifier, {
isProduction,
locals,
strictMode,
}),
options
);
},
CallExpression(path, state) {
let calleePath = path.get('callee');
let options = state.presentModules.get(calleePath.node.name);
if (!options) {
return;
}
if (options.disableFunctionCall) {
throw path.buildCodeFrameError(
`Attempted to use \`${options.originalName}\` as a function call, but it can only be used as a template tag: ${options.originalName}\`content here\``
);
}
let args = path.node.arguments;
let template;
switch (args[0] && args[0].type) {
case 'StringLiteral':
template = args[0].value;
break;
case 'TemplateLiteral':
if (args[0].expressions.length) {
throw path.buildCodeFrameError(
'placeholders inside a template string are not supported'
);
} else {
template = args[0].quasis.map((quasi) => quasi.value.cooked).join('');
}
break;
case 'TaggedTemplateExpression':
throw path.buildCodeFrameError(
`tagged template strings inside ${options.originalName} are not supported`
);
default:
throw path.buildCodeFrameError(
'hbs should be invoked with at least a single argument: the template string'
);
}
let compilerOptions;
switch (args.length) {
case 1:
compilerOptions = {};
break;
case 2: {
if (args[1].type !== 'ObjectExpression') {
throw path.buildCodeFrameError(
'hbs can only be invoked with 2 arguments: the template string, and any static options'
);
}
compilerOptions = parseObjectExpression(
state,
path.buildCodeFrameError.bind(path),
options.originalName,
args[1],
true
);
break;
}
default:
throw path.buildCodeFrameError(
'hbs can only be invoked with 2 arguments: the template string, and any static options'
);
}
let { isProduction } = state.opts;
// allow the user specified value to "win" over ours
if (!('isProduction' in compilerOptions)) {
compilerOptions.isProduction = isProduction;
}
if (shouldUseAutomaticScope(options)) {
// If using the transform semantics, then users are not expected to pass
// options, so we override any existing scope
compilerOptions.locals = getScope(path.scope);
}
if (shouldUseStrictMode(options)) {
// If using the transform semantics, then users are not expected to pass
// options, so we override any existing strict option
compilerOptions.strictMode = true;
}
replacePath(
path,
state,
compileTemplate(
precompile,
template,
state.ensureImport('createTemplateFactory', '@ember/template-factory'),
compilerOptions
),
options
);
},
};
return { visitor };
};
module.exports._parallelBabel = {
requireFile: __filename,
};
module.exports.baseDir = function () {
return __dirname;
};
module.exports.preprocessEmbeddedTemplates = require('./dist/preprocess-embedded-templates').default;