Skip to content

Commit

Permalink
feat(context-explorer): add a component for context explorer
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed Apr 18, 2020
1 parent e434b58 commit f1c3557
Show file tree
Hide file tree
Showing 22 changed files with 2,851 additions and 0 deletions.
1 change: 1 addition & 0 deletions extensions/context-explorer/.npmrc
@@ -0,0 +1 @@
package-lock=true
25 changes: 25 additions & 0 deletions extensions/context-explorer/LICENSE
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2020. All Rights Reserved.
Node module: @loopback/context-explorer
This project is licensed under the MIT License, full text below.

--------

MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
89 changes: 89 additions & 0 deletions extensions/context-explorer/README.md
@@ -0,0 +1,89 @@
# @loopback/context-explorer

This module contains a component adding a Context Explorer to LoopBack
applications.

## Stability: ⚠️Experimental⚠️

> Experimental packages provide early access to advanced or experimental
> functionality to get community feedback. Such modules are published to npm
> using `0.x.y` versions. Their APIs and functionality may be subject to
> breaking changes in future releases.
## Installation

```sh
npm install --save @loopback/context-explorer
```

## Basic use

The component should be loaded in the constructor of your custom Application
class.

Start by importing the component class:

```ts
import {ContextExplorerComponent} from '@loopback/context-explorer';
```

In the constructor, add the component to your application:

```ts
this.component(ContextExplorerComponent);
```

By default, API Explorer is mounted at `/context-explorer`. This path can be
customized via ContextExplorer configuration as follows:

```ts
this.configure(ContextExplorerBindings.COMPONENT).to({
path: '/context-ui',
});
```

## Endpoints

The following endpoints are added by the component.

1. `/context-explorer/inspect`: Fetch a JSON document for the context hierarchy.

The following query parameters are supported:

