index.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import corejs2Polyfills from '@babel/compat-data/corejs2-built-ins';
  2. import semver from 'semver';
  3. import defineProvider from '@babel/helper-define-polyfill-provider';
  4. import * as _babel from '@babel/core';
  5. const define = (name, pure, global = [], meta) => {
  6. return {
  7. name,
  8. pure,
  9. global,
  10. meta
  11. };
  12. };
  13. const pureAndGlobal = (pure, global, minRuntimeVersion = null) => define(global[0], pure, global, {
  14. minRuntimeVersion
  15. });
  16. const globalOnly = global => define(global[0], null, global);
  17. const pureOnly = (pure, name) => define(name, pure, []);
  18. const ArrayNatureIterators = ["es6.object.to-string", "es6.array.iterator", "web.dom.iterable"];
  19. const CommonIterators = ["es6.string.iterator", ...ArrayNatureIterators];
  20. const PromiseDependencies = ["es6.object.to-string", "es6.promise"];
  21. const BuiltIns = {
  22. DataView: globalOnly(["es6.typed.data-view"]),
  23. Float32Array: globalOnly(["es6.typed.float32-array"]),
  24. Float64Array: globalOnly(["es6.typed.float64-array"]),
  25. Int8Array: globalOnly(["es6.typed.int8-array"]),
  26. Int16Array: globalOnly(["es6.typed.int16-array"]),
  27. Int32Array: globalOnly(["es6.typed.int32-array"]),
  28. Map: pureAndGlobal("map", ["es6.map", ...CommonIterators]),
  29. Number: globalOnly(["es6.number.constructor"]),
  30. Promise: pureAndGlobal("promise", PromiseDependencies),
  31. RegExp: globalOnly(["es6.regexp.constructor"]),
  32. Set: pureAndGlobal("set", ["es6.set", ...CommonIterators]),
  33. Symbol: pureAndGlobal("symbol/index", ["es6.symbol"]),
  34. Uint8Array: globalOnly(["es6.typed.uint8-array"]),
  35. Uint8ClampedArray: globalOnly(["es6.typed.uint8-clamped-array"]),
  36. Uint16Array: globalOnly(["es6.typed.uint16-array"]),
  37. Uint32Array: globalOnly(["es6.typed.uint32-array"]),
  38. WeakMap: pureAndGlobal("weak-map", ["es6.weak-map", ...CommonIterators]),
  39. WeakSet: pureAndGlobal("weak-set", ["es6.weak-set", ...CommonIterators]),
  40. setImmediate: pureOnly("set-immediate", "web.immediate"),
  41. clearImmediate: pureOnly("clear-immediate", "web.immediate"),
  42. parseFloat: pureOnly("parse-float", "es6.parse-float"),
  43. parseInt: pureOnly("parse-int", "es6.parse-int")
  44. };
  45. const InstanceProperties = {
  46. __defineGetter__: globalOnly(["es7.object.define-getter"]),
  47. __defineSetter__: globalOnly(["es7.object.define-setter"]),
  48. __lookupGetter__: globalOnly(["es7.object.lookup-getter"]),
  49. __lookupSetter__: globalOnly(["es7.object.lookup-setter"]),
  50. anchor: globalOnly(["es6.string.anchor"]),
  51. big: globalOnly(["es6.string.big"]),
  52. bind: globalOnly(["es6.function.bind"]),
  53. blink: globalOnly(["es6.string.blink"]),
  54. bold: globalOnly(["es6.string.bold"]),
  55. codePointAt: globalOnly(["es6.string.code-point-at"]),
  56. copyWithin: globalOnly(["es6.array.copy-within"]),
  57. endsWith: globalOnly(["es6.string.ends-with"]),
  58. entries: globalOnly(ArrayNatureIterators),
  59. every: globalOnly(["es6.array.every"]),
  60. fill: globalOnly(["es6.array.fill"]),
  61. filter: globalOnly(["es6.array.filter"]),
  62. finally: globalOnly(["es7.promise.finally", ...PromiseDependencies]),
  63. find: globalOnly(["es6.array.find"]),
  64. findIndex: globalOnly(["es6.array.find-index"]),
  65. fixed: globalOnly(["es6.string.fixed"]),
  66. flags: globalOnly(["es6.regexp.flags"]),
  67. flatMap: globalOnly(["es7.array.flat-map"]),
  68. fontcolor: globalOnly(["es6.string.fontcolor"]),
  69. fontsize: globalOnly(["es6.string.fontsize"]),
  70. forEach: globalOnly(["es6.array.for-each"]),
  71. includes: globalOnly(["es6.string.includes", "es7.array.includes"]),
  72. indexOf: globalOnly(["es6.array.index-of"]),
  73. italics: globalOnly(["es6.string.italics"]),
  74. keys: globalOnly(ArrayNatureIterators),
  75. lastIndexOf: globalOnly(["es6.array.last-index-of"]),
  76. link: globalOnly(["es6.string.link"]),
  77. map: globalOnly(["es6.array.map"]),
  78. match: globalOnly(["es6.regexp.match"]),
  79. name: globalOnly(["es6.function.name"]),
  80. padStart: globalOnly(["es7.string.pad-start"]),
  81. padEnd: globalOnly(["es7.string.pad-end"]),
  82. reduce: globalOnly(["es6.array.reduce"]),
  83. reduceRight: globalOnly(["es6.array.reduce-right"]),
  84. repeat: globalOnly(["es6.string.repeat"]),
  85. replace: globalOnly(["es6.regexp.replace"]),
  86. search: globalOnly(["es6.regexp.search"]),
  87. small: globalOnly(["es6.string.small"]),
  88. some: globalOnly(["es6.array.some"]),
  89. sort: globalOnly(["es6.array.sort"]),
  90. split: globalOnly(["es6.regexp.split"]),
  91. startsWith: globalOnly(["es6.string.starts-with"]),
  92. strike: globalOnly(["es6.string.strike"]),
  93. sub: globalOnly(["es6.string.sub"]),
  94. sup: globalOnly(["es6.string.sup"]),
  95. toISOString: globalOnly(["es6.date.to-iso-string"]),
  96. toJSON: globalOnly(["es6.date.to-json"]),
  97. toString: globalOnly(["es6.object.to-string", "es6.date.to-string", "es6.regexp.to-string"]),
  98. trim: globalOnly(["es6.string.trim"]),
  99. trimEnd: globalOnly(["es7.string.trim-right"]),
  100. trimLeft: globalOnly(["es7.string.trim-left"]),
  101. trimRight: globalOnly(["es7.string.trim-right"]),
  102. trimStart: globalOnly(["es7.string.trim-left"]),
  103. values: globalOnly(ArrayNatureIterators)
  104. };
  105. // This isn't present in older @babel/compat-data versions
  106. if ("es6.array.slice" in corejs2Polyfills) {
  107. InstanceProperties.slice = globalOnly(["es6.array.slice"]);
  108. }
  109. const StaticProperties = {
  110. Array: {
  111. from: pureAndGlobal("array/from", ["es6.symbol", "es6.array.from", ...CommonIterators]),
  112. isArray: pureAndGlobal("array/is-array", ["es6.array.is-array"]),
  113. of: pureAndGlobal("array/of", ["es6.array.of"])
  114. },
  115. Date: {
  116. now: pureAndGlobal("date/now", ["es6.date.now"])
  117. },
  118. JSON: {
  119. stringify: pureOnly("json/stringify", "es6.symbol")
  120. },
  121. Math: {
  122. // 'Math' was not included in the 7.0.0
  123. // release of '@babel/runtime'. See issue https://github.com/babel/babel/pull/8616.
  124. acosh: pureAndGlobal("math/acosh", ["es6.math.acosh"], "7.0.1"),
  125. asinh: pureAndGlobal("math/asinh", ["es6.math.asinh"], "7.0.1"),
  126. atanh: pureAndGlobal("math/atanh", ["es6.math.atanh"], "7.0.1"),
  127. cbrt: pureAndGlobal("math/cbrt", ["es6.math.cbrt"], "7.0.1"),
  128. clz32: pureAndGlobal("math/clz32", ["es6.math.clz32"], "7.0.1"),
  129. cosh: pureAndGlobal("math/cosh", ["es6.math.cosh"], "7.0.1"),
  130. expm1: pureAndGlobal("math/expm1", ["es6.math.expm1"], "7.0.1"),
  131. fround: pureAndGlobal("math/fround", ["es6.math.fround"], "7.0.1"),
  132. hypot: pureAndGlobal("math/hypot", ["es6.math.hypot"], "7.0.1"),
  133. imul: pureAndGlobal("math/imul", ["es6.math.imul"], "7.0.1"),
  134. log1p: pureAndGlobal("math/log1p", ["es6.math.log1p"], "7.0.1"),
  135. log10: pureAndGlobal("math/log10", ["es6.math.log10"], "7.0.1"),
  136. log2: pureAndGlobal("math/log2", ["es6.math.log2"], "7.0.1"),
  137. sign: pureAndGlobal("math/sign", ["es6.math.sign"], "7.0.1"),
  138. sinh: pureAndGlobal("math/sinh", ["es6.math.sinh"], "7.0.1"),
  139. tanh: pureAndGlobal("math/tanh", ["es6.math.tanh"], "7.0.1"),
  140. trunc: pureAndGlobal("math/trunc", ["es6.math.trunc"], "7.0.1")
  141. },
  142. Number: {
  143. EPSILON: pureAndGlobal("number/epsilon", ["es6.number.epsilon"]),
  144. MIN_SAFE_INTEGER: pureAndGlobal("number/min-safe-integer", ["es6.number.min-safe-integer"]),
  145. MAX_SAFE_INTEGER: pureAndGlobal("number/max-safe-integer", ["es6.number.max-safe-integer"]),
  146. isFinite: pureAndGlobal("number/is-finite", ["es6.number.is-finite"]),
  147. isInteger: pureAndGlobal("number/is-integer", ["es6.number.is-integer"]),
  148. isSafeInteger: pureAndGlobal("number/is-safe-integer", ["es6.number.is-safe-integer"]),
  149. isNaN: pureAndGlobal("number/is-nan", ["es6.number.is-nan"]),
  150. parseFloat: pureAndGlobal("number/parse-float", ["es6.number.parse-float"]),
  151. parseInt: pureAndGlobal("number/parse-int", ["es6.number.parse-int"])
  152. },
  153. Object: {
  154. assign: pureAndGlobal("object/assign", ["es6.object.assign"]),
  155. create: pureAndGlobal("object/create", ["es6.object.create"]),
  156. defineProperties: pureAndGlobal("object/define-properties", ["es6.object.define-properties"]),
  157. defineProperty: pureAndGlobal("object/define-property", ["es6.object.define-property"]),
  158. entries: pureAndGlobal("object/entries", ["es7.object.entries"]),
  159. freeze: pureAndGlobal("object/freeze", ["es6.object.freeze"]),
  160. getOwnPropertyDescriptor: pureAndGlobal("object/get-own-property-descriptor", ["es6.object.get-own-property-descriptor"]),
  161. getOwnPropertyDescriptors: pureAndGlobal("object/get-own-property-descriptors", ["es7.object.get-own-property-descriptors"]),
  162. getOwnPropertyNames: pureAndGlobal("object/get-own-property-names", ["es6.object.get-own-property-names"]),
  163. getOwnPropertySymbols: pureAndGlobal("object/get-own-property-symbols", ["es6.symbol"]),
  164. getPrototypeOf: pureAndGlobal("object/get-prototype-of", ["es6.object.get-prototype-of"]),
  165. is: pureAndGlobal("object/is", ["es6.object.is"]),
  166. isExtensible: pureAndGlobal("object/is-extensible", ["es6.object.is-extensible"]),
  167. isFrozen: pureAndGlobal("object/is-frozen", ["es6.object.is-frozen"]),
  168. isSealed: pureAndGlobal("object/is-sealed", ["es6.object.is-sealed"]),
  169. keys: pureAndGlobal("object/keys", ["es6.object.keys"]),
  170. preventExtensions: pureAndGlobal("object/prevent-extensions", ["es6.object.prevent-extensions"]),
  171. seal: pureAndGlobal("object/seal", ["es6.object.seal"]),
  172. setPrototypeOf: pureAndGlobal("object/set-prototype-of", ["es6.object.set-prototype-of"]),
  173. values: pureAndGlobal("object/values", ["es7.object.values"])
  174. },
  175. Promise: {
  176. all: globalOnly(CommonIterators),
  177. race: globalOnly(CommonIterators)
  178. },
  179. Reflect: {
  180. apply: pureAndGlobal("reflect/apply", ["es6.reflect.apply"]),
  181. construct: pureAndGlobal("reflect/construct", ["es6.reflect.construct"]),
  182. defineProperty: pureAndGlobal("reflect/define-property", ["es6.reflect.define-property"]),
  183. deleteProperty: pureAndGlobal("reflect/delete-property", ["es6.reflect.delete-property"]),
  184. get: pureAndGlobal("reflect/get", ["es6.reflect.get"]),
  185. getOwnPropertyDescriptor: pureAndGlobal("reflect/get-own-property-descriptor", ["es6.reflect.get-own-property-descriptor"]),
  186. getPrototypeOf: pureAndGlobal("reflect/get-prototype-of", ["es6.reflect.get-prototype-of"]),
  187. has: pureAndGlobal("reflect/has", ["es6.reflect.has"]),
  188. isExtensible: pureAndGlobal("reflect/is-extensible", ["es6.reflect.is-extensible"]),
  189. ownKeys: pureAndGlobal("reflect/own-keys", ["es6.reflect.own-keys"]),
  190. preventExtensions: pureAndGlobal("reflect/prevent-extensions", ["es6.reflect.prevent-extensions"]),
  191. set: pureAndGlobal("reflect/set", ["es6.reflect.set"]),
  192. setPrototypeOf: pureAndGlobal("reflect/set-prototype-of", ["es6.reflect.set-prototype-of"])
  193. },
  194. String: {
  195. at: pureOnly("string/at", "es7.string.at"),
  196. fromCodePoint: pureAndGlobal("string/from-code-point", ["es6.string.from-code-point"]),
  197. raw: pureAndGlobal("string/raw", ["es6.string.raw"])
  198. },
  199. Symbol: {
  200. // FIXME: Pure disabled to work around zloirock/core-js#262.
  201. asyncIterator: globalOnly(["es6.symbol", "es7.symbol.async-iterator"]),
  202. for: pureOnly("symbol/for", "es6.symbol"),
  203. hasInstance: pureOnly("symbol/has-instance", "es6.symbol"),
  204. isConcatSpreadable: pureOnly("symbol/is-concat-spreadable", "es6.symbol"),
  205. iterator: define("es6.symbol", "symbol/iterator", CommonIterators),
  206. keyFor: pureOnly("symbol/key-for", "es6.symbol"),
  207. match: pureAndGlobal("symbol/match", ["es6.regexp.match"]),
  208. replace: pureOnly("symbol/replace", "es6.symbol"),
  209. search: pureOnly("symbol/search", "es6.symbol"),
  210. species: pureOnly("symbol/species", "es6.symbol"),
  211. split: pureOnly("symbol/split", "es6.symbol"),
  212. toPrimitive: pureOnly("symbol/to-primitive", "es6.symbol"),
  213. toStringTag: pureOnly("symbol/to-string-tag", "es6.symbol"),
  214. unscopables: pureOnly("symbol/unscopables", "es6.symbol")
  215. }
  216. };
  217. const webPolyfills = {
  218. "web.timers": {},
  219. "web.immediate": {},
  220. "web.dom.iterable": {}
  221. };
  222. const purePolyfills = {
  223. "es6.parse-float": {},
  224. "es6.parse-int": {},
  225. "es7.string.at": {}
  226. };
  227. function addPlatformSpecificPolyfills (targets, method, polyfills) {
  228. const targetNames = Object.keys(targets);
  229. const isAnyTarget = !targetNames.length;
  230. const isWebTarget = targetNames.some(name => name !== "node");
  231. return {
  232. ...polyfills,
  233. ...(method === "usage-pure" ? purePolyfills : null),
  234. ...(isAnyTarget || isWebTarget ? webPolyfills : null)
  235. };
  236. }
  237. function hasMinVersion(minVersion, runtimeVersion) {
  238. // If the range is unavailable, we're running the script during Babel's
  239. // build process, and we want to assume that all versions are satisfied so
  240. // that the built output will include all definitions.
  241. if (!runtimeVersion || !minVersion) return true;
  242. runtimeVersion = String(runtimeVersion);
  243. // semver.intersects() has some surprising behavior with comparing ranges
  244. // with preprelease versions. We add '^' to ensure that we are always
  245. // comparing ranges with ranges, which sidesteps this logic.
  246. // For example:
  247. //
  248. // semver.intersects(`<7.0.1`, "7.0.0-beta.0") // false - surprising
  249. // semver.intersects(`<7.0.1`, "^7.0.0-beta.0") // true - expected
  250. //
  251. // This is because the first falls back to
  252. //
  253. // semver.satisfies("7.0.0-beta.0", `<7.0.1`) // false - surprising
  254. //
  255. // and this fails because a prerelease version can only satisfy a range
  256. // if it is a prerelease within the same major/minor/patch range.
  257. //
  258. // Note: If this is found to have issues, please also revist the logic in
  259. // babel-core's availableHelper() API.
  260. if (semver.valid(runtimeVersion)) runtimeVersion = `^${runtimeVersion}`;
  261. return !semver.intersects(`<${minVersion}`, runtimeVersion) && !semver.intersects(`>=8.0.0`, runtimeVersion);
  262. }
  263. const {
  264. types: t
  265. } = _babel.default || _babel;
  266. const BABEL_RUNTIME = "@babel/runtime-corejs2";
  267. const presetEnvCompat = "#__secret_key__@babel/preset-env__compatibility";
  268. const runtimeCompat = "#__secret_key__@babel/runtime__compatibility";
  269. const has = Function.call.bind(Object.hasOwnProperty);
  270. var index = defineProvider(function (api, {
  271. [presetEnvCompat]: {
  272. entryInjectRegenerator = false,
  273. noRuntimeName = false
  274. } = {},
  275. [runtimeCompat]: {
  276. useBabelRuntime = false,
  277. runtimeVersion = "",
  278. ext = ".js"
  279. } = {}
  280. }) {
  281. const resolve = api.createMetaResolver({
  282. global: BuiltIns,
  283. static: StaticProperties,
  284. instance: InstanceProperties
  285. });
  286. const {
  287. debug,
  288. shouldInjectPolyfill,
  289. method
  290. } = api;
  291. const polyfills = addPlatformSpecificPolyfills(api.targets, method, corejs2Polyfills);
  292. const coreJSBase = useBabelRuntime ? `${BABEL_RUNTIME}/core-js` : method === "usage-pure" ? "core-js/library/fn" : "core-js/modules";
  293. function inject(name, utils) {
  294. if (typeof name === "string") {
  295. // Some polyfills aren't always available, for example
  296. // web.dom.iterable when targeting node
  297. if (has(polyfills, name) && shouldInjectPolyfill(name)) {
  298. debug(name);
  299. utils.injectGlobalImport(`${coreJSBase}/${name}.js`);
  300. }
  301. return;
  302. }
  303. name.forEach(name => inject(name, utils));
  304. }
  305. function maybeInjectPure(desc, hint, utils) {
  306. let {
  307. pure,
  308. meta,
  309. name
  310. } = desc;
  311. if (!pure || !shouldInjectPolyfill(name)) return;
  312. if (runtimeVersion && meta && meta.minRuntimeVersion && !hasMinVersion(meta && meta.minRuntimeVersion, runtimeVersion)) {
  313. return;
  314. }
  315. // Unfortunately core-js and @babel/runtime-corejs2 don't have the same
  316. // directory structure, so we need to special case this.
  317. if (useBabelRuntime && pure === "symbol/index") pure = "symbol";
  318. return utils.injectDefaultImport(`${coreJSBase}/${pure}${ext}`, hint);
  319. }
  320. return {
  321. name: "corejs2",
  322. runtimeName: noRuntimeName ? null : BABEL_RUNTIME,
  323. polyfills,
  324. entryGlobal(meta, utils, path) {
  325. if (meta.kind === "import" && meta.source === "core-js") {
  326. debug(null);
  327. inject(Object.keys(polyfills), utils);
  328. if (entryInjectRegenerator) {
  329. utils.injectGlobalImport("regenerator-runtime/runtime.js");
  330. }
  331. path.remove();
  332. }
  333. },
  334. usageGlobal(meta, utils) {
  335. const resolved = resolve(meta);
  336. if (!resolved) return;
  337. let deps = resolved.desc.global;
  338. if (resolved.kind !== "global" && "object" in meta && meta.object && meta.placement === "prototype") {
  339. const low = meta.object.toLowerCase();
  340. deps = deps.filter(m => m.includes(low));
  341. }
  342. inject(deps, utils);
  343. },
  344. usagePure(meta, utils, path) {
  345. if (meta.kind === "in") {
  346. if (meta.key === "Symbol.iterator") {
  347. path.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/is-iterable${ext}`, "isIterable"), [path.node.right] // meta.kind === "in" narrows this
  348. ));
  349. }
  350. return;
  351. }
  352. if (path.parentPath.isUnaryExpression({
  353. operator: "delete"
  354. })) return;
  355. if (meta.kind === "property") {
  356. // We can't compile destructuring.
  357. if (!path.isMemberExpression()) return;
  358. if (!path.isReferenced()) return;
  359. if (meta.key === "Symbol.iterator" && shouldInjectPolyfill("es6.symbol") && path.parentPath.isCallExpression({
  360. callee: path.node
  361. }) && path.parentPath.node.arguments.length === 0) {
  362. path.parentPath.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/get-iterator${ext}`, "getIterator"), [path.node.object]));
  363. path.skip();
  364. return;
  365. }
  366. }
  367. const resolved = resolve(meta);
  368. if (!resolved) return;
  369. const id = maybeInjectPure(resolved.desc, resolved.name, utils);
  370. if (id) path.replaceWith(id);
  371. },
  372. visitor: method === "usage-global" && {
  373. // yield*
  374. YieldExpression(path) {
  375. if (path.node.delegate) {
  376. inject("web.dom.iterable", api.getUtils(path));
  377. }
  378. },
  379. // for-of, [a, b] = c
  380. "ForOfStatement|ArrayPattern"(path) {
  381. CommonIterators.forEach(name => inject(name, api.getUtils(path)));
  382. }
  383. }
  384. };
  385. });
  386. export default index;
  387. //# sourceMappingURL=index.mjs.map