New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@lamnhan/docsuper

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@lamnhan/docsuper

Document generator for Typescript projects.

latest
Source
npmnpm
Version
0.0.2
Version published
Maintainers
1
Created
Source

@lamnhan/docsuper

Document generator for Typescript projects.

License Support me on Patreon PayPal Ask me anything

Table of content

Introduction

Documentation is a crucial part of every great open-source projects. But making docs is such a Pain-In-The-Brain process.

Since Typescript is an self documenting language, we can leverage its power to extract the source code information. This library is based on Typedoc, one of the best tool for generating Typescript documentation.

What is it?

docsuper is a tool for generating documentation directly from the source code.

It provides 3 main services:

Using the CLI, you can easily generate a document by providing the configuration in package.json or docsuper.config.js file.

An example configuration:

{
  "files": {
    "README.md": {
      "head": true,
      "toc": true,
      "section1": ["Class1"],
      "section2": ["Interface2"],
      "license": true
    }
  }
}

Run docsuper generate will output:

  • The docs/ folder: the detail document, generated by Typedoc.
  • And every document files based on the configuration.

NOTE: docsuper uses Typedoc to generate the detail documentation (can be ignored). The CLI is only used to generate simpler additional document files, such as README.md.

What the benefits?

  • Easy to config & usage
  • Avoid reference mistakes and code duplications
  • Improve source code quality with TSdoc
  • Save time and avoid brain damage

The workflow

Adding docsuper to any project in less than 5 simple steps:

  • Coding as usual
  • (Optional) Documenting the source code with TSdoc
  • (Optional) Putting custom sections and placeholders to files
  • Add configuration to package.json or docsuper.config.js
  • Run docsuper generate to generate content

Getting started

You can use docsuper to generate documentation from the command-line interface or manually parsing, converting or rendering content in a Node application.

The CLI

Install globally by running:

npm install -g @lamnhan/docsuper

A command now available from the terminal, you can run: docsuper.

If you wish to run the CLI locally, install the package with --save-dev flag:

npm install --save-dev @lamnhan/docsuper

Then put a script in the package.json, so you can do npm run docs every build.

{
  "scripts": {
    "docs": "docsuper generate"
  }
}

The library

Install as dev dependency:

npm install --save-dev @lamnhan/docsuper

Use the library:

import { docsuper } from "@lamnhan/docsuper";

// init an instance
const generator = docsuper(/* Options */);

// parsing
const parsing = generator.parse("Main");

// rendering
const rendering = generator.render({
  section1: ["Options"],
  section2: ["Main"]
});

See Main for service detail and Options for more options.

Understand the source code

A Typescript project source code contains many elements with different kinds: Variable/Property, Function/Method, Interface, Class, ...

Imagine your source code has 3 files: file1.ts, file2.ts, file3.ts. Each file exports certain elements.

But you can see your whole source code as a single flattened file like this:

// ================== file1.ts ==================

/**
 * This is a Variable element named `PI`
 */
export const PI = 3.14;

// ================== file2.ts ==================

/**
 * This is a Function element named `doSomething`
 */
export function doSomething() {
  return true;
}

// ================== file3.ts ==================

/**
 * This is an Interface element named `Options`
 *
 * And this is the `Options` element detail.
 *
 * Supports Markdown content.
 */
export interface Options {
  /**
   * This is a Property element named `prop1`
   */
  prop1?: string;
  prop2?: number;
}

/**
 * This is a Class element named `Main`
 *
 * And this is the `Main` element detail.
 *
 * Supports Markdown content.
 */
export class Main {
  property = "a property";
  constructor() {}
  /**
   * This is a Method element named `method1`
   */
  method1() {
    return "a method";
  }
}

To get information, we turn any element of the source code into a Declaration (a source code unit). There are 2 types of Declaration:

  • Direct: for top level elements, such as: Variable, Function, Interface, Class and a Collection of any top level elements.
  • Indirect: for child elements of a top level element, such as: Property and Method.

Configuration

The CLI load configuration from package.json or docsuper.config.js. See Options section for detail.

Open package.json and add:

{
  "name": "my-package",
  "description": "My package description.",
  "@lamnhan/docsuper": {
    "files": {
      "TEST.md": {
        "head": true,
        "s1": ["Main", "SELF"]
      }
    }
  }
}

With the configuration above, you tell the CLI to create a file named TEST.md with two sections:

  • The head section: a built-in section that display the package name and description.
  • The s1 section: a rendering section that display the source code element title and description.

The TEST.md content would be:

<\section id="head">

\# my-package

**My package description.**

</\section>

</\section id="s1">

\## The `Main` class

**This is a Class element named `Main`**

And this is the `Main` element detail.

Supports Markdown content.

</\section>

Rendering input

Take a look at the s1 section configuration above. We see it holds an array of values: ["Main", "SELF"]. This array is called a rendering input.

A rendering input provide instructions for the Parser and the Converter, it has 3 parts:

  • The WHAT: tells the Parser to parse what source code element:
    • Top level elements: provide the name of the element, example: PI, Options, ...
    • Child elements: put a . between the parent and the child name, example: Options.prop1, Main.method1, ...
    • Collection of elements: the list of paths, @ for ./src/ and separated by +, example: @file1.ts+@lib/filex.ts
  • The HOW (optional, default to SELF): tells the Converter how we want to extract the information from the parsing result.
  • The options (optional): custom converter options, see ConverterOptions.

