|
| 1 | +/** |
| 2 | + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS-IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { Transform, Range, TransformInterface } from '../types'; |
| 18 | +import { TransformSourceDescription } from 'rollup'; |
| 19 | +import MagicString from 'magic-string'; |
| 20 | +import { ArrowFunctionExpression } from 'estree'; |
| 21 | +import { parse, walk } from '../acorn'; |
| 22 | + |
| 23 | +/** |
| 24 | + * Closure Compiler will occasionally wrap ArrowFunctionExpression Parameters with additional parenthesis. |
| 25 | + * e.g (a)=>a.foo() => a=>a.foo() |
| 26 | + * |
| 27 | + * @see https://astexplorer.net/#/gist/20d7fbe32292c6c9f303c1d9643885ec/6c97fabca987814cced795b8d3d078094e642264 |
| 28 | + */ |
| 29 | +export default class ArrowFunctionTransform extends Transform implements TransformInterface { |
| 30 | + /** |
| 31 | + * @param code source to parse, and modify |
| 32 | + * @return modified input source with computed literal keys |
| 33 | + */ |
| 34 | + public async postCompilation(code: string): Promise<TransformSourceDescription> { |
| 35 | + const source = new MagicString(code); |
| 36 | + const program = parse(code); |
| 37 | + |
| 38 | + walk.simple(program, { |
| 39 | + ArrowFunctionExpression(arrowFunction: ArrowFunctionExpression) { |
| 40 | + const functionRange: Range = arrowFunction.range as Range; |
| 41 | + const params = arrowFunction.params; |
| 42 | + if (params.length === 1) { |
| 43 | + const identifier = params[0]; |
| 44 | + if ('name' in identifier) { |
| 45 | + const paramRange: Range = params[0].range as Range; |
| 46 | + if (functionRange[0] !== paramRange[0]) { |
| 47 | + const bodyRange = arrowFunction.body.range as Range; |
| 48 | + source.overwrite(functionRange[0], bodyRange[0], `${identifier.name}=>`); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + return { |
| 56 | + code: source.toString(), |
| 57 | + map: source.generateMap().mappings, |
| 58 | + }; |
| 59 | + } |
| 60 | +} |
0 commit comments