- includeParent: include parent contexts (default: `true`)
- includeInjections: include injections (default: `true`)
- includeGraph: include a graph in [graphviz](https://www.graphviz.org/) dot
format (default: `true`)

2. `/context-explorer/graph`: Render the LoopBack application as a SVG diagram.

The following query parameters are supported:

- includeParent: include parent contexts (default: `true`)
- includeInjections: include injections (default: `true`)
- format: `dot` or `svg` (default: `svg`)

3. `/context-explorer`: Display the graph using
[d3-graphviz](https://github.com/magjac/d3-graphviz).

## Sample graph

![graph.svg](sample-graph.svg)

## Contributions

- [Guidelines](https://github.com/strongloop/loopback-next/blob/master/docs/CONTRIBUTING.md)
- [Join the team](https://github.com/strongloop/loopback-next/issues/110)

## Tests

Run `npm test` from the root folder.

## Contributors

See
[all contributors](https://github.com/strongloop/loopback-next/graphs/contributors).

## License

MIT
6 changes: 6 additions & 0 deletions extensions/context-explorer/index.d.ts
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2020. All Rights Reserved.
// Node module: @loopback/context-explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dist';
6 changes: 6 additions & 0 deletions extensions/context-explorer/index.js
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2020. All Rights Reserved.
// Node module: @loopback/context-explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = require('./dist');
8 changes: 8 additions & 0 deletions extensions/context-explorer/index.ts
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2020. All Rights Reserved.
// Node module: @loopback/context-explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// DO NOT EDIT THIS FILE
// Add any additional (re)exports to src/index.ts instead.
export * from './src';
32 changes: 32 additions & 0 deletions extensions/context-explorer/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions extensions/context-explorer/package.json
@@ -0,0 +1,54 @@
{
"name": "@loopback/context-explorer",
"version": "0.0.1",
"description": "LoopBack's Context/Binding Explorer",
"engines": {
"node": ">=10"
},
"scripts": {
"build": "lb-tsc",
"clean": "lb-clean loopback-explorer*.tgz dist tsconfig.build.tsbuildinfo package",
"pretest": "npm run build",
"test": "lb-mocha \"dist/__tests__/**/*.js\"",
"verify": "npm pack && tar xf loopback-context-explorer*.tgz && tree package && npm run clean"
},
"author": "IBM Corp.",
"copyright.owner": "IBM Corp.",
"license": "MIT",
"dependencies": {
"@loopback/context": "^3.2.0",
"@loopback/core": "^2.2.0",
"@loopback/rest": "^3.1.0",
"ts-graphviz": "^0.10.0",
"viz.js": "^2.1.2"
},
"devDependencies": {
"@loopback/build": "^5.0.0",
"@loopback/eslint-config": "^6.0.2",
"@loopback/testlab": "^3.0.0",
"@types/node": "^10.17.19"
},
"keywords": [
"LoopBack",
"Explorer",
"Context",
"Binding"
],
"files": [
"README.md",
"index.js",
"index.d.ts",
"dist",
"src",
"!*/__tests__",
"templates"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/strongloop/loopback-next.git",
"directory": "extensions/context-explorer"
}
}
92 changes: 92 additions & 0 deletions extensions/context-explorer/public/index.html
@@ -0,0 +1,92 @@
<!--
// Copyright IBM Corp. 2020. All Rights Reserved.
// Node module: @loopback/context-explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
-->
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<title>LoopBack Context Explorer</title>
<body>
<a href="/graph-d3.html">Reload</a>
<script src="//d3js.org/d3.v4.min.js"></script>

<script
src="https://unpkg.com/viz.js@1.8.2/viz.js"
type="javascript/worker"
></script>
<script src="https://unpkg.com/d3-graphviz@2.6.1/build/d3-graphviz.min.js"></script>

<script src="https://unpkg.com/graphlib-dot@0.6.4/dist/graphlib-dot.min.js"></script>
<script src="js/graph-util.js"></script>

<div id="graph" style="text-align: center;"></div>

<script>
var dots = [];
var dotIndex = 0;

function transitionFactory() {
return d3
.transition('main')
.ease(d3.easeLinear)
.delay(50)
.duration(500 * dotIndex);
}

async function fetchDots() {
const res = await fetch('./dots');
dots = JSON.parse(await res.text());
}

const graphviz = d3
.select('#graph')
.graphviz({
engine: 'fdp',
fit: true,
width: window.screen.availWidth,
height: window.screen.availHeight,
})
.logEvents(true)
.transition(transitionFactory)
.tweenShapes(false)
.on('initEnd', render);

async function render() {
if (dots.length === 0) await fetchDots();
const dot = dots[dotIndex];
graphviz.renderDot(dot).on('end', function() {
dotIndex++;
if (dotIndex < dots.length) {
render();
} else {
const nodes = d3.selectAll('.node');
nodes.on('click', renderNode);
}
});
}

/**
* Render the current node and its dependencies for the `click` event
*/
function renderNode() {
const current = d3.select(this);
const nodeId = current
.selectAll('title')
.text()
.trim();
var label = current.selectAll('text').text();
const yes = confirm(`Render "${label}" and its dependencies?`);
if (yes) {
const dotStr = dots[dotIndex - 1];
const newDotStr = selectNodes(dotStr, new Set([nodeId]));
if (dotStr !== newDotStr) {
dots.push(newDotStr);
render();
}
}
}
</script>
</body>
</html>
77 changes: 77 additions & 0 deletions extensions/context-explorer/public/js/graph-util.js
@@ -0,0 +1,77 @@
// Copyright IBM Corp. 2020. All Rights Reserved.
// Node module: @loopback/context-explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

/* eslint-disable no-undef */
/**
* Find dependencies of a set of starting nodes, including transitive ones
* @param graph - Graph object
* @param startingNodes - A set of nodes as starting ones
*/
function findDependencies(graph, startingNodes) {
const visited = new Set();
let nodesToBeAdded = new Set(startingNodes);
while (nodesToBeAdded.size !== 0) {
// Try to find nodes that are successors of starting nodes
const matched = new Set();
for (const node of nodesToBeAdded) {
visited.add(node);
const successors = graph.successors(node);
for (const s of successors) {
matched.add(s);
}
}
// Only include nodes found but not visited yet
nodesToBeAdded = new Set();
for (const node of matched) {
if (!visited.has(node)) {
nodesToBeAdded.add(node);
}
visited.add(node);
}
}
return visited;
}

/**
* Filter the graph with a set of starting nodes and their dependencies
* @param graph - Graph object
* @param startingNodes - A set of starting nodes
*/
function filterGraph(graph, startingNodes) {
const selected = findDependencies(graph, startingNodes);
const nodesToBeRemoved = graph
.nodes()
.filter(n => !selected.has(n) && graph.children(n).length === 0);
for (const node of nodesToBeRemoved) {
graph.removeNode(node);
}
removeEmptySubgraphs(graph);
}

function removeEmptySubgraphs(graph) {
// Remove empty subgraphs
// eslint-disable-next-line no-constant-condition
while (true) {
const emptySubgraphs = graph
.nodes()
.filter(n => n.startsWith('cluster_') && graph.children(n).length === 0);
if (emptySubgraphs.length === 0) break;
for (const node of emptySubgraphs) {
graph.removeNode(node);
}
}
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function selectNodes(dotGraph, startingNodes) {
const graph = graphlibDot.read(normalizeDot(dotGraph));
filterGraph(graph, startingNodes);
return graphlibDot.write(graph);
}

function normalizeDot(dotGraph) {
// graphlib-dot does not support the trailing `,` after the last attribute
return dotGraph.replace(/,(\s+\];)/gm, '$1');
}

0 comments on commit f1c3557

Please sign in to comment.