Giter Site home page Giter Site logo

sverweij / dependency-cruiser Goto Github PK

View Code? Open in Web Editor NEW
5.0K 22.0 248.0 61.01 MB

Validate and visualize dependencies. Your rules. JavaScript, TypeScript, CoffeeScript. ES6, CommonJS, AMD.

Home Page: https://npmjs.com/dependency-cruiser

License: MIT License

Makefile 0.05% JavaScript 95.64% HTML 1.63% TypeScript 1.63% CoffeeScript 0.07% Vue 0.10% Shell 0.03% SCSS 0.01% Svelte 0.01% Mermaid 0.61% D2 0.19% CSS 0.03%
dependency-cruiser typescript javascript static-analysis dependency-analysis dependency-graph circular-dependencies jsx tsx dependencies

dependency-cruiser's People

Contributors

0xflotus avatar ajafff avatar bashess avatar brmatt avatar christianvuerings avatar creative-ataraxia avatar danielo515 avatar davidparkagoda avatar dependabot[bot] avatar dignite avatar elektronik2k5 avatar forivall avatar friederbluemle avatar gaggle avatar greglockwood avatar jessitron avatar larsartmann avatar lukeapage avatar magland avatar martinslota avatar mh4gf avatar mrmckeb avatar neelance avatar quentindemetz avatar radiantly avatar rklos avatar soulhat avatar sverweij avatar vadimk7 avatar winner95 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dependency-cruiser's Issues

Not working on TypeScript classes

Tried to use the tool without much success

image

It shows that little despite AppManager having dozens of imports

image

For reference the command I'm using is

depcruise --max-depth 99 --output-type dot .\src\scripts\main.ts | dot -T svg > dependencygraph.svg

When I try to use it on the all folder the result is empty, meaning when I run:

depcruise --max-depth 99 --output-type dot src/scripts | dot -T svg > dependencygraph.svg

Expected Behavior

It should show dependencies

Current Behavior

It doesn't show dependencies

Windows Support (forward slashes instead of backslashes)

On Windows, dependency-cruiser extracts all modules and dependencies with backslashes \ in their names instead of forward slashes /. The backslashes are even shown in the HTML tables generated by the HTML reporter.

The main problem is that the default rules don't match backslashes as they are written with forward slashes. Thus, the rules cannot be written platform-agnostic.

Expected Behavior

dependency-cruiser should always use forward slashes.

Possible Solution

Maybe convert all backslashes to forward slashes?

Steps to Reproduce (for bugs)

On windows:

$ depcruise --validate .dependency-cruiser.json src

  error some-rule: src\cli.ts → src\content\entry\index.ts
...

Context

Development on Windows, CI/CD on Linux. I'd love to use dependency-cruiser without any changes on both platforms.

Your Environment

  • Version used: 2.10.1
  • Node version: 8.9.2
  • Operating System and version: Win10

false positive on no-orphans when file is only used for TypeScript types

Expected Behavior

A file should not be marked as no-orphans if it only exports types when these type exports are imported in other files.

Current Behavior

no-orphans is true if only types are imported from a file. There is no warning if the file also exports any other values but as long as types are the only thing that's exported from a file depcruise shows a no-orphans warning.

Possible Solution

depcruise should also check if types are imported and/or exported and not consider a file as orphaned if types are referenced

Steps to Reproduce (for bugs)

I found the bug(?) in a public repo of mine. Here is the file with the type exports:
https://github.com/manuelbieh/react-ssr-setup/blob/master/src/shared/store/app/types.ts

they are imported here: https://github.com/manuelbieh/react-ssr-setup/blob/master/src/shared/store/app/actions.ts#L1
and here: https://github.com/manuelbieh/react-ssr-setup/blob/master/src/shared/store/app/reducer.ts#L3

yet depcruise gives me the following result:

$ depcruise -c .dependency-cruiser.js --ts-config tsconfig.json src/
  warn no-orphans: src/shared/store/app/types.ts → src/shared/store/app/types.ts
× 1 dependency violations (0 errors, 1 warnings). 50 modules cruised.
  1. git clone [email protected]:manuelbieh/react-ssr-setup.git
  2. cd react-ssr-setup
  3. yarn install
  4. yarn lint:deps

Context

It's not really affecting me in a very dramatical way but it would still be nice if it worked without a warning

Your Environment

Option to make output in DOT use module path not resolved path if exists

Expected Behavior

