Catharsis
A JavaScript parser for Google Closure Compiler and JSDoc type expressions.
Install / Use
/learn @hegemonic/CatharsisREADME
Catharsis
A JavaScript parser for Google Closure Compiler and JSDoc type expressions.
Catharsis is designed to be:
- Accurate. Catharsis is based on a Peggy grammar that's designed to handle any valid type expression. It uses a thorough test suite to verify the parser's accuracy.
- Flexible. Catharsis can convert a parse result back into a type expression, or into a description of the type expression. In addition, Catharsis can parse JSDoc-style type expressions.
Example
const catharsis = require('catharsis');
// Closure Compiler parsing
const type = '!Object';
let parsedType;
try {
parsedType = catharsis.parse(type); // {"type":"NameExpression,"name":"Object","nullable":false}
} catch(e) {
console.error('unable to parse %s: %s', type, e);
}
// JSDoc-style type expressions enabled
const jsdocType = 'string[]'; // Closure Compiler expects Array<string>
let parsedJsdocType;
try {
parsedJsdocType = catharsis.parse(jsdocType, { jsdoc: true });
} catch (e) {
console.error('unable to parse %s: %s', jsdocType, e);
}
// Converting parse results back to type expressions
catharsis.stringify(parsedType); // !Object
catharsis.stringify(parsedJsdocType); // Array<string>
// Converting parse results to descriptions of the type expression
catharsis.describe(parsedType).simple; // non-null Object
catharsis.describe(parsedJsdocType).simple; // Array of string
See the
test/specs directory
for more examples of Catharsis' parse results.
Methods
parse(typeExpression, options)
Parse a type expression, and return the parse results. Throws an error if the type expression cannot be parsed.
When called without options, Catharsis attempts to parse type expressions in the
same way as Closure Compiler. When the jsdoc option is enabled, Catharsis can
also parse several kinds of type expressions that are permitted in
JSDoc:
- The string
functionis treated as a function type with no parameters. - If you append
[]to a name expression (for example,string[]), it is interpreted as a type application with the expressionArray(for example,Array<string>). - Name expressions can contain the characters
#,~,:, and/. - Name expressions can contain a suffix that is similar to a function signature
(for example,
MyClass(foo, bar)). - Name expressions can contain a reserved word.
- Record types can use types other than name expressions for keys.
Parameters
type: A string containing a Closure Compiler type expression.options: Options for parsing the type expression.options.jsdoc: Specifies whether to enable parsing of JSDoc-style type expressions. Defaults tofalse.
Returns
An object containing the parse results. See the
test/specs directory
for examples of the parse results for different type expressions.
stringify(parsedType, options)
Stringify parsedType, and return the type expression. If validation is
enabled, throws an error if the stringified type expression cannot be parsed.
Parameters
parsedType: An object containing a parsed Closure Compiler type expression.options: Options for stringifying the parse results.options.htmlSafe: Specifies whether to return an HTML-safe string that replaces angle brackets (<and>) with HTML entities. Note: Characters in name expressions are not escaped.options.linkClass: A CSS class to add to HTML links. Used only ifoptions.linksis provided. By default, no CSS class is added.options.links: An object or map whose keys are name expressions and whose values are URIs. You can also provide a map-like object with aget()method. If a name expression matches a key inoptions.links, the name expression will be wrapped in an HTML<a>tag that links to the URI. If you also specifyoptions.linkClass, the<a>tag includes aclassattribute.options.validate: Specifies whether to validate the stringified parse results by attempting to parse them as a type expression. If the stringified results are not parsable with the default options, you must also provide the appropriate options to pass to theparse()method. Defaults tofalse.
Returns
A string containing the type expression.
describe(parsedType, options)
Convert a parsed type to a description of the type expression. This method is especially useful if your users are not familiar with the syntax for type expressions.
The describe() method returns the description in two formats:
- Simple format. A string that provides a complete description of the type expression.
- Extended format. An object that separates out some of the details about the outermost type expression, such as whether the type is optional, nullable, or repeatable.
For example, when you call describe('?function(new:MyObject, string)='), the
method returns the following data:
{
simple: 'optional nullable function(constructs MyObject, string)',
extended: {
description: 'function(string)',
modifiers: {
functionNew: 'Returns MyObject when called with new.',
functionThis: '',
optional: 'Optional.',
nullable: 'May be null.',
repeatable: ''
},
returns: ''
}
}
Parameters
parsedType: An object containing a parsed Closure Compiler type expression.options: Options for creating the description.options.codeClass: A CSS class to add to the tag that is wrapped around type names. Used only if you specifyoptions.codeTag. By default, no CSS class is added.options.codeTag: The name of an HTML tag (for example,code) to wrap around type names. For example, if this option is set tocode, the type expressionArray<string>would have the simple description<code>Array</code> of <code>string</code>.options.language: A string identifying the language in which to generate the description. The identifier should be an ISO 639-1 language code (for example,en). It can optionally be followed by a hyphen and an ISO 3166-1 alpha-2 country code (for example,en-US). If you use values other thanen, you must provide translation resources inoptions.resources. Defaults toen.options.linkClass: A CSS class to add to HTML links. Used only ifoptions.linksis provided. By default, no CSS class is added.options.links: An object or map whose keys are name expressions and whose values are URIs. You can also provide a map-like object with aget()method. If a name expression matches a key inoptions.links, the name expression will be wrapped in an HTML<a>tag that links to the URI. If you also specifyoptions.linkClass, the<a>tag includes aclassattribute.options.resources: An object that specifies how to describe type expressions for a given language. The object's property names should use the same format asoptions.language. Each property should contain an object in the same format as the translation resources inres/en.json. If you specify a value foroptions.resources.en, that value overrides the defaults inres/en.json.
Returns
An object with the following properties:
simple: A string that provides a complete description of the type expression.extended: An object containing details about the outermost type expression.extended.description: A string that provides a basic description of the type expression, excluding the information contained in other properties.extended.modifiers: Information about modifiers that apply to the type expression.extended.modifiers.functionNew: A string that describes what a function returns when called withnew. Returned only for function types.extended.modifiers.functionThis: A string that describes what the keywordthisrefers to within a function. Returned only for function types.extended.modifiers.nullable: A string that indicates whether the type is nullable or non-nullable.extended.modifiers.optional: A string that indicates whether the type is optional.extended.modifiers.repeatable: A string that indicates whether the type can be repeated.
extended.returns: A string that describes the function's return value. Returned only for function types.
Changelog
- 0.11.0 (December 2024):
- The
stringify()method now always restringifies the parsed type, rather than returning the original type expression in some cases. - The
stringify()method no longer accepts anoptions.cssClassproperty. This property was deprecated in version 0.8.0. - Catharsis no longer caches return values. Callers can cache the return values as needed.
- Catharsis's methods no longer return frozen objects. Callers can freeze the objects as needed.
- The
- 0.10.0 (December 2024):
- The
stringify()method no longer includes a dot separator for type applications. For example, an array of numbers is stringified asArray<number>rather thanArray.<number>. - For the
stringify()method, whenoptions.htmlSafeis set totrue, t
- The
Related Skills
node-connect
347.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
107.8kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
347.0kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
347.0kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
