6.1.3 • Published 1 year ago

@phenomnomnominal/tsquery v6.1.3

Weekly downloads
197,199
License
MIT
Repository
github
Last release
1 year ago

TSQuery

npm version

TSQuery is a port of the ESQuery API for TypeScript! TSQuery allows you to query a TypeScript AST for patterns of syntax using a CSS style selector system.

Demos:

ESQuery demo - note that the demo requires JavaScript code, not TypeScript TSQuery demo by Uri Shaked

Installation

npm install @phenomnomnominal/tsquery --save-dev

Examples

Say we want to select all instances of an identifier with name "Animal", e.g. the identifier in the class declaration, and the identifier in the extends declaration.

We would do something like the following:

import { ast, query } from '@phenomnomnominal/tsquery';

const typescript = `

class Animal {
    constructor(public name: string) { }
    move(distanceInMeters: number = 0) {
        console.log(\`\${this.name} moved \${distanceInMeters}m.\`);
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

`;

const ast = ast(typescript);
const nodes = query(ast, 'Identifier[name="Animal"]');
console.log(nodes.length); // 2

Selectors

The following selectors are supported:

Common AST node types

  • Identifier - any identifier (name of a function, class, variable, etc)
  • IfStatement, ForStatement, WhileStatement, DoStatement - control flow
  • FunctionDeclaration, ClassDeclaration, ArrowFunction - declarations
  • VariableStatement - var, const, let.
  • ImportDeclaration - any import statement
  • StringLiteral - any string
  • TrueKeyword, FalseKeyword, NullKeyword, AnyKeyword - various keywords
  • CallExpression - function call
  • NumericLiteral - any numeric constant
  • NoSubstitutionTemplateLiteral, TemplateExpression - template strings and expressions

API:

ast:

Parse a string of code into an Abstract Syntax Tree which can then be queried with TSQuery Selectors.

import { ast } from '@phenomnomnominal/tsquery';

const sourceFile = ast('const x = 1;');

includes:

Check for Nodes within a given string of code or AST Node matching a Selector.

import { includes } from '@phenomnomnominal/tsquery';

const hasIdentifier = includes('const x = 1;', 'Identifier');

map:

Transform AST Nodes within a given Node matching a Selector. Can be used to do Node-based replacement or removal of parts of the input AST.

import { factory } from 'typescript';
import { map } from '@phenomnomnominal/tsquery';

const tree = ast('const x = 1;')
const updatedTree = map(tree, 'Identifier', () => factory.createIdentifier('y'));

match:

Find AST Nodes within a given AST Node matching a Selector.

import { ast, match } from '@phenomnomnominal/tsquery';

const tree = ast('const x = 1;')
const [xNode] = match(tree, 'Identifier');

parse:

Parse a string into an ESQuery Selector.

import { parse } from '@phenomnomnominal/tsquery';

const selector = parse(':matches([attr] > :first-child, :last-child)');

print:

Print a given Node or SourceFile to a string, using the default TypeScript printer.

import { print } from '@phenomnomnominal/tsquery';
import { factory } from 'typescript';

  // create synthetic node:
const node = factory.createArrowFunction(
  // ...
);
const code = print(node);

project:

Get all the SourceFiles included in a the TypeScript project described by a given config file.

import { project } from '@phenomnomnominal/tsquery';

const files = project('./tsconfig.json');

files:

Get all the file paths included ina the TypeScript project described by a given config file.

import { files } from '@phenomnomnominal/tsquery';

const filePaths = files('./tsconfig.json');

match:

Find AST Nodes within a given string of code or AST Node matching a Selector.

import {query } from '@phenomnomnominal/tsquery';

const [xNode] = query('const x = 1;', 'Identifier');

replace:

Transform AST Nodes within a given Node matching a Selector. Can be used to do string-based replacement or removal of parts of the input AST. The updated code will be printed with the TypeScript Printer, so you may need to run your own formatter on any output code.

import { replace } from '@phenomnomnominal/tsquery';

const updatedCode = replace('const x = 1;', 'Identifier', () => 'y'));
doc-props@mkoeglbynary/gens@infinitebrahmanuniverse/nolb-_phe@everything-registry/sub-chunk-714wzmsba-cli-dupschematics-for-reactschematics-for-vueredectemp-marvinirwin-lb4-cliscrypt-ts-transpilersvg-tslint-rulesinquirer-code-promptsipsumetmonaco-typescript-project-utilhow-depimport-pathlwc-extractmall-cloud-buildermeasure-tech-debtppflyprg-tslint-rulespostcss-angularnx-cargonx-code-modsnx-vscodenx-sonarqubeproductipngrx-tslint-rulesplayground-plugin-tsqueryng-modulonomorecrudnx-loopback-next-clinx-nest-dddrerumametsugar-bookrxjs-tslint-rulestsplottslint-etctypeof-jsonts-enhancetypestattypewiz-angularts-comment-predictorts-query-cli@apj-pace/pace-nx-plugin@appril/dev@ammarrabie/ngx-translate-extract@amplitude/ampli@angular-architects/ddd@angular-experts/ng-parsel@angular-extensions/lint-rules@angular-extensions/testing-library@asuncode/ng2element@aum_biosync/ngx-translate-extract@arck/architect@baloise/ds-styles@bartholomej/ngx-translate-extract@biesbjerg/ngx-translate-extract@betterer/cli@betterer/tsquery@christophbuehler/ngx-translate-extract@chrisczach/ngx-translate-extract@clacky-ai/jest-plugin@clarivate/ngx-translate-extract@cloud20x/cli@aaqilniz/cli@aaqilniz/cli-updated@6sigmadc/ngx-translate-extractunderhilltsdependts-spec-bootstrapperts-bigfish-plugin@farin/ngx-translate-extract@feinarbyte/pluginbase@field123/openapi-ep-typescript-codegen@gunnaway/ngx-translate-extract@hairy/api-generator@flycode-org/tsfind@foolishchow/tsutil@foolishchow/vue-cli-plugin-vuex-gen@evertz/bzlgen@gisaia/ngx-translate-extract@gmsca/ng2element@gmsca/ngdivolte@gmsca/setupbootstrap@gmsca/setupmaterial@lkit/create-code-react@loopback/cli@itly/itly@lzhoucs/nx-cypress@maxkuzmin/i18n-helper@mgruel/ngx-translate-extract@matheo/ionic-angular@matheo/ionic-react@ngneat/check-onpush@ngneat/transloco-keys-manager@neox/schematics@nativescript/schematics@nativescript/tslint-rules
6.1.0

1 year ago

6.0.1

1 year ago

6.0.0

1 year ago

6.1.2

1 year ago

6.1.1

1 year ago

6.0.2

1 year ago

6.1.3

1 year ago

5.0.1

2 years ago

5.0.0

3 years ago

4.2.0

3 years ago

4.1.1

4 years ago

4.1.0

5 years ago

4.0.0

5 years ago

3.0.0

6 years ago

2.2.0

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

2.0.0-beta.7

6 years ago

2.0.0-beta.6

6 years ago

2.0.0-beta.5

6 years ago

2.0.0-beta.4

7 years ago

2.0.0-beta.3

7 years ago

2.0.0-beta.2

7 years ago

2.0.0-beta.1

7 years ago

2.0.0-beta.0

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.1.0

7 years ago

0.1.0-beta.3

7 years ago

0.1.0-beta.2

7 years ago

0.1.0-beta.1

7 years ago

0.1.0-beta.0

7 years ago

0.1.0-beta

7 years ago