/** * Base Tokenizer Class * * Abstract base class for language-specific tokenizers. * Provides keyword management, morphological normalization, * and high-level token extraction methods. */ import type { LanguageToken, TokenKind, TokenStream, LanguageTokenizer } from '../types'; import type { MorphologicalNormalizer, NormalizationResult } from './morphology/types'; import { type ValueExtractor, type KeywordEntry } from '../../interfaces/value-extractor'; import { type TimeUnitMapping } from './token-utils'; export type { KeywordEntry }; /** * Profile interface for keyword derivation. * Matches the structure of LanguageProfile but only includes fields needed for tokenization. */ export interface TokenizerProfile { readonly keywords?: Record; readonly references?: Record; readonly roleMarkers?: Record; readonly possessive?: { readonly marker: string; readonly markerPosition: 'after-object' | 'between' | 'before-property'; readonly specialForms?: Record; readonly usePossessiveAdjectives?: boolean; readonly keywords?: Record; }; } /** * Abstract base class for language-specific tokenizers. * Provides common functionality for CSS selectors, strings, and numbers. */ export declare abstract class BaseTokenizer implements LanguageTokenizer { abstract readonly language: string; abstract readonly direction: 'ltr' | 'rtl'; /** Optional morphological normalizer for this language */ protected normalizer?: MorphologicalNormalizer; /** Keywords derived from profile, sorted longest-first for greedy matching */ protected profileKeywords: KeywordEntry[]; /** * Space-containing profile keywords (multi-word phrases), longest-first. * Used by `tryMultiWordKeyword` so natural spaced forms (hi `मेल खाता`, * vi `chuyển đổi`, es `tecla abajo`, …) tokenize as ONE keyword — the * profile-driven replacement for the per-language hardcoded compound lists. * Empty for no-space (CJK) languages, so they are unaffected. */ protected multiWordKeywords: KeywordEntry[]; /** Map for O(1) keyword lookups by lowercase native word */ protected profileKeywordMap: Map; /** * The raw EXTRAS list passed to initializeKeywordsFromProfile, kept pre-dedup. * The keyword map is keyed by native word with last-wins insertion, so a * duplicate native word inside the extras silently shadows the earlier entry * (e.g. a `nächste→closest` entry shadowing `nächste→next` broke German * positional expressions). Exposed so consistency tests can detect such * intra-extras collisions, which are invisible in the deduplicated map. */ private rawExtraEntries; /** Raw extras as passed in, pre-dedup — for consistency tests. */ getExtraKeywordEntries(): readonly KeywordEntry[]; /** * Pluggable value extractors for domain-specific syntax. * When registered, BaseTokenizer will use extractor-based tokenization instead of legacy methods. */ protected extractors: ValueExtractor[]; /** * Tokenize input string to token stream. * Delegates to extractor-based tokenization if extractors are registered, * otherwise subclass must override this method. * * @param input - Input string to tokenize * @returns Token stream */ tokenize(input: string): TokenStream; abstract classifyToken(token: string): TokenKind; /** * Register a value extractor for domain-specific syntax. * Extractors are tried in registration order during tokenization. * Context-aware extractors automatically receive the tokenizer context. * * @param extractor - Value extractor to register */ registerExtractor(extractor: ValueExtractor): void; /** * Register multiple value extractors at once. * * @param extractors - Array of value extractors to register */ registerExtractors(extractors: ValueExtractor[]): void; /** * Clear all registered extractors. * Returns tokenizer to legacy mode. */ clearExtractors(): void; /** * Check if this tokenizer is using extractor-based tokenization. * Returns true if any extractors are registered. */ protected isUsingExtractors(): boolean; /** * Tokenize input using registered value extractors. * This is the new path - extractors handle all syntax detection. * * @param input - Input string to tokenize * @returns Token stream */ protected tokenizeWithExtractors(input: string): TokenStream; /** * ASCII word of the shape the English word-walker produces. Excludes `:`, so a * token that already carries a qualifier never merges again — `a:b:c` yields * `a:b` + `:c`, byte-matching the English extractor's single-segment merge. */ private static readonly ASCII_WORD; /** `:name` — only a variable-ref-style extractor ever emits this token shape. */ private static readonly COLON_QUALIFIER; /** * Fuse `name` + `:qualifier` into ONE identifier (`draggable:start`). * * `:name` is hyperscript's local-variable sigil, but a colon IMMEDIATELY * preceded by an identifier is a qualifier (custom event namespace), not a * sigil. The English tokenizer already merges these inside * EnglishKeywordExtractor; this post-pass gives the other 23 languages the * same stream. Strict position adjacency is the discriminator: whitespace * between the tokens (`trigger :start`) breaks `end === start`, so a spaced * local-variable reference survives untouched. * * Self-gating for non-hyperscript tokenizers (domain DSLs): their extractor * sets tokenize `:` as bare punctuation (length 1), which never matches * COLON_QUALIFIER, so this pass is a no-op for them. */ protected mergeColonQualifiedNames(tokens: LanguageToken[]): LanguageToken[]; /** * Classify an unknown character when no extractor matches. * Provides sensible defaults for common syntax. * * @param char - Character to classify * @returns Token kind */ protected classifyUnknownChar(char: string): TokenKind; /** * Check if current position is a property access (obj.prop) vs CSS selector (.active). * Property access: no whitespace before '.', previous token is identifier/keyword/selector. * Also detects standalone method calls: .identifier( pattern. * * Returns true if '.' was emitted as an operator token and pos should advance by 1. * Returns false if this is a CSS selector and should be handled by trySelector(). */ protected tryPropertyAccess(input: string, pos: number, tokens: LanguageToken[]): boolean; /** * Initialize keyword mappings from a language profile. * Builds a list of native→english mappings from: * - profile.keywords (primary + alternatives) * - profile.references (me, it, you, etc.) * - profile.roleMarkers (into, from, with, etc.) * * Results are sorted longest-first for greedy matching (important for non-space languages). * Extras take precedence over profile entries when there are duplicates. * * @param profile - Language profile containing keyword translations * @param extras - Additional keyword entries to include (literals, positional, events) */ protected initializeKeywordsFromProfile(profile: TokenizerProfile, extras?: KeywordEntry[]): void; /** * Remove diacritical marks from a word for normalization. * Primarily for Arabic (shadda, fatha, kasra, damma, sukun, etc.) * but could be extended for other languages. * * @param word - Word to normalize * @returns Word without diacritics */ protected removeDiacritics(word: string): string; /** * Try to match a keyword from profile at the current position. * Uses longest-first greedy matching (important for non-space languages). * * @param input - Input string * @param pos - Current position * @returns Token if matched, null otherwise */ protected tryProfileKeyword(input: string, pos: number): LanguageToken | null; /** * Match the longest multi-word (space-containing) profile keyword at `pos`, * requiring the match to end at a word boundary. The profile-driven * counterpart of the per-language hardcoded compound lists (the hindi and * vietnamese keyword extractors). Returns a keyword token (with the normalized * form) or null. Case-sensitive against the stored native form, mirroring * `tryProfileKeyword`/`isKeywordStart` (the i18n dicts emit a fixed surface * case). No-op when `multiWordKeywords` is empty (no-space/CJK languages). * * @param input - Input string * @param pos - Current position (must be a token-start boundary) * @param isWordChar - End-boundary predicate (defaults to Unicode letter/digit/_) */ protected tryMultiWordKeyword(input: string, pos: number, isWordChar?: (char: string) => boolean): LanguageToken | null; /** * Check if the remaining input starts with any known keyword. * Useful for non-space languages to detect word boundaries. * * @param input - Input string * @param pos - Current position * @returns true if a keyword starts at this position */ protected isKeywordStart(input: string, pos: number): boolean; /** * Check if a known keyword starts at the given position AND ends at a word * boundary (end of input or a non-word character). * * Space-delimited languages must use this (not `isKeywordStart`) for * word-walk break checks: the keyword table includes English canonical * fallbacks (me, it, you, …), so a raw `startsWith` check splits any native * word with an embedded fallback mid-word (e.g. Quechua ñit'iy contains * "it"). CJK/no-space tokenizers rely on mid-text keyword starts and must * keep using `isKeywordStart`. * * @param input - Input string * @param pos - Current position * @param isWordChar - Language-specific word-character predicate; pass the * tokenizer's letter classifier so e.g. the Quechua glottal apostrophe * counts as part of a word. Defaults to Unicode letters/digits/underscore. * @returns true if a keyword starts here and is not followed by a word char */ protected isKeywordStartAtBoundary(input: string, pos: number, isWordChar?: (char: string) => boolean): boolean; /** * Look up a keyword by native word (case-insensitive, diacritic-insensitive). * O(1) lookup using the keyword map. * * The map is INDEXED both with and without diacritics (see * `initializeKeywordsFromProfile`), so a stripped QUERY is the other half of * that: it lets a surface form carrying harakat the profile does not happen to * spell still find its entry. Only consulted after the exact lookup misses, so * every previously-matching word resolves byte-identically. * * Half-implementing this — indexing stripped but querying exact — is what made * diacritized `بَدِّل` (toggle) tokenize as `kind=particle normalized=with`: * `isKeyword` returned false, so the guard in `ArabicProcliticExtractor` that * exists to prevent exactly that handed the word on, and the single-char `ب` * bi- proclitic claimed it. A wrong CONCEPT, not a failed parse. * * @param native - Native word to look up * @returns KeywordEntry if found, undefined otherwise */ protected lookupKeyword(native: string): KeywordEntry | undefined; /** * Check if a word is a known keyword (case-insensitive, diacritic-insensitive). * O(1) lookup using the keyword map. See {@link lookupKeyword}. * * @param native - Native word to check * @returns true if the word is a keyword */ protected isKeyword(native: string): boolean; /** * Set the morphological normalizer for this tokenizer. */ setNormalizer(normalizer: MorphologicalNormalizer): void; /** * Try to normalize a word using the morphological normalizer. * Returns null if no normalizer is set or normalization fails. * * Note: We don't check isNormalizable() here because the individual tokenizers * historically called normalize() directly without that check. The normalize() * method itself handles returning noChange() for words that can't be normalized. */ protected tryNormalize(word: string): NormalizationResult | null; /** * Try morphological normalization and keyword lookup. * * If the word can be normalized to a stem that matches a known keyword, * returns a keyword token with morphological metadata (stem, stemConfidence). * * This is the common pattern for handling conjugated verbs across languages: * 1. Normalize the word (e.g., "toggled" → "toggle") * 2. Look up the stem in the keyword map * 3. Create a token with both the original form and stem metadata * * @param word - The word to normalize and look up * @param startPos - Start position for the token * @param endPos - End position for the token * @returns Token if stem matches a keyword, null otherwise */ protected tryMorphKeywordMatch(word: string, startPos: number, endPos: number): LanguageToken | null; /** * Try to extract a CSS selector at the current position. */ protected trySelector(input: string, pos: number): LanguageToken | null; /** * Try to extract an event modifier at the current position. * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy) */ protected tryEventModifier(input: string, pos: number): LanguageToken | null; /** * Try to extract a string literal at the current position. */ protected tryString(input: string, pos: number): LanguageToken | null; /** * Try to extract a number at the current position. */ protected tryNumber(input: string, pos: number): LanguageToken | null; /** * Configuration for native language time units. * Maps patterns to their standard suffix (ms, s, m, h). */ protected static readonly STANDARD_TIME_UNITS: readonly TimeUnitMapping[]; /** * Try to match a time unit from a list of patterns. * * @param input - Input string * @param pos - Position after the number * @param timeUnits - Array of time unit mappings (native pattern → standard suffix) * @param skipWhitespace - Whether to skip whitespace before time unit (default: false) * @returns Object with matched suffix and new position, or null if no match */ protected tryMatchTimeUnit(input: string, pos: number, timeUnits: readonly TimeUnitMapping[], skipWhitespace?: boolean): { suffix: string; endPos: number; } | null; /** * Parse a base number (sign, integer, decimal) without time units. * Returns the number string and end position. * * @param input - Input string * @param startPos - Start position * @param allowSign - Whether to allow +/- sign (default: true) * @returns Object with number string and end position, or null */ protected parseBaseNumber(input: string, startPos: number, allowSign?: boolean): { number: string; endPos: number; } | null; /** * Try to extract a number with native language time units. * * This is a template method that handles the common pattern: * 1. Parse the base number (sign, integer, decimal) * 2. Try to match native language time units * 3. Fall back to standard time units (ms, s, m, h) * * @param input - Input string * @param pos - Start position * @param nativeTimeUnits - Language-specific time unit mappings * @param options - Configuration options * @returns Token if number found, null otherwise */ protected tryNumberWithTimeUnits(input: string, pos: number, nativeTimeUnits: readonly TimeUnitMapping[], options?: { allowSign?: boolean; skipWhitespace?: boolean; }): LanguageToken | null; /** * Try to extract a URL at the current position. * Handles /path, ./path, ../path, //domain.com, http://, https:// */ protected tryUrl(input: string, pos: number): LanguageToken | null; /** * Try to extract a variable reference (:varname) at the current position. * In hyperscript, :x refers to a local variable named x. */ protected tryVariableRef(input: string, pos: number): LanguageToken | null; /** * Try to extract an operator or punctuation token at the current position. * Handles two-character operators (==, !=, etc.) and single-character operators. */ protected tryOperator(input: string, pos: number): LanguageToken | null; /** * Try to match a multi-character particle from a list. * * Used by languages like Japanese, Korean, and Chinese that have * multi-character particles (e.g., Japanese から, まで, より). * * @param input - Input string * @param pos - Current position * @param particles - Array of multi-character particles to match * @returns Token if matched, null otherwise */ protected tryMultiCharParticle(input: string, pos: number, particles: readonly string[]): LanguageToken | null; } /** * Configuration for createSimpleTokenizer. * * Creates a tokenizer from declarative config instead of a class definition. * Covers the common pattern used by domain packages (SQL, BDD, JSX). * * **Keyword resolution** uses two additive paths: * 1. `keywords` — explicit list, checked first. Respects `caseInsensitive`. * 2. `keywordProfile` — populates BaseTokenizer's profile keyword map via * `initializeKeywordsFromProfile()`. Checked second via `isKeyword()`, which * always lowercases (harmless for CJK/Arabic; notable for Latin scripts * with `caseInsensitive: false`). Provides normalization metadata for * non-Latin scripts. */ export interface SimpleTokenizerConfig { /** ISO 639-1 language code */ language: string; /** Text direction (default: 'ltr') */ direction?: 'ltr' | 'rtl'; /** Keywords to recognize (lowercased for lookup if caseInsensitive) */ keywords: string[]; /** Extra keyword entries for non-Latin normalization */ keywordExtras?: KeywordEntry[]; /** Profile for initializeKeywordsFromProfile (for non-Latin scripts) */ keywordProfile?: TokenizerProfile; /** Include operator classification (default: false). Uses DEFAULT_OPERATORS from OperatorExtractor. */ includeOperators?: boolean; /** Case-insensitive keyword matching (default: true) */ caseInsensitive?: boolean; /** Custom extractors registered BEFORE default extractors */ customExtractors?: ValueExtractor[]; } /** * Create a tokenizer from declarative configuration. * * Eliminates the boilerplate of extending BaseTokenizer for simple domain tokenizers. * Handles keyword classification, optional operator support, and non-Latin keyword setup. * * @example * ```typescript * const englishSQL = createSimpleTokenizer({ * language: 'en', * keywords: ['select', 'insert', 'update', 'delete', 'from', 'into', 'where', 'set', 'values'], * includeOperators: true, * caseInsensitive: true, * }); * ``` */ export declare function createSimpleTokenizer(config: SimpleTokenizerConfig): LanguageTokenizer; //# sourceMappingURL=base-tokenizer.d.ts.map