@embroider/macros 1.21.2 → 1.21.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/babel/app-ember-satisfies.d.ts +5 -0
- package/src/babel/app-ember-satisfies.js +38 -0
- package/src/babel/app-ember-satisfies.js.map +1 -0
- package/src/babel/dependency-satisfies.d.ts +5 -0
- package/src/babel/dependency-satisfies.js +38 -0
- package/src/babel/dependency-satisfies.js.map +1 -0
- package/src/babel/each.d.ts +14 -0
- package/src/babel/each.js +55 -0
- package/src/babel/each.js.map +1 -0
- package/src/babel/error.d.ts +3 -0
- package/src/babel/error.js +21 -0
- package/src/babel/error.js.map +1 -0
- package/src/babel/evaluate-json.d.ts +36 -0
- package/src/babel/evaluate-json.js +429 -0
- package/src/babel/evaluate-json.js.map +1 -0
- package/src/babel/fail-build.d.ts +5 -0
- package/src/babel/fail-build.js +36 -0
- package/src/babel/fail-build.js.map +1 -0
- package/src/babel/get-config.d.ts +9 -0
- package/src/babel/get-config.js +107 -0
- package/src/babel/get-config.js.map +1 -0
- package/src/babel/import-sync-pattern.d.ts +22 -0
- package/src/babel/import-sync-pattern.js +151 -0
- package/src/babel/import-sync-pattern.js.map +1 -0
- package/src/babel/macro-condition.d.ts +12 -0
- package/src/babel/macro-condition.js +76 -0
- package/src/babel/macro-condition.js.map +1 -0
- package/src/babel/macros-babel-plugin.d.ts +3 -0
- package/src/babel/macros-babel-plugin.js +312 -0
- package/src/babel/macros-babel-plugin.js.map +1 -0
- package/src/babel/module-exists.d.ts +5 -0
- package/src/babel/module-exists.js +30 -0
- package/src/babel/module-exists.js.map +1 -0
- package/src/babel/state.d.ts +34 -0
- package/src/babel/state.js +64 -0
- package/src/babel/state.js.map +1 -0
- package/src/babel.d.ts +47 -0
- package/src/babel.js +36 -0
- package/src/babel.js.map +1 -0
- package/src/ember-addon-main.d.ts +9 -0
- package/src/ember-addon-main.js +112 -0
- package/src/ember-addon-main.js.map +1 -0
- package/src/glimmer/app-ember-satisfies.d.ts +3 -0
- package/src/glimmer/app-ember-satisfies.js +32 -0
- package/src/glimmer/app-ember-satisfies.js.map +1 -0
- package/src/glimmer/ast-transform.d.ts +133 -0
- package/src/glimmer/ast-transform.js +240 -0
- package/src/glimmer/ast-transform.js.map +1 -0
- package/src/glimmer/dependency-satisfies.d.ts +3 -0
- package/src/glimmer/dependency-satisfies.js +37 -0
- package/src/glimmer/dependency-satisfies.js.map +1 -0
- package/src/glimmer/evaluate.d.ts +7 -0
- package/src/glimmer/evaluate.js +16 -0
- package/src/glimmer/evaluate.js.map +1 -0
- package/src/glimmer/fail-build.d.ts +2 -0
- package/src/glimmer/fail-build.js +22 -0
- package/src/glimmer/fail-build.js.map +1 -0
- package/src/glimmer/get-config.d.ts +5 -0
- package/src/glimmer/get-config.js +38 -0
- package/src/glimmer/get-config.js.map +1 -0
- package/src/glimmer/literal.d.ts +2 -0
- package/src/glimmer/literal.js +28 -0
- package/src/glimmer/literal.js.map +1 -0
- package/src/glimmer/macro-condition.d.ts +7 -0
- package/src/glimmer/macro-condition.js +119 -0
- package/src/glimmer/macro-condition.js.map +1 -0
- package/src/glimmer/macro-maybe-attrs.d.ts +2 -0
- package/src/glimmer/macro-maybe-attrs.js +31 -0
- package/src/glimmer/macro-maybe-attrs.js.map +1 -0
- package/src/index.d.ts +59 -0
- package/src/index.js +80 -0
- package/src/index.js.map +1 -0
- package/src/macros-config.d.ts +52 -0
- package/src/macros-config.js +394 -0
- package/src/macros-config.js.map +1 -0
- package/src/node.d.ts +5 -0
- package/src/node.js +21 -0
- package/src/node.js.map +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-config.js","sourceRoot":"","sources":["get-config.ts"],"names":[],"mappings":";;;;;AAmCA,4BAUC;AAKD,oCAyBC;AAiCD,kDAMC;AA/GD,oDAA4B;AAE5B,mDAAwE;AACxE,gEAAuC;AAMvC,SAAS,UAAU,CAAC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AAS,IAAI,UAAU,CAAC,sBAAsB,EAAE,EAAE,CAAC;YAC7D,OAAO,EAAE,IAAI,EAAE,MAAM,EAAG,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAqB,CAAC,KAAK,EAAE,CAAC;QAC/E,CAAC;QACD,IAAI,GAAG,UAAU,CAAC;IACpB,CAAC;AACH,CAAC;AAED,SAAgB,mBAAmB,CAAC,IAAqC,EAAE,KAAY,EAAE,OAAqB;IAC5G,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG;QAC3B,OAAO,CAAC,KAAK,CAAC,eAAe,CAC3B,IAAA,6BAAa,EAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,OAAO,CAAC,CAC9F;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport type State from './state';\nimport type { RewrittenPackageCache, Package } from '@embroider/shared-internals';\nimport error from './error';\nimport type { ConfidentResult } from './evaluate-json';\nimport { Evaluator, assertArray, buildLiterals } from './evaluate-json';\nimport assertNever from 'assert-never';\nimport type * as Babel from '@babel/core';\nimport type { types as t } from '@babel/core';\n\nexport type Mode = 'own' | 'getGlobalConfig' | 'package';\n\nfunction getPackage(path: NodePath<t.CallExpression>, state: State, mode: 'own' | 'package'): { root: string } | null {\n let packageName: string | undefined;\n if (mode === 'own') {\n if (path.node.arguments.length !== 0) {\n throw error(path, `getOwnConfig takes zero arguments, you passed ${path.node.arguments.length}`);\n }\n packageName = undefined;\n } else if (mode === 'package') {\n if (path.node.arguments.length !== 1) {\n throw error(path, `getConfig takes exactly one argument, you passed ${path.node.arguments.length}`);\n }\n let packageNode = path.node.arguments[0];\n if (packageNode.type !== 'StringLiteral') {\n throw error(assertArray(path.get('arguments'))[0], `the argument to getConfig must be a string literal`);\n }\n packageName = packageNode.value;\n } else {\n assertNever(mode);\n }\n return targetPackage(state.originalOwningPackage(), packageName, state.packageCache);\n}\n\n// this evaluates to the actual value of the config. It can be used directly by the Evaluator.\nexport default function getConfig(path: NodePath<t.CallExpression>, state: State, mode: Mode) {\n let config: unknown | undefined;\n if (mode === 'getGlobalConfig') {\n return state.opts.globalConfig;\n }\n let pkg = getPackage(path, state, mode);\n if (pkg) {\n config = state.opts.userConfigs[pkg.root];\n }\n return config;\n}\n\n// this is the imperative version that's invoked directly by the babel visitor\n// when we encounter getConfig. It's implemented in terms of getConfig so we can\n// be sure we have the same semantics.\nexport function insertConfig(path: NodePath<t.CallExpression>, state: State, mode: Mode, context: typeof Babel) {\n if (state.opts.mode === 'compile-time') {\n let config = getConfig(path, state, mode);\n let collapsed = collapse(path, config);\n let literalResult = buildLiterals(collapsed.config, context);\n collapsed.path.replaceWith(literalResult);\n } else {\n if (mode === 'getGlobalConfig') {\n let callee = path.get('callee');\n callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'getGlobalConfig'));\n } else {\n let pkg = getPackage(path, state, mode);\n let pkgRoot;\n if (pkg) {\n pkgRoot = context.types.stringLiteral(pkg.root);\n } else {\n pkgRoot = context.types.identifier('undefined');\n }\n path.replaceWith(\n context.types.callExpression(state.importUtil.import(path, state.pathToOurAddon('runtime'), 'config'), [\n pkgRoot,\n ])\n );\n }\n }\n}\n\nfunction targetPackage(\n us: Package,\n packageName: string | undefined,\n packageCache: RewrittenPackageCache\n): Package | null {\n if (!packageName) {\n return us;\n }\n try {\n let target = packageCache.resolve(packageName, us);\n return packageCache.original(target);\n } catch (err) {\n return null;\n }\n}\n\nfunction collapse(path: NodePath, config: unknown) {\n let evaluator = new Evaluator({\n knownPaths: new Map([[path, { confident: true, value: config, hasRuntimeImplementation: false }]]),\n });\n\n while (true) {\n let parentPath = path.parentPath!;\n let result = evaluator.evaluate(parentPath);\n if (!result.confident || parentPath.isAssignmentExpression()) {\n return { path, config: (evaluator.evaluate(path) as ConfidentResult).value };\n }\n path = parentPath;\n }\n}\n\nexport function inlineRuntimeConfig(path: NodePath<t.FunctionDeclaration>, state: State, context: typeof Babel) {\n path.get('body').node.body = [\n context.types.returnStatement(\n buildLiterals({ packages: state.opts.userConfigs, global: state.opts.globalConfig }, context)\n ),\n ];\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type * as Babel from '@babel/core';
|
|
2
|
+
import type { types as t } from '@babel/core';
|
|
3
|
+
type Types = typeof Babel.types;
|
|
4
|
+
export type PatternPart = {
|
|
5
|
+
type: 'static';
|
|
6
|
+
value: string;
|
|
7
|
+
} | {
|
|
8
|
+
type: 'dynamic';
|
|
9
|
+
value: t.Expression;
|
|
10
|
+
};
|
|
11
|
+
export interface ParsedSpecifier {
|
|
12
|
+
dir: string;
|
|
13
|
+
pattern: PatternPart[];
|
|
14
|
+
}
|
|
15
|
+
export declare function patternParts(types: Types, specifier: t.Node): PatternPart[] | undefined;
|
|
16
|
+
export declare function parseSpecifier(parts: PatternPart[]): ParsedSpecifier | undefined;
|
|
17
|
+
export declare function entryKey(entry: string): string;
|
|
18
|
+
export declare function patternMatcher(pattern: PatternPart[]): (key: string) => boolean;
|
|
19
|
+
export declare function lookupExpression(types: Types, pattern: PatternPart[]): t.Expression;
|
|
20
|
+
export declare function relativeSpecifier(path: string): string;
|
|
21
|
+
export {};
|
|
22
|
+
//# sourceMappingURL=import-sync-pattern.d.ts.map
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.patternParts = patternParts;
|
|
4
|
+
exports.parseSpecifier = parseSpecifier;
|
|
5
|
+
exports.entryKey = entryKey;
|
|
6
|
+
exports.patternMatcher = patternMatcher;
|
|
7
|
+
exports.lookupExpression = lookupExpression;
|
|
8
|
+
exports.relativeSpecifier = relativeSpecifier;
|
|
9
|
+
// Turns a specifier expression into a flat list of static and dynamic parts.
|
|
10
|
+
// Returns undefined if this isn't a shape we understand.
|
|
11
|
+
function patternParts(types, specifier) {
|
|
12
|
+
if (specifier.type === 'TemplateLiteral') {
|
|
13
|
+
let parts = [];
|
|
14
|
+
for (let [index, quasi] of specifier.quasis.entries()) {
|
|
15
|
+
parts.push({ type: 'static', value: quasi.value.cooked });
|
|
16
|
+
let expression = specifier.expressions[index];
|
|
17
|
+
if (expression) {
|
|
18
|
+
if (!types.isExpression(expression)) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
parts.push({ type: 'dynamic', value: expression });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return normalize(parts);
|
|
25
|
+
}
|
|
26
|
+
// babel might transform the template form `../my-path/${id}` into
|
|
27
|
+
// '../my-path/'.concat(id)
|
|
28
|
+
if (specifier.type === 'CallExpression' &&
|
|
29
|
+
specifier.callee.type === 'MemberExpression' &&
|
|
30
|
+
specifier.callee.property.type === 'Identifier' &&
|
|
31
|
+
specifier.callee.property.name === 'concat' &&
|
|
32
|
+
specifier.callee.object.type === 'StringLiteral') {
|
|
33
|
+
let parts = [{ type: 'static', value: specifier.callee.object.value }];
|
|
34
|
+
for (let arg of specifier.arguments) {
|
|
35
|
+
if (arg.type === 'StringLiteral') {
|
|
36
|
+
parts.push({ type: 'static', value: arg.value });
|
|
37
|
+
}
|
|
38
|
+
else if (types.isExpression(arg)) {
|
|
39
|
+
parts.push({ type: 'dynamic', value: arg });
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return normalize(parts);
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
// merges adjacent static parts and drops empty ones, so that the rest of the
|
|
50
|
+
// code can assume statics are maximal and non-empty
|
|
51
|
+
function normalize(parts) {
|
|
52
|
+
let output = [];
|
|
53
|
+
for (let part of parts) {
|
|
54
|
+
if (part.type === 'static') {
|
|
55
|
+
if (part.value === '') {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
let previous = output[output.length - 1];
|
|
59
|
+
if ((previous === null || previous === void 0 ? void 0 : previous.type) === 'static') {
|
|
60
|
+
output[output.length - 1] = { type: 'static', value: previous.value + part.value };
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
output.push(part);
|
|
65
|
+
}
|
|
66
|
+
return output;
|
|
67
|
+
}
|
|
68
|
+
// Splits the parts into the directory we're going to read and the pattern that
|
|
69
|
+
// entries in it need to match. Returns undefined when the parts don't describe
|
|
70
|
+
// a relative path with a statically-known directory.
|
|
71
|
+
function parseSpecifier(parts) {
|
|
72
|
+
let first = parts[0];
|
|
73
|
+
if ((first === null || first === void 0 ? void 0 : first.type) !== 'static' || !first.value.startsWith('.')) {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
let slash = first.value.lastIndexOf('/');
|
|
77
|
+
if (slash === -1) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
let dir = first.value.slice(0, slash + 1);
|
|
81
|
+
let head = first.value.slice(slash + 1);
|
|
82
|
+
let pattern = normalize([{ type: 'static', value: head }, ...parts.slice(1)]);
|
|
83
|
+
// The directory we read is only one level deep, so a "/" anywhere later in
|
|
84
|
+
// the pattern could never match one of its entries.
|
|
85
|
+
if (pattern.some(part => part.type === 'static' && part.value.includes('/'))) {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
return { dir, pattern: withoutExtension(pattern) };
|
|
89
|
+
}
|
|
90
|
+
// The lookup table is keyed by extension-less filenames, because that's what we
|
|
91
|
+
// hand to the resolver. So if the author wrote the extension (which is what
|
|
92
|
+
// Vite's own dynamic import rules ask for) we drop it from the pattern too.
|
|
93
|
+
function withoutExtension(pattern) {
|
|
94
|
+
let last = pattern[pattern.length - 1];
|
|
95
|
+
if ((last === null || last === void 0 ? void 0 : last.type) !== 'static') {
|
|
96
|
+
return pattern;
|
|
97
|
+
}
|
|
98
|
+
let stripped = last.value.replace(/\.\w+$/, '');
|
|
99
|
+
if (stripped === last.value) {
|
|
100
|
+
return pattern;
|
|
101
|
+
}
|
|
102
|
+
return normalize([...pattern.slice(0, -1), { type: 'static', value: stripped }]);
|
|
103
|
+
}
|
|
104
|
+
// The key we use for a directory entry: its name minus the file extension.
|
|
105
|
+
function entryKey(entry) {
|
|
106
|
+
let dot = entry.lastIndexOf('.');
|
|
107
|
+
return dot === -1 ? entry : entry.slice(0, dot);
|
|
108
|
+
}
|
|
109
|
+
// Which keys could this pattern actually select? Everything else in the
|
|
110
|
+
// directory would be dead weight in the bundle.
|
|
111
|
+
function patternMatcher(pattern) {
|
|
112
|
+
let source = '^' + pattern.map(part => (part.type === 'static' ? escapeRegExp(part.value) : '[\\s\\S]*')).join('') + '$';
|
|
113
|
+
let regex = new RegExp(source);
|
|
114
|
+
return key => regex.test(key);
|
|
115
|
+
}
|
|
116
|
+
function escapeRegExp(str) {
|
|
117
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
118
|
+
}
|
|
119
|
+
// Builds the expression we use to index into the lookup table. When the pattern
|
|
120
|
+
// is a single interpolation (the only shape that used to work) this is just that
|
|
121
|
+
// expression, so existing call sites compile to byte-identical output.
|
|
122
|
+
function lookupExpression(types, pattern) {
|
|
123
|
+
if (pattern.length === 1 && pattern[0].type === 'dynamic') {
|
|
124
|
+
return pattern[0].value;
|
|
125
|
+
}
|
|
126
|
+
let quasis = [];
|
|
127
|
+
let expressions = [];
|
|
128
|
+
let pending = '';
|
|
129
|
+
for (let part of pattern) {
|
|
130
|
+
if (part.type === 'static') {
|
|
131
|
+
pending += part.value;
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }));
|
|
135
|
+
pending = '';
|
|
136
|
+
expressions.push(part.value);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }, true));
|
|
140
|
+
return types.templateLiteral(quasis, expressions);
|
|
141
|
+
}
|
|
142
|
+
function escapeTemplate(str) {
|
|
143
|
+
return str.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
|
|
144
|
+
}
|
|
145
|
+
// path.join() will strip a leading "./", which would turn our relative path
|
|
146
|
+
// into a bare package specifier.
|
|
147
|
+
function relativeSpecifier(path) {
|
|
148
|
+
let normalized = path.replace(/\\/g, '/');
|
|
149
|
+
return normalized.startsWith('.') ? normalized : './' + normalized;
|
|
150
|
+
}
|
|
151
|
+
//# sourceMappingURL=import-sync-pattern.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"import-sync-pattern.js","sourceRoot":"","sources":["import-sync-pattern.ts"],"names":[],"mappings":";;AA8BA,oCAuCC;AAyBD,wCAoBC;AAkBD,4BAGC;AAID,wCAKC;AASD,4CAkBC;AAQD,8CAGC;AA1JD,6EAA6E;AAC7E,yDAAyD;AACzD,SAAgB,YAAY,CAAC,KAAY,EAAE,SAAiB;IAC1D,IAAI,SAAS,CAAC,IAAI,KAAK,iBAAiB,EAAE,CAAC;QACzC,IAAI,KAAK,GAAkB,EAAE,CAAC;QAC9B,KAAK,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;YACtD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,MAAO,EAAE,CAAC,CAAC;YAC3D,IAAI,UAAU,GAAG,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YAC9C,IAAI,UAAU,EAAE,CAAC;gBACf,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE,CAAC;oBACpC,OAAO,SAAS,CAAC;gBACnB,CAAC;gBACD,KAAK,CAAC,IAAI,CAAC,EAAE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AI,IAAI,IAAI,OAAO,EAAE,CAAC;QACzB,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3B,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC;QACxB,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE,GAAG,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YACtF,OAAO,GAAG,EAAE,CAAC;YACb,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IACD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE,GAAG,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC;IAC5F,OAAO,KAAK,CAAC,eAAe,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,cAAc,CAAC,GAAW;IACjC,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAClF,CAAC;AAED,4EAA4E;AAC5E,iCAAiC;AACjC,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAI,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAC1C,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,GAAG,UAAU,CAAC;AACrE,CAAC","sourcesContent":["import type * as Babel from '@babel/core';\nimport type { types as t } from '@babel/core';\n\ntype Types = typeof Babel.types;\n\n/*\n Support for `importSync` with a dynamic path, like:\n\n importSync(`../components/results/${type}-result`)\n\n In eager mode we can't do a truly dynamic import, so we expand the call into a\n lookup table over the real contents of the directory. To do that correctly we\n need to understand the *whole* pattern, not just the part before the first\n interpolation.\n*/\n\nexport type PatternPart = { type: 'static'; value: string } | { type: 'dynamic'; value: t.Expression };\n\n// A parsed `importSync` specifier: the statically-known directory that we will\n// read, plus the pattern that filenames within it must match.\nexport interface ParsedSpecifier {\n // always ends in \"/\", always starts with \".\" (we only support relative paths)\n dir: string;\n // the filename pattern, with the file extension (if any) already removed, so\n // it lines up with the extension-less keys we put in the lookup table\n pattern: PatternPart[];\n}\n\n// Turns a specifier expression into a flat list of static and dynamic parts.\n// Returns undefined if this isn't a shape we understand.\nexport function patternParts(types: Types, specifier: t.Node): PatternPart[] | undefined {\n if (specifier.type === 'TemplateLiteral') {\n let parts: PatternPart[] = [];\n for (let [index, quasi] of specifier.quasis.entries()) {\n parts.push({ type: 'static', value: quasi.value.cooked! });\n let expression = specifier.expressions[index];\n if (expression) {\n if (!types.isExpression(expression)) {\n return undefined;\n }\n parts.push({ type: 'dynamic', value: expression });\n }\n }\n return normalize(parts);\n }\n\n // babel might transform the template form `../my-path/${id}` into\n // '../my-path/'.concat(id)\n if (\n specifier.type === 'CallExpression' &&\n specifier.callee.type === 'MemberExpression' &&\n specifier.callee.property.type === 'Identifier' &&\n specifier.callee.property.name === 'concat' &&\n specifier.callee.object.type === 'StringLiteral'\n ) {\n let parts: PatternPart[] = [{ type: 'static', value: specifier.callee.object.value }];\n for (let arg of specifier.arguments) {\n if (arg.type === 'StringLiteral') {\n parts.push({ type: 'static', value: arg.value });\n } else if (types.isExpression(arg)) {\n parts.push({ type: 'dynamic', value: arg });\n } else {\n return undefined;\n }\n }\n return normalize(parts);\n }\n\n return undefined;\n}\n\n// merges adjacent static parts and drops empty ones, so that the rest of the\n// code can assume statics are maximal and non-empty\nfunction normalize(parts: PatternPart[]): PatternPart[] {\n let output: PatternPart[] = [];\n for (let part of parts) {\n if (part.type === 'static') {\n if (part.value === '') {\n continue;\n }\n let previous = output[output.length - 1];\n if (previous?.type === 'static') {\n output[output.length - 1] = { type: 'static', value: previous.value + part.value };\n continue;\n }\n }\n output.push(part);\n }\n return output;\n}\n\n// Splits the parts into the directory we're going to read and the pattern that\n// entries in it need to match. Returns undefined when the parts don't describe\n// a relative path with a statically-known directory.\nexport function parseSpecifier(parts: PatternPart[]): ParsedSpecifier | undefined {\n let first = parts[0];\n if (first?.type !== 'static' || !first.value.startsWith('.')) {\n return undefined;\n }\n let slash = first.value.lastIndexOf('/');\n if (slash === -1) {\n return undefined;\n }\n let dir = first.value.slice(0, slash + 1);\n let head = first.value.slice(slash + 1);\n let pattern = normalize([{ type: 'static', value: head }, ...parts.slice(1)]);\n\n // The directory we read is only one level deep, so a \"/\" anywhere later in\n // the pattern could never match one of its entries.\n if (pattern.some(part => part.type === 'static' && part.value.includes('/'))) {\n return undefined;\n }\n\n return { dir, pattern: withoutExtension(pattern) };\n}\n\n// The lookup table is keyed by extension-less filenames, because that's what we\n// hand to the resolver. So if the author wrote the extension (which is what\n// Vite's own dynamic import rules ask for) we drop it from the pattern too.\nfunction withoutExtension(pattern: PatternPart[]): PatternPart[] {\n let last = pattern[pattern.length - 1];\n if (last?.type !== 'static') {\n return pattern;\n }\n let stripped = last.value.replace(/\\.\\w+$/, '');\n if (stripped === last.value) {\n return pattern;\n }\n return normalize([...pattern.slice(0, -1), { type: 'static', value: stripped }]);\n}\n\n// The key we use for a directory entry: its name minus the file extension.\nexport function entryKey(entry: string): string {\n let dot = entry.lastIndexOf('.');\n return dot === -1 ? entry : entry.slice(0, dot);\n}\n\n// Which keys could this pattern actually select? Everything else in the\n// directory would be dead weight in the bundle.\nexport function patternMatcher(pattern: PatternPart[]): (key: string) => boolean {\n let source =\n '^' + pattern.map(part => (part.type === 'static' ? escapeRegExp(part.value) : '[\\\\s\\\\S]*')).join('') + '$';\n let regex = new RegExp(source);\n return key => regex.test(key);\n}\n\nfunction escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n// Builds the expression we use to index into the lookup table. When the pattern\n// is a single interpolation (the only shape that used to work) this is just that\n// expression, so existing call sites compile to byte-identical output.\nexport function lookupExpression(types: Types, pattern: PatternPart[]): t.Expression {\n if (pattern.length === 1 && pattern[0].type === 'dynamic') {\n return pattern[0].value;\n }\n let quasis: t.TemplateElement[] = [];\n let expressions: t.Expression[] = [];\n let pending = '';\n for (let part of pattern) {\n if (part.type === 'static') {\n pending += part.value;\n } else {\n quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }));\n pending = '';\n expressions.push(part.value);\n }\n }\n quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }, true));\n return types.templateLiteral(quasis, expressions);\n}\n\nfunction escapeTemplate(str: string): string {\n return str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${');\n}\n\n// path.join() will strip a leading \"./\", which would turn our relative path\n// into a bare package specifier.\nexport function relativeSpecifier(path: string): string {\n let normalized = path.replace(/\\\\/g, '/');\n return normalized.startsWith('.') ? normalized : './' + normalized;\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { NodePath } from '@babel/traverse';
|
|
2
|
+
import type { types as t } from '@babel/core';
|
|
3
|
+
import type * as Babel from '@babel/core';
|
|
4
|
+
import type State from './state';
|
|
5
|
+
export interface MacroCondition {
|
|
6
|
+
parity: boolean;
|
|
7
|
+
conditional: NodePath<t.IfStatement | t.ConditionalExpression | t.LogicalExpression>;
|
|
8
|
+
callExpression: NodePath<t.CallExpression>;
|
|
9
|
+
}
|
|
10
|
+
export declare function identifyMacroConditionPath(path: NodePath<t.IfStatement | t.ConditionalExpression | t.LogicalExpression>): MacroCondition | false;
|
|
11
|
+
export default function macroCondition(macro: MacroCondition, state: State, context: typeof Babel): void;
|
|
12
|
+
//# sourceMappingURL=macro-condition.d.ts.map
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.identifyMacroConditionPath = identifyMacroConditionPath;
|
|
7
|
+
exports.default = macroCondition;
|
|
8
|
+
const evaluate_json_1 = require("./evaluate-json");
|
|
9
|
+
const error_1 = __importDefault(require("./error"));
|
|
10
|
+
function identifyMacroConditionPath(path) {
|
|
11
|
+
let parity = true;
|
|
12
|
+
let test;
|
|
13
|
+
if (path.isLogicalExpression()) {
|
|
14
|
+
if (path.node.operator !== '&&' && path.node.operator !== '||') {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
test = path.get('left');
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
test = path.get('test');
|
|
21
|
+
}
|
|
22
|
+
if (test.isUnaryExpression() && test.node.operator === '!') {
|
|
23
|
+
parity = false;
|
|
24
|
+
test = test.get('argument');
|
|
25
|
+
}
|
|
26
|
+
if (test.isCallExpression()) {
|
|
27
|
+
let callee = test.get('callee');
|
|
28
|
+
if (callee.referencesImport('@embroider/macros', 'macroCondition')) {
|
|
29
|
+
return { parity, conditional: path, callExpression: test };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
function macroCondition(macro, state, context) {
|
|
35
|
+
let args = macro.callExpression.get('arguments');
|
|
36
|
+
if (args.length !== 1) {
|
|
37
|
+
throw (0, error_1.default)(macro.conditional, `macroCondition accepts exactly one argument, you passed ${args.length}`);
|
|
38
|
+
}
|
|
39
|
+
let [predicatePath] = args;
|
|
40
|
+
let predicate = new evaluate_json_1.Evaluator({ state }).evaluate(predicatePath);
|
|
41
|
+
if (!predicate.confident) {
|
|
42
|
+
throw (0, error_1.default)(args[0], `the first argument to macroCondition must be statically known`);
|
|
43
|
+
}
|
|
44
|
+
if (state.opts.mode === 'run-time' && predicate.hasRuntimeImplementation !== false) {
|
|
45
|
+
let callee = macro.callExpression.get('callee');
|
|
46
|
+
callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'macroCondition'));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (macro.conditional.isLogicalExpression()) {
|
|
50
|
+
let effectivePredicate = predicate.value === macro.parity;
|
|
51
|
+
let right = macro.conditional.get('right');
|
|
52
|
+
let keptRight = (macro.conditional.node.operator === '&&') === effectivePredicate;
|
|
53
|
+
if (keptRight) {
|
|
54
|
+
macro.conditional.replaceWith(right.node);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
state.removed.add(right.node);
|
|
58
|
+
macro.conditional.replaceWith(context.types.booleanLiteral(effectivePredicate));
|
|
59
|
+
}
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
let conditional = macro.conditional;
|
|
63
|
+
let consequent = conditional.get('consequent');
|
|
64
|
+
let alternate = conditional.get('alternate');
|
|
65
|
+
let [kept, removed] = predicate.value === macro.parity ? [consequent.node, alternate.node] : [alternate.node, consequent.node];
|
|
66
|
+
if (kept) {
|
|
67
|
+
conditional.replaceWith(kept);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
conditional.remove();
|
|
71
|
+
}
|
|
72
|
+
if (removed) {
|
|
73
|
+
state.removed.add(removed);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=macro-condition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"macro-condition.js","sourceRoot":"","sources":["macro-condition.ts"],"names":[],"mappings":";;;;;AAaA,gEA2BC;AAED,iCA6CC;AAtFD,mDAA4C;AAG5C,oDAA4B;AAS5B,SAAgB,0BAA0B,CACxC,IAA6E;IAE7E,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,IAAI,IAAsB,CAAC;IAE3B,IAAI,IAAI,CAAC,mBAAmB,E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D,OAAO;IACT,CAAC;IAED,IAAI,WAAW,GAAG,KAAK,CAAC,WAAgE,CAAC;IACzF,IAAI,UAAU,GAAG,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IAC/C,IAAI,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAE7C,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,GACjB,SAAS,CAAC,KAAK,KAAK,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;IAC3G,IAAI,IAAI,EAAE,CAAC;QACT,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,WAAW,CAAC,MAAM,EAAE,CAAC;IACvB,CAAC;IACD,IAAI,OAAO,EAAE,CAAC;QACZ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport { Evaluator } from './evaluate-json';\nimport type { types as t } from '@babel/core';\nimport type * as Babel from '@babel/core';\nimport error from './error';\nimport type State from './state';\n\nexport interface MacroCondition {\n parity: boolean;\n conditional: NodePath<t.IfStatement | t.ConditionalExpression | t.LogicalExpression>;\n callExpression: NodePath<t.CallExpression>;\n}\n\nexport function identifyMacroConditionPath(\n path: NodePath<t.IfStatement | t.ConditionalExpression | t.LogicalExpression>\n): MacroCondition | false {\n let parity = true;\n let test: NodePath<t.Node>;\n\n if (path.isLogicalExpression()) {\n if (path.node.operator !== '&&' && path.node.operator !== '||') {\n return false;\n }\n test = path.get('left');\n } else {\n test = (path as NodePath<t.IfStatement | t.ConditionalExpression>).get('test');\n }\n\n if (test.isUnaryExpression() && test.node.operator === '!') {\n parity = false;\n test = test.get('argument');\n }\n\n if (test.isCallExpression()) {\n let callee = test.get('callee');\n if (callee.referencesImport('@embroider/macros', 'macroCondition')) {\n return { parity, conditional: path, callExpression: test };\n }\n }\n return false;\n}\n\nexport default function macroCondition(macro: MacroCondition, state: State, context: typeof Babel) {\n let args = macro.callExpression.get('arguments');\n if (args.length !== 1) {\n throw error(macro.conditional, `macroCondition accepts exactly one argument, you passed ${args.length}`);\n }\n\n let [predicatePath] = args;\n let predicate = new Evaluator({ state }).evaluate(predicatePath);\n if (!predicate.confident) {\n throw error(args[0], `the first argument to macroCondition must be statically known`);\n }\n\n if (state.opts.mode === 'run-time' && predicate.hasRuntimeImplementation !== false) {\n let callee = macro.callExpression.get('callee');\n callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'macroCondition'));\n return;\n }\n\n if (macro.conditional.isLogicalExpression()) {\n let effectivePredicate = predicate.value === macro.parity;\n let right = macro.conditional.get('right');\n let keptRight = (macro.conditional.node.operator === '&&') === effectivePredicate;\n if (keptRight) {\n macro.conditional.replaceWith(right.node);\n } else {\n state.removed.add(right.node);\n macro.conditional.replaceWith(context.types.booleanLiteral(effectivePredicate));\n }\n return;\n }\n\n let conditional = macro.conditional as NodePath<t.IfStatement | t.ConditionalExpression>;\n let consequent = conditional.get('consequent');\n let alternate = conditional.get('alternate');\n\n let [kept, removed] =\n predicate.value === macro.parity ? [consequent.node, alternate.node] : [alternate.node, consequent.node];\n if (kept) {\n conditional.replaceWith(kept);\n } else {\n conditional.remove();\n }\n if (removed) {\n state.removed.add(removed);\n }\n}\n"]}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.default = main;
|
|
40
|
+
const state_1 = require("./state");
|
|
41
|
+
const get_config_1 = require("./get-config");
|
|
42
|
+
const macro_condition_1 = __importStar(require("./macro-condition"));
|
|
43
|
+
const each_1 = require("./each");
|
|
44
|
+
const error_1 = __importDefault(require("./error"));
|
|
45
|
+
const fail_build_1 = __importDefault(require("./fail-build"));
|
|
46
|
+
const evaluate_json_1 = require("./evaluate-json");
|
|
47
|
+
const fs_1 = require("fs");
|
|
48
|
+
const import_sync_pattern_1 = require("./import-sync-pattern");
|
|
49
|
+
const path_1 = require("path");
|
|
50
|
+
function main(context) {
|
|
51
|
+
let t = context.types;
|
|
52
|
+
let visitor = {
|
|
53
|
+
Program: {
|
|
54
|
+
enter(path, state) {
|
|
55
|
+
(0, state_1.initState)(context, path, state);
|
|
56
|
+
},
|
|
57
|
+
exit(_, state) {
|
|
58
|
+
// @embroider/macros itself has no runtime behaviors and should always be removed
|
|
59
|
+
state.importUtil.removeAllImports('@embroider/macros');
|
|
60
|
+
for (let handler of state.jobs) {
|
|
61
|
+
handler();
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
'IfStatement|ConditionalExpression|LogicalExpression': {
|
|
66
|
+
enter(path, state) {
|
|
67
|
+
let found = (0, macro_condition_1.identifyMacroConditionPath)(path);
|
|
68
|
+
if (found) {
|
|
69
|
+
state.calledIdentifiers.add(found.callExpression.get('callee').node);
|
|
70
|
+
(0, macro_condition_1.default)(found, state, context);
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
ForOfStatement: {
|
|
75
|
+
enter(path, state) {
|
|
76
|
+
if ((0, each_1.isEachPath)(path)) {
|
|
77
|
+
state.calledIdentifiers.add(path.get('right').get('callee').node);
|
|
78
|
+
(0, each_1.insertEach)(path, state, context);
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
FunctionDeclaration: {
|
|
83
|
+
enter(path, state) {
|
|
84
|
+
let id = path.get('id');
|
|
85
|
+
if (id.isIdentifier() && id.node.name === 'initializeRuntimeMacrosConfig' && state.opts.mode === 'run-time') {
|
|
86
|
+
let pkg = state.owningPackage();
|
|
87
|
+
if (pkg && pkg.name === '@embroider/macros') {
|
|
88
|
+
(0, get_config_1.inlineRuntimeConfig)(path, state, context);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
CallExpression: {
|
|
94
|
+
enter(path, state) {
|
|
95
|
+
let callee = path.get('callee');
|
|
96
|
+
if (!callee.isIdentifier()) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
// failBuild is implemented for side-effect, not value, so it's not
|
|
100
|
+
// handled by evaluateMacroCall.
|
|
101
|
+
if (callee.referencesImport('@embroider/macros', 'failBuild')) {
|
|
102
|
+
state.calledIdentifiers.add(callee.node);
|
|
103
|
+
(0, fail_build_1.default)(path, state);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (callee.referencesImport('@embroider/macros', 'importSync')) {
|
|
107
|
+
// we handle importSync in the exit hook
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
// getOwnConfig/getGlobalConfig/getConfig needs special handling, so
|
|
111
|
+
// even though it also emits values via evaluateMacroCall when they're
|
|
112
|
+
// needed recursively by other macros, it has its own insertion-handling
|
|
113
|
+
// code that we invoke here.
|
|
114
|
+
//
|
|
115
|
+
// The things that are special include:
|
|
116
|
+
// - automatic collapsing of chained properties, etc
|
|
117
|
+
// - these macros have runtime implementations sometimes, which changes
|
|
118
|
+
// how we rewrite them
|
|
119
|
+
let mode = callee.referencesImport('@embroider/macros', 'getOwnConfig')
|
|
120
|
+
? 'own'
|
|
121
|
+
: callee.referencesImport('@embroider/macros', 'getGlobalConfig')
|
|
122
|
+
? 'getGlobalConfig'
|
|
123
|
+
: callee.referencesImport('@embroider/macros', 'getConfig')
|
|
124
|
+
? 'package'
|
|
125
|
+
: false;
|
|
126
|
+
if (mode) {
|
|
127
|
+
state.calledIdentifiers.add(callee.node);
|
|
128
|
+
(0, get_config_1.insertConfig)(path, state, mode, context);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
// isTesting can have a runtime implementation. At compile time it
|
|
132
|
+
// instead falls through to evaluateMacroCall.
|
|
133
|
+
if (callee.referencesImport('@embroider/macros', 'isTesting') && state.opts.mode === 'run-time') {
|
|
134
|
+
state.calledIdentifiers.add(callee.node);
|
|
135
|
+
callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'isTesting'));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (callee.referencesImport('@embroider/macros', 'setTesting')) {
|
|
139
|
+
state.calledIdentifiers.add(callee.node);
|
|
140
|
+
if (state.opts.mode === 'run-time') {
|
|
141
|
+
callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'setTesting'));
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
let args = path.get('arguments');
|
|
145
|
+
if (args.length === 0) {
|
|
146
|
+
throw (0, error_1.default)(path, `setTesting() requires a boolean argument`);
|
|
147
|
+
}
|
|
148
|
+
let arg = args[0];
|
|
149
|
+
let evaluator = new evaluate_json_1.Evaluator({ state });
|
|
150
|
+
let result = evaluator.evaluate(arg);
|
|
151
|
+
if (!result.confident) {
|
|
152
|
+
throw (0, error_1.default)(arg, `setTesting() can only be called with a statically analyzable value in compile-time mode. The argument must be a literal boolean or other macro that can resolves to a boolean at compile-time.`);
|
|
153
|
+
}
|
|
154
|
+
let macrosConfig = state.opts.globalConfig['@embroider/macros'] || {};
|
|
155
|
+
let currentIsTesting = Boolean(macrosConfig.isTesting);
|
|
156
|
+
let newIsTesting = Boolean(result.value);
|
|
157
|
+
if (currentIsTesting !== newIsTesting) {
|
|
158
|
+
throw (0, error_1.default)(path, `setTesting(${newIsTesting}) cannot change the testing state in compile-time mode. The current global config has isTesting=${currentIsTesting}. ` +
|
|
159
|
+
`setTesting() calls are compiled away at build time, so they cannot change the testing state. ` +
|
|
160
|
+
`If you need to change the testing state at runtime, use runtime mode instead.`);
|
|
161
|
+
}
|
|
162
|
+
path.remove();
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
let result = new evaluate_json_1.Evaluator({ state }).evaluateMacroCall(path);
|
|
167
|
+
if (result.confident) {
|
|
168
|
+
state.calledIdentifiers.add(callee.node);
|
|
169
|
+
path.replaceWith((0, evaluate_json_1.buildLiterals)(result.value, context));
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
exit(path, state) {
|
|
173
|
+
let callee = path.get('callee');
|
|
174
|
+
if (!callee.isIdentifier()) {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
// importSync doesn't evaluate to a static value, so it's implemented
|
|
178
|
+
// directly here, not in evaluateMacroCall.
|
|
179
|
+
// We intentionally do this on exit here, to allow other transforms to handle importSync before we do
|
|
180
|
+
// For example ember-auto-import needs to do some custom transforms to enable use of dynamic template strings,
|
|
181
|
+
// so its babel plugin needs to see and handle the importSync call first!
|
|
182
|
+
if (callee.referencesImport('@embroider/macros', 'importSync')) {
|
|
183
|
+
if (state.opts.importSyncImplementation === 'eager') {
|
|
184
|
+
let specifier = path.node.arguments[0];
|
|
185
|
+
let target;
|
|
186
|
+
if ((specifier === null || specifier === void 0 ? void 0 : specifier.type) === 'StringLiteral') {
|
|
187
|
+
target = specifier.value;
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
let parts = specifier ? (0, import_sync_pattern_1.patternParts)(t, specifier) : undefined;
|
|
191
|
+
if (parts && parts.length > 0 && parts.every(part => part.type === 'static')) {
|
|
192
|
+
// a template literal that has no interpolations at all is just
|
|
193
|
+
// a string, so treat it like one
|
|
194
|
+
target = parts.map(part => (part.type === 'static' ? part.value : '')).join('');
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
let parsed = parts ? (0, import_sync_pattern_1.parseSpecifier)(parts) : undefined;
|
|
198
|
+
if (!parsed) {
|
|
199
|
+
throw new Error(`importSync eager mode only supports dynamic paths which are relative, must start with a '.', had ${specifier === null || specifier === void 0 ? void 0 : specifier.type}`);
|
|
200
|
+
}
|
|
201
|
+
const { dir, pattern } = parsed;
|
|
202
|
+
const resolvedPath = (0, path_1.resolve)((0, path_1.dirname)(state.filename), dir);
|
|
203
|
+
let entries = [];
|
|
204
|
+
if ((0, fs_1.existsSync)(resolvedPath)) {
|
|
205
|
+
entries = (0, fs_1.readdirSync)(resolvedPath).filter(e => !e.startsWith('.'));
|
|
206
|
+
}
|
|
207
|
+
const matches = (0, import_sync_pattern_1.patternMatcher)(pattern);
|
|
208
|
+
const seen = new Set();
|
|
209
|
+
const properties = [];
|
|
210
|
+
for (const entry of entries) {
|
|
211
|
+
const key = (0, import_sync_pattern_1.entryKey)(entry);
|
|
212
|
+
// entries that the pattern could never select would just bloat
|
|
213
|
+
// the bundle, and files that differ only by extension collapse
|
|
214
|
+
// to the same key (and the same extension-less import)
|
|
215
|
+
if (!matches(key) || seen.has(key)) {
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
seen.add(key);
|
|
219
|
+
const id = t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [state.importUtil.import(path, (0, import_sync_pattern_1.relativeSpecifier)((0, path_1.join)(dir, key)), '*')]);
|
|
220
|
+
properties.push(t.objectProperty(t.stringLiteral(key), id));
|
|
221
|
+
}
|
|
222
|
+
const memberExpr = t.memberExpression(t.objectExpression(properties), (0, import_sync_pattern_1.lookupExpression)(t, pattern), true);
|
|
223
|
+
path.replaceWith(memberExpr);
|
|
224
|
+
state.calledIdentifiers.add(callee.node);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
path.replaceWith(t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [
|
|
229
|
+
state.importUtil.import(path, target, '*'),
|
|
230
|
+
]));
|
|
231
|
+
state.calledIdentifiers.add(callee.node);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
if (path.scope.hasBinding('require')) {
|
|
236
|
+
path.scope.rename('require');
|
|
237
|
+
}
|
|
238
|
+
let r = t.identifier('require');
|
|
239
|
+
state.generatedRequires.add(r);
|
|
240
|
+
path.replaceWith(t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [
|
|
241
|
+
t.callExpression(r, path.node.arguments),
|
|
242
|
+
]));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
},
|
|
247
|
+
ReferencedIdentifier(path, state) {
|
|
248
|
+
for (let candidate of [
|
|
249
|
+
'dependencySatisfies',
|
|
250
|
+
'appEmberSatisfies',
|
|
251
|
+
'moduleExists',
|
|
252
|
+
'getConfig',
|
|
253
|
+
'getOwnConfig',
|
|
254
|
+
'failBuild',
|
|
255
|
+
// we cannot check importSync, as the babel transform runs on exit, so *after* this check
|
|
256
|
+
// 'importSync',
|
|
257
|
+
'isDevelopingApp',
|
|
258
|
+
'isDevelopingThisPackage',
|
|
259
|
+
'isTesting',
|
|
260
|
+
'setTesting',
|
|
261
|
+
]) {
|
|
262
|
+
if (path.referencesImport('@embroider/macros', candidate) && !state.calledIdentifiers.has(path.node)) {
|
|
263
|
+
throw (0, error_1.default)(path, `You can only use ${candidate} as a function call`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (path.referencesImport('@embroider/macros', 'macroCondition') && !state.calledIdentifiers.has(path.node)) {
|
|
267
|
+
throw (0, error_1.default)(path, `macroCondition can only be used as the predicate of an if statement, ternary expression, or && / || logical expression`);
|
|
268
|
+
}
|
|
269
|
+
if (path.referencesImport('@embroider/macros', 'each') && !state.calledIdentifiers.has(path.node)) {
|
|
270
|
+
throw (0, error_1.default)(path, `the each() macro can only be used within a for ... of statement, like: for (let x of each(thing)){}`);
|
|
271
|
+
}
|
|
272
|
+
if (state.opts.owningPackageRoot) {
|
|
273
|
+
// there is only an owningPackageRoot when we are running inside a
|
|
274
|
+
// classic ember-cli build. In the embroider stage3 build, there is no
|
|
275
|
+
// owning package root because we're compiling *all* packages
|
|
276
|
+
// simultaneously.
|
|
277
|
+
//
|
|
278
|
+
// given that we're inside classic ember-cli, stop here without trying
|
|
279
|
+
// to rewrite bare `require`. It's not needed, because both our
|
|
280
|
+
// `importSync` and any user-written bare `require` can both mean the
|
|
281
|
+
// same thing: runtime AMD `require`.
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (path.node.name === 'require' &&
|
|
285
|
+
!state.generatedRequires.has(path.node) &&
|
|
286
|
+
!path.scope.hasBinding('require') &&
|
|
287
|
+
state.owningPackage().isEmberAddon()) {
|
|
288
|
+
// Our importSync macro has been compiled to `require`. But we want to
|
|
289
|
+
// distinguish that from any pre-existing, user-written `require` in an
|
|
290
|
+
// Ember addon, which should retain its *runtime* meaning.
|
|
291
|
+
path.replaceWith(t.memberExpression(t.identifier('window'), path.node));
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
if (context.types.OptionalMemberExpression) {
|
|
296
|
+
// our getConfig and getOwnConfig macros are supposed to be able to absorb
|
|
297
|
+
// optional chaining. To make that work we need to see the optional chaining
|
|
298
|
+
// before preset-env compiles them away.
|
|
299
|
+
visitor.OptionalMemberExpression = {
|
|
300
|
+
enter(path, state) {
|
|
301
|
+
if (state.opts.mode === 'compile-time') {
|
|
302
|
+
let result = new evaluate_json_1.Evaluator({ state }).evaluate(path);
|
|
303
|
+
if (result.confident) {
|
|
304
|
+
path.replaceWith((0, evaluate_json_1.buildLiterals)(result.value, context));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
return { visitor };
|
|
311
|
+
}
|
|
312
|
+
//# sourceMappingURL=macros-babel-plugin.js.map
|