Output for modules currently uses resolved path, would like the ability to use module path if it exists.

Current Behavior

Currently the path for sub modules, if using things like npm linking and webpack resolve gives you the relative path, ie ../../
This is ugly, i'd prefer to use the unresolved module path

change UTF-16 default format to something else

First of all, thank you!
I was waiting for this thing for a long time and din't find it until now :(

depcruise --exclude "^node_modules" --output-type rcdot src > test.dot
produces a UTF-16LE file (visible in Notepad++ / Encoding menu).

It breaks gv2gml and dottoxml conversions to gml format

Once converted to UTF-8 or ANSI and saved, you can user converters.

Expected Behavior

-encoding "ANSI" and/or -encoding "UTF8"?

Rules as a JS file i.e. .dependency-cruiser.js

Expected Behavior

It would be nice if the rules can be a .js file

Example:

yarn depcruise --validate .dependency-cruiser.js packages/*/src

Possible Solution

Detect config file extension and load it differently

Context

I'm trying to make general rules for the monorepo, but allow specific packages to extend them differently. For example, our frontend packages have different no-dev-dependency rules than our backend packages (toplevel front-end app packages have no real dependencies once fully built).

The JS file will define a set of common rules, then export 3 variants that extend them via Object.assign - backend apps, frontend apps, shared libraries. Individual packages will have their own .dependency-cruiser.js saying e.g.

module.exports = require('@our/build-tools/dependency-cruiser-rules').frontendApp;

This will also open up a lot of possibilities with regards to the configuration - e.g. "from" and "to" could take function predicates.

Analyze SASS files?

With default rules and the latest WebPack support, if a file contains import "./style.sass", this SASS file is also analyzed. But it can contain import paths that are not recognized by WebPack/Depcruise:

@import "vars" throws:

  error not-to-unresolvable: src/xxx.sass → vars
  error no-non-package-json: src/xxx.sass → vars

This can be valid outside of WebPack/Depcruise, because:

  • SASS automatically tries sass, scss, css extensions, while these extensions don't need to be in WebPack resolve.extensions config
  • sass-loader has separate includePaths option

For now, I excluded SASS files with "exclude": "\\.s[ac]ss$". The question is, should Depcruise improve support for such files, or always exclude them?

Thanks for great project btw!

Does not find inputs provided with absolute paths

When passing an absolute path as input to dependency-cruiser it exits with an error, because resolving the file fails.

For example.

$ dependency-cruise --validate .dependency-cruiser.js /Users/felix/Development/dashboard/src

  ERROR: ENOENT: no such file or directory, stat '/Users/felix/Development/dashboard/Users/felix/Development/dashboard/src'

Expected Behavior

dependency-cruiser should correctly determine that a provided input path is absolute and does not require prefixing it with a base path.

Current Behavior

dependency-cruiser prefixes every input path with a base path, preventing it from finding inputs specified with an absolute path.

Possible Solution

It appears that src/extract/gatherInitialSources.js is responsible for the concatenation. Ideally it would check every pThis before concatenating or use something like path.resolve instead.

The ideal solution would involve exposing a basePath option that allows customizing the behavior further.

Steps to Reproduce (for bugs)

  1. Call dependency-cruiser with an absolute path to the input file. It won't be resolved.

Context

We are trying to integrate this very useful tool into our project to prevent teams from importing other teams' code. Part of achieving this is running dependency-cruiser via lint-staged in a pre-commit hook. lint-staged passes absolute file paths to tools and dependency-cruiser seems to simply concat the input file paths with process.cwd(). Obviously this breaks.

Thanks for making such a great tool! I'd be happy to open a PR, but I'll need some more help getting the dev environment set up. I couldn't find a working build task in package.json. The build command exits without doing anything:

$ make dev-build
make: Nothing to be done for `dev-build'.

Your Environment

  • Version used: 4.12.0
  • Node version: 8.9.4
  • Operating System and version: macOS Mojave
  • Link to your project: closed-source

Duplicate edges with `--ts-config --ts-pre-compilation-deps`

Expected Behavior

In the dot output, between any pair of vertices A and B there is at most one directed edge from A to B.

Current Behavior

When using the --ts-config --ts-pre-compilation-deps CLI options and a tsconfig.json with "module": "commonjs", depcruise sometimes creates two outward edges to the same vertex.

Steps to Reproduce

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs"
  }
}

scratch/a.ts

import { foo } from './b';
foo();

scratch/b.ts

export function foo() {}

Now run depcruise --ts-config --ts-pre-compilation-deps -T dot scratch. Observe that the output contains:

    "scratch/a.ts" -> "scratch/b.ts"
    "scratch/a.ts" -> "scratch/b.ts"

Your Environment

  • Version used: 4.14.0
  • Node version: v10.14.1
  • TypeScript version: 3.3.1

API to make changes to the generated dot file (and others)

Thank you for your work. About the issue: Right now (AFAIK) there is no way to change the color of the background nodes or other visual aspects, for example if I want files with more than one class to show with red background there is no way to do it, I think there should be an api to easily customize the dot output based on logic written in a JavaScript file.

Possible Solution

An API with a good enough abstraction for such changes, something like

cruise.on('file-parsed', e => {
    if (e.file.defined.classes.length > 2) {
        e.file.output.fillcolor = 'red';
        e.file.output.label += ' [WARNING: MORE THAN 1 CLASS DEFINED ON THIS FILE]';
    }
})

The properties needed for such file object the most in my opinion are numberOfLines, defined.classes, defined.functions, exported.functions, exported.classes, exported.values (as in non-classes-and-non-function variables)

Feature request: "depth" option

I think it would be useful to have a "depth" option, to limit how deep dependency-cruiser goes to crawl the dependency tree?

e.g.: If "depth" is 3, it will only traverse from the root node down to 3 levels of dependencies.

The reason for this is that sometimes I'd like to see a higher-level view of the dependencies without needing to know every single "deep" dependency. Perhaps to get a feel for whether some set of files need to be broken out into a separate module. For large projects, seeing every dependency can create quite an overwhelming graph.

Thoughts?

exclude patterns exclude more than expected

Expected Behavior

passing an exclude pattern only exludes modules matching that pattern

Current Behavior

orphans (and maybe other modules?) don't show up in the output

Steps to Reproduce (for bugs)

depcruise -T dot src | dot -T png -Gdpi=192 > fixture.png

result:
fixture

Adding an exclude parameter e.g. like this

depcruise --exclude "^[a-z]+$" -T dot src | dot -T png -Gdpi=192 > less
.png

yields not only the exclusion of /^[a-z]+$/, but also of the orphans that are left after excluding:
less

Context

see #61

Your Environment

  • Version used: 4.7.0
  • Node version: 10
  • Operating System and version: NR

Typescript - TSConfig path is not taken into account

Feature Request

Expected Behavior

I want to create the dependency graph of my project.

My project structure is like this:
src/

  • main.ts
    • core/
      • magicalFile.ts

I am using in the "paths" option the TSConfig.json to create shortcuts for my imports.

relevant parts of tsconfig.json:

{
  ...
    "baseUrl": "src",
    "paths": {
      "@core/*": ["core/*"],
    }
...
}

in my main file "main.ts" i am importing other files with the shortcut.
import { MagicalClass } from '@core/magicalFile'

Now i try to create a dependency table.
dependency-cruiser -v -T html -f dependencyGraph.html ./src/main.ts

I would expect, that dependency-cruiser will take those settings in the tsconfig.json into account and follow the import shortcuts.

Current Behavior

Dependency-cruiser does not take the tsconfig settings into account and try´s to find
@core/magicalFile.ts in the directory @core. Which does not exist.
As a result the dependency graph ends at main.ts and only shows some not resolvable imports.

Possible Solution

It would be nice if, for typescript files, the path option in the tsconfig.json would be taken into account.

Context

For projects wit a certain size, the path-option helps to reduce the length of import statements and to make them more readable.

Your Environment

  • Version used: 4.3.2
  • Node version: 8
  • Operating System and version: Windows 10

Thank you in advance and warm regards

.tsx support

Hi!
The test fails with this code.

import {A as B} from "target";

dependency-cruiser is support {A as B} format?

Expected Behavior

Test successful

Current Behavior

error not-to-unresolvable: src/renderer.ts → ./process/renders/main/ui/render

Steps to Reproduce (for bugs)

  1. depcruise --init-rules
  2. import {render as appRender} from './process/renders/main/ui/render'; in src/renderer.ts
  3. export async function render(container: Element | null) {} in ./process/renders/main/ui/render.ts
  4. depcruise --validate .dependency-cruiser.json src

Your Environment

Add yarn pnp support

See yarnpkg/rfcs#101

Context & motivation

  • If the aforementioned PR lands and the benefits mentioned in the paper are true, it will get traction and dependency-cruiser will need to support it.
  • I'd like to play with it :-)

Possible implementations

  • use the webpack resolver in the sample app (which plugs into enhanced-resolve)
  • directly on.pnp.js? => might be necessary anyway for peeking into a module's config (check?)
  • advise node preloading (node -r ./.pnp.js?)use (?)
  • advise using yarn node (=> will that work => test)?
  • ... ?

notes

  • installConfig.pnp in package.json contains whether or not pnp is enabled (as long as pnp is experimental)
  • need for a new detection type? (regex matching with node_modules won't work anymore in path, exclude and donotfollow keys)
  • tools relying on crossing package boundaries in order to load their plugins need help

  • test semver-try-require with pnp

[Question] Mark as orphan if imported from `__test__` dir.

Greetings! Thanks so much for maintaining this great library- I really like it so far!

I have a question:

  • My Typescript project places unit tests in a number of __tests__ directories.
  • After large refactors, we sometimes end up with orphaned modules that don't show up as orphans because they have unit tests.

Is there a way to mark a module as an orphan if it is only used in a path containing the word __tests__?

Example:

  • foo.ts exports function bar() {}
  • __tests__/foo_test.ts imports bar from ../foo.tx
  • function bar() is an orphan, even though it is imported by __tests__/foo_test.ts

Empty png and svg files

Empty png and svg images.
Windows 10.

Running depcruise -x node_modules -T dot . | dot -T png > coffee-script-coffee-without-node_modules.png give me 0 KB invalid file.

Breaking change regarding symlinks in latest release

Updating to the latest release is breaking my build: https://circleci.com/gh/fimbullinter/wotan/11618

It seems that symlinks are resolved before looking up the package in package.json.

packages/bifrost/src/index.js imports from @fimbul/ymir where node_modules/@fimbul/ymir is a symlink to packages/ymir.

Before: packages/bifrost/src/index.js → node_modules/@fimbul/ymir/src/index.js
Now: packages/bifrost/src/index.js → packages/ymir/src/index.js

Therefore I now get tons of error no-non-package-json

I guess this is caused by your recent switch to pnp to resolve dependencies.

Steps to Reproduce (for bugs)

  1. check out fimbullinter/wotan@176571e
  2. yarn
  3. yarn check-dependencies

Your Environment

  • Version used: 4.15.0 (before 4.14.0)
  • Node version: 10 LTS
  • Operating System and version: Ubuntu?
  • Link to your project: see above

API: Subsequent calls to cruise will return same result even when file changed

I am not exactly sure if this is a BUG;

I'm trying to use dependency cruiser in a server that watches for file changes. On every file change, "cruise" will be called on all the files in the directory; however it doesn't change the final result of the call (even if the dependencies are modified in any way)

Expected Behavior

"cruise" call should return a correct scan result that reflects the current state of the modified files

Current Behavior

"cruise" call returns the scan result of the FIRST run. It seems that it keeps a cache of all scanned files.

Only display file names, not TypeScript classes

Expected Behavior

When running the following command:

npx depcruise -T dot -x node_modules -v -- src/index.ts | dot -T svg > dependencygraph.svg

I expect the Graph to display the TypeScript classes

Current Behavior

But it isn't, it just displays the file names:
Screenshot 2019-08-13 at 08 20 03

Possible Solution

No idea, am I missing something? 🤷‍♂

Steps to Reproduce (for bugs)

  1. npx depcruise -T dot -x node_modules -v -- src/index.ts | dot -T svg > dependencygraph.svg on a TypeScript project
  2. See "current behaviour"

Context

Just after initialization like this:

npx depcruise --init
? What format do you want your config file to be in? JSON
? Do you want to use a preset or a self-contained configuration? preset
? Pick a preset recommended, warn only (good starter choice)
? Looks like you're using TypeScript. Use a 'tsconfig.json'? Yes
? Full path to 'tsconfig.json': ./tsconfig.json
? Also regard TypeScript dependencies that exist only before compilation? Yes

  Successfully created '.dependency-cruiser.json'

Your Environment

  • Version used: [email protected]
  • Node version: v8.16.0
  • Operating System and version: OSX latest.
  • Link to your project: ø

Support webpack config resolution alias

Its not uncommon to see module resolution aliases in webpack land:

// webpack.config.js
resolve: {
    alias: {
      components: path.join(__dirname, 'src', 'components'),
      config: path.join(__dirname, 'src', 'config'),
      data: path.join(__dirname, 'src', 'data'),
      lib: path.join(__dirname, 'src', 'lib'),
      rdx: path.join(__dirname, 'src', 'rdx')
    }
  }

Is it possible to set up a rule to that can enable module resolution uisng webpack style aliases?

I love this program. Lots of fun.

Use glob for CLI arguments

Currently the CLI doesn't support globbing. That's not a problem on linux shells as they already expend glob patterns.
If I wanted to use the same command on Windows however, I get an error like ERROR: Can't open 'packages/*/src' for reading. Does it exist?.
Because of this, I cannot really use this package on a windows CI to test my dependencies.

