ajafff / tsutils Goto Github PK
View Code? Open in Web Editor NEWutility functions for working with typescript's AST
License: MIT License
utility functions for working with typescript's AST
License: MIT License
With TypeScript 3.0.0-rc, below failures.
Apparently it's now possible for Nodes to not have any tokens, which I'm not sure how to fix.
The other issues look minor, just some adjusted signatures.
test/rules/control-flow/testCfaRule.ts:32:34 - error TS2345: Argument of type 'Node | undefined' is not assignable to parameter of type 'Node'.
Type 'undefined' is not assignable to type 'Node'.
32 ctx.addFailureAtNode(node.getFirstToken(ctx.sourceFile), 'control flow end');
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test/tokenTests.ts:67:45 - error TS2345: Argument of type 'Node | undefined' is not assignable to parameter of type 'Node'.
Type 'undefined' is not assignable to type 'Node'.
67 assert.isUndefined(getPreviousToken(sourceFile.getFirstToken()), 'Token');
~~~~~~~~~~~~~~~~~~~~~~~~~~
util/type.ts:87:5 - error TS2322: Type 'ReadonlyArray<Signature>' is not assignable to type 'Signature[]'.
Property 'push' is missing in type 'ReadonlyArray<Signature>'.
87 return type.getCallSignatures();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
util/type.ts:97:61 - error TS2345: Argument of type 'Type | undefined' is not assignable to parameter of type 'Type'.
Type 'undefined' is not assignable to type 'Type'.
97 for (const ty of unionTypeParts(checker.getApparentType(type))) {
~~~~
util/util.ts:85:41 - error TS2345: Argument of type 'Node' is not assignable to parameter of type 'Declaration'.
Property '_declarationBrand' is missing in type 'Node'.
85 return (ts.getCombinedModifierFlags(node) & flag) !== 0;
~~~~
util/util.ts:953:15 - error TS2339: Property 'unescapeIdentifier' does not exist on type 'typeof ts'.
953 return ts.unescapeIdentifier ? ts.unescapeIdentifier(node.text) : node.text;
~~~~~~~~~~~~~~~~~~
util/util.ts:953:39 - error TS2339: Property 'unescapeIdentifier' does not exist on type 'typeof ts'.
953 return ts.unescapeIdentifier ? ts.unescapeIdentifier(node.text) : node.text;
~~~~~~~~~~~~~~~~~~
I am getting this error while i try to install tsutill.
npm WARN [email protected] requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev but none is installed. You must install peer dependencies yourself.
tsc --version
Version 3.1.3
Handle nested LabeledStatements on a single IterationStatement or SwitchStatement.
Related: #24
Branch | Build failing π¨ |
---|---|
Dependency |
tslib
|
Current Version | 1.9.1 |
Type | dependency |
This version is covered by your current version range and after updating it in your project the build failed.
tslib is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.
Fixes issues in the __generator
helper regarding return
-ing and throw
-ing. Details are available on Microsoft/TypeScript#24463
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
CFA could be even more powerful if it constructs a full control flow graph that users can inspect.
Ref: fimbullinter/wotan#160
Ref: fimbullinter/wotan#165
getUsageDomain
should handle NamedTypeArgument
once microsoft/TypeScript#23696 lands.
microsoft/TypeScript#20324 adds support for numeric separators, e.g. 1_000_000
.
Ensure that isValidNumericLiteral
and isValidPropertyName
function correctly after the PR landed upstream.
collectVariableUsage
only collect variable with variable declaration.
Can we get global variable usage such as process.env.REACT_APP_HOST
's process
or window.document
's window
?
/**
* First
*/
const firstVariable = true,
/**
* Second
*/
secondVariable = false;
import { getJsDoc } from "tsutils";
// Edit: not visitVariableStatement(node: VariableStatement)
function visitVariableDeclaration(node: VariableDeclaration) {
// Blank
getJsDoc(node);
// Always ["First"]
getJsDoc(node.parent);
}
Expected:
Calling getJsDoc
on a VariableStatement
should retrieve the docs for the node, even if they're also the docs for the containing VariableDeclarationList
.
Actual:
Only ever gets the docs for the VariableDeclarationList
.
drop support for typescript@<2.4?
Branch | Build failing π¨ |
---|---|
Dependency | tslib |
Current Version | 1.8.1 |
Type | dependency |
This version is covered by your current version range and after updating it in your project the build failed.
tslib is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.
This release introduces import helpers that are utilized by TypeScript 2.7's --esModuleInterop
flag for interoperability between ECMAScript modules and legacy module formats.
The new version differs by 4 commits.
3d0f4d4
Update version to '1.9.0'.
c380b8d
Merge pull request #43 from Microsoft/import-helpers
c1cd8e1
Remove erroneous semicolons from import star helper
b630cee
Add import helpers
See the full diff
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
let foo; // this `foo` is unused
(bar = () => foo, foo) => bar;
Currently the foo
parameter is marked as unused. Actually the outer variable foo
is unused.
The current API is somewhat difficult to use and does too much by analyzing the whole source file ahead of time.
The new API should return an object that can be used to:
optionally:
Needs a good name:
... once the proposal reaches stage 3 and is supported by TypeScript
Branch | Build failing π¨ |
---|---|
Dependency | @types/mocha |
Current Version | 2.2.47 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
@types/mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
Some recent (and not-so-recent) rule requests hinge on the ability to accurately detect the number of lines spanned by a given piece of code. Something like this would be very helpful:
const lineCount: number = getNewlineCount(node);
Of course, some variations may be needed, specifically the option to ignore lines w/ comments only.
When using tsutils with the latest Typescript (typescript@next, currently 2.8.0-dev.20180221), they appear to have renamed the TypeVariable interface to InstantiableType. This changed somewhere between commits afc588eb9e6322faf55bc28f26994712e3f02261 and edffb120549536cefd73409cc87f0439dac722cf but I didn't dig deep enough to see where.
If you simply change ts.TypeVariable to ts.InstantiableType in typeguard/type.ts, that fixes the compile error in tsutils, but I don't know if that has other side effects that need investigating, or if you want to rename the checks as a result of the TS renaming.
tsutils has a function findImports()
that finds imports where the argument to the import is a string literal:
const foo = require('foo');
but does not find imports where the argument is dynamically constructed:
const myPath = resolvePathSomehow();
const bar = require(myPath);
It would be handy to have a function that finds this second case for a library like tslint which has a linting rule no-require-imports
which should find all occurrences of the require()
function, regardless of its argument, but doesn't since it uses the current implementation of findImports()
. See this item.
Typescript v3 was released today
This issue is to track the tsutils
project compatibility with it
C:\Users\camer\ts\TsAst [base-class β‘ +0 ~4 -0 !]> tsc
node_modules/tsutils/util/usage.d.ts(30,74): error TS2304: Cannot find name 'Map'.
c:\Users\camer\ts\TsAst\node_modules\tsutils\util\usage.d.ts
export declare function collectVariableUsage(sourceFile: ts.SourceFile): Map<ts.Identifier, VariableInfo>;
"dependencies": {
"@types/node": "^8.0.51",
"tsutils": "^2.12.2",
"typescript": "^2.6.1"
},
if (true)
throw 'end';
while (false)
break outer; // never executed
for (;;)
return; // always executed
do {
continue; // this is guaranteed to be executed
} while (false);
for (const e of [])
throw 'never executed - needs type information';
TODO: determine if this should use type information if available
See ajafff/tslint-consistent-codestyle#85
type Values<T> = T extends {[K in keyof T]: infer U} ? U : never;
Expected:
U
in the then branch of the conditional type references infer U
inside the mapped type.
Actual:
infer U
has no uses.
endsControlFlow
applies some special handling to iteration statements (and switch) if they are the child of a LabeledSatement.
This behavior is not quite correct since there may be multiple nested labels.
Either way the result may be surprising.
Decide whether this is a bugfix or a breaking change.
Name typo.
See discussion in microsoft/tslint-microsoft-contrib#469 (comment):
Using tsc v2.6.2
node_modules/tsutils/util/util.d.ts(117,73): error TS1005: ';' expected.
node_modules/tsutils/util/util.d.ts(118,1): error TS1128: Declaration or statement expected.
node_modules/tsutils/util/util.d.ts(118,3): error TS1128: Declaration or statement expected.
node_modules/tsutils/util/util.d.ts(119,17): error TS1005: ',' expected.
node_modules/tsutils/util/util.d.ts(119,36): error TS1005: ';' expected.
node_modules/tsutils/util/util.d.ts(119,44): error TS1005: ';' expected.
node_modules/tsutils/util/util.d.ts(120,3): error TS1128: Declaration or statement expected.
tsutils lists its TypeScript dependency as allowing 2.1 and up. Two issues:
<Component/*comment*/</*comment*/any/*comment*/>/*comment*/></Component>;
<Component/*comment*/</*comment*/any/*comment*/>/*comment*//>;
Would be helpful to have this utility.
If the loop body isn't executed once due to the condition, there will be no jump.
That's not true for do { jump; } while (condition);
we are still on typescript 2.8 and we are having such error with latest version 2.27.2 :
node_modules/tsutils/typeguard/node.d.ts:67:69 - error TS2694: Namespace 'ts' has no exported member 'ImportTypeNode'.
67 export declare function isImportTypeNode(node: ts.Node): node is ts.ImportTypeNode;
on 2.27.1 it was fine because this line was under // @internal
was this change made by accident, or we just have to stay on 2.27.1 until we upgrade to 2.9 typescript?
2.8 typescript is still supported if I read correctly your package.json
Branch | Build failing π¨ |
---|---|
Dependency |
@types/mocha
|
Current Version | 5.2.0 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
@types/mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
Node.js v4 is EOL at the end of April 2018
Affects
The 'no-misused-new' rule threw an error in 'D:/Code/WebClient/src/typings/lib.dom.custom.d.ts':
TypeError: ts.unescapeIdentifier is not a function
at getIdentifierText (D:\Code\WebClient\node_modules\tsutils\util\util.js:872:15)
at Object.getPropertyName (D:\Code\WebClient\node_modules\tsutils\util\util.js:208:61)
at cb (D:\Code\WebClient\node_modules\tslint\lib\rules\noMisusedNewRule.js:51:27)
at visitNodes (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15098:30)
at Object.forEachChild (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15404:21)
at cb (D:\Code\WebClient\node_modules\tslint\lib\rules\noMisusedNewRule.js:67:19)
at visitNodes (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15098:30)
at Object.forEachChild (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15324:24)
at walk (D:\Code\WebClient\node_modules\tslint\lib\rules\noMisusedNewRule.js:49:15)
Currently the project is giving this error:
tslint-eslint-rules/node_modules/tsutils/src/typeguard.d.ts(140,70): error TS2694: Namespace 'ts' has no exported member 'EnumLiteralType'.
Updated all the packages to try to fix it, i noticed that this project has ts ^2.4.0 which is making wonder if their 2.4.1 broke it. I also installed ts 2.4.0 and the error still remains.
isTypeScopeBoundary
isFunctionScopeBoundary
ScopeBoundarySelector
export const enum ScopeBoundary {
None = 0,
Function = 1,
Block = 2,
Type = 4,
}
export const enum ScopeBoundarySelector {
Function = ScopeBoundary.Function,
Block = Function | ScopeBounary.Block,
Type = Block | ScopeBoundary.Type,
}
class Foo {}
function identity<T>(p: T) {
return p;
}
(class Foo extends identity(Foo) { // references the class expression instead of the outer class declaration
});
1 as const
has a TypeReferenceNode where the Identifier is const
. This is currently handled as reference to a type named const
. This is not a real problem, but needs to be handled eventually.
Branch | Build failing π¨ |
---|---|
Dependency |
@types/node
|
Current Version | 10.1.3 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
ConditionalTypes can introduce a new type variable with infer R
In some projects, I conditionally use longjohn when NODE_ENV !== 'production'
. This turns out to break some import/dependency checks I am implementing using tsutils
.
Source (yes, thatβs it):
require('longjohn');
Result:
TypeError: Cannot read property 'kind' of undefined
at ImportFinder._findNestedImports (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:1070:30)
at ImportFinder.find (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:1016:18)
at findImportLikeNodes (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:1001:48)
at Object.findImports (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:971:24)
at p.getSourceFiles.filter.forEach (/home/petter/lint_cmds/depcheck.js:50:6)
The relevant part of the lint command:
const ts = require('typescript');
const p = ts.createProgram(
tsFiles, // array of paths
JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'))
);
p.getSourceFiles().forEach((f) => tsutils.findImports(f, 1 | 2 | 16 | 32));
Given a fileName and a CompilerOptions object, determine the output file name(s).
It also needs an API to determine the output file name(s) for projects with outFile
.
This requires another helper function to determine the inferred or declared rootDir
of a given config.
Needed for fimbullinter/wotan#392
Related: microsoft/TypeScript#26410
Is there a way to get the moduleName
s for a SourceFile? They are all showing up as uknown
when I do this?
http://www.typescriptlang.org/docs/handbook/module-resolution.html
import * as ts from "typescript";
import * as fs from "fs";
// import {isTypeReference, isClassDeclaration} from "tsutils";
const tsPath = "node_modules/@types/mocha/index.d.ts"
const options: ts.CompilerOptions = { target: ts.ScriptTarget.ES2015 }
const host = ts.createCompilerHost(options, true);
const program = ts.createProgram([tsPath], options, host)
const checker = program.getTypeChecker()
for (const sf of program.getSourceFiles()){
console.log(sf.fileName + ": " + sf.moduleName)
}
C:\Users\camer\ts\TsAst [moduleName +1 ~0 -0 !]> node .\modulename.js
C:/Users/camer/ts/TsAst/node_modules/typescript/lib/lib.es6.d.ts: undefined
node_modules/@types/mocha/index.d.ts: undefined
C:/Users/camer/ts/TsAst/node_modules/@types/node/inspector.d.ts: undefined
C:/Users/camer/ts/TsAst/node_modules/@types/node/index.d.ts: undefined
Could you please add [email protected] support?
Would be nice to see a really good example of getting comments from TS using your package. I found out about tsutils
from this post but could not quite get it to work like I want.
I also tried an official example from Typescript but ran into problems as well.
Typescript Compiler Example for Type Checker
Issue I posted about the problem
Basically I can only ever get an object with the position of comments but not the text itself or anything else out of it.
Here is my code below:
import * as utils from 'tsutils';
import * as ts from 'typescript';
import {SourceFile} from 'typescript';
function generateDocumentation(
fileNames: string[],
options: ts.CompilerOptions
): void {
// Build a program using the set of root file names in fileNames
let program = ts.createProgram(fileNames, options);
// Visit every sourceFile in the program
for (const sourceFile of program.getSourceFiles()) {
if (!sourceFile.isDeclarationFile) {
// Walk the tree to search for classes
//ts.forEachChild(sourceFile, visit);
visit(sourceFile,sourceFile);
}
}
return;
/** visit nodes finding exported classes */
function visit(node: ts.Node, src: SourceFile) {
utils.forEachComment(node, (fullText: string, comment: ts.CommentRange) => {
console.log('--- The comment object looks like below ---');
console.dir(comment);
//this line definitely does not get the text of the comment, but what does????
var commentStr: ts.CommentRange = utils.getCommentAtPosition(src,comment.pos);
console.log('The comment text is ', commentStr);
console.log('--- --- --- --- ---');
});
}
}
generateDocumentation(
['src/controllers/testController.ts'],
{
target: ts.ScriptTarget.Latest,
module: ts.ModuleKind.CommonJS
}
);
Any chance of some more docs on how to use this package? A good example of getting and displaying comments would be sooooo useful.
finally
override everything from try
and catch
if exhaustive.try
needs to be filtered if there is a catch
clausecatch
only end control flow if try
AND catch
definitely end control flowAdding this issue following suggestion from @JoshuaKGoldberg in this comment
The MS export-name tslint rule could be a lot simpler if there were a utility which could answer the question "Given a list of statements, what is the set of symbols exported in that list?"
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.