UNPKG

simple-text-parser

Version:
66 lines (65 loc) 2.39 kB
export interface Node { type: string; text: string; [key: string]: unknown; } export declare namespace Node { function is(r: any): r is Node; } export declare type Match = string | RegExp | Match.Location | Match.Location[] | Match.Function; export declare namespace Match { type Location = [number, number]; namespace Location { function is(loc: any): loc is Location; } type Function = (str: string) => string | RegExp | Location | Location[]; function is(val: any): val is Match; } export declare type Replace = string | Replace.Function; export declare namespace Replace { type Function = (match: string, ...groups: string[]) => Partial<Node> | string; function is(val: any): val is Replace; } export interface Rule { match: Match; type?: string; replace?: Replace; } export declare namespace Rule { function is(r: any): r is Rule; } export declare class Parser { static presets: Map<string, Match>; /** * Register a new global preset rule. Presets don't handle the replacing, only the matching. There are three * pre-included presets: `tag`, `url`, and `email`. */ static registerPreset(type: string, match: Match): void; rules: Rule[]; /** Add a rule to this parser. A rule consists of a match and optionally, a replace and type. */ addRule(match: Match, replace?: Replace, type?: string): this; /** Add a rule object to this parser. */ addRule(rule: Rule): this; /** * Add a registered global preset rule within this parser and give it a replace. The preset must first be registered * using `Parser.registerPreset()` before it can be used with this method. */ addPreset(type: string, replace?: Replace): this; private _replace; private _toTree; /** * Returns the parsed string as an array of nodes. Every node includes at least `type` and `text` properties. `type` * defaults to `"text"` but could be any value as returned by `replace`. The `text` key is used to replaced the * matched string by `render()`. */ toTree(str: string): Node[]; /** * Returns a string derived from the text property on a list of nodes. */ static renderTree(tree: Node[]): string; /** * Returns a parsed string with all matches replaced. */ render(str: string): string; } export default Parser;