Skip to content

lpaladin/json-inline-doc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JSON Inline Doc

Add inline comments on stringified JSON (JSONC), or generate from JSON schema

Use case: Using JSON for configuration and provide inline documentation as comments for users.

JSONC is JSON with JavaScript style comments. Please note that original JSON does not support comments.

Installation:

npm install json-inline-doc

Example - Comments Generated from JSON Schema

import { SchemaMetadataWriter } from 'json-inline-doc';

// Create a writer with a schema
const w: SchemaMetadataWriter = new SchemaMetadataWriter({
    "description": "Cluster Configuration",
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "description": "Cluster name"
        }
    },
    "required": []
});

// The API is the same as JSON.stringify
w.stringify({ name: 'Sample Cluster' }, null, 4);

Output:

/**
 * @type object
 * @description Cluster Configuration
 */
{
    /**
     * @type string
     * @description Cluster name
     */
    "name": "Sample Cluster"
}

Example - Custom Comments

import { CustomCommentWriter } from 'json-inline-doc';

// Create a writer
const w: CustomCommentWriter = new CustomCommentWriter();

// Add custom comments to fields
w.addComments([], [{ type: 'line', content: 'test' }]);
w.addComments(['test'], [{ type: 'block', content: 'test2' }]);
w.addComments(['test', 1], [{ type: 'end', content: 'test3' }]);
w.addComments(['test', undefined, undefined], [{ type: 'line', content: 'test4' }]);
w.addComments(['test', undefined, 'test2'], [{ type: 'block', content: path => path.toString() }]);

// The API is the same as JSON.stringify
console.log(w.stringify({ test: [{ test2: 3 }, { test2: 4 }, 3, [5]] }, null, 4));

Output:

// test
{
    /**
     * test2
     */
    "test": [
        {
            /**
             * test,0,test2
             */
            "test2": 3
        },
        {
            "test2": 4
        }, // test3
        3,
        [
            // test4
            5
        ]
    ]
}

For more detailed examples, please see the test cases.

API Documentation

All code is written in TypeScript which can be self-explanatory.

Writers

The abstract base class of all writers.

writer = new JSONCommentWriterBase(configuration)

  • Note: The above line of code is only for explanation. This class is abstract - do not try to new a instance by yourself!
  • configuration: object (optional)
    • emptyLineBeforeComments: boolean (default true)

      Add a blank line before every block and line comment, except comments of the followings:

      • The root object
      • The first item in array
      • The first key-value pair in object

      Not supported if space when calling stringify is 0.

    • spaceAroundCommentSymbol: boolean (default true)

      Add space around '//', '/*' and '*/'. '/*' and '*/' will not be affected by this configuration if styledBlockComment is true.

    • styledBlockComment: boolean (default true)

      Make block comment styled:

      • Asterisk (' * ') at the beginning of each line
      • The first line being '/**'
      • The last line being ' */'

      Not supported if space when calling stringify is 0. (Except for comments of root object)

    • maxLineLength: number (default 80)

      Maximum line length of each line of comment. Lines will be auto wrapped if exceeded. If any non-positive number is specified, auto wrapping will be disabled.

      Not supported if space when calling stringify is 0. (Except for comments of root object)

writer.stringify(value, replacer, space)

A class of JSON comment writer which supports custom comments for fields specified by path.

writer = new CustomCommentWriter(configuration)

writer.addComments(selector, comments)

  • Add custom comments to fields specified by selector.

  • selector: (string | number | undefined)[] (required)

    A path of keys. undefined can be used to match any other key not matched on that level. An empty array matches the root object.

  • comments: IJSONComment[] (required)

    Comments to be shown when the selector matches.

A class of JSON comment writer generating comments for fields specified in JSON schema.

writer = new SchemaMetadataWriter(schemaObject, commentGenerator, configuration)

  • Construct a new SchemaMetadataWriter.

  • schemaObject: JSONSchema (required)

    A fully dereferenced JSON schema object containing no $ref, which can be obtained using libraries like json-schema-ref-parser.dereference with circular being true.

    This object is allowed to be recursive.

  • commentGenerator: function (defaults to a simple schema comment generator)

    A function to generate comment string from the schema of a field.

    Signature: (schema: JSONSchema) => IJSONComment | undefined

  • configuration: object (optional)

    Please refer to the constructor of JSONCommentWriterBase.

Types

Represents a single comment. Can be an object or a string.

  • When being a string:

    The comment will be assumed to be a block comment (see below), and the string will be the content of comment.

  • When being an object:

    • type: 'block' | 'line' | 'end' (required)

      Type of the comment:

      • block - block comment wrapped with '/*' and '*/' before the item
      • line - line comment beginning with '//' before the item
      • end - line comment at the end of the item on the same line

      line and end are not supported if space when calling stringify is 0. (Except for comments of root object)

    • content: string or function (required)

      Content of the comment. Could be:

      • A single-line or multi-line string
      • A function to be called when stringifying the matched field.
        • Signature: (matchedFieldPath: (string | number)[]) => string | undefined
        • Return undefined to omit.
      • '*/' will be escaped automatically if type is block.

License

MIT license