diff options
| author | ruki <waruqi@gmail.com> | 2018-11-08 00:38:48 +0800 |
|---|---|---|
| committer | ruki <waruqi@gmail.com> | 2018-11-07 21:53:09 +0800 |
| commit | 26105034da4fcce7ac883c899d781f016559310d (patch) | |
| tree | c459a5dc4e3aa0972d9919033ece511ce76dd129 /node_modules/@babel/plugin-transform-runtime | |
| parent | 2c77f00f1a7ecb6c8192f9c16d3b2001b254a107 (diff) | |
| download | xmake-docs-26105034da4fcce7ac883c899d781f016559310d.tar.gz xmake-docs-26105034da4fcce7ac883c899d781f016559310d.zip | |
switch to vuepress
Diffstat (limited to 'node_modules/@babel/plugin-transform-runtime')
4 files changed, 732 insertions, 0 deletions
diff --git a/node_modules/@babel/plugin-transform-runtime/README.md b/node_modules/@babel/plugin-transform-runtime/README.md new file mode 100644 index 00000000..7b39101f --- /dev/null +++ b/node_modules/@babel/plugin-transform-runtime/README.md @@ -0,0 +1,358 @@ +# @babel/plugin-transform-runtime + +> Externalise references to helpers and built-ins, automatically polyfilling your code without polluting globals. (This plugin is recommended in a library/tool) + +NOTE: Instance methods such as `"foobar".includes("foo")` will not work since that would require modification of existing built-ins (Use [`@babel/polyfill`](http://babeljs.io/docs/usage/polyfill) for that). + +## Why? + +Babel uses very small helpers for common functions such as `_extend`. By default this will be added to every file that requires it. This duplication is sometimes unnecessary, especially when your application is spread out over multiple files. + +This is where the `@babel/plugin-transform-runtime` plugin comes in: all of the helpers will reference the module `@babel/runtime` to avoid duplication across your compiled output. The runtime will be compiled into your build. + +Another purpose of this transformer is to create a sandboxed environment for your code. If you use [@babel/polyfill](http://babeljs.io/docs/usage/polyfill/) and the built-ins it provides such as `Promise`, `Set` and `Map`, those will pollute the global scope. While this might be ok for an app or a command line tool, it becomes a problem if your code is a library which you intend to publish for others to use or if you can't exactly control the environment in which your code will run. + +The transformer will alias these built-ins to `core-js` so you can use them seamlessly without having to require the polyfill. + +See the [technical details](#technical-details) section for more information on how this works and the types of transformations that occur. + +## Installation + +**NOTE - Production vs. development dependencies** + +In most cases, you should install `@babel/plugin-transform-runtime` as a development dependency (with `--save-dev`). + +```sh +npm install --save-dev @babel/plugin-transform-runtime +``` + +and `@babel/runtime` as a production dependency (with `--save`). + +```sh +npm install --save @babel/runtime +``` + +The transformation plugin is typically used only in development, but the runtime itself will be depended on by your deployed/published code. See the examples below for more details. + +## Usage + +### Via `.babelrc` (Recommended) + +Add the following line to your `.babelrc` file: + +Without options: + +```json +{ + "plugins": ["@babel/plugin-transform-runtime"] +} +``` + +With options: + +```json +{ + "plugins": [ + ["@babel/plugin-transform-runtime", { + "helpers": false, + "polyfill": false, + "regenerator": true, + "moduleName": "@babel/runtime" + }] + ] +} +``` + +### Via CLI + +```sh +babel --plugins @babel/plugin-transform-runtime script.js +``` + +### Via Node API + +```javascript +require("@babel/core").transform("code", { + plugins: ["@babel/plugin-transform-runtime"] +}); +``` + +## Options + +### `helpers` + +`boolean`, defaults to `true`. + +Toggles whether or not inlined Babel helpers (`classCallCheck`, `extends`, etc.) are replaced with calls to `moduleName`. + +For more information, see [Helper aliasing](#helper-aliasing). + +### `polyfill` + +`boolean`, defaults to `true`. + +Toggles whether or not new built-ins (`Promise`, `Set`, `Map`, etc.) are transformed to use a non-global polluting polyfill. + +For more information, see [`core-js` aliasing](#core-js-aliasing). + +### `regenerator` + +`boolean`, defaults to `true`. + +Toggles whether or not generator functions are transformed to use a regenerator runtime that does not pollute the global scope. + +For more information, see [Regenerator aliasing](#regenerator-aliasing). + +### `moduleName` + +`string`, defaults to `"@babel/runtime"`. + +Sets the name/path of the module used when importing helpers. + +Example: + +```json +{ + "moduleName": "flavortown/runtime" +} +``` + +```js +import extends from 'flavortown/runtime/helpers/extends'; +``` + +### `useBuiltIns` + +`boolean`, defaults to `false`. + +When enabled, the transform will use helpers that do not use _any_ polyfills +from `core-js`. + +For example, here is the `instance` helper with `useBuiltIns` disabled: + +```js +exports.__esModule = true; + +var _hasInstance = require("../core-js/symbol/has-instance"); + +var _hasInstance2 = _interopRequireDefault(_hasInstance); + +var _symbol = require("../core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function (left, right) { + if (right != null && typeof _symbol2.default !== "undefined" && right[_hasInstance2.default]) { + return right[_hasInstance2.default](left); + } else { + return left instanceof right; + } +}; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +``` + +And, with it enabled: + +```js +exports.__esModule = true; + +exports.default = function (left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +}; +``` + +### `useESModules` + +`boolean`, defaults to `false`. + +When enabled, the transform will use helpers that do not get run through +`@babel/plugin-transform-modules-commonjs`. This allows for smaller builds in module +systems like webpack, since it doesn't need to preserve commonjs semantics. + +For example, here is the `classCallCheck` helper with `useESModules` disabled: + +```js +exports.__esModule = true; + +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; +``` + +And, with it enabled: + +```js +export default function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} +``` + +## Technical details + +The `runtime` transformer plugin does three things: + +* Automatically requires `@babel/runtime/regenerator` when you use generators/async functions. +* Automatically requires `@babel/runtime/core-js` and maps ES6 static methods and built-ins. +* Removes the inline Babel helpers and uses the module `@babel/runtime/helpers` instead. + +What does this actually mean though? Basically, you can use built-ins such as `Promise`, `Set`, `Symbol`, etc., as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries. + +Make sure you include `@babel/runtime` as a dependency. + +### Regenerator aliasing + +Whenever you use a generator function or async function: + +```javascript +function* foo() { + +} +``` + +the following is generated: + +```javascript +"use strict"; + +var _marked = [foo].map(regeneratorRuntime.mark); + +function foo() { + return regeneratorRuntime.wrap(function foo$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); + } + } + }, _marked[0], this); +} +``` + +This isn't ideal since it relies on the regenerator runtime being included, which +pollutes the global scope. + +With the `runtime` transformer, however, it is compiled to: + +```javascript +"use strict"; + +var _regenerator = require("@babel/runtime/regenerator"); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _marked = [foo].map(_regenerator2.default.mark); + +function foo() { + return _regenerator2.default.wrap(function foo$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); + } + } + }, _marked[0], this); +} +``` + +This means that you can use the regenerator runtime without polluting your current environment. + +### `core-js` aliasing + +Sometimes you may want to use new built-ins such as `Map`, `Set`, `Promise` etc. Your only way +to use these is usually to include a globally polluting polyfill. + +What the `runtime` transformer does is transform the following: + +```javascript +var sym = Symbol(); + +var promise = new Promise; + +console.log(arr[Symbol.iterator]()); +``` + +into the following: + +```javascript +"use strict"; + +var _getIterator2 = require("@babel/runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _promise = require("@babel/runtime/core-js/promise"); + +var _promise2 = _interopRequireDefault(_promise); + +var _symbol = require("@babel/runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var sym = (0, _symbol2.default)(); + +var promise = new _promise2.default(); + +console.log((0, _getIterator3.default)(arr)); +``` + +This means is that you can seamlessly use these native built-ins and static methods +without worrying about where they come from. + +**NOTE:** Instance methods such as `"foobar".includes("foo")` will **not** work. + +### Helper aliasing + +Usually Babel will place helpers at the top of your file to do common tasks to avoid +duplicating the code around in the current file. Sometimes these helpers can get a +little bulky and add unnecessary duplication across files. The `runtime` +transformer replaces all the helper calls to a module. + +That means that the following code: + +```javascript +class Person { +} +``` + +usually turns into: + +```javascript +"use strict"; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Person = function Person() { + _classCallCheck(this, Person); +}; +``` + +the `runtime` transformer however turns this into: + +```javascript +"use strict"; + +var _classCallCheck2 = require("@babel/runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Person = function Person() { + (0, _classCallCheck3.default)(this, Person); +}; +``` diff --git a/node_modules/@babel/plugin-transform-runtime/lib/definitions.js b/node_modules/@babel/plugin-transform-runtime/lib/definitions.js new file mode 100644 index 00000000..a6a4346e --- /dev/null +++ b/node_modules/@babel/plugin-transform-runtime/lib/definitions.js @@ -0,0 +1,168 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = { + builtins: { + Symbol: "symbol", + Promise: "promise", + Map: "map", + WeakMap: "weak-map", + Set: "set", + WeakSet: "weak-set", + Observable: "observable", + setImmediate: "set-immediate", + clearImmediate: "clear-immediate", + asap: "asap" + }, + methods: { + Array: { + copyWithin: "array/copy-within", + entries: "array/entries", + every: "array/every", + fill: "array/fill", + filter: "array/filter", + findIndex: "array/find-index", + find: "array/find", + forEach: "array/for-each", + from: "array/from", + includes: "array/includes", + indexOf: "array/index-of", + join: "array/join", + keys: "array/keys", + lastIndexOf: "array/last-index-of", + map: "array/map", + of: "array/of", + reduceRight: "array/reduce-right", + reduce: "array/reduce", + some: "array/some", + sort: "array/sort", + splice: "array/splice", + values: "array/values" + }, + JSON: { + stringify: "json/stringify" + }, + Object: { + assign: "object/assign", + create: "object/create", + defineProperties: "object/define-properties", + defineProperty: "object/define-property", + entries: "object/entries", + freeze: "object/freeze", + getOwnPropertyDescriptor: "object/get-own-property-descriptor", + getOwnPropertyDescriptors: "object/get-own-property-descriptors", + getOwnPropertyNames: "object/get-own-property-names", + getOwnPropertySymbols: "object/get-own-property-symbols", + getPrototypeOf: "object/get-prototype-of", + isExtensible: "object/is-extensible", + isFrozen: "object/is-frozen", + isSealed: "object/is-sealed", + is: "object/is", + keys: "object/keys", + preventExtensions: "object/prevent-extensions", + seal: "object/seal", + setPrototypeOf: "object/set-prototype-of", + values: "object/values" + }, + Math: { + acosh: "math/acosh", + asinh: "math/asinh", + atanh: "math/atanh", + cbrt: "math/cbrt", + clz32: "math/clz32", + cosh: "math/cosh", + expm1: "math/expm1", + fround: "math/fround", + hypot: "math/hypot", + imul: "math/imul", + log10: "math/log10", + log1p: "math/log1p", + log2: "math/log2", + sign: "math/sign", + sinh: "math/sinh", + tanh: "math/tanh", + trunc: "math/trunc", + iaddh: "math/iaddh", + isubh: "math/isubh", + imulh: "math/imulh", + umulh: "math/umulh" + }, + Symbol: { + for: "symbol/for", + hasInstance: "symbol/has-instance", + isConcatSpreadable: "symbol/is-concat-spreadable", + iterator: "symbol/iterator", + keyFor: "symbol/key-for", + match: "symbol/match", + replace: "symbol/replace", + search: "symbol/search", + species: "symbol/species", + split: "symbol/split", + toPrimitive: "symbol/to-primitive", + toStringTag: "symbol/to-string-tag", + unscopables: "symbol/unscopables" + }, + String: { + at: "string/at", + codePointAt: "string/code-point-at", + endsWith: "string/ends-with", + fromCodePoint: "string/from-code-point", + includes: "string/includes", + matchAll: "string/match-all", + padStart: "string/pad-start", + padEnd: "string/pad-end", + raw: "string/raw", + repeat: "string/repeat", + startsWith: "string/starts-with", + trim: "string/trim", + trimLeft: "string/trim-left", + trimRight: "string/trim-right", + trimStart: "string/trim-start", + trimEnd: "string/trim-end" + }, + Number: { + EPSILON: "number/epsilon", + isFinite: "number/is-finite", + isInteger: "number/is-integer", + isNaN: "number/is-nan", + isSafeInteger: "number/is-safe-integer", + MAX_SAFE_INTEGER: "number/max-safe-integer", + MIN_SAFE_INTEGER: "number/min-safe-integer", + parseFloat: "number/parse-float", + parseInt: "number/parse-int" + }, + Reflect: { + apply: "reflect/apply", + construct: "reflect/construct", + defineProperty: "reflect/define-property", + deleteProperty: "reflect/delete-property", + getOwnPropertyDescriptor: "reflect/get-own-property-descriptor", + getPrototypeOf: "reflect/get-prototype-of", + get: "reflect/get", + has: "reflect/has", + isExtensible: "reflect/is-extensible", + ownKeys: "reflect/own-keys", + preventExtensions: "reflect/prevent-extensions", + setPrototypeOf: "reflect/set-prototype-of", + set: "reflect/set", + defineMetadata: "reflect/define-metadata", + deleteMetadata: "reflect/delete-metadata", + getMetadata: "reflect/get-metadata", + getMetadataKeys: "reflect/get-metadata-keys", + getOwnMetadata: "reflect/get-own-metadata", + getOwnMetadataKeys: "reflect/get-own-metadata-keys", + hasMetadata: "reflect/has-metadata", + hasOwnMetadata: "reflect/has-own-metadata", + metadata: "reflect/metadata" + }, + System: { + global: "system/global" + }, + Date: {}, + Function: {} + } +}; +exports.default = _default;
\ No newline at end of file diff --git a/node_modules/@babel/plugin-transform-runtime/lib/index.js b/node_modules/@babel/plugin-transform-runtime/lib/index.js new file mode 100644 index 00000000..716e2b0f --- /dev/null +++ b/node_modules/@babel/plugin-transform-runtime/lib/index.js @@ -0,0 +1,184 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "definitions", { + enumerable: true, + get: function get() { + return _definitions.default; + } +}); +exports.default = void 0; + +function _helperPluginUtils() { + const data = require("@babel/helper-plugin-utils"); + + _helperPluginUtils = function _helperPluginUtils() { + return data; + }; + + return data; +} + +function _helperModuleImports() { + const data = require("@babel/helper-module-imports"); + + _helperModuleImports = function _helperModuleImports() { + return data; + }; + + return data; +} + +function _core() { + const data = require("@babel/core"); + + _core = function _core() { + return data; + }; + + return data; +} + +var _definitions = _interopRequireDefault(require("./definitions")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = (0, _helperPluginUtils().declare)((api, options) => { + api.assertVersion(7); + const helpers = options.helpers, + _options$moduleName = options.moduleName, + moduleName = _options$moduleName === void 0 ? "@babel/runtime" : _options$moduleName, + polyfill = options.polyfill, + regenerator = options.regenerator, + useBuiltIns = options.useBuiltIns, + useESModules = options.useESModules; + const regeneratorEnabled = regenerator !== false; + const notPolyfillOrDoesUseBuiltIns = polyfill === false || useBuiltIns; + const isPolyfillAndUseBuiltIns = polyfill && useBuiltIns; + const baseHelpersDir = useBuiltIns ? "helpers/builtin" : "helpers"; + const helpersDir = useESModules ? `${baseHelpersDir}/es6` : baseHelpersDir; + + function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + + const HEADER_HELPERS = ["interopRequireWildcard", "interopRequireDefault"]; + return { + pre(file) { + if (helpers !== false) { + file.set("helperGenerator", name => { + const isInteropHelper = HEADER_HELPERS.indexOf(name) !== -1; + const blockHoist = isInteropHelper && !(0, _helperModuleImports().isModule)(file.path) ? 4 : undefined; + return this.addDefaultImport(`${moduleName}/${helpersDir}/${name}`, name, blockHoist); + }); + } + + if (isPolyfillAndUseBuiltIns) { + throw new Error("The polyfill option conflicts with useBuiltIns; use one or the other"); + } + + this.moduleName = moduleName; + const cache = new Map(); + + this.addDefaultImport = (source, nameHint, blockHoist) => { + const cacheKey = (0, _helperModuleImports().isModule)(file.path); + const key = `${source}:${nameHint}:${cacheKey || ""}`; + let cached = cache.get(key); + + if (cached) { + cached = _core().types.cloneNode(cached); + } else { + cached = (0, _helperModuleImports().addDefault)(file.path, source, { + importedInterop: "uncompiled", + nameHint, + blockHoist + }); + cache.set(key, cached); + } + + return cached; + }; + }, + + visitor: { + ReferencedIdentifier(path) { + const node = path.node, + parent = path.parent, + scope = path.scope; + + if (node.name === "regeneratorRuntime" && regeneratorEnabled) { + path.replaceWith(this.addDefaultImport(`${this.moduleName}/regenerator`, "regeneratorRuntime")); + return; + } + + if (notPolyfillOrDoesUseBuiltIns) return; + if (_core().types.isMemberExpression(parent)) return; + if (!has(_definitions.default.builtins, node.name)) return; + if (scope.getBindingIdentifier(node.name)) return; + path.replaceWith(this.addDefaultImport(`${moduleName}/core-js/${_definitions.default.builtins[node.name]}`, node.name)); + }, + + CallExpression(path) { + if (notPolyfillOrDoesUseBuiltIns) return; + if (path.node.arguments.length) return; + const callee = path.node.callee; + if (!_core().types.isMemberExpression(callee)) return; + if (!callee.computed) return; + + if (!path.get("callee.property").matchesPattern("Symbol.iterator")) { + return; + } + + path.replaceWith(_core().types.callExpression(this.addDefaultImport(`${moduleName}/core-js/get-iterator`, "getIterator"), [callee.object])); + }, + + BinaryExpression(path) { + if (notPolyfillOrDoesUseBuiltIns) return; + if (path.node.operator !== "in") return; + if (!path.get("left").matchesPattern("Symbol.iterator")) return; + path.replaceWith(_core().types.callExpression(this.addDefaultImport(`${moduleName}/core-js/is-iterable`, "isIterable"), [path.node.right])); + }, + + MemberExpression: { + enter(path) { + if (notPolyfillOrDoesUseBuiltIns) return; + if (!path.isReferenced()) return; + const node = path.node; + const obj = node.object; + const prop = node.property; + if (!_core().types.isReferenced(obj, node)) return; + if (node.computed) return; + if (!has(_definitions.default.methods, obj.name)) return; + const methods = _definitions.default.methods[obj.name]; + if (!has(methods, prop.name)) return; + if (path.scope.getBindingIdentifier(obj.name)) return; + + if (obj.name === "Object" && prop.name === "defineProperty" && path.parentPath.isCallExpression()) { + const call = path.parentPath.node; + + if (call.arguments.length === 3 && _core().types.isLiteral(call.arguments[1])) { + return; + } + } + + path.replaceWith(this.addDefaultImport(`${moduleName}/core-js/${methods[prop.name]}`, `${obj.name}$${prop.name}`)); + }, + + exit(path) { + if (notPolyfillOrDoesUseBuiltIns) return; + if (!path.isReferenced()) return; + const node = path.node; + const obj = node.object; + if (!has(_definitions.default.builtins, obj.name)) return; + if (path.scope.getBindingIdentifier(obj.name)) return; + path.replaceWith(_core().types.memberExpression(this.addDefaultImport(`${moduleName}/core-js/${_definitions.default.builtins[obj.name]}`, obj.name), node.property, node.computed)); + } + + } + } + }; +}); + +exports.default = _default;
\ No newline at end of file diff --git a/node_modules/@babel/plugin-transform-runtime/package.json b/node_modules/@babel/plugin-transform-runtime/package.json new file mode 100644 index 00000000..be24dbe8 --- /dev/null +++ b/node_modules/@babel/plugin-transform-runtime/package.json @@ -0,0 +1,22 @@ +{ + "name": "@babel/plugin-transform-runtime", + "version": "7.0.0-beta.47", + "description": "Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals", + "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime", + "license": "MIT", + "main": "lib/index.js", + "keywords": [ + "babel-plugin" + ], + "dependencies": { + "@babel/helper-module-imports": "7.0.0-beta.47", + "@babel/helper-plugin-utils": "7.0.0-beta.47" + }, + "peerDependencies": { + "@babel/core": "7.0.0-beta.47" + }, + "devDependencies": { + "@babel/core": "7.0.0-beta.47", + "@babel/helper-plugin-test-runner": "7.0.0-beta.47" + } +} |
