Options
All
  • Public
  • Public/Protected
  • All
Menu

@stoplight/graphite

Maintainability Test Coverage

Nodes'n things.

Installation

Supported in modern browsers and node.

# latest stable
yarn add @stoplight/graphite

Usage

Note, this is not all implemented, but rather an example of what it might look like.

import {
  Graphite,
  FilesystemPlugin,
  JsonPlugin,
  YamlPlugin,
  Oas2Plugin
} from "@stoplight/graphite";

const graphite = Graphite();

graphite.registerPlugins(
  FilesystemSource(),
  JsonPlugin(),
  YamlPlugin(),
  Oas2Plugin()
);

// Mirror two Graphite instances. The mirroredGraphite instance has no plugins, and simply applies the results of the graphite instance.
const mirroredGraphite = Graphite();
graphite.on("did_patch", mirroredGraphite.applyPatch);

// Add a single SourceNode of type file
const n = graphite.addSourceNode({
  type: FilesystemPlugin.File,
  path: "/foo.json"
});

// Queue up a read task for that node
n.read();

// Wait until all processing is done
await graphite.tasksProcessed();

// The two graphs should be identical, ids and all.
// Note, the mirroredGraph did NO work - all the file reading, parsing, etc, was done by the plugins in the main graphite instance.
expect(graphite.dehydrate()).toEqual(mirroredGraphite.dehydrate());

Concepts

Graph

  • Holds nodes and edges.
  • Exposes methods to add and remove nodes/edges.
  • Responsible for managing node/edge lifecycle.

Nodes

  • They hold data.
  • There are three node categories (described below): source, source_map, and virtual.

Edges

  • They represent relationships between nodes.

Graphite

  • Manages a single graph instance.
  • Exposes applyPatch method.
  • Emits events as patches are processed.
  • Exposes convenience methods for common patterns, such as addSourceNode, that simply build and a patch or task and call applyPatch or queueTask.
  • Manages tasks.

Mutations

  • ALL changes, both internal and external, pass through the graphite.applyPatch method.

JsonPatch

  • A group of JsonOperations.

GraphPatch

  • A group of JsonOperations, and their inverse. This is similar to the concept of a "transaction".
  • If one operation fails, they all fail, and a rollback is attempted.

GraphTask

  • Describes a single change to be made to the graph.
  • Any operations that cannot be accomplished via JsonPatch must be queued up via a GraphTask.
  • Examples include add_node, read_node, write_node, parse_node, compute_node_source_map.
  • Plugins can define their own tasks, such as oas2_lint_node.
  • The result of a GraphTask must always be a GraphPatch.
  • When a task is run, the GraphPatch it returns is applied to the graph.

Scheduler

  • Manages one or more task queues.
  • We will at the very least have high and low priority queues.
  • Tasks such as add_node and read_node will go into a high priority queue.
  • Tasks such as oas2_lint_node and resolve_node will go into a low priority queue.

Notifier

  • Manages events like a boss.

Sources

SourceNode

  • Source nodes are the only node category
  • Exposes 4 primary properties - original, raw, parsed (TODO), and isDirty.
  • Exposes 4 primary methods - read, write, updateRaw, and updateParsed.

SourceSink

  • Responsible for reading data from some data source, and adding the appropriate source nodes.
  • Responsible for refreshing the original property of a SourceNode in response to read_node tasks.
  • Responsible for writing the SourceNode raw property back to the data source in response to write_node tasks.
  • Implements ISourceReader and/or ISourceWriter.

SourceParser

  • Targets one or more SourceNodes.
  • Responsible for computing its parsed value when raw changes.
  • Responsible for computing its raw value when parsed changes.

SourceMapNode

  • A specific type of node that is a child of a SourceNode.
  • Its uri points to a real location in the original source.
  • Its data property points to a value in its parent SourceNode.parsed, according to its uri.
  • Exposes an update method that queues a GraphPatch to update its source node parsed value.

SourceTree

  • Defines a ISourceTreeMap that describes how a SourceNode.parsed value should be translated into SourceMapNodes.

VirtualNode

  • Anything that is not a SourceNode or SourceTreeNode
  • Examples: linting results, transformed http operation and http service nodes, etc

Contributing

  1. Clone repo.
  2. Create / checkout feature/{name}, chore/{name}, or fix/{name} branch.
  3. Install deps: yarn.
  4. Make your changes.
  5. Run tests: yarn test.prod.
  6. Stage relevant files to git.
  7. Commit: yarn commit. NOTE: Commits that don't follow the conventional format will be rejected. yarn commit creates this format for you, or you can put it together manually and then do a regular git commit.
  8. Push: git push.
  9. Open PR targeting the next branch.

Index

Enumerations

Classes

Interfaces

