0.0.5 • Published 8 months ago

@zx-libs/docgen v0.0.5

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

@zx-libs/docgen

A document generator that read the comments in the code and automatically generate MarkDown documents.

npm i -D @zx-libs/docgen
const { outputFile } = require('@zx-libs/docgen')
// import { outputFile } from '@zx-libs/docgen'

outputFile('./src', './outputDir/README.md', {})

see DEMO https://github.com/capricorncd/zx-libs/blob/main/node/docgen/scripts/docs.mjs

Methods

error(...args)

Output 😡 red color log in console

ParamTypesRequiredDescription
argsArray<string>yes-
  • @returns void

getCommentsData(input, needArray, options)

Get comments from the input file or directory. Supported keywords are type, document, method, code and more.

For example

A source file ./src/index.js, or a directory ./src.

/**
 * @method someMethod(param)
 * someMethod description 1 ...
 * someMethod description 2 ...
 * @param param `any` param's description
 * @returns `object` return's description
 * @sort 192
 */
function someMethod(param) {
  // do something ...
  return {...};
}

Get comments info form ./src or ./src/index.js

nodejs file ./scripts/create-docs.js.

const path = require('path')
const { getCommentsData } = require('@zx-libs/docgen')

const result = getCommentsData(path.resolve(__dirname, './src'));
console.log(result);

result

{
  '/usr/.../src/index.js': {
    method_someMethod: {
      type: 'method',
      sort: 192,
      name: 'someMethod',
      fullName: 'someMethod(param)',
      desc: [
        'someMethod description 1 ...',
        'someMethod description 2 ...',
      ],
      params: [
        {
          name: 'param',
          required: true,
          desc: ['param\'s description'],
          types: ['any'],
          raw: 'param `any` param\'s description',
        },
      ],
      returns: [
        {
          types: ['object'],
          desc: ['return\'s description'],
          raw: '`object` return\'s description',
        },
      ],
      codes: [],
      private: false,
      path: '/usr/.../src/index.js',
    },
    method_someMethod2: { ... },
    document_someDocument: { ... },
    type_someTypeName: { ... },
    ...
  }
}

Parameter needArray is true, or const { data } = outputFile(path.resolve(__dirname, './src')), result/data:

[
  {
    type: 'method',
    sort: 192,
    name: 'someMethod',
    fullName: 'someMethod(param)',
    desc: [
      'someMethod description 1 ...',
      'someMethod description 2 ...',
    ],
    params: [
      {
        name: 'param',
        required: true,
        desc: ['param\'s description'],
        types: ['any'],
        raw: 'param `any` param\'s description',
      },
    ],
    returns: [
      {
        types: ['object'],
        desc: ['return\'s description'],
        raw: '`object` return\'s description',
      },
    ],
    codes: [],
    private: false,
    path: '/usr/.../src/index.js',
  },
  ...
]
ParamTypesRequiredDescription
inputstring/string[]yesThe target file or directory.
needArraybooleannoIt's true will be returned an array. default false.
optionsGetCommentsDataOptionsnoGetCommentsDataOptions, default {}
  • @returns Record<filePath, Record<commentTypeName, CommentInfoItem>> | CommentInfoItem[] It's an array if needArray is true. What's CommentInfoItem.

getTypes(data)

Get types from getCommentsData's returned data.

ParamTypesRequiredDescription
dataRecord<filePath, Record<commentTypeName, CommentInfoItem>>/CommentInfoItem[]yesThe data obtained using the getCommentsData method

isFileLike(filePath)

is file like, *.ext.

ParamTypesRequiredDescription
filePathstringyes-
  • @returns boolean

isValidArray(arr)

Determine whether arr is an array and it has some elements.

ParamTypesRequiredDescription
arrT[]no-
  • @generic T

  • @returns boolean

log(...args)

Output 😎 green color log in console

ParamTypesRequiredDescription
argsArray<string>yes-
  • @returns void

mkdirSync(dir)

make a directory synchronously

ParamTypesRequiredDescription
dirstringyesdirectory path
  • @returns void

outputFile(input, outputDirOrFile, options)

Output the obtained annotation content as a document.

ParamTypesRequiredDescription
input{[filePath]: {[key]: CommentInfoItem}}/CommentInfoItem[]/stringyesComment obtained from the source. When string it's a file path, and the getCommentsData will be called. What's CommentInfoItem.
outputDirOrFilestringnoOptional parameter. The file or directory where the output will be written. When outputDirOrFile is undefined, no file will be output.
optionsOutputFileOptionsnoOutputFileOptions

