UNPKG

2.71 kBJavaScriptView Raw
1export function declare(builder) {
2 return (api, options, dirname) => {
3 if (!api.assertVersion) {
4 // Inject a custom version of 'assertVersion' for Babel 6 and early
5 // versions of Babel 7's beta that didn't have it.
6 api = Object.assign(copyApiObject(api), {
7 assertVersion(range) {
8 throwVersionError(range, api.version);
9 },
10 });
11 }
12
13 return builder(api, options || {}, dirname);
14 };
15}
16
17function copyApiObject(api) {
18 // Babel >= 7 <= beta.41 passed the API as a new object that had
19 // babel/core as the prototype. While slightly faster, it also
20 // means that the Object.assign copy below fails. Rather than
21 // keep complexity, the Babel 6 behavior has been reverted and this
22 // normalizes all that for Babel 7.
23 let proto = null;
24 if (typeof api.version === "string" && /^7\./.test(api.version)) {
25 proto = Object.getPrototypeOf(api);
26 if (
27 proto &&
28 (!has(proto, "version") ||
29 !has(proto, "transform") ||
30 !has(proto, "template") ||
31 !has(proto, "types"))
32 ) {
33 proto = null;
34 }
35 }
36
37 return {
38 ...proto,
39 ...api,
40 };
41}
42
43function has(obj, key) {
44 return Object.prototype.hasOwnProperty.call(obj, key);
45}
46
47function throwVersionError(range, version) {
48 if (typeof range === "number") {
49 if (!Number.isInteger(range)) {
50 throw new Error("Expected string or integer value.");
51 }
52 range = `^${range}.0.0-0`;
53 }
54 if (typeof range !== "string") {
55 throw new Error("Expected string or integer value.");
56 }
57
58 const limit = Error.stackTraceLimit;
59
60 if (typeof limit === "number" && limit < 25) {
61 // Bump up the limit if needed so that users are more likely
62 // to be able to see what is calling Babel.
63 Error.stackTraceLimit = 25;
64 }
65
66 let err;
67 if (version.slice(0, 2) === "7.") {
68 err = new Error(
69 `Requires Babel "^7.0.0-beta.41", but was loaded with "${version}". ` +
70 `You'll need to update your @gerhobbelt/babel-core version.`,
71 );
72 } else {
73 err = new Error(
74 `Requires Babel "${range}", but was loaded with "${version}". ` +
75 `If you are sure you have a compatible version of @gerhobbelt/babel-core, ` +
76 `it is likely that something in your build process is loading the ` +
77 `wrong version. Inspect the stack trace of this error to look for ` +
78 `the first entry that doesn't mention "@gerhobbelt/babel-core" or "babel-core" ` +
79 `to see what is calling Babel.`,
80 );
81 }
82
83 if (typeof limit === "number") {
84 Error.stackTraceLimit = limit;
85 }
86
87 throw Object.assign(
88 err,
89 ({
90 code: "BABEL_VERSION_UNSUPPORTED",
91 version,
92 range,
93 }: any),
94 );
95}