Type aliases

Variables

Functions

Type aliases

CreateEdgesFunc

CreateEdgesFunc: function

Type declaration

DehydratedNode

DeserializeFunc

DeserializeFunc: function

Type declaration

    • (raw: string): IParserResult
    • Parameters

      • raw: string

      Returns IParserResult

Edge

Edge: IEdge

EdgeInstance

EdgeInstance: IEdgeInstance

EdgeWithOptionalId

EdgeWithOptionalId: Omit<Edge, "id"> & object

GraphOperation

GraphOperationResult

GraphOperationResult: O & IOperationResult

GraphOrJsonOperation

GraphOrJsonOperation: GraphOperation | JsonOperation

Operations: Base

GraphOrJsonOperationResult

GraphOrJsonOperationResult: GraphOperationResult | JsonOperationResult

GraphTask

GraphTaskResult

GraphTaskResult: GraphTask[] | void

GraphiteEmitter

GraphiteEmitter: IEventEmitter<IGraphiteEvents>

GraphiteError

HttpSecurityScheme

HttpSecurityScheme: IApiKeySecurityScheme | IBearerSecurityScheme | IBasicSecurityScheme | IOauth2SecurityScheme | IOpenIdConnectSecurityScheme

ISourceNodeParsed

ISourceNodeParsed: IParserResult<any, object, Optional<unknown>>

IdGenerator

IdGenerator: function

Type declaration

IdGeneratorWrapper

IdGeneratorWrapper: function

Type declaration

JsonOperation

JsonOperationResult

JsonOperationResult: JsonOperation<D> & IOperationResult

JsonPatch

JsonPatch: D[]

JsonPatchResult

JsonPatchResult: D[]

Node

NodeInstance

NodeWithOptionalId

NodeWithOptionalId: Omit<Node, "id" | "language"> & object

Ommitting language and re-setting as optional is a workaround for a TS bug (?). W/o this hack language becomes required...

Oas2TranslateOperationOptions

Oas2TranslateOperationOptions: ITranslateOperationOptions<Operation, Path, Spec>

Oas3TranslateOperationOptions

Oas3TranslateOperationOptions: ITranslateOperationOptions<OperationObject, PathObject, OpenAPIObject>

SerializeFunc

SerializeFunc: function

Type declaration

    • (parsed: any): string
    • Parameters

      • parsed: any

      Returns string

SourceBackendFactory

SourceBackendFactory: function

SourceBackend

Type declaration

SourceNodeProp

SourceNodeProp: keyof Pick<ISourceNodeInstance, "spec"> | "data.raw" | "data.parsed" | "data.original" | "data.resolved" | "data.diagnostics" | "data.ast" | "data.lineMap" | "data.refMap"

TaskRunFunc

TaskRunFunc: function

Type declaration

Variables

Const addNodeTree

addNodeTree: (Anonymous function) & IAction = action((helpers: Pick<IPatchableGraph, 'addNode'>, tree: INodeTree[], parentId?: string) => {for (const node of tree) {const n = helpers.addNode({...node,parentId,});if (node.children && node.children.length) {addNodeTree(helpers, node.children, n.id);}}})

This function takes a source tree object and adds it to the graph

Const errorReporter

errorReporter: ErrorReporter = new ErrorReporter(createNotifier())

Const languageMap

languageMap: object = new Proxy(extensionToLanguage, {get(target, lang) {return lang in target ? target[lang] : lang;},})

Type declaration

Const registry

registry: SpecProviderRegistry = new SpecProviderRegistry()

Functions

URI

  • URI(url?: string | URI): object

applyJsonPatch

  • applyJsonPatch<T>(value: T, patch: JsonPatch): T

applyPatch

applyTextOperation

  • applyTextOperation(value: any, operation: Omit<ITextOperation, "op">): string

combinePathAndUri

  • combinePathAndUri(path: string, uri?: undefined | string): string

computeNodeChildrenUriMap

computeSourceMap

  • computeSourceMap(map: ISourceNodeMap[], data: any, parentUri?: undefined | string): IComputeSourceMapResult

createComputeSourceMapHandler

createDeserializeSourceNodeHandler

createDiagnoseSourceNodeHandler

createEdge

  • createEdge(props: IEdge): Edge

Const createFileSystemBackend

createGraph

createGraphite

Const createJsonParser

Const createJsonPlugin

Const createJsonSchemaPlugin

createNotifier

createOas2HttpPlugin

createOas2Plugin

Const createOas2SourceMap

createOas3HttpPlugin

createOas3Plugin

Const createOas3SourceMap

createOasHttpPlugin

  • createOasHttpPlugin<Operation, Path, Spec>(version: OasVersion, config: IHttpOperationHookConfig<Operation, Path, Spec>): IGraphitePlugin

