|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2020 Google LLC |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +// eslint-disable-next-line import/no-extraneous-dependencies |
| 19 | +import * as ts from 'typescript'; |
| 20 | + |
| 21 | +// Location of file that includes the asserts |
| 22 | +const ASSERT_LOCATION = 'packages/firestore/src/util/assert.ts'; |
| 23 | + |
| 24 | +export function removeAsserts( |
| 25 | + program: ts.Program |
| 26 | +): ts.TransformerFactory<ts.SourceFile> { |
| 27 | + const removeAsserts = new RemoveAsserts(program.getTypeChecker()); |
| 28 | + return (context: ts.TransformationContext) => (file: ts.SourceFile) => { |
| 29 | + return removeAsserts.visitNodeAndChildren(file, context); |
| 30 | + }; |
| 31 | +} |
| 32 | + |
| 33 | +/** Transformer that removes all "debugAssert" statements from the SDK. */ |
| 34 | +class RemoveAsserts { |
| 35 | + constructor(private readonly typeChecker: ts.TypeChecker) {} |
| 36 | + |
| 37 | + visitNodeAndChildren<T extends ts.Node>( |
| 38 | + node: T, |
| 39 | + context: ts.TransformationContext |
| 40 | + ): T { |
| 41 | + return ts.visitEachChild( |
| 42 | + this.visitNode(node), |
| 43 | + (childNode: ts.Node) => this.visitNodeAndChildren(childNode, context), |
| 44 | + context |
| 45 | + ) as T; |
| 46 | + } |
| 47 | + |
| 48 | + visitNode(node: ts.Node): ts.Node { |
| 49 | + if (ts.isCallExpression(node)) { |
| 50 | + const signature = this.typeChecker.getResolvedSignature(node); |
| 51 | + if ( |
| 52 | + signature && |
| 53 | + signature.declaration && |
| 54 | + signature.declaration.kind === ts.SyntaxKind.FunctionDeclaration |
| 55 | + ) { |
| 56 | + const declaration = signature.declaration as ts.FunctionDeclaration; |
| 57 | + if ( |
| 58 | + declaration && |
| 59 | + declaration.getSourceFile().fileName.indexOf(ASSERT_LOCATION) >= 0 |
| 60 | + ) { |
| 61 | + const method = declaration.name!.text; |
| 62 | + if (method === 'debugAssert') { |
| 63 | + return ts.createEmptyStatement(); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + return node; |
| 69 | + } |
| 70 | +} |
0 commit comments