It would be great if you could consider using glob to find the files.

As a side effect that also allows using extglob and globstar features even if the shell doesn't support that. You only need to wrap the glob pattern in quotes and let depcruise do the globbing instead of the shell.

Unable to generate a usable chart

Thanks for the great library. I'm trying to use it for our Vue project but even though the graph it generates is meaningful, it's impossible to track down the arrows and connections between the nodes.

Expected Behavior

I should be able to keep track of connections easily even though the graph will be huge.

Current Behavior

image

It kinda looks like this: :)
image

Possible Solution

We can make the graph much bigger or make the SVG interactive so that when I click the graph I can follow how the lines are connected to each other. I'm not sure how to do that using Graphviz but here is a D3 example: http://bl.ocks.org/robschmuecker/7880033

Steps to Reproduce (for bugs)

I can't share the SVG due to privacy reasons but let me know if you need more info. It probably happens in case a node has too many dependencies that are connected to each other.

Your Environment

  • Version used: Latest
  • Graphviz version: 2.40.1 (20161225.0304)
  • Link to your project: Private

Files resolved via webpack configured modules are categorised as "undetermined"

First off, thanks for the excellent work on this project. I've been waiting for #4 to be merged so I can use it in a webpack project, and it's working very nicely. I've found one issue with the new webpack resolution.

