import { ALLOWED_TAGS, ALLOWED_TARGETS, MAX_NESTING_DEPTH, TAG_ALIASES } from '../constants'; import { MarkupNode } from '../Markup.types'; export { MAX_NESTING_DEPTH }; export const MAX_INPUT_LENGTH = 10_000; export const MAX_ACCESSIBILITY_LABEL_LENGTH = 250; const OBJECT_PROTOTYPE_KEYS = new Set(Object.getOwnPropertyNames(Object.prototype)); // eslint-disable-next-line regexp/no-control-character const CONTROL_CHARS = /[\x00-\x1f\x7f-\x9f]/g; const HTML_METACHAR = /[<>"']/g; /** * Matches opening and closing tags from the ALLOWED_TAGS allow-list. * * Capture groups: * 1. `/` if this is a closing tag, undefined otherwise * 2. Tag name * 3. Raw attribute string between the tag name and `>` (empty for closing tags) * * The lookahead `(?=[\s>/])` after the tag name ensures we don't match partial * words — e.g. `` won't be matched as ``. * * Global flag (`g`) allows iterative matching via `exec()`. */ const TAG_REGEX = new RegExp( `<(\\/)?(${ALLOWED_TAGS.join('|')})(?=[\\s>/])((?:[^>"']*(?:"[^"]*"|'[^']*'))*[^>"']*)>`, 'g', ); type Token = | { type: 'text'; content: string } | { type: 'newline' } | { type: 'open'; tag: string; attrs: string } | { type: 'close'; tag: string }; /** * Splits the input string into a flat list of tokens by scanning for known tags. * Text between tags is emitted as text/newline tokens. Unrecognised tags are never * tokenised — they remain part of the surrounding text content. */ function tokenise(input: string): Token[] { const tokens: Token[] = []; let lastIndex = 0; TAG_REGEX.lastIndex = 0; let match = TAG_REGEX.exec(input); while (match !== null) { if (match.index > lastIndex) { pushTextWithNewlines(tokens, input.slice(lastIndex, match.index)); } const isClose = match[1] === '/'; const tag = match[2]; const attrs = match[3] || ''; if (isClose) { tokens.push({ type: 'close', tag }); } else { tokens.push({ type: 'open', tag, attrs }); } lastIndex = TAG_REGEX.lastIndex; match = TAG_REGEX.exec(input); } if (lastIndex < input.length) { pushTextWithNewlines(tokens, input.slice(lastIndex)); } return tokens; } /** Splits a text fragment on newline characters, interleaving newline tokens between parts. */ function pushTextWithNewlines(tokens: Token[], text: string): void { const parts = text.split('\n'); for (let index = 0; index < parts.length; index += 1) { if (index > 0) { tokens.push({ type: 'newline' }); } if (parts[index]) { tokens.push({ type: 'text', content: parts[index] }); } } } type ParseResult = { closed: true; nodes: MarkupNode[] } | { closed: false; nodes: MarkupNode[] }; /** * Recursive descent parser that consumes tokens and builds a MarkupNode tree. * * When `untilTag` is provided, the function collects nodes until it finds a matching * close token — returning `{ closed: true }`. If it exhausts all tokens without finding * the close, it returns `{ closed: false }` so the caller can fall back to plain text * (graceful degradation for malformed input). * * The shared `position` object acts as a cursor across recursive calls, avoiding the * need to slice or copy the token array. */ function parse( tokens: Token[], position: { index: number }, untilTag?: string, depth = 0, ): ParseResult { const nodes: MarkupNode[] = []; while (position.index < tokens.length) { const token = tokens[position.index]; if (token.type === 'text') { nodes.push({ type: 'text', content: token.content }); position.index += 1; } else if (token.type === 'newline') { nodes.push({ type: 'newline' }); position.index += 1; } else if (token.type === 'close') { if (token.tag === untilTag) { position.index += 1; return { closed: true, nodes }; } // Mismatched close tag — render as literal text nodes.push({ type: 'text', content: `` }); position.index += 1; } else if (token.type === 'open') { if (depth >= MAX_NESTING_DEPTH) { nodes.push({ type: 'text', content: `<${token.tag}${token.attrs}>` }); position.index += 1; } else { position.index += 1; const result = parse(tokens, position, token.tag, depth + 1); if (result.closed) { const node = buildNode(token.tag, token.attrs, result.nodes); nodes.push(node); } else { nodes.push({ type: 'text', content: `<${token.tag}${token.attrs}>` }); nodes.push(...result.nodes); } } } } if (untilTag) { return { closed: false, nodes }; } return { closed: true, nodes }; } /** * Maps a raw tag name to a typed MarkupNode. Resolves aliases first (p→paragraph, a→link), * then builds the appropriate node shape. Link nodes carry full attributes; other element * nodes extract only accessibilityLabel. */ function buildNode(rawTag: string, attrs: string, children: MarkupNode[]): MarkupNode { const tag = TAG_ALIASES[rawTag] || rawTag; if (tag === 'link') { return { type: 'link', children, ...parseAttributes(attrs) }; } if (tag === 'paragraph') { return { type: 'paragraph', children }; } const { accessibilityLabel } = parseAttributes(attrs); return { type: tag as MarkupNode['type'], children, ...(accessibilityLabel && { accessibilityLabel }), } as MarkupNode; } /** * Matches allow-listed attributes from the raw attribute string captured by TAG_REGEX. * Requires whitespace before each attribute name to prevent matching inside quoted values. * * Example: for input ` href="https://wise.com" target="_blank"` * - Match 1: groups = ['href', 'https://wise.com', undefined] * - Match 2: groups = ['target', '_blank', undefined] * * Capture groups: * 1. Attribute name (href, action, target, or accessibilityLabel) * 2. Double-quoted value (if present) * 3. Single-quoted value (if present) */ const ATTR_REGEX = /(?<=\s)(href|action|target|accessibilityLabel)=(?:"([^"]*)"|'([^']*)')/g; type ParsedAttributes = { href?: string; action?: string; target?: string; accessibilityLabel?: string; }; /** * Extracts allowed attributes from a raw attribute string. * Supports both double- and single-quoted values. Any attribute not in the * allow-list (href, action, target, accessibilityLabel) is silently discarded. * First occurrence wins — duplicates are ignored. */ function parseAttributes(attrs: string): ParsedAttributes { const result: ParsedAttributes = {}; ATTR_REGEX.lastIndex = 0; let match = ATTR_REGEX.exec(attrs); while (match !== null) { const key = match[1] as 'href' | 'action' | 'target' | 'accessibilityLabel'; const value = match[2] ?? match[3]; if (!(key in result)) { const sanitized = sanitizeAttributeValue(key, value); if (sanitized !== undefined) { result[key] = sanitized; } } match = ATTR_REGEX.exec(attrs); } return result; } function sanitizeAttributeValue( key: 'href' | 'action' | 'target' | 'accessibilityLabel', value: string, ): string | undefined { switch (key) { case 'href': return value.replace(CONTROL_CHARS, ''); case 'action': if (OBJECT_PROTOTYPE_KEYS.has(value)) { return undefined; } return value; case 'target': if (!ALLOWED_TARGETS.includes(value)) { return undefined; } return value; case 'accessibilityLabel': return value.replace(HTML_METACHAR, '').slice(0, MAX_ACCESSIBILITY_LABEL_LENGTH); default: return undefined; } } /** Entry point: tokenises the input string, then parses the token stream into a MarkupNode tree. */ export function parseMarkup(input: string): MarkupNode[] { if (!input) { return []; } if (input.length > MAX_INPUT_LENGTH) { return [{ type: 'text', content: input }]; } const tokens = tokenise(input); const position = { index: 0 }; return parse(tokens, position).nodes; }