UNPKG

segment-matcher

Version:

Segment Matcher - TypeScript version with dual ESM/CJS format support

130 lines (129 loc) 4.69 kB
import { MessageSegment } from './types'; import { PatternToken } from './pattern_token'; import { MatchResult } from './match_result'; import { FieldMappingConfig } from './field_mapping'; /** * 消息段匹配器类 * * 负责根据模式令牌数组匹配消息段。 * 支持字面量匹配、类型化字面量匹配、参数提取和剩余参数收集。 * * @example * ```typescript * const tokens = PatternParser.parse('hello <name:text>'); * const segments = [{ type: 'text', data: { text: 'hello Alice' } }]; * const result = BasicMatcher.match(tokens, segments); * // result.params.name === 'Alice' * ``` */ export declare class BasicMatcher { /** * 匹配消息段 * * 根据模式令牌数组匹配消息段,提取参数并收集剩余消息段。 * 支持空格敏感匹配和自定义字段映射。 * * @param pattern - 解析后的模式令牌数组 * @param segments - 消息段数组 * @param typedLiteralFieldMap - 自定义的类型化字面量字段映射(可选) * @returns 匹配结果或 null(匹配失败时) * * @example * ```typescript * // 基础匹配 * const result = BasicMatcher.match(tokens, segments); * * // 自定义字段映射 * const customResult = BasicMatcher.match(tokens, segments, { * image: 'src' // 使用 'src' 字段而不是默认的 'file' 或 'url' * }); * ``` */ static match(pattern: PatternToken[], segments: MessageSegment[], typedLiteralFieldMap?: FieldMappingConfig): MatchResult | null; /** * 匹配单个令牌和消息段 * * 根据令牌类型选择相应的匹配策略。 * * @param token - 模式令牌 * @param segment - 消息段 * @param segments - 完整的消息段数组(用于修改) * @param segmentIndex - 当前消息段索引 * @param typedLiteralFieldMap - 自定义字段映射 * @returns 匹配响应 */ private static matchToken; /** * 匹配字面量令牌 * * 检查文本消息段是否以指定的字面量开头。 * 支持空格敏感匹配,将剩余文本插入到下一个位置。 * * @param token - 字面量令牌 * @param segment - 消息段 * @param segments - 消息段数组(用于插入剩余文本) * @param segmentIndex - 当前索引 * @returns 匹配响应 */ private static matchLiteral; /** * 匹配类型化字面量令牌 * * 检查消息段类型和字段值是否匹配指定的类型化字面量。 * 支持多字段匹配和文本包含匹配。 * * @param token - 类型化字面量令牌 * @param segment - 消息段 * @param segments - 消息段数组(用于插入分割后的文本) * @param segmentIndex - 当前索引 * @param typedLiteralFieldMap - 自定义字段映射 * @returns 匹配响应 */ private static matchTypedLiteral; /** * 解析引号包裹的文本 * 支持单引号和双引号,以及嵌套不同类型的引号 * * @param text - 输入文本 * @returns 解析结果,包含引号内的文本和剩余文本,如果解析失败返回 null */ private static parseQuotedText; /** * 匹配单个参数令牌和消息段 * * 根据参数令牌的类型和数据类型,匹配对应的消息段并提取参数值。 * 支持特殊类型规则的自动类型转换和验证。 * 支持从单个文本段中部分提取参数(例如从 "100 200" 中提取 "100")。 * * @param token - 参数令牌 * @param segment - 消息段 * @param segments - 完整的消息段数组(用于插入剩余文本) * @param segmentIndex - 当前消息段索引 * @param typedLiteralFieldMap - 自定义字段映射 * @returns 匹配响应 */ private static matchParameter; /** * 匹配剩余参数令牌 * * 收集剩余的所有消息段或指定类型的消息段。 * 支持类型限制,遇到第一个不匹配的类型就停止收集。 * * @param token - 剩余参数令牌 * @param segments - 消息段数组 * @param segmentIndex - 开始收集的位置 * @returns 匹配响应 */ private static matchRestParameter; /** * 分割文本 * * 将文本按照指定模式分割为前文本、匹配文本和后文本。 * 用于类型化字面量的包含匹配。 * * @param text - 原始文本 * @param pattern - 匹配模式 * @returns 分割后的文本对象 */ private static splitText; }