npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cannabis

v0.1.2

Published

TypeScript AST Query library

Downloads

74

Readme

Build Status Coverage Status

TypeScript AST Query Selector library

Based on the powerful astq AST Query engine and syntax language.

Contents

Playground

Try out this interactive TypeScript AST Query editor with examples to understand what this is all about.

Usage

npm install cannabis
import { queryAst } from 'cannabis'

const code = `
function f(o: any){
  for(let i in o)
    console.log(i)
}
class A{
  private method1(){
    for(var name in this)
      this.n.push(name)    
  }
}
`
// match Blocks containing ForInStatement direct children
const query = '//Block [ /ForInStatement ]'
const { result, error} = queryAst(query, code1)
if(error){
  // there was a query syntax error 
}else{
  result.map(node=>console.log(node.getStart(), node.getEnd()))
}

From string

From ts.Node

Loading projects

cannabis supports AST Nodes of type File and Directory, so it's possible to load a project or folder or sets of files as AST Nodes.

TODO example

Attributes

In general attributes will return a value if there is something to return, empty array, empty string, false or 0 for those types if there is no value to return, and null if thevalue is an object or there was an error.

@text

@text - string

returns current node's text as in ts.Node#getText(). Example:

// VariableDeclaration [ @text!~'2' ]

@name

@name - string

There are node kinds that have name, like InterfaceDeclaration, and others that don't, like IfStatement. Example: // * [ @name=='f' && @modifiers=~'export' ]

@modifiers

@modifiers - string

A comma separated modifier names in "export","default","declare","abstract","public","protected","private","readonly","static","async","const".

Example:

// PropertyDeclaration [ @modifiers=~'private' || @modifiers=~'protected' ]

If the node has no modifiers at all it returns empty string.

@type

@type - string

Returns current node's type string representation.

If type is not declared it will be inferrer form usage.

If type doesn't apply to current node it will return empty string.

Examples:

// VariableDeclaration [ @type=='Date[]'],

// Parameter [ @type=='boolean' || @type=='number']

@expression

@expression - Node (ts-morph Node instance)

Returns a AST Node if the node has an expression, or null other wise.

Examples: TODO

@literalText

Gets the literal text of a literal-like node , example

// LiteralString [compareText({forbidden}, @literalText, 'verb:equals,caseSensitive:true']

@start

Returns the position of current node in its source file.

@end

Returns the position of current node's end, in its source file.

@width

Returns the amount of characters of current node.

@body

Return current node's body node, or null if it doesn't have a body.

@leadingComments

Returns the text of comments before this node.

@trailingComments

Returns the text of comments after this node.

@indexPath

Returns a child-index based path for the node, similar to src/services/login/loginService/2/1

@kindPath

Returns a node kind based path for the node, like src/services/login/loginService/InterfaceDeclaration/Identifier. Notice that unlike @indexPath, this doesn't necessarily points to the node.

@namePath

Returns a node-name based path for current node, like src/services/login/loginService/LoginService/method1/param1. Notice that unlike @indexPath, this doesn't necessarily points to the node. If a node doesn't have a name, its kind name will be printed in the path instead.

Functions

The following are custom function that can be used in the queries directly, added to standard query functions of astq library, related to TypeScript AST.

isFunctionLike

  • isFunctionLike(arg?) - boolean

Returns true if current node kind is function like, this is a callable node like FunctionDeceleration, MethodDeclaration, ArrowFunction, etc.

Examples:

//* [ isFunctionLike() && type() != ConstructorDeclaration]

extendsAnyNamed

Supports two signatures:

extendsAnyNamed(name: string) - boolean extendsAnyNamed(node: ASTNode, name: string|string[]) - boolean

Returns true if current node (or given node given as parameter) extends any class or interface (directly or indirectly) which name is included in names parameter. If names is a string then it will be split using ','.

Example: //ClassDeclaration [extendsAnyNamed('Base,ExternalBase')]: Returns true if current node ClassDeclaration extends (directly or indirectly) a class named 'Base' OR 'ExternalBase'.

Example: Identifier [extendsAnyNamed(parent(), {names}): Returns true if current node's parent extends (directly or indirectly) a type with name included in names parameter.

Take into account that it will search across all extends HeritageClauses, (directly or indirectly) so it's an expensive operation. Also remember that an interface can extend both interfaces and classes. Examples:

extendsAllNamed

implementsAnyNamed

implementsAnyNamed(name: string): boolean

Returns true if current node (class declaration) implements recursively an interface with given name.

Take into account that it will search across all implemented HeritageClauses of all interfaces implemented by super classes and also interfaces extended by super interfaces, recursively.

Examples:

//ClassDeclaration [implementsAnyNamed('Touchable')]

implementsAllNamed

sourceFile

sourceFile(node?: ASTNode): ASTNode | null

Returns current sourceFile Node.

findReferences

(node?: ASTNode): ASTNode[]

Returns an array of Nodes which are referencing current node. If a project was used as starting node, and current node is exported, then it could return references of nodes in other files.

If an argument is passed it will return the references of that node.

Examples:

Find unused variables:

// VariableDeclaration [@modifiers!~'export' && count(findReferences())==0]

Passing a node argument:

// Identifier [@name=='Foo22' && count(findReferences(parent()))>=0]

debug(...args?: any[]): true

Examples:

// Identifier [..//* && debug(count(findReferences()), kindName(), @name) && count(findReferences())==2]

includes

includes(a: string | any[], b: any): boolean

parent

parent(arg?ASTNode): ASTNode|null

children

children(arg?:ASTNode): ASTNode[]

sourceFile

Gets given node's SourceFile or current node's if no node is given.

Query Syntax

  • ASTQ Query syntax
  • Based on https://github.com/rse/astq
  • This is a very WIP project...
  • Helper functions to reference high level AST concepts will be added & documented

TODO

See TODO.md