| 1 | _"Polyfill providers"_ are the packages which contain the actual polyfills data. |
| 2 | Their job is to provide the correct import paths for every functionality that their underling polyfill can handle. |
| 3 | |
| 4 | > You can find some examples in the [`packages`](https://github.com/nicolo-ribaudo/babel-polyfills/tree/main/packages) folder of this repository |
| 5 | |
| 6 | A _"polyfill provider"_ is defined passing a factory function to `@babel/helper-define-polyfill-provider`. The factory function takes two parameters (`api` and `options`) and returns an object with the provider implementation. |
| 7 | |
| 8 | ```ts |
| 9 | function polyfillProvider(api: ProviderApi, options: Options): Provider; |
| 10 | ``` |
| 11 | |
| 12 | ## The `Provider` result object. |
| 13 | |
| 14 | The provider object exposes different properties and methods: |
| 15 | |
| 16 | ### `provider.name: string` |
| 17 | |
| 18 | It's the name of the polyfill providers, similarly Babel plugins' `name` property. It's mostly used when the `debug` option is enabled, and in error messages. |
| 19 | |
| 20 | ```js |
| 21 | function myProvider(api) { |
| 22 | return { |
| 23 | name: "my-polyfill", |
| 24 | // ... |
| 25 | }; |
| 26 | } |
| 27 | ``` |
| 28 | |
| 29 | ### `provider.polyfills: string[] | { [name: string]: Support }` |
| 30 | |
| 31 | Is the list of polyfills supported by the polyfill provider. The names don't have a predefined format, but it's important that you are consistent. For example, `core-js` always uses `es.OBJECT.METHOD`, like in `es.array.includes`. |
| 32 | These names will be used for two main purpuses to automatically validate and apply the `include` and `exclude` options specified by the user. |
| 33 | If you use the recommended object version of this option, you can specify which browsers natively support the feature provided by the polyfill: this will make your provider support the `target` option of `@babel/helper-define-polyfill-provider`. |
| 34 | |
| 35 | ```js |
| 36 | function myProvider(api) { |
| 37 | return { |
| 38 | // ... |
| 39 | polyfills: { |
| 40 | "es.array.from": { chrome: "51", firefox: "53", node: "6.5" }, |
| 41 | "es.array.includes": { chrome: "53", firefox: "48", node: "7.0" }, |
| 42 | }, |
| 43 | }; |
| 44 | } |
| 45 | ``` |
| 46 | |
| 47 | ### `provider.filterPolyfills: (name: string) => boolean` |
| 48 | |
| 49 | Sometimes you might want to conditionally include a polyfill based on some additional options that your provider takes. |
| 50 | For example, you might want to only include some non compliant shams if the `sham: true` option is enabled. |
| 51 | |
| 52 | This is similar to directly filtering the `polyfills` option, but it is applied _after_ validating the `include` and `exclude` options. Since only polyfills defined with `polyfills` can be used in those option, `filterPolyfills` prevents errors in case someone is excluding a polyfill which would be excluded by this method anyway. |
| 53 | |
| 54 | ```js |
| 55 | function myProvider(api, options) { |
| 56 | return { |
| 57 | // ... |
| 58 | polyfills: ["Object.assign", "Object.create"], |
| 59 | filterPolyfills(name) { |
| 60 | if (name === "Object.create" && !options.sham) return false; |
| 61 | return true; |
| 62 | }, |
| 63 | }; |
| 64 | } |
| 65 | ``` |
| 66 | |
| 67 | ### `provider.visitor` |
| 68 | |
| 69 | If a provider needs to handle special cases which aren't supported by `@babel/helper-define-polyfill-provider`, it can provide a normal `visitor` like any Babel plugin. |
| 70 | |
| 71 | ### `provider.entryGlobal`, `provider.usageGlobal` and `provider.usagePure` |
| 72 | |
| 73 | These three functions are the core of any polyfill provider. |
| 74 | They correspond, respectively, to the `entry-global`, `usage-global` and `usage-pure` values of the `method` option of `@babel/helper-define-polyfill-provider`. |
| 75 | They are all optional, but you must specify at least one of them. |
| 76 | |
| 77 | They take three parameters, and return nothing: |
| 78 | |
| 79 | ```js |
| 80 | function entryGlobal(meta, utils, path): void; |
| 81 | ``` |
| 82 | |
| 83 | #### `meta` |
| 84 | |
| 85 | A `meta` object describes the statement or expression which triggered the call to the polyfill provider. It always has a `kind` property which can be used to differentiate between the possible polyfill types. |
| 86 | |
| 87 | - ```js |
| 88 | import "my-polyfill"`; |
| 89 | ``` |
| 90 | |
| 91 | ```js |
| 92 | type Meta = { kind: "import", source: string }; |
| 93 | ``` |
| 94 | |
| 95 | This can only happen when using `method: "entry-global"`. It is needed to replace the generic entry point of the plugin with the optimized entry points based on the targets. |
| 96 | |
| 97 | - ```js |
| 98 | Promise; |
| 99 | ``` |
| 100 | |
| 101 | ```js |
| 102 | type Meta = { kind: "global", name: string }; |
| 103 | ``` |
| 104 | |
| 105 | Where, in this example, `name` is `"Promise"` |
| 106 | |
| 107 | - ```js |
| 108 | obj.prop; |
| 109 | ``` |
| 110 | |
| 111 | ```js |
| 112 | type Meta = { |
| 113 | kind: "property", |
| 114 | placement: "static" | "prototype" | null, |
| 115 | object: string | null, |
| 116 | key: string, |
| 117 | }; |
| 118 | ``` |
| 119 | |
| 120 | `@babel/plugin-inject-polyfill` tries to detect the origin of `obj`, to infer the property placement and the real name of `obj`. |
| 121 | |
| 122 | - If `obj` is a global binding not declared in the current file, `obj.prop` is assumed to be a static property of a built-in object: |
| 123 | |
| 124 | ```js |
| 125 | Array.from; |
| 126 | ``` |
| 127 | |
| 128 | ```js |
| 129 | type Meta = { |
| 130 | kind: "property", |
| 131 | placement: "static", |
| 132 | object: "Array", |
| 133 | key: "from", |
| 134 | }; |
| 135 | ``` |
| 136 | |
| 137 | Note that `@babel/helper-define-polyfill-provider` will also track assignments as much as possible. For example, this code is represented by the same `Meta`: |
| 138 | |
| 139 | ```js |
| 140 | var MyArray = Array; |
| 141 | var propName = "from"; |
| 142 | |
| 143 | MyArray[propName]; |
| 144 | ``` |
| 145 | |
| 146 | - If `obj` can be inferred to be a native JS type (e.g. an array), or it comes from a `Something.prototype` access, it is considered a prototype property: |
| 147 | |
| 148 | ```js |
| 149 | [].includes; |
| 150 | ``` |
| 151 | |
| 152 | ```js |
| 153 | type Meta = { |
| 154 | kind: "property", |
| 155 | placement: "prototype", |
| 156 | object: "Array", |
| 157 | key: "includes", |
| 158 | }; |
| 159 | ``` |
| 160 | |
| 161 | - If it isn't possible to detect where `obj` comes from, for example when it is generated by a complex expression, both `placement` and `obj` are set to `null`: |
| 162 | |
| 163 | ```js |
| 164 | getThing().includes; |
| 165 | ``` |
| 166 | |
| 167 | ```js |
| 168 | type Meta = { |
| 169 | kind: "property", |
| 170 | placement: null, |
| 171 | object: null, |
| 172 | key: "includes", |
| 173 | }; |
| 174 | ``` |
| 175 | |
| 176 | The `"property"` kind is also used when destructuring, for example in `{ from } = Array`. |
| 177 | |
| 178 | `Symbol.*` property names are considered as an unit. For example, in `Array.prototype[Symbol.iterator]`, `meta.key` is `"Symbol.iterator"`. |
| 179 | |
| 180 | - ```js |
| 181 | Symbol.iterator in []; |
| 182 | ``` |
| 183 | |
| 184 | Many dynamic checks for the presence of a polyfilled property can be statically replaced. For example, an "is iterable" check could be statically replaced with a functions which checks if the lhs is an array, `arguments`, or any other polyfilled built-in which should be handled as if it was iterable. |
| 185 | |
| 186 | ```js |
| 187 | type Meta = { |
| 188 | kind: "in", |
| 189 | placement: ?("static" | "prototype"), |
| 190 | object: ?string, |
| 191 | key: string, |
| 192 | }; |
| 193 | ``` |
| 194 | |
| 195 | It follows the same rules as the `"property"` kind. |
| 196 | |
| 197 | #### `utils` |
| 198 | |
| 199 | When calling a provider function (e.g. `usageGlobal`), `@babel/helper-define-polyfill-provider` will provide it a few utilities to easily inject the necessary `import` statements or `require` calls, depending on the source type. Polyfill providers shouldn't worry about which AST represents an import, or about the source type of the file being transpiled. |
| 200 | |
| 201 | - `utils.injectGlobalImport(url: string)` can be used to inject side-effectful global imports. It is usually called when injecting global polyfills. |
| 202 | For example, `utils.injectGlobalImport("my-polyfill")` would generate this code: |
| 203 | |
| 204 | ```js |
| 205 | import "my-polyfill"; |
| 206 | ``` |
| 207 | |
| 208 | - `utils.injectNamedImport(url: string, name: string, hint?: string)` and `utils.injectDefaultImport(url: string, hint?: string)` are used to inject named or defaults import. They both return an identifier referencing the imported value. |
| 209 | The optional `hint` parameter can be used to generate a nice-looking alias for the import. |
| 210 | For example, `utils.injectNamedImport("array-polyfills", "from, "Array.from")` would generate this code: |
| 211 | |
| 212 | ```js |
| 213 | import { from as _ArrayFrom } from "array-polyfills"; |
| 214 | ``` |
| 215 | |
| 216 | and return this AST node: |
| 217 | |
| 218 | ```json |
| 219 | { |
| 220 | "type": "Identifier", |
| 221 | "name": "_ArrayFrom" |
| 222 | } |
| 223 | ``` |
| 224 | |
| 225 | ## The `ProviderApi` parameter |
| 226 | |
| 227 | While some utilities are provided in the `utils` object, some of them are provided in the `api` object. The main different is that `utils` methods act on a specific input source file, while `api` methods provide info about how the plugin was configured and are not directly related to the transformed source code. |
| 228 | |
| 229 | ### `api.method` |
| 230 | |
| 231 | It represents the `method` option passed to `@babel/helper-define-polyfill-provider`, and it can be one of `"entry-global"`, `"usage-global"`, or `"usage-pure"`. |
| 232 | |
| 233 | ### `api.targets` |
| 234 | |
| 235 | It represents the resolved engines which the user is targeting. Regardless of how they were specified (i.e. via browserslist), they are always normalized to an object mapping from engine names to versions. |
| 236 | |
| 237 | Example: |
| 238 | |
| 239 | ```json |
| 240 | { |
| 241 | "chrome": "74.0.0", |
| 242 | "firefox": "67.0.0", |
| 243 | "ios": "12.2.0" |
| 244 | } |
| 245 | ``` |
| 246 | |
| 247 | ### `api.shouldInjectPolyfill(name: string): boolean` |
| 248 | |
| 249 | This methods returns wether or not a polyfill is needed, using data from the `targets`, `include` and `exclude` options, and from the engines support specified in the `provider.polyfills` property returned by the polyfill provider. |
| 250 | |
| 251 | ### `api.debug(name: string | null)` |
| 252 | |
| 253 | This method is used to log information about the injected polyfills, which will then be reported to the user if the `debug` option is enabled. |
| 254 | |
| 255 | It should be called passing the polyfill name as a string whenever a polyfill is injected. When, in `"entry-global"` mode, the polyfill entry point has been found but removed becase no polyfill was needed, this method should be called passing `null` as a parameter to indicate that nothing has been injected. |
| 256 | |
| 257 | ### `api.assertDependency(name: string, version?: string)` |
| 258 | |
| 259 | This method is used to verify that a polyfill package that is going to be used is installed. If it's not installed, it will log a message asking the user to install it. |
| 260 | |
| 261 | ### `api.getUtils(path: NodePath): Utils` |
| 262 | |
| 263 | Sometimes you might need to inject an import outside of the `entryGlobal`/`usageGlobal`/`usagePure` methods. You could manually create the AST representing it, after checking which source type the current file is using (if `script` or `module`), but it is way more complex than the out-of-the-box support provided by the `utils` object. |
| 264 | |
| 265 | You can use this method to create a new `utils` object with all its utilities, attached to the file the current `NodePath` belongs to. |
| 266 | |
| 267 | ```js |
| 268 | export default function({ getUtils }) { |
| 269 | return { |
| 270 | // ... |
| 271 | visitor: { |
| 272 | YieldExpression(path) { |
| 273 | if (!path.node.star) return; |
| 274 | getUtils(path).injectGlobalImport("iterators-polyfill"); |
| 275 | }, |
| 276 | }, |
| 277 | }; |
| 278 | } |
| 279 | ``` |
| 280 | |
| 281 | ### `api.createMetaResolver` |
| 282 | |
| 283 | ```js |
| 284 | function createMetaResolver<T>(definitions: Definitions<T>): (meta: Meta) => T; |
| 285 | ``` |
| 286 | |
| 287 | From a syntactic point of view, `window.Promise` is a static property access: we are accessing the `"Promise"` property of the `window` object. For this reason, when polyfilling the ES2015 `Promise` constructor, we need to check both for static properties and for global variables. |
| 288 | Following the same pattern, `theFoo.includes` has the same problem: it could be a static property access on the `theFoo` global object, or `theFoo` could be a global instance of an array and `includes` would then be a prototype property. |
| 289 | |
| 290 | To avoid having to manually check for all these cases, the `createMetaResolver` factory creates a function which does it for you. |
| 291 | |
| 292 | The `definitions` parameter is an object containing mappings of global values, and of static and instance properties. It has the following shape: |
| 293 | |
| 294 | ```js |
| 295 | type Definitions<T> = { |
| 296 | global: { |
| 297 | [variableName: string]: T, |
| 298 | }, |
| 299 | instance: { |
| 300 | [propertyName: string]: T, |
| 301 | }, |
| 302 | static: { |
| 303 | [objectName: string]: { |
| 304 | [propertyName: string]: T, |
| 305 | }, |
| 306 | }, |
| 307 | }; |
| 308 | ``` |
| 309 | |
| 310 | Instance properties aren't categorized by their object, because often it's not possible to statically determine it. |
| 311 | For this reason, it is highly recommended that pure polyfills for instance properties, if supported, check their argument type at runtime. |
| 312 | For example, a `*.includes` polyfill might look like this: |
| 313 | |
| 314 | ```js |
| 315 | import * as array from "array-methods"; |
| 316 | import * as string from "string-methods"; |
| 317 | |
| 318 | export default includes(thisValue, value) { |
| 319 | if (typeof thisValue === "string") { |
| 320 | return string.includes(thisValue, value); |
| 321 | } |
| 322 | if (Array.isArray(thisValue)) { |
| 323 | return array.includes(thisValue, value); |
| 324 | } |
| 325 | |
| 326 | // This is not an array or a string, so we call the original method |
| 327 | return arr.includes(value); |
| 328 | } |
| 329 | ``` |
| 330 | |
| 331 | ## Naming convention |
| 332 | |
| 333 | Polyfill providers follow a naming convention similar to Babel plugins and presets: |
| 334 | |
| 335 | - `@babel/plugin-polyfill-POLYFILL-NAME` |
| 336 | - `@ORG/babel-plugin-polyfill-POLYFILL-NAME` |
| 337 | - `@ORG/babel-plugin-polyfill` |