function createTslibImport(node, useRequire = false) {
    const name = getVariableStatementName(node);
    if (!name) {
        return node;
    }
    if (useRequire) {
        // Use `var __helper = /*@__PURE__*/ require("tslib").__helper`.
        const requireCall = ts.createCall(ts.createIdentifier('require'), undefined, [ts.createLiteral('tslib')]);
        const pureRequireCall = ts.addSyntheticLeadingComment(requireCall, ts.SyntaxKind.MultiLineCommentTrivia, '@__PURE__', false);
        const helperAccess = ts.createPropertyAccess(pureRequireCall, name);
        const variableDeclaration = ts.createVariableDeclaration(name, undefined, helperAccess);
        const variableStatement = ts.createVariableStatement(undefined, [variableDeclaration]);
        return variableStatement;
    }
    else {
        // Use `import { __helper } from "tslib"`.
        const namedImports = ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))]);
        // typescript@2.4 is needed for a fix to the function parameter types of ts.createImportClause.
        // https://github.com/Microsoft/TypeScript/pull/15999
        // Hiding it from lint until we upgrade.
        // tslint:disable-next-line:no-any
        const importClause = ts.createImportClause(undefined, namedImports);
        const newNode = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral('tslib'));
        return newNode;
    }
}
 _NodeEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt) {
     if (stmt.hasModifier(compiler_1.StmtModifier.Exported) && stmt.value instanceof compiler_1.ExternalExpr &&
         !stmt.type) {
         // check for a reexport
         var _a = stmt.value.value, name_1 = _a.name, moduleName = _a.moduleName;
         if (moduleName) {
             var reexports = this._reexports.get(moduleName);
             if (!reexports) {
                 reexports = [];
                 this._reexports.set(moduleName, reexports);
             }
             reexports.push({ name: name_1, as: stmt.name });
             return null;
         }
     }
     var varDeclList = ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createIdentifier(stmt.name), 
         /* type */ undefined, (stmt.value && stmt.value.visitExpression(this, null)) || undefined)]);
     if (stmt.hasModifier(compiler_1.StmtModifier.Exported)) {
         // Note: We need to add an explicit variable and export declaration so that
         // the variable can be referred in the same file as well.
         var tsVarStmt = this.record(stmt, ts.createVariableStatement(/* modifiers */ [], varDeclList));
         var exportStmt = this.record(stmt, ts.createExportDeclaration(
         /*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(stmt.name, stmt.name)])));
         return [tsVarStmt, exportStmt];
     }
     return this.record(stmt, ts.createVariableStatement(this.getModifiers(stmt), varDeclList));
 };
function createWrappedEnum(name, hostNode, statements, literalInitializer) {
    literalInitializer = literalInitializer || ts.createObjectLiteral();
    const innerVarStmt = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
        ts.createVariableDeclaration(name, undefined, literalInitializer),
    ]));
    const innerReturn = ts.createReturn(ts.createIdentifier(name));
    const iife = ts.createImmediatelyInvokedFunctionExpression([
        innerVarStmt,
        ...statements,
        innerReturn,
    ]);
    return updateHostNode(hostNode, ts.createParen(iife));
}
function createTslibImport(name, useRequire = false) {
    if (useRequire) {
        // Use `var __helper = /*@__PURE__*/ require("tslib").__helper`.
        const requireCall = ts.createCall(ts.createIdentifier('require'), undefined, [ts.createLiteral('tslib')]);
        const pureRequireCall = ts.addSyntheticLeadingComment(requireCall, ts.SyntaxKind.MultiLineCommentTrivia, '@__PURE__', false);
        const helperAccess = ts.createPropertyAccess(pureRequireCall, name);
        const variableDeclaration = ts.createVariableDeclaration(name, undefined, helperAccess);
        const variableStatement = ts.createVariableStatement(undefined, [variableDeclaration]);
        return variableStatement;
    }
    else {
        // Use `import { __helper } from "tslib"`.
        const namedImports = ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))]);
        const importClause = ts.createImportClause(undefined, namedImports);
        const newNode = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral('tslib'));
        return newNode;
    }
}
Exemple #5
0
function createWrappedEnum(name, hostNode, statements, literalInitializer) {
    const pureFunctionComment = '@__PURE__';
    literalInitializer = literalInitializer || ts.createObjectLiteral();
    const innerVarStmt = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
        ts.createVariableDeclaration(name, undefined, literalInitializer),
    ]));
    const innerReturn = ts.createReturn(ts.createIdentifier(name));
    // NOTE: TS 2.4+ has a create IIFE helper method
    const iife = ts.createCall(ts.createParen(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock([
        innerVarStmt,
        ...statements,
        innerReturn,
    ]))), undefined, []);
    // Update existing host node with the pure comment before the variable declaration initializer.
    const variableDeclaration = hostNode.declarationList.declarations[0];
    const outerVarStmt = ts.updateVariableStatement(hostNode, hostNode.modifiers, ts.updateVariableDeclarationList(hostNode.declarationList, [
        ts.updateVariableDeclaration(variableDeclaration, variableDeclaration.name, variableDeclaration.type, ts.addSyntheticLeadingComment(iife, ts.SyntaxKind.MultiLineCommentTrivia, pureFunctionComment, false)),
    ]));
    return outerVarStmt;
}
 function transformFactorySourceFile(factoryMap, context, coreImportsFrom, file) {
     // If this is not a generated file, it won't have factory info associated with it.
     if (!factoryMap.has(file.fileName)) {
         // Don't transform non-generated code.
         return file;
     }
     var _a = factoryMap.get(file.fileName), moduleSymbolNames = _a.moduleSymbolNames, sourceFilePath = _a.sourceFilePath;
     var clone = ts.getMutableClone(file);
     var transformedStatements = file.statements.map(function (stmt) {
         if (coreImportsFrom !== null && ts.isImportDeclaration(stmt) &&
             ts.isStringLiteral(stmt.moduleSpecifier) && stmt.moduleSpecifier.text === '@angular/core') {
             var path = path_1.relativePathBetween(sourceFilePath, coreImportsFrom.fileName);
             if (path !== null) {
                 return ts.updateImportDeclaration(stmt, stmt.decorators, stmt.modifiers, stmt.importClause, ts.createStringLiteral(path));
             }
             else {
                 return ts.createNotEmittedStatement(stmt);
             }
         }
         else if (ts.isVariableStatement(stmt) && stmt.declarationList.declarations.length === 1) {
             var decl = stmt.declarationList.declarations[0];
             if (ts.isIdentifier(decl.name)) {
                 var match = STRIP_NG_FACTORY.exec(decl.name.text);
                 if (match === null || !moduleSymbolNames.has(match[1])) {
                     // Remove the given factory as it wasn't actually for an NgModule.
                     return ts.createNotEmittedStatement(stmt);
                 }
             }
             return stmt;
         }
         else {
             return stmt;
         }
     });
     if (!transformedStatements.some(ts.isVariableStatement)) {
         // If the resulting file has no factories, include an empty export to
         // satisfy closure compiler.
         transformedStatements.push(ts.createVariableStatement([ts.createModifier(ts.SyntaxKind.ExportKeyword)], ts.createVariableDeclarationList([ts.createVariableDeclaration('ɵNonEmptyModule', undefined, ts.createTrue())], ts.NodeFlags.Const)));
     }
     clone.statements = ts.createNodeArray(transformedStatements);
     return clone;
 }
 _NodeEmitterVisitor.prototype.visitTryCatchStmt = function (stmt) {
     return this.record(stmt, ts.createTry(this._visitStatements(stmt.bodyStmts), ts.createCatchClause(CATCH_ERROR_NAME, this._visitStatementsPrefix([ts.createVariableStatement(
         /* modifiers */ undefined, [ts.createVariableDeclaration(CATCH_STACK_NAME, /* type */ undefined, ts.createPropertyAccess(ts.createIdentifier(CATCH_ERROR_NAME), ts.createIdentifier(CATCH_STACK_NAME)))])], stmt.catchStmts)), 
     /* finallyBlock */ undefined));
 };
 const standardTransform = function (sourceFile) {
     const ops = [];
     if (!shouldTransform(sourceFile.fileName)) {
         return ops;
     }
     const replacements = findResources(sourceFile);
     if (replacements.length > 0) {
         // Add the replacement operations.
         ops.push(...(replacements.map((rep) => rep.replaceNodeOperation)));
         // If we added a require call, we need to also add typings for it.
         // The typings need to be compatible with node typings, but also work by themselves.
         // interface NodeRequire {(id: string): any;}
         const nodeRequireInterface = ts.createInterfaceDeclaration([], [], 'NodeRequire', [], [], [
             ts.createCallSignature([], [
                 ts.createParameter([], [], undefined, 'id', undefined, ts.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
             ], ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)),
         ]);
         // declare var require: NodeRequire;
         const varRequire = ts.createVariableStatement([ts.createToken(ts.SyntaxKind.DeclareKeyword)], [ts.createVariableDeclaration('require', ts.createTypeReferenceNode('NodeRequire', []))]);
         ops.push(new interfaces_1.AddNodeOperation(sourceFile, ast_helpers_1.getFirstNode(sourceFile), nodeRequireInterface));
         ops.push(new interfaces_1.AddNodeOperation(sourceFile, ast_helpers_1.getFirstNode(sourceFile), varRequire));
     }
     return ops;
 };
Exemple #9
0
 var varDecls = declarations.map(function (i) { return ts.createVariableDeclaration(i.name, /* type */ undefined, i.node); });
 const standardTransform = function (sourceFile) {
     const ops = [];
     const lazyRoutes = lazyRoutesCb();
     if (!shouldTransform(sourceFile.fileName)) {
         return ops;
     }
     const dirName = path.normalize(path.dirname(sourceFile.fileName));
     const modules = Object.keys(lazyRoutes)
         .map((loadChildrenString) => {
         const [, moduleName] = loadChildrenString.split('#');
         const modulePath = lazyRoutes[loadChildrenString];
         return {
             modulePath,
             moduleName,
             loadChildrenString,
         };
     });
     modules.forEach((module, index) => {
         const modulePath = module.modulePath;
         if (!modulePath) {
             return;
         }
         let relativePath = path.relative(dirName, modulePath).replace(/\\/g, '/');
         if (!(relativePath.startsWith('./') || relativePath.startsWith('../'))) {
             // 'a/b/c' is a relative path for Node but an absolute path for TS, so we must convert it.
             relativePath = `./${relativePath}`;
         }
         // Create the new namespace import node.
         const namespaceImport = ts.createNamespaceImport(ts.createIdentifier(`__lazy_${index}__`));
         const importClause = ts.createImportClause(undefined, namespaceImport);
         const newImport = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(relativePath));
         const firstNode = ast_helpers_1.getFirstNode(sourceFile);
         if (firstNode) {
             ops.push(new interfaces_1.AddNodeOperation(sourceFile, firstNode, newImport));
         }
     });
     const lazyModuleObjectLiteral = ts.createObjectLiteral(modules.map((mod, idx) => {
         let [modulePath, moduleName] = mod.loadChildrenString.split('#');
         if (modulePath.match(/\.ngfactory/)) {
             modulePath = modulePath.replace('.ngfactory', '');
             moduleName = moduleName.replace('NgFactory', '');
         }
         return ts.createPropertyAssignment(ts.createLiteral(`${modulePath}#${moduleName}`), ts.createPropertyAccess(ts.createIdentifier(`__lazy_${idx}__`), mod.moduleName));
     }));
     const lazyModuleVariableStmt = ts.createVariableStatement([ts.createToken(ts.SyntaxKind.ExportKeyword)], [ts.createVariableDeclaration('LAZY_MODULE_MAP', undefined, lazyModuleObjectLiteral)]);
     const lastNode = ast_helpers_1.getLastNode(sourceFile);
     if (lastNode) {
         ops.push(new interfaces_1.AddNodeOperation(sourceFile, lastNode, undefined, lazyModuleVariableStmt));
     }
     return ops;
 };