rti
Root namespace for the RTI Transpiler.
Summary
Static Properties
| indentingNodeTypes | Node types whose renderer increases the indentation level by one ( |
| nodeChildren | Map of Babel node types to their child keys that contain traversable AST nodes. |
| parserOptions | We use the same options in different places, so it's nice to keep them in sync without changing them in multiple locations. |
| requiredTypeofs |
Static Methods
| addTypeChecks | Simple facade which does all the processing. |
| annotate | Attaches JSDoc comment blocks to the AST nodes which carry TypeScript types. |
| ast2json | |
| ast2jsonForComparison | |
| attachComment | Attaches a JSDoc comment (built from |
| capitalize | |
| code2ast2code | A roundtrip between code -> AST -> code to validate Stringifier. |
| collectVariableTypeComments | Attaches |
| compareAST | |
| expandType | Transforms a type string into a structured type representation. |
| expandTypeBabelTS | |
| expandTypeDepFree | 'DepFree' refers to the fact that this function has no dependencies,
while |
| extractCurlyContent | Extracts the content of a string that is delimited by curly braces. |
| extractNameAndOptionality | Extracts the parameter name and its optionality from a JSDoc parameter string. |
| findCommentHost | Finds the statement-ish node where a JSDoc comment should live. |
| formatCommentBreaks | Moves a statement that follows a generated JSDoc block onto its own line, e. |
| functionSignatureToJSDoc | |
| hasTypedParams | |
| importTypeToJSDoc | Renders a JSDoc |
| inferTypeFromDefault | Infers a JSDoc type from a default value literal. |
| injectParameterProperties | Injects |
| jsdocLinesFromFunction | Returns the JSDoc lines for a function-like node. |
| jsImportSource | Rewrites a TypeScript import specifier to its JavaScript counterpart, e. |
| literalToJSDoc | Converts a literal type node to its JSDoc representation. |
| makeComment | Creates a Babel CommentBlock node with a fabricated |
| nodeIsFunctionLike | Checks if the provided node is a function-like structure. |
| paramToJSDoc | Extracts param information and produces a |
| parseJSDoc | Parses JSDoc comments to extract parameter type information. |
| parseJSDocSetter | |
| parseJSDocTemplates | Parses JSDoc comments to extract parameter type information. |
| parseJSDocTypedef | Parses JSDoc comments to extract and expand typedefs and their associated properties. |
| parseTS | Parses TypeScript code, automatically falling back to TSX (JSX) mode when the input contains JSX elements. |
| parseType | |
| parseTypeBabelTS | |
| propertySignatureToJSDoc | |
| renderIndentDepth | Counts the renderer indentation levels that nest |
| restElementType | Unwraps the trailing |
| simplifyReference | Reduces a possibly namespace-qualified type name to its local identifier, e. |
| simplifyType | |
| statReset | |
| templateLiteralToJSDoc | |
| toSourceBabelTS | Converts a Babel AST node to its source string representation or structured type object. |
| toSourceTS | Converts a TypeScript AST node to a source string representation or to an intermediate object describing the type. |
| trimEndSpaces | |
| ts2js | A roundtrip between TypeScript code -> JavaScript code with JSDoc types. |
| tsTypeToJSDoc | Converts a Babel-TS type AST node into a JSDoc compatible type string, e. |
| typeLiteralMembersToJSDoc | Converts a |
Details
Static Properties
| indentingNodeTypes | Node types whose renderer increases the indentation level by one ( |
| nodeChildren | Map of Babel node types to their child keys that contain traversable AST nodes. |
| parserOptions | We use the same options in different places, so it's nice to keep them in sync without changing them in multiple locations. |
| requiredTypeofs |
Static Methods
addTypeChecks(src, [options]) #
Simple facade which does all the processing. Processes the input source string, adding runtime type checks based on JSDoc comments.
This function takes JavaScript source code as input, parses it to an AST, traverses the AST to find type annotations in JSDoc comments, and generates appropriate runtime type assertions. These are then inserted into the source, producing a new version of the code that includes runtime type checking based on the original JSDoc annotations.
Parameters
| src | string | The input source code containing JSDoc comments to be processed for type checks. |
| options | import('./Asserter.js').Options | Configuration options that dictate how the processing is performed. |
Returns
stringThe transformed source code with inserted runtime type checks, or the original source code commented with an error if processing fails.
annotate(node, parents) #
Attaches JSDoc comment blocks to the AST nodes which carry TypeScript types.
Parameters
| node | Node | The node to annotate recursively. |
| parents | Node[] | The current parent stack. |
ast2json(ast) #
Parameters
| ast | object | The Babel AST. |
Returns
stringString representation in JSON format for debugging/inspecting the AST.
ast2jsonForComparison(ast) #
setRight(ast2jsonForComparison(parseSync("/** *"))); // Close comment with / after last *Parameters
| ast | object | The Babel AST. |
Returns
stringString representation in JSON format for debugging/inspecting the AST.
attachComment(node, lines, parents) #
Attaches a JSDoc comment (built from lines) to a suitable statement-level host node.
Parameters
| node | Node | The annotated node. |
| lines | string[] | The JSDoc lines. |
| parents | Node[] | The parent stack. |
capitalize(_) #
capitalize("hello"); // Outputs: HelloParameters
| _ | string | The input string. |
Returns
stringThe capitalized output string.
code2ast2code(code) #
A roundtrip between code -> AST -> code to validate Stringifier.
Parameters
| code | string | The code. |
Returns
string, undefinedThe new and once parsed and stringified code.
collectVariableTypeComments(node, parents) #
Attaches @type comments for typed variable declarations.
Parameters
| node | import('@babel/types').VariableDeclaration | The declaration node. |
| parents | Node[] | The parent stack. |
compareAST(left, right) #
Parameters
| left | string | Left source code. |
| right | string | Right source code. |
Returns
booleanWhether source codes are identical on the AST level.
expandType(type) #
Transforms a type string into a structured type representation.
This function parses a given type string and converts it into a TypeScript Abstract Syntax Tree (AST), then uses that AST to return a structured type representation that can be further utilized or interpreted.
const {expandType} = await import("./src-transpiler/expandType.js");
expandType('[string, Array|AnyTypedArray, number[]]|[ONNXTensor]');
expandType('(123) '); // Outputs: '123'
expandType(' ( ( 123 ) ) '); // Outputs: '123'
expandType('Array '); // Outputs: {type: 'array', elementType: 'number'}
expandType('Array<(123) > '); // Outputs: {type: 'array', elementType: '123'}
expandType('Array<"abc" | 123> '); // Outputs: {type: 'array', elementType: {type: 'union', members: ['"abc"', '123']}}
expandType(' (string ) |(number ) '); // Outputs: {type: 'union', members: [ 'string', 'number']}
expandType(' "apples" | ( "bananas") '); // Outputs: {type: 'union', members: [ '"apples"', '"bananas"']}
expandType('123? '); // Outputs: {"type":"union","members":["123","null"]}
expandType('123|null '); // Outputs: {"type":"union","members":["123","null"]}
expandType('Map '); // Outputs:
expandType('typeof Number '); // Outputs: Parameters
| type | string | The type string to be expanded into a structured representation. |
Returns
string | number | boolean | {type: string, [key: string]: any} | undefinedThe structured type representation obtained from parsing and converting the provided type string.
expandTypeBabelTS(type) #
const {expandTypeBabelTS} = await import("./src-transpiler/expandTypeBabelTS.js");
expandTypeBabelTS('[string, Array|AnyTypedArray, number[]]|[ONNXTensor]');
expandTypeBabelTS('(123) '); // Outputs: '123'
expandTypeBabelTS(' ( ( 123 ) ) '); // Outputs: '123'
expandTypeBabelTS('Array '); // Outputs: {type: 'array', elementType: 'number'}
expandTypeBabelTS('Array<(123) > '); // Outputs: {type: 'array', elementType: '123'}
expandTypeBabelTS('Array<"abc" | 123> '); // Outputs: {type: 'array', elementType: {type: 'union', members: ['"abc"', '123']}}
expandTypeBabelTS(' (string ) |(number ) '); // Outputs: {type: 'union', members: [ 'string', 'number']}
expandTypeBabelTS(' "apples" | ( "bananas") '); // Outputs: {type: 'union', members: [ '"apples"', '"bananas"']}
expandTypeBabelTS('123? '); // Outputs: {type: 'union', members: ['123', 'null']}
expandTypeBabelTS('123|null '); // Outputs: {type: 'union', members: ['123', 'null']}
expandTypeBabelTS('Map '); // Outputs: {type: 'map', key: 'string', val: 'any'}
expandTypeBabelTS("(a: number, b: number) => number") Parameters
| type | string | The input type. |
Returns
string, object, undefined- See
toSourceBabelTS.
expandTypeDepFree(type) #
'DepFree' refers to the fact that this function has no dependencies,
while expandType depends on TypeScript itself for maximum compatibility.
expandTypeDepFree('(123) '); // Outputs: '123'
expandTypeDepFree('Array '); // Outputs: { type: 'array', elementType: 'number' }
expandTypeDepFree('Array<(123) > '); // Outputs: { type: 'array', elementType: '123' }
expandTypeDepFree(' ( ( 123 ) ) '); // Outputs: '123'
expandTypeDepFree(' (string ) |(number ) '); // Outputs: { type: 'union', members: ['string', 'number'] }
expandTypeDepFree(' (( Object ) ) '); // Outputs: { type: 'object', properties: {} } Parameters
| type | string | The input type to expand. |
Returns
string, ExpandTypeReturnValueObject containing parsed information from type string.
extractCurlyContent(line) #
Extracts the content of a string that is delimited by curly braces.
extractCurlyContent('{ {inner} }'); // Returns: {content: ' {inner} ', nextIndex: 11}Parameters
| line | string | The string to extract from. |
Returns
ObjectAn object containing the extracted content, and the index of the character immediately following the closing curly brace.
extractNameAndOptionality(rest) #
Extracts the parameter name and its optionality from a JSDoc parameter string.
This function takes a rest parameter string from a JSDoc comment, trims it, and determines the parameter's name and whether it is optional. The optionality is inferred based on the presence of square brackets around the parameter name.
Parameters
| rest | string | The rest part of a JSDoc parameter string to parse. |
Returns
[string, boolean]A tuple where the first element is the name of the parameter, and the second element is a boolean indicating if the parameter is optional.
findCommentHost(node, parents) #
Finds the statement-ish node where a JSDoc comment should live.
For const f = (a) => {} the comment belongs on the VariableDeclaration,
for export function f it belongs on the ExportNamedDeclaration.
Parameters
| node | Node | The function/property node. |
| parents | Node[] | The parent stack. |
Returns
NodeThe host node.
formatCommentBreaks(source) #
Moves a statement that follows a generated JSDoc block onto its own line,
e.g. a closing comment marker directly followed by export function f() {}
becomes the closing marker, a newline, then export function f() {}.
Parameters
| source | string | The generated source code. |
Returns
stringThe source with fixed comment/statement breaks.
functionSignatureToJSDoc(node) #
Parameters
| node | Node | A function-like type node ( |
Returns
stringThe (a: A) => R style JSDoc type string.
hasTypedParams(node) #
Parameters
| node | Node | The function-like node. |
Returns
booleanTrue if any parameter carries a type annotation.
importTypeToJSDoc(specifiers, source) #
Renders a JSDoc @import comment for type-only import specifiers,
e.g. import type {OnlyType} from './types' becomes the single line
@import { OnlyType } from './types.js' and carries the type
information without creating a runtime import.
Parameters
| specifiers | import('@babel/types').ImportSpecifier[]|import('@babel/types').ImportDefaultSpecifier[]|import('@babel/types').ImportNamespaceSpecifier[] | The import specifiers. |
| source | import('@babel/types').StringLiteral | The import source. |
Returns
stringThe @import JSDoc comment (or an empty string).
inferTypeFromDefault(node) #
Infers a JSDoc type from a default value literal.
Parameters
| node | Node | The default value node. |
Returns
import('@babel/types').Node|undefinedA primitive keyword node or undefined.
injectParameterProperties(node) #
Injects this.prop = prop; statements for constructor parameter properties
(constructor(public prop: number)).
Parameters
| node | import('@babel/types').ClassMethod|import('@babel/types').ClassPrivateMethod | The constructor node. |
jsdocLinesFromFunction(node) #
Returns the JSDoc lines for a function-like node.
Parameters
| node | Node | The function-like node. |
Returns
string[]The JSDoc lines (without @param/@returns separators).
jsImportSource(source) #
Rewrites a TypeScript import specifier to its JavaScript counterpart,
e.g. ./types becomes ./types.js.
Parameters
| source | import('@babel/types').StringLiteral | The import source. |
Returns
stringThe JavaScript module specifier.
literalToJSDoc(literal) #
Converts a literal type node to its JSDoc representation.
Parameters
| literal | Node | The literal node. |
Returns
stringThe JSDoc type string.
makeComment(node, lines, parents) #
Creates a Babel CommentBlock node with a fabricated loc.
The column is derived from the renderer indentation depth of the annotated
node (2 spaces per indenting ancestor) so that the comment aligns with the
spaces of the node's rendered position, independent of the original
(namespace-shifted) source column.
Parameters
| node | Node | The annotated node. |
| lines | string[] | The JSDoc lines. |
| parents | Node[] | The parent stack. |
Returns
import('@babel/types').CommentBlockThe comment node.
nodeIsFunctionLike(node) #
Checks if the provided node is a function-like structure.
Parameters
| node | Node | The Babel AST node to be tested. |
Returns
node is Functiontrueif the node is a function-like structure, otherwisefalse.
paramToJSDoc(param, index) #
Extracts param information and produces a @param JSDoc line,
or nothing when nothing can be said about the parameter.
Parameters
| param | Node | The parameter node. |
| index | number | The index of the parameter. |
Returns
string, undefinedThe @param line.
parseJSDoc(src, [expandType]) #
Parses JSDoc comments to extract parameter type information.
Parameters
| src | string | The JSDoc comment string to parse. |
| expandType | ExpandType | An optional function to process the types found in the JSDoc. |
Returns
Record<string, ExpandTypeReturnType>, undefinedAn object mapping parameter names to their parsed types, or undefined if no parameters are found.
parseJSDocSetter(src, expandType) #
Parameters
| src | string | JSDoc comment of the setter. |
| expandType | function | The expandType function. |
Returns
string, DocType, undefinedThe parsed and possibly expanded type from
the JSDoc comment, or undefined if parsing fails to find @type.
parseJSDocTemplates(src, [expandType]) #
Parses JSDoc comments to extract parameter type information.
Parameters
| src | string | The JSDoc comment string to parse. |
| expandType | ExpandType | An optional function to process the types found in the JSDoc. |
Returns
Record<string, ExpandTypeReturnType>, undefinedAn object mapping template names to their parsed types,
or undefined if no template tags were found.
parseJSDocTypedef(typedefs, warn, comment, expandType) #
Parses JSDoc comments to extract and expand typedefs and their associated properties.
It iterates through the lines of a CommentBlock from the Babel AST, looking for @typedef and @property
annotations. When it finds a typedef, it stores it in the typedefs record. When it finds a property,
it adds it to the last found typedef if it is an object type.
Parameters
| typedefs | Record.<string, object> | An object to store typedefs, mapping type names to their expanded definitions. |
| warn | Console["warn"] | A warn function used for emitting warnings about non-extensible types. |
| comment | import("@babel/types").Comment | A comment extracted from Babel's AST, expected to be a CommentBlock containing type definitions. |
| expandType | function | A function that takes a type expression as a string and returns a structured representation of the type. |
parseTS(code) #
Parses TypeScript code, automatically falling back to TSX (JSX) mode when the input contains JSX elements.
Parameters
| code | string | The TypeScript code. |
Returns
import('@babel/parser').ParseResult<import('@babel/types').File>The parsed AST.
parseType(str) #
Parameters
| str | string | The type string. |
Returns
ts.TypeNode, undefined- The node containing all the information about the input type string.
parseTypeBabelTS(str) #
Parameters
| str | string | The type string. |
Returns
import('@babel/types').Node- The node containing all the information about the input type string.
propertySignatureToJSDoc(node) #
Parameters
| node | Node | The |
Returns
stringThe name: type (or optional name?: type) string.
renderIndentDepth(node, parents) #
Counts the renderer indentation levels that nest node, so comments can be
placed at the column the stringifier will use (2 spaces per level).
Parameters
| node | Node | The annotated node. |
| parents | Node[] | The parent stack. |
Returns
numberThe indentation depth of the node.
restElementType(typeStr) #
Unwraps the trailing [] of an array type in a rest parameter context,
e.g. @param {...string[]} rest becomes @param {...string} rest.
Parameters
| typeStr | string | The JSDoc type string. |
Returns
stringThe element type.
simplifyReference(node) #
Reduces a possibly namespace-qualified type name to its local identifier,
e.g. Validation.StringValidator becomes StringValidator, since flattened
namespaces hoist their interfaces/classes to plain identifiers.
Parameters
| node | Node | The referenced name node. |
Returns
stringThe simplified JSDoc type string.
simplifyType(type, optional) #
Parameters
| type | string, DocType | The type. |
| optional | boolean | Optionality |
Returns
string, DocTypeThe simplified type.
templateLiteralToJSDoc(node) #
Parameters
| node | Node | The |
Returns
stringThe template literal type as string.
toSourceBabelTS(node) #
Converts a Babel AST node to its source string representation or structured type object.
This function handles a variety of node types provided by Babel and converts them into a string or an intermediate object representing the type, depending on the complexity of the type described by the node.
Parameters
| node | import('@babel/types').Node | The Babel AST node to convert. |
Returns
string, object, undefined- A string, object representing a structured type, or
undefinedfor unhandled types. Depending on the node, it may return a simple type string (e.g.,"string"forTSStringKeyword), a structured type object (e.g., a record type forTSTypeReferencewith type arguments), orundefinedif the encountered type is not handled. Unhandled types trigger a warning and enter a debugger statement.
toSourceTS(node) #
Converts a TypeScript AST node to a source string representation or to an intermediate object describing the type.
This function handles various TypeScript AST node types and converts them into a string or an object representing the type.
Parameters
| node | ts.TypeNode, ts.Identifier, ts.QualifiedName, undefined | The TypeScript AST node to convert. |
Returns
string | number | boolean | {type: string, [key: string]: any} | undefinedThe source string/number,
or an object with type information based on the node, or undefined if the node kind is not handled.
trimEndSpaces(str) #
trimEndSpaces('test \n '); // Returns: 'test \n'Parameters
| str | string | The input string. |
Returns
stringOutput string without spaces at the end.
ts2js(code, [options]) #
A roundtrip between TypeScript code -> JavaScript code with JSDoc types.
Parameters
| code | string | The TypeScript code. |
| options | object | Options for the conversion. |
| options.filename | boolean | Unused placeholder, kept for API symmetry. |
Returns
stringThe converted JavaScript code.
tsTypeToJSDoc(node) #
Converts a Babel-TS type AST node into a JSDoc compatible type string,
e.g. number, string[], Map<string, number> or {a: number, b?: string}.
The produced strings are valid TypeScript types as well, so they can be fed
back into expandType/parseJSDoc of this very project.
Parameters
| node | Node | The Babel-TS type node. |
Returns
stringThe JSDoc-compatible type string.