Const createParser

Const createPlugin

createScheduler

createSerializeSourceNodeHandler

Const createSpectralPlugin

Const createTaskHandler

  • createTaskHandler(decoratee: ITaskHandlerWithNoId, id?: undefined | string): TaskHandler

Const createYamlParser

Const createYamlPlugin

Const defaultIdGenerator

  • defaultIdGenerator(): any

diffText

filenameToLanguage

  • filenameToLanguage(fileName: string): string
  • Takes a filename, extracts its extension and maps to a language we detected.

    Parameters

    • fileName: string

    Returns string

generateNodeId

getConsumes

  • getConsumes(operation: Partial<Operation>, spec: Partial<Spec>): string[]

getOas3Securities

  • getOas3Securities(operation: Partial<OperationObject>, spec: Partial<OpenAPIObject>): SecuritySchemeObject[]

getOasParameters

  • getOasParameters<ParamType>(operationParameters: ParamType[] | undefined, pathParameters: ParamType[] | undefined): ParamType[]
  • Type parameters

    • ParamType: object

    Parameters

    • operationParameters: ParamType[] | undefined
    • pathParameters: ParamType[] | undefined

    Returns ParamType[]

getParentUri

  • getParentUri(uri: string): string | undefined

getProduces

  • getProduces(operation: Partial<Operation>, spec: Partial<Spec>): string[]

getSecurities

  • getSecurities(operationSecurity: Array<Dictionary<string[], string>> | undefined, spec: Partial<Spec>): Security[]

identifyMoveOperations

  • identifyMoveOperations(patch: JsonPatch, parentUri: string, getNodeByUri: function): JsonPatch

isBodyParameter

  • isBodyParameter(parameter: Parameter): boolean

isChild

  • isChild(node: object): boolean

isFormDataParameter

  • isFormDataParameter(parameter: Parameter): boolean

isHeaderParameter

  • isHeaderParameter(parameter: Parameter): boolean

isPathParameter

  • isPathParameter(parameter: Parameter): boolean

isQueryParameter

  • isQueryParameter(parameter: Parameter): boolean

isRootNode

  • isRootNode(node: object): boolean

isSourceNode

  • isSourceNode(node: object): boolean

isVirtualNode

  • isVirtualNode(node: object): boolean

oasEdgePlugin

Const printTree

  • printTree(nodes: IPrintableNode[] | IPrintableNode, relative?: boolean): string
  • Parameters

    • nodes: IPrintableNode[] | IPrintableNode
    • Default value relative: boolean = true

    Returns string

relativeJsonPath

  • relativeJsonPath(parentUri: string, uri: string): JsonPath

Const resolveSourceNodeHandler

setWithPush

  • setWithPush(object: any, path: string, value: any): any

translateHeaderObject

  • translateHeaderObject(headerObject: HeaderObject, name: string): IHttpHeaderParam

translateMediaTypeObject

  • translateMediaTypeObject(__namedParameters: object, mediaType: string): IHttpContent

translateOas3ToRequest

  • translateOas3ToRequest(parameters: ParameterObject[], requestBodyObject?: RequestBodyObject): IHttpOperationRequest

translateOas3ToSecurities

translateOperation

translateToBodyParameter

  • translateToBodyParameter(body: BodyParameter, consumes: string[]): IHttpOperationRequestBody

translateToContent

  • translateToContent(schema: ISchema, mediaTypes: string[]): object

translateToFormDataParameter

  • translateToFormDataParameter(form: FormDataParameter, requestBody: IHttpOperationRequestBody | null | undefined, consumes: string[]): IHttpOperationRequestBody

translateToHeaderParam

  • translateToHeaderParam(parameter: HeaderParameter, consumes: string[]): IHttpHeaderParam

translateToHeaderParams

  • translateToHeaderParams(headers: object, consumes: string[]): IHttpHeaderParam[]

translateToOas3Responses

  • translateToOas3Responses(responses: ResponsesObject): IHttpOperationResponse[]

translateToPathParameter

  • translateToPathParameter(parameter: PathParameter, consumes: string[]): IHttpPathParam

translateToQueryParameter

  • translateToQueryParameter(query: QueryParameter, consumes: string[]): IHttpQueryParam

translateToRequest

  • translateToRequest(parameters: Parameter[], consumes: string[]): IHttpOperationRequest

translateToResponses

  • translateToResponses(responses: object, produces: string[]): IHttpOperationResponse[]

translateToSecurities

translateToServers

  • translateToServers(operation: Partial<Operation>, spec: Partial<Spec>): IServer[]

translateToTags

  • translateToTags(tags: string[]): INodeTag[]

uniqFlatMap

  • uniqFlatMap<T>(collection?: T[]): string[]