Expected behaviour

When a file contains an import from e.g. "shared/foo" which webpack resolves to a file in the local source tree (say ./src/shared/foo.ts), then dependency cruiser should classify the dependency as "local".

Current Behavior

The dependency is correctly mapped - the source and destination files paths are correctly resolved - but the dependency is classified as "undetermined".

Steps to Reproduce (for bugs)

Key files excerpted below, hopefully this is enough detail but let me know if you'd like me to make a working minimal repro.

src/A.ts:

import foo from "shared/B"

src/shared/B.ts

export default function X() {}

webpack.config.js

module.exports = {
  context: path.resolve(__dirname, "src"),
  resolve: {
    // treat all folders in src as modules
    modules: [path.resolve(__dirname, "src"), "node_modules"],
    extensions: [".ts", ".tsx", ".js", ".json"]
  }
}

.dependency-cruiser.json

// in "rules"
    {
      "name": "no-undetermined",
      "severity": "error",
      "comment": "Don't allow undetermined dependencies",
      "from": {
        "path": ".*"
      },
      "to": {
        "dependencyTypes": ["undetermined"]
      }
    }

CLI output

depcruise --validate .dependency-cruiser.json src/A.ts

error no-undetermined: src/A.ts → src/screens/B.ts

Context

Your Environment

  • Version used: 4.1.1
  • Node version: v8.11.2
  • Operating System and version: Mac OS 10.13.5
  • Link to your project: private, but can provide a public minimal reproduction if required