See the Parser for parsing detail and the Converter for converting detail.

Using templates

Rendering template is a convinient way to render documents for common source code structure. To use a template, just replace rendering sections with the template name:

{
  "files": {
    "TEST.md": "mini"
  }
}

Currently supported 2 templates:

  • mini template, included these sections:

    • head: package name & description
    • toc: table of content
    • options: summary properties of Options interface
    • main: full Main class info
    • license: license informatiion
  • full template, included these sections:

    • head: package name & description
    • toc: table of content
    • functions: full list of all functions
    • interfaces: summary list of all interfaces
    • classes: full list of all classes
    • license: license informatiion

Custom sections

You can add any custom sections to a document file. The CLI will replace any section exists in the configuration with generated content and keep others as is.

You must wrap content inside the HTML section tag with a unique id.

<\section id="xxx">

Any markdown content goes here!

</\section>

Section can also be put in the source file, called local section.

IMPORTANT: If the content has these structures, you must escape them to avoid conflicts:

  • <\section id="xxx">...</\section> (HTML sections with an id)
  • \# A heading (Markdown headings, but not intended to be headings)
  • <\h1>A heading</\h1> (HTML headings, but not intended to be headings)

Options

Custom generator options

Options can be provided in 3 ways:

  • Under the @lamnhan/autodocs property of package.json file
  • The docsuper.config.js file for more advanced config
  • By the options param when init new docsuper(options?) instance.

Options properties

NameTypeDescription
apiGenerator"typedoc" | "none"Detail API generator
apiUrlstringCustom API reference url, default to the Github Pages repo url
convertsAdditionalConvertsAdditional converts
filesobjectList of documents to be generated: key is the path to the document and value is a template name or a rendering input
noAttrbooleanNo generator footer attribution
typedocTypedocConfigsCustom Typedoc config

Main service

The Main service

Main properties

NameTypeDescription
ContentContentServiceGet the Content service
ConverterConvertServiceGet the Converter service
LoaderLoadServiceGet the Loader service
ParserParseServiceGet the Parser service
ProjectProjectServiceGet the Project service
RendererRenderServiceGet the Renderer service
TypedocTypedocServiceGet the Typedoc service

Main methods

FunctionReturns typeDescription
convert(declaration, output, options?)HeadingBlock | TextBlock | ListBlock | TableBlock[]Convert a declaration into content blocks.
generateDocs()voidGenerate the API reference using Typedoc.
output(path, rendering)voidRender and save a document
outputLocal()voidRender and save documents based on local configuration.
parse(input?)DeclarationTurn the source code into a Declaration.
render(rendering, currentContent?, html?)stringRender content based on configuration.
renderLocal()BatchRenderResultRender content based on local configuration.

convert(declaration, output, options?)

Convert a declaration into content blocks.

Parameters

ParamTypeDescription
declarationDeclarationThe declaration
outputstringExpected output
optionsConvertOptionsCustom convertion options

Returns

HeadingBlock | TextBlock | ListBlock | TableBlock[]

generateDocs()

Generate the API reference using Typedoc.

The default folder is /docs. You can change the output folder by providing the out property of Options.

Returns

void

output(path, rendering)

Render and save a document

Parameters

ParamTypeDescription
pathstringPath to the document
renderingRenderingRendering configuration

Returns

void

outputLocal()

Render and save documents based on local configuration.

Returns

void

parse(input?)

Turn the source code into a Declaration.

Parameters

ParamTypeDescription
inputstringParsing input

Returns

Declaration

render(rendering, currentContent?, html?)

Render content based on configuration.

Parameters

ParamTypeDescription
renderingRenderingRedering configuration
currentContentContentBySectionsCurrent content by sections
htmlboolean

Returns

string

renderLocal()

Render content based on local configuration.

Returns

BatchRenderResult

Declaration

A Declaration is an object the holds information of a source code element.

Declaration properties

NameTypeDescription
DEFAULT_VALUEany
DISPLAY_TYPEstring
FULL_TEXTstring
IDstring
IS_OPTIONALboolean
LEVELnumber
LINKstring
NAMEstring
PARAMETERSReflectionData[]
REFLECTIONReflection
RETURNSstring
SECTIONSContentBySections
SHORT_TEXTstring
TEXTstring
TYPEstring

Declaration methods

FunctionReturns typeDescription
getChild(name)Declaration
getChildId(childName)string
getClasses(offset?)Declaration[]
getFunctionsOrMethods(offset?)Declaration[]
getInterfaces(offset?)Declaration[]
getVariablesOrProperties(offset?)Declaration[]
hasClasses()boolean
hasFunctionsOrMethods()boolean
hasInterfaces()boolean
hasVariablesOrProperties()boolean
isKind(kindString)boolean
setId(id)this
setLevel(level)this

getChild(name)

The getChild call signature.

Parameters

ParamTypeDescription
namestring

Returns

Declaration

getChildId(childName)

The getChildId call signature.

Parameters

ParamTypeDescription
childNamestring

Returns

string

getClasses(offset?)

The getClasses call signature.

Parameters

ParamTypeDescription
offsetnumber

Returns

Declaration[]

getFunctionsOrMethods(offset?)

The getFunctionsOrMethods call signature.

Parameters

ParamTypeDescription
offsetnumber

Returns

Declaration[]

getInterfaces(offset?)

The getInterfaces call signature.

Parameters

ParamTypeDescription
offsetnumber

Returns

Declaration[]

getVariablesOrProperties(offset?)

The getVariablesOrProperties call signature.

Parameters

ParamTypeDescription
offsetnumber

Returns

Declaration[]

hasClasses()

The hasClasses call signature.

Returns

boolean

hasFunctionsOrMethods()

The hasFunctionsOrMethods call signature.

Returns

boolean

hasInterfaces()

The hasInterfaces call signature.

Returns

boolean

hasVariablesOrProperties()

The hasVariablesOrProperties call signature.

Returns

boolean

isKind(kindString)

The isKind call signature.

Parameters

ParamTypeDescription
kindStringkeyof ReflectionKind

Returns

boolean

setId(id)

The setId call signature.

Parameters

ParamTypeDescription
idstring

Returns

this

setLevel(level)

The setLevel call signature.

Parameters

ParamTypeDescription
levelnumber

Returns

this

The Parser

The Parser turns source code into Declaration

ParseService methods

FunctionReturns typeDescription
parse(input?)Declaration

parse(input?)

The parse call signature.

Parameters

ParamTypeDescription
inputstring

Returns

Declaration

The Converter

The Converter turns Declaration into content blocks

Converter output

A Declaration supports certain output depended on its kind:

OutputKindsDescription
FULLanyAll content (with headings)
SELFanyTitle, description, content WITHOUT local sections, parameters & returns (for function)
SECTION:<SECTION_ID>anyA local section
VALUEVariable, PropertyDefault value
SUMMARY_VARIABLESCollectionSummary table of variables
DETAIL_VARIABLESCollectionDetail list of variables
FULL_VARIABLESCollectionSummary table & detail list of variables
SUMMARY_FUNCTIONSCollectionSummary table of functions
DETAIL_FUNCTIONSCollectionDetail list of functions
FULL_FUNCTIONSCollectionSummary table & detail list of functions
SUMMARY_PROPERTIESInterface, ClassSummary table of properties
DETAIL_PROPERTIESInterface, ClassDetail list of properties
FULL_PROPERTIESInterface, ClassSummary table & detail list of properties
SUMMARY_METHODSClassSummary table of methods
DETAIL_METHODSClassDetail list of methods
FULL_METHODSClassSummary table & detail list of methods
SUMMARY_INTERFACESCollectionSummary table of interfaces
DETAIL_INTERFACESCollectionDetail list of interfaces
FULL_INTERFACESCollectionSummary table & detail list of interfaces
SUMMARY_CLASSESCollectionSummary table of classes
DETAIL_CLASSESCollectionDetail list of classes
FULL_CLASSESCollectionSummary table & detail list of classes

Provide options with the third item of a rendering input:

  • Declaration level/id: { level: number, id }
  • SELF header: { title, link }
  • Raw object: { raw: true }
  • Use the default heading: { heading: true }
  • Use local anchors (instead of detail links): { local: true }

ConvertService methods

FunctionReturns typeDescription
convert(declaration, output, options?)HeadingBlock | TextBlock | ListBlock | TableBlock[]

convert(declaration, output, options?)

The convert call signature.

Parameters

ParamTypeDescription
declarationDeclaration
outputstring
optionsConvertOptions

Returns

HeadingBlock | TextBlock | ListBlock | TableBlock[]

The Renderer

The Renderer turns a rendering input into the final content

Builtin sections:

  • head: Package name & description
  • toc: Table of content
  • tocx: Table of content, with detail API reference link
  • license: License information

RenderService methods

FunctionReturns typeDescription
getData(rendering)RenderingData
getDataBatch(batchRendering)BatchRenderingData
render(rendering, currentContent?, html?)string
renderBatch(batchRendering, batchCurrentContent?)BatchRenderResult

getData(rendering)

The getData call signature.

Parameters

ParamTypeDescription
renderingRendering

Returns

RenderingData

getDataBatch(batchRendering)

The getDataBatch call signature.

Parameters

ParamTypeDescription
batchRenderingBatchRendering

Returns

BatchRenderingData

render(rendering, currentContent?, html?)

The render call signature.

Parameters

ParamTypeDescription
renderingRendering
currentContentContentBySections
htmlboolean

Returns

string

renderBatch(batchRendering, batchCurrentContent?)

The renderBatch call signature.

Parameters

ParamTypeDescription
batchRenderingBatchRendering
batchCurrentContentobject

Returns

BatchRenderResult

License

@lamnhan/docsuper is released under the MIT license.

⚡️ This document is generated automatically using @lamnhan/docsuper.

Keywords

docs

FAQs

Package last updated on 27 Oct 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts