How to use @ts-morph/common - 10 common examples

To help you get started, we’ve selected a few @ts-morph/common examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dsherret / ts-morph / packages / ts-morph / src / factories / DirectoryCache.ts View on Github external
addDirectory(directory: Directory) {
        const path = directory.getPath();
        const parentDirPath = FileUtils.getDirPath(path);
        const isRootDir = parentDirPath === path;

        // remove any orphans that have a loaded parent
        for (const orphanDir of this.orphanDirs.getValues()) {
            const orphanDirPath = orphanDir.getPath();
            const orphanDirParentPath = FileUtils.getDirPath(orphanDirPath);
            const isOrphanRootDir = orphanDirParentPath === orphanDirPath;
            if (!isOrphanRootDir && orphanDirParentPath === path)
                this.orphanDirs.removeByKey(orphanDirPath);
        }

        if (!isRootDir)
            this.addToDirectoriesByDirPath(directory);

        if (!this.has(parentDirPath))
            this.orphanDirs.set(path, directory);
github dsherret / ts-morph / packages / ts-morph / src / factories / DirectoryCache.ts View on Github external
addDirectory(directory: Directory) {
        const path = directory.getPath();
        const parentDirPath = FileUtils.getDirPath(path);
        const isRootDir = parentDirPath === path;

        // remove any orphans that have a loaded parent
        for (const orphanDir of this.orphanDirs.getValues()) {
            const orphanDirPath = orphanDir.getPath();
            const orphanDirParentPath = FileUtils.getDirPath(orphanDirPath);
            const isOrphanRootDir = orphanDirParentPath === orphanDirPath;
            if (!isOrphanRootDir && orphanDirParentPath === path)
                this.orphanDirs.removeByKey(orphanDirPath);
        }

        if (!isRootDir)
            this.addToDirectoriesByDirPath(directory);

        if (!this.has(parentDirPath))
            this.orphanDirs.set(path, directory);

        this.directoriesByPath.set(path, directory);
        if (!this.context.fileSystemWrapper.directoryExistsSync(path))
            this.context.fileSystemWrapper.queueMkdir(path);

        for (const orphanDir of this.orphanDirs.getValues()) {
github dsherret / ts-morph / packages / ts-morph / src / factories / DirectoryCache.ts View on Github external
private removeFromDirectoriesByDirPath(dirPath: string) {
        if (FileUtils.isRootDirPath(dirPath))
            return;
        const parentDirPath = FileUtils.getDirPath(dirPath);
        const directories = this.directoriesByDirPath.get(parentDirPath);
        if (directories == null)
            return;
        directories.removeByKey(FileUtils.getBaseName(dirPath));

        // clean up
        if (!directories.hasItems())
            this.directoriesByDirPath.removeByKey(parentDirPath);
    }
github dsherret / ts-morph / packages / ts-morph / src / structurePrinters / class / ClassDeclarationStructurePrinter.ts View on Github external
private printHeader(writer: CodeBlockWriter, structure: OptionalKind) {
        this.factory.forModifierableNode().printText(writer, structure);
        writer.write(`class`);
        // can be null, ex. `export default class { ... }`
        if (!StringUtils.isNullOrWhitespace(structure.name))
            writer.space().write(structure.name);
        this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters);
        writer.space();

        writer.hangingIndent(() => {
            if (structure.extends != null) {
                const extendsText = this.getText(writer, structure.extends);
                if (!StringUtils.isNullOrWhitespace(extendsText))
                    writer.write(`extends ${extendsText} `);
            }

            if (structure.implements != null) {
                const implementsText = structure.implements instanceof Array
                    ? structure.implements.map(i => this.getText(writer, i)).join(", ")
                    : this.getText(writer, structure.implements);
github dsherret / ts-morph / packages / ts-morph / src / compiler / ast / module / ImportSpecifier.ts View on Github external
renameAlias(alias: string) {
        if (StringUtils.isNullOrWhitespace(alias)) {
            this.removeAliasWithRename();
            return this;
        }

        let aliasIdentifier = this.getAliasNode();
        if (aliasIdentifier == null) {
            // trick is to insert an alias with the same name, then rename the alias. TS compiler will take care of the rest.
            this.setAlias(this.getName());
            aliasIdentifier = this.getAliasNode()!;
        }
        aliasIdentifier.rename(alias);
        return this;
    }
github dsherret / ts-morph / packages / ts-morph / scripts / inspectors / tsMorph / Mixin.ts View on Github external
getCoveredTsNodePropertyNames(): string[] {
        // this is done just to be fast... there's definitely a more correct way of doing this
        const sourceFile = this.node.getSourceFile();
        const propertyAccessExpressions = sourceFile.getDescendantsOfKind(tsMorph.SyntaxKind.PropertyAccessExpression);
        const names: string[] = [];

        for (const expr of propertyAccessExpressions) {
            if (expr.getText() !== "this.compilerNode")
                continue;
            const parent = expr.getParentIfKind(tsMorph.SyntaxKind.PropertyAccessExpression);
            if (parent == null)
                continue;
            names.push(parent.getName());
        }

        return [...names, ...ArrayUtils.flatten(this.getMixins().map(m => m.getCoveredTsNodePropertyNames()))];
    }
}
github dsherret / ts-morph / packages / ts-morph / src / compiler / ast / jsx / JsxElement.ts View on Github external
set(structure: Partial) {
        callBaseSet(JsxElementBase.prototype, this, structure);

        if (structure.attributes != null) {
            const openingElement = this.getOpeningElement();
            openingElement.getAttributes().forEach(a => a.remove());
            openingElement.addAttributes(structure.attributes);
        }

        // todo: deprecate bodyText when implementing this
        if (structure.children != null)
            throw new errors.NotImplementedError("Setting JSX children is currently not implemented. Please open an issue if you need this.");

        if (structure.bodyText != null)
            this.setBodyText(structure.bodyText);
        else if (structure.hasOwnProperty(nameof(structure.bodyText)))
            this.setBodyTextInline("");

        if (structure.name != null) {
            this.getOpeningElement().getTagNameNode().replaceWithText(structure.name);
            this.getClosingElement().getTagNameNode().replaceWithText(structure.name);
        }

        return this;
    }
github dsherret / ts-morph / packages / ts-morph / src / compiler / ast / base / GeneratorableNode.ts View on Github external
function getAsteriskInsertPos(node: Node) {
    if (node.getKind() === SyntaxKind.FunctionDeclaration)
        return node.getFirstChildByKindOrThrow(SyntaxKind.FunctionKeyword).getEnd();

    const namedNode = node as any as NamedNode;

    /* istanbul ignore if */
    if (namedNode.getName == null)
        throw new errors.NotImplementedError("Expected a name node for a non-function declaration.");

    return namedNode.getNameNode().getStart();
}
github dsherret / ts-morph / packages / ts-morph / src / compiler / ast / base / export / ExportableNode.ts View on Github external
setIsDefaultExport(value: boolean) {
            if (value === this.isDefaultExport())
                return this;

            if (value && !TypeGuards.isSourceFile(this.getParentOrThrow()))
                throw new errors.InvalidOperationError("The parent must be a source file in order to set this node as a default export.");

            // remove any existing default export
            const sourceFile = this.getSourceFile();
            const fileDefaultExportSymbol = sourceFile.getDefaultExportSymbol();

            if (fileDefaultExportSymbol != null)
                sourceFile.removeDefaultExport(fileDefaultExportSymbol);

            if (!value)
                return this;

            // set this node as the one to default export
            if (TypeGuards.hasName(this) && shouldWriteAsSeparateStatement.call(this)) {
                const parentSyntaxList = this.getFirstAncestorByKindOrThrow(SyntaxKind.SyntaxList);
                const name = this.getName();
github dsherret / ts-morph / packages / ts-morph / src / manipulation / nodeHandlers / TryOrForgetNodeHandler.ts View on Github external
handleNode(currentNode: Node, newNode: ts.Node, newSourceFile: ts.SourceFile) {
        /* istanbul ignore next */
        if (!Node.isSourceFile(currentNode))
            throw new errors.InvalidOperationError(`Can only use a ${nameof(TryOrForgetNodeHandler)} with a source file.`);

        try {
            this.handler.handleNode(currentNode, newNode, newSourceFile);
        } catch (ex) {
            currentNode._context.logger.warn("Could not replace tree, so forgetting all nodes instead. Message: " + ex);
            // forget all the source file's nodes
            currentNode.getChildSyntaxListOrThrow().forget();
            // replace the source file with the temporary source file
            currentNode._context.compilerFactory.replaceCompilerNode(currentNode, newNode);
        }
    }
}