toTableLines(data)

Convert data to a table in Markdown format.

ParamTypesRequiredDescription
dataToTableLinesParamDatayessee type ToTableLinesParamData.
  • @returns string[]

warn(...args)

Output 😕 yellow color log in console

ParamTypesRequiredDescription
argsArray<string>yes-
  • @returns void

writeFileSync(outputFileName, outputLines)

Synchronized file write function.

ParamTypesRequiredDescription
outputFileNamestringyesOutput filename, absolute path.
outputLinesstring[]/NodeJS.ArrayBufferView/stringyesThe output file content, an array of strings.
  • @returns void

Types

CommentInfoItem

CommentInfoItem is the comment information read with the getCommentsData function.

PropTypesRequiredDescription
typestringyesmethod/type/class/document
namestringyes@method name(...args)'s name
fullNamestringyes@method name(...args)'s name(...args)
descstring[]yesdescription
paramsCommentInfoItemParam[]yesmethod's params
returnsCommentInfoItemReturn[]yesmethod's returns
codesstring[]yesfor example codes
privatebooleanyesWhether the member method of the class is private
pathstringyesfile path
propsCommentInfoItemProp[]noCommentInfoItemProp
sortnumberyessort in the output file
genericsstring[]yesgeneric
interface CommentInfoItem {
  // method/type/class/document
  type: string
  // @method name(...args)'s `name`
  name: string
  // @method name(...args)'s `name(...args)`
  fullName: string
  // description
  desc: string[]
  // method's params
  params: CommentInfoItemParam[]
  // method's returns
  returns: CommentInfoItemReturn[]
  // for example codes
  codes: string[]
  // Whether the member method of the class is private
  private: boolean
  // file path
  path: string
  // [CommentInfoItemProp](#CommentInfoItemProp)
  props?: CommentInfoItemProp[]
  // sort in the output file
  sort: number
  // generic
  generics: string[]
}

CommentInfoItemParam

CommentInfoItem's params.

PropTypesRequiredDescription
rawstringyesunprocessed raw string
namestringyesparameter name or property name
requiredbooleanyesWhether the parameter is required, or the field must exist in the returned data.
descstring[]yesparameter or property's descriptions
typesstring[]yesparameter or property's types
interface CommentInfoItemParam {
  // unprocessed raw string
  raw: string
  // parameter name or property name
  name: string
  // Whether the parameter is required, or the field must exist in the returned data.
  required: boolean
  // parameter or property's descriptions
  desc: string[]
  // parameter or property's types
  types: string[]
}

CommentInfoItemProp

The properties of CommentInfoItem, only exists when the type is type or interface.

PropTypesRequiredDescription
namestringyesparameter name or property name
requiredbooleanyesWhether the parameter is required, or the field must exist in the returned data.
descstring[]yesparameter or property's descriptions
typesstring[]yesparameter or property's types
rawstringyesraw annotation string
interface CommentInfoItemProp extends CommentInfoItemParam {
  raw: string // raw annotation string
}

CommentInfoItemReturn

CommentInfoItem's return.

PropTypesRequiredDescription
descstring[]yesreturned's descriptions.
typesstring[]yesreturned's types
rawstringyesraw annotation string
interface CommentInfoItemReturn {
  // returned's descriptions.
  desc: string[]
  // returned's types
  types: string[]
  // raw annotation string
  raw: string
}

DocTypes

type DocTypes = 'document' | 'method' | 'type' | 'constant'

ExpendTypesHandler

expend types handler of GetCommentsDataOptions

type ExpendTypesHandler = (data: CommentInfoItem, line: string) => void

GetCommentsDataOptions

Parameter options of function getCommentsData