Feature request: TeamCity inspection format output

For all TeamCity users, it would be cool to have a "TeamCity inspections" output, like eslint-teamcity produces.

Example output (from es-lint): https://i.imgur.com/JXzBuaV.png

Context

Better discoverability / readability of the dependency violations. Further, if the file paths are reported, TeamCity renders links to them, so you could open the files in different IDEs (for example WebStorm).

Expected Behavior

Output dependency violations in the "TeamCity inspections service message" format. (Optionally, using the --format CLI parameter.)

Current Behavior

Only plain text.

Possible Solution

Either directly implement the TC format (e.g. using this package), or implement the eslint formatter contract, so that we could use eslint-teamcity or other formatter plugin libraries.

Only the first violation per import is reported

Expected Behavior

Consider the following config:

{
  "forbidden": [
    {
      "name": "no-core",
      "severity": "info",
      "from": {
        "path": "^src/"
      },
      "to": {
        "dependencyTypes": [
          "core"
        ]
      }
    },
    {
      "name": "no-fs",
      "severity": "error",
      "from": {},
      "to": {
        "dependencyTypes": [
          "core"
        ],
        "path": "^fs$"
      }
    }
  ],
  "allowed": [
    {
      "from": {
        "path": "^src/foo.js$"
      },
      "to": {
        "path": "^src/bar.js$"
      }
    }
  ]
}

and a file named src/foo.js with the following content:

require('fs');

I expect the following output:

warn not-in-allowed: src/foo.js → fs
info no-core: src/foo.js → fs
error no-fs: src/foo.js → fs

and a non-zero exit code.

Current Behavior

warn not-in-allowed: src/foo.js → fs

and exit code 0

Possible Solution

In validateAgainstRules use filter instead of find. Also don't return early if none of the allowed rules matched.

Or sort by severity and report the first violation with the highest severity.

Steps to Reproduce (for bugs)

See above

Context

I noticed this when updating to 3.0.0-beta-1. Once the not-in-allowed warnings were gone, I had a few errors which previously didn't show up.
I remembered to report it as I saw what causes is while reviewing #39

Also note if you remove the allowed section, you will only see the message with severity info which doesn't end the process with an non-zero exit code.

Your Environment

  • Version used:
  • Node version:
  • Operating System and version:
  • Link to your project:

[question] how to exclude builtin node modules like fs?

See above question. The builtin node modules are grayed out so depcruise already recognizes them, there must be some option I'm missing that would let me exclude them from the dot diagram.

depcruise --exclude "vscode" --output-type dot src | dot -T svg > dependencygraph.svg

dependencygraph

(diagram of arepl-vscode)

Feature request: Option to exclude dynamic imports

Now that dynamic import support is in, it'd be nice to have the option to not follow dynamic imports. Or at the very least, to exclude dynamic imports from a no-circular rule. AFAICT, there's no (documented) way to disable this though.

Context

We use dependency-cruiser to make sure there aren't any circular dependencies with static imports. We don't care so much about the dynamic ones though since they're less problematic than cycles affecting code that's run on module execution.

Possible Solution

Perhaps a noFollowDynamic option?

Color-coding of nodes by file type in dot/graphviz output

Expected Behavior

File nodes produced in dot "mode" would be color-coded based on file type. Maybe yellow for JavaScript, blue for TypeScript, etc. (This might be worth a separate issue request all together, but some sort of visual indication/highlighting of orphaned nodes---files that are neither reference other files nor are referenced by other files---could be very helpful too.)

Current Behavior

Currently all file nodes are the same pale yellow color regardless of file type.

Context

I'm using the graphviz dependency tree to help migrate a JavaScript project over to a TypeScript one, and color-coded nodes by file type would be extremely helpful for knowing what's already been converted, and what's left to do.

Fantastic project though! Been looking for something like this for a long time, great work!!

Ignore Files

I would like to ignore *.test.js files

From what I can tell -x doesn't match on filenames, only module names. It'd be nice not to see my test files without having to place them in a separate package.

"not-reachable" rule

Question (or feature request if it isn't possible at the moment)

Is it possible to declare an "not-reachable" rule, which is an extension of the "no-orphans" rule, but also checks for modules with outgoing imports. This rule would require to specify a list of "entry points".

Example

Given

src/index.js       -> src/mod_a.js
src/mod_a.js       -> src/mod_b.js
src/mod_orphan.js  -> src/mod_b.js

Then this rule should report src/mod_orphan.js as "not reachable" (given ["src/index.js"] as "entry point list").

Question: rule to enforce module encapsulation

Expected Behavior

I'd like to create a rule that would warn when a module imports/requires something directly from another folder that isn't exported in that folder's index.js/index.ts file.

Current Behavior

Possible Solution

Context

TypeScript absolute imports within project are shown as duplicate red boxes

First of all, thanks for working on this awesome utility!

I've tried running this on a big project and also have issues like #87, but more importantly, the graph is divided into two clusters due to some inconsistency between how the TypeScript compiler resolves modules and how depcruiser does it.

Imports like this:

import { appServices } from "./AppServices"

End up like this:

screen shot 2019-01-04 at 23 14 47

But imports like this:

import { appServices } from "app/AppServices"

End up as a duplicate in a different location like this:

screen shot 2019-01-04 at 23 14 19

GraphViz Error

Generating the .dot file works, but I'm having trouble getting dot to work...

 ❯❯❯ dependency-cruise -T dot -x node_modules src  > src.dot
 ❯❯❯ dot -T svg src.dot > src.svg
Assertion failed: (constraining_flat_edge(g,v,e) == FALSE), function flat_reorder, file mincross.c, line 1561.
[1]    6084 abort      dot -T svg src.dot > src.svg

Any ideas? Here's my dot file 👍

src.dot.zip

Use closest package.json instead of ./package.json

Expected Behavior

I have a monorepo with multiple packages. I want to cruise the whole repo at once to avoid unnecessary work.
To determine if a dependency of a file is an npm package declared in package.json depcruise looks at the package.json in the directory the command was executed.
In my case this is wrong, because each package has its own package.json and there is another one for development dependencies in the repo root.

package.json // dependencies: dependency-cruiser, glob
scripts
  \-- script.js // require('glob')
packages
  |-- a
  |   |-- index.js // require('foo')
  |   \-- package.json // dependencies: foo
  \-- b
      |-- src
      |    \-- index.js // require('bar')
      \-- package.json // dependencies: bar

Expected:

  • scripts/script.js uses ./package.json and is valid, because the dependency is listed
  • packages/a/index.js uses packages/a/package.json and is therefore valid
  • packages/b/src/index.js uses packages/b/package.json and is therefore valid

Current Behavior

Only the root package.json is looked at. The dependencies declared in the package.json files in subdirectories are ignored.
packages/a/index.js and packages/b/src/index.js are invalid.

Possible Solution

Always use the closest package.json for each file.

Your Environment

Include line numbers

Expected Behavior

I'd like to see line numbers for the original source

Current Behavior

No line numbers

Possible Solution

a "line": N, entry in the JSON output, and a <filename>:N in the normal text output

Context

I've got this one case that I can't figure out where a file has a bunch of imports and the last entry in the JSON output is:

        {
          "resolved": "",
          "coreModule": false,
          "followable": false,
          "couldNotResolve": true,
          "dependencyTypes": [
            "unknown"
          ],
          "module": "",
          "moduleSystem": "es6",
          "matchesDoNotFollow": false,
          "circular": false,
          "valid": false,
          "rules": [
            {
              "severity": "error",
              "name": "not-to-unresolvable"
            }
          ]
        }

I have no idea what this is and looking at the source files, everything looks good.

* in lhs of tsconfig paths don't get processed correctly

I love the idea of this project and have some ideas for further contributions!

But I can't seem to make it work. I'm not sure why, but NONE of my dependencies are found, specifically every import hits the included not-to-unresolvable rule. My project is 100% typescript.

It fails for:

  1. modules in node_modules
  2. local, relative dependencies
  3. inter-module dependencies (like uf/foo/bar imports uf/base/xhr,

All of these should be resolvable using the paths settings in tsconfig.json

Expected Behavior

I expect it to find these dependencies.

Current Behavior

All imports are marked invalid:
code like this:

import superagent from 'superagent';
import Swagger from 'swagger-client';
import { UFApiClient } from 'uf-api';
import { UFApiClient as UFManagementApiClient } from 'uf-api-management';
import warning from 'warning';

results in errors like this:

  error not-to-unresolvable: uf/base/xhr.ts → superagent
  error not-to-unresolvable: uf/base/xhr.ts → swagger-client
  error not-to-unresolvable: uf/base/xhr.ts → uf-api
  error not-to-unresolvable: uf/base/xhr.ts → uf-api-management
  error not-to-unresolvable: uf/base/xhr.ts → warning

Possible Solution

No idea!

Steps to Reproduce (for bugs)

Our project is quite large, our setup is as follows:

  1. package.json has "name": "uf"
  2. source code is in the directory uf
  3. There are other directories here: uf-api and uf-api-management - I realize these should be separate packages but they aren't right now.
  4. tsconfig has paths:
    "paths": {
      "*": ["types/*"],
      "integration/*": ["integration/*"],
      "uf-api-management": ["uf-api-management"],
      "uf-api-management/*": ["uf-api-management/*"],
      "uf-api": ["uf-api"],
      "uf-api/*": ["uf-api/*"],
      "uf/*": ["uf/*"]
    },

Context

Just trying it by installing globally, and also installing directly into the project.

Your Environment

  • Version used: 4.13.1
  • Node version: 10.15.1
  • Operating System and version: OSX
  • Link to your project: (not open source)

ERROR: must provide pattern

When the pFileDir is a absolute path which is same with process.cwd(),it will throw an error

ERROR: must provide pattern

Expected Behavior

It should return the result.

Current Behavior

It reports error.

Possible Solution

In src/main/filesAndDirs/normalize.js , the relativize function will return empty, thus glob.sync receives an empty string.

Steps to Reproduce (for bugs)

  1. Install dependency-cruiser
  2. run
depcruise --exclude "^node_modules" --output-type csv `pwd`

Context

I'm using the api to get the dependency tree of a certain directory.

Your Environment

  • Version used: 4.15.3
  • Node version: v11.13.0
  • Operating System and version: Mac OS X 10.14.3
  • Link to your project:

Generate dependencies among methods / interfaces?

Hi, cool project!

Expected Behavior

Is it feasible with current tools to output a dependency graph not only among files, but among any symbol which can return output from "find references"? A dependency graph among files is helpful, but being able to cruise dependencies among any symbol would take this to a whole other level to aid in fine-grained code examination.

Context

I want to load this dependency graph into a graph database and supplement with javadoc descriptions in order to generate fine-grained code documentation searchable as a web, rather than existing doc tools which output a hierarchy without rich links based on references.

Add dynamic import support

Expected Behavior

Add dynamic import support. It is widely used in lazy loading and code splitting scenarios.

Current Behavior

Now all dependencies imported using import() won't be added to the graph.

Possible Solution

Context

import() now is a proposal:
https://github.com/tc39/proposal-dynamic-import

Webpack lazy loading and code splitting:
https://webpack.js.org/guides/lazy-loading/
https://webpack.js.org/guides/code-splitting/

React code splitting
https://reactjs.org/docs/code-splitting.html

Option to treat warnings as errors

Because my package dependencies are a bit special (same package in peerDependencies and devDependencies), I cannot use forbidden rules to express what kinds of npm dependencies are allowed. Therefore I use allowed rules: https://github.com/fimbullinter/wotan/blob/7866ba356e39b66aa0ea4817bd8ae2afa17d5baf/packages/wotan/.dependency-cruiser.json

Unfortunately violating allowed only results in warnings. It would be great if there was an option to treat warnings as errors and exit with a non-zero exit code.

(Typescript) Dependency is not reported if the only import is a type.

When only importing a type from a module, dependency-cruiser does not report the dependency.

Steps to Reproduce (for bugs)

  1. Create module A with interface A
  2. Create module B
  3. Import interface A from module B
  4. Generate dependencies report with dependency-cruiser

Your Environment

  • Version used: 2.10.1
  • Node version: v9.3.0
  • Operating System and version: Archlinux

Typescript Union Types : Cannot read property 'kind' of undefined

Analyze failed when ts file have union types.

Current Behavior

Analyze stop without report on this error :

ERROR: Extracting dependencies ran afoul of...

Cannot read property 'kind' of undefined
... in src/...

Steps to Reproduce (for bugs)

export interface request {
method?: "get" | "post" | "patch" | "put" | "delete" | "head" | "options";
}

or :

test(sort: "none" | "ascending" | "descending" )

Your Environment

  • Version used: 4.27.1
  • Node version: 8.9.4
  • Operating System and version: Debian 9
  • typecript: 3.4.5

Add option to resolve symlinks of dependencies

Expected Behavior

I use yarn workspaces to link the packages in my monorepo to each other. This bascially does yarn link (or npm link) behind the scenes.
The setup is as follows:

packages
  |-- a
  \-- b
node_modules
  |-- a -> ../packages/a
  \-- b -> ../packages/b

a requires b, so I would expect the path to be packages/b/index.js but instead it is node_modules/b/index.js.

Node resolves symlinks during require. That's why I expected this tool to do that too.

Current Behavior

Symlinks are not resolved, see above.

Possible Solution

Add an option whether fs.realpath should be used after resolving imports.
This should not be enabled by default, because it would probably break other users.

Your Environment

  • Version used: 2.13.1
  • Node version: 9.5.0
  • Operating System and version: macOS High Sierra 10.13.3
  • Link to your project: https://github.com/fimbullinter/wotan (.dependecy-cruiser.json is not updated as of writing this)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.