PropTypesRequiredDescription
fileTypeRegExpnoRegular expression for the type of file to be read, defaults to /\.[mc]?[tj]sx?$/.
disableKeySortingbooleannoDisables key sorting, defaults to false, and sorts alphabetically.
typesCommentInfoItem[]noThis types array is obtained from other files or directories for extends related processing.
expendTypesstring[]noexpend types of getCommentsData function.
expendTypesHandlersRecord<string, ExpendTypesHandler>nohandler of the expend types.
codeTypesstring[]noNeed to get source code of the type, default ['type', 'constant'].
isExtractCodeFromCommentsbooleannoIf true, the code in the comment will be added to the end of the @document or @method.
interface GetCommentsDataOptions {
  // Regular expression for the type of file to be read, defaults to `/\.[mc]?[tj]sx?$/`.
  fileType?: RegExp
  // Disables key sorting, defaults to `false`, and sorts alphabetically.
  disableKeySorting?: boolean
  // This `types` array is obtained from other files or directories for `extends` related processing.
  types?: CommentInfoItem[]
  // expend types of getCommentsData function.
  expendTypes?: string[]
  // handler of the expend types.
  expendTypesHandlers?: Record<string, ExpendTypesHandler>
  // Need to get source code of the type, default `['type', 'constant']`.
  codeTypes?: string[]
  // If true, the code in the comment will be added to the end of the @document or @method.
  isExtractCodeFromComments?: boolean
}

OutputFileInput

A parameter input of function outputFile.

type OutputFileInput =
  | string
  | string[]
  | Record<string, Record<string, CommentInfoItem>>
  | CommentInfoItem[]

OutputFileOptionAlias

PropTypesRequiredDescription
tableHeadRecord<string, string>noAlias of table head th inner text.
sourceCodeSummarystringnoSummary of details, <details><summary>Source Code</summary></details>'s summary, default Source Code.
requiredValuesOutputFileOptionAliasRequiredValuesnoRequired values
typesRecord<string, string>noAlias of the DocTypes name. types: { method: '方法/函数' }
interface OutputFileOptionAlias {
  // Alias of table head th inner text.
  tableHead?: Record<string, string>
  // Summary of details, `<details><summary>Source Code</summary></details>`'s summary, default `Source Code`.
  sourceCodeSummary?: string
  // Required values
  requiredValues?: OutputFileOptionAliasRequiredValues
  // Alias of the DocTypes name. `types: { method: '方法/函数' }`
  types?: Record<string, string>
}

OutputFileOptionAliasRequiredValues

Required values of OutputFileOptionAlias. For example {requiredValues: {0: 'no', 1: 'yes'}} or {requiredValues: {method: {0: 'no', 1: 'yes'}}}. And {requiredValues: ['no', 'yes']} or {requiredValues: {method: ['no', 'yes']}}

type OutputFileOptionAliasRequiredValues =
  | Record<string, string>
  | Record<string, Record<string, string>>

OutputFileOptionHandler

Custom type output handler.

PropTypesRequiredDescription
arrCommentInfoItem[],yes-
optionsOutputFileOptions,yes-
linesstring[]yes-
type OutputFileOptionHandler = (
  arr: CommentInfoItem[],
  options: OutputFileOptions,
  lines: string[]
) => void

OutputFileOptionLines

PropTypesRequiredDescription
startstring/string[]noThe start that need to be added at the start.
endstring/string[]noThe 'end' that need to be added at the end, such as adding some license information. ['## License', 'BLANK_LINE', 'MIT License © 2018-Present [Capricorncd](https://github.com/capricorncd).'].
afterTypeRecord<string, string \| string[]>noIt's will be appended to the [type], before the ## [other type]
afterTitleRecord<string, string \| string[]>noIt's will be insert after type title line. For example, {method: ['some type description content']}, It's will to insert after method line, like this's ['## Methods', 'some type description content', '...']
interface OutputFileOptionLines {
  // The `start` that need to be added at the start.
  start?: string | string[]
  // The 'end' that need to be added at the end, such as adding some license information. `['## License', 'BLANK_LINE', 'MIT License © 2018-Present [Capricorncd](https://github.com/capricorncd).']`.
  end?: string | string[]
  // It's will be appended to the `[type]`, before the `## [other type]`
  afterType?: Record<string, string | string[]>
  // It's will be insert after `type` title line.
  // For example, `{method: ['some type description content']}`,
  // It's will to insert after `method` line, like this's `['## Methods', 'some type description content', '...']`
  afterTitle?: Record<string, string | string[]>
}

OutputFileOptions

Options of the function outputFile, extends GetCommentsDataOptions

PropTypesRequiredDescription
fileTypeRegExpnoRegular expression for the type of file to be read, defaults to /\.[mc]?[tj]sx?$/.
disableKeySortingbooleannoDisables key sorting, defaults to false, and sorts alphabetically.
typesCommentInfoItem[]noThis types array is obtained from other files or directories for extends related processing.
expendTypesstring[]noexpend types of getCommentsData function.
expendTypesHandlersRecord<string, ExpendTypesHandler>nohandler of the expend types.
codeTypesstring[]noNeed to get source code of the type, default ['type', 'constant'].
isExtractCodeFromCommentsbooleannoIf true, the code in the comment will be added to the end of the @document or @method.
methodWithRawbooleannoDisplay methods using raw string, not table. default false
typeWithTablebooleannoDisplay types using only table, not Source Code. default false
typeWithSourceCodebooleannoDisplay types using only Source Code, not table. default false
typeWithAutobooleannoBy default, table and <details><summary>Source Code</summary></details> are displayed, but sometimes table's data may not exist, only Source Code can be displayed and <details> not using.
linesOutputFileOptionLinesnolines. OutputFileOptionLines
aliasOutputFileOptionAliasnoalias. OutputFileOptionAlias
outputDocTypesAndOrderstring[]noOutput types and their order, default ['document', 'method', 'type', 'constant']
handlersRecord<string, OutputFileOptionHandler>noCustom type output handler. Note that the default handler function will not be executed when this parameter is set. For example {method: (arr, options, lines) => do something}.
tableAlignRecord<string, 'left' \| 'center' \| 'right'>noAlignment of table columns, {Required: 'center'}. Default {[key]: 'left'}
interface OutputFileOptions extends GetCommentsDataOptions {
  // Display `methods` using raw string, not table. default `false`
  methodWithRaw?: boolean
  // Display `types` using only table, not Source Code. default `false`
  typeWithTable?: boolean
  // Display `types` using only Source Code, not table. default `false`
  typeWithSourceCode?: boolean
  // By default, `table` and `<details><summary>Source Code</summary></details>` are displayed,
  // but sometimes `table`'s data may not exist, only `Source Code` can be displayed and `<details>` not using.
  typeWithAuto?: boolean
  // lines. [OutputFileOptionLines](#OutputFileOptionLines)
  lines?: OutputFileOptionLines
  // alias. [OutputFileOptionAlias](#OutputFileOptionAlias)
  alias?: OutputFileOptionAlias
  // Output types and their order, default `['document', 'method', 'type', 'constant']`
  outputDocTypesAndOrder?: string[]
  // Custom type output handler. Note that the default handler function will not be executed when this parameter is set. For example `{method: (arr, options, lines) => do something}`.
  handlers?: Record<string, OutputFileOptionHandler>
  // Alignment of table columns, {Required: 'center'}. Default `{[key]: 'left'}`
  tableAlign?: Record<string, 'left' | 'center' | 'right'>
}

OutputFileReturns

Returned data of function outputFile.

PropTypesRequiredDescription
outputFileNamestring/nullyesoutputted filename
linesstring[]yesline array in the output file
dataCommentInfoItem[]yescomments data read from code
interface OutputFileReturns {
  // outputted filename
  outputFileName: string | null
  // line array in the output file
  lines: string[]
  // comments data read from code
  data: CommentInfoItem[]
}

TableHeadInnerText

Table head th inner text of the output file.

type TableHeadInnerText =
  | 'Name'
  | 'Param'
  | 'Prop'
  | 'Types'
  | 'Required'
  | 'Description'

ToTableLinesParamData

The options type of function toTableLines.

PropTypesRequiredDescription
alignstring[]yesAlignment of the table content, left, center or right, the default is left.
theadstring[]noThe table header displays a one-dimensional array of content. {thead: ['Name', 'Description']}.
tbodystring[][]noThe table body displays a two-dimensional array of contents. {tbody: [['someName1', 'someDescription1'],['someName2', 'someDescription2']]}.
interface ToTableLinesParamData {
  // Alignment of the table content, `left`, `center` or `right`, the default is `left`.
  align: string[]
  // The table header displays a one-dimensional array of content.
  // `{thead: ['Name', 'Description']}`.
  thead?: string[]
  // The table body displays a two-dimensional array of contents.
  // `{tbody: [['someName1', 'someDescription1'],['someName2', 'someDescription2']]}`.
  tbody?: string[][]
}

Constants

BLANK_LINE

blank line.

const BLANK_LINE = ''

DOC_TYPES

Supported annotation types.

const DOC_TYPES = {
  method: 'method',
  type: 'type',
  document: 'document',
  constant: 'constant',
  property: 'property',
}

License

MIT License © 2022-Present Capricorncd.

0.0.5

8 months ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago