@lokascript/framework 2.11.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +301 -1
- package/dist/api/domain-registry.d.ts +2 -2
- package/dist/api/index.js.map +1 -1
- package/dist/core/index.js +7 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/tokenization/base-tokenizer.d.ts.map +1 -1
- package/dist/core/tokenization/index.js +7 -1
- package/dist/core/tokenization/index.js.map +1 -1
- package/dist/index.cjs +7 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/interfaces/value-extractor.d.ts.map +1 -1
- package/dist/multilingual/index.js +7 -1
- package/dist/multilingual/index.js.map +1 -1
- package/dist/prompts/prompt-generator.d.ts +1 -1
- package/package.json +2 -2
- package/src/api/domain-registry.ts +2 -2
- package/src/core/tokenization/apostrophe-possessive.test.ts +42 -0
- package/src/core/tokenization/base-tokenizer.ts +21 -3
- package/src/interfaces/value-extractor.ts +10 -0
- package/src/prompts/prompt-generator.ts +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/core/types.ts","../src/core/logger.ts","../src/core/pattern-matching/utils/type-validation.ts","../src/core/pattern-matching/utils/possessive-keywords.ts","../src/core/pattern-matching/pattern-matcher.ts","../src/generation/pattern-generator.ts","../src/generation/renderer.ts","../src/grammar/types.ts","../src/grammar/transformer.ts","../src/interfaces/dictionary.ts","../src/interfaces/profile-provider.ts","../src/interfaces/value-extractor.ts","../src/ir/references.ts","../src/ir/explicit-parser.ts","../src/ir/explicit-renderer.ts","../src/ir/json-schema.ts","../src/ir/protocol-json.ts","../src/ir/from-interchange.ts","../src/ir/to-runtime-ast.ts","../src/api/create-dsl.ts","../src/prompts/prompt-generator.ts","../src/training/schema-synthesizer.ts","../src/feedback/feedback-formatter.ts","../src/api/domain-registry.ts","../src/api/dispatcher.ts","../src/aot/domain-scanner.ts","../src/aot/aot-orchestrator.ts","../src/aot/registry-bridge.ts","../src/schema/command-schema.ts","../src/generation/diagnostics.ts","../src/core/tokenization/token-utils.ts","../src/core/tokenization/extractors.ts","../src/core/tokenization/extractors/operator.ts","../src/core/tokenization/extractors/punctuation.ts","../src/core/tokenization/default-extractors.ts","../src/core/tokenization/base-tokenizer.ts","../src/multilingual/builders.ts","../src/core/tokenization/char-classifiers.ts","../src/core/tokenization/morphology/types.ts","../src/core/tokenization/morphology/base-normalizer.ts","../src/training/jsonl-writer.ts","../src/feedback/confidence-gate.ts","../src/feedback/pattern-tracker.ts","../src/parsing/multi-statement.ts"],"sourcesContent":["/**\n * @lokascript/framework - Generic framework for building multilingual DSLs\n *\n * This framework provides the building blocks for creating domain-specific languages\n * that work across multiple human languages (English, Japanese, Spanish, etc.) with\n * semantic parsing and grammar transformation.\n *\n * @example\n * ```typescript\n * import { createMultilingualDSL } from '@lokascript/framework';\n *\n * const myDSL = createMultilingualDSL({\n * schemas: [{ action: 'select', roles: [...] }],\n * languages: [{ code: 'en', profile: {...}, tokenizer: {...} }],\n * codeGenerator: (node) => generateSQL(node)\n * });\n *\n * myDSL.parse('select name from users', 'en');\n * myDSL.translate('select name from users', 'en', 'ja');\n * ```\n */\n\n// Main API\nexport * from './api';\n\n// AOT (generalized ahead-of-time compilation)\nexport * from './aot';\n\n// Interfaces (for dependency injection)\nexport * from './interfaces';\n\n// Core modules\nexport * from './schema';\nexport * from './generation';\n\n// Grammar exports - explicitly list to avoid PatternMatcher conflict with core\nexport { GrammarTransformer } from './grammar/transformer';\nexport type { TransformerConfig } from './grammar/transformer';\nexport { reorderRoles, insertMarkers, joinTokens } from './grammar/types';\nexport type {\n LanguageProfile,\n PatternTransform,\n ParsedElement,\n WordOrder,\n GrammaticalMarker,\n AdpositionType,\n} from './grammar/types';\n\n// Multilingual bridge — inject semantic language profiles into domain DSLs\n// (explicit list: the module also re-exports grammar types already exported above)\nexport {\n buildPatternProfile,\n buildDomainTokenizer,\n buildLanguageConfig,\n deriveRoleMarkers,\n} from './multilingual';\nexport type {\n GrammarProfileSlice,\n DomainVocabulary,\n DomainKeywordTranslation,\n DomainKeywordEntry,\n RoleMarkerSlice,\n TokenizationSlice,\n VerbSlice,\n DomainTokenizerOptions,\n LanguageConfigMeta,\n} from './multilingual';\n\n// Core - export classes and utilities\nexport * from './core';\n\n// Re-export key types for convenience\nexport type {\n ActionType,\n SemanticRole as SemanticRoleType,\n SemanticValue,\n SemanticNode,\n CommandSemanticNode,\n EventHandlerSemanticNode,\n ConditionalSemanticNode,\n CompoundSemanticNode,\n LoopSemanticNode,\n LiteralValue,\n SelectorValue,\n ReferenceValue,\n PropertyPathValue,\n ExpressionValue,\n SemanticMetadata,\n SourcePosition,\n LanguageToken,\n TokenStream,\n LanguageTokenizer,\n LanguagePattern,\n // v1.2 types\n Annotation,\n ProtocolDiagnostic,\n AsyncVariant,\n MatchArm,\n LSEEnvelope,\n} from './core/types';\n\nexport type { CommandSchema, RoleSpec } from './schema';\n\n// Renderer\nexport type {\n NaturalLanguageRenderer,\n KeywordTable,\n MarkerTable,\n RendererConfig,\n DomainRenderFn,\n DomainRendererConfig,\n} from './generation/renderer';\nexport {\n lookupKeyword,\n lookupMarker,\n buildPhrase,\n buildTablesFromProfiles,\n detectWordOrders,\n createSchemaRenderer,\n createDomainRenderer,\n} from './generation/renderer';\n\n// Diagnostics\nexport type {\n DiagnosticSeverity,\n Diagnostic,\n DiagnosticResult,\n DiagnosticSummary,\n DiagnosticCollector,\n DiagnosticOptions,\n} from './generation/diagnostics';\nexport { createDiagnosticCollector, fromError, filterBySeverity } from './generation/diagnostics';\n\nexport type {\n LanguageConfig,\n DSLConfig,\n MultilingualDSL,\n CodeGenerator,\n DomainExtension,\n ExtensionVocabulary,\n ValidationResult,\n CompileResult,\n DomainDescriptor,\n MCPToolDefinition,\n MCPToolResponse,\n DispatchResult,\n CompositeParseResult,\n CompositeStatement,\n CompositeError,\n DispatcherOptions,\n} from './api';\n\n// `createMultilingualDSL` is the package's primary entry point, so it is\n// exported by name rather than reaching consumers only through `export * from\n// './api'` above.\nexport { createMultilingualDSL, DomainRegistry, CrossDomainDispatcher } from './api';\n\n// Re-export helper functions\nexport {\n createLiteral,\n createSelector,\n createReference,\n createPropertyPath,\n createExpression,\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createCompoundNode,\n createLoopNode,\n extractValue,\n extractRoleValue,\n // v1.2 factories\n createTryNode,\n createAsyncNode,\n createMatchNode,\n} from './core/types';\n\nexport { defineCommand, defineRole } from './schema';\nexport { createSimpleTokenizer } from './core/tokenization/base-tokenizer';\nexport type { SimpleTokenizerConfig } from './core/tokenization/base-tokenizer';\n\n// Morphological normalization base class and types\nexport { BaseMorphologicalNormalizer } from './core/tokenization/morphology/base-normalizer';\nexport type {\n ConjugationEnding,\n NormalizerConfig,\n} from './core/tokenization/morphology/base-normalizer';\n\n// IR (Intermediate Representation) — explicit syntax, JSON conversion, reference validation\nexport * from './ir';\n\n// LLM Prompt Generation — auto-generate system prompts from CommandSchema[]\nexport * from './prompts';\n\n// Training Data Generation — synthesize (natural_language, LSE) pairs from schemas\nexport * from './training';\n\n// Feedback Loop — structured errors, disambiguation, pattern tracking\nexport * from './feedback';\n\n// Multi-statement parser\nexport { createMultiStatementParser, accumulateBlocks } from './parsing/multi-statement';\nexport type {\n MultiStatementParser,\n MultiStatementConfig,\n MultiStatementResult,\n ParsedStatement,\n StatementError,\n StatementBlock,\n BlockConfig,\n BlockResult,\n KeywordMap,\n WordOrderHint,\n} from './parsing/multi-statement';\n","/**\n * Core Types — re-exported from @lokascript/intent + framework-specific extensions\n *\n * The universal semantic types (SemanticNode, SemanticValue, etc.) now live in\n * @lokascript/intent and are re-exported here for backward compatibility.\n *\n * Framework-specific types (tokenization, pattern matching) are defined below.\n */\n\n// =============================================================================\n// Re-export everything from @lokascript/intent\n// =============================================================================\n\nexport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n ExpectedType,\n LiteralValue,\n SelectorValue,\n ReferenceValue,\n PropertyPathValue,\n ExpressionValue,\n FlagValue,\n Annotation,\n ProtocolDiagnostic,\n AsyncVariant,\n MatchArm,\n SemanticNode,\n SemanticMetadata,\n SourcePosition,\n CommandSemanticNode,\n EventHandlerSemanticNode,\n EventModifiers,\n ConditionalSemanticNode,\n CompoundSemanticNode,\n LoopVariant,\n LoopSemanticNode,\n LSEEnvelope,\n} from '@lokascript/intent';\n\nexport {\n createLiteral,\n createSelector,\n createReference,\n createPropertyPath,\n createExpression,\n createFlag,\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createCompoundNode,\n createLoopNode,\n createTryNode,\n createAsyncNode,\n createMatchNode,\n extractValue,\n extractRoleValue,\n getRoleValue,\n} from '@lokascript/intent';\n\n// =============================================================================\n// Framework-specific types (multilingual DSL infrastructure)\n// =============================================================================\n\nimport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n SelectorValue,\n ExpectedType,\n SourcePosition,\n} from '@lokascript/intent';\n\n/**\n * Token kind - categorizes what type of token this is.\n */\nexport type TokenKind =\n | 'keyword' // Command or modifier keyword\n | 'selector' // CSS selector or identifier (#id, .class, table-name)\n | 'literal' // String or number literal\n | 'particle' // Grammatical particle (を, に, من)\n | 'conjunction' // Grammatical conjunction\n | 'event-modifier' // Event modifier (.once, .debounce(300))\n | 'identifier' // Generic identifier\n | 'operator' // Operators (., +, -, etc.)\n | 'punctuation' // Punctuation (parentheses, etc.)\n | 'url'; // URL or path\n\n/**\n * A language token - the result of tokenization.\n */\nexport interface LanguageToken {\n readonly value: string;\n readonly kind: TokenKind;\n readonly position: SourcePosition;\n readonly normalized?: string;\n readonly stem?: string;\n readonly stemConfidence?: number;\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Token stream - provides sequential access to tokens with backtracking.\n */\nexport interface TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n peek(offset?: number): LanguageToken | null;\n advance(): LanguageToken;\n isAtEnd(): boolean;\n mark(): StreamMark;\n reset(mark: StreamMark): void;\n position(): number;\n}\n\nexport interface StreamMark {\n readonly position: number;\n}\n\n/**\n * Language tokenizer interface - converts text to tokens.\n */\nexport interface LanguageTokenizer {\n readonly language: string;\n readonly direction: 'ltr' | 'rtl';\n tokenize(input: string): TokenStream;\n classifyToken(token: string): TokenKind;\n}\n\n// =============================================================================\n// Pattern Matching Types\n// =============================================================================\n\nexport interface LanguagePattern {\n readonly id: string;\n readonly language: string;\n readonly command: ActionType;\n readonly priority: number;\n readonly template: PatternTemplate;\n readonly extraction: ExtractionRules;\n readonly constraints?: PatternConstraints;\n}\n\nexport interface PatternTemplate {\n readonly format: string;\n readonly tokens: PatternToken[];\n}\n\nexport type PatternToken = LiteralPatternToken | RolePatternToken | GroupPatternToken;\n\nexport interface LiteralPatternToken {\n readonly type: 'literal';\n readonly value: string;\n readonly alternatives?: string[];\n}\n\nexport interface RolePatternToken {\n readonly type: 'role';\n readonly role: SemanticRole;\n readonly optional?: boolean;\n readonly expectedTypes?: Array<ExpectedType>;\n readonly greedy?: boolean;\n}\n\nexport interface GroupPatternToken {\n readonly type: 'group';\n readonly tokens: PatternToken[];\n readonly optional?: boolean;\n}\n\nexport interface ExtractionRules {\n readonly [role: string]: ExtractionRule;\n}\n\nexport interface ExtractionRule {\n readonly position?: number;\n readonly marker?: string;\n readonly markerAlternatives?: string[];\n readonly transform?: (raw: string) => SemanticValue;\n readonly default?: SemanticValue;\n readonly value?: string;\n readonly fromRole?: string;\n}\n\nexport interface PatternConstraints {\n readonly requiredRoles?: SemanticRole[];\n readonly forbiddenRoles?: SemanticRole[];\n readonly validPatientTypes?: Array<SelectorValue['selectorKind']>;\n readonly conflictsWith?: string[];\n}\n\nexport interface PatternMatchResult {\n readonly pattern: LanguagePattern;\n readonly captured: ReadonlyMap<SemanticRole, SemanticValue>;\n readonly consumedTokens: number;\n readonly confidence: number;\n}\n\nexport interface PatternMatchError {\n readonly message: string;\n readonly position: SourcePosition;\n readonly expectedPatterns?: string[];\n readonly partialMatch?: Partial<PatternMatchResult>;\n}\n","/**\n * Debug Logging System\n *\n * Provides environment-aware debug logging for the framework.\n * Enable via DEBUG environment variable or programmatically.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n isEnabled(): boolean;\n}\n\nclass DebugLogger {\n private enabled: boolean;\n private namespace: string;\n\n constructor(namespace: string) {\n this.namespace = namespace;\n this.enabled = this.checkEnabled();\n }\n\n private checkEnabled(): boolean {\n // Check if running in Node.js\n if (typeof process !== 'undefined' && process.env) {\n const DEBUG = process.env.DEBUG || '';\n // Enable if DEBUG=* or DEBUG=framework:* or DEBUG=framework:namespace\n return (\n DEBUG === '*' ||\n DEBUG.includes('framework:*') ||\n DEBUG.includes(`framework:${this.namespace}`)\n );\n }\n return false;\n }\n\n private log(level: LogLevel, message: string, ...args: any[]): void {\n if (!this.enabled) return;\n\n const prefix = `[framework:${this.namespace}]`;\n const timestamp = new Date().toISOString();\n\n switch (level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(`${timestamp} ${prefix} INFO:`, message, ...args);\n break;\n case 'warn':\n // eslint-disable-next-line no-console\n console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);\n break;\n case 'error':\n // eslint-disable-next-line no-console\n console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);\n break;\n }\n }\n\n debug(message: string, ...args: any[]): void {\n this.log('debug', message, ...args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.log('error', message, ...args);\n }\n\n /**\n * Check if logging is enabled for this namespace.\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n\n /**\n * Programmatically enable logging for this namespace.\n */\n enable(): void {\n this.enabled = true;\n }\n\n /**\n * Programmatically disable logging for this namespace.\n */\n disable(): void {\n this.enabled = false;\n }\n}\n\n/**\n * Create a logger for a specific namespace.\n *\n * @param namespace - Logger namespace (e.g., 'pattern-matcher', 'tokenizer')\n * @returns Logger instance\n *\n * @example\n * const logger = createLogger('pattern-matcher');\n * logger.debug('Matching pattern:', pattern.id);\n * logger.warn('Low confidence match:', confidence);\n */\nexport function createLogger(namespace: string): Logger {\n return new DebugLogger(namespace);\n}\n\n/**\n * No-op logger that does nothing.\n * Useful for disabling logging in production builds.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n isEnabled: () => false,\n};\n","/**\n * Type Validation Utility\n *\n * Shared utilities for validating semantic value types against expected types.\n * Used by pattern-matcher to validate captured role values.\n */\n\nimport type { SemanticValue } from '../../types';\n\n/**\n * Semantic value type strings.\n */\nexport type SemanticValueType = SemanticValue['type'];\n\n/**\n * Check if a value type matches any of the expected types.\n *\n * The 'expression' type is treated as a wildcard that matches any value.\n * The 'property-path' type is compatible with selector, reference, and expression.\n *\n * @param actualType The actual type of the value\n * @param expectedTypes Array of expected types\n * @returns True if the type is compatible\n */\nexport function isTypeCompatible(\n actualType: SemanticValueType | string,\n expectedTypes: (SemanticValueType | string)[]\n): boolean {\n // Empty expected types means any type is valid\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n // Direct match\n if (expectedTypes.includes(actualType)) {\n return true;\n }\n\n // 'expression' is always compatible (wildcard)\n if (expectedTypes.includes('expression')) {\n return true;\n }\n\n // 'property-path' is compatible with selector, reference, and expression\n if (actualType === 'property-path') {\n return expectedTypes.some(t => ['selector', 'reference', 'expression'].includes(t));\n }\n\n return false;\n}\n\n/**\n * Validate a semantic value against expected types.\n *\n * @param value The semantic value to validate\n * @param expectedTypes Array of expected types (empty means any type is valid)\n * @returns True if the value type is valid\n */\nexport function validateValueType(\n value: SemanticValue,\n expectedTypes?: (SemanticValueType | string)[]\n): boolean {\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n return isTypeCompatible(value.type, expectedTypes);\n}\n\n/**\n * Check if a value is a CSS selector.\n */\nexport function isCSSSelector(value: string): boolean {\n return value.startsWith('.') || value.startsWith('#') || value.startsWith('<');\n}\n\n/**\n * Check if a value is a class name (starts with .).\n */\nexport function isClassName(value: string): boolean {\n return value.startsWith('.');\n}\n\n/**\n * Check if a value is an ID selector (starts with #).\n */\nexport function isIdSelector(value: string): boolean {\n return value.startsWith('#');\n}\n\n/**\n * Check if a value is a CSS property reference (starts with *).\n */\nexport function isCSSPropertyRef(value: string): boolean {\n return value.startsWith('*');\n}\n\n/**\n * Check if a value is a numeric value.\n */\nexport function isNumericValue(value: string): boolean {\n // Handle duration values (e.g., \"100ms\", \"2s\")\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n return true;\n }\n\n // Plain number\n const num = parseFloat(value);\n return !isNaN(num) && isFinite(num);\n}\n\n/**\n * Check if a value is a property name (identifier-like).\n */\nexport function isPropertyName(value: string): boolean {\n // Property names are identifiers (start with letter or _, contain alphanumeric)\n return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);\n}\n\n/**\n * Check if a value is a variable reference (starts with :).\n */\nexport function isVariableRef(value: string): boolean {\n return value.startsWith(':');\n}\n\n/**\n * Check if a value is a built-in reference (me, you, it, etc.).\n */\nexport function isBuiltInReference(value: string): boolean {\n const builtIns = new Set(['me', 'you', 'it', 'result', 'event', 'target', 'body']);\n return builtIns.has(value.toLowerCase());\n}\n","/**\n * Possessive Keywords Utility\n *\n * Provides functions to look up possessive keywords from language profiles.\n * Used by pattern-matcher to recognize possessive expressions like \"my value\".\n */\n\n/**\n * Minimal profile interface for possessive keyword lookup.\n */\nexport interface PossessiveProfile {\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n/**\n * Get the reference for a possessive keyword from a profile.\n *\n * @param profile Language profile\n * @param keyword Possessive keyword (e.g., 'my', 'your', 'its')\n * @returns The reference (e.g., 'me', 'you', 'it') or undefined if not found\n */\nexport function getPossessiveReference(\n profile: PossessiveProfile | undefined,\n keyword: string\n): string | undefined {\n return profile?.possessive?.keywords?.[keyword];\n}\n\n/**\n * Check if a keyword is a possessive keyword in the given profile.\n *\n * @param profile Language profile\n * @param keyword Keyword to check\n * @returns True if the keyword is a possessive keyword\n */\nexport function isPossessiveKeyword(\n profile: PossessiveProfile | undefined,\n keyword: string\n): boolean {\n return profile?.possessive?.keywords?.[keyword] !== undefined;\n}\n\n/**\n * Get all possessive keywords from a profile.\n *\n * @param profile Language profile\n * @returns Record of possessive keywords to references, or empty object\n */\nexport function getAllPossessiveKeywords(\n profile: PossessiveProfile | undefined\n): Record<string, string> {\n return profile?.possessive?.keywords ?? {};\n}\n","/**\n * Pattern Matcher\n *\n * Matches tokenized input against language patterns to extract semantic roles.\n * This is the core algorithm for multilingual parsing.\n */\n\nimport type {\n LanguagePattern,\n PatternToken,\n PatternMatchResult,\n ReferenceValue,\n SemanticRole,\n SemanticValue,\n TokenStream,\n LanguageToken,\n} from '../types';\nimport { createSelector, createLiteral, createReference, createPropertyPath } from '../types';\nimport { createLogger } from '../logger';\n\n/**\n * Helper to check if a value is a built-in reference.\n * In the generic framework, we don't assume any built-in references.\n * DSLs that need references (like hyperscript's 'me', 'it', 'you') should\n * handle them in their tokenizer or provide a custom reference validator.\n *\n * For generic DSLs, identifiers are treated as expressions by default.\n */\nfunction isValidReference(_value: string): boolean {\n // In generic framework, no built-in references\n // Identifiers should be expressions\n return false;\n}\nimport { isTypeCompatible } from './utils/type-validation';\nimport { getPossessiveReference } from './utils/possessive-keywords';\n\n/**\n * Minimal profile interface needed by PatternMatcher.\n * DSLs can provide this to enable possessive handling and language-specific features.\n */\nexport interface PatternMatcherProfile {\n readonly code: string;\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Pattern Matcher\n// =============================================================================\n\nexport class PatternMatcher {\n /** Maximum tokens to scan ahead when looking for a group's leading marker */\n private static readonly MAX_MARKER_SCAN = 3;\n\n /** Debug logger */\n private logger = createLogger('pattern-matcher');\n\n /** Current language profile for the pattern being matched */\n private currentProfile: PatternMatcherProfile | undefined;\n\n /**\n * Safely convert a value to lowercase string.\n * Provides protection against non-string values at runtime.\n */\n private safeToLowerCase(value: unknown): string {\n if (typeof value === 'string') {\n return value.toLowerCase();\n }\n if (value === null || value === undefined) {\n return '';\n }\n return String(value).toLowerCase();\n }\n\n /**\n * Try to match a single pattern against the token stream.\n * Returns the match result or null if no match.\n *\n * @param tokens - Token stream to match against\n * @param pattern - Pattern to match\n * @param profile - Optional language profile for possessive handling\n */\n matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern,\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const mark = tokens.mark();\n const captured = new Map<SemanticRole, SemanticValue>();\n\n // Debug logging\n this.logger.debug('========================================');\n this.logger.debug('matchPattern ENTRY');\n this.logger.debug('Pattern ID:', pattern.id);\n this.logger.debug('Pattern command:', pattern.command);\n this.logger.debug('Pattern language:', pattern.language);\n this.logger.debug('Pattern template:', JSON.stringify(pattern.template, null, 2));\n\n if (this.logger.isEnabled()) {\n const firstTokens = [];\n for (let i = 0; i < 10; i++) {\n const t = tokens.peek(i);\n if (t)\n firstTokens.push({\n type: (t as any).type,\n value: (t as any).value,\n kind: (t as any).kind,\n });\n else break;\n }\n this.logger.debug('Input tokens (first 10):', firstTokens);\n this.logger.debug('Profile code:', profile?.code);\n }\n\n // Use provided profile for possessive keyword lookup\n this.currentProfile = profile;\n\n // Reset match counters for this pattern\n this.stemMatchCount = 0;\n this.totalKeywordMatches = 0;\n\n this.logger.debug('--- Calling matchTokenSequence ---');\n this.logger.debug('Pattern tokens to match:', JSON.stringify(pattern.template.tokens, null, 2));\n const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);\n this.logger.debug('matchTokenSequence returned:', success);\n this.logger.debug(\n 'Captured roles:',\n Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])\n );\n\n if (!success) {\n this.logger.debug('>>> MATCH FAILED - resetting token position');\n tokens.reset(mark);\n return null;\n }\n\n // Calculate confidence BEFORE applying defaults\n // This ensures defaulted roles don't artificially inflate confidence\n const confidence = this.calculateConfidence(pattern, captured);\n\n // Apply extraction rules to fill in any missing roles with defaults\n this.applyExtractionRules(pattern, captured);\n\n return {\n pattern,\n captured,\n consumedTokens: tokens.position() - mark.position,\n confidence,\n };\n }\n\n /**\n * Try to match multiple patterns, return the best match.\n *\n * @param tokens - Token stream to match against\n * @param patterns - Candidate patterns to try\n * @param profile - Optional language profile for possessive handling\n */\n matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[],\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const matches: PatternMatchResult[] = [];\n\n for (const pattern of patterns) {\n const mark = tokens.mark();\n const result = this.matchPattern(tokens, pattern, profile);\n\n if (result) {\n matches.push(result);\n }\n\n tokens.reset(mark);\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort by confidence and priority\n matches.sort((a, b) => {\n // First by priority\n const priorityDiff = b.pattern.priority - a.pattern.priority;\n if (priorityDiff !== 0) return priorityDiff;\n\n // Then by confidence\n const confidenceDiff = b.confidence - a.confidence;\n if (Math.abs(confidenceDiff) > 0.001) return confidenceDiff;\n\n // Then by tokens consumed (prefer more complete matches)\n return b.consumedTokens - a.consumedTokens;\n });\n\n // Re-consume tokens for the best match\n const best = matches[0];\n this.matchPattern(tokens, best.pattern);\n\n return best;\n }\n\n /**\n * Match a sequence of pattern tokens against the token stream.\n *\n * Supports bounded single-step backtracking: if an optional role consumes\n * a token and the immediately following pattern token fails, the matcher\n * resets to before the optional role and retries the failed token.\n */\n private matchTokenSequence(\n tokens: TokenStream,\n patternTokens: PatternToken[],\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n // Skip leading conjunctions for Arabic (proclitics: و, ف, ول, وب, etc.)\n // BUT NOT if the pattern explicitly expects a conjunction (proclitic patterns)\n const firstPatternToken = patternTokens[0];\n const patternExpectsConjunction =\n firstPatternToken?.type === 'literal' &&\n (firstPatternToken.value === 'and' ||\n firstPatternToken.value === 'then' ||\n firstPatternToken.alternatives?.includes('and') ||\n firstPatternToken.alternatives?.includes('then'));\n\n if (this.currentProfile?.code === 'ar' && !patternExpectsConjunction) {\n while (tokens.peek()?.kind === 'conjunction') {\n tokens.advance();\n }\n }\n\n // Backtracking state: track the most recent optional role that consumed a token\n let prevOptionalMark: ReturnType<TokenStream['mark']> | null = null;\n let prevOptionalRole: SemanticRole | null = null;\n\n for (let i = 0; i < patternTokens.length; i++) {\n const patternToken = patternTokens[i];\n this.logger.debug(' >> Matching pattern token:', JSON.stringify(patternToken, null, 2));\n const currTok = tokens.peek();\n this.logger.debug(\n ' >> Current input token:',\n currTok\n ? JSON.stringify({\n type: (currTok as any).type,\n value: (currTok as any).value,\n kind: (currTok as any).kind,\n })\n : 'EOF'\n );\n\n // Greedy role capture: consume all remaining tokens until the next\n // recognized marker keyword or end of input\n if (patternToken.type === 'role' && patternToken.greedy) {\n const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n // Merge parent-level stop markers so greedy roles inside groups\n // know when to stop for tokens outside the group (e.g., SOV verb keywords)\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) stopMarkers.add(m);\n }\n const values: string[] = [];\n while (!tokens.isAtEnd()) {\n const nextToken = tokens.peek();\n if (!nextToken) break;\n if (this.isStopMarker(nextToken, stopMarkers)) break;\n values.push(nextToken.value);\n tokens.advance();\n }\n if (values.length > 0) {\n captured.set(patternToken.role, { type: 'expression', raw: values.join(' ') });\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n } else if (patternToken.optional) {\n continue;\n } else {\n return false;\n }\n }\n\n // Group tokens: compute sibling stop markers and forward to inner matching\n if (patternToken.type === 'group') {\n const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) siblingStopMarkers.add(m);\n }\n const groupMatched = this.matchGroupToken(\n tokens,\n patternToken as PatternToken & { type: 'group' },\n captured,\n siblingStopMarkers\n );\n if (groupMatched) {\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n }\n if (this.isOptional(patternToken)) {\n continue;\n }\n return false;\n }\n\n // Save stream position before attempting optional roles\n const isOptionalRole = patternToken.type === 'role' && patternToken.optional === true;\n const markBefore = isOptionalRole ? tokens.mark() : null;\n\n // SOV marker-stealing guard: before matching a required role, check if\n // the current input token would match the immediately-following pattern\n // literal (the role's own postpositional marker). If so, skip consuming\n // this token as a role value — it should be matched as the literal instead.\n const isRoleToken = patternToken.type === 'role';\n if (isRoleToken && !isOptionalRole) {\n const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;\n if (nextPT?.type === 'literal') {\n const currentToken = tokens.peek();\n if (currentToken && this.getMatchType(currentToken, nextPT.value) !== 'none') {\n // Current token is the marker literal, not a role value — treat role as failed\n this.logger.debug(\n ' >> MARKER-STEAL GUARD: current token matches next literal, skipping role'\n );\n // Fall through to failure handling below\n // (which will trigger backtracking of previous optional role)\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n }\n }\n\n const matched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Match result:', matched);\n\n if (matched) {\n if (isOptionalRole) {\n // Track this consumption so we can undo it if the next token fails\n prevOptionalMark = markBefore;\n prevOptionalRole = patternToken.role;\n } else {\n // Non-optional succeeded — clear backtrack state\n prevOptionalMark = null;\n prevOptionalRole = null;\n }\n continue;\n }\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Match a single pattern token against the current position in the stream.\n */\n private matchPatternToken(\n tokens: TokenStream,\n patternToken: PatternToken,\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n switch (patternToken.type) {\n case 'literal':\n return this.matchLiteralToken(tokens, patternToken);\n\n case 'role':\n return this.matchRoleToken(tokens, patternToken, captured);\n\n case 'group':\n return this.matchGroupToken(tokens, patternToken, captured);\n\n default:\n return false;\n }\n }\n\n /**\n * Match a literal pattern token (keyword or particle).\n */\n private matchLiteralToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'literal' }\n ): boolean {\n const token = tokens.peek();\n this.logger.debug(' >>> matchLiteralToken: expecting', patternToken.value);\n this.logger.debug(\n ' >>> matchLiteralToken: got token',\n token\n ? JSON.stringify({\n type: (token as any).type,\n value: (token as any).value,\n kind: (token as any).kind,\n })\n : 'null'\n );\n if (!token) {\n this.logger.debug(' >>> matchLiteralToken: FAIL - no token');\n return false;\n }\n\n // Check main value\n const matchType = this.getMatchType(token, patternToken.value);\n this.logger.debug(\n ' >>> matchType for',\n token.value,\n 'vs',\n patternToken.value,\n ':',\n matchType\n );\n if (matchType !== 'none') {\n this.totalKeywordMatches++;\n if (matchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n\n // Check alternatives\n if (patternToken.alternatives) {\n for (const alt of patternToken.alternatives) {\n const altMatchType = this.getMatchType(token, alt);\n if (altMatchType !== 'none') {\n this.totalKeywordMatches++;\n if (altMatchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Match a role pattern token (captures a semantic value).\n * Handles multi-token expressions like:\n * - 'my value' (possessive keyword + property)\n * - '#dialog.showModal()' (method call)\n * - \"#element's *opacity\" (possessive selector + property)\n */\n private matchRoleToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'role' },\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n this.logger.debug(' >>> matchRoleToken ENTRY: capturing role', patternToken.role);\n this.logger.debug(' >>> matchRoleToken: expected types', patternToken.expectedTypes);\n this.logger.debug(' >>> matchRoleToken: optional?', patternToken.optional);\n // Skip noise words like \"the\" before selectors (English idiom support)\n this.skipNoiseWords(tokens);\n\n const token = tokens.peek();\n this.logger.debug(\n ' >>> After skipNoiseWords, current token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n if (!token) {\n return patternToken.optional || false;\n }\n\n // Check for possessive expression (e.g., 'my value', 'its innerHTML')\n const possessiveValue = this.tryMatchPossessiveExpression(tokens);\n if (possessiveValue) {\n // Validate expected types if specified\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveValue);\n return true;\n }\n\n // Check for method call expression (e.g., '#dialog.showModal()')\n const methodCallValue = this.tryMatchMethodCallExpression(tokens);\n if (methodCallValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, methodCallValue);\n return true;\n }\n\n // Check for possessive selector expression (e.g., \"#element's *opacity\")\n const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);\n if (possessiveSelectorValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n // property-path is compatible with selector, reference, and expression\n if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveSelectorValue);\n return true;\n }\n\n // Check for property access expression (e.g., 'userData.name', 'it.data')\n const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);\n if (propertyAccessValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, propertyAccessValue);\n return true;\n }\n\n // Check for selector + property expression (e.g., '#output.innerText')\n // This handles cases where the tokenizer produces two selector tokens\n const selectorPropertyValue = this.tryMatchSelectorPropertyExpression(tokens);\n if (selectorPropertyValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, selectorPropertyValue);\n return true;\n }\n\n // Try to extract a semantic value from the token\n this.logger.debug(\n ' >>> Trying tokenToSemanticValue for token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n const value = this.tokenToSemanticValue(token);\n this.logger.debug(\n ' >>> tokenToSemanticValue returned:',\n value ? JSON.stringify(value) : 'null'\n );\n if (!value) {\n return patternToken.optional || false;\n }\n\n // Validate expected types if specified\n this.logger.debug(\n ' >>> Validating type:',\n value.type,\n 'against expected:',\n patternToken.expectedTypes\n );\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {\n this.logger.debug(' >>> TYPE MISMATCH - returning', patternToken.optional || false);\n return patternToken.optional || false;\n }\n }\n this.logger.debug(' >>> Type validation PASSED');\n\n captured.set(patternToken.role, value);\n tokens.advance();\n return true;\n }\n\n /**\n * Try to match a possessive expression like 'my value' or 'its innerHTML'.\n * Returns the PropertyPathValue if matched, or null if not.\n */\n private tryMatchPossessiveExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Use profile-based possessive keyword lookup\n if (!this.currentProfile) return null;\n\n const tokenValue = token.normalized || token.value;\n const tokenLower = this.safeToLowerCase(tokenValue);\n const baseRef = getPossessiveReference(this.currentProfile, tokenLower);\n\n if (!baseRef) return null;\n\n // We have a possessive keyword, look ahead for property name\n const mark = tokens.mark();\n tokens.advance();\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n // Just the possessive keyword, no property - revert\n tokens.reset(mark);\n return null;\n }\n\n // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)\n // Examples: \"my value\", \"my innerHTML\", \"my *background\", \"my *opacity\", \"my @data-count\"\n // Also handles dot-property access: \"my.textContent\" tokenized as \"my\" + \".textContent\"\n if (\n propertyToken.kind === 'identifier' ||\n (propertyToken.kind === 'keyword' && !this.isStructuralKeyword(propertyToken.value)) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||\n (propertyToken.kind === 'selector' &&\n propertyToken.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyToken.value))\n ) {\n tokens.advance();\n\n // For dot-property selectors (.textContent), strip the leading dot\n let propertyName = propertyToken.value;\n if (\n propertyToken.kind === 'selector' &&\n propertyName.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyName)\n ) {\n propertyName = propertyName.substring(1);\n }\n\n // Consume chained dot-property access (.parentElement.style.display)\n let chainedProps = propertyName;\n while (\n tokens.peek()?.kind === 'selector' &&\n tokens.peek()!.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(tokens.peek()!.value)\n ) {\n chainedProps += tokens.peek()!.value; // keep the dots for chaining\n tokens.advance();\n }\n\n // Check for method call — next token is '(' in the value (e.g., .getAttribute(\"data-id\"))\n const nextPeek = tokens.peek();\n if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {\n // Consume method args\n chainedProps += nextPeek.value;\n tokens.advance();\n }\n\n // Create property-path: my value -> { object: me, property: 'value' }\n // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)\n return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);\n }\n\n // Not a valid property, revert\n tokens.reset(mark);\n return null;\n }\n\n /**\n * Check if a keyword is a structural keyword (preposition, control flow, etc.)\n * that shouldn't be consumed as a property name.\n */\n private isStructuralKeyword(value: string): boolean {\n const structural = new Set([\n // Prepositions\n 'into',\n 'in',\n 'to',\n 'from',\n 'at',\n 'by',\n 'with',\n 'without',\n 'before',\n 'after',\n 'of',\n 'as',\n 'on',\n // Control flow\n 'then',\n 'end',\n 'else',\n 'if',\n 'repeat',\n 'while',\n 'for',\n // Commands (shouldn't be property names)\n 'toggle',\n 'add',\n 'remove',\n 'put',\n 'set',\n 'show',\n 'hide',\n 'increment',\n 'decrement',\n 'send',\n 'trigger',\n 'call',\n ]);\n return structural.has(value.toLowerCase());\n }\n\n /**\n * Try to match a method call expression like '#dialog.showModal()'.\n * Pattern: selector + '.' + identifier + '(' + [args] + ')'\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: . identifier (\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const methodToken = tokens.peek();\n if (!methodToken || methodToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume method name\n\n const openParen = tokens.peek();\n if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume (\n\n // Consume arguments until we find ) (with depth limit for security)\n const args: string[] = [];\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n tokens.advance(); // consume )\n break;\n }\n // Skip commas\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value: #dialog.showModal()\n const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n /**\n * Try to match a property access expression like 'userData.name' or 'it.data'.\n * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Must start with an identifier or keyword reference\n if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;\n\n // Look ahead for: . identifier\n const mark = tokens.mark();\n tokens.advance(); // consume first token\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property name\n\n // Build the property chain\n let chain = `${token.value}.${propertyToken.value}`;\n let depth = 1; // Already have one property access\n\n // Continue for nested property access (e.g., userData.address.city)\n // With depth limit for security\n while (!tokens.isAtEnd() && depth < PatternMatcher.MAX_PROPERTY_DEPTH) {\n const nextDot = tokens.peek();\n if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {\n break;\n }\n tokens.advance(); // consume .\n\n const nextProp = tokens.peek();\n if (!nextProp || nextProp.kind !== 'identifier') {\n // Dot without property - put the dot back and stop\n // Can't easily put a single token back, so we'll include it\n break;\n }\n tokens.advance(); // consume property\n chain += `.${nextProp.value}`;\n depth++;\n }\n\n // Check for method call: chain + '(' + args + ')'\n // e.g., me.insertBefore(draggedItem, dropTarget)\n const openParen = tokens.peek();\n if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {\n tokens.advance(); // consume (\n\n // Collect arguments (comma-separated values)\n const args: string[] = [];\n let argDepth = 0; // Track nested parentheses\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n\n // Handle close paren - respecting nesting\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n if (argDepth === 0) {\n tokens.advance(); // consume )\n break;\n }\n argDepth--;\n }\n // Track nested open parens\n if (argToken.kind === 'punctuation' && argToken.value === '(') {\n argDepth++;\n }\n // Skip commas between arguments\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value with method call: me.insertBefore(a, b)\n const methodCall = `${chain}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n // Create expression value: userData.name\n return {\n type: 'expression',\n raw: chain,\n } as SemanticValue;\n }\n\n /**\n * Try to match a possessive selector expression like \"#element's *opacity\".\n * Pattern: selector + \"'s\" + (selector | identifier)\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: 's (possessive marker)\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const possessiveToken = tokens.peek();\n if (\n !possessiveToken ||\n possessiveToken.kind !== 'punctuation' ||\n possessiveToken.value !== \"'s\"\n ) {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume 's\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n tokens.reset(mark);\n return null;\n }\n\n // Property can be a selector (*opacity) or identifier\n if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property\n\n // Create property-path: #element's *opacity\n return createPropertyPath(createSelector(token.value), propertyToken.value);\n }\n\n /**\n * Try to match a selector + property expression like \"#output.innerText\".\n * This handles cases where the tokenizer produces two selector tokens:\n * - #output (id selector)\n * - .innerText (looks like class selector, but is actually property)\n *\n * Pattern: id-selector + class-selector-that-is-actually-property\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Must be an ID selector (starts with #)\n if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;\n\n // Look ahead for: selector that looks like a property (.something)\n const mark = tokens.mark();\n tokens.advance(); // consume first selector\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'selector') {\n tokens.reset(mark);\n return null;\n }\n\n // Second token must look like a class selector (starts with .)\n // but we interpret it as a property access\n if (!propertyToken.value.startsWith('.')) {\n tokens.reset(mark);\n return null;\n }\n\n // Verify the next token is not a selector (to avoid consuming too many)\n // This helps distinguish \"#output.innerText\" from \"#box .child\"\n const peek2 = tokens.peek(1);\n if (peek2 && peek2.kind === 'selector') {\n // Could be a compound selector chain - only take first two\n }\n\n tokens.advance(); // consume property selector\n\n // Create property-path: #output.innerText\n // Extract property name without the leading dot\n const propertyName = propertyToken.value.slice(1);\n\n return createPropertyPath(createSelector(token.value), propertyName);\n }\n\n /**\n * Match a group pattern token (optional sequence).\n * When the group's leading marker isn't at the current position, scans ahead\n * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens\n * (e.g., a value like 'hello') to sit between groups without blocking later\n * marker matches.\n */\n private matchGroupToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'group' },\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n const mark = tokens.mark();\n const capturedBefore = new Set(captured.keys());\n\n const success = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (success) return true;\n\n // Reset from failed attempt\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n\n if (!patternToken.optional) return false;\n\n // Marker scan: look ahead for the group's leading marker past intervening tokens.\n // This handles cases like \"types 'hello' into #search\" where 'hello' blocks the\n // 'into' marker from being found at the current position.\n const leadingMarker = this.getGroupLeadingMarker(patternToken);\n if (leadingMarker) {\n for (let offset = 1; offset <= PatternMatcher.MAX_MARKER_SCAN; offset++) {\n const ahead = tokens.peek(offset);\n if (!ahead) break;\n const aheadValue = (ahead.normalized || ahead.value).toLowerCase();\n if (aheadValue === leadingMarker) {\n this.logger.debug(\n ' >> MARKER SCAN: found',\n leadingMarker,\n 'at offset',\n offset,\n '- skipping intervening tokens'\n );\n // Advance past intervening tokens to reach the marker\n for (let s = 0; s < offset; s++) tokens.advance();\n\n // Retry group match from marker position\n const retrySuccess = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (retrySuccess) return true;\n\n // Retry failed — full reset\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n break;\n }\n }\n }\n\n return true; // Optional group, just skip\n }\n\n /**\n * Get the leading marker literal from an optional group.\n * Returns the lowercase marker value, or null if the group\n * doesn't start with a literal token (e.g., SOV groups where\n * the role comes before the marker).\n */\n private getGroupLeadingMarker(group: PatternToken & { type: 'group' }): string | null {\n const first = group.tokens[0];\n if (first?.type === 'literal') return first.value.toLowerCase();\n return null;\n }\n\n /**\n * Get the type of match for a token against a value.\n * Used for confidence calculation.\n */\n private getMatchType(\n token: LanguageToken,\n value: string\n ): 'exact' | 'normalized' | 'stem' | 'case-insensitive' | 'none' {\n // Exact match (highest confidence)\n if (token.value === value) return 'exact';\n\n // Explicit keyword map normalized match (high confidence)\n if (token.normalized === value) return 'normalized';\n\n // Morphologically normalized stem match (medium-high confidence)\n // Only accept if stem confidence is reasonable\n if (token.stem === value && token.stemConfidence !== undefined && token.stemConfidence >= 0.7) {\n return 'stem';\n }\n\n // Case-insensitive match for keywords (medium confidence)\n if (token.kind === 'keyword' && this.safeToLowerCase(token.value) === value.toLowerCase()) {\n return 'case-insensitive';\n }\n\n return 'none';\n }\n\n /**\n * Collect literal values from upcoming pattern tokens that act as stop markers\n * for greedy role capture. Returns the set of lowercase values.\n */\n private collectStopMarkers(patternTokens: PatternToken[], startIndex: number): Set<string> {\n const markers = new Set<string>();\n for (let j = startIndex; j < patternTokens.length; j++) {\n const pt = patternTokens[j];\n if (pt.type === 'literal') {\n markers.add(pt.value.toLowerCase());\n if (pt.alternatives) {\n for (const alt of pt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n if (pt.type === 'group') {\n for (const gt of pt.tokens) {\n if (gt.type === 'literal') {\n markers.add(gt.value.toLowerCase());\n if (gt.alternatives) {\n for (const alt of gt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n }\n // For optional groups, continue scanning past them so the greedy\n // capture also sees subsequent required literals (e.g., the SOV verb\n // keyword after an optional WHERE group).\n if (!pt.optional) break;\n }\n }\n return markers;\n }\n\n /**\n * Check if a token matches any stop marker for greedy capture.\n */\n private isStopMarker(token: LanguageToken, stopMarkers: Set<string>): boolean {\n if (stopMarkers.size === 0) return false;\n // Check both raw value and normalized form against stop markers.\n // Pattern literals use native keywords (e.g., '選択') while tokenizers may\n // set normalized to the English equivalent (e.g., 'select'). Both must match.\n if (stopMarkers.has(token.value.toLowerCase())) return true;\n if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;\n return false;\n }\n\n /**\n * Track stem matches for confidence calculation.\n * This is set during matching and read during confidence calculation.\n */\n private stemMatchCount: number = 0;\n private totalKeywordMatches: number = 0;\n\n // ==========================================================================\n // Depth Limits for Expression Parsing (security hardening)\n // ==========================================================================\n\n /** Maximum depth for nested property access (e.g., a.b.c.d...) */\n private static readonly MAX_PROPERTY_DEPTH = 10;\n\n /** Maximum number of arguments in method calls */\n private static readonly MAX_METHOD_ARGS = 20;\n\n /**\n * Convert a language token to a semantic value.\n */\n private tokenToSemanticValue(token: LanguageToken): SemanticValue | null {\n switch (token.kind) {\n case 'selector':\n return createSelector(token.value);\n\n case 'literal':\n return this.parseLiteralValue(token.value);\n\n case 'keyword':\n // Keywords might be references or values\n const tokenValue = token.normalized || token.value;\n const lower = this.safeToLowerCase(tokenValue);\n if (isValidReference(lower)) {\n return createReference(lower);\n }\n return createLiteral(token.normalized || token.value);\n\n case 'identifier':\n // Check if it's a variable reference (:varname)\n // Note: :varname doesn't match the ReferenceValue union but is used as a\n // reference token downstream — this cast preserves existing behavior\n if (typeof token.value === 'string' && token.value.startsWith(':')) {\n return createReference(token.value as ReferenceValue['value']);\n }\n // Check if it's a built-in reference\n const identLower = this.safeToLowerCase(token.value);\n if (isValidReference(identLower)) {\n return createReference(identLower);\n }\n // Regular identifiers are variable references - use 'expression' type\n // which gets converted to 'identifier' AST nodes by semantic-integration.ts\n return { type: 'expression', raw: token.value } as const;\n\n case 'url':\n // URLs are treated as string literals (paths/URLs for navigation/fetch)\n return createLiteral(token.value, 'string');\n\n default:\n return null;\n }\n }\n\n /**\n * Parse a literal value (string, number, boolean).\n */\n private parseLiteralValue(value: string): SemanticValue {\n // String literal\n if (\n value.startsWith('\"') ||\n value.startsWith(\"'\") ||\n value.startsWith('`') ||\n value.startsWith('「')\n ) {\n const inner = value.slice(1, -1);\n return createLiteral(inner, 'string');\n }\n\n // Boolean\n if (value === 'true') return createLiteral(true, 'boolean');\n if (value === 'false') return createLiteral(false, 'boolean');\n\n // Duration (number with suffix)\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n const num = parseFloat(durationMatch[1]);\n const unit = durationMatch[2];\n if (unit) {\n return createLiteral(value, 'duration');\n }\n return createLiteral(num, 'number');\n }\n\n // Plain number\n const num = parseFloat(value);\n if (!isNaN(num)) {\n return createLiteral(num, 'number');\n }\n\n // Default to string\n return createLiteral(value, 'string');\n }\n\n /**\n * Apply extraction rules to fill in static values and defaults for missing roles.\n */\n private applyExtractionRules(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): void {\n for (const [role, rule] of Object.entries(pattern.extraction)) {\n if (!captured.has(role as SemanticRole)) {\n if (rule.value !== undefined) {\n // Static value extraction (e.g., action: { value: \"toggle\" })\n captured.set(role as SemanticRole, { type: 'literal', value: rule.value });\n } else if (rule.default) {\n captured.set(role as SemanticRole, rule.default);\n }\n }\n }\n }\n\n /**\n * Check if a pattern token is optional.\n */\n private isOptional(patternToken: PatternToken): boolean {\n return patternToken.type !== 'literal' && patternToken.optional === true;\n }\n\n /**\n * Calculate confidence score for a match (0-1).\n *\n * Confidence is reduced for:\n * - Stem matches (morphological normalization has inherent uncertainty)\n * - Missing optional roles (but less penalty if role has a default value)\n *\n * Confidence is increased for:\n * - VSO languages (Arabic) when pattern starts with a verb\n */\n private calculateConfidence(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n let score = 0;\n let maxScore = 0;\n\n // Helper to check if a role has a default value in extraction rules\n const hasDefault = (role: SemanticRole): boolean => {\n return pattern.extraction?.[role]?.default !== undefined;\n };\n\n // Score based on captured roles\n for (const token of pattern.template.tokens) {\n if (token.type === 'role') {\n maxScore += 1;\n if (captured.has(token.role)) {\n score += 1;\n }\n } else if (token.type === 'group') {\n // Group tokens are optional - weight depends on whether they have defaults\n for (const subToken of token.tokens) {\n if (subToken.type === 'role') {\n const roleHasDefault = hasDefault(subToken.role);\n const weight = 0.8; // Optional roles: 80% weight\n maxScore += weight;\n\n if (captured.has(subToken.role)) {\n // Role was explicitly provided by user\n score += weight;\n } else if (roleHasDefault) {\n // Role has a default - give 60% partial credit since command is semantically complete\n // This prevents penalizing common patterns like \"toggle .active\" (default: me)\n score += weight * 0.6;\n }\n // If no default and not captured, score += 0 (true penalty for missing info)\n }\n }\n }\n }\n\n let baseConfidence = maxScore > 0 ? score / maxScore : 1;\n\n // Apply penalty for stem matches\n // Each stem match reduces confidence slightly (e.g., 5% per stem match)\n // This ensures exact matches are preferred over morphological matches\n if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {\n const stemPenalty = (this.stemMatchCount / this.totalKeywordMatches) * 0.15;\n baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);\n }\n\n // Apply VSO confidence boost for Arabic verb-first patterns\n const vsoBoost = this.calculateVSOConfidenceBoost(pattern);\n baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);\n\n // Apply preposition disambiguation adjustment for Arabic\n const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);\n baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));\n\n return baseConfidence;\n }\n\n /**\n * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.\n * Arabic naturally uses VSO word order, so patterns that start with a verb\n * should receive a confidence boost.\n *\n * Returns +0.15 confidence boost if:\n * - Language is Arabic ('ar')\n * - Pattern's first token is a verb keyword\n *\n * @param pattern The language pattern being matched\n * @returns Confidence boost (0 or 0.15)\n */\n private calculateVSOConfidenceBoost(pattern: LanguagePattern): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n // Check if first token in pattern is a literal (keyword)\n const firstToken = pattern.template.tokens[0];\n if (!firstToken || firstToken.type !== 'literal') {\n return 0;\n }\n\n // List of Arabic verb keywords (command verbs)\n const ARABIC_VERBS = new Set([\n 'بدل',\n 'غير',\n 'أضف',\n 'أزل',\n 'ضع',\n 'اجعل',\n 'عين',\n 'زد',\n 'انقص',\n 'سجل',\n 'أظهر',\n 'أخف',\n 'شغل',\n 'أرسل',\n 'ركز',\n 'شوش',\n 'توقف',\n 'انسخ',\n 'احذف',\n 'اصنع',\n 'انتظر',\n 'انتقال',\n 'أو',\n ]);\n\n // Check if first token value is a verb\n if (ARABIC_VERBS.has(firstToken.value)) {\n return 0.15;\n }\n\n // Check alternatives\n if (firstToken.alternatives) {\n for (const alt of firstToken.alternatives) {\n if (ARABIC_VERBS.has(alt)) {\n return 0.15;\n }\n }\n }\n\n return 0;\n }\n\n /**\n * Arabic preposition disambiguation for confidence adjustment.\n *\n * Different Arabic prepositions are more or less natural for different semantic roles:\n * - على (on/upon) is preferred for patient/target roles (element selectors)\n * - إلى (to) is preferred for destination roles\n * - من (from) is preferred for source roles\n * - في (in) is preferred for location roles\n *\n * This method analyzes the prepositions used with captured semantic roles and\n * adjusts confidence based on idiomaticity:\n * - +0.10 for highly idiomatic preposition choices\n * - -0.10 for less natural preposition choices\n *\n * @param pattern The language pattern being matched\n * @param captured The captured semantic values\n * @returns Confidence adjustment (-0.10 to +0.10)\n */\n private arabicPrepositionDisambiguation(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n let adjustment = 0;\n\n // Preferred prepositions for each semantic role\n // Only including roles that commonly use prepositions in Arabic\n const PREFERRED_PREPOSITIONS: Partial<Record<SemanticRole, string[]>> = {\n patient: ['على'], // element selectors prefer على (on/upon)\n destination: ['إلى', 'الى'], // destination prefers إلى (to)\n source: ['من'], // source prefers من (from)\n agent: ['من'], // agent/by prefers من (from/by)\n manner: ['ب'], // manner prefers ب (with/by)\n style: ['ب'], // style prefers ب (with)\n goal: ['إلى', 'الى'], // target state prefers إلى (to)\n method: ['ب'], // method prefers ب (with/by)\n };\n\n // Check each captured role for preposition metadata\n for (const [role, value] of captured.entries()) {\n // Skip if no preferred prepositions defined for this role\n const preferred = PREFERRED_PREPOSITIONS[role];\n if (!preferred || preferred.length === 0) {\n continue;\n }\n\n // Check if the value has preposition metadata (from Arabic tokenizer)\n // This metadata is attached when a preposition particle token is consumed\n const metadata =\n 'metadata' in value ? (value as { metadata: Record<string, unknown> }).metadata : undefined;\n if (metadata && typeof metadata.prepositionValue === 'string') {\n const usedPreposition = metadata.prepositionValue;\n\n // Check if the used preposition is in the preferred list\n if (preferred.includes(usedPreposition)) {\n // Idiomatic choice - boost confidence\n adjustment += 0.1;\n } else {\n // Less natural choice - reduce confidence\n adjustment -= 0.1;\n }\n }\n }\n\n // Cap total adjustment at ±0.10 (even if multiple roles analyzed)\n return Math.max(-0.1, Math.min(0.1, adjustment));\n }\n\n // ===========================================================================\n // English Idiom Support - Noise Word Handling\n // ===========================================================================\n\n /**\n * Noise words that can be skipped in English for more natural syntax.\n * - \"the\" before selectors: \"toggle the .active\" → \"toggle .active\"\n * - \"class\" after class selectors: \"add the .visible class\" → \"add .visible\"\n */\n private static readonly ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);\n\n /**\n * Skip noise words like \"the\" before selectors.\n * This enables more natural English syntax like \"toggle the .active\".\n */\n private skipNoiseWords(tokens: TokenStream): void {\n const token = tokens.peek();\n if (!token) return;\n\n const tokenLower = this.safeToLowerCase(token.value);\n\n // Check if current token is a noise word (like \"the\")\n if (PatternMatcher.ENGLISH_NOISE_WORDS.has(tokenLower)) {\n // Look ahead to see if the next token is a selector\n const mark = tokens.mark();\n tokens.advance();\n const nextToken = tokens.peek();\n\n if (nextToken && nextToken.kind === 'selector') {\n // Keep the position after \"the\" - effectively skipping it\n return;\n }\n\n // Not followed by a selector, revert\n tokens.reset(mark);\n }\n\n // Also handle \"class\" after class selectors: \".visible class\" → \".visible\"\n // This is handled when the selector has already been consumed,\n // so we check if current token is \"class\" and skip it\n if (tokenLower === 'class') {\n // Skip \"class\" as it's just noise after a class selector\n tokens.advance();\n }\n }\n\n /**\n * Extract event modifiers from the token stream.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n * that can appear after event names.\n *\n * Returns EventModifiers object or undefined if no modifiers found.\n */\n extractEventModifiers(tokens: TokenStream): import('../types').EventModifiers | undefined {\n const modifiers: {\n once?: boolean;\n debounce?: number;\n throttle?: number;\n queue?: 'first' | 'last' | 'all' | 'none';\n from?: SemanticValue;\n } = {};\n\n let foundModifier = false;\n\n // Consume all consecutive event modifier tokens\n while (!tokens.isAtEnd()) {\n const token = tokens.peek();\n if (!token || token.kind !== 'event-modifier') {\n break;\n }\n\n const metadata = token.metadata as\n { modifierName: string; value?: number | string } | undefined;\n if (!metadata) {\n break;\n }\n\n foundModifier = true;\n\n switch (metadata.modifierName) {\n case 'once':\n modifiers.once = true;\n break;\n case 'debounce':\n if (typeof metadata.value === 'number') {\n modifiers.debounce = metadata.value;\n }\n break;\n case 'throttle':\n if (typeof metadata.value === 'number') {\n modifiers.throttle = metadata.value;\n }\n break;\n case 'queue':\n if (\n metadata.value === 'first' ||\n metadata.value === 'last' ||\n metadata.value === 'all' ||\n metadata.value === 'none'\n ) {\n modifiers.queue = metadata.value;\n }\n break;\n }\n\n tokens.advance();\n }\n\n return foundModifier ? modifiers : undefined;\n }\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * Singleton pattern matcher instance.\n */\nexport const patternMatcher = new PatternMatcher();\n\n/**\n * Match tokens against a pattern.\n */\nexport function matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern\n): PatternMatchResult | null {\n return patternMatcher.matchPattern(tokens, pattern);\n}\n\n/**\n * Match tokens against multiple patterns, return best match.\n */\nexport function matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[]\n): PatternMatchResult | null {\n return patternMatcher.matchBest(tokens, patterns);\n}\n","/**\n * Pattern Generator\n *\n * Generates LanguagePattern objects from CommandSchema + LanguageProfile.\n * This solves the pattern explosion problem by deriving patterns from\n * high-level schema definitions rather than hand-writing each one.\n */\n\nimport type { LanguagePattern, PatternToken, ExtractionRule } from '../core/types';\nimport type { CommandSchema, RoleSpec } from '../schema';\n\n/**\n * Minimal language profile interface for pattern generation.\n */\nexport interface PatternGenLanguageProfile {\n readonly code: string;\n readonly wordOrder: 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OSV' | 'OVS' | 'free';\n readonly keywords: Record<string, { primary: string; alternatives?: string[] }>;\n readonly roleMarkers?: Record<\n string,\n { primary: string; alternatives?: string[]; position?: 'before' | 'after' }\n >;\n}\n\n/**\n * Configuration for pattern generation.\n */\nexport interface GeneratorConfig {\n /** Base priority for generated patterns (default: 100) */\n readonly basePriority?: number;\n /** Include optional role variants (default: true) */\n readonly includeOptionalVariants?: boolean;\n}\n\nconst defaultConfig: GeneratorConfig = {\n basePriority: 100,\n includeOptionalVariants: true,\n};\n\n/**\n * Generate a language pattern from a command schema and language profile.\n *\n * @param schema - Command schema defining the command structure\n * @param profile - Language profile with word order and keywords\n * @param config - Optional configuration\n * @returns Generated language pattern\n */\nexport function generatePattern(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern {\n const id = `${schema.action}-${profile.code}-generated`;\n const priority = config.basePriority ?? 100;\n\n // Get keyword translation\n const keyword = profile.keywords[schema.action];\n if (!keyword) {\n throw new Error(`No keyword translation for '${schema.action}' in ${profile.code}`);\n }\n\n // Build tokens based on word order\n const tokens = buildTokens(schema, profile, keyword.primary, keyword.alternatives);\n\n // Build extraction rules\n const extraction = buildExtractionRules(schema, profile);\n\n // Build format string for documentation\n const format = buildFormatString(schema, profile, keyword.primary);\n\n return {\n id,\n language: profile.code,\n command: schema.action,\n priority,\n template: {\n format,\n tokens,\n },\n extraction,\n };\n}\n\n/**\n * Build pattern tokens based on word order and role markers.\n */\nfunction buildTokens(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string,\n alternatives?: string[]\n): PatternToken[] {\n const tokens: PatternToken[] = [];\n const keywordToken: PatternToken = {\n type: 'literal',\n value: keyword,\n ...(alternatives?.length && { alternatives }),\n };\n\n // Sort roles by word order\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n\n // For SVO: [action, patient, destination, source, ...]\n if (profile.wordOrder === 'SVO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // For SOV: [patient, destination, source, ..., action, postVerb roles...]\n else if (profile.wordOrder === 'SOV') {\n // `sovSlot: 'postVerb'` moves a role AFTER the verb, which is what the\n // renderer does (`renderer.ts` buckets by the same field). Generation has\n // to mirror it: a role the renderer writes post-verb but the pattern\n // expects pre-verb produces a faithful surface its own parser drops the\n // argument from — voice's `戻る 2` re-parsing as a bare `back`.\n const preVerb: PatternToken[] = [];\n const postVerb: PatternToken[] = [];\n\n for (const role of sortedRoles) {\n addRoleWithMarker(role.sovSlot === 'postVerb' ? postVerb : preVerb, role, profile);\n }\n\n tokens.push(...preVerb, keywordToken, ...postVerb);\n }\n // For VSO: [action, destination, patient, source, ...]\n else if (profile.wordOrder === 'VSO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // Other word orders can be added as needed\n else {\n // Fallback to SVO-style ordering\n tokens.push(keywordToken);\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n\n return tokens;\n}\n\n/**\n * Add a role token with its grammatical marker if needed.\n * For optional roles, wraps the role + marker in a group.\n */\nfunction addRoleWithMarker(\n tokens: PatternToken[],\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): void {\n const marker = getMarkerForRole(roleSpec, profile);\n const isOptional = !roleSpec.required;\n\n // Build the role token\n const roleToken: PatternToken = {\n type: 'role',\n role: roleSpec.role,\n optional: isOptional,\n expectedTypes: roleSpec.expectedTypes,\n ...(roleSpec.greedy && { greedy: true }),\n };\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[roleSpec.role];\n // Priority: schema markerPosition → profile roleMarkers position → word-order default\n const defaultPosition = profile.wordOrder === 'SOV' ? 'after' : 'before';\n const position = roleSpec.markerPosition ?? markerInfo?.position ?? defaultPosition;\n\n if (isOptional) {\n // Optional role: wrap marker + role in optional group\n if (position === 'before') {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [{ type: 'literal', value: marker }, roleToken],\n });\n } else {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [roleToken, { type: 'literal', value: marker }],\n });\n }\n } else {\n // Required role: add marker + role separately\n if (position === 'before') {\n tokens.push({ type: 'literal', value: marker });\n tokens.push(roleToken);\n } else {\n tokens.push(roleToken);\n tokens.push({ type: 'literal', value: marker });\n }\n }\n } else {\n // No marker - just add the role\n tokens.push(roleToken);\n }\n}\n\n/**\n * Get the grammatical marker for a role from the profile.\n */\nfunction getMarkerForRole(\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): string | undefined {\n // Check for role-specific override first\n if (roleSpec.markerOverride?.[profile.code]) {\n return roleSpec.markerOverride[profile.code];\n }\n\n // Use profile's default marker for this role\n return profile.roleMarkers?.[roleSpec.role]?.primary;\n}\n\n/**\n * Sort roles by word order for pattern building.\n *\n * Exported so the renderer sorts with exactly this comparator — a rendered\n * surface whose role order differs from the generated pattern would not re-parse.\n */\nexport function sortRolesByWordOrder(roles: RoleSpec[], wordOrder: string): RoleSpec[] {\n const sorted = [...roles];\n\n if (wordOrder === 'SVO') {\n // Sort by svoPosition (higher = earlier)\n sorted.sort((a, b) => (b.svoPosition ?? 0) - (a.svoPosition ?? 0));\n } else if (wordOrder === 'SOV') {\n // Sort by sovPosition (higher = earlier)\n sorted.sort((a, b) => (b.sovPosition ?? 0) - (a.sovPosition ?? 0));\n }\n // VSO and others use SVO-style ordering\n\n return sorted;\n}\n\n/**\n * Build extraction rules for capturing role values during parsing.\n */\nfunction buildExtractionRules(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile\n): Record<string, ExtractionRule> {\n const rules: Record<string, ExtractionRule> = {};\n\n for (const roleSpec of schema.roles) {\n // Build the rule object correctly with readonly properties\n const marker = getMarkerForRole(roleSpec, profile);\n\n const rule: ExtractionRule = {\n ...(roleSpec.default !== undefined && { default: roleSpec.default }),\n ...(marker && { marker }),\n };\n\n rules[roleSpec.role] = rule;\n }\n\n return rules;\n}\n\n/**\n * Build a human-readable format string for the pattern.\n */\nfunction buildFormatString(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string\n): string {\n const isSOV = profile.wordOrder === 'SOV';\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n // Order roles the same way buildTokens does (descending position). Iterating\n // declaration order here would disagree with the token order whenever a\n // schema's roles are declared in a different order than their positions imply.\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n for (const role of sortedRoles) {\n const marker = getMarkerForRole(role, profile);\n const roleName = `{${role.role}}`;\n // Same pre/post-verb split buildTokens applies, so the documented format\n // string keeps describing the tokens it is generated alongside.\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[role.role];\n if (markerInfo?.position === 'after') {\n bucket.push(`${roleName} ${marker}`);\n } else {\n bucket.push(`${marker} ${roleName}`);\n }\n } else {\n bucket.push(roleName);\n }\n }\n\n return (isSOV ? [...preVerb, keyword, ...postVerb] : [keyword, ...preVerb, ...postVerb]).join(\n ' '\n );\n}\n\n/**\n * Generate multiple pattern variants (with and without optional roles).\n */\nexport function generatePatternVariants(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern[] {\n const patterns: LanguagePattern[] = [];\n\n // Main pattern (all roles)\n patterns.push(generatePattern(schema, profile, config));\n\n // TODO: Generate variants with optional roles omitted\n // This can be added later when needed\n\n return patterns;\n}\n","/**\n * Natural Language Renderer\n *\n * Interface and utilities for rendering SemanticNode → human-readable text\n * in any supported language. This is the inverse of parsing: it converts\n * a language-neutral semantic representation back to natural-language syntax.\n *\n * Every domain that supports `translate()` needs a renderer.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { extractRoleValue, extractValue } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { sortRolesByWordOrder, type PatternGenLanguageProfile } from './pattern-generator';\n\n// =============================================================================\n// Renderer Interface\n// =============================================================================\n\n/**\n * Renders a SemanticNode to human-readable text in a target language.\n */\nexport interface NaturalLanguageRenderer {\n render(node: SemanticNode, language: string): string;\n}\n\n// =============================================================================\n// Renderer Helpers\n// =============================================================================\n\n/**\n * Keyword table: action → language → translated keyword.\n *\n * @example\n * ```typescript\n * const KEYWORDS: KeywordTable = {\n * select: { en: 'select', ja: '選択', es: 'seleccionar' },\n * insert: { en: 'insert', ja: '挿入', es: 'insertar' },\n * };\n * ```\n */\nexport type KeywordTable = Record<string, Record<string, string>>;\n\n/**\n * Marker table: marker name → language → translated marker.\n *\n * @example\n * ```typescript\n * const MARKERS: MarkerTable = {\n * from: { en: 'from', ja: 'から', es: 'de' },\n * into: { en: 'into', ja: 'に', es: 'en' },\n * };\n * ```\n */\nexport type MarkerTable = Record<string, Record<string, string>>;\n\n/**\n * Configuration for building a renderer from schemas and profiles.\n */\nexport interface RendererConfig {\n /** Command keyword translations per language */\n readonly keywords: KeywordTable;\n\n /** Role marker translations per language (prepositions/particles) */\n readonly markers: MarkerTable;\n\n /** Languages that use SOV word order */\n readonly sovLanguages: ReadonlySet<string>;\n\n /** Languages that use VSO word order (optional, defaults to empty) */\n readonly vsoLanguages?: ReadonlySet<string>;\n}\n\n/**\n * Look up a command keyword in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupKeyword(keywords: KeywordTable, action: string, language: string): string {\n return keywords[action]?.[language] ?? action;\n}\n\n/**\n * Look up a role marker in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupMarker(markers: MarkerTable, marker: string, language: string): string {\n return markers[marker]?.[language] ?? marker;\n}\n\n/**\n * Build a phrase from parts, filtering empty strings and joining with space.\n *\n * @example\n * ```typescript\n * buildPhrase('select', '', 'name', 'from', 'users')\n * // → 'select name from users'\n * ```\n */\nexport function buildPhrase(...parts: string[]): string {\n return parts.filter(Boolean).join(' ');\n}\n\n/**\n * Build keyword and marker tables from schemas and language profiles.\n * Extracts translations from the profile's keyword definitions and\n * role marker overrides.\n *\n * @example\n * ```typescript\n * const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n * ```\n */\nexport function buildTablesFromProfiles(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): { keywords: KeywordTable; markers: MarkerTable } {\n const keywords: KeywordTable = {};\n const markers: MarkerTable = {};\n\n // Build keyword table from profiles\n for (const profile of profiles) {\n for (const [action, kw] of Object.entries(profile.keywords)) {\n if (!keywords[action]) keywords[action] = {};\n keywords[action][profile.code] = kw.primary;\n }\n }\n\n // Build marker table from schema markerOverrides\n for (const schema of schemas) {\n for (const role of schema.roles) {\n if (role.markerOverride) {\n // Use role name as marker key\n const markerKey = role.role;\n if (!markers[markerKey]) markers[markerKey] = {};\n for (const [lang, markerText] of Object.entries(role.markerOverride)) {\n markers[markerKey][lang] = markerText;\n }\n }\n }\n }\n\n // Also extract role markers from profiles\n for (const profile of profiles) {\n if (profile.roleMarkers) {\n for (const [markerKey, markerDef] of Object.entries(profile.roleMarkers)) {\n if (!markers[markerKey]) markers[markerKey] = {};\n markers[markerKey][profile.code] = markerDef.primary;\n }\n }\n }\n\n return { keywords, markers };\n}\n\n/**\n * Detect word order from language profiles.\n * Returns sets of SOV and VSO language codes.\n */\nexport function detectWordOrders(profiles: readonly PatternGenLanguageProfile[]): {\n sovLanguages: Set<string>;\n vsoLanguages: Set<string>;\n} {\n const sovLanguages = new Set<string>();\n const vsoLanguages = new Set<string>();\n\n for (const profile of profiles) {\n if (profile.wordOrder === 'SOV') sovLanguages.add(profile.code);\n if (profile.wordOrder === 'VSO') vsoLanguages.add(profile.code);\n }\n\n return { sovLanguages, vsoLanguages };\n}\n\n/**\n * Create a basic renderer from schemas and profiles.\n *\n * This generates a renderer that handles word-order reordering automatically.\n * For each command, it constructs the output by placing the keyword and\n * role values in the correct order for the target language.\n *\n * For complex domain-specific rendering, implement `NaturalLanguageRenderer`\n * directly instead.\n *\n * @example\n * ```typescript\n * const renderer = createSchemaRenderer(schemas, profiles);\n * renderer.render(node, 'ja'); // → \"users から name 選択\"\n * ```\n */\nexport function createSchemaRenderer(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): NaturalLanguageRenderer {\n const tables = buildRenderTables(schemas, profiles);\n\n return {\n render(node: SemanticNode, language: string): string {\n // An action with no schema still has a name — render that rather than\n // nothing. `createDomainRenderer` returns null for this case instead.\n return renderFromSchema(node, language, tables) ?? node.action;\n },\n };\n}\n\n// =============================================================================\n// Domain renderer (hand-written cases + schema fallthrough)\n// =============================================================================\n\n/**\n * Renders a SemanticNode, or returns `null` when the action cannot be rendered.\n *\n * The nullable counterpart to {@link NaturalLanguageRenderer}: `null` means \"I\n * do not know this action\", which callers can act on. A domain that signals the\n * same condition with a sentinel string forces consumers into string matching.\n */\nexport type DomainRenderFn = (node: SemanticNode, language: string) => string | null;\n\n/**\n * Configuration for {@link createDomainRenderer}.\n */\nexport interface DomainRendererConfig {\n /** Schemas for this domain's commands, including any extensions. */\n readonly schemas: readonly CommandSchema[];\n\n /** Language profiles supplying keywords and role markers. */\n readonly profiles: readonly PatternGenLanguageProfile[];\n\n /**\n * Hand-written renderers per action. These take absolute precedence over the\n * schema-driven path, so a domain's existing output is preserved byte for byte.\n *\n * An override returning `null` means \"this action cannot be rendered\" and is\n * passed straight through — it does not fall through to the schema path,\n * since a hand-written renderer knows more about its action than the schema does.\n */\n readonly overrides?: Readonly<Record<string, DomainRenderFn>>;\n}\n\n/**\n * Create a renderer that composes a domain's hand-written per-action renderers\n * with the schema-driven fallback.\n *\n * Resolution order:\n * 1. `overrides[node.action]` — the domain's own rendering, unchanged\n * 2. schema-driven rendering — any action with a schema but no hand-written case\n * 3. `null` — no override and no schema\n *\n * Step 2 is what makes a domain extensible: a consumer that adds a command\n * schema (with per-language keywords in the profiles) gets correct word order,\n * markers and keywords for free, without the domain package having to know\n * about that command.\n *\n * @example\n * ```typescript\n * const render = createDomainRenderer({\n * schemas: allSchemas,\n * profiles: allProfiles,\n * overrides: { select: renderSelect, insert: renderInsert },\n * });\n * render(node, 'ja'); // hand-written for `select`, schema-driven otherwise\n * render(bogusNode, 'en'); // → null\n * ```\n */\nexport function createDomainRenderer(config: DomainRendererConfig): DomainRenderFn {\n const { schemas, profiles, overrides } = config;\n\n // Built on first render — a domain module can construct its renderer at import\n // time without paying for table construction it may never use.\n let tables: RenderTables | undefined;\n\n return (node: SemanticNode, language: string): string | null => {\n const override = overrides?.[node.action];\n if (override) return override(node, language);\n\n tables ??= buildRenderTables(schemas, profiles);\n return renderFromSchema(node, language, tables);\n };\n}\n\n// =============================================================================\n// Shared schema-driven rendering\n// =============================================================================\n\ninterface RenderTables {\n readonly keywords: KeywordTable;\n readonly markers: MarkerTable;\n /** Marker side per role per language, from each profile's roleMarkers. */\n readonly markerPositions: Record<string, Record<string, 'before' | 'after'>>;\n readonly sovLanguages: ReadonlySet<string>;\n readonly schemaMap: ReadonlyMap<string, CommandSchema>;\n}\n\nfunction buildRenderTables(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): RenderTables {\n const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n const { sovLanguages } = detectWordOrders(profiles);\n\n const markerPositions: Record<string, Record<string, 'before' | 'after'>> = {};\n for (const profile of profiles) {\n for (const [role, markerDef] of Object.entries(profile.roleMarkers ?? {})) {\n if (!markerDef.position) continue;\n markerPositions[role] ??= {};\n markerPositions[role][profile.code] = markerDef.position;\n }\n }\n\n const schemaMap = new Map<string, CommandSchema>();\n for (const s of schemas) schemaMap.set(s.action, s);\n return { keywords, markers, markerPositions, sovLanguages, schemaMap };\n}\n\n/**\n * The one schema-driven rendering algorithm, shared by `createSchemaRenderer`\n * and `createDomainRenderer` so the two can never drift.\n *\n * Returns `null` when the action has no schema.\n */\nfunction renderFromSchema(\n node: SemanticNode,\n language: string,\n tables: RenderTables\n): string | null {\n const schema = tables.schemaMap.get(node.action);\n if (!schema) return null;\n\n const keyword = lookupKeyword(tables.keywords, node.action, language);\n const isSOV = tables.sovLanguages.has(language);\n\n // Order roles by their declared positions, using the SAME comparator pattern\n // generation uses. Rendering in declaration order instead would produce a\n // surface the generated pattern cannot re-parse whenever the two disagree.\n const ordered = sortRolesByWordOrder([...schema.roles], isSOV ? 'SOV' : 'SVO');\n\n // Roles rendered before the verb, and (SOV only) after it.\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n for (const role of ordered) {\n let value = extractRoleValue(node, role.role);\n if (!value && role.default !== undefined) {\n value = String(extractValue(role.default));\n }\n // A role with no value is skipped entirely — including its marker. Emitting\n // the marker of an absent role produces dangling text (\"analyze #content as\",\n // \"#content として 分析\"), which is never valid surface syntax. This applies to\n // required roles too: a required role with no value is a malformed node, and\n // a dangling marker is a worse rendering of it than simply leaving it out.\n if (!value) continue;\n\n if (role.quoteMultiword && /\\s/.test(value) && !/^([\"']).*\\1$/.test(value)) {\n value = `\"${value}\"`;\n }\n\n // Marker resolution, most specific first. `renderOverride` for this exact\n // language is the most specific statement; `''` means \"render this role\n // bare\" (a marker that exists only to help the parser). The `'*'` key is a\n // blanket statement about the PROFILE default, so it ranks below a\n // per-language markerOverride — which is how SQL's `get` renders bare in\n // SVO languages while keeping its SOV source particles.\n const markerText =\n role.renderOverride?.[language] ??\n role.markerOverride?.[language] ??\n role.renderOverride?.['*'] ??\n tables.markers[role.role]?.[language];\n\n const markerPosition =\n role.markerPositionOverride?.[language] ??\n role.markerPosition ??\n tables.markerPositions[role.role]?.[language] ??\n (isSOV ? 'after' : 'before');\n\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n if (markerText && markerPosition === 'before') {\n bucket.push(markerText, value);\n } else if (markerText) {\n bucket.push(value, markerText);\n } else {\n bucket.push(value);\n }\n }\n\n return isSOV\n ? buildPhrase(...preVerb, keyword, ...postVerb)\n : buildPhrase(keyword, ...preVerb, ...postVerb);\n}\n","/**\n * Generalized Grammar System for Multilingual Hyperscript\n *\n * This system abstracts grammatical patterns across language families,\n * enabling deep multilingual support without per-language hardcoding.\n *\n * Key Linguistic Concepts:\n * - Word Order: SVO, SOV, VSO (and variations)\n * - Adposition Type: Preposition (English) vs Postposition (Japanese/Korean)\n * - Morphology: Isolating (Chinese) vs Agglutinative (Turkish) vs Fusional (Arabic)\n * - Text Direction: LTR vs RTL\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Semantic roles in hyperscript commands.\n * These are universal across all 13 supported languages - only the surface form changes.\n *\n * ## Core Thematic Roles (from linguistic theory)\n * | Role | Usage | Purpose | Example |\n * |-------------|-------|-----------------------------|---------------------------|\n * | action | 100% | Command verb | toggle, put, fetch |\n * | patient | 90% | What is acted upon | .active, #count |\n * | destination | 40% | Where something goes | into #output, to .class |\n * | source | 13% | Where something comes from | from #input, from URL |\n * | event | 106% | Trigger events | click, keydown, submit |\n * | condition | 8% | Boolean expressions | if x > 5, when visible |\n * | agent | 0% | Who performs action | Reserved for future use |\n * | goal | 1% | Target value/state | to 'red' (in transition) |\n *\n * ## Quantitative Roles (answer \"how much/long\")\n * | Role | Usage | Purpose | Example |\n * |----------|-------|----------------|----------------------|\n * | quantity | 7% | Numeric amount | by 5, 3 times |\n * | duration | 1% | Time span | for 5 seconds, 500ms |\n *\n * ## Adverbial/Modifier Roles (answer \"how/by what means\")\n * | Role | Usage | Purpose | Example |\n * |--------------|-------|---------------------------|-------------------|\n * | style | 2% | Animation/behavior | with fade |\n * | manner | 2% | Insertion position | before, after |\n * | method | 1% | HTTP method/technique | via POST, as GET |\n * | responseType | 1% | Response format | as json, as html |\n *\n * ## Control Flow Roles\n * | Role | Usage | Purpose | Example |\n * |----------|-------|--------------|-----------------------|\n * | loopType | 6% | Loop variant | forever, until, times |\n *\n * ## Design Notes\n * - Low-usage roles (agent, goal, method, responseType) are intentionally kept for:\n * - Linguistic completeness across all 13 languages\n * - Future extensibility (AI agents, server-side execution)\n * - Command-specific semantics (fetch, transition)\n * - Each role has distinct grammatical markers per language (see profiles/index.ts)\n * - Usage percentages based on pattern database analysis\n */\nexport type SemanticRole =\n // Core thematic roles\n | 'action' // The command/verb (increment, put, toggle)\n | 'agent' // Who/what performs action (reserved for future: AI agents, server-side)\n | 'patient' // What is acted upon (the counter, .active)\n | 'source' // Origin (from #input, from URL)\n | 'destination' // Target location (into #output, to .class)\n | 'goal' // Target value/state (to 'red', to 100)\n | 'event' // Trigger (click, input, keydown)\n | 'condition' // Boolean expression (if x > 5)\n // Quantitative roles\n | 'quantity' // Numeric amount (by 5, 3 times)\n | 'duration' // Time span (for 5 seconds, over 500ms)\n // Adverbial roles\n | 'responseType' // Response format (as json, as text, as html)\n | 'method' // HTTP method/technique (via POST, using GET)\n | 'style' // Visual/behavioral manner (with fade, smoothly)\n | 'manner' // Insertion position (before, after)\n // Control flow roles\n | 'loopType' // Loop variant: forever, times, for, while, until, until-event\n // Structural roles (for parser control)\n | 'continues'; // Continuation marker (then-chains)\n\n/**\n * Word order patterns\n * These represent the major typological categories\n */\nexport type WordOrder = 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OVS' | 'OSV' | 'free';\n\n/**\n * Where grammatical markers appear relative to their noun/verb\n */\nexport type AdpositionType = 'preposition' | 'postposition' | 'circumposition' | 'none';\n\n/**\n * Morphological typology - how words are constructed\n */\nexport type MorphologyType =\n | 'isolating' // Chinese - no inflection, word order matters\n | 'agglutinative' // Turkish, Japanese - morphemes stack predictably\n | 'fusional' // Arabic, Spanish - morphemes blend together\n | 'polysynthetic'; // Quechua - complex words encode full sentences\n\n/**\n * A grammatical marker (particle, case ending, preposition)\n */\nexport interface GrammaticalMarker {\n form: string; // The actual text (を, に, to, 的)\n role: SemanticRole; // What semantic role it marks\n position: AdpositionType; // Where it appears\n required: boolean; // Is it mandatory?\n alternatives?: string[]; // Alternative forms (e.g., 을/를 in Korean)\n}\n\n/**\n * Metadata for preserving line structure during translation.\n * Tracks indentation and blank lines so output maintains the same format.\n */\nexport interface LineMetadata {\n /** Trimmed line content (empty string for blank lines) */\n content: string;\n /** Leading whitespace (tabs/spaces) from original line */\n originalIndent: string;\n /** True if the line was empty or whitespace-only */\n isBlank: boolean;\n}\n\n// =============================================================================\n// Language Profile\n// =============================================================================\n\n/**\n * Complete grammatical profile for a language\n * This captures the essential typological features needed for transformation\n */\nexport interface LanguageProfile {\n code: string; // ISO 639-1 code\n name: string; // Native name\n\n // Typological features\n wordOrder: WordOrder;\n adpositionType: AdpositionType;\n morphology: MorphologyType;\n direction: 'ltr' | 'rtl';\n\n // Grammatical markers for each semantic role\n markers: GrammaticalMarker[];\n\n // Role ordering - which semantic roles come in what order\n // E.g., Japanese: ['patient', 'source', 'destination', 'action']\n // E.g., English: ['action', 'patient', 'source', 'destination']\n canonicalOrder: SemanticRole[];\n\n // Special rules\n rules?: GrammarRule[];\n}\n\n/**\n * Pattern for transforming hyperscript structures\n */\nexport interface GrammarRule {\n name: string;\n description: string;\n\n // Pattern matching (in canonical English form)\n match: PatternMatcher;\n\n // How to transform for this language\n transform: PatternTransform;\n\n // Priority (higher = checked first)\n priority: number;\n}\n\n/**\n * Matches a hyperscript pattern\n */\nexport interface PatternMatcher {\n // Command type(s) this matches\n commands?: string[];\n\n // Required semantic roles\n requiredRoles: SemanticRole[];\n\n // Optional roles\n optionalRoles?: SemanticRole[];\n\n // Custom predicate for complex matching\n predicate?: (parsed: ParsedStatement) => boolean;\n}\n\n/**\n * Defines how to transform a matched pattern\n */\nexport interface PatternTransform {\n // Reorder roles for target language\n roleOrder: SemanticRole[];\n\n // Insert markers between roles\n insertMarkers?: boolean;\n\n // Custom transformation function\n custom?: (parsed: ParsedStatement, profile: LanguageProfile) => string;\n}\n\n// =============================================================================\n// Parsed Structures\n// =============================================================================\n\n/**\n * A parsed hyperscript statement broken into semantic components\n */\nexport interface ParsedStatement {\n type: 'event-handler' | 'command' | 'conditional' | 'loop';\n roles: Map<SemanticRole, ParsedElement>;\n original: string;\n}\n\n/**\n * A single element with its semantic role\n */\nexport interface ParsedElement {\n role: SemanticRole;\n value: string; // Original English value\n translated?: string; // Translated value\n isSelector?: boolean; // CSS selector (don't translate)\n isLiteral?: boolean; // Literal value (don't translate)\n}\n\n// =============================================================================\n// Universal Pattern Templates\n// =============================================================================\n\n/**\n * Universal templates for common hyperscript patterns\n * These define the semantic structure independent of surface form\n */\nexport const UNIVERSAL_PATTERNS = {\n // on click increment #count\n eventIncrement: {\n name: 'event-increment',\n roles: ['event', 'action', 'patient'] as SemanticRole[],\n english: 'on {event} {action} {patient}',\n },\n\n // put X into Y\n putInto: {\n name: 'put-into',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} into {destination}',\n },\n\n // add .class to element\n addTo: {\n name: 'add-to',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} to {destination}',\n },\n\n // toggle .class on element\n toggleOn: {\n name: 'toggle-on',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} on {destination}',\n },\n\n // wait 2 seconds\n waitDuration: {\n name: 'wait-duration',\n roles: ['action', 'quantity'] as SemanticRole[],\n english: '{action} {quantity}',\n },\n\n // if condition then ... end\n conditional: {\n name: 'conditional',\n roles: ['action', 'condition'] as SemanticRole[],\n english: '{action} {condition} then ... end',\n },\n\n // fetch URL as type\n fetchAs: {\n name: 'fetch-as',\n roles: ['action', 'source', 'method'] as SemanticRole[],\n english: '{action} {source} as {method}',\n },\n\n // show element with animation\n showWith: {\n name: 'show-with',\n roles: ['action', 'patient', 'style'] as SemanticRole[],\n english: '{action} {patient} with {style}',\n },\n\n // transition property over duration\n transitionOver: {\n name: 'transition-over',\n roles: ['action', 'patient', 'duration'] as SemanticRole[],\n english: '{action} {patient} over {duration}',\n },\n} as const;\n\n// =============================================================================\n// Language Family Defaults\n// =============================================================================\n\n/**\n * Default profiles for major language families\n * Individual languages inherit and override these\n */\nexport const LANGUAGE_FAMILY_DEFAULTS: Record<string, Partial<LanguageProfile>> = {\n // Germanic (English, German, Dutch)\n germanic: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Romance (Spanish, French, Italian, Portuguese)\n romance: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Japonic (Japanese)\n japonic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Koreanic (Korean)\n koreanic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Turkic (Turkish, Azerbaijani)\n turkic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Sinitic (Chinese, Cantonese)\n sinitic: {\n wordOrder: 'SVO', // Topic-prominent, flexible\n adpositionType: 'preposition',\n morphology: 'isolating',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Semitic (Arabic, Hebrew)\n semitic: {\n wordOrder: 'VSO',\n adpositionType: 'preposition',\n morphology: 'fusional', // Root-pattern system\n direction: 'rtl',\n canonicalOrder: [\n 'action',\n 'agent',\n 'patient',\n 'destination',\n 'source',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Austronesian (Indonesian, Tagalog)\n austronesian: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Quechuan (Quechua)\n quechuan: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative', // Actually polysynthetic but simplified\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Bantu (Swahili)\n bantu: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n};\n\n// =============================================================================\n// Transformation Utilities\n// =============================================================================\n\n/**\n * Reorder semantic roles according to target language.\n * Includes a safety net to append any roles present in input\n * but missing from the target order, preventing data loss.\n */\nexport function reorderRoles(\n roles: Map<SemanticRole, ParsedElement>,\n targetOrder: SemanticRole[]\n): ParsedElement[] {\n const result: ParsedElement[] = [];\n const usedRoles = new Set<SemanticRole>();\n\n // 1. Add roles that are explicitly in the canonical order\n for (const role of targetOrder) {\n const element = roles.get(role);\n if (element) {\n result.push(element);\n usedRoles.add(role);\n }\n }\n\n // 2. Safety Net: Append any roles present in input but missing from target order\n // This prevents data loss (e.g., if 'manner' or 'instrument' isn't in the profile)\n for (const [role, element] of roles) {\n if (!usedRoles.has(role)) {\n result.push(element);\n }\n }\n\n return result;\n}\n\n/**\n * Insert grammatical markers between elements\n */\nexport function insertMarkers(\n elements: ParsedElement[],\n markers: GrammaticalMarker[],\n adpositionType: AdpositionType\n): string[] {\n const result: string[] = [];\n\n for (const element of elements) {\n const marker = markers.find(m => m.role === element.role);\n\n if (marker) {\n if (adpositionType === 'preposition') {\n // Marker before element: \"to element\"\n if (marker.form) result.push(marker.form);\n result.push(element.translated || element.value);\n } else if (adpositionType === 'postposition') {\n // Marker after element: \"element を\"\n result.push(element.translated || element.value);\n if (marker.form) result.push(marker.form);\n } else {\n result.push(element.translated || element.value);\n }\n } else {\n result.push(element.translated || element.value);\n }\n }\n\n return result;\n}\n\n/**\n * Intelligently joins tokens, handling agglutinative suffixes and prefixes.\n *\n * Rules:\n * 1. If a token ends with '-' (prefix marker), no space after it\n * 2. If a token starts with '-' (suffix marker), no space before it\n * 3. Removes the hyphen indicators from the final output\n *\n * Examples:\n * - ['#count', '-ta'] → '#countta' (Quechua accusative suffix)\n * - ['بـ-', 'الماوس'] → 'بـالماوس' (Arabic prefix attachment)\n * - ['value', 'を'] → 'value を' (Japanese particle, normal spacing)\n */\nexport function joinTokens(tokens: string[]): string {\n if (tokens.length === 0) return '';\n\n let result = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n const nextToken = tokens[i + 1];\n\n // Check if current token is a prefix (ends with -)\n const isPrefix = token.endsWith('-');\n // Check if current token is a suffix (starts with -)\n const isSuffix = token.startsWith('-');\n\n // Get the display form (strip hyphen markers)\n let displayToken = token;\n if (isPrefix) displayToken = token.slice(0, -1);\n if (isSuffix) displayToken = token.substring(1);\n\n result += displayToken;\n\n // Determine if we need a space before the next token\n if (nextToken) {\n const nextIsSuffix = nextToken.startsWith('-');\n\n // Don't add space if:\n // - Current token is a prefix (ends with -)\n // - Next token is a suffix (starts with -)\n if (!isPrefix && !nextIsSuffix) {\n result += ' ';\n }\n }\n }\n\n return result;\n}\n\n/**\n * Transform a parsed statement to target language\n */\nexport function transformStatement(\n parsed: ParsedStatement,\n _sourceProfile: LanguageProfile,\n targetProfile: LanguageProfile\n): string {\n // 1. Reorder roles for target language\n const reordered = reorderRoles(parsed.roles, targetProfile.canonicalOrder);\n\n // 2. Insert grammatical markers\n const withMarkers = insertMarkers(reordered, targetProfile.markers, targetProfile.adpositionType);\n\n // 3. Join with intelligent spacing for agglutinative languages\n // (handles suffixes like -ta, prefixes like بـ-, etc.)\n return joinTokens(withMarkers);\n}\n","/**\n * Grammar Transformer - Dependency Injection Architecture\n *\n * Transforms statements between languages using injected dependencies.\n * This makes the transformer completely domain-agnostic.\n */\n\nimport type { LanguageProfile, ParsedElement, SemanticRole } from './types';\nimport { reorderRoles, insertMarkers, joinTokens } from './types';\nimport type { Dictionary } from '../interfaces/dictionary';\nimport type { ProfileProvider } from '../interfaces/profile-provider';\n\n/**\n * Configuration for grammar transformer.\n */\nexport interface TransformerConfig {\n /** Dictionary for keyword translation */\n readonly dictionary: Dictionary;\n\n /** Profile provider for grammar rules */\n readonly profileProvider: ProfileProvider;\n}\n\n/**\n * Generic grammar transformer using dependency injection.\n *\n * @example\n * const transformer = new GrammarTransformer({\n * dictionary: new InMemoryDictionary(translations),\n * profileProvider: new InMemoryProfileProvider(profiles)\n * });\n *\n * const japanese = transformer.transform('select name from users', 'en', 'ja');\n * // → \"users から name を 選択\"\n */\nexport class GrammarTransformer {\n private dictionary: Dictionary;\n private profileProvider: ProfileProvider;\n\n constructor(config: TransformerConfig) {\n this.dictionary = config.dictionary;\n this.profileProvider = config.profileProvider;\n }\n\n /**\n * Transform a statement from one language to another.\n *\n * @param input - Statement in source language\n * @param fromLanguage - Source language code\n * @param toLanguage - Target language code\n * @returns Transformed statement in target language\n *\n * @throws Error if profiles not found or translation fails\n */\n transform(input: string, fromLanguage: string, toLanguage: string): string {\n // Get language profiles\n const fromProfile = this.profileProvider.getProfile(fromLanguage);\n const toProfile = this.profileProvider.getProfile(toLanguage);\n\n if (!fromProfile) {\n throw new Error(`No profile found for language: ${fromLanguage}`);\n }\n if (!toProfile) {\n throw new Error(`No profile found for language: ${toLanguage}`);\n }\n\n // Parse statement to semantic roles\n const parsed = this.parseStatement(input, fromLanguage, fromProfile);\n\n // Translate each word\n const translated = this.translateRoles(parsed, fromLanguage, toLanguage);\n\n // Reorder and insert markers\n const reordered = reorderRoles(translated, toProfile.canonicalOrder);\n\n const withMarkers = insertMarkers(reordered, toProfile.markers, toProfile.adpositionType);\n\n return joinTokens(withMarkers);\n }\n\n /**\n * Parse statement into semantic roles.\n * This is a simplified generic parser - DSLs can provide custom parsers.\n */\n private parseStatement(\n input: string,\n language: string,\n profile: LanguageProfile\n ): Map<SemanticRole, string> {\n const roles = new Map<SemanticRole, string>();\n const tokens = input.split(/\\s+/);\n\n // Simple parsing: extract roles based on markers\n let i = 0;\n while (i < tokens.length) {\n const token = tokens[i];\n\n // Check if token is a marker\n const marker = profile.markers.find(m => m.form === token);\n\n if (marker) {\n // Next token is the value for this role\n if (i + 1 < tokens.length) {\n roles.set(marker.role, tokens[i + 1]);\n i += 2;\n } else {\n i++;\n }\n } else {\n // Look up token in dictionary to find its role\n const canonical = this.dictionary.lookup(token, language);\n\n if (canonical) {\n // Assume it's the action (command keyword)\n roles.set('action', canonical);\n } else {\n // Assume it's a value (selector, identifier, etc.)\n // Try to guess the role based on syntax\n if (token.startsWith('#') || token.startsWith('.')) {\n roles.set('patient', token);\n } else {\n // Default to patient for unknown values\n roles.set('patient', token);\n }\n }\n\n i++;\n }\n }\n\n return roles;\n }\n\n /**\n * Translate roles using injected dictionary.\n * Returns a Map of ParsedElement objects expected by reorderRoles.\n */\n private translateRoles(\n roles: Map<SemanticRole, string>,\n _fromLanguage: string,\n toLanguage: string\n ): Map<SemanticRole, ParsedElement> {\n const result = new Map<SemanticRole, ParsedElement>();\n\n for (const [role, value] of roles) {\n // Translate using dictionary\n const translated = this.dictionary.translate(value, toLanguage);\n\n // Create ParsedElement with role, value, and translated\n result.set(role, {\n role,\n value, // Original value\n translated: translated ?? value, // Translated value or original if no translation\n });\n }\n\n return result;\n }\n}\n","/**\n * Dictionary Interface - Keyword Translation\n *\n * Provides keyword translations between languages.\n * DSLs implement this to provide their domain-specific translations.\n */\n\n/**\n * Dictionary provides keyword translations between languages.\n */\nexport interface Dictionary {\n /**\n * Look up canonical form from localized keyword.\n *\n * @param localizedWord - Word in target language (e.g., 'トグル', 'alternar')\n * @param language - Language code\n * @returns Canonical form (e.g., 'toggle') or undefined\n *\n * @example\n * dictionary.lookup('トグル', 'ja') // → 'toggle'\n * dictionary.lookup('alternar', 'es') // → 'toggle'\n */\n lookup(localizedWord: string, language: string): string | undefined;\n\n /**\n * Translate canonical keyword to target language.\n *\n * @param canonical - Canonical form (e.g., 'toggle')\n * @param targetLanguage - Target language code\n * @returns Localized form or undefined\n *\n * @example\n * dictionary.translate('toggle', 'ja') // → 'トグル'\n * dictionary.translate('toggle', 'es') // → 'alternar'\n */\n translate(canonical: string, targetLanguage: string): string | undefined;\n\n /**\n * Get all translations of a word across all supported languages.\n *\n * @param word - Word to translate\n * @param sourceLanguage - Source language\n * @returns Map of language code to translation\n *\n * @example\n * dictionary.getAllTranslations('toggle', 'en')\n * // → { ja: 'トグル', es: 'alternar', ko: '토글', ... }\n */\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string>;\n\n /**\n * Optional: Find what category a word belongs to.\n * Useful for organizing translations by domain (commands, modifiers, events, etc.).\n */\n getCategory?(word: string, language: string): string | undefined;\n}\n\n/**\n * Simple in-memory dictionary implementation.\n * Suitable for small DSLs or prototyping.\n */\nexport class InMemoryDictionary implements Dictionary {\n /**\n * @param translations - Map of language code to canonical→localized mappings\n *\n * @example\n * new InMemoryDictionary({\n * en: { select: 'select', insert: 'insert' },\n * es: { select: 'seleccionar', insert: 'insertar' },\n * ja: { select: '選択', insert: '挿入' }\n * })\n */\n constructor(private translations: Record<string, Record<string, string>>) {}\n\n lookup(word: string, language: string): string | undefined {\n const langDict = this.translations[language];\n if (!langDict) return undefined;\n\n // Reverse lookup: find key where value = word\n const wordLower = word.toLowerCase();\n for (const [canonical, localized] of Object.entries(langDict)) {\n if (localized.toLowerCase() === wordLower) {\n return canonical;\n }\n }\n return undefined;\n }\n\n translate(canonical: string, targetLanguage: string): string | undefined {\n return this.translations[targetLanguage]?.[canonical];\n }\n\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string> {\n const canonical = this.lookup(word, sourceLanguage);\n if (!canonical) return {};\n\n const result: Record<string, string> = {};\n for (const [lang, dict] of Object.entries(this.translations)) {\n const translation = dict[canonical];\n if (translation) {\n result[lang] = translation;\n }\n }\n return result;\n }\n}\n\n/**\n * Null dictionary - no translations (useful for single-language DSLs).\n */\nexport class NullDictionary implements Dictionary {\n lookup(word: string, _language: string): string | undefined {\n return word; // Identity: word is its own canonical form\n }\n\n translate(canonical: string, _targetLanguage: string): string | undefined {\n return canonical; // Identity: no translation\n }\n\n getAllTranslations(word: string, _sourceLanguage: string): Record<string, string> {\n return { en: word }; // Only source language\n }\n}\n","/**\n * Profile Provider Interface - Language Profile Access\n *\n * Provides language profiles for grammar transformation.\n * DSLs implement this to provide their domain-specific profiles.\n */\n\nimport type { LanguageProfile } from '../grammar';\n\n/**\n * Provides language profiles for transformation.\n */\nexport interface ProfileProvider {\n /**\n * Get language profile by code.\n *\n * @param language - ISO 639-1 code (e.g., 'en', 'ja', 'es')\n * @returns Language profile or undefined if not supported\n *\n * @example\n * const profile = provider.getProfile('ja');\n * console.log(profile.wordOrder); // 'SOV'\n */\n getProfile(language: string): LanguageProfile | undefined;\n\n /**\n * Get all supported language codes.\n *\n * @returns Array of ISO 639-1 codes\n *\n * @example\n * provider.getSupportedLanguages() // → ['en', 'ja', 'es', 'ko']\n */\n getSupportedLanguages(): string[];\n\n /**\n * Check if a language is supported.\n *\n * @param language - Language code to check\n * @returns True if language is supported\n */\n hasLanguage(language: string): boolean;\n}\n\n/**\n * Simple in-memory profile provider.\n */\nexport class InMemoryProfileProvider implements ProfileProvider {\n /**\n * @param profiles - Map of language code to profile\n *\n * @example\n * new InMemoryProfileProvider({\n * en: { code: 'en', wordOrder: 'SVO', ... },\n * ja: { code: 'ja', wordOrder: 'SOV', ... }\n * })\n */\n constructor(private profiles: Record<string, LanguageProfile>) {}\n\n getProfile(language: string): LanguageProfile | undefined {\n return this.profiles[language];\n }\n\n getSupportedLanguages(): string[] {\n return Object.keys(this.profiles);\n }\n\n hasLanguage(language: string): boolean {\n return language in this.profiles;\n }\n}\n\n/**\n * Null profile provider - for DSLs that don't need grammar transformation.\n */\nexport class NullProfileProvider implements ProfileProvider {\n getProfile(_language: string): LanguageProfile | undefined {\n return undefined;\n }\n\n getSupportedLanguages(): string[] {\n return [];\n }\n\n hasLanguage(_language: string): boolean {\n return false;\n }\n}\n","/**\n * Value Extractor Interface - Pluggable Tokenization\n *\n * Extracts typed values from input strings.\n * DSLs can provide custom extractors for their domain-specific syntax.\n *\n * Includes the ContextAwareExtractor extension for extractors that need\n * access to tokenizer state (keyword maps, morphological normalizers, etc.).\n */\n\nimport type { MorphologicalNormalizer } from '../core/tokenization/morphology/types';\n\n// =============================================================================\n// Keyword Entry (needed by TokenizerContext)\n// =============================================================================\n\n/**\n * Keyword entry for tokenizer - maps native word to normalized English form.\n * Re-exported here so ContextAwareExtractor consumers can use it without\n * depending on the base-tokenizer module directly.\n */\nexport interface KeywordEntry {\n readonly native: string;\n readonly normalized: string;\n}\n\n// =============================================================================\n// Core Extractor Types\n// =============================================================================\n\n/**\n * Extraction result with value and consumed length.\n */\nexport interface ExtractionResult {\n /** The extracted value */\n readonly value: string;\n\n /** Number of characters consumed */\n readonly length: number;\n\n /** Optional metadata about the extraction */\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Value extractor - identifies and extracts typed values from input.\n */\nexport interface ValueExtractor {\n /** Name of this extractor (for debugging) */\n readonly name: string;\n\n /**\n * Check if this extractor can handle input at position.\n *\n * @param input - Full input string\n * @param position - Current position\n * @returns True if this extractor should try\n *\n * @example\n * // CSS selector extractor\n * canExtract('#button', 0) // → true (starts with #)\n * canExtract('button', 0) // → false\n */\n canExtract(input: string, position: number): boolean;\n\n /**\n * Extract value from input at position.\n *\n * @param input - Full input string\n * @param position - Start position\n * @returns Extraction result or null if extraction failed\n *\n * @example\n * extract('#button', 0) // → { value: '#button', length: 7 }\n * extract('button', 0) // → null (can't extract CSS selector)\n */\n extract(input: string, position: number): ExtractionResult | null;\n}\n\n/**\n * String literal extractor - handles quoted strings.\n */\nexport class StringLiteralExtractor implements ValueExtractor {\n readonly name = 'string-literal';\n\n canExtract(input: string, position: number): boolean {\n const char = input[position];\n return (\n char === '\"' ||\n char === \"'\" ||\n char === '`' ||\n char === '\\u201C' || // Chinese double quote open \"\n char === '\\u2018' // Chinese single quote open '\n );\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n const quote = input[position];\n\n // Chinese double quotes \" ... \"\n if (quote === '\\u201C') {\n let length = 1;\n while (position + length < input.length) {\n if (input[position + length] === '\\u201D') {\n length++;\n return { value: input.substring(position, position + length), length };\n }\n length++;\n }\n return null;\n }\n\n // Chinese single quotes ' ... '\n if (quote === '\\u2018') {\n let length = 1;\n while (position + length < input.length) {\n if (input[position + length] === '\\u2019') {\n length++;\n return { value: input.substring(position, position + length), length };\n }\n length++;\n }\n return null;\n }\n\n // ASCII quotes (same open/close, support escaping)\n let length = 1;\n let escaped = false;\n\n while (position + length < input.length) {\n const char = input[position + length];\n\n if (escaped) {\n escaped = false;\n length++;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n length++;\n continue;\n }\n\n if (char === quote) {\n length++; // Include closing quote\n return {\n value: input.substring(position, position + length),\n length,\n };\n }\n\n length++;\n }\n\n // Unterminated string\n return null;\n }\n}\n\n/**\n * Number extractor - handles integers and floats.\n */\nexport class NumberExtractor implements ValueExtractor {\n readonly name = 'number';\n\n canExtract(input: string, position: number): boolean {\n return /\\d/.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n let hasDecimal = false;\n\n while (position + length < input.length) {\n const char = input[position + length];\n\n if (/\\d/.test(char)) {\n length++;\n } else if (char === '.' && !hasDecimal) {\n hasDecimal = true;\n length++;\n } else {\n break;\n }\n }\n\n if (length === 0) return null;\n\n const numValue = input.substring(position, position + length);\n const afterNum = position + length;\n\n // Check for time unit suffixes\n if (afterNum < input.length) {\n const remaining = input.slice(afterNum);\n\n // CJK multi-char time units (longest first)\n const cjkMultiUnits: { pattern: string; suffix: string }[] = [\n { pattern: '毫秒', suffix: 'ms' }, // Chinese milliseconds\n { pattern: '分钟', suffix: 'm' }, // Chinese minutes\n { pattern: '小时', suffix: 'h' }, // Chinese hours\n { pattern: 'ミリ秒', suffix: 'ms' }, // Japanese milliseconds\n { pattern: '時間', suffix: 'h' }, // Japanese hours\n ];\n for (const unit of cjkMultiUnits) {\n if (remaining.startsWith(unit.pattern)) {\n return {\n value: numValue + unit.suffix,\n length: length + unit.pattern.length,\n metadata: { hasTimeUnit: true },\n };\n }\n }\n\n // ASCII 'ms' (2 chars, must check before single-char)\n if (remaining.startsWith('ms')) {\n return {\n value: numValue + 'ms',\n length: length + 2,\n metadata: { hasTimeUnit: true },\n };\n }\n\n // CJK single-char time units\n const cjkSingleUnits: { pattern: string; suffix: string }[] = [\n { pattern: '秒', suffix: 's' }, // CJK seconds\n { pattern: '分', suffix: 'm' }, // CJK minutes\n ];\n for (const unit of cjkSingleUnits) {\n if (remaining.startsWith(unit.pattern)) {\n return {\n value: numValue + unit.suffix,\n length: length + 1,\n metadata: { hasTimeUnit: true },\n };\n }\n }\n\n // ASCII single-char units: s, m, h (with word boundary check)\n if (/^[smh](?![a-zA-Z])/.test(remaining)) {\n return {\n value: numValue + remaining[0],\n length: length + 1,\n metadata: { hasTimeUnit: true },\n };\n }\n }\n\n return { value: numValue, length };\n }\n}\n\n/**\n * Identifier extractor - handles variable/property names.\n */\nexport class IdentifierExtractor implements ValueExtractor {\n readonly name = 'identifier';\n\n canExtract(input: string, position: number): boolean {\n return /[a-zA-Z_]/.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n\n while (position + length < input.length) {\n const char = input[position + length];\n if (/[a-zA-Z0-9_]/.test(char)) {\n length++;\n } else {\n break;\n }\n }\n\n return length > 0\n ? {\n value: input.substring(position, position + length),\n length,\n }\n : null;\n }\n}\n\n/**\n * Unicode identifier extractor - handles non-Latin scripts.\n *\n * Matches contiguous runs of Unicode letters, numbers, and combining marks\n * that aren't ASCII (ASCII identifiers are handled by IdentifierExtractor).\n * Essential for DSLs supporting CJK, Arabic, Cyrillic, Devanagari, etc.\n */\nexport class UnicodeIdentifierExtractor implements ValueExtractor {\n readonly name = 'unicode-identifier';\n\n canExtract(input: string, position: number): boolean {\n const code = input.charCodeAt(position);\n // Skip ASCII range (handled by IdentifierExtractor)\n if (code < 0x80) return false;\n // Match any Unicode letter\n return /\\p{L}/u.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n\n while (position + length < input.length) {\n const char = input[position + length];\n // Match Unicode letters, numbers, and combining marks (e.g., Arabic diacritics)\n if (/[\\p{L}\\p{N}\\p{M}]/u.test(char)) {\n length++;\n } else {\n break;\n }\n }\n\n return length > 0 ? { value: input.substring(position, position + length), length } : null;\n }\n}\n\n/**\n * Latin Extended identifier extractor — handles Latin-script languages with\n * diacritics (Spanish ñ/á/é/í/ó/ú; French é/à/ù/ç; Turkish ç/ş/ı/ü/ğ/ö;\n * Portuguese ã/õ; German ä/ö/ü/ß; etc).\n *\n * Use this in addition to (or instead of) the default `IdentifierExtractor`\n * for any tokenizer whose language is Latin-script and may contain diacritic\n * characters in identifiers. Without it, words like `añadir` tokenize as\n * `[\"a\", \"ñadir\"]` because the default ASCII extractor stops at `ñ` and the\n * Unicode extractor only kicks in when a token *starts* with a non-ASCII\n * character.\n *\n * Matches contiguous runs of `/[\\p{L}\\p{N}_-]/u` — any Unicode letter or\n * number, plus underscore and hyphen.\n */\nexport class LatinExtendedIdentifierExtractor implements ValueExtractor {\n readonly name = 'latin-extended-identifier';\n\n canExtract(input: string, position: number): boolean {\n return /\\p{L}/u.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let end = position;\n while (end < input.length && /[\\p{L}\\p{N}_-]/u.test(input[end])) {\n end++;\n }\n if (end === position) return null;\n return { value: input.slice(position, end), length: end - position };\n }\n}\n\n/**\n * CSS selector extractor — keeps `#id` and `.class` a SINGLE token.\n *\n * Without it the sigil is split off as its own token and the role capture keeps\n * only that sigil: `add .active to #button` parses with patient `\".\"` and\n * destination `\"#\"`, silently, in every language. Five domain DSLs each carried\n * a private copy of this class and four (learn, todo, sql, jsx) had none — this\n * is the shared one; register it via `customExtractors`.\n *\n * The character after the sigil must be a letter, `_` or `-`: a CSS identifier\n * cannot start with a digit, and refusing to claim a bare `.`/`#` leaves\n * property access and other uses of those characters to the extractors that own\n * them.\n *\n * The body is Unicode so diacritics survive (`.año`, not `.a`) but STOPS at Han,\n * kana and Hangul. Those scripts are where the SOV languages write their\n * particles, and a selector is written adjacent to them with no space:\n * `#buttonに .activeを 追加` must yield `#button` + `に`, not a `#buttonに` that\n * swallows the particle and takes the role marker with it.\n */\nconst SELECTOR_BODY_CHAR = /[\\p{L}\\p{N}_-]/u;\nconst PARTICLE_SCRIPT_CHAR = /[\\p{sc=Han}\\p{sc=Hiragana}\\p{sc=Katakana}\\p{sc=Hangul}]/u;\n\nfunction isSelectorBodyChar(char: string): boolean {\n return SELECTOR_BODY_CHAR.test(char) && !PARTICLE_SCRIPT_CHAR.test(char);\n}\n\nexport class CssSelectorExtractor implements ValueExtractor {\n readonly name = 'css-selector';\n\n canExtract(input: string, position: number): boolean {\n const char = input[position];\n if (char !== '#' && char !== '.') return false;\n const next = input[position + 1];\n if (next === undefined) return false;\n return (\n next === '_' || next === '-' || (/\\p{L}/u.test(next) && !PARTICLE_SCRIPT_CHAR.test(next))\n );\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let end = position + 1;\n while (end < input.length && isSelectorBodyChar(input[end])) {\n end++;\n }\n if (end === position + 1) return null;\n return { value: input.slice(position, end), length: end - position };\n }\n}\n\n/**\n * Whitespace extractor - handles spaces, tabs, newlines.\n */\nexport class WhitespaceExtractor implements ValueExtractor {\n readonly name = 'whitespace';\n\n canExtract(input: string, position: number): boolean {\n return /\\s/.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n\n while (position + length < input.length && /\\s/.test(input[position + length])) {\n length++;\n }\n\n return length > 0\n ? {\n value: input.substring(position, position + length),\n length,\n }\n : null;\n }\n}\n\n// =============================================================================\n// Context-Aware Extractor System\n// =============================================================================\n\n/**\n * Tokenizer context provided to context-aware extractors.\n * Gives extractors access to tokenizer state without tight coupling.\n */\nexport interface TokenizerContext {\n /** ISO 639-1 language code */\n readonly language: string;\n\n /** Text direction */\n readonly direction: 'ltr' | 'rtl';\n\n /**\n * Look up a keyword by its native form.\n * Returns keyword entry with normalized form, or undefined if not found.\n */\n lookupKeyword(native: string): KeywordEntry | undefined;\n\n /**\n * Check if a word is a known keyword.\n */\n isKeyword(native: string): boolean;\n\n /**\n * Check if a known keyword starts at the given position.\n * Useful for word boundary detection in non-space languages.\n */\n isKeywordStart(input: string, position: number): boolean;\n\n /**\n * Like `isKeywordStart`, but only true when the keyword match ends at a\n * word boundary (end of input or a char rejected by `isWordChar`).\n * Space-delimited languages must use this for word-walk break checks —\n * the keyword table includes English canonical fallbacks (me, it, you, …),\n * so the raw check splits native words mid-word (e.g. Quechua ñit'iy\n * contains \"it\"). Optional for backward compatibility with hand-rolled\n * contexts; callers should treat absence as \"no boundary keyword here\".\n */\n isKeywordStartAtBoundary?(\n input: string,\n position: number,\n isWordChar?: (char: string) => boolean\n ): boolean;\n\n /**\n * Optional morphological normalizer for this language.\n */\n readonly normalizer?: MorphologicalNormalizer;\n}\n\n/**\n * Context-aware extractor - has access to tokenizer state.\n *\n * Use this for extractors that need:\n * - Keyword lookup (for normalization)\n * - Morphological analysis (for conjugation handling)\n * - Language-specific rules\n *\n * For stateless extractors (strings, numbers, operators), use ValueExtractor.\n */\nexport interface ContextAwareExtractor extends ValueExtractor {\n /**\n * Set the tokenizer context.\n * Called once by the tokenizer during registration.\n */\n setContext(context: TokenizerContext): void;\n}\n\n/**\n * Type guard to check if an extractor is context-aware.\n */\nexport function isContextAwareExtractor(\n extractor: ValueExtractor | ContextAwareExtractor\n): extractor is ContextAwareExtractor {\n return 'setContext' in extractor && typeof extractor.setContext === 'function';\n}\n\n/**\n * Create a TokenizerContext from a tokenizer instance.\n * Works with any object that exposes the required methods.\n */\nexport function createTokenizerContext(tokenizer: {\n language: string;\n direction: 'ltr' | 'rtl';\n lookupKeyword(native: string): KeywordEntry | undefined;\n isKeyword(native: string): boolean;\n isKeywordStart(input: string, position: number): boolean;\n isKeywordStartAtBoundary?(\n input: string,\n position: number,\n isWordChar?: (char: string) => boolean\n ): boolean;\n normalizer?: MorphologicalNormalizer;\n}): TokenizerContext {\n const ctx: TokenizerContext = {\n language: tokenizer.language,\n direction: tokenizer.direction,\n lookupKeyword: tokenizer.lookupKeyword.bind(tokenizer),\n isKeyword: tokenizer.isKeyword.bind(tokenizer),\n isKeywordStart: tokenizer.isKeywordStart.bind(tokenizer),\n ...(tokenizer.isKeywordStartAtBoundary\n ? { isKeywordStartAtBoundary: tokenizer.isKeywordStartAtBoundary.bind(tokenizer) }\n : {}),\n };\n\n if (tokenizer.normalizer) {\n return { ...ctx, normalizer: tokenizer.normalizer };\n }\n\n return ctx;\n}\n","/**\n * Reference Validation — re-exported from @lokascript/intent\n */\n\nexport { DEFAULT_REFERENCES, isValidReference } from '@lokascript/intent';\n","/**\n * Explicit Syntax Parser — re-exported from @lokascript/intent\n */\n\nexport {\n STRUCTURAL_ROLES,\n parseExplicit,\n isExplicitSyntax,\n parseCompound,\n parseDocument,\n isCompoundSyntax,\n isDocumentSyntax,\n} from '@lokascript/intent';\n","/**\n * Explicit Syntax Renderer — re-exported from @lokascript/intent\n */\n\nexport { renderExplicit, renderDocument } from '@lokascript/intent';\n","/**\n * LLM JSON Schema Conversion (DEPRECATED)\n *\n * These functions are superseded by the unified protocol JSON functions in\n * protocol-json.ts. `fromProtocolJSON()` now accepts optional `kind` (defaults\n * to \"command\") and `trigger` sugar, making these wrappers unnecessary.\n *\n * Use instead:\n * - `validateProtocolJSON()` instead of `validateSemanticJSON()`\n * - `fromProtocolJSON()` instead of `jsonToSemanticNode()`\n * - `toProtocolJSON()` instead of `semanticNodeToJSON()`\n *\n * These functions are kept for backward compatibility and will be removed\n * in a future major version.\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n SemanticRole,\n EventHandlerSemanticNode,\n CompoundSemanticNode,\n} from '../core/types';\nimport {\n createCommandNode,\n createEventHandlerNode,\n createSelector,\n createLiteral,\n createReference,\n createExpression,\n createFlag,\n} from '../core/types';\nimport type { SemanticJSON, SemanticJSONValue, IRDiagnostic } from './types';\n\n// =============================================================================\n// Validation\n// =============================================================================\n\nconst VALID_VALUE_TYPES = new Set([\n 'selector',\n 'literal',\n 'reference',\n 'expression',\n 'property-path',\n 'flag',\n]);\n\n/**\n * Validate LLM JSON input structure.\n * Returns diagnostics (empty array = valid).\n * @deprecated Use `validateProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function validateSemanticJSON(input: SemanticJSON): IRDiagnostic[] {\n const diagnostics: IRDiagnostic[] = [];\n\n // Action is required and must be a string\n if (!input.action || typeof input.action !== 'string') {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_ACTION',\n message: 'Field \"action\" is required and must be a string.',\n suggestion: 'Provide a command name like \"toggle\", \"add\", \"set\", etc.',\n });\n return diagnostics; // Can't proceed without action\n }\n\n // Roles validation\n if (input.roles && typeof input.roles === 'object') {\n for (const [role, value] of Object.entries(input.roles)) {\n if (!value || typeof value !== 'object') {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_ROLE_VALUE',\n message: `Role \"${role}\" must be an object with \"type\" and \"value\" fields.`,\n suggestion: 'Use: { \"type\": \"selector\", \"value\": \".active\" }',\n });\n continue;\n }\n\n const v = value as SemanticJSONValue;\n if (!VALID_VALUE_TYPES.has(v.type)) {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_VALUE_TYPE',\n message: `Role \"${role}\" has invalid type \"${v.type}\".`,\n suggestion: 'Valid types: selector, literal, reference, expression, property-path.',\n });\n }\n\n if (v.value === undefined || v.value === null) {\n diagnostics.push({\n severity: 'error',\n code: 'MISSING_VALUE',\n message: `Role \"${role}\" is missing the \"value\" field.`,\n });\n }\n }\n }\n\n // Trigger validation (optional)\n if (input.trigger) {\n if (!input.trigger.event || typeof input.trigger.event !== 'string') {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_TRIGGER',\n message: 'Trigger \"event\" is required and must be a string.',\n suggestion: 'Use an event name like \"click\", \"mouseover\", \"keydown\".',\n });\n }\n }\n\n return diagnostics;\n}\n\n// =============================================================================\n// JSON → SemanticNode\n// =============================================================================\n\n/**\n * Convert validated SemanticJSON to a SemanticNode.\n *\n * Returns a properly typed SemanticNode using the framework's factory functions.\n * If `trigger` is present, wraps the command in an event handler node.\n * @deprecated Use `fromProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function jsonToSemanticNode(input: SemanticJSON): SemanticNode {\n const roles = new Map<SemanticRole, SemanticValue>();\n\n if (input.roles) {\n for (const [role, value] of Object.entries(input.roles)) {\n roles.set(role as SemanticRole, convertJSONValue(value));\n }\n }\n\n // Event handler wrapping\n if (input.trigger) {\n // Set the event role\n roles.set('event' as SemanticRole, createLiteral(input.trigger.event, 'string'));\n\n // Build body as a single command node\n const bodyRoles = new Map(roles);\n bodyRoles.delete('event' as SemanticRole);\n const bodyNode = createCommandNode(input.action, bodyRoles);\n\n return createEventHandlerNode(\n 'on',\n roles,\n [bodyNode],\n { sourceLanguage: 'json' },\n (input.trigger.modifiers as Record<string, unknown> | undefined) ?? {}\n );\n }\n\n return createCommandNode(input.action, roles, {\n sourceLanguage: 'json',\n });\n}\n\n// =============================================================================\n// SemanticNode → JSON\n// =============================================================================\n\n/**\n * Convert a SemanticNode to SemanticJSON format.\n *\n * This is the inverse of jsonToSemanticNode(). For event handlers,\n * the event is extracted into the `trigger` field.\n * @deprecated Use `toProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function semanticNodeToJSON(node: SemanticNode): SemanticJSON {\n if (node.kind === 'compound') {\n // Compound nodes: use first statement's action, flatten roles\n const compound = node as CompoundSemanticNode;\n if (compound.statements.length > 0) {\n return semanticNodeToJSON(compound.statements[0]);\n }\n return { action: 'compound', roles: {} };\n }\n\n if (node.kind === 'event-handler') {\n const eventNode = node as EventHandlerSemanticNode;\n const bodyAction = eventNode.body?.[0]?.action ?? node.action;\n const roles: Record<string, SemanticJSONValue> = {};\n\n // Convert body's roles (not the event handler's)\n if (eventNode.body?.[0]) {\n for (const [role, value] of eventNode.body[0].roles) {\n roles[role] = semanticValueToJSON(value);\n }\n }\n\n // Extract event from roles\n const eventValue = node.roles.get('event');\n const eventName = eventValue\n ? 'value' in eventValue\n ? String(eventValue.value)\n : 'raw' in eventValue\n ? eventValue.raw\n : 'unknown'\n : 'unknown';\n\n const result: SemanticJSON = {\n action: bodyAction === 'on' ? (eventNode.body?.[0]?.action ?? 'on') : bodyAction,\n roles,\n trigger: {\n event: eventName,\n },\n };\n\n if (eventNode.eventModifiers && Object.keys(eventNode.eventModifiers).length > 0) {\n result.trigger!.modifiers = eventNode.eventModifiers as Record<string, unknown>;\n }\n\n return result;\n }\n\n // Regular command\n const roles: Record<string, SemanticJSONValue> = {};\n for (const [role, value] of node.roles) {\n roles[role] = semanticValueToJSON(value);\n }\n\n return { action: node.action, roles };\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Convert a SemanticJSONValue to a SemanticValue.\n */\nfunction convertJSONValue(value: SemanticJSONValue): SemanticValue {\n switch (value.type) {\n case 'selector':\n return createSelector(String(value.value), detectSelectorKind(String(value.value)));\n\n case 'literal':\n return createLiteral(\n value.value,\n typeof value.value === 'number'\n ? 'number'\n : typeof value.value === 'boolean'\n ? 'boolean'\n : 'string'\n );\n\n case 'reference':\n return createReference(String(value.value));\n\n case 'expression':\n return createExpression(String(value.value));\n\n case 'property-path':\n // Property paths in JSON are represented as dot-separated strings\n return createExpression(String(value.value));\n\n case 'flag':\n return createFlag(String(value.value), true);\n\n default:\n return createLiteral(String(value.value), 'string');\n }\n}\n\n/**\n * Convert a SemanticValue to a SemanticJSONValue.\n */\nfunction semanticValueToJSON(value: SemanticValue): SemanticJSONValue {\n switch (value.type) {\n case 'selector':\n return { type: 'selector', value: value.value };\n\n case 'literal':\n return { type: 'literal', value: value.value };\n\n case 'reference':\n return { type: 'reference', value: value.value };\n\n case 'expression':\n return { type: 'expression', value: value.raw };\n\n case 'property-path':\n return {\n type: 'property-path',\n value: `${semanticValueToJSON(value.object).value}.${value.property}`,\n };\n\n case 'flag':\n return { type: 'flag', value: value.enabled };\n }\n}\n\nfunction detectSelectorKind(selector: string): 'id' | 'class' | 'attribute' | 'complex' {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n","/**\n * Protocol JSON Serialization — re-exported from @lokascript/intent\n */\n\nexport {\n toProtocolJSON,\n fromProtocolJSON,\n validateProtocolJSON,\n toEnvelopeJSON,\n fromEnvelopeJSON,\n isEnvelope,\n} from '@lokascript/intent';\n","/**\n * InterchangeNode → SemanticNode Converter\n *\n * Converts the expression-level InterchangeNode AST (from core/semantic parsers)\n * into the command-level SemanticNode IR used by LSE, MCP tools, and domain DSLs.\n *\n * This bridges the two IR pipelines in the monorepo:\n * - Pipeline A (InterchangeNode): full expression trees, 16 node types\n * - Pipeline B (SemanticNode): command-level semantics, opaque expression values\n *\n * Expression subtrees are intentionally collapsed to ExpressionValue { raw: string }\n * — LSE deliberately abstracts away expression-level detail.\n *\n * Uses structural typing for the input to avoid a dependency on the core package.\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n SemanticRole,\n LoopVariant,\n EventModifiers as SemanticEventModifiers,\n} from '../core/types';\nimport {\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createLoopNode,\n createLiteral,\n createSelector,\n createReference,\n createExpression,\n createPropertyPath,\n} from '../core/types';\nimport { DEFAULT_REFERENCES } from './references';\n\n// =============================================================================\n// Structural Input Types (no core package dependency)\n// =============================================================================\n\n/**\n * Minimal interface matching InterchangeNode's structural shape.\n * Uses the `type` discriminant for dispatch. Additional fields are\n * accessed dynamically — this keeps the framework free of core imports.\n */\ninterface INode {\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Convert an InterchangeNode (expression-level AST) to a SemanticNode (command-level IR).\n *\n * Handles all 16 InterchangeNode types:\n * - Command/event nodes map to corresponding SemanticNode kinds\n * - Control flow nodes (if, repeat, foreach, while) map to conditional/loop kinds\n * - Expression nodes are wrapped as `get` commands with the value as patient role\n *\n * @param node - An InterchangeNode (or structurally compatible object)\n * @returns A SemanticNode suitable for LSE rendering, protocol JSON, or MCP tools\n */\nexport function fromInterchangeNode(node: INode): SemanticNode {\n if (!node || typeof node !== 'object') {\n return createCommandNode('unknown', {});\n }\n\n switch (node.type) {\n case 'event':\n return convertEvent(node);\n\n case 'command':\n return convertCommand(node);\n\n case 'if':\n return convertIf(node);\n\n case 'repeat':\n return convertRepeat(node);\n\n case 'foreach':\n return convertForEach(node);\n\n case 'while':\n return convertWhile(node);\n\n // Expression nodes — wrap as `get` command with patient role\n default:\n return createCommandNode('get', { patient: convertValue(node) });\n }\n}\n\n// =============================================================================\n// Node Converters\n// =============================================================================\n\nfunction convertEvent(node: INode): SemanticNode {\n const event = String(node.event ?? 'click');\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n\n const roles: Record<SemanticRole, SemanticValue> = {\n event: createLiteral(event),\n };\n\n // Preserve event target if present\n if (node.target && typeof node.target === 'object') {\n roles.source = convertValue(node.target as INode);\n }\n\n // Bridge event modifiers\n const modifiers = node.modifiers as Record<string, unknown> | undefined;\n let eventModifiers: SemanticEventModifiers | undefined;\n\n if (modifiers) {\n eventModifiers = bridgeEventModifiers(modifiers);\n\n // InterchangeNode-only modifiers → encode as roles\n if (modifiers.prevent) roles.prevent = createLiteral(true);\n if (modifiers.stop) roles.stop = createLiteral(true);\n if (modifiers.passive) roles.passive = createLiteral(true);\n if (modifiers.capture) roles.capture = createLiteral(true);\n }\n\n return createEventHandlerNode('on', roles, body, undefined, eventModifiers);\n}\n\nfunction convertCommand(node: INode): SemanticNode {\n const name = String(node.name ?? 'unknown');\n const args = Array.isArray(node.args) ? (node.args as INode[]) : [];\n const target =\n node.target && typeof node.target === 'object' ? (node.target as INode) : undefined;\n const existingRoles = node.roles as Record<string, INode> | undefined;\n const modifiers = node.modifiers as Record<string, unknown> | undefined;\n\n let roles: Record<SemanticRole, SemanticValue>;\n\n if (existingRoles && typeof existingRoles === 'object' && Object.keys(existingRoles).length > 0) {\n // Semantic parser path: roles already present\n roles = {};\n for (const [role, value] of Object.entries(existingRoles)) {\n if (value && typeof value === 'object' && 'type' in value) {\n roles[role] = convertValue(value as INode);\n }\n }\n } else {\n // Core parser path: infer roles from command name\n roles = inferRoles(name, args, modifiers, target);\n }\n\n return createCommandNode(name, roles);\n}\n\nfunction convertIf(node: INode): SemanticNode {\n const condition =\n node.condition && typeof node.condition === 'object'\n ? convertValue(node.condition as INode)\n : createExpression('true');\n\n const thenBody = Array.isArray(node.thenBranch) ? (node.thenBranch as INode[]) : [];\n const thenBranch = thenBody.map(fromInterchangeNode);\n\n // Handle else branch — may include chained else-if\n let elseBranch: SemanticNode[] | undefined;\n\n const elseIfBranches = node.elseIfBranches as\n ReadonlyArray<{ condition: INode; body: INode[] }> | undefined;\n\n if (elseIfBranches && elseIfBranches.length > 0) {\n // Chain else-if branches as nested conditionals\n elseBranch = [chainElseIfs(elseIfBranches, node.elseBranch as INode[] | undefined)];\n } else if (Array.isArray(node.elseBranch) && (node.elseBranch as INode[]).length > 0) {\n elseBranch = (node.elseBranch as INode[]).map(fromInterchangeNode);\n }\n\n const roles: Record<SemanticRole, SemanticValue> = { condition };\n return createConditionalNode('if', roles, thenBranch, elseBranch);\n}\n\nfunction chainElseIfs(\n branches: ReadonlyArray<{ condition: INode; body: INode[] }>,\n finalElse: INode[] | undefined\n): SemanticNode {\n const [first, ...rest] = branches;\n const condition = convertValue(first.condition as INode);\n const thenBranch = first.body.map(fromInterchangeNode);\n\n let elseBranch: SemanticNode[] | undefined;\n if (rest.length > 0) {\n elseBranch = [chainElseIfs(rest, finalElse)];\n } else if (finalElse && finalElse.length > 0) {\n elseBranch = finalElse.map(fromInterchangeNode);\n }\n\n return createConditionalNode('if', { condition }, thenBranch, elseBranch);\n}\n\nfunction convertRepeat(node: INode): SemanticNode {\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n let variant: LoopVariant;\n\n if (node.count !== undefined && node.count !== null) {\n variant = 'times';\n if (typeof node.count === 'number') {\n roles.quantity = createLiteral(node.count, 'number');\n } else if (typeof node.count === 'object') {\n roles.quantity = convertValue(node.count as INode);\n }\n } else if (node.whileCondition && typeof node.whileCondition === 'object') {\n variant = 'while';\n roles.condition = convertValue(node.whileCondition as INode);\n } else if (typeof node.untilEvent === 'string') {\n variant = 'until';\n roles.condition = createLiteral(node.untilEvent);\n } else {\n variant = 'forever';\n }\n\n return createLoopNode('repeat', roles, variant, body);\n}\n\nfunction convertForEach(node: INode): SemanticNode {\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n if (node.collection && typeof node.collection === 'object') {\n roles.source = convertValue(node.collection as INode);\n }\n\n const itemName = typeof node.itemName === 'string' ? node.itemName : undefined;\n const indexName = typeof node.indexName === 'string' ? node.indexName : undefined;\n\n return createLoopNode('repeat', roles, 'for', body, itemName, indexName);\n}\n\nfunction convertWhile(node: INode): SemanticNode {\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n if (node.condition && typeof node.condition === 'object') {\n roles.condition = convertValue(node.condition as INode);\n }\n\n return createLoopNode('repeat', roles, 'while', body);\n}\n\n// =============================================================================\n// Value Conversion\n// =============================================================================\n\n/**\n * Convert an InterchangeNode to a SemanticValue.\n *\n * Simple nodes map directly to typed SemanticValue variants.\n * Complex expression nodes are collapsed to ExpressionValue { raw: string }.\n */\nexport function convertValue(node: INode): SemanticValue {\n switch (node.type) {\n case 'literal':\n return convertLiteral(node);\n\n case 'selector':\n return createSelector(String(node.value ?? ''), inferSelectorKind(String(node.value ?? '')));\n\n case 'identifier':\n return convertIdentifier(node);\n\n case 'variable':\n return convertVariable(node);\n\n case 'possessive':\n return createPropertyPath(\n node.object && typeof node.object === 'object'\n ? convertValue(node.object as INode)\n : createReference('me'),\n String(node.property ?? '')\n );\n\n // Complex expressions → collapse to raw string\n case 'binary':\n case 'unary':\n case 'member':\n case 'call':\n case 'positional':\n return createExpression(renderExpr(node));\n\n default:\n // Unknown type — render as expression\n if ('value' in node) return createLiteral(String(node.value ?? ''));\n return createExpression(renderExpr(node));\n }\n}\n\nfunction convertLiteral(node: INode): SemanticValue {\n const value = node.value;\n if (value === null || value === undefined) return createLiteral('null');\n\n const dataType =\n typeof value === 'number'\n ? ('number' as const)\n : typeof value === 'boolean'\n ? ('boolean' as const)\n : undefined;\n\n return createLiteral(value as string | number | boolean, dataType);\n}\n\nfunction convertIdentifier(node: INode): SemanticValue {\n const value = String(node.value ?? '');\n if (DEFAULT_REFERENCES.has(value)) {\n return createReference(value);\n }\n return createLiteral(value);\n}\n\nfunction convertVariable(node: INode): SemanticValue {\n const name = String(node.name ?? '');\n const scope = String(node.scope ?? 'local');\n\n switch (scope) {\n case 'element':\n return createExpression(`:${name}`);\n case 'global':\n return createExpression(`$${name}`);\n default:\n return createExpression(name);\n }\n}\n\n// =============================================================================\n// Expression Renderer\n// =============================================================================\n\n/**\n * Recursively render an InterchangeNode expression tree to a string.\n * Used to collapse complex expressions into ExpressionValue.raw.\n */\nexport function renderExpr(node: INode): string {\n if (!node || typeof node !== 'object') return '';\n\n switch (node.type) {\n case 'literal': {\n const v = node.value;\n if (v === null || v === undefined) return 'null';\n if (typeof v === 'string') return /\\s/.test(v) ? `\"${v}\"` : v;\n return String(v);\n }\n\n case 'identifier':\n return String(node.value ?? '');\n\n case 'selector':\n return String(node.value ?? '');\n\n case 'variable': {\n const name = String(node.name ?? '');\n const scope = String(node.scope ?? 'local');\n if (scope === 'element') return `:${name}`;\n if (scope === 'global') return `$${name}`;\n return name;\n }\n\n case 'binary': {\n const left = node.left && typeof node.left === 'object' ? renderExpr(node.left as INode) : '';\n const right =\n node.right && typeof node.right === 'object' ? renderExpr(node.right as INode) : '';\n return `${left} ${node.operator ?? ''} ${right}`;\n }\n\n case 'unary': {\n const operand =\n node.operand && typeof node.operand === 'object' ? renderExpr(node.operand as INode) : '';\n return `${node.operator ?? ''} ${operand}`;\n }\n\n case 'member': {\n const obj =\n node.object && typeof node.object === 'object' ? renderExpr(node.object as INode) : '';\n if (node.computed && node.property && typeof node.property === 'object') {\n return `${obj}[${renderExpr(node.property as INode)}]`;\n }\n const prop =\n typeof node.property === 'string'\n ? node.property\n : node.property && typeof node.property === 'object'\n ? renderExpr(node.property as INode)\n : '';\n return `${obj}.${prop}`;\n }\n\n case 'possessive': {\n const obj =\n node.object && typeof node.object === 'object' ? renderExpr(node.object as INode) : '';\n return `${obj}'s ${node.property ?? ''}`;\n }\n\n case 'call': {\n const callee =\n node.callee && typeof node.callee === 'object' ? renderExpr(node.callee as INode) : '';\n const args = Array.isArray(node.args)\n ? (node.args as INode[]).map(a => renderExpr(a)).join(', ')\n : '';\n return `${callee}(${args})`;\n }\n\n case 'positional': {\n const target =\n node.target && typeof node.target === 'object' ? renderExpr(node.target as INode) : '';\n return target ? `${node.position ?? ''} ${target}` : String(node.position ?? '');\n }\n\n default:\n if ('value' in node) return String(node.value ?? '');\n return '';\n }\n}\n\n// =============================================================================\n// Role Inference\n// =============================================================================\n\n/**\n * Marker-keyword sets — mirror the runtime command parsers' skip lists so the\n * inferred roles point at the real value, not the literal marker word.\n */\nconst SCROLL_MARKERS: ReadonlySet<string> = new Set([\n 'to',\n 'of',\n 'the',\n 'top',\n 'bottom',\n 'middle',\n 'center',\n 'nearest',\n 'left',\n 'right',\n 'smoothly',\n 'instantly',\n]);\nconst URL_MARKERS: ReadonlySet<string> = new Set(['url']);\nconst PARTIALS_IN_MARKERS: ReadonlySet<string> = new Set(['partials', 'in']);\n\n/**\n * Return the first arg that isn't a marker identifier from the given set.\n * Identifier args carry the marker word in `name` (or `value` as a fallback).\n */\nfunction firstNonMarkerArg(args: INode[], markers: ReadonlySet<string>): INode | undefined {\n for (const a of args) {\n if (a.type === 'identifier') {\n const ident = a as { name?: unknown; value?: unknown };\n const word = typeof ident.name === 'string' ? ident.name : ident.value;\n if (typeof word === 'string' && markers.has(word)) continue;\n }\n return a;\n }\n return undefined;\n}\n\n/**\n * Infer semantic roles from command name, positional args, modifiers, and target.\n * Mirrors the heuristics in core's from-core.ts inferRoles() function.\n */\nfunction inferRoles(\n name: string,\n args: INode[],\n modifiers: Record<string, unknown> | undefined,\n target: INode | undefined\n): Record<SemanticRole, SemanticValue> {\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n switch (name) {\n case 'set': {\n if (args[0]) roles.destination = convertValue(args[0]);\n const toVal = modifiers?.to;\n if (toVal && typeof toVal === 'object' && 'type' in (toVal as object)) {\n roles.patient = convertValue(toVal as INode);\n } else if (args[1]) {\n roles.patient = convertValue(args[1]);\n }\n break;\n }\n\n case 'put': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (modifiers) {\n for (const key of ['into', 'before', 'after'] as const) {\n const val = modifiers[key];\n if (val && typeof val === 'object' && 'type' in (val as object)) {\n roles.destination = convertValue(val as INode);\n roles.method = createLiteral(key);\n break;\n }\n }\n }\n if (!roles.destination && target) {\n roles.destination = convertValue(target);\n }\n break;\n }\n\n case 'increment':\n case 'decrement': {\n if (args[0]) roles.destination = convertValue(args[0]);\n const byVal = modifiers?.by;\n if (byVal && typeof byVal === 'object' && 'type' in (byVal as object)) {\n roles.quantity = convertValue(byVal as INode);\n } else if (args[1]) {\n roles.quantity = convertValue(args[1]);\n }\n break;\n }\n\n case 'fetch': {\n if (args[0]) roles.source = convertValue(args[0]);\n const asVal = modifiers?.as;\n if (asVal && typeof asVal === 'object' && 'type' in (asVal as object)) {\n roles.responseType = convertValue(asVal as INode);\n } else if (typeof asVal === 'string') {\n roles.responseType = createLiteral(asVal);\n }\n break;\n }\n\n case 'wait':\n case 'settle': {\n if (args[0]) roles.duration = convertValue(args[0]);\n break;\n }\n\n case 'toggle':\n case 'add':\n case 'show':\n case 'hide': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.destination = convertValue(target);\n break;\n }\n\n case 'remove': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.source = convertValue(target);\n break;\n }\n\n case 'send':\n case 'trigger': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.destination = convertValue(target);\n break;\n }\n\n case 'log': {\n if (args[0]) roles.patient = convertValue(args[0]);\n break;\n }\n\n // scroll [to] [position] target [smoothly|instantly] → destination=target\n case 'scroll': {\n const t = firstNonMarkerArg(args, SCROLL_MARKERS);\n if (t) roles.destination = convertValue(t);\n break;\n }\n\n // push|replace url <X> → patient=X\n case 'push':\n case 'replace': {\n const t = firstNonMarkerArg(args, URL_MARKERS);\n if (t) roles.patient = convertValue(t);\n break;\n }\n\n // process partials in <X> → patient=X\n case 'process': {\n const t = firstNonMarkerArg(args, PARTIALS_IN_MARKERS);\n if (t) roles.patient = convertValue(t);\n break;\n }\n\n default: {\n // Generic fallback: first arg as patient, target as destination\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.destination = convertValue(target);\n break;\n }\n }\n\n return roles;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Infer selectorKind from a CSS selector string.\n */\nfunction inferSelectorKind(\n value: string\n): 'id' | 'class' | 'attribute' | 'element' | 'complex' | undefined {\n if (!value) return undefined;\n if (value.startsWith('#')) return 'id';\n if (value.startsWith('.')) return 'class';\n if (value.startsWith('[')) return 'attribute';\n if (value.startsWith('<') || value.startsWith('*')) return 'element';\n // Check for combinators indicating complex selectors\n if (/[>\\+~ ]/.test(value) && value.length > 1) return 'complex';\n return undefined;\n}\n\n/**\n * Infer a SemanticValue from a string (for event modifier `from` bridging).\n */\nfunction inferValueFromString(value: string): SemanticValue {\n if (DEFAULT_REFERENCES.has(value)) return createReference(value);\n const kind = inferSelectorKind(value);\n if (kind) return createSelector(value, kind);\n return createLiteral(value);\n}\n\n/**\n * Bridge InterchangeNode EventModifiers to SemanticNode EventModifiers.\n */\nfunction bridgeEventModifiers(mods: Record<string, unknown>): SemanticEventModifiers | undefined {\n const once = mods.once === true ? true : undefined;\n const debounce = typeof mods.debounce === 'number' ? mods.debounce : undefined;\n const throttle = typeof mods.throttle === 'number' ? mods.throttle : undefined;\n const from = typeof mods.from === 'string' ? inferValueFromString(mods.from) : undefined;\n\n if (\n once === undefined &&\n debounce === undefined &&\n throttle === undefined &&\n from === undefined\n ) {\n return undefined;\n }\n\n return {\n ...(once !== undefined ? { once } : {}),\n ...(debounce !== undefined ? { debounce } : {}),\n ...(throttle !== undefined ? { throttle } : {}),\n ...(from !== undefined ? { from } : {}),\n };\n}\n","/**\n * SemanticNode → Runtime AST Converter\n *\n * Converts framework SemanticNode (LSE IR) to a structural AST format\n * that the core runtime can execute directly. Uses structural typing\n * to avoid a dependency on the core package.\n *\n * This is the canonical converter — AOT compiler delegates to it.\n *\n * The output matches the core runtime's expected node shapes:\n * - `{ type: 'command', name, args, roles }` → processCommand()\n * - `{ type: 'event', event, modifiers, body }` → adapted to executeEventHandler()\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n EventHandlerSemanticNode,\n ConditionalSemanticNode,\n LoopSemanticNode,\n} from '../core/types';\n\n// =============================================================================\n// Structural output types (no core package dependency)\n// =============================================================================\n\n/** Minimal AST node that the core runtime can execute. */\nexport interface RuntimeASTNode {\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\n/** Command node shape expected by runtime's processCommand(). */\nexport interface RuntimeCommandNode extends RuntimeASTNode {\n readonly type: 'command';\n readonly name: string;\n readonly args: RuntimeASTNode[];\n readonly roles?: Readonly<Record<string, RuntimeASTNode>>;\n readonly modifiers?: Record<string, unknown>;\n}\n\n/** Event node shape expected by runtime's event adapter. */\nexport interface RuntimeEventNode extends RuntimeASTNode {\n readonly type: 'event';\n readonly event: string;\n readonly modifiers: Record<string, unknown>;\n readonly body: RuntimeASTNode[];\n}\n\n// =============================================================================\n// Converter\n// =============================================================================\n\n/**\n * Convert a SemanticNode to a RuntimeASTNode that the core runtime can execute.\n *\n * @example\n * ```typescript\n * import { parseExplicit } from '@lokascript/framework/ir';\n * import { semanticNodeToRuntimeAST } from '@lokascript/framework/ir';\n *\n * const node = parseExplicit('[toggle patient:.active]');\n * const ast = semanticNodeToRuntimeAST(node);\n * // { type: 'command', name: 'toggle', args: [{ type: 'selector', value: '.active' }], roles: { patient: ... } }\n * ```\n */\nexport function semanticNodeToRuntimeAST(node: SemanticNode): RuntimeASTNode {\n switch (node.kind) {\n case 'event-handler':\n return convertEventHandler(node as EventHandlerSemanticNode);\n\n case 'conditional':\n return convertConditional(node as ConditionalSemanticNode);\n\n case 'loop':\n return convertLoop(node as LoopSemanticNode);\n\n case 'compound': {\n const compound = node as SemanticNode & { statements?: SemanticNode[]; chainType?: string };\n const commands = (compound.statements ?? []).map(semanticNodeToRuntimeAST);\n return {\n type: 'CommandSequence',\n commands,\n };\n }\n\n case 'command':\n default:\n return convertCommand(node);\n }\n}\n\nfunction convertEventHandler(eh: EventHandlerSemanticNode): RuntimeEventNode {\n const eventValue = eh.roles.get('event');\n const eventName = eventValue && 'value' in eventValue ? String(eventValue.value) : 'click';\n\n const modifiers: Record<string, unknown> = {};\n if (eh.eventModifiers) {\n if (eh.eventModifiers.once) modifiers.once = true;\n if (eh.eventModifiers.debounce) modifiers.debounce = eh.eventModifiers.debounce;\n if (eh.eventModifiers.throttle) modifiers.throttle = eh.eventModifiers.throttle;\n if (eh.eventModifiers.queue) modifiers.queue = eh.eventModifiers.queue;\n }\n\n return {\n type: 'event',\n event: eventName,\n modifiers,\n body: (eh.body ?? []).map(semanticNodeToRuntimeAST),\n };\n}\n\nfunction convertCommand(node: SemanticNode): RuntimeCommandNode {\n const roles: Record<string, RuntimeASTNode> = {};\n const args: RuntimeASTNode[] = [];\n\n for (const [roleName, value] of node.roles) {\n const astValue = semanticValueToAST(value);\n roles[roleName] = astValue;\n args.push(astValue);\n }\n\n return {\n type: 'command',\n name: node.action,\n args,\n roles,\n };\n}\n\nfunction convertConditional(node: ConditionalSemanticNode): RuntimeASTNode {\n const conditionValue = node.roles.get('condition');\n return {\n type: 'command',\n name: 'if',\n args: conditionValue ? [semanticValueToAST(conditionValue)] : [],\n condition: conditionValue ? semanticValueToAST(conditionValue) : undefined,\n thenBranch: (node.thenBranch ?? []).map(semanticNodeToRuntimeAST),\n elseBranch: (node.elseBranch ?? []).map(semanticNodeToRuntimeAST),\n };\n}\n\nfunction convertLoop(node: LoopSemanticNode): RuntimeASTNode {\n const countValue = node.roles.get('patient') || node.roles.get('count');\n return {\n type: 'command',\n name: 'repeat',\n args: countValue ? [semanticValueToAST(countValue)] : [],\n loopVariant: node.loopVariant ?? 'forever',\n body: (node.body ?? []).map(semanticNodeToRuntimeAST),\n loopVariable: node.loopVariable,\n indexVariable: node.indexVariable,\n };\n}\n\n/**\n * Convert a SemanticValue to a RuntimeASTNode.\n */\nexport function semanticValueToAST(value: SemanticValue): RuntimeASTNode {\n switch (value.type) {\n case 'selector':\n return { type: 'selector', value: value.value as string };\n\n case 'reference':\n return { type: 'identifier', value: value.value as string };\n\n case 'literal': {\n const lit = value as { value: unknown; dataType?: string };\n if (lit.dataType === 'duration') {\n const str = String(lit.value);\n const match = /^(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(str);\n if (match) {\n const ms = match[2] === 's' ? parseFloat(match[1]) * 1000 : parseFloat(match[1]);\n return { type: 'literal', value: ms };\n }\n }\n return { type: 'literal', value: lit.value as string | number | boolean | null };\n }\n\n case 'property-path': {\n const pp = value as import('../core/types').PropertyPathValue;\n const objectAST = semanticValueToAST(pp.object);\n return {\n type: 'member',\n object: objectAST,\n property: pp.property,\n };\n }\n\n case 'expression': {\n const expr = value as { raw: string };\n return { type: 'expression', value: expr.raw };\n }\n\n case 'flag': {\n const flag = value as { name: string; enabled: boolean };\n return { type: 'literal', value: flag.enabled };\n }\n\n default:\n return { type: 'literal', value: String((value as { value?: unknown }).value ?? '') };\n }\n}\n","/**\n * Main API for creating multilingual DSLs\n */\n\nimport type { SemanticNode, LanguageTokenizer, LanguagePattern } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { PatternMatcher, type PatternMatcherProfile } from '../core/pattern-matching';\nimport { generatePattern, type PatternGenLanguageProfile } from '../generation/pattern-generator';\nimport { createDomainRenderer, type DomainRenderFn } from '../generation/renderer';\nimport { GrammarTransformer, type LanguageProfile as GrammarProfile } from '../grammar';\nimport {\n type Dictionary,\n type ProfileProvider,\n type ValueExtractor,\n InMemoryDictionary,\n InMemoryProfileProvider,\n} from '../interfaces';\nimport { isExplicitSyntax, parseExplicit } from '../ir';\nimport type { SchemaLookup } from '../ir';\n\n/**\n * Language configuration for a DSL.\n */\nexport interface LanguageConfig {\n /** ISO 639-1 language code */\n readonly code: string;\n /** English name of the language */\n readonly name: string;\n /** Native name of the language */\n readonly nativeName: string;\n /** Language tokenizer */\n readonly tokenizer: LanguageTokenizer;\n /** Language profile for pattern generation */\n readonly patternProfile: PatternGenLanguageProfile;\n /**\n * Language profile for grammar transformation.\n *\n * Optional everywhere: `translate()` primarily works parse→render through\n * the schema-driven renderer, which needs no grammar profile. Configure this\n * only to enable the whole-string GrammarTransformer FALLBACK for input the\n * pattern matcher cannot parse (or actions render() cannot cover).\n */\n readonly grammarProfile?: GrammarProfile;\n}\n\n/**\n * Code generator function that transforms semantic AST to target code.\n */\nexport interface CodeGenerator {\n generate(node: SemanticNode): string;\n}\n\n/**\n * Per-language vocabulary for a command added via {@link DomainExtension}.\n *\n * This is the same shape a language profile uses, narrowed to the parts a\n * single new command needs.\n */\nexport interface ExtensionVocabulary {\n /** The command's verb in this language. */\n readonly keyword: PatternGenLanguageProfile['keywords'][string];\n /**\n * Markers for roles this language does not already cover in its profile.\n * Usually unnecessary: role markers are shared across a domain's commands.\n */\n readonly roleMarkers?: PatternGenLanguageProfile['roleMarkers'];\n}\n\n/**\n * A command added to a DSL from outside the package that defines it.\n *\n * Supplying a schema plus one vocabulary entry per language is enough to parse,\n * render and translate the command in every one of them — word order, role\n * markers and keyword placement all follow from the schema and the language\n * profiles. `render` and `generate` are only needed when the command's surface\n * form or output cannot be derived.\n *\n * @example\n * ```typescript\n * const research: DomainExtension = {\n * schema: defineCommand({\n * action: 'research',\n * roles: [\n * defineRole({ role: 'patient', required: true, expectedTypes: ['expression'] }),\n * defineRole({\n * role: 'source', required: true, expectedTypes: ['expression'],\n * markerOverride: { en: 'from', ja: 'から', ar: 'من' },\n * }),\n * ],\n * }),\n * vocabulary: {\n * en: { keyword: { primary: 'research' } },\n * ja: { keyword: { primary: '調査' } },\n * ar: { keyword: { primary: 'ابحث' } },\n * },\n * };\n *\n * const llm = createLLMDSL({ extensions: [research] });\n * llm.parse('research \"climate\" from #wiki', 'en');\n * llm.render(node, 'ja'); // → '\"climate\" #wiki から 調査'\n * ```\n */\nexport interface DomainExtension {\n /** Schema for the new command. Its action must not collide with an existing one. */\n readonly schema: CommandSchema;\n\n /**\n * Vocabulary per language code. Codes must be configured on the DSL; an\n * unknown code is a configuration error, not a silent no-op.\n *\n * A subset is allowed — a command can be added in six of a DSL's eleven\n * languages. The languages left out simply do not parse it, so vocabulary\n * can be filled in over time rather than all at once.\n */\n readonly vocabulary: Readonly<Record<string, ExtensionVocabulary>>;\n\n /** Custom rendering for this action; takes precedence over the schema-driven path. */\n readonly render?: DomainRenderFn;\n\n /** Custom code generation for this action; takes precedence over the DSL's generator. */\n readonly generate?: (node: SemanticNode) => string;\n}\n\n/**\n * DSL configuration with dependency injection support.\n */\nexport interface DSLConfig {\n /** DSL name (for debugging/documentation) */\n readonly name?: string;\n\n /** Command schemas defining the DSL grammar */\n readonly schemas: readonly CommandSchema[];\n\n /** Language configurations */\n readonly languages: readonly LanguageConfig[];\n\n // === Dependency Injection (Optional) ===\n\n /** Dictionary for keyword translation (default: built from language configs) */\n readonly dictionary?: Dictionary;\n\n /** Profile provider for grammar transformation (default: built from language configs) */\n readonly profileProvider?: ProfileProvider;\n\n /** Value extractors for tokenization (default: generic extractors) */\n readonly valueExtractors?: ValueExtractor[];\n\n /** Code generator for compilation (default: none) */\n readonly codeGenerator?: CodeGenerator;\n\n /**\n * The domain's natural-language renderer, consulted by {@link MultilingualDSL.render}.\n * Actions it returns `null` for fall through to the schema-driven renderer.\n */\n readonly renderer?: DomainRenderFn;\n\n /**\n * Commands added from outside this package. Their schemas and vocabulary are\n * merged into the DSL before pattern generation, so they parse, render and\n * compile like built-in commands.\n */\n readonly extensions?: readonly DomainExtension[];\n\n // === Options ===\n\n /** Auto-generate patterns from schemas (default: true) */\n readonly generatePatterns?: boolean;\n\n /** Custom patterns to supplement generated ones */\n readonly customPatterns?: LanguagePattern[];\n}\n\n/**\n * Validation result.\n */\nexport interface ValidationResult {\n readonly valid: boolean;\n readonly node?: SemanticNode;\n readonly errors?: string[];\n}\n\n/**\n * Compilation result.\n */\nexport interface CompileResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly errors?: string[];\n readonly node?: SemanticNode;\n readonly metadata?: {\n readonly parser: string;\n readonly confidence: number;\n };\n}\n\n/**\n * Main multilingual DSL interface.\n */\nexport interface MultilingualDSL {\n // Parsing\n parse(input: string, language: string): SemanticNode;\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number };\n\n // Validation\n validate(input: string, language: string): ValidationResult;\n\n // Compilation\n compile(input: string, language: string): CompileResult;\n\n // Translation\n translate(input: string, fromLanguage: string, toLanguage: string): string;\n\n /**\n * Render a parsed node back to natural language.\n *\n * Returns `null` when the action cannot be rendered — no custom renderer, no\n * domain renderer, and no schema. Optional so that third-party implementers\n * of this interface are not broken by its addition; `createMultilingualDSL`\n * always provides it.\n */\n render?(node: SemanticNode, language: string): string | null;\n\n // Language support\n getSupportedLanguages(): string[];\n}\n\n/**\n * Internal registry for DSL configuration.\n */\nclass DSLRegistry {\n private patterns = new Map<string, LanguagePattern[]>();\n private tokenizers = new Map<string, LanguageTokenizer>();\n private schemas: readonly CommandSchema[];\n private partiallyTranslatedActions: ReadonlySet<string>;\n\n /**\n * @param partiallyTranslatedActions Actions permitted to lack a keyword in\n * some configured languages — extension commands, which may be added for a\n * subset of the DSL's languages. A built-in command missing a keyword stays\n * an error, since that is a domain-authoring mistake.\n */\n constructor(config: DSLConfig, partiallyTranslatedActions: ReadonlySet<string> = new Set()) {\n this.schemas = config.schemas;\n this.partiallyTranslatedActions = partiallyTranslatedActions;\n\n // Register each language\n for (const lang of config.languages) {\n this.registerLanguage(lang);\n }\n }\n\n private registerLanguage(lang: LanguageConfig): void {\n // Register tokenizer\n this.tokenizers.set(lang.code, lang.tokenizer);\n\n // Generate patterns for this language\n const patterns: LanguagePattern[] = [];\n for (const schema of this.schemas) {\n if (\n this.partiallyTranslatedActions.has(schema.action) &&\n !lang.patternProfile.keywords[schema.action]\n ) {\n continue; // this extension command was not translated into this language\n }\n const pattern = generatePattern(schema, lang.patternProfile);\n patterns.push(pattern);\n }\n\n this.patterns.set(lang.code, patterns);\n }\n\n getPatterns(language: string): LanguagePattern[] {\n return this.patterns.get(language) || [];\n }\n\n getTokenizer(language: string): LanguageTokenizer | undefined {\n return this.tokenizers.get(language);\n }\n\n getSupportedLanguages(): string[] {\n return Array.from(this.patterns.keys());\n }\n}\n\n/**\n * Implementation of MultilingualDSL.\n */\nclass MultilingualDSLImpl implements MultilingualDSL {\n private registry: DSLRegistry;\n private matcher: PatternMatcher;\n private transformer: GrammarTransformer;\n private profileProvider: ProfileProvider;\n private codeGenerator?: CodeGenerator;\n private schemaLookup: SchemaLookup;\n private domainRenderer?: DomainRenderFn;\n private extensionRenderers: Map<string, DomainRenderFn>;\n private schemaFallbackRenderer: DomainRenderFn;\n\n constructor(\n config: DSLConfig,\n registry: DSLRegistry,\n transformer: GrammarTransformer,\n profileProvider: ProfileProvider\n ) {\n this.registry = registry;\n this.matcher = new PatternMatcher();\n this.transformer = transformer;\n this.profileProvider = profileProvider;\n if (config.codeGenerator) {\n this.codeGenerator = config.codeGenerator;\n }\n if (config.renderer) {\n this.domainRenderer = config.renderer;\n }\n\n this.extensionRenderers = new Map();\n for (const extension of config.extensions ?? []) {\n if (extension.render) this.extensionRenderers.set(extension.schema.action, extension.render);\n }\n\n // Last resort for render(): covers extension commands with no custom\n // renderer, and any built-in action the domain renderer declines. Lazy, so\n // a DSL that never renders pays nothing.\n this.schemaFallbackRenderer = createDomainRenderer({\n schemas: config.schemas,\n profiles: config.languages.map(l => l.patternProfile),\n });\n\n // Build SchemaLookup from config schemas for explicit syntax validation\n const schemaMap = new Map(config.schemas.map(s => [s.action, s]));\n this.schemaLookup = {\n getSchema: (action: string) => schemaMap.get(action),\n };\n }\n\n parse(input: string, language: string): SemanticNode {\n const result = this.parseWithConfidence(input, language);\n return result.node;\n }\n\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number } {\n // Try explicit bracket syntax first (language-agnostic)\n if (isExplicitSyntax(input)) {\n const node = parseExplicit(input, { schemaLookup: this.schemaLookup });\n // Only match if this DSL has a schema for the action\n if (!this.schemaLookup.getSchema(node.action)) {\n throw new Error(`No schema for action \"${node.action}\" in this DSL`);\n }\n return { node, confidence: 1.0 };\n }\n\n // Get tokenizer for language\n const tokenizer = this.registry.getTokenizer(language);\n if (!tokenizer) {\n throw new Error(`No tokenizer registered for language: ${language}`);\n }\n\n // Tokenize input\n const tokens = tokenizer.tokenize(input);\n\n // Get patterns for language\n const patterns = this.registry.getPatterns(language);\n\n // Create profile for matcher\n const profile: PatternMatcherProfile = {\n code: language,\n };\n\n // Try to match each pattern\n for (const pattern of patterns) {\n const match = this.matcher.matchPattern(tokens, pattern, profile);\n if (match) {\n // Build semantic node\n const node: SemanticNode = {\n kind: 'command',\n action: pattern.command,\n roles: match.captured,\n metadata: {\n sourceLanguage: language,\n sourceText: input,\n patternId: pattern.id,\n confidence: match.confidence,\n },\n };\n\n return { node, confidence: match.confidence };\n }\n }\n\n throw new Error(`No pattern matched for input: ${input}`);\n }\n\n validate(input: string, language: string): ValidationResult {\n try {\n const result = this.parseWithConfidence(input, language);\n return {\n valid: true,\n node: result.node,\n };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n translate(input: string, fromLanguage: string, toLanguage: string): string {\n // Explicit syntax is language-agnostic — return unchanged\n if (isExplicitSyntax(input)) return input;\n\n // Primary route: parse in the source language, render in the target — the\n // same parse→render path DomainRegistry.translate uses. The schema-driven\n // renderer covers every configured language, so this needs NO grammar\n // profiles (before 2026-08 translate() required them and therefore threw\n // for every domain in the family — none configures one).\n let node: SemanticNode;\n try {\n node = this.parseWithConfidence(input, fromLanguage).node;\n } catch (parseError) {\n // Whole-string grammar transformation can sometimes translate input the\n // pattern matcher cannot parse — but only when profiles are configured.\n if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n throw parseError;\n }\n\n // Only consult render() for a CONFIGURED target language — the schema\n // renderer's lookup tables fall back to raw action/marker names for\n // unknown languages, which would silently return wrong-language output.\n const rendered = this.registry.getSupportedLanguages().includes(toLanguage)\n ? this.render(node, toLanguage)\n : null;\n if (rendered != null) return rendered;\n\n // render() covered nothing for this action/language pair; fall back to the\n // grammar transformer when profiles exist, otherwise name both remedies.\n if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n throw new Error(\n `translate() could not render action \"${node.action}\" in language \"${toLanguage}\": no ` +\n `custom renderer, domain renderer, or schema pattern covers it, and no grammar ` +\n `profile is configured for the transformer fallback. Either add \"${toLanguage}\" to ` +\n `the DSL's languages/renderer, or set 'grammarProfile' on its LanguageConfig in ` +\n `createMultilingualDSL() (parse/validate/compile do not need it).`\n );\n }\n\n private hasGrammarProfile(language: string): boolean {\n return this.profileProvider.getProfile(language) != null;\n }\n\n compile(input: string, language: string): CompileResult {\n if (!this.codeGenerator) {\n return {\n ok: false,\n errors: ['No code generator configured for this DSL'],\n };\n }\n\n try {\n const result = this.parseWithConfidence(input, language);\n const code = this.codeGenerator.generate(result.node);\n\n return {\n ok: true,\n code,\n node: result.node,\n metadata: {\n parser: 'semantic',\n confidence: result.confidence,\n },\n };\n } catch (error) {\n return {\n ok: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n render(node: SemanticNode, language: string): string | null {\n // 1. An extension's own renderer, if it supplied one\n const extensionRenderer = this.extensionRenderers.get(node.action);\n if (extensionRenderer) {\n const rendered = extensionRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 2. The domain's renderer — its hand-written cases are authoritative\n if (this.domainRenderer) {\n const rendered = this.domainRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 3. Schema-driven, which is how extension commands render by default\n return this.schemaFallbackRenderer(node, language);\n }\n\n getSupportedLanguages(): string[] {\n return this.registry.getSupportedLanguages();\n }\n}\n\n/**\n * Create a new multilingual DSL instance.\n *\n * @param config - DSL configuration\n * @returns MultilingualDSL instance\n *\n * @example\n * ```typescript\n * const myDSL = createMultilingualDSL({\n * schemas: [\n * defineCommand('select', [\n * defineRole('field', 'identifier', true),\n * defineRole('source', 'identifier', true),\n * ]),\n * ],\n * languages: [\n * {\n * code: 'en',\n * name: 'English',\n * nativeName: 'English',\n * tokenizer: englishTokenizer,\n * patternProfile: englishProfile,\n * },\n * ],\n * codeGenerator: {\n * generate: (node) => generateSQL(node),\n * },\n * });\n *\n * const result = myDSL.compile('select name from users', 'en');\n * ```\n */\n/**\n * Create default dictionary from language configurations.\n */\nfunction createDefaultDictionary(config: DSLConfig): Dictionary {\n const translations: Record<string, Record<string, string>> = {};\n\n for (const lang of config.languages) {\n // Convert keyword objects to simple string mappings\n const keywords: Record<string, string> = {};\n for (const [canonical, keywordDef] of Object.entries(lang.patternProfile.keywords)) {\n keywords[canonical] = keywordDef.primary;\n }\n translations[lang.code] = keywords;\n }\n\n return new InMemoryDictionary(translations);\n}\n\n/**\n * Create default profile provider from language configurations.\n */\nfunction createDefaultProfileProvider(config: DSLConfig): ProfileProvider {\n const profiles: Record<string, GrammarProfile> = {};\n\n for (const lang of config.languages) {\n if (lang.grammarProfile) {\n profiles[lang.code] = lang.grammarProfile;\n }\n }\n\n return new InMemoryProfileProvider(profiles);\n}\n\n/**\n * Fold extensions into the config so that everything downstream — pattern\n * generation, the dictionary, explicit-syntax lookup, rendering — sees\n * extension commands exactly as it sees built-in ones.\n *\n * Done up front rather than by mutating a live DSL: `DSLRegistry` generates\n * every language's patterns in its constructor, so a command registered later\n * would compile and render but silently fail to parse.\n */\nfunction applyExtensions(config: DSLConfig): DSLConfig {\n const extensions = config.extensions;\n if (!extensions || extensions.length === 0) return config;\n\n const configuredLanguages = new Set(config.languages.map(l => l.code));\n const actions = new Set(config.schemas.map(s => s.action));\n\n for (const extension of extensions) {\n const { action } = extension.schema;\n if (actions.has(action)) {\n throw new Error(\n `Extension command \"${action}\" collides with a command this DSL already defines. ` +\n `Pick a different action name.`\n );\n }\n actions.add(action);\n\n for (const code of Object.keys(extension.vocabulary)) {\n if (!configuredLanguages.has(code)) {\n throw new Error(\n `Extension command \"${action}\" supplies vocabulary for language \"${code}\", which is ` +\n `not configured on this DSL. Configured languages: ` +\n `${[...configuredLanguages].join(', ')}.`\n );\n }\n }\n }\n\n const schemas = [...config.schemas, ...extensions.map(e => e.schema)];\n\n const languages = config.languages.map(lang => {\n const keywords = { ...lang.patternProfile.keywords };\n let roleMarkers = lang.patternProfile.roleMarkers;\n\n for (const extension of extensions) {\n const vocabulary = extension.vocabulary[lang.code];\n if (!vocabulary) continue;\n keywords[extension.schema.action] = { ...vocabulary.keyword };\n if (vocabulary.roleMarkers) {\n roleMarkers = { ...roleMarkers, ...vocabulary.roleMarkers };\n }\n }\n\n return {\n ...lang,\n patternProfile: {\n ...lang.patternProfile,\n keywords,\n ...(roleMarkers !== undefined && { roleMarkers }),\n },\n };\n });\n\n // Extension code generators dispatch ahead of the domain's own generator,\n // whose `default` branch would otherwise throw on an action it never knew.\n const extensionGenerators = new Map(\n extensions.filter(e => e.generate).map(e => [e.schema.action, e.generate!])\n );\n const baseGenerator = config.codeGenerator;\n const codeGenerator: CodeGenerator | undefined =\n extensionGenerators.size > 0\n ? {\n generate(node: SemanticNode): string {\n const generate = extensionGenerators.get(node.action);\n if (generate) return generate(node);\n if (!baseGenerator) {\n throw new Error(`No code generator for action \"${node.action}\"`);\n }\n return baseGenerator.generate(node);\n },\n }\n : baseGenerator;\n\n return {\n ...config,\n schemas,\n languages,\n ...(codeGenerator !== undefined && { codeGenerator }),\n };\n}\n\nexport function createMultilingualDSL(config: DSLConfig): MultilingualDSL {\n // Extensions must be folded in before anything reads the config\n const effectiveConfig = applyExtensions(config);\n const extensionActions = new Set((config.extensions ?? []).map(e => e.schema.action));\n\n // Create or use provided dictionary\n const dictionary = effectiveConfig.dictionary ?? createDefaultDictionary(effectiveConfig);\n\n // Create or use provided profile provider\n const profileProvider =\n effectiveConfig.profileProvider ?? createDefaultProfileProvider(effectiveConfig);\n\n // Create grammar transformer with injected dependencies\n const transformer = new GrammarTransformer({\n dictionary,\n profileProvider,\n });\n\n // Create registry and implementation\n const registry = new DSLRegistry(effectiveConfig, extensionActions);\n return new MultilingualDSLImpl(effectiveConfig, registry, transformer, profileProvider);\n}\n","/**\n * LLM Prompt Generator\n *\n * Auto-generates LLM system prompts from CommandSchema[]. Given a set of\n * domain schemas, produces a structured markdown prompt that teaches LLMs\n * to output valid LSE bracket syntax and/or LLM-simplified JSON.\n *\n * The generated prompt includes:\n * - Protocol overview (LSE syntax summary)\n * - Value type reference\n * - Per-command documentation with role descriptions\n * - Synthetic examples in both formats\n * - Output format specification\n * - Error recovery instructions\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type {\n PromptGeneratorConfig,\n GeneratedPrompt,\n PromptSection,\n PromptMetadata,\n} from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Generate an LLM system prompt from domain command schemas.\n *\n * @example\n * ```typescript\n * import { generatePrompt } from '@lokascript/framework';\n * import { allSchemas } from '@lokascript/domain-flow';\n *\n * const prompt = generatePrompt({\n * domain: 'flow',\n * description: 'Reactive data flow pipelines',\n * schemas: allSchemas,\n * });\n *\n * console.log(prompt.text); // Full markdown system prompt\n * ```\n */\nexport function generatePrompt(config: PromptGeneratorConfig): GeneratedPrompt {\n const outputFormat = config.outputFormat ?? 'both';\n const examplesPerCommand = config.examplesPerCommand ?? 2;\n\n const sections: PromptSection[] = [\n buildProtocolSection(),\n buildValueTypeSection(),\n buildCommandsSection(config.schemas, outputFormat, examplesPerCommand),\n buildOutputFormatSection(outputFormat),\n buildErrorRecoverySection(),\n ];\n\n // Apply token budget if specified\n let finalSections = sections;\n if (config.maxTokens && config.maxTokens > 0) {\n finalSections = truncateToTokenBudget(sections, config.maxTokens);\n }\n\n const text = finalSections.map(s => `## ${s.title}\\n\\n${s.content}`).join('\\n\\n---\\n\\n');\n\n const totalRoles = config.schemas.reduce((sum, s) => sum + s.roles.length, 0);\n const approximateTokens = estimateTokens(text);\n\n const metadata: PromptMetadata = {\n domain: config.domain,\n commandCount: config.schemas.length,\n roleCount: totalRoles,\n approximateTokens,\n };\n\n return { text, sections: finalSections, metadata };\n}\n\n/**\n * Generate synthetic LSE examples from a single command schema.\n * Used by both the prompt generator and training data synthesizer.\n */\nexport function generateExamples(\n schema: CommandSchema,\n count: number = 2\n): Array<{ explicit: string; json: SemanticJSON }> {\n const combos = generateRoleCombinations(schema);\n const examples: Array<{ explicit: string; json: SemanticJSON }> = [];\n\n for (let i = 0; i < Math.min(count, combos.length); i++) {\n const combo = combos[i];\n const roles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of combo) {\n const sample = sampleValue(role);\n roles.set(role.role, sample);\n }\n\n // Build SemanticNode for rendering to bracket syntax\n const nodeRoles = new Map<\n string,\n {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n }\n >();\n for (const [roleName, sample] of roles) {\n nodeRoles.set(roleName, toSemanticValue(sample));\n }\n\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [roleName, sample] of roles) {\n jsonRoles[roleName] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n examples.push({ explicit, json });\n }\n\n return examples;\n}\n\n/**\n * Generate a condensed LSE protocol reference (for MCP resources).\n */\nexport function generateProtocolReference(): string {\n const protocol = buildProtocolSection();\n const valueTypes = buildValueTypeSection();\n return `# LokaScript Explicit Syntax (LSE) Quick Reference\\n\\n${protocol.content}\\n\\n${valueTypes.content}`;\n}\n\n// =============================================================================\n// Section Builders\n// =============================================================================\n\nfunction buildProtocolSection(): PromptSection {\n const content = `LokaScript Explicit Syntax (LSE) is a bracket-based format for imperative commands.\n\n### Syntax\n\n\\`\\`\\`\n[command role1:value1 role2:value2 +flag1 ~flag2]\n\\`\\`\\`\n\n- **Command**: The first token inside brackets (lowercased)\n- **Role pair**: \\`name:value\\` — a named semantic role with a typed value (no space around colon)\n- **Enabled flag**: \\`+name\\` — boolean attribute present\n- **Disabled flag**: \\`~name\\` — boolean attribute negated\n- **Nested body**: \\`body:[command ...]\\` — a bracket command inside a role value\n\n### Rules\n\n1. Commands are always lowercased\n2. Role names preserve their original case\n3. No spaces around the colon in role:value pairs\n4. Strings with spaces must be quoted: \\`patient:\"hello world\"\\`\n5. Selectors start with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`\n6. A selector containing a space, a combinator (\\`>\\` \\`+\\` \\`~\\`), or a comma must use a selector literal: \\`patient:<ul > li/>\\`, \\`patient:<.a, .b/>\\`\n7. Inside a structural role (\\`body\\`, \\`then\\`, \\`else\\`, \\`condition\\`, \\`loop-body\\`, \\`variable\\`, \\`catch\\`, \\`finally\\`) a \\`[...]\\` value is always a nested command. Write an attribute selector there as \\`condition:<[data-active]/>\\`\n8. Output must be valid bracket syntax: \\`[action role:value ...]\\``;\n\n return {\n id: 'protocol',\n title: 'LSE Protocol',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildValueTypeSection(): PromptSection {\n const content = `Values in LSE are classified by their syntactic form (first match wins):\n\n| Type | Syntax | Example |\n|------|--------|---------|\n| Selector literal | Delimited by \\`<\\` and \\`/>\\` | \\`<ul > li/>\\`, \\`<.a, .b/>\\`, \\`<[data-id]/>\\` |\n| Selector | Starts with \\`#\\` \\`.\\` \\`[\\` \\`@\\` \\`*\\` | \\`#button\\`, \\`.active\\`, \\`[data-id]\\` |\n| String | Quoted with \\`\"\\` or \\`'\\` | \\`\"hello world\"\\`, \\`'json'\\` |\n| Boolean | Exact: \\`true\\` / \\`false\\` | \\`visible:true\\` |\n| Reference | Built-in name | \\`me\\`, \\`you\\`, \\`it\\`, \\`result\\`, \\`event\\`, \\`target\\`, \\`body\\` |\n| Duration | Number + suffix | \\`500ms\\`, \\`2s\\`, \\`1m\\`, \\`1h\\` |\n| Number | Digits with optional decimal | \\`5\\`, \\`3.14\\`, \\`-1\\` |\n| Plain | Fallback (any non-whitespace) | \\`/api/users\\`, \\`json\\`, \\`production\\` |\n\n**Important**: Classification is by prefix, not by intent. \\`#true\\` is a selector (not boolean). \\`event\\` as a value is a reference (not plain text).`;\n\n return {\n id: 'value-types',\n title: 'Value Types',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildCommandsSection(\n schemas: readonly CommandSchema[],\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): PromptSection {\n const parts: string[] = [];\n\n for (const schema of schemas) {\n parts.push(formatCommandDoc(schema, outputFormat, examplesPerCommand));\n }\n\n const content = parts.join('\\n\\n');\n\n return {\n id: 'commands',\n title: 'Available Commands',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildOutputFormatSection(outputFormat: 'explicit' | 'json' | 'both'): PromptSection {\n let content: string;\n\n if (outputFormat === 'explicit') {\n content = `Output valid LSE bracket syntax. Each command must be wrapped in brackets:\n\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\nDo NOT output JSON. Only use bracket syntax.`;\n } else if (outputFormat === 'json') {\n content = `Output valid JSON in the LLM-simplified format:\n\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nValid value types: \\`selector\\`, \\`literal\\`, \\`reference\\`, \\`expression\\`.\nDo NOT output bracket syntax. Only use JSON.`;\n } else {\n content = `You may output EITHER format:\n\n**Bracket syntax** (preferred for single commands):\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\n**JSON format** (preferred when structured data is needed):\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nBoth formats are equally valid. Use whichever is more natural for the context.`;\n }\n\n return {\n id: 'output-format',\n title: 'Output Format',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildErrorRecoverySection(): PromptSection {\n const content = `If you're unsure about a command or role:\n\n1. **Unknown command**: Use the closest matching command from the Available Commands section. Do not invent commands.\n2. **Unknown role**: Use only the roles listed for each command. Do not add roles not in the schema.\n3. **Ambiguous value type**: When in doubt, use \\`expression\\` type (it's the most permissive).\n4. **Missing required role**: Always include all required roles. Check the Required/Optional labels.\n5. **Selector vs plain value**: If a value starts with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`, it's a selector. URLs like \\`/api/data\\` are plain values.\n\nWhen generating LSE, prefer explicit role labeling over positional guessing. Every value should have a role name.`;\n\n return {\n id: 'error-recovery',\n title: 'Error Recovery',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\n// =============================================================================\n// Command Documentation\n// =============================================================================\n\nfunction formatCommandDoc(\n schema: CommandSchema,\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): string {\n const lines: string[] = [];\n\n // Header\n lines.push(`### \\`${schema.action}\\` — ${schema.description}`);\n lines.push('');\n\n // Roles\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n if (required.length > 0) {\n lines.push('**Required roles:**');\n for (const role of required) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n if (optional.length > 0) {\n lines.push('**Optional roles:**');\n for (const role of optional) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n // Examples\n const examples = generateExamples(schema, examplesPerCommand);\n if (examples.length > 0) {\n lines.push('');\n if (outputFormat === 'explicit' || outputFormat === 'both') {\n lines.push('**Bracket syntax:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`\\n${ex.explicit}\\n\\`\\`\\``);\n }\n }\n if (outputFormat === 'json' || outputFormat === 'both') {\n lines.push('**JSON format:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`json\\n${JSON.stringify(ex.json, null, 2)}\\n\\`\\`\\``);\n }\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatExpectedTypes(role: RoleSpec): string {\n return role.expectedTypes.join(' | ');\n}\n\n// =============================================================================\n// Example Generation Helpers\n// =============================================================================\n\n/**\n * Generate role combinations for example synthesis.\n * Returns arrays of RoleSpec[] representing different valid input combinations:\n * 1. Required roles only\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (if different from #1 and #2)\n */\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if there are 2+ optional roles)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if schema has no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n/**\n * Sample a value for a role based on its expected types and name.\n */\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n // Use role name as a heuristic for realistic values\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\n/**\n * Convert a sampled value into a SemanticValue for renderExplicit().\n */\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n\n// =============================================================================\n// Token Budget\n// =============================================================================\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction truncateToTokenBudget(sections: PromptSection[], maxTokens: number): PromptSection[] {\n const result: PromptSection[] = [];\n let budget = maxTokens;\n\n for (const section of sections) {\n if (section.approximateTokens <= budget) {\n result.push(section);\n budget -= section.approximateTokens;\n } else {\n // Truncate the section to fit remaining budget (always include at least something)\n const charBudget = Math.max(budget * 4, 40);\n const truncatedContent = section.content.slice(0, charBudget) + '\\n\\n*(truncated)*';\n result.push({\n ...section,\n content: truncatedContent,\n approximateTokens: estimateTokens(truncatedContent),\n });\n break;\n }\n }\n\n return result;\n}\n","/**\n * Schema Synthesizer\n *\n * Generates synthetic (natural_language, LSE) training pairs from\n * CommandSchema[]. Enumerates valid role combinations and produces\n * examples in both bracket syntax and JSON wire format.\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { TrainingPair, SynthesisConfig, SynthesisResult, SynthesisMetadata } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Synthesize training pairs from command schemas.\n *\n * Generates multiple examples per command by enumerating role combinations:\n * 1. Required roles only (minimum viable)\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (maximum)\n * 4. Shuffled role order variants (teaches role-label independence)\n */\nexport function synthesizeFromSchemas(\n schemas: readonly CommandSchema[],\n config: SynthesisConfig\n): SynthesisResult {\n const maxPerCommand = config.maxPairsPerCommand ?? 5;\n const minQuality = config.minQuality ?? 0.5;\n const shuffleRoles = config.shuffleRoles ?? true;\n const languages = config.languages ?? ['en'];\n\n const pairs: TrainingPair[] = [];\n let idCounter = 0;\n\n for (const schema of schemas) {\n const combos = generateRoleCombinations(schema);\n\n for (const language of languages) {\n let commandPairCount = 0;\n\n for (const combo of combos) {\n if (commandPairCount >= maxPerCommand) break;\n\n const pair = buildTrainingPair(\n schema,\n combo,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n\n if (pair.quality >= minQuality) {\n pairs.push(pair);\n commandPairCount++;\n }\n\n // Generate shuffled variant\n if (shuffleRoles && combo.length >= 2 && commandPairCount < maxPerCommand) {\n const shuffled = [...combo].reverse();\n const shuffledPair = buildTrainingPair(\n schema,\n shuffled,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n if (shuffledPair.quality >= minQuality) {\n pairs.push(shuffledPair);\n commandPairCount++;\n }\n }\n }\n }\n }\n\n const metadata: SynthesisMetadata = {\n domain: config.domain,\n commandCount: schemas.length,\n pairCount: pairs.length,\n bySource: { synthetic: pairs.length },\n languages,\n };\n\n return { pairs, metadata };\n}\n\n// =============================================================================\n// Role Combination Generation\n// =============================================================================\n\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if 2+ optional)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n// =============================================================================\n// Pair Building\n// =============================================================================\n\nfunction buildTrainingPair(\n schema: CommandSchema,\n roles: RoleSpec[],\n language: string,\n domain: string,\n id: string\n): TrainingPair {\n const sampledRoles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of roles) {\n sampledRoles.set(role.role, sampleValue(role));\n }\n\n // Build SemanticNode for bracket syntax\n const nodeRoles = new Map<string, unknown>();\n for (const [name, sample] of sampledRoles) {\n nodeRoles.set(name, toSemanticValue(sample));\n }\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [name, sample] of sampledRoles) {\n jsonRoles[name] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n // Build natural language form\n const natural = buildNaturalForm(schema, sampledRoles, language);\n\n // Quality: synthetic pairs get a base quality, higher if more roles are filled\n const requiredCount = schema.roles.filter(r => r.required).length;\n const filledRequired = roles.filter(r => r.required).length;\n const quality = requiredCount > 0 ? filledRequired / requiredCount : 0.8;\n\n return {\n id,\n natural,\n language,\n explicit,\n json,\n domain,\n action: schema.action,\n source: 'synthetic',\n quality,\n };\n}\n\n/**\n * Build a natural language form from sampled roles.\n * Uses marker overrides for the given language when available.\n */\nfunction buildNaturalForm(\n schema: CommandSchema,\n roles: Map<string, { type: string; value: string | number | boolean }>,\n language: string\n): string {\n const parts: string[] = [schema.action];\n\n for (const roleSpec of schema.roles) {\n const sample = roles.get(roleSpec.role);\n if (!sample) continue;\n\n const marker = roleSpec.markerOverride?.[language];\n if (marker) {\n parts.push(marker);\n }\n parts.push(String(sample.value));\n }\n\n return parts.join(' ');\n}\n\n// =============================================================================\n// Value Sampling\n// =============================================================================\n\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n","/**\n * Feedback Formatter\n *\n * Maps diagnostics to machine-actionable LSEFeedback with hints,\n * corrected examples, and schema context. Enables LLMs to self-correct\n * based on structured error information.\n */\n\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup, SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { LSEFeedback, FeedbackDiagnostic, FixType } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Build structured feedback from diagnostics and optional schema context.\n *\n * @param input - The original input text\n * @param inputFormat - Format of the input\n * @param diagnostics - Error diagnostics from validation/parsing\n * @param schemaLookup - Optional schema lookup for generating hints and corrections\n * @param action - The attempted command action (if identifiable)\n */\nexport function buildFeedback(\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): LSEFeedback {\n const hasErrors = diagnostics.some(d => d.severity === 'error');\n const feedbackDiagnostics = diagnostics.map(d => toFeedbackDiagnostic(d));\n const hints = generateHints(feedbackDiagnostics, schemaLookup, action);\n\n let schemaInfo: LSEFeedback['schema'] | undefined;\n let correctedExample: LSEFeedback['correctedExample'] | undefined;\n\n if (action && schemaLookup) {\n const schema = schemaLookup.getSchema(action);\n if (schema) {\n schemaInfo = extractSchemaInfo(schema);\n if (hasErrors) {\n correctedExample = generateCorrectedExample(schema);\n }\n }\n }\n\n return {\n accepted: !hasErrors,\n input: { format: inputFormat, text: input },\n diagnostics: feedbackDiagnostics,\n hints,\n ...(schemaInfo && { schema: schemaInfo }),\n ...(correctedExample && { correctedExample }),\n };\n}\n\n// =============================================================================\n// Diagnostic Classification\n// =============================================================================\n\n/**\n * Map a framework Diagnostic to a FeedbackDiagnostic with fix type.\n */\nfunction toFeedbackDiagnostic(d: Diagnostic): FeedbackDiagnostic {\n const fixType = classifyFixType(d);\n return {\n severity: d.severity,\n code: d.code || 'unknown',\n message: d.message,\n ...(d.suggestions?.[0] && { suggestion: d.suggestions[0] }),\n ...(fixType && { fixType }),\n };\n}\n\n/**\n * Classify a diagnostic into a machine-actionable fix type.\n */\nfunction classifyFixType(d: Diagnostic): FixType | undefined {\n const code = (d.code || '').toLowerCase();\n const msg = d.message.toLowerCase();\n\n // Missing required role\n if (\n code.includes('missing-role') ||\n code.includes('missing_role') ||\n msg.includes('required role') ||\n msg.includes('missing role')\n ) {\n return 'missing_role';\n }\n\n // Invalid value type\n if (\n code.includes('invalid-type') ||\n code.includes('invalid_type') ||\n code.includes('type-mismatch') ||\n msg.includes('invalid type') ||\n msg.includes('expected type')\n ) {\n return 'invalid_type';\n }\n\n // Unknown command\n if (\n code.includes('unknown-command') ||\n code.includes('unknown_command') ||\n msg.includes('unknown command') ||\n (msg.includes('not recognized') && msg.includes('command'))\n ) {\n return 'unknown_command';\n }\n\n // Unknown role\n if (\n code.includes('unknown-role') ||\n code.includes('unknown_role') ||\n msg.includes('unknown role') ||\n (msg.includes('not recognized') && msg.includes('role'))\n ) {\n return 'unknown_role';\n }\n\n // Syntax error (catch-all for parse errors)\n if (\n code.includes('parse') ||\n code.includes('syntax') ||\n msg.includes('syntax error') ||\n msg.includes('parse error') ||\n msg.includes('unexpected')\n ) {\n return 'syntax_error';\n }\n\n return undefined;\n}\n\n// =============================================================================\n// Hint Generation\n// =============================================================================\n\nfunction generateHints(\n diagnostics: readonly FeedbackDiagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): string[] {\n const hints: string[] = [];\n const schema = action && schemaLookup ? schemaLookup.getSchema(action) : undefined;\n\n for (const d of diagnostics) {\n if (d.severity !== 'error') continue;\n\n switch (d.fixType) {\n case 'missing_role': {\n if (schema) {\n const required = schema.roles\n .filter(r => r.required)\n .map(r => `'${r.role}' (${r.description}, type: ${r.expectedTypes.join('|')})`)\n .join(', ');\n hints.push(`Required roles for '${action}': ${required}`);\n } else {\n hints.push('Check that all required roles are present.');\n }\n break;\n }\n\n case 'unknown_command': {\n hints.push(\n `Command not recognized. Ensure you're using a valid command from the domain schema.`\n );\n break;\n }\n\n case 'unknown_role': {\n if (schema) {\n const validRoles = schema.roles.map(r => `'${r.role}'`).join(', ');\n hints.push(`Valid roles for '${action}': ${validRoles}`);\n } else {\n hints.push('Use only roles defined in the command schema.');\n }\n break;\n }\n\n case 'invalid_type': {\n hints.push(\n 'Check value types: selectors start with #.[@*, strings use quotes, numbers are plain digits.'\n );\n break;\n }\n\n case 'syntax_error': {\n hints.push('Ensure bracket syntax: [command role:value ...]. No spaces around the colon.');\n break;\n }\n\n default: {\n if (d.suggestion) {\n hints.push(d.suggestion);\n }\n }\n }\n }\n\n // Deduplicate\n return [...new Set(hints)];\n}\n\n// =============================================================================\n// Schema Info Extraction\n// =============================================================================\n\nfunction extractSchemaInfo(schema: CommandSchema): LSEFeedback['schema'] {\n const requiredRoles: string[] = [];\n const optionalRoles: string[] = [];\n const roleDescriptions: Record<string, string> = {};\n\n for (const role of schema.roles) {\n if (role.required) {\n requiredRoles.push(role.role);\n } else {\n optionalRoles.push(role.role);\n }\n roleDescriptions[role.role] = role.description;\n }\n\n return {\n action: schema.action,\n requiredRoles,\n optionalRoles,\n roleDescriptions,\n };\n}\n\n// =============================================================================\n// Corrected Example Generation\n// =============================================================================\n\nfunction generateCorrectedExample(schema: CommandSchema): { explicit: string; json: SemanticJSON } {\n const roles = new Map<string, unknown>();\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n\n for (const role of schema.roles) {\n if (!role.required) continue;\n const sample = sampleDefaultValue(role.role, role.expectedTypes[0] || 'expression');\n roles.set(role.role, toSemanticValue(sample));\n jsonRoles[role.role] = sample as SemanticJSONValue;\n }\n\n const node = createCommandNode(schema.action, roles as never);\n const explicit = renderExplicit(node);\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n return { explicit, json };\n}\n\nfunction sampleDefaultValue(\n roleName: string,\n expectedType: string\n): { type: string; value: string } {\n switch (expectedType) {\n case 'selector':\n return { type: 'selector', value: `#${roleName}` };\n case 'expression':\n return { type: 'expression', value: `<${roleName}-value>` };\n case 'literal':\n return { type: 'literal', value: `<${roleName}-value>` };\n case 'reference':\n return { type: 'reference', value: 'me' };\n default:\n return { type: 'expression', value: `<${roleName}-value>` };\n }\n}\n\nfunction toSemanticValue(sample: { type: string; value: string }): {\n type: string;\n value: string;\n raw?: string;\n selectorKind?: string;\n dataType?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return { type: 'selector', value: sample.value, selectorKind: 'id' };\n case 'expression':\n return { type: 'expression', value: sample.value, raw: sample.value };\n case 'literal':\n return { type: 'literal', value: sample.value, dataType: 'string' };\n case 'reference':\n return { type: 'reference', value: sample.value };\n default:\n return { type: 'literal', value: sample.value, dataType: 'string' };\n }\n}\n","/**\n * Domain Registry\n *\n * Provides auto-discovery and registration of framework domains for MCP servers.\n * Instead of hardcoding tool definitions and dispatch logic per domain, domains\n * export a `DomainDescriptor` and the registry generates everything automatically.\n *\n * @example\n * ```typescript\n * import { DomainRegistry } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n *\n * // Register domains (each provides a descriptor)\n * registry.register({\n * name: 'sql',\n * description: 'Natural language SQL',\n * languages: ['en', 'es', 'ja', 'ar'],\n * inputLabel: 'query',\n * inputDescription: 'SQL query in natural language',\n * getDSL: () => import('@lokascript/domain-sql').then(m => m.createSQLDSL()),\n * getRenderer: () => import('@lokascript/domain-sql').then(m => m.renderSQL),\n * });\n *\n * // Auto-generate MCP tool definitions\n * const tools = registry.getToolDefinitions();\n *\n * // Dispatch a tool call\n * const result = await registry.handleToolCall('parse_sql', { query: 'select name from users' });\n * ```\n */\n\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport type { NaturalLanguageRenderer, DomainRenderFn } from '../generation/renderer';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup } from '../ir/types';\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { GeneratedPrompt, PromptGeneratorConfig } from '../prompts/types';\nimport type { SynthesisConfig, SynthesisResult } from '../training/types';\nimport type { LSEFeedback } from '../feedback/types';\nimport { generatePrompt as _generatePrompt } from '../prompts/prompt-generator';\nimport { synthesizeFromSchemas as _synthesizeFromSchemas } from '../training/schema-synthesizer';\nimport { buildFeedback as _buildFeedback } from '../feedback/feedback-formatter';\nimport { parseExplicit as _parseExplicit } from '../ir/explicit-parser';\n\n// =============================================================================\n// Descriptor Interface\n// =============================================================================\n\n/**\n * Describes a domain for auto-registration in MCP servers.\n *\n * Domains provide this descriptor to the registry, which generates\n * tool definitions and handles dispatch automatically.\n */\nexport interface DomainDescriptor {\n /** Short identifier (used in tool names: parse_{name}, compile_{name}, etc.) */\n readonly name: string;\n\n /** Human-readable description */\n readonly description: string;\n\n /** Supported language codes */\n readonly languages: readonly string[];\n\n /** Label for the primary input parameter (e.g., 'query', 'scenario', 'code') */\n readonly inputLabel: string;\n\n /** Description of the primary input parameter */\n readonly inputDescription: string;\n\n /** What compile_{name} produces (e.g., \"a SQL query string\"). Used in tool description. */\n readonly outputDescription?: string;\n\n /**\n * Factory to lazily create the DSL instance.\n * Called once on first tool use. The result is cached.\n */\n readonly getDSL: () => MultilingualDSL | Promise<MultilingualDSL>;\n\n /**\n * Factory to lazily create the renderer.\n * Required for translate_{name} tool. Called once on first use.\n *\n * The function form may return `null` for an action it cannot render; the\n * translate tool reports that as an unsuccessful translation.\n */\n readonly getRenderer?: () =>\n NaturalLanguageRenderer | DomainRenderFn | Promise<NaturalLanguageRenderer | DomainRenderFn>;\n\n /**\n * Which standard tools to generate. Default: all four.\n */\n readonly tools?: readonly ('parse' | 'compile' | 'validate' | 'translate')[];\n\n /**\n * Optional command schemas for this domain.\n * When provided, enables system prompt generation, training data synthesis,\n * and structured feedback via the registry's convenience methods.\n */\n readonly schemas?: readonly CommandSchema[];\n\n /**\n * Optional scan configuration for AOT compilation and Vite plugin.\n * Declares which HTML attributes/script types this domain uses.\n */\n readonly scanConfig?: {\n /** Attribute names to scan for (e.g., ['data-sql', '_sql']) */\n readonly attributes: readonly string[];\n /** Script tag types to scan for (e.g., ['text/sql-dsl']) */\n readonly scriptTypes?: readonly string[];\n /** Default language when not specified on element */\n readonly defaultLanguage?: string;\n /** Keywords for detection, keyed by language code */\n readonly keywords?: Readonly<Record<string, readonly string[]>>;\n };\n}\n\n// =============================================================================\n// MCP Tool Types (minimal — compatible with @modelcontextprotocol/server)\n// =============================================================================\n\n/**\n * MCP tool definition. Compatible with the MCP SDK's tool schema.\n */\nexport interface MCPToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: {\n readonly type: 'object';\n readonly properties: Record<string, unknown>;\n readonly required: readonly string[];\n };\n}\n\n/**\n * MCP tool response. Compatible with the MCP SDK's response format.\n */\nexport interface MCPToolResponse {\n readonly content: ReadonlyArray<{ readonly type: string; readonly text: string }>;\n readonly isError?: boolean;\n}\n\n// =============================================================================\n// Domain Registry\n// =============================================================================\n\n/**\n * Registry for framework domains.\n *\n * Manages domain descriptors, generates MCP tool definitions,\n * and dispatches tool calls to the appropriate domain.\n */\nexport class DomainRegistry {\n private descriptors = new Map<string, DomainDescriptor>();\n private dslCache = new Map<string, MultilingualDSL>();\n private rendererCache = new Map<string, NaturalLanguageRenderer | DomainRenderFn>();\n\n /**\n * Register a domain.\n * @throws if a domain with the same name is already registered\n */\n register(descriptor: DomainDescriptor): void {\n if (this.descriptors.has(descriptor.name)) {\n throw new Error(`Domain already registered: ${descriptor.name}`);\n }\n this.descriptors.set(descriptor.name, descriptor);\n }\n\n /**\n * Attach schemas to an already-registered domain.\n * Useful for lazy loading schemas after initial registration.\n */\n setSchemas(name: string, schemas: readonly CommandSchema[]): void {\n const existing = this.descriptors.get(name);\n if (!existing) {\n throw new Error(`Domain not registered: ${name}`);\n }\n // Create a new descriptor with schemas attached\n this.descriptors.set(name, { ...existing, schemas });\n }\n\n /**\n * Get all registered domain names.\n */\n getDomainNames(): string[] {\n return Array.from(this.descriptors.keys());\n }\n\n /**\n * Get a specific domain descriptor.\n */\n getDescriptor(name: string): DomainDescriptor | undefined {\n return this.descriptors.get(name);\n }\n\n /**\n * Generate MCP tool definitions for all registered domains.\n */\n getToolDefinitions(): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n for (const desc of this.descriptors.values()) {\n tools.push(...generateToolDefinitions(desc));\n }\n return tools;\n }\n\n /**\n * Check if a tool name belongs to a registered domain.\n */\n canHandle(toolName: string): boolean {\n const parsed = parseToolName(toolName);\n if (!parsed) return false;\n return this.descriptors.has(parsed.domain);\n }\n\n /**\n * Handle a tool call by dispatching to the appropriate domain.\n * Returns null if the tool name doesn't match any registered domain.\n */\n async handleToolCall(\n toolName: string,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse | null> {\n const parsed = parseToolName(toolName);\n if (!parsed) return null;\n\n const descriptor = this.descriptors.get(parsed.domain);\n if (!descriptor) return null;\n\n try {\n const dsl = await this.getDSL(descriptor);\n\n switch (parsed.operation) {\n case 'parse':\n return await this.handleParse(descriptor, dsl, args);\n case 'compile':\n return await this.handleCompile(descriptor, dsl, args);\n case 'validate':\n return await this.handleValidate(descriptor, dsl, args);\n case 'translate':\n return await this.handleTranslate(descriptor, dsl, args);\n default:\n return jsonResponse({ error: `Unknown operation: ${parsed.operation}` }, true);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return jsonResponse({ error: `${descriptor.name} tool error: ${message}` }, true);\n }\n }\n\n /**\n * Get the DSL instance for a named domain.\n * Returns null if the domain is not registered.\n * The DSL is lazily created and cached.\n */\n async getDSLForDomain(name: string): Promise<MultilingualDSL | null> {\n const descriptor = this.descriptors.get(name);\n if (!descriptor) return null;\n return this.getDSL(descriptor);\n }\n\n // ---------------------------------------------------------------------------\n // LLM ↔ LSE Convenience Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Generate an LLM system prompt for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generatePrompt(domain: string, config?: Partial<PromptGeneratorConfig>): GeneratedPrompt | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _generatePrompt({\n domain,\n description: descriptor.description,\n schemas: descriptor.schemas,\n ...config,\n });\n }\n\n /**\n * Synthesize training data for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generateTrainingData(domain: string, config?: Partial<SynthesisConfig>): SynthesisResult | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _synthesizeFromSchemas(descriptor.schemas, {\n domain,\n ...config,\n });\n }\n\n /**\n * Build structured feedback for a failed LSE input in a domain.\n * Returns null if the domain is not registered or has no schemas.\n */\n buildFeedback(\n domain: string,\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[]\n ): LSEFeedback | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n const schemaLookup = this.createSchemaLookup(descriptor.schemas);\n\n // Try to extract the action from the input\n let action: string | undefined;\n try {\n if (inputFormat === 'explicit') {\n const node = _parseExplicit(input, { schemaLookup });\n action = node.action;\n }\n } catch {\n // Action detection failed — still build feedback without it\n }\n\n return _buildFeedback(input, inputFormat, diagnostics, schemaLookup, action);\n }\n\n /**\n * Get schemas for a domain (if available).\n */\n getSchemas(domain: string): readonly CommandSchema[] | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas) return null;\n return descriptor.schemas;\n }\n\n /**\n * Create a SchemaLookup from a domain's schemas.\n */\n private createSchemaLookup(schemas: readonly CommandSchema[]): SchemaLookup {\n const map = new Map<string, CommandSchema>();\n for (const s of schemas) {\n map.set(s.action, s);\n }\n return { getSchema: (action: string) => map.get(action) };\n }\n\n // ---------------------------------------------------------------------------\n // Private: DSL/renderer lifecycle\n // ---------------------------------------------------------------------------\n\n private async getDSL(descriptor: DomainDescriptor): Promise<MultilingualDSL> {\n const cached = this.dslCache.get(descriptor.name);\n if (cached) return cached;\n\n const dsl = await descriptor.getDSL();\n this.dslCache.set(descriptor.name, dsl);\n return dsl;\n }\n\n private async getRenderer(\n descriptor: DomainDescriptor\n ): Promise<NaturalLanguageRenderer | DomainRenderFn | null> {\n if (!descriptor.getRenderer) return null;\n\n const cached = this.rendererCache.get(descriptor.name);\n if (cached) return cached;\n\n const renderer = await descriptor.getRenderer();\n this.rendererCache.set(descriptor.name, renderer);\n return renderer;\n }\n\n // ---------------------------------------------------------------------------\n // Private: Tool handlers\n // ---------------------------------------------------------------------------\n\n private async handleParse(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const node = dsl.parse(input, language);\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n action: node.action,\n roles,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleCompile(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: CompileResult = dsl.compile(input, language);\n\n return jsonResponse({\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n language,\n input,\n });\n }\n\n private async handleValidate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: ValidationResult = dsl.validate(input, language);\n\n return jsonResponse({\n valid: result.valid,\n errors: result.errors,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleTranslate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const from = getString(args, 'from');\n if (!from) return missingParam('from');\n const to = getString(args, 'to');\n if (!to) return missingParam('to');\n\n // Parse in source language\n const node = dsl.parse(input, from);\n\n // Compile (language-neutral output)\n const compiled = dsl.compile(input, from);\n\n // Render to target language\n let rendered: string | null = null;\n const renderer = await this.getRenderer(descriptor);\n if (renderer) {\n try {\n rendered = typeof renderer === 'function' ? renderer(node, to) : renderer.render(node, to);\n } catch {\n // Fall through with rendered = null\n }\n } else if (dsl.render) {\n // A descriptor without an explicit renderer can still render: the DSL\n // knows its own domain renderer and its schema fallback.\n try {\n rendered = dsl.render(node, to);\n } catch {\n // Fall through with rendered = null\n }\n }\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n input: { [descriptor.inputLabel]: input, language: from },\n ...(rendered != null && { rendered: { text: rendered, language: to } }),\n semantic: { action: node.action, roles },\n ...(compiled.ok && compiled.code != null && { compiled: compiled.code }),\n });\n }\n}\n\n// =============================================================================\n// Tool Definition Generator\n// =============================================================================\n\nfunction generateToolDefinitions(desc: DomainDescriptor): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n const ops = desc.tools ?? (['parse', 'compile', 'validate', 'translate'] as const);\n const langList = desc.languages.join(', ');\n\n for (const op of ops) {\n switch (op) {\n case 'parse':\n tools.push({\n name: `parse_${desc.name}`,\n description: `Parse a ${desc.description} input into a semantic representation (action, roles, confidence). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'compile':\n tools.push({\n name: `compile_${desc.name}`,\n description: `Compile a ${desc.description} input to ${desc.outputDescription ?? 'target code'}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'validate':\n tools.push({\n name: `validate_${desc.name}`,\n description: `Check ${desc.description} syntax for errors. Returns {valid, errors[]}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to validate`,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'translate':\n tools.push({\n name: `translate_${desc.name}`,\n description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to translate`,\n },\n from: {\n type: 'string',\n description: `Source language code: ${langList}`,\n },\n to: {\n type: 'string',\n description: `Target language code: ${langList}`,\n },\n },\n required: [desc.inputLabel, 'from', 'to'],\n },\n });\n break;\n }\n }\n\n return tools;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction parseToolName(name: string): { operation: string; domain: string } | null {\n const match = name.match(/^(parse|compile|validate|translate)_(.+)$/);\n if (!match) return null;\n return { operation: match[1], domain: match[2] };\n}\n\nfunction getString(args: Record<string, unknown>, name: string, defaultValue = ''): string {\n const value = args[name];\n return typeof value === 'string' ? value : defaultValue;\n}\n\nfunction jsonResponse(data: unknown, isError?: boolean): MCPToolResponse {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n ...(isError && { isError: true }),\n };\n}\n\nfunction missingParam(param: string): MCPToolResponse {\n return jsonResponse({ error: `Missing required parameter: ${param}` }, true);\n}\n","/**\n * Cross-Domain Dispatcher\n *\n * Routes natural-language input to the correct domain by trying all registered\n * domains and picking the highest-confidence match. Supports auto-detection,\n * composite multi-line parsing, and confidence-based routing.\n *\n * @example\n * ```typescript\n * import { DomainRegistry, CrossDomainDispatcher } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n * registry.register(sqlDescriptor);\n * registry.register(bddDescriptor);\n *\n * const dispatcher = new CrossDomainDispatcher(registry);\n *\n * // Auto-detect which domain handles the input\n * const result = await dispatcher.detect('select name from users', 'en');\n * // → { domain: 'sql', node: ..., confidence: 0.95, dsl: ... }\n *\n * // Parse multi-line input across domains\n * const composite = await dispatcher.parseComposite(`\n * select name from users\n * given page http://localhost\n * `, 'en');\n * ```\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport { DomainRegistry } from './domain-registry';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Result of domain auto-detection */\nexport interface DispatchResult {\n /** The domain that matched */\n readonly domain: string;\n /** Parsed semantic node */\n readonly node: SemanticNode;\n /** Confidence score (0-1) */\n readonly confidence: number;\n /** The DSL instance that parsed it */\n readonly dsl: MultilingualDSL;\n}\n\n/** A single statement in a composite parse result */\nexport interface CompositeStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly node: SemanticNode;\n readonly confidence: number;\n}\n\n/** An error from a composite parse */\nexport interface CompositeError {\n readonly line: number;\n readonly input: string;\n readonly message: string;\n}\n\n/** Result of multi-domain composite parsing */\nexport interface CompositeParseResult {\n /** Successfully parsed statements */\n readonly statements: readonly CompositeStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** A single compiled statement in a composite compile result */\nexport interface CompositeCompileStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly ok: boolean;\n readonly code?: string | undefined;\n readonly errors?: string[] | undefined;\n}\n\n/** Result of multi-domain composite compilation */\nexport interface CompositeCompileResult {\n /** Successfully detected and compiled statements */\n readonly statements: readonly CompositeCompileStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** Dispatcher configuration options */\nexport interface DispatcherOptions {\n /** Minimum confidence to accept a match (default: 0.5) */\n readonly minConfidence?: number;\n /** Domain priority order — earlier domains win on confidence ties */\n readonly priority?: readonly string[];\n}\n\n// =============================================================================\n// Comment line detection\n// =============================================================================\n\nconst COMMENT_PATTERN = /^\\s*(\\/\\/|--|#)/;\n\nfunction isSkippableLine(line: string): boolean {\n const trimmed = line.trim();\n return trimmed === '' || COMMENT_PATTERN.test(trimmed);\n}\n\n// =============================================================================\n// CrossDomainDispatcher\n// =============================================================================\n\n/**\n * Dispatcher that routes input to the correct domain by confidence scoring.\n *\n * Built on top of DomainRegistry — uses registered domains' DSL instances\n * to try parsing input and picks the highest-confidence match.\n */\nexport class CrossDomainDispatcher {\n private registry: DomainRegistry;\n private minConfidence: number;\n private priority: readonly string[];\n\n constructor(registry: DomainRegistry, options?: DispatcherOptions) {\n this.registry = registry;\n this.minConfidence = options?.minConfidence ?? 0.5;\n this.priority = options?.priority ?? [];\n }\n\n /**\n * Auto-detect which domain handles the input.\n * Tries all registered domains and returns the highest-confidence match.\n * Returns null if no domain matches above minConfidence.\n */\n async detect(input: string, language = 'en'): Promise<DispatchResult | null> {\n const domainNames = this.registry.getDomainNames();\n if (domainNames.length === 0) return null;\n\n const candidates: DispatchResult[] = [];\n\n for (const name of domainNames) {\n try {\n const dsl = await this.registry.getDSLForDomain(name);\n if (!dsl) continue;\n\n const { node, confidence } = dsl.parseWithConfidence(input, language);\n if (confidence >= this.minConfidence) {\n candidates.push({ domain: name, node, confidence, dsl });\n }\n } catch {\n // Domain could not be loaded or parse this input — skip\n }\n }\n\n if (candidates.length === 0) return null;\n\n // Sort by priority first, then confidence within each priority tier.\n // Simpler schemas (fewer roles) often score higher confidence than more\n // specific ones — e.g., voice's \"select [patient:greedy]\" gets 1.0 while\n // sql's \"select [columns] from [source]\" gets 0.71 for the same input.\n // Priority ordering ensures domain specificity wins when both match.\n if (this.priority.length > 0) {\n candidates.sort((a, b) => {\n const pa = this.getPriorityIndex(a.domain);\n const pb = this.getPriorityIndex(b.domain);\n if (pa !== pb) return pa - pb;\n return b.confidence - a.confidence;\n });\n } else {\n // No priority configured: pure confidence ordering\n candidates.sort((a, b) => b.confidence - a.confidence);\n }\n\n return candidates[0];\n }\n\n /**\n * Parse multi-line input where each line may belong to a different domain.\n * Empty lines and comment lines (starting with //, --, or #) are skipped.\n */\n async parseComposite(input: string, language = 'en'): Promise<CompositeParseResult> {\n const lines = input.split('\\n');\n const statements: CompositeStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const result = await this.detect(trimmed, language);\n\n if (result) {\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: result.domain,\n node: result.node,\n confidence: result.confidence,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Compile input using auto-detected domain.\n * Returns the compilation result with the domain name.\n */\n async compile(\n input: string,\n language = 'en'\n ): Promise<(CompileResult & { domain: string }) | null> {\n const detected = await this.detect(input, language);\n if (!detected) return null;\n\n const result = detected.dsl.compile(input, language);\n return { ...result, domain: detected.domain };\n }\n\n /**\n * Compile multi-line input where each line may belong to a different domain.\n * Detects the domain for each line and compiles it, returning per-line results.\n * Empty lines and comment lines are skipped.\n */\n async compileComposite(input: string, language = 'en'): Promise<CompositeCompileResult> {\n const lines = input.split('\\n');\n const statements: CompositeCompileStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const detected = await this.detect(trimmed, language);\n\n if (detected) {\n const result = detected.dsl.compile(trimmed, language);\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: detected.domain,\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Validate input against all domains, returning the best match.\n */\n async validate(input: string, language = 'en'): Promise<ValidationResult & { domain?: string }> {\n const detected = await this.detect(input, language);\n if (!detected) {\n return { valid: false, errors: ['No domain matched this input'] };\n }\n\n const result = detected.dsl.validate(input, language);\n return { ...result, domain: detected.domain };\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private getPriorityIndex(domain: string): number {\n const idx = this.priority.indexOf(domain);\n return idx === -1 ? this.priority.length : idx;\n }\n}\n","/**\n * Domain-Aware Scanner\n *\n * Extracts DSL snippets from HTML/template files based on domain-declared\n * attribute patterns and script types. Unlike the hyperscript-specific\n * HTMLScanner, this scanner is configured dynamically from DomainScanConfig.\n */\n\nimport type { DomainScanConfig, ExtractedSnippet } from './types';\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Build regex patterns for extracting attribute values.\n * Handles double-quoted, single-quoted, and backtick-quoted values.\n */\nfunction buildAttributePatterns(attributes: readonly string[]): RegExp[] {\n const patterns: RegExp[] = [];\n for (const attr of attributes) {\n const escaped = attr.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Match: attr=\"value\", attr='value', attr=`value`\n patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*\"([^\"]+)\"`, 'g'));\n patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*'([^']+)'`, 'g'));\n patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*\\`([^\\`]+)\\``, 'g'));\n }\n return patterns;\n}\n\n/**\n * Build regex patterns for extracting script tag contents.\n */\nfunction buildScriptPatterns(scriptTypes: readonly string[]): RegExp[] {\n return scriptTypes.map(type => {\n const escaped = type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`<script[^>]*type=[\"']?${escaped}[\"']?[^>]*>([\\\\s\\\\S]*?)<\\\\/script>`, 'gi');\n });\n}\n\n/**\n * Count newlines before a position to determine line number.\n */\nfunction getLineNumber(source: string, position: number): number {\n let line = 1;\n for (let i = 0; i < position && i < source.length; i++) {\n if (source[i] === '\\n') line++;\n }\n return line;\n}\n\n/**\n * Try to extract an element ID near the matched attribute.\n * Looks backward in the source for an id=\"...\" on the same element.\n */\nfunction extractElementId(source: string, matchIndex: number): string | undefined {\n // Find the opening < before this attribute\n const before = source.lastIndexOf('<', matchIndex);\n if (before === -1) return undefined;\n\n const tagChunk = source.slice(before, matchIndex + 200);\n const idMatch = tagChunk.match(/\\bid=[\"']([^\"']+)[\"']/);\n return idMatch?.[1];\n}\n\n/**\n * Try to extract a lang attribute from the element.\n */\nfunction extractLangAttribute(source: string, matchIndex: number): string | undefined {\n const before = source.lastIndexOf('<', matchIndex);\n if (before === -1) return undefined;\n\n const tagChunk = source.slice(before, matchIndex + 200);\n const langMatch = tagChunk.match(/\\blang=[\"']([^\"']+)[\"']/);\n return langMatch?.[1];\n}\n\n// =============================================================================\n// DomainAwareScanner\n// =============================================================================\n\n/**\n * Scans HTML/template files for domain-specific snippets.\n *\n * Configured by DomainScanConfig objects, each declaring which\n * HTML attributes and script types a domain uses.\n */\nexport class DomainAwareScanner {\n private configs: readonly DomainScanConfig[];\n\n constructor(configs: readonly DomainScanConfig[]) {\n this.configs = configs;\n }\n\n /**\n * Extract all domain snippets from an HTML source string.\n */\n extract(source: string, filename: string): ExtractedSnippet[] {\n const snippets: ExtractedSnippet[] = [];\n\n for (const config of this.configs) {\n const defaultLang = config.defaultLanguage ?? 'en';\n\n // Extract from attributes\n const attrPatterns = buildAttributePatterns(config.attributes);\n for (const pattern of attrPatterns) {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(source))) {\n const code = match[1].trim();\n if (!code) continue;\n\n const line = getLineNumber(source, match.index);\n const elementId = extractElementId(source, match.index);\n const langAttr = extractLangAttribute(source, match.index);\n\n snippets.push({\n domain: config.domain,\n code,\n language: langAttr ?? defaultLang,\n file: filename,\n line,\n column: 1,\n ...(elementId != null && { elementId }),\n });\n }\n }\n\n // Extract from script tags\n if (config.scriptTypes) {\n const scriptPatterns = buildScriptPatterns(config.scriptTypes);\n for (const pattern of scriptPatterns) {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(source))) {\n const code = match[1].trim();\n if (!code) continue;\n\n const line = getLineNumber(source, match.index);\n\n snippets.push({\n domain: config.domain,\n code,\n language: defaultLang,\n file: filename,\n line,\n column: 1,\n });\n }\n }\n }\n }\n\n return snippets;\n }\n\n /**\n * Extract snippets from multiple files.\n */\n async extractFromFiles(\n files: string[],\n readFile: (path: string) => Promise<string>\n ): Promise<ExtractedSnippet[]> {\n const allSnippets: ExtractedSnippet[] = [];\n\n for (const file of files) {\n try {\n const source = await readFile(file);\n const snippets = this.extract(source, file);\n allSnippets.push(...snippets);\n } catch {\n // Skip files that can't be read\n }\n }\n\n return allSnippets;\n }\n}\n","/**\n * Generalized AOT Orchestrator\n *\n * Coordinates scan → parse → compile → collect for any domain.\n * Each domain provides a DomainCompilationBackend (DSL + CodeGenerator + scan config),\n * and the orchestrator handles the rest.\n *\n * @example\n * ```typescript\n * import { AOTOrchestrator } from '@lokascript/framework';\n *\n * const orchestrator = new AOTOrchestrator();\n *\n * orchestrator.registerBackend({\n * domain: 'sql',\n * dsl: createSQLDSL(),\n * codeGenerator: sqlCodeGenerator,\n * scanConfig: {\n * domain: 'sql',\n * attributes: ['data-sql'],\n * scriptTypes: ['text/sql-dsl'],\n * },\n * });\n *\n * const result = await orchestrator.compileFiles(\n * ['index.html', 'about.html'],\n * (path) => fs.promises.readFile(path, 'utf-8')\n * );\n * ```\n */\n\nimport type { MultilingualDSL, CodeGenerator } from '../api/create-dsl';\nimport type {\n DomainScanConfig,\n ExtractedSnippet,\n CompiledSnippet,\n AOTBatchResult,\n GeneralizedAOTOptions,\n OutputOptions,\n} from './types';\nimport { DomainAwareScanner } from './domain-scanner';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Per-domain compilation backend.\n * Provides everything needed to scan, parse, and compile a domain's syntax.\n */\nexport interface DomainCompilationBackend {\n /** Domain name (must match scanConfig.domain) */\n readonly domain: string;\n /** The DSL instance for parsing and compilation */\n readonly dsl: MultilingualDSL;\n /** Code generator for producing target code from semantic nodes */\n readonly codeGenerator: CodeGenerator;\n /** Scan configuration declaring HTML attribute patterns */\n readonly scanConfig: DomainScanConfig;\n}\n\n// =============================================================================\n// AOTOrchestrator\n// =============================================================================\n\n/**\n * Generalized AOT orchestrator for any domain.\n */\nexport class AOTOrchestrator {\n private backends = new Map<string, DomainCompilationBackend>();\n private options: Required<GeneralizedAOTOptions>;\n\n constructor(options?: GeneralizedAOTOptions) {\n this.options = {\n confidenceThreshold: options?.confidenceThreshold ?? 0.7,\n continueOnError: options?.continueOnError ?? true,\n debug: options?.debug ?? false,\n };\n }\n\n /**\n * Register a domain compilation backend.\n * @throws if a backend with the same domain name is already registered\n */\n registerBackend(backend: DomainCompilationBackend): void {\n if (this.backends.has(backend.domain)) {\n throw new Error(`Backend already registered for domain: ${backend.domain}`);\n }\n this.backends.set(backend.domain, backend);\n }\n\n /**\n * Scan source files and compile all domain snippets.\n */\n async compileFiles(\n files: string[],\n readFile: (path: string) => Promise<string>\n ): Promise<AOTBatchResult> {\n // Build scanner from all backends' scan configs\n const configs = Array.from(this.backends.values()).map(b => b.scanConfig);\n const scanner = new DomainAwareScanner(configs);\n\n // Extract all snippets\n const snippets = await scanner.extractFromFiles(files, readFile);\n\n if (this.options.debug) {\n console.log(`[aot] Extracted ${snippets.length} snippets from ${files.length} files`);\n }\n\n // Compile each snippet\n const compiled: CompiledSnippet[] = [];\n const errors: AOTBatchResult['errors'][number][] = [];\n const domainBreakdown: Record<string, number> = {};\n\n for (const snippet of snippets) {\n domainBreakdown[snippet.domain] = (domainBreakdown[snippet.domain] ?? 0) + 1;\n\n const result = this.compileSnippet(snippet);\n if ('error' in result) {\n errors.push({\n domain: snippet.domain,\n source: snippet.code,\n file: snippet.file,\n line: snippet.line,\n message: result.error,\n });\n if (!this.options.continueOnError) break;\n } else {\n compiled.push(result);\n }\n }\n\n return {\n compiled,\n errors,\n stats: {\n totalSnippets: snippets.length,\n compiledCount: compiled.length,\n errorCount: errors.length,\n domainBreakdown,\n },\n };\n }\n\n /**\n * Compile a single extracted snippet.\n * Returns the compiled result or an error object.\n */\n compileSnippet(snippet: ExtractedSnippet): CompiledSnippet | { error: string } {\n const backend = this.backends.get(snippet.domain);\n if (!backend) {\n return { error: `No backend registered for domain: ${snippet.domain}` };\n }\n\n try {\n const result = backend.dsl.compile(snippet.code, snippet.language);\n if (!result.ok || !result.code) {\n return { error: result.errors?.join('; ') ?? 'Compilation failed' };\n }\n\n return {\n domain: snippet.domain,\n source: snippet.code,\n compiled: result.code,\n language: snippet.language,\n file: snippet.file,\n line: snippet.line,\n };\n } catch (err) {\n return { error: err instanceof Error ? err.message : String(err) };\n }\n }\n\n /**\n * Generate combined output from compilation results.\n */\n generateOutput(result: AOTBatchResult, options?: OutputOptions): string {\n const format = options?.format ?? 'esm';\n const includeComments = options?.includeComments ?? true;\n const groupByDomain = options?.groupByDomain ?? true;\n\n const sections: string[] = [];\n\n if (includeComments) {\n sections.push(`// Generated by @lokascript/framework AOT compiler`);\n sections.push(\n `// ${result.stats.compiledCount} snippets compiled, ${result.stats.errorCount} errors`\n );\n sections.push('');\n }\n\n if (groupByDomain) {\n // Group by domain\n const grouped = new Map<string, CompiledSnippet[]>();\n for (const snippet of result.compiled) {\n const list = grouped.get(snippet.domain) ?? [];\n list.push(snippet);\n grouped.set(snippet.domain, list);\n }\n\n for (const [domain, snippets] of grouped) {\n if (includeComments) {\n sections.push(`// === Domain: ${domain} ===`);\n sections.push('');\n }\n\n for (const snippet of snippets) {\n if (includeComments) {\n sections.push(`// Source: ${snippet.file}:${snippet.line}`);\n sections.push(`// Language: ${snippet.language}`);\n }\n sections.push(snippet.compiled);\n sections.push('');\n }\n }\n } else {\n for (const snippet of result.compiled) {\n if (includeComments) {\n sections.push(`// [${snippet.domain}] ${snippet.file}:${snippet.line}`);\n }\n sections.push(snippet.compiled);\n sections.push('');\n }\n }\n\n const body = sections.join('\\n').trimEnd();\n\n switch (format) {\n case 'cjs':\n return `'use strict';\\n\\n${body}\\n`;\n case 'iife':\n return `(function() {\\n${body}\\n})();\\n`;\n case 'esm':\n default:\n return `${body}\\n`;\n }\n }\n}\n","/**\n * Registry-to-AOT Bridge\n *\n * Converts DomainRegistry entries into DomainCompilationBackend instances\n * for use with AOTOrchestrator. Only domains that have scanConfig defined\n * are included.\n *\n * @example\n * ```typescript\n * const registry = new DomainRegistry();\n * // ... register domains with scanConfig ...\n *\n * const backends = await registryToAOTBackends(registry);\n * const orchestrator = new AOTOrchestrator();\n * for (const backend of backends) {\n * orchestrator.registerBackend(backend);\n * }\n * ```\n */\n\nimport type { DomainCompilationBackend } from './aot-orchestrator';\nimport type { DomainScanConfig } from './types';\nimport type { DomainRegistry } from '../api/domain-registry';\nimport type { CodeGenerator } from '../api/create-dsl';\nimport type { SemanticNode } from '../core/types';\n\n/**\n * Convert all registry entries with scanConfig into AOT backends.\n * Domains without scanConfig are skipped.\n */\nexport async function registryToAOTBackends(\n registry: DomainRegistry\n): Promise<DomainCompilationBackend[]> {\n const backends: DomainCompilationBackend[] = [];\n\n for (const name of registry.getDomainNames()) {\n const descriptor = registry.getDescriptor(name);\n if (!descriptor?.scanConfig) continue;\n\n const dsl = await registry.getDSLForDomain(name);\n if (!dsl) continue;\n\n const scanConfig: DomainScanConfig = {\n domain: name,\n attributes: [...descriptor.scanConfig.attributes],\n ...(descriptor.scanConfig.scriptTypes\n ? { scriptTypes: [...descriptor.scanConfig.scriptTypes] }\n : {}),\n defaultLanguage: descriptor.scanConfig.defaultLanguage ?? 'en',\n };\n\n // The AOTOrchestrator only calls backend.dsl.compile(), not codeGenerator directly.\n // Provide a thin adapter that parses then generates via the DSL's internal pipeline.\n const codeGenerator: CodeGenerator = {\n generate(node: SemanticNode): string {\n // Fallback: compile through the DSL by reconstructing explicit syntax.\n // In practice, AOTOrchestrator uses dsl.compile() directly.\n return JSON.stringify({ action: node.action, roles: Object.fromEntries(node.roles) });\n },\n };\n\n backends.push({ domain: name, dsl, codeGenerator, scanConfig });\n }\n\n return backends;\n}\n","/**\n * Command Schema Types — re-exported from @lokascript/intent\n */\n\nexport type { CommandSchema, RoleSpec } from '@lokascript/intent';\nexport { defineCommand, defineRole, getRoleSpec } from '@lokascript/intent';\n","/**\n * Structured Error Diagnostics\n *\n * Re-exported from @lokascript/intent.\n * This module is the framework's re-export point for the diagnostic types\n * that live in the universal intent package.\n */\n\nexport type {\n DiagnosticSeverity,\n Diagnostic,\n DiagnosticResult,\n DiagnosticSummary,\n DiagnosticCollector,\n DiagnosticOptions,\n} from '@lokascript/intent';\n\nexport { createDiagnosticCollector, fromError, filterBySeverity } from '@lokascript/intent';\n","/**\n * Token Utilities\n *\n * Core token creation, stream implementation, and character classification.\n * These are the foundational building blocks used by all tokenizers.\n */\n\nimport type { LanguageToken, TokenKind, TokenStream, StreamMark, SourcePosition } from '../types';\n\n// =============================================================================\n// Time Unit Configuration\n// =============================================================================\n\n/**\n * Configuration for a native language time unit pattern.\n * Used by tryNumberWithTimeUnits() to match language-specific time units.\n */\nexport interface TimeUnitMapping {\n /** The pattern to match (e.g., 'segundos', 'ミリ秒') */\n readonly pattern: string;\n /** The standard suffix to use (ms, s, m, h) */\n readonly suffix: string;\n /** Length of the pattern (for optimization) */\n readonly length: number;\n /** Whether to check for word boundary after the pattern */\n readonly checkBoundary?: boolean;\n /** Character that cannot follow the pattern (e.g., 's' for 'm' to avoid 'ms') */\n readonly notFollowedBy?: string;\n /** Whether to do case-insensitive matching */\n readonly caseInsensitive?: boolean;\n}\n\n// =============================================================================\n// Token Stream Implementation\n// =============================================================================\n\n/**\n * Concrete implementation of TokenStream.\n */\nexport class TokenStreamImpl implements TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n private pos: number = 0;\n\n constructor(tokens: LanguageToken[], language: string) {\n this.tokens = tokens;\n this.language = language;\n }\n\n peek(offset: number = 0): LanguageToken | null {\n const index = this.pos + offset;\n if (index < 0 || index >= this.tokens.length) {\n return null;\n }\n return this.tokens[index];\n }\n\n advance(): LanguageToken {\n if (this.isAtEnd()) {\n throw new Error('Unexpected end of token stream');\n }\n return this.tokens[this.pos++];\n }\n\n isAtEnd(): boolean {\n return this.pos >= this.tokens.length;\n }\n\n mark(): StreamMark {\n return { position: this.pos };\n }\n\n reset(mark: StreamMark): void {\n this.pos = mark.position;\n }\n\n position(): number {\n return this.pos;\n }\n\n /**\n * Get remaining tokens as an array.\n */\n remaining(): LanguageToken[] {\n return this.tokens.slice(this.pos);\n }\n\n /**\n * Consume tokens while predicate is true.\n */\n takeWhile(predicate: (token: LanguageToken) => boolean): LanguageToken[] {\n const result: LanguageToken[] = [];\n while (!this.isAtEnd() && predicate(this.peek()!)) {\n result.push(this.advance());\n }\n return result;\n }\n\n /**\n * Skip tokens while predicate is true.\n */\n skipWhile(predicate: (token: LanguageToken) => boolean): void {\n while (!this.isAtEnd() && predicate(this.peek()!)) {\n this.advance();\n }\n }\n}\n\n// =============================================================================\n// Shared Tokenization Utilities\n// =============================================================================\n\n/**\n * Create a source position from start and end offsets.\n */\nexport function createPosition(start: number, end: number): SourcePosition {\n return { start, end };\n}\n\n/**\n * Options for creating a token with optional morphological data.\n */\nexport interface CreateTokenOptions {\n /** Explicitly normalized form from keyword map */\n normalized?: string;\n /** Morphologically normalized stem */\n stem?: string;\n /** Confidence in the stem (0.0-1.0) */\n stemConfidence?: number;\n /** Additional metadata for specific token types (e.g., event modifier data) */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Token creation options (object style).\n */\nexport interface TokenCreationParams extends CreateTokenOptions {\n value: string;\n kind: TokenKind;\n position: SourcePosition;\n}\n\n/**\n * Create a language token (object style).\n */\nexport function createToken(params: TokenCreationParams): LanguageToken;\n\n/**\n * Create a language token (separate parameters style).\n */\nexport function createToken(\n value: string,\n kind: TokenKind,\n position: SourcePosition,\n normalizedOrOptions?: string | CreateTokenOptions\n): LanguageToken;\n\n/**\n * Create a language token.\n * Supports both object style and separate parameters style.\n */\nexport function createToken(\n valueOrParams: string | TokenCreationParams,\n kind?: TokenKind,\n position?: SourcePosition,\n normalizedOrOptions?: string | CreateTokenOptions\n): LanguageToken {\n // Handle object style\n if (typeof valueOrParams === 'object') {\n const { value, kind, position, normalized, stem, stemConfidence, metadata } = valueOrParams;\n return {\n value,\n kind,\n position,\n ...(normalized !== undefined && { normalized }),\n ...(stem !== undefined && { stem }),\n ...(stemConfidence !== undefined && { stemConfidence }),\n ...(metadata !== undefined && { metadata }),\n };\n }\n\n // Handle separate parameters style\n const value = valueOrParams;\n if (!kind || !position) {\n throw new Error('createToken requires kind and position parameters');\n }\n // Handle legacy string argument for backward compatibility\n if (typeof normalizedOrOptions === 'string') {\n return { value, kind, position, normalized: normalizedOrOptions };\n }\n\n // Handle options object\n if (normalizedOrOptions) {\n const { normalized, stem, stemConfidence, metadata } = normalizedOrOptions;\n return {\n value,\n kind,\n position,\n ...(normalized !== undefined && { normalized }),\n ...(stem !== undefined && { stem }),\n ...(stemConfidence !== undefined && { stemConfidence }),\n ...(metadata !== undefined && { metadata }),\n };\n }\n\n return { value, kind, position };\n}\n\n/**\n * Check if a character is whitespace.\n */\nexport function isWhitespace(char: string): boolean {\n return /\\s/.test(char);\n}\n\n/**\n * Check if a string starts with a CSS selector prefix.\n * Includes JSX-style element selectors: <form />, <div>\n */\nexport function isSelectorStart(char: string): boolean {\n return (\n char === '#' || char === '.' || char === '[' || char === '@' || char === '*' || char === '<'\n );\n}\n\n/**\n * Check if a character is a quote (string delimiter).\n */\nexport function isQuote(char: string): boolean {\n return char === '\"' || char === \"'\" || char === '`' || char === '「' || char === '」';\n}\n\n/**\n * Check if a character is a digit.\n */\nexport function isDigit(char: string): boolean {\n return /\\d/.test(char);\n}\n\n/**\n * Strip diacritical marks that are OPTIONAL in their script — currently Arabic\n * harakat (U+064B–U+0652: fatha, kasra, damma, sukun, shadda…) and the\n * superscript alif (U+0670).\n *\n * `بدّل` and `بَدِّل` are the same word; Arabic prose writes either. So any place\n * that compares an Arabic surface form against a declared keyword has to compare\n * stripped, or the same word fails to match itself.\n *\n * Deliberately Arabic-only. Latin diacritics are NOT optional — `obtén`, `récupère`\n * and `vá` differ from their unaccented spellings in meaning or validity — and\n * Hebrew niqqud (U+05B0–U+05BC) is out of range too, so this is inert for every\n * other script.\n */\nexport function stripOptionalDiacritics(word: string): string {\n return word.replace(/[\\u064b-\\u0652\\u0670]/g, '');\n}\n\n/**\n * Check if a character is an ASCII letter.\n */\nexport function isAsciiLetter(char: string): boolean {\n return /[a-zA-Z]/.test(char);\n}\n\n/**\n * Check if a character is part of an ASCII identifier.\n */\nexport function isAsciiIdentifierChar(char: string): boolean {\n return /[a-zA-Z0-9_-]/.test(char);\n}\n","/**\n * Extraction Utilities\n *\n * Pure functions for extracting CSS selectors, string literals, URLs, and numbers\n * from input strings. These are language-independent and used by all tokenizers.\n */\n\nimport {\n isSelectorStart,\n isWhitespace,\n isAsciiIdentifierChar,\n isAsciiLetter,\n isQuote,\n isDigit,\n} from './token-utils';\n\n// =============================================================================\n// CSS Selector Tokenization\n// =============================================================================\n\n/**\n * Extract a CSS selector from the input string starting at pos.\n * CSS selectors are universal across languages.\n *\n * Supported formats:\n * - #id\n * - .class\n * - [attribute]\n * - [attribute=value]\n * - @attribute (shorthand)\n * - *property (CSS property shorthand)\n * - Complex selectors with combinators (limited)\n *\n * Method call handling:\n * - #dialog.showModal() → stops after #dialog (method call, not compound selector)\n * - #box.active → compound selector (no parens)\n *\n * NOTE: intentionally diverges from the semantic package's copy\n * (packages/semantic/src/tokenizers/extractors/css-selector.ts), which also\n * consumes pseudo-class/pseudo-element segments (#x:hover, .a:not(.b)). This\n * legacy version is only used by BaseTokenizer.trySelector (no semantic call\n * sites) and stays as-is.\n */\nexport function extractCssSelector(input: string, startPos: number): string | null {\n if (startPos >= input.length) return null;\n\n const char = input[startPos];\n if (!isSelectorStart(char)) return null;\n\n let pos = startPos;\n let selector = '';\n\n // Handle different selector types\n if (char === '#' || char === '.') {\n // ID or class selector: #id, .class\n selector += input[pos++];\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n // Must have at least one character after prefix\n if (selector.length <= 1) return null;\n\n // Check for method call pattern: #id.method() or .class.method()\n // If we see .identifier followed by (, don't consume it - it's a method call\n if (pos < input.length && input[pos] === '.' && char === '#') {\n // Look ahead to see if this is a method call\n const methodStart = pos + 1;\n let methodEnd = methodStart;\n while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {\n methodEnd++;\n }\n // If followed by (, it's a method call - stop here\n if (methodEnd < input.length && input[methodEnd] === '(') {\n return selector;\n }\n }\n } else if (char === '[') {\n // Attribute selector: [attr] or [attr=value] or [attr=\"value\"]\n // Need to track quote state to avoid counting brackets inside quotes\n let depth = 1;\n let inQuote = false;\n let quoteChar: string | null = null;\n let escaped = false;\n\n selector += input[pos++]; // [\n\n while (pos < input.length && depth > 0) {\n const c = input[pos];\n selector += c;\n\n if (escaped) {\n // Skip escaped character\n escaped = false;\n } else if (c === '\\\\') {\n // Next character is escaped\n escaped = true;\n } else if (inQuote) {\n // Inside a quoted string\n if (c === quoteChar) {\n inQuote = false;\n quoteChar = null;\n }\n } else {\n // Not inside a quoted string\n if (c === '\"' || c === \"'\" || c === '`') {\n inQuote = true;\n quoteChar = c;\n } else if (c === '[') {\n depth++;\n } else if (c === ']') {\n depth--;\n }\n }\n pos++;\n }\n if (depth !== 0) return null;\n } else if (char === '@') {\n // Attribute shorthand: @disabled\n selector += input[pos++];\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n if (selector.length <= 1) return null;\n } else if (char === '*') {\n // CSS property shorthand: *display\n selector += input[pos++];\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n if (selector.length <= 1) return null;\n } else if (char === '<') {\n // HTML literal selector with optional modifiers and attributes:\n // - <div>\n // - <div.class>\n // - <div#id>\n // - <div.class#id>\n // - <button[disabled]/>\n // - <div.card/>\n // - <div.class#id[attr=\"value\"]/>\n selector += input[pos++]; // <\n\n // Must be followed by an identifier (tag name)\n if (pos >= input.length || !isAsciiLetter(input[pos])) return null;\n\n // Extract tag name\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n\n // Process modifiers and attributes\n // Can have multiple .class, one #id, and multiple [attr] in any order\n while (pos < input.length) {\n const modChar = input[pos];\n\n if (modChar === '.') {\n // Class modifier\n selector += input[pos++]; // .\n if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {\n return null; // Invalid - class name required after .\n }\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n } else if (modChar === '#') {\n // ID modifier\n selector += input[pos++]; // #\n if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {\n return null; // Invalid - ID required after #\n }\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n } else if (modChar === '[') {\n // Attribute modifier: [disabled] or [type=\"button\"]\n // Need to track quote state to avoid counting brackets inside quotes\n let depth = 1;\n let inQuote = false;\n let quoteChar: string | null = null;\n let escaped = false;\n\n selector += input[pos++]; // [\n\n while (pos < input.length && depth > 0) {\n const c = input[pos];\n selector += c;\n\n if (escaped) {\n escaped = false;\n } else if (c === '\\\\') {\n escaped = true;\n } else if (inQuote) {\n if (c === quoteChar) {\n inQuote = false;\n quoteChar = null;\n }\n } else {\n if (c === '\"' || c === \"'\" || c === '`') {\n inQuote = true;\n quoteChar = c;\n } else if (c === '[') {\n depth++;\n } else if (c === ']') {\n depth--;\n }\n }\n pos++;\n }\n if (depth !== 0) return null; // Unclosed bracket\n } else {\n // No more modifiers\n break;\n }\n }\n\n // Skip whitespace before optional self-closing /\n while (pos < input.length && isWhitespace(input[pos])) {\n selector += input[pos++];\n }\n\n // Optional self-closing /\n if (pos < input.length && input[pos] === '/') {\n selector += input[pos++];\n // Skip whitespace after /\n while (pos < input.length && isWhitespace(input[pos])) {\n selector += input[pos++];\n }\n }\n\n // Must end with >\n if (pos >= input.length || input[pos] !== '>') return null;\n selector += input[pos++]; // >\n }\n\n return selector || null;\n}\n\n// =============================================================================\n// String Literal Tokenization\n// =============================================================================\n\n/**\n * Check if a single quote at pos is a possessive marker ('s).\n * Returns true if this looks like possessive, not a string start.\n *\n * Examples:\n * - #element's *opacity → possessive (returns true)\n * - 'hello' → string (returns false)\n * - it's value → possessive (returns true)\n */\nexport function isPossessiveMarker(input: string, pos: number): boolean {\n if (pos >= input.length || input[pos] !== \"'\") return false;\n\n // Check if followed by 's' or 'S'\n if (pos + 1 >= input.length) return false;\n const nextChar = input[pos + 1].toLowerCase();\n if (nextChar !== 's') return false;\n\n // After 's, should be end, whitespace, or special char (not alphanumeric)\n if (pos + 2 >= input.length) return true; // end of input\n const afterS = input[pos + 2];\n return isWhitespace(afterS) || afterS === '*' || !isAsciiIdentifierChar(afterS);\n}\n\n/**\n * Extract a string literal from the input starting at pos.\n * Handles both ASCII quotes and Unicode quotes.\n *\n * Note: Single quotes that look like possessive markers ('s) are skipped.\n */\nexport function extractStringLiteral(input: string, startPos: number): string | null {\n if (startPos >= input.length) return null;\n\n const openQuote = input[startPos];\n if (!isQuote(openQuote)) return null;\n\n // Check for possessive marker - don't treat as string\n if (openQuote === \"'\" && isPossessiveMarker(input, startPos)) {\n return null;\n }\n\n // Map opening quotes to closing quotes\n const closeQuoteMap: Record<string, string> = {\n '\"': '\"',\n \"'\": \"'\",\n '`': '`',\n '「': '」',\n };\n\n const closeQuote = closeQuoteMap[openQuote];\n if (!closeQuote) return null;\n\n let pos = startPos + 1;\n let literal = openQuote;\n let escaped = false;\n\n while (pos < input.length) {\n const char = input[pos];\n literal += char;\n\n if (escaped) {\n escaped = false;\n } else if (char === '\\\\') {\n escaped = true;\n } else if (char === closeQuote) {\n // Found closing quote\n return literal;\n }\n pos++;\n }\n\n // Unclosed string - return what we have\n return literal;\n}\n\n// =============================================================================\n// URL Tokenization\n// =============================================================================\n\n/**\n * Check if the input at position starts a URL.\n * Detects: /path, ./path, ../path, //domain.com, http://, https://\n */\nexport function isUrlStart(input: string, pos: number): boolean {\n if (pos >= input.length) return false;\n\n const char = input[pos];\n const next = input[pos + 1] || '';\n const third = input[pos + 2] || '';\n\n // Absolute path: /something (but not just /)\n // Must be followed by alphanumeric or path char, not another / (that's protocol-relative)\n if (char === '/' && next !== '/' && /[a-zA-Z0-9._-]/.test(next)) {\n return true;\n }\n\n // Protocol-relative: //domain.com\n if (char === '/' && next === '/' && /[a-zA-Z]/.test(third)) {\n return true;\n }\n\n // Relative path: ./ or ../\n if (char === '.' && (next === '/' || (next === '.' && third === '/'))) {\n return true;\n }\n\n // Full URL: http:// or https://\n const slice = input.slice(pos, pos + 8).toLowerCase();\n if (slice.startsWith('http://') || slice.startsWith('https://')) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Extract a URL from the input starting at pos.\n * Handles paths, query strings, and fragments.\n *\n * Fragment (#) handling:\n * - /page#section → includes fragment as part of URL\n * - #id alone → not a URL (CSS selector)\n */\nexport function extractUrl(input: string, startPos: number): string | null {\n if (!isUrlStart(input, startPos)) return null;\n\n let pos = startPos;\n let url = '';\n\n // Core URL characters (RFC 3986 unreserved + sub-delims + path/query chars)\n // Includes: letters, digits, and - . _ ~ : / ? # [ ] @ ! $ & ' ( ) * + , ; = %\n const urlChars = /[a-zA-Z0-9/:._\\-?&=%@+~!$'()*,;[\\]]/;\n\n while (pos < input.length) {\n const char = input[pos];\n\n // Special handling for #\n if (char === '#') {\n // Only include # if we have path content before it (it's a fragment)\n // If # appears at URL start or after certain chars, stop (might be CSS selector)\n if (url.length > 0 && /[a-zA-Z0-9/.]$/.test(url)) {\n // Include fragment\n url += char;\n pos++;\n // Consume fragment identifier (letters, digits, underscore, hyphen)\n while (pos < input.length && /[a-zA-Z0-9_-]/.test(input[pos])) {\n url += input[pos++];\n }\n }\n // Stop either way - fragment consumed or # is separate token\n break;\n }\n\n if (urlChars.test(char)) {\n url += char;\n pos++;\n } else {\n break;\n }\n }\n\n // Minimum length validation\n if (url.length < 2) return null;\n\n return url;\n}\n\n// =============================================================================\n// Number Tokenization\n// =============================================================================\n\n/**\n * Extract a number from the input starting at pos.\n * Handles integers and decimals.\n */\nexport function extractNumber(input: string, startPos: number): string | null {\n if (startPos >= input.length) return null;\n\n const char = input[startPos];\n if (!isDigit(char) && char !== '-' && char !== '+') return null;\n\n let pos = startPos;\n let number = '';\n\n // Optional sign\n if (input[pos] === '-' || input[pos] === '+') {\n number += input[pos++];\n }\n\n // Must have at least one digit\n if (pos >= input.length || !isDigit(input[pos])) {\n return null;\n }\n\n // Integer part\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n\n // Optional decimal part\n if (pos < input.length && input[pos] === '.') {\n number += input[pos++];\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n }\n\n // Optional duration suffix (s, ms, m, h)\n if (pos < input.length) {\n const suffix = input.slice(pos, pos + 2);\n if (suffix === 'ms') {\n number += 'ms';\n } else if (input[pos] === 's' || input[pos] === 'm' || input[pos] === 'h') {\n number += input[pos];\n }\n }\n\n return number;\n}\n","/**\n * Operator Extractor - Handles programming language operators\n *\n * Extracts operators like +, -, *, /, =, >, <, >=, <=, !=, ===, etc.\n * Supports multi-character operators with longest-match priority.\n */\n\nimport type { ValueExtractor, ExtractionResult } from '../../../interfaces/value-extractor';\n\n/**\n * Default operators for most programming languages.\n * Sorted longest-first for greedy matching.\n */\nexport const DEFAULT_OPERATORS = [\n // Three-character operators\n '===',\n '!==',\n '->',\n // Two-character operators\n '==',\n '!=',\n '<=',\n '>=',\n '&&',\n '||',\n '**',\n '+=',\n '-=',\n '*=',\n '/=',\n // Single-character operators\n '+',\n '-',\n '*',\n '/',\n '=',\n '>',\n '<',\n '!',\n '&',\n '|',\n '%',\n '^',\n '~',\n];\n\n/**\n * OperatorExtractor - Extracts programming language operators.\n */\nexport class OperatorExtractor implements ValueExtractor {\n readonly name = 'operator';\n\n constructor(private operators: string[] = DEFAULT_OPERATORS) {\n // Sort operators longest-first for greedy matching\n this.operators = [...operators].sort((a, b) => b.length - a.length);\n }\n\n canExtract(input: string, position: number): boolean {\n return this.operators.some(op => input.startsWith(op, position));\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n // Find longest matching operator\n for (const op of this.operators) {\n if (input.startsWith(op, position)) {\n return {\n value: op,\n length: op.length,\n };\n }\n }\n\n return null;\n }\n}\n","/**\n * Punctuation Extractor - Handles punctuation characters\n *\n * Extracts punctuation like parentheses, brackets, braces, commas, colons, semicolons.\n * Each character is extracted individually (no multi-character punctuation).\n */\n\nimport type { ValueExtractor, ExtractionResult } from '../../../interfaces/value-extractor';\n\n/**\n * Default punctuation characters for most programming languages.\n */\nexport const DEFAULT_PUNCTUATION = '()[]{},:;';\n\n/**\n * PunctuationExtractor - Extracts punctuation characters.\n */\nexport class PunctuationExtractor implements ValueExtractor {\n readonly name = 'punctuation';\n\n constructor(private punctuation: string = DEFAULT_PUNCTUATION) {}\n\n canExtract(input: string, position: number): boolean {\n return this.punctuation.includes(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n const char = input[position];\n\n if (this.punctuation.includes(char)) {\n return {\n value: char,\n length: 1,\n };\n }\n\n return null;\n }\n}\n","/**\n * Default Extractor Sets\n *\n * Provides pre-configured sets of extractors for common use cases.\n * DSLs can use these as a starting point and add domain-specific extractors.\n */\n\nimport type { ValueExtractor } from '../../interfaces/value-extractor';\nimport {\n StringLiteralExtractor,\n NumberExtractor,\n IdentifierExtractor,\n UnicodeIdentifierExtractor,\n} from '../../interfaces/value-extractor';\nimport { OperatorExtractor, PunctuationExtractor } from './extractors/index';\n\n/**\n * Get default extractors for generic programming-language-style DSLs.\n * These work for most DSLs (SQL, config files, scripts, etc.).\n *\n * Included extractors:\n * - String literals: \"double\", 'single', `backtick`\n * - Numbers: 123, 45.67\n * - Operators: +, -, *, /, =, ==, !=, >=, <=, etc.\n * - Punctuation: ( ) [ ] { } , : ;\n * - Identifiers: variable_names, functionNames\n * - Unicode identifiers: CJK, Arabic, Cyrillic, etc.\n *\n * @returns Array of default extractors\n *\n * @example\n * ```typescript\n * class MyDSLTokenizer extends BaseTokenizer {\n * constructor() {\n * super();\n * this.registerExtractors(getDefaultExtractors());\n * }\n * }\n * ```\n */\nexport function getDefaultExtractors(): ValueExtractor[] {\n return [\n new StringLiteralExtractor(), // \"strings\", 'strings', `strings`\n new NumberExtractor(), // 123, 45.67\n new OperatorExtractor(), // +, -, *, /, =, >, <, etc.\n new PunctuationExtractor(), // ( ) [ ] { } , : ;\n new IdentifierExtractor(), // variable_names, functionNames (ASCII)\n new UnicodeIdentifierExtractor(), // CJK, Arabic, Cyrillic, etc.\n ];\n}\n\n/**\n * Auto-register default extractors in a tokenizer.\n * Convenience helper for chaining.\n *\n * @param tokenizer - Tokenizer to configure\n * @returns The same tokenizer (for chaining)\n *\n * @example\n * ```typescript\n * const tokenizer = withDefaultExtractors(new MyTokenizer());\n * ```\n */\nexport function withDefaultExtractors<\n T extends { registerExtractors(extractors: ValueExtractor[]): void },\n>(tokenizer: T): T {\n tokenizer.registerExtractors(getDefaultExtractors());\n return tokenizer;\n}\n","/**\n * Base Tokenizer Class\n *\n * Abstract base class for language-specific tokenizers.\n * Provides keyword management, morphological normalization,\n * and high-level token extraction methods.\n */\n\nimport type { LanguageToken, TokenKind, TokenStream, LanguageTokenizer } from '../types';\nimport type { MorphologicalNormalizer, NormalizationResult } from './morphology/types';\nimport {\n type ValueExtractor,\n type KeywordEntry,\n isContextAwareExtractor,\n createTokenizerContext,\n} from '../../interfaces/value-extractor';\nimport {\n createToken,\n createPosition,\n isWhitespace,\n isDigit,\n isAsciiIdentifierChar,\n stripOptionalDiacritics,\n TokenStreamImpl,\n type TimeUnitMapping,\n type CreateTokenOptions,\n} from './token-utils';\nimport { extractCssSelector, extractStringLiteral, extractNumber, extractUrl } from './extractors';\nimport { DEFAULT_OPERATORS } from './extractors/operator';\nimport { getDefaultExtractors } from './default-extractors';\n\n// Module-scope operator set for O(1) lookup in createSimpleTokenizer.\n// Uses the canonical list from OperatorExtractor to avoid duplication.\nconst SIMPLE_TOKENIZER_OPERATOR_SET = new Set(DEFAULT_OPERATORS);\n\n/**\n * Normalized concepts that are matched via the pattern matcher's ROLE-MARKER\n * MECHANISM (the source/destination/event clause matchers in\n * `packages/semantic/src/parser/pattern-matcher.ts`), which peeks/advances a\n * SINGLE token and checks `.value`/`.normalized`. A multi-word phrase carrying\n * one of these must NOT be pre-matched as a single keyword token — doing so\n * shadows the single-word marker those clause matchers expect (e.g. id\n * `ke dalam`=into hides the `ke` destination marker; ko `할 때`=eventMarker\n * pre-empts SOV event extraction).\n *\n * NOTE — what is *not* here. Prepositional modifiers that the generated patterns\n * expose as ordinary pattern LITERALS (`before`/`after` in put-before/after,\n * `until` in repeat-until) are deliberately absent: those are read by\n * `matchLiteralToken`, which compares the whole token by exact value OR\n * normalized form (`getMatchType`), so a multi-word marker token (`से पहले`,\n * `cho đến khi`) matches the literal's value/alternatives directly with no\n * special handling. Keeping them out lets `tryMultiWordKeyword` emit them as one\n * token — the profile-driven replacement for the per-language hardcoded compound\n * lists (Task #10). `into` stays excluded because it IS consumed by the role\n * mechanism in some languages (id destination `ke`), and `from`/`to`/`with`/\n * `on`/`at`/`of`/`as`/`by`/`in` are genuine role markers. Command verbs /\n * control-flow / event names were always absent. See `multiWordKeywords` /\n * `tryMultiWordKeyword`.\n */\nconst MARKER_CONCEPT_NORMALIZEDS: ReadonlySet<string> = new Set([\n // Role-marker role names (profile.roleMarkers normalizeds)\n 'patient',\n 'destination',\n 'source',\n 'style',\n 'event',\n 'eventMarker',\n 'agent',\n 'goal',\n 'manner',\n // Prepositional / positional modifier concepts matched via the role mechanism\n // (profile.keywords \"Modifiers\"). `before`/`after`/`until` are intentionally\n // NOT here — they are pattern literals (see the note above).\n 'into',\n 'from',\n 'to',\n 'with',\n 'at',\n 'of',\n 'as',\n 'by',\n 'in',\n 'on',\n 'over',\n 'under',\n 'between',\n 'through',\n 'without',\n]);\n\n// =============================================================================\n// Types\n// =============================================================================\n\n// KeywordEntry is imported from interfaces/value-extractor and re-exported\n// for backward compatibility with code importing from this module.\nexport type { KeywordEntry };\n\n/**\n * Standard DOM event names recognized in every language as universal fallbacks.\n * The i18n grammar transformer emits these verbatim (no native dictionary form),\n * so each tokenizer must accept them or English-named event handlers won't parse.\n * Kept to genuine DOM event names (not command verbs) to minimize collisions; the\n * registration is `!has`-guarded so any native keyword of the same spelling wins.\n */\nconst ENGLISH_DOM_EVENT_NAMES: readonly string[] = [\n 'click',\n 'dblclick',\n 'input',\n 'change',\n 'submit',\n 'keydown',\n 'keyup',\n 'keypress',\n 'mousedown',\n 'mouseup',\n 'mouseover',\n 'mouseout',\n 'mouseenter',\n 'mouseleave',\n 'mousemove',\n 'pointerdown',\n 'pointerup',\n 'pointermove',\n 'focus',\n 'blur',\n 'load',\n 'resize',\n 'scroll',\n];\n\n/**\n * Profile interface for keyword derivation.\n * Matches the structure of LanguageProfile but only includes fields needed for tokenization.\n */\nexport interface TokenizerProfile {\n readonly keywords?: Record<\n string,\n { primary: string; alternatives?: string[]; normalized?: string }\n >;\n readonly references?: Record<string, string>;\n readonly roleMarkers?: Record<\n string,\n { primary: string; alternatives?: string[]; position?: string }\n >;\n readonly possessive?: {\n readonly marker: string;\n readonly markerPosition: 'after-object' | 'between' | 'before-property';\n readonly specialForms?: Record<string, string>;\n readonly usePossessiveAdjectives?: boolean;\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Base Tokenizer Class\n// =============================================================================\n\n/**\n * Abstract base class for language-specific tokenizers.\n * Provides common functionality for CSS selectors, strings, and numbers.\n */\nexport abstract class BaseTokenizer implements LanguageTokenizer {\n abstract readonly language: string;\n abstract readonly direction: 'ltr' | 'rtl';\n\n /** Optional morphological normalizer for this language */\n protected normalizer?: MorphologicalNormalizer;\n\n /** Keywords derived from profile, sorted longest-first for greedy matching */\n protected profileKeywords: KeywordEntry[] = [];\n\n /**\n * Space-containing profile keywords (multi-word phrases), longest-first.\n * Used by `tryMultiWordKeyword` so natural spaced forms (hi `मेल खाता`,\n * vi `chuyển đổi`, es `tecla abajo`, …) tokenize as ONE keyword — the\n * profile-driven replacement for the per-language hardcoded compound lists.\n * Empty for no-space (CJK) languages, so they are unaffected.\n */\n protected multiWordKeywords: KeywordEntry[] = [];\n\n /** Map for O(1) keyword lookups by lowercase native word */\n protected profileKeywordMap: Map<string, KeywordEntry> = new Map();\n\n /**\n * The raw EXTRAS list passed to initializeKeywordsFromProfile, kept pre-dedup.\n * The keyword map is keyed by native word with last-wins insertion, so a\n * duplicate native word inside the extras silently shadows the earlier entry\n * (e.g. a `nächste→closest` entry shadowing `nächste→next` broke German\n * positional expressions). Exposed so consistency tests can detect such\n * intra-extras collisions, which are invisible in the deduplicated map.\n */\n private rawExtraEntries: KeywordEntry[] = [];\n\n /** Raw extras as passed in, pre-dedup — for consistency tests. */\n getExtraKeywordEntries(): readonly KeywordEntry[] {\n return this.rawExtraEntries;\n }\n\n /**\n * Pluggable value extractors for domain-specific syntax.\n * When registered, BaseTokenizer will use extractor-based tokenization instead of legacy methods.\n */\n protected extractors: ValueExtractor[] = [];\n\n /**\n * Tokenize input string to token stream.\n * Delegates to extractor-based tokenization if extractors are registered,\n * otherwise subclass must override this method.\n *\n * @param input - Input string to tokenize\n * @returns Token stream\n */\n tokenize(input: string): TokenStream {\n if (this.isUsingExtractors()) {\n return this.tokenizeWithExtractors(input);\n }\n\n // If no extractors registered, subclass must provide implementation\n throw new Error(\n `${this.constructor.name}: tokenize() not implemented and no extractors registered. ` +\n 'Either register extractors or override tokenize() method.'\n );\n }\n\n abstract classifyToken(token: string): TokenKind;\n\n /**\n * Register a value extractor for domain-specific syntax.\n * Extractors are tried in registration order during tokenization.\n * Context-aware extractors automatically receive the tokenizer context.\n *\n * @param extractor - Value extractor to register\n */\n registerExtractor(extractor: ValueExtractor): void {\n if (isContextAwareExtractor(extractor)) {\n extractor.setContext(createTokenizerContext(this as any));\n }\n this.extractors.push(extractor);\n }\n\n /**\n * Register multiple value extractors at once.\n *\n * @param extractors - Array of value extractors to register\n */\n registerExtractors(extractors: ValueExtractor[]): void {\n for (const extractor of extractors) {\n this.registerExtractor(extractor);\n }\n }\n\n /**\n * Clear all registered extractors.\n * Returns tokenizer to legacy mode.\n */\n clearExtractors(): void {\n this.extractors = [];\n }\n\n /**\n * Check if this tokenizer is using extractor-based tokenization.\n * Returns true if any extractors are registered.\n */\n protected isUsingExtractors(): boolean {\n return this.extractors.length > 0;\n }\n\n /**\n * Tokenize input using registered value extractors.\n * This is the new path - extractors handle all syntax detection.\n *\n * @param input - Input string to tokenize\n * @returns Token stream\n */\n protected tokenizeWithExtractors(input: string): TokenStream {\n const tokens: LanguageToken[] = [];\n let pos = 0;\n\n while (pos < input.length) {\n // Skip whitespace\n while (pos < input.length && isWhitespace(input[pos])) {\n pos++;\n }\n if (pos >= input.length) break;\n\n // Multi-word keyword pre-match: a profile keyword containing a space\n // (e.g. hi `मेल खाता`, vi `chuyển đổi`, es `tecla abajo`) is matched as ONE\n // keyword token at a word boundary, longest-first. Runs before the\n // per-language extractors so natural spaced multi-word keywords tokenize\n // without each tokenizer hardcoding a compound list. No-op for single-word\n // and no-space (CJK) languages (multiWordKeywords is empty).\n const multiWord = this.tryMultiWordKeyword(input, pos);\n if (multiWord) {\n tokens.push(multiWord);\n pos = multiWord.position.end;\n continue;\n }\n\n // Try registered extractors in order\n let extracted = false;\n for (const extractor of this.extractors) {\n if (extractor.canExtract(input, pos)) {\n const result = extractor.extract(input, pos);\n if (result) {\n // Promote normalized/stem/stemConfidence from metadata to top-level token options\n const normalized = result.metadata?.normalized as string | undefined;\n const stem = result.metadata?.stem as string | undefined;\n const stemConfidence = result.metadata?.stemConfidence as number | undefined;\n\n // Build clean metadata without promoted fields\n const cleanMetadata: Record<string, unknown> = {};\n if (result.metadata) {\n for (const [key, value] of Object.entries(result.metadata)) {\n if (key !== 'normalized' && key !== 'stem' && key !== 'stemConfidence') {\n cleanMetadata[key] = value;\n }\n }\n }\n\n const options: CreateTokenOptions = {};\n if (normalized) options.normalized = normalized;\n if (stem) options.stem = stem;\n if (stemConfidence !== undefined) options.stemConfidence = stemConfidence;\n if (Object.keys(cleanMetadata).length > 0) options.metadata = cleanMetadata;\n\n tokens.push(\n createToken(\n result.value,\n this.classifyToken(result.value),\n createPosition(pos, pos + result.length),\n Object.keys(options).length > 0 ? options : undefined\n )\n );\n pos += result.length;\n extracted = true;\n break;\n }\n }\n }\n\n // Fallback: single character as operator/punctuation\n if (!extracted) {\n const char = input[pos];\n const kind = this.classifyUnknownChar(char);\n tokens.push(createToken(char, kind, createPosition(pos, pos + 1)));\n pos++;\n }\n }\n\n return new TokenStreamImpl(this.mergeColonQualifiedNames(tokens), this.language);\n }\n\n /**\n * ASCII word of the shape the English word-walker produces. Excludes `:`, so a\n * token that already carries a qualifier never merges again — `a:b:c` yields\n * `a:b` + `:c`, byte-matching the English extractor's single-segment merge.\n */\n private static readonly ASCII_WORD = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n /** `:name` — only a variable-ref-style extractor ever emits this token shape. */\n private static readonly COLON_QUALIFIER = /^:[A-Za-z_][A-Za-z0-9_]*$/;\n\n /**\n * Fuse `name` + `:qualifier` into ONE identifier (`draggable:start`).\n *\n * `:name` is hyperscript's local-variable sigil, but a colon IMMEDIATELY\n * preceded by an identifier is a qualifier (custom event namespace), not a\n * sigil. The English tokenizer already merges these inside\n * EnglishKeywordExtractor; this post-pass gives the other 23 languages the\n * same stream. Strict position adjacency is the discriminator: whitespace\n * between the tokens (`trigger :start`) breaks `end === start`, so a spaced\n * local-variable reference survives untouched.\n *\n * Self-gating for non-hyperscript tokenizers (domain DSLs): their extractor\n * sets tokenize `:` as bare punctuation (length 1), which never matches\n * COLON_QUALIFIER, so this pass is a no-op for them.\n */\n protected mergeColonQualifiedNames(tokens: LanguageToken[]): LanguageToken[] {\n const out: LanguageToken[] = [];\n for (const tok of tokens) {\n const prev = out[out.length - 1];\n // No kind gate: the English extractor merges before classification, so a\n // word some language classifies as particle/keyword (es `a`, tr `i`)\n // must fuse the same way. ASCII_WORD already excludes every non-word\n // kind structurally (selectors, urls, numbers, strings, operators).\n if (\n prev &&\n BaseTokenizer.ASCII_WORD.test(prev.value) &&\n BaseTokenizer.COLON_QUALIFIER.test(tok.value) &&\n prev.position.end === tok.position.start\n ) {\n const merged = prev.value + tok.value;\n // Re-classify and drop normalized/stem/metadata — the merged word is no\n // longer the keyword the pieces may have been (matches the en shape).\n out[out.length - 1] = createToken(\n merged,\n this.classifyToken(merged),\n createPosition(prev.position.start, tok.position.end)\n );\n continue;\n }\n out.push(tok);\n }\n return out;\n }\n\n /**\n * Classify an unknown character when no extractor matches.\n * Provides sensible defaults for common syntax.\n *\n * @param char - Character to classify\n * @returns Token kind\n */\n protected classifyUnknownChar(char: string): TokenKind {\n if ('()[]{},:;'.includes(char)) return 'punctuation';\n if ('+-*/<>=!&|'.includes(char)) return 'operator';\n return 'identifier';\n }\n\n /**\n * Check if current position is a property access (obj.prop) vs CSS selector (.active).\n * Property access: no whitespace before '.', previous token is identifier/keyword/selector.\n * Also detects standalone method calls: .identifier( pattern.\n *\n * Returns true if '.' was emitted as an operator token and pos should advance by 1.\n * Returns false if this is a CSS selector and should be handled by trySelector().\n */\n protected tryPropertyAccess(input: string, pos: number, tokens: LanguageToken[]): boolean {\n if (input[pos] !== '.') return false;\n\n const lastToken = tokens[tokens.length - 1];\n // Property access requires NO whitespace between tokens (e.g., \"obj.prop\")\n const hasWhitespaceBefore = lastToken && lastToken.position.end < pos;\n const isPropertyAccess =\n lastToken &&\n !hasWhitespaceBefore &&\n (lastToken.kind === 'identifier' ||\n lastToken.kind === 'keyword' ||\n lastToken.kind === 'selector');\n\n if (isPropertyAccess) {\n tokens.push(createToken('.', 'operator', createPosition(pos, pos + 1)));\n return true;\n }\n\n // Check for method call pattern at start: .identifier(\n const methodStart = pos + 1;\n let methodEnd = methodStart;\n while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {\n methodEnd++;\n }\n if (methodEnd < input.length && input[methodEnd] === '(') {\n tokens.push(createToken('.', 'operator', createPosition(pos, pos + 1)));\n return true;\n }\n\n return false;\n }\n\n /**\n * Initialize keyword mappings from a language profile.\n * Builds a list of native→english mappings from:\n * - profile.keywords (primary + alternatives)\n * - profile.references (me, it, you, etc.)\n * - profile.roleMarkers (into, from, with, etc.)\n *\n * Results are sorted longest-first for greedy matching (important for non-space languages).\n * Extras take precedence over profile entries when there are duplicates.\n *\n * @param profile - Language profile containing keyword translations\n * @param extras - Additional keyword entries to include (literals, positional, events)\n */\n protected initializeKeywordsFromProfile(\n profile: TokenizerProfile,\n extras: KeywordEntry[] = []\n ): void {\n // Use a Map to deduplicate, with extras taking precedence\n const keywordMap = new Map<string, KeywordEntry>();\n this.rawExtraEntries = extras;\n\n // Extract from keywords (command translations)\n if (profile.keywords) {\n for (const [normalized, translation] of Object.entries(profile.keywords)) {\n // Primary translation\n keywordMap.set(translation.primary, {\n native: translation.primary,\n normalized: translation.normalized || normalized,\n });\n\n // Alternative forms\n if (translation.alternatives) {\n for (const alt of translation.alternatives) {\n keywordMap.set(alt, {\n native: alt,\n normalized: translation.normalized || normalized,\n });\n }\n }\n }\n }\n\n // Extract from references (me, it, you, etc.)\n if (profile.references) {\n for (const [normalized, native] of Object.entries(profile.references)) {\n keywordMap.set(native, { native, normalized });\n }\n // Also register English canonical forms as universal fallbacks.\n // Users frequently mix English references (me, it, you) into non-English\n // hyperscript (e.g., \"alternar .active on me\"). Without this, the English\n // word \"me\" would be unrecognized in non-English token streams.\n for (const canonical of Object.keys(profile.references)) {\n if (!keywordMap.has(canonical)) {\n keywordMap.set(canonical, { native: canonical, normalized: canonical });\n }\n }\n }\n\n // Extract from roleMarkers (into, from, with, etc.)\n if (profile.roleMarkers) {\n for (const [role, marker] of Object.entries(profile.roleMarkers)) {\n if (marker.primary) {\n keywordMap.set(marker.primary, { native: marker.primary, normalized: role });\n }\n if (marker.alternatives) {\n for (const alt of marker.alternatives) {\n keywordMap.set(alt, { native: alt, normalized: role });\n }\n }\n }\n }\n\n // Extract from possessive keywords (e.g., ñuqapa, qampa for Quechua)\n if (profile.possessive?.keywords) {\n for (const [native, normalized] of Object.entries(profile.possessive.keywords)) {\n keywordMap.set(native, { native, normalized });\n }\n }\n\n // Register English DOM event names as universal fallbacks. The i18n grammar\n // transformer has no native form for most DOM events, so it passes them\n // through verbatim (`on keyup …` → `<on-marker> keyup …`). Without these,\n // non-English token streams treat `keyup`/`keydown`/`resize`/… as bare\n // identifiers, and event handlers using them (often with `[key==…]` guards)\n // fail to parse. Guarded by `!has` so any native mapping wins (same policy\n // as the English-reference fallbacks above). Generalizes the per-language\n // registration introduced for Hebrew in #272.\n for (const evt of ENGLISH_DOM_EVENT_NAMES) {\n if (!keywordMap.has(evt)) {\n keywordMap.set(evt, { native: evt, normalized: evt });\n }\n }\n\n // Add extra entries (literals, positional, events) - these OVERRIDE profile entries\n for (const extra of extras) {\n keywordMap.set(extra.native, extra);\n }\n\n // Convert to array and sort longest-first for greedy matching\n this.profileKeywords = Array.from(keywordMap.values()).sort(\n (a, b) => b.native.length - a.native.length\n );\n\n // Multi-word (space-containing) keywords, for longest-phrase matching at a\n // token boundary. Already longest-first (profileKeywords is sorted above).\n // Marker/modifier concepts are EXCLUDED: those are matched positionally by\n // the pattern matcher (role markers), and greedily consuming a multi-word\n // marker phrase shadows the single-word marker patterns rely on — e.g. id\n // `ke dalam` (into) would swallow the `ke` destination marker, and ko `할 때`\n // (eventMarker) would pre-empt the SOV event extraction. Command verbs,\n // control-flow, and event-name keywords (vi `với mỗi`=for, es `tecla abajo`=\n // keydown, bn `তৈরি করুন`=make) are kept — the pattern matcher treats those\n // as keyword literals, so one-token matching is strictly better.\n this.multiWordKeywords = this.profileKeywords.filter(\n k => k.native.includes(' ') && !MARKER_CONCEPT_NORMALIZEDS.has(k.normalized)\n );\n\n // Build Map for O(1) lookups (case-insensitive + diacritic-insensitive)\n // This allows matching both 'بدّل' (with shadda) and 'بدل' (without) to the same entry\n this.profileKeywordMap = new Map();\n for (const keyword of this.profileKeywords) {\n // Add original form (with diacritics if present)\n this.profileKeywordMap.set(keyword.native.toLowerCase(), keyword);\n\n // Add diacritic-normalized form (for Arabic, Turkish, etc.)\n const normalized = this.removeDiacritics(keyword.native);\n if (normalized !== keyword.native && !this.profileKeywordMap.has(normalized.toLowerCase())) {\n this.profileKeywordMap.set(normalized.toLowerCase(), keyword);\n }\n }\n }\n\n /**\n * Remove diacritical marks from a word for normalization.\n * Primarily for Arabic (shadda, fatha, kasra, damma, sukun, etc.)\n * but could be extended for other languages.\n *\n * @param word - Word to normalize\n * @returns Word without diacritics\n */\n protected removeDiacritics(word: string): string {\n return stripOptionalDiacritics(word);\n }\n\n /**\n * Try to match a keyword from profile at the current position.\n * Uses longest-first greedy matching (important for non-space languages).\n *\n * @param input - Input string\n * @param pos - Current position\n * @returns Token if matched, null otherwise\n */\n protected tryProfileKeyword(input: string, pos: number): LanguageToken | null {\n for (const entry of this.profileKeywords) {\n if (input.slice(pos).startsWith(entry.native)) {\n return createToken(\n entry.native,\n 'keyword',\n createPosition(pos, pos + entry.native.length),\n entry.normalized\n );\n }\n }\n return null;\n }\n\n /**\n * Match the longest multi-word (space-containing) profile keyword at `pos`,\n * requiring the match to end at a word boundary. The profile-driven\n * counterpart of the per-language hardcoded compound lists (the hindi and\n * vietnamese keyword extractors). Returns a keyword token (with the normalized\n * form) or null. Case-sensitive against the stored native form, mirroring\n * `tryProfileKeyword`/`isKeywordStart` (the i18n dicts emit a fixed surface\n * case). No-op when `multiWordKeywords` is empty (no-space/CJK languages).\n *\n * @param input - Input string\n * @param pos - Current position (must be a token-start boundary)\n * @param isWordChar - End-boundary predicate (defaults to Unicode letter/digit/_)\n */\n protected tryMultiWordKeyword(\n input: string,\n pos: number,\n isWordChar: (char: string) => boolean = ch => /[\\p{L}\\p{N}_]/u.test(ch)\n ): LanguageToken | null {\n if (this.multiWordKeywords.length === 0) return null;\n const rest = input.slice(pos);\n for (const entry of this.multiWordKeywords) {\n if (!rest.startsWith(entry.native)) continue;\n const after = input[pos + entry.native.length];\n if (after !== undefined && isWordChar(after)) continue; // not a word boundary\n return createToken(\n entry.native,\n 'keyword',\n createPosition(pos, pos + entry.native.length),\n entry.normalized\n );\n }\n return null;\n }\n\n /**\n * Check if the remaining input starts with any known keyword.\n * Useful for non-space languages to detect word boundaries.\n *\n * @param input - Input string\n * @param pos - Current position\n * @returns true if a keyword starts at this position\n */\n protected isKeywordStart(input: string, pos: number): boolean {\n const remaining = input.slice(pos);\n return this.profileKeywords.some(entry => remaining.startsWith(entry.native));\n }\n\n /**\n * Check if a known keyword starts at the given position AND ends at a word\n * boundary (end of input or a non-word character).\n *\n * Space-delimited languages must use this (not `isKeywordStart`) for\n * word-walk break checks: the keyword table includes English canonical\n * fallbacks (me, it, you, …), so a raw `startsWith` check splits any native\n * word with an embedded fallback mid-word (e.g. Quechua ñit'iy contains\n * \"it\"). CJK/no-space tokenizers rely on mid-text keyword starts and must\n * keep using `isKeywordStart`.\n *\n * @param input - Input string\n * @param pos - Current position\n * @param isWordChar - Language-specific word-character predicate; pass the\n * tokenizer's letter classifier so e.g. the Quechua glottal apostrophe\n * counts as part of a word. Defaults to Unicode letters/digits/underscore.\n * @returns true if a keyword starts here and is not followed by a word char\n */\n protected isKeywordStartAtBoundary(\n input: string,\n pos: number,\n isWordChar: (char: string) => boolean = ch => /[\\p{L}\\p{N}_]/u.test(ch)\n ): boolean {\n const remaining = input.slice(pos);\n return this.profileKeywords.some(entry => {\n if (!remaining.startsWith(entry.native)) return false;\n const after = input[pos + entry.native.length];\n return after === undefined || !isWordChar(after);\n });\n }\n\n /**\n * Look up a keyword by native word (case-insensitive, diacritic-insensitive).\n * O(1) lookup using the keyword map.\n *\n * The map is INDEXED both with and without diacritics (see\n * `initializeKeywordsFromProfile`), so a stripped QUERY is the other half of\n * that: it lets a surface form carrying harakat the profile does not happen to\n * spell still find its entry. Only consulted after the exact lookup misses, so\n * every previously-matching word resolves byte-identically.\n *\n * Half-implementing this — indexing stripped but querying exact — is what made\n * diacritized `بَدِّل` (toggle) tokenize as `kind=particle normalized=with`:\n * `isKeyword` returned false, so the guard in `ArabicProcliticExtractor` that\n * exists to prevent exactly that handed the word on, and the single-char `ب`\n * bi- proclitic claimed it. A wrong CONCEPT, not a failed parse.\n *\n * @param native - Native word to look up\n * @returns KeywordEntry if found, undefined otherwise\n */\n protected lookupKeyword(native: string): KeywordEntry | undefined {\n const exact = this.profileKeywordMap.get(native.toLowerCase());\n if (exact) return exact;\n const stripped = this.removeDiacritics(native);\n if (stripped === native) return undefined;\n return this.profileKeywordMap.get(stripped.toLowerCase());\n }\n\n /**\n * Check if a word is a known keyword (case-insensitive, diacritic-insensitive).\n * O(1) lookup using the keyword map. See {@link lookupKeyword}.\n *\n * @param native - Native word to check\n * @returns true if the word is a keyword\n */\n protected isKeyword(native: string): boolean {\n return this.lookupKeyword(native) !== undefined;\n }\n\n /**\n * Set the morphological normalizer for this tokenizer.\n */\n setNormalizer(normalizer: MorphologicalNormalizer): void {\n this.normalizer = normalizer;\n }\n\n /**\n * Try to normalize a word using the morphological normalizer.\n * Returns null if no normalizer is set or normalization fails.\n *\n * Note: We don't check isNormalizable() here because the individual tokenizers\n * historically called normalize() directly without that check. The normalize()\n * method itself handles returning noChange() for words that can't be normalized.\n */\n protected tryNormalize(word: string): NormalizationResult | null {\n if (!this.normalizer) return null;\n\n const result = this.normalizer.normalize(word);\n\n // Only return if actually normalized (stem differs from input)\n if (result.stem !== word && result.confidence >= 0.7) {\n return result;\n }\n\n return null;\n }\n\n /**\n * Try morphological normalization and keyword lookup.\n *\n * If the word can be normalized to a stem that matches a known keyword,\n * returns a keyword token with morphological metadata (stem, stemConfidence).\n *\n * This is the common pattern for handling conjugated verbs across languages:\n * 1. Normalize the word (e.g., \"toggled\" → \"toggle\")\n * 2. Look up the stem in the keyword map\n * 3. Create a token with both the original form and stem metadata\n *\n * @param word - The word to normalize and look up\n * @param startPos - Start position for the token\n * @param endPos - End position for the token\n * @returns Token if stem matches a keyword, null otherwise\n */\n protected tryMorphKeywordMatch(\n word: string,\n startPos: number,\n endPos: number\n ): LanguageToken | null {\n const result = this.tryNormalize(word);\n if (!result) return null;\n\n // Check if the stem is a known keyword\n const stemEntry = this.lookupKeyword(result.stem);\n if (!stemEntry) return null;\n\n const tokenOptions: CreateTokenOptions = {\n normalized: stemEntry.normalized,\n stem: result.stem,\n stemConfidence: result.confidence,\n };\n return createToken(word, 'keyword', createPosition(startPos, endPos), tokenOptions);\n }\n\n /**\n * Try to extract a CSS selector at the current position.\n */\n protected trySelector(input: string, pos: number): LanguageToken | null {\n const selector = extractCssSelector(input, pos);\n if (selector) {\n return createToken(selector, 'selector', createPosition(pos, pos + selector.length));\n }\n return null;\n }\n\n /**\n * Try to extract an event modifier at the current position.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n */\n protected tryEventModifier(input: string, pos: number): LanguageToken | null {\n // Must start with a dot\n if (input[pos] !== '.') {\n return null;\n }\n\n // Match pattern: .(once|debounce|throttle|queue) followed by optional (value)\n const match = input\n .slice(pos)\n .match(/^\\.(?:once|debounce|throttle|queue)(?:\\(([^)]+)\\))?(?:\\s|$|\\.)/);\n if (!match) {\n return null;\n }\n\n const fullMatch = match[0].replace(/(\\s|\\.)$/, ''); // Remove trailing space or dot\n const modifierName = fullMatch.slice(1).split('(')[0]; // Extract modifier name\n const value = match[1]; // Extract value from parentheses if present\n\n // Create token with metadata\n const token = createToken(\n fullMatch,\n 'event-modifier',\n createPosition(pos, pos + fullMatch.length)\n );\n\n // Add metadata for the modifier\n return {\n ...token,\n metadata: {\n modifierName,\n value: value ? (modifierName === 'queue' ? value : parseInt(value, 10)) : undefined,\n },\n };\n }\n\n /**\n * Try to extract a string literal at the current position.\n */\n protected tryString(input: string, pos: number): LanguageToken | null {\n const literal = extractStringLiteral(input, pos);\n if (literal) {\n return createToken(literal, 'literal', createPosition(pos, pos + literal.length));\n }\n return null;\n }\n\n /**\n * Try to extract a number at the current position.\n */\n protected tryNumber(input: string, pos: number): LanguageToken | null {\n const number = extractNumber(input, pos);\n if (number) {\n return createToken(number, 'literal', createPosition(pos, pos + number.length));\n }\n return null;\n }\n\n /**\n * Configuration for native language time units.\n * Maps patterns to their standard suffix (ms, s, m, h).\n */\n protected static readonly STANDARD_TIME_UNITS: readonly TimeUnitMapping[] = [\n { pattern: 'ms', suffix: 'ms', length: 2 },\n { pattern: 's', suffix: 's', length: 1, checkBoundary: true },\n { pattern: 'm', suffix: 'm', length: 1, checkBoundary: true, notFollowedBy: 's' },\n { pattern: 'h', suffix: 'h', length: 1, checkBoundary: true },\n ];\n\n /**\n * Try to match a time unit from a list of patterns.\n *\n * @param input - Input string\n * @param pos - Position after the number\n * @param timeUnits - Array of time unit mappings (native pattern → standard suffix)\n * @param skipWhitespace - Whether to skip whitespace before time unit (default: false)\n * @returns Object with matched suffix and new position, or null if no match\n */\n protected tryMatchTimeUnit(\n input: string,\n pos: number,\n timeUnits: readonly TimeUnitMapping[],\n skipWhitespace = false\n ): { suffix: string; endPos: number } | null {\n let unitPos = pos;\n\n // Optionally skip whitespace before time unit\n if (skipWhitespace) {\n while (unitPos < input.length && isWhitespace(input[unitPos])) {\n unitPos++;\n }\n }\n\n const remaining = input.slice(unitPos);\n\n // Check each time unit pattern\n for (const unit of timeUnits) {\n const candidate = remaining.slice(0, unit.length);\n const matches = unit.caseInsensitive\n ? candidate.toLowerCase() === unit.pattern.toLowerCase()\n : candidate === unit.pattern;\n\n if (matches) {\n // Check notFollowedBy constraint (e.g., 'm' should not match 'ms')\n if (unit.notFollowedBy) {\n const nextChar = remaining[unit.length] || '';\n if (nextChar === unit.notFollowedBy) continue;\n }\n\n // Check word boundary if required\n if (unit.checkBoundary) {\n const nextChar = remaining[unit.length] || '';\n if (isAsciiIdentifierChar(nextChar)) continue;\n }\n\n return { suffix: unit.suffix, endPos: unitPos + unit.length };\n }\n }\n\n return null;\n }\n\n /**\n * Parse a base number (sign, integer, decimal) without time units.\n * Returns the number string and end position.\n *\n * @param input - Input string\n * @param startPos - Start position\n * @param allowSign - Whether to allow +/- sign (default: true)\n * @returns Object with number string and end position, or null\n */\n protected parseBaseNumber(\n input: string,\n startPos: number,\n allowSign = true\n ): { number: string; endPos: number } | null {\n let pos = startPos;\n let number = '';\n\n // Optional sign\n if (allowSign && (input[pos] === '-' || input[pos] === '+')) {\n number += input[pos++];\n }\n\n // Must have at least one digit\n if (pos >= input.length || !isDigit(input[pos])) {\n return null;\n }\n\n // Integer part\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n\n // Optional decimal\n if (pos < input.length && input[pos] === '.') {\n number += input[pos++];\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n }\n\n if (!number || number === '-' || number === '+') return null;\n\n return { number, endPos: pos };\n }\n\n /**\n * Try to extract a number with native language time units.\n *\n * This is a template method that handles the common pattern:\n * 1. Parse the base number (sign, integer, decimal)\n * 2. Try to match native language time units\n * 3. Fall back to standard time units (ms, s, m, h)\n *\n * @param input - Input string\n * @param pos - Start position\n * @param nativeTimeUnits - Language-specific time unit mappings\n * @param options - Configuration options\n * @returns Token if number found, null otherwise\n */\n protected tryNumberWithTimeUnits(\n input: string,\n pos: number,\n nativeTimeUnits: readonly TimeUnitMapping[],\n options: { allowSign?: boolean; skipWhitespace?: boolean } = {}\n ): LanguageToken | null {\n const { allowSign = true, skipWhitespace = false } = options;\n\n // Parse base number\n const baseResult = this.parseBaseNumber(input, pos, allowSign);\n if (!baseResult) return null;\n\n let { number, endPos } = baseResult;\n\n // Try native time units first, then standard\n const allUnits = [...nativeTimeUnits, ...BaseTokenizer.STANDARD_TIME_UNITS];\n const timeMatch = this.tryMatchTimeUnit(input, endPos, allUnits, skipWhitespace);\n\n if (timeMatch) {\n number += timeMatch.suffix;\n endPos = timeMatch.endPos;\n }\n\n return createToken(number, 'literal', createPosition(pos, endPos));\n }\n\n /**\n * Try to extract a URL at the current position.\n * Handles /path, ./path, ../path, //domain.com, http://, https://\n */\n protected tryUrl(input: string, pos: number): LanguageToken | null {\n const url = extractUrl(input, pos);\n if (url) {\n return createToken(url, 'url', createPosition(pos, pos + url.length));\n }\n return null;\n }\n\n /**\n * Try to extract a variable reference (:varname) at the current position.\n * In hyperscript, :x refers to a local variable named x.\n */\n protected tryVariableRef(input: string, pos: number): LanguageToken | null {\n if (input[pos] !== ':') return null;\n if (pos + 1 >= input.length) return null;\n if (!isAsciiIdentifierChar(input[pos + 1])) return null;\n\n let endPos = pos + 1;\n while (endPos < input.length && isAsciiIdentifierChar(input[endPos])) {\n endPos++;\n }\n\n const varRef = input.slice(pos, endPos);\n return createToken(varRef, 'identifier', createPosition(pos, endPos));\n }\n\n /**\n * Try to extract an operator or punctuation token at the current position.\n * Handles two-character operators (==, !=, etc.) and single-character operators.\n */\n protected tryOperator(input: string, pos: number): LanguageToken | null {\n // Two-character operators\n const twoChar = input.slice(pos, pos + 2);\n if (['==', '!=', '<=', '>=', '&&', '||', '->'].includes(twoChar)) {\n return createToken(twoChar, 'operator', createPosition(pos, pos + 2));\n }\n\n // Single-character operators\n const oneChar = input[pos];\n if (['<', '>', '!', '+', '-', '*', '/', '='].includes(oneChar)) {\n return createToken(oneChar, 'operator', createPosition(pos, pos + 1));\n }\n\n // Punctuation\n if (['(', ')', '{', '}', ',', ';', ':'].includes(oneChar)) {\n return createToken(oneChar, 'punctuation', createPosition(pos, pos + 1));\n }\n\n return null;\n }\n\n /**\n * Try to match a multi-character particle from a list.\n *\n * Used by languages like Japanese, Korean, and Chinese that have\n * multi-character particles (e.g., Japanese から, まで, より).\n *\n * @param input - Input string\n * @param pos - Current position\n * @param particles - Array of multi-character particles to match\n * @returns Token if matched, null otherwise\n */\n protected tryMultiCharParticle(\n input: string,\n pos: number,\n particles: readonly string[]\n ): LanguageToken | null {\n for (const particle of particles) {\n if (input.slice(pos, pos + particle.length) === particle) {\n return createToken(particle, 'particle', createPosition(pos, pos + particle.length));\n }\n }\n return null;\n }\n}\n\n// =============================================================================\n// Simple Tokenizer Factory\n// =============================================================================\n\n/**\n * Configuration for createSimpleTokenizer.\n *\n * Creates a tokenizer from declarative config instead of a class definition.\n * Covers the common pattern used by domain packages (SQL, BDD, JSX).\n *\n * **Keyword resolution** uses two additive paths:\n * 1. `keywords` — explicit list, checked first. Respects `caseInsensitive`.\n * 2. `keywordProfile` — populates BaseTokenizer's profile keyword map via\n * `initializeKeywordsFromProfile()`. Checked second via `isKeyword()`, which\n * always lowercases (harmless for CJK/Arabic; notable for Latin scripts\n * with `caseInsensitive: false`). Provides normalization metadata for\n * non-Latin scripts.\n */\nexport interface SimpleTokenizerConfig {\n /** ISO 639-1 language code */\n language: string;\n /** Text direction (default: 'ltr') */\n direction?: 'ltr' | 'rtl';\n /** Keywords to recognize (lowercased for lookup if caseInsensitive) */\n keywords: string[];\n /** Extra keyword entries for non-Latin normalization */\n keywordExtras?: KeywordEntry[];\n /** Profile for initializeKeywordsFromProfile (for non-Latin scripts) */\n keywordProfile?: TokenizerProfile;\n /** Include operator classification (default: false). Uses DEFAULT_OPERATORS from OperatorExtractor. */\n includeOperators?: boolean;\n /** Case-insensitive keyword matching (default: true) */\n caseInsensitive?: boolean;\n /** Custom extractors registered BEFORE default extractors */\n customExtractors?: ValueExtractor[];\n}\n\n/**\n * Create a tokenizer from declarative configuration.\n *\n * Eliminates the boilerplate of extending BaseTokenizer for simple domain tokenizers.\n * Handles keyword classification, optional operator support, and non-Latin keyword setup.\n *\n * @example\n * ```typescript\n * const englishSQL = createSimpleTokenizer({\n * language: 'en',\n * keywords: ['select', 'insert', 'update', 'delete', 'from', 'into', 'where', 'set', 'values'],\n * includeOperators: true,\n * caseInsensitive: true,\n * });\n * ```\n */\nexport function createSimpleTokenizer(config: SimpleTokenizerConfig): LanguageTokenizer {\n const {\n language,\n direction = 'ltr',\n keywords,\n keywordExtras,\n keywordProfile,\n includeOperators = false,\n caseInsensitive = true,\n customExtractors,\n } = config;\n\n const keywordSet = new Set(caseInsensitive ? keywords.map(k => k.toLowerCase()) : keywords);\n\n class SimpleTokenizer extends BaseTokenizer {\n readonly language = language;\n readonly direction = direction;\n\n constructor() {\n super();\n if (customExtractors) {\n this.registerExtractors(customExtractors);\n }\n this.registerExtractors(getDefaultExtractors());\n if (keywordProfile) {\n this.initializeKeywordsFromProfile(keywordProfile, keywordExtras);\n }\n }\n\n classifyToken(token: string): TokenKind {\n // Fast path: explicit keywords from config (respects caseInsensitive)\n const lookup = caseInsensitive ? token.toLowerCase() : token;\n if (keywordSet.has(lookup)) return 'keyword';\n // Profile path: non-Latin normalization (always lowercases via profileKeywordMap)\n if (this.isKeyword(token)) return 'keyword';\n if (/^\\d/.test(token)) return 'literal';\n if (/^['\"]/.test(token)) return 'literal';\n if (includeOperators && SIMPLE_TOKENIZER_OPERATOR_SET.has(token)) return 'operator';\n return 'identifier';\n }\n }\n\n return new SimpleTokenizer();\n}\n","/**\n * Framework ↔ Semantic bridge builders.\n *\n * Pure functions that combine an injected {@link GrammarProfileSlice} (the\n * per-language grammar facts, typically a `@lokascript/semantic`\n * `LanguageProfile`) with a {@link DomainVocabulary} (the only thing a domain\n * authors per language) into the shapes `createMultilingualDSL` consumes:\n * a `PatternGenLanguageProfile`, a `LanguageTokenizer`, or a complete\n * `LanguageConfig`.\n */\n\nimport type { LanguageTokenizer } from '../core/types';\nimport type { PatternGenLanguageProfile } from '../generation/pattern-generator';\nimport type { LanguageConfig } from '../api/create-dsl';\nimport type { LanguageProfile as GrammarProfile } from '../grammar';\nimport { createSimpleTokenizer, type TokenizerProfile } from '../core/tokenization/base-tokenizer';\nimport {\n LatinExtendedIdentifierExtractor,\n type ValueExtractor,\n} from '../interfaces/value-extractor';\nimport type { DomainVocabulary, GrammarProfileSlice, RoleMarkerSlice } from './types';\n\n/** Mutable role-marker shape shared by PatternGenLanguageProfile and TokenizerProfile. */\ntype MergedRoleMarker = { primary: string; alternatives?: string[]; position?: 'before' | 'after' };\n\n/**\n * Merge the slice's language-default role markers with the vocabulary's\n * domain-specific overrides (vocabulary wins). Empty-string primaries are\n * dropped — an empty override means \"bare positional arg, no marker\".\n */\nfunction mergeRoleMarkers(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary\n): Record<string, MergedRoleMarker> {\n const merged: Record<string, MergedRoleMarker> = {};\n const add = (role: string, marker: RoleMarkerSlice | undefined) => {\n if (!marker?.primary) {\n delete merged[role];\n return;\n }\n merged[role] = {\n primary: marker.primary,\n ...(marker.alternatives?.length && { alternatives: [...marker.alternatives] }),\n ...(marker.position && { position: marker.position }),\n };\n };\n for (const [role, marker] of Object.entries(slice.roleMarkers ?? {})) add(role, marker);\n for (const [role, marker] of Object.entries(vocab.roleMarkerOverrides ?? {})) add(role, marker);\n return merged;\n}\n\n/**\n * Build a pattern-generation profile: domain keywords + slice grammar\n * (word order, role markers). The result feeds `generatePattern` /\n * `generatePatternVariants` and `LanguageConfig.patternProfile`.\n */\nexport function buildPatternProfile(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary\n): PatternGenLanguageProfile {\n const keywords: Record<string, { primary: string; alternatives?: string[] }> = {};\n for (const [action, translation] of Object.entries(vocab.keywords)) {\n keywords[action] = {\n primary: translation.primary,\n ...(translation.alternatives?.length && { alternatives: [...translation.alternatives] }),\n };\n }\n\n const roleMarkers = mergeRoleMarkers(slice, vocab);\n\n return {\n code: slice.code,\n wordOrder: slice.wordOrder,\n keywords,\n ...(Object.keys(roleMarkers).length > 0 && { roleMarkers }),\n };\n}\n\n/** Options for {@link buildDomainTokenizer}, overriding the slice-derived defaults. */\nexport interface DomainTokenizerOptions {\n /**\n * Recognize operator tokens (default: false, matching `createSimpleTokenizer`).\n * Domains whose grammar contains operators (e.g. SQL's `WHERE age > 18`) pass\n * `true`; most natural-language DSLs leave it off.\n */\n readonly includeOperators?: boolean;\n /**\n * Case-insensitive keyword matching. Defaults to true for bicameral scripts\n * (`latin`, `cyrillic`, or when the slice omits `script`), false otherwise.\n */\n readonly caseInsensitive?: boolean;\n /** Extra extractors, registered before the slice-derived ones */\n readonly customExtractors?: readonly ValueExtractor[];\n}\n\nfunction defaultCaseInsensitive(script: string | undefined): boolean {\n return script === undefined || script === 'latin' || script === 'cyrillic';\n}\n\n/**\n * Build a domain tokenizer from a grammar slice + domain vocabulary, wrapping\n * `createSimpleTokenizer`. Derived from the slice:\n *\n * - `direction` (rtl for e.g. Arabic/Hebrew slices)\n * - keyword set: vocabulary verbs (primary + alternatives), role markers\n * (slice defaults merged with `vocab.roleMarkerOverrides`), tokenization\n * particles, and `vocab.tokenizerKeywords`\n * - keyword-normalization profile (native verb → action name, marker → role)\n * - a `LatinExtendedIdentifierExtractor` when `slice.script === 'latin'`, so\n * diacritics (ñ, é, ş, …) never split identifiers\n * - case-insensitivity for bicameral scripts\n */\nexport function buildDomainTokenizer(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary,\n options: DomainTokenizerOptions = {}\n): LanguageTokenizer {\n const roleMarkers = mergeRoleMarkers(slice, vocab);\n\n // Flat keyword list for token classification.\n const keywords = new Set<string>();\n for (const translation of Object.values(vocab.keywords)) {\n keywords.add(translation.primary);\n for (const alt of translation.alternatives ?? []) keywords.add(alt);\n }\n for (const marker of Object.values(roleMarkers)) {\n keywords.add(marker.primary);\n for (const alt of marker.alternatives ?? []) keywords.add(alt);\n }\n for (const particle of slice.tokenization?.particles ?? []) keywords.add(particle);\n for (const extra of vocab.tokenizerKeywords ?? []) keywords.add(extra);\n\n // Normalization profile: native verb forms → action names, markers → roles.\n const profileKeywords: NonNullable<TokenizerProfile['keywords']> = {};\n for (const [action, translation] of Object.entries(vocab.keywords)) {\n profileKeywords[action] = {\n primary: translation.primary,\n ...(translation.alternatives?.length && { alternatives: [...translation.alternatives] }),\n normalized: translation.normalized ?? action,\n };\n }\n const keywordProfile: TokenizerProfile = {\n keywords: profileKeywords,\n ...(Object.keys(roleMarkers).length > 0 && { roleMarkers }),\n };\n\n const customExtractors: ValueExtractor[] = [\n ...(options.customExtractors ?? []),\n ...(slice.script === 'latin' ? [new LatinExtendedIdentifierExtractor()] : []),\n ];\n\n return createSimpleTokenizer({\n language: slice.code,\n direction: slice.direction ?? 'ltr',\n keywords: [...keywords],\n ...(vocab.keywordExtras?.length && { keywordExtras: vocab.keywordExtras.map(e => ({ ...e })) }),\n keywordProfile,\n includeOperators: options.includeOperators ?? false,\n caseInsensitive: options.caseInsensitive ?? defaultCaseInsensitive(slice.script),\n ...(customExtractors.length > 0 && { customExtractors }),\n });\n}\n\n/** Metadata / overrides for {@link buildLanguageConfig}. */\nexport interface LanguageConfigMeta {\n /** English name (default: `slice.name`, falling back to `slice.code`) */\n readonly name?: string;\n /** Native name (default: `slice.nativeName`, falling back to the English name) */\n readonly nativeName?: string;\n /** Grammar-transformation profile to attach (optional, as on `LanguageConfig`) */\n readonly grammarProfile?: GrammarProfile;\n /** Use this tokenizer instead of the slice-derived one */\n readonly tokenizer?: LanguageTokenizer;\n /** Options for the slice-derived tokenizer (ignored when `tokenizer` is given) */\n readonly tokenizerOptions?: DomainTokenizerOptions;\n}\n\n/**\n * The one-call path into `createMultilingualDSL`: build a complete\n * `LanguageConfig` (tokenizer + pattern profile + names) from a grammar slice\n * and a domain vocabulary.\n */\nexport function buildLanguageConfig(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary,\n meta: LanguageConfigMeta = {}\n): LanguageConfig {\n const name = meta.name ?? slice.name ?? slice.code;\n return {\n code: slice.code,\n name,\n nativeName: meta.nativeName ?? slice.nativeName ?? name,\n tokenizer: meta.tokenizer ?? buildDomainTokenizer(slice, vocab, meta.tokenizerOptions),\n patternProfile: buildPatternProfile(slice, vocab),\n ...(meta.grammarProfile && { grammarProfile: meta.grammarProfile }),\n };\n}\n\n/**\n * Derive schema `markerOverride` defaults for ONE language from the slice's\n * role markers, given a domain-role → semantic-role mapping. Returns\n * `{ domainRole: primaryMarker }` with entries only where the slice has a\n * marker for the mapped semantic role.\n *\n * ```ts\n * deriveRoleMarkers(jaSlice, { table: 'source', target: 'destination' });\n * // → { table: 'から', target: 'に' }\n * ```\n *\n * Explicitly authored `markerOverride` entries stay authoritative — when\n * assembling a per-language marker map for a schema role, spread the explicit\n * entries after the derived defaults.\n */\nexport function deriveRoleMarkers(\n slice: GrammarProfileSlice,\n roleMapping: Readonly<Record<string, string>>\n): Record<string, string> {\n const derived: Record<string, string> = {};\n for (const [domainRole, semanticRole] of Object.entries(roleMapping)) {\n const marker = slice.roleMarkers?.[semanticRole];\n if (marker?.primary) derived[domainRole] = marker.primary;\n }\n return derived;\n}\n","/**\n * Character Classifiers\n *\n * Unicode range classification and Latin character classifier factories.\n * Used by language-specific tokenizers to define character sets.\n */\n\n// =============================================================================\n// Unicode Range Classification\n// =============================================================================\n\n/**\n * Unicode range tuple: [start, end] (inclusive).\n */\nexport type UnicodeRange = readonly [number, number];\n\n/**\n * Create a character classifier for Unicode ranges.\n * Returns a function that checks if a character's code point falls within any of the ranges.\n *\n * @example\n * // Japanese Hiragana\n * const isHiragana = createUnicodeRangeClassifier([[0x3040, 0x309f]]);\n *\n * // Korean (Hangul syllables + Jamo)\n * const isKorean = createUnicodeRangeClassifier([\n * [0xac00, 0xd7a3], // Hangul syllables\n * [0x1100, 0x11ff], // Hangul Jamo\n * [0x3130, 0x318f], // Hangul Compatibility Jamo\n * ]);\n */\nexport function createUnicodeRangeClassifier(\n ranges: readonly UnicodeRange[]\n): (char: string) => boolean {\n return (char: string): boolean => {\n const code = char.charCodeAt(0);\n return ranges.some(([start, end]) => code >= start && code <= end);\n };\n}\n\n/**\n * Combine multiple character classifiers into one.\n * Returns true if any of the classifiers return true.\n *\n * @example\n * const isJapanese = combineClassifiers(isHiragana, isKatakana, isKanji);\n */\nexport function combineClassifiers(\n ...classifiers: Array<(char: string) => boolean>\n): (char: string) => boolean {\n return (char: string): boolean => classifiers.some(fn => fn(char));\n}\n\n/**\n * Character classifiers for a Latin-based language.\n */\nexport interface LatinCharClassifiers {\n /** Check if character is a letter in this language (including accented chars). */\n isLetter: (char: string) => boolean;\n /** Check if character is part of an identifier (letter, digit, underscore, hyphen). */\n isIdentifierChar: (char: string) => boolean;\n}\n\n/**\n * Create character classifiers for a Latin-based language.\n * Returns isLetter and isIdentifierChar functions based on the provided regex.\n *\n * @example\n * // Spanish letters\n * const { isLetter, isIdentifierChar } = createLatinCharClassifiers(/[a-zA-Z\\u00e1\\u00e9\\u00ed\\u00f3\\u00fa\\u00fc\\u00f1\\u00c1\\u00c9\\u00cd\\u00d3\\u00da\\u00dc\\u00d1]/);\n *\n * // German letters\n * const { isLetter, isIdentifierChar } = createLatinCharClassifiers(/[a-zA-Z\\u00e4\\u00f6\\u00fc\\u00c4\\u00d6\\u00dc\\u00df]/);\n */\nexport function createLatinCharClassifiers(letterPattern: RegExp): LatinCharClassifiers {\n const isLetter = (char: string): boolean => letterPattern.test(char);\n const isIdentifierChar = (char: string): boolean => isLetter(char) || /[0-9_-]/.test(char);\n return { isLetter, isIdentifierChar };\n}\n","/**\n * Morphological Normalizer Types\n *\n * Defines interfaces for language-specific morphological analysis.\n * Normalizers reduce conjugated/inflected forms to canonical stems\n * that can be matched against keyword dictionaries.\n */\n\n/**\n * Result of morphological normalization.\n */\nexport interface NormalizationResult {\n /** The extracted stem/root form */\n readonly stem: string;\n\n /** Confidence in the normalization (0.0-1.0) */\n readonly confidence: number;\n\n /** Optional metadata about the transformation */\n readonly metadata?: NormalizationMetadata;\n}\n\n/**\n * Metadata about morphological transformations applied.\n */\nexport interface NormalizationMetadata {\n /** Prefixes that were removed */\n readonly removedPrefixes?: readonly string[];\n\n /** Suffixes that were removed */\n readonly removedSuffixes?: readonly string[];\n\n /** Type of conjugation detected */\n readonly conjugationType?: ConjugationType;\n\n /** Original form classification */\n readonly originalForm?: string;\n\n /** Applied transformation rules (for debugging) */\n readonly appliedRules?: readonly string[];\n}\n\n/**\n * Types of verb conjugation/inflection.\n */\nexport type ConjugationType =\n // Tense\n | 'present'\n | 'past'\n | 'future'\n | 'progressive'\n | 'perfect'\n // Mood\n | 'imperative'\n | 'subjunctive'\n | 'conditional'\n // Voice\n | 'passive'\n | 'causative'\n // Politeness (Japanese/Korean)\n | 'polite'\n | 'humble'\n | 'honorific'\n // Form\n | 'negative'\n | 'potential'\n | 'volitional'\n // Japanese conditional forms\n | 'conditional-tara' // たら/したら - if/when (completed action)\n | 'conditional-to' // と/すると - when (habitual/expected)\n | 'conditional-ba' // ば/すれば - if (hypothetical)\n // Korean-specific\n | 'connective' // 하고, 해서 etc.\n | 'conditional-myeon' // -(으)면 - if/when (general conditional)\n | 'temporal-ttae' // -(으)ㄹ 때 - when (at the time of)\n | 'causal-nikka' // -(으)니까 - because/since\n // Korean honorific forms (-시- infix)\n | 'honorific-conditional' // -하시면 - if (honorific)\n | 'honorific-temporal' // -하실 때 - when (honorific)\n | 'honorific-causal' // -하시니까 - because (honorific)\n | 'honorific-past' // -하셨어요 - past (honorific)\n | 'honorific-polite' // -하십니다 - polite (honorific)\n // Korean sequential forms\n | 'sequential-after' // -고 나서 - after doing\n | 'sequential-before' // -기 전에 - before doing\n | 'immediate' // -자마자 - as soon as\n | 'obligation' // -아야/어야 해 - must do, should do\n // Spanish-specific\n | 'reflexive'\n | 'reflexive-imperative'\n | 'gerund'\n | 'participle'\n // Arabic-specific\n | 'conditional-idha' // إذا - if/when (hypothetical)\n | 'temporal-indama' // عندما - when (temporal conjunction)\n | 'temporal-hina' // حين - at the time of\n | 'temporal-lamma' // لمّا - when (past emphasis)\n | 'past-verb' // فعل ماضي - past tense verb\n // Turkish-specific\n | 'conditional-se' // -se/-sa - if (hypothetical)\n | 'temporal-ince' // -ince/-ınca/-unca/-ünce - when/as\n | 'temporal-dikce' // -dikçe/-dıkça/-dukça/-dükçe - as/while\n | 'aorist' // -ir/-ar - habitual/general\n | 'optative' // -eyim/-ayım/-elim/-alım - let me/us\n | 'necessitative' // -meli/-malı - must/should\n // Japanese request/contracted forms\n | 'request' // てください/でください - polite request\n | 'casual-request' // てくれ/でくれ - casual request\n | 'contracted' // ちゃう/じゃう - contracted completion (てしまう)\n | 'contracted-past' // ちゃった/じゃった - contracted past completion\n // Compound\n | 'compound' // Multi-layer suffixes (ていなかった, 하고나서였어)\n | 'te-form' // Japanese て-form\n | 'dictionary'; // Base/infinitive form\n\n/**\n * Interface for language-specific morphological normalizers.\n *\n * Normalizers attempt to reduce inflected word forms to their\n * canonical stems. This enables matching conjugated verbs against\n * keyword dictionaries that only contain base forms.\n *\n * Example (Japanese):\n * 切り替えた (past) → { stem: '切り替え', confidence: 0.85 }\n * 切り替えます (polite) → { stem: '切り替え', confidence: 0.85 }\n *\n * Example (Spanish):\n * mostrarse (reflexive infinitive) → { stem: 'mostrar', confidence: 0.85 }\n * alternando (gerund) → { stem: 'alternar', confidence: 0.85 }\n */\nexport interface MorphologicalNormalizer {\n /** Language code this normalizer handles */\n readonly language: string;\n\n /**\n * Normalize a word to its canonical stem form.\n *\n * @param word - The word to normalize\n * @returns Normalization result with stem and confidence\n */\n normalize(word: string): NormalizationResult;\n\n /**\n * Check if a word appears to be a verb form that can be normalized.\n * Optional optimization to skip normalization for non-verb tokens.\n *\n * @param word - The word to check\n * @returns true if the word might be a normalizable verb form\n */\n isNormalizable?(word: string): boolean;\n}\n\n/**\n * Configuration for suffix-based normalization rules.\n * Used by agglutinative languages (Japanese, Korean, Turkish).\n */\nexport interface SuffixRule {\n /** The suffix pattern to match */\n readonly pattern: string;\n\n /** Confidence when this suffix is stripped */\n readonly confidence: number;\n\n /** What to replace the suffix with (empty string for simple removal) */\n readonly replacement?: string;\n\n /** Conjugation type this suffix indicates */\n readonly conjugationType?: ConjugationType;\n\n /** Minimum stem length after stripping (to avoid over-stripping) */\n readonly minStemLength?: number;\n}\n\n/**\n * Configuration for prefix-based normalization rules.\n * Used primarily by Arabic for article/conjunction prefixes.\n */\nexport interface PrefixRule {\n /** The prefix pattern to match */\n readonly pattern: string;\n\n /** Confidence penalty when this prefix is stripped */\n readonly confidencePenalty: number;\n\n /** What the prefix indicates (for metadata) */\n readonly prefixType?: 'article' | 'conjunction' | 'preposition' | 'verb-marker';\n\n /** Minimum remaining characters after stripping (to avoid over-stripping) */\n readonly minRemaining?: number;\n}\n\n/**\n * Helper to create a \"no change\" normalization result.\n */\nexport function noChange(word: string): NormalizationResult {\n return { stem: word, confidence: 1.0 };\n}\n\n/**\n * Helper to create a normalization result with metadata.\n */\nexport function normalized(\n stem: string,\n confidence: number,\n metadata?: NormalizationMetadata\n): NormalizationResult {\n if (metadata) {\n return { stem, confidence, metadata };\n }\n return { stem, confidence };\n}\n","/**\n * BaseMorphologicalNormalizer — Shared base class for language normalizers.\n *\n * Provides the common suffix/prefix stripping loop, reflexive verb handling,\n * and normalize() pipeline. Language-specific normalizers extend this class\n * and provide their conjugation rules.\n *\n * Phase 3.1 of parser-ecosystem-plan-v3.\n */\n\nimport type {\n MorphologicalNormalizer,\n NormalizationResult,\n ConjugationType,\n SuffixRule,\n PrefixRule,\n} from './types';\nimport { noChange, normalized } from './types';\n\n/**\n * Conjugation ending rule for verb classes (Romance languages etc.)\n * Broader than SuffixRule — includes the replacement stem (e.g., strip -ando, add -ar).\n */\nexport interface ConjugationEnding {\n readonly ending: string;\n readonly stem: string;\n readonly confidence: number;\n readonly type: ConjugationType;\n}\n\n/**\n * Configuration for BaseMorphologicalNormalizer.\n * Subclasses provide this in their constructor.\n */\nexport interface NormalizerConfig {\n /** Language code */\n readonly language: string;\n\n /** Minimum word length to attempt normalization */\n readonly minWordLength?: number;\n\n /** Minimum stem length after stripping (default: 2) */\n readonly minStemLength?: number;\n\n /** Conjugation endings sorted longest-first */\n readonly endings?: readonly ConjugationEnding[];\n\n /** Suffix rules (for SuffixRule-style normalizers) */\n readonly suffixRules?: readonly SuffixRule[];\n\n /** Prefix rules */\n readonly prefixRules?: readonly PrefixRule[];\n\n /** Reflexive suffixes (for Romance languages) */\n readonly reflexiveSuffixes?: readonly string[];\n\n /** Infinitive endings (for checking if already normalized) */\n readonly infinitiveEndings?: readonly string[];\n}\n\n/**\n * Abstract base class for morphological normalizers.\n *\n * Subclasses must implement `isNormalizable()` and can override any\n * normalization step. The default `normalize()` pipeline is:\n *\n * 1. Check if already in dictionary form → noChange\n * 2. Try reflexive normalization (if reflexiveSuffixes configured)\n * 3. Try conjugation endings (if endings configured)\n * 4. Try suffix rules (if suffixRules configured)\n * 5. Try prefix rules (if prefixRules configured)\n * 6. Return noChange\n */\nexport abstract class BaseMorphologicalNormalizer implements MorphologicalNormalizer {\n readonly language: string;\n protected readonly config: NormalizerConfig;\n\n constructor(config: NormalizerConfig) {\n this.language = config.language;\n this.config = {\n minWordLength: 3,\n minStemLength: 2,\n ...config,\n };\n }\n\n /**\n * Check if a word can be normalized. Subclasses must implement this\n * with language-specific script/character detection.\n */\n abstract isNormalizable(word: string): boolean;\n\n /**\n * Standard normalization pipeline. Override for custom behavior.\n */\n normalize(word: string): NormalizationResult {\n const lower = word.toLowerCase();\n\n // Check if already in dictionary form\n if (this.isAlreadyNormalized(lower)) {\n return noChange(word);\n }\n\n // Try reflexive normalization (Romance languages)\n if (this.config.reflexiveSuffixes) {\n const reflexive = this.tryReflexiveNormalization(lower);\n if (reflexive) return reflexive;\n }\n\n // Try conjugation endings\n if (this.config.endings) {\n const conjugation = this.tryConjugationEndings(lower);\n if (conjugation) return conjugation;\n }\n\n // Try suffix rules\n if (this.config.suffixRules) {\n const suffix = this.trySuffixRules(lower);\n if (suffix) return suffix;\n }\n\n // Try prefix rules\n if (this.config.prefixRules) {\n const prefix = this.tryPrefixRules(lower);\n if (prefix) return prefix;\n }\n\n return noChange(word);\n }\n\n /**\n * Check if word is already in dictionary form (e.g., ends in -ar/-er/-ir).\n * Override for language-specific checks.\n */\n protected isAlreadyNormalized(word: string): boolean {\n if (this.config.infinitiveEndings) {\n return this.config.infinitiveEndings.some(e => word.endsWith(e));\n }\n return false;\n }\n\n /**\n * Try to strip reflexive suffixes and normalize the remainder.\n * Common in Romance languages (Spanish, Portuguese, French).\n */\n protected tryReflexiveNormalization(word: string): NormalizationResult | null {\n const suffixes = this.config.reflexiveSuffixes;\n if (!suffixes) return null;\n\n for (const suffix of suffixes) {\n if (!word.endsWith(suffix)) continue;\n const remainder = word.slice(0, -suffix.length);\n\n // Check if remainder is already an infinitive\n if (this.isAlreadyNormalized(remainder)) {\n return normalized(remainder, 0.88, {\n removedSuffixes: [suffix],\n conjugationType: 'reflexive',\n });\n }\n\n // Try to normalize the remainder\n const inner = this.tryConjugationEndings(remainder) || this.trySuffixRules(remainder);\n if (inner && inner.stem !== remainder) {\n return normalized(inner.stem, inner.confidence * 0.95, {\n removedSuffixes: [suffix, ...(inner.metadata?.removedSuffixes || [])],\n conjugationType: 'reflexive',\n });\n }\n }\n\n return null;\n }\n\n /**\n * Try conjugation endings (verb class endings like -ar/-er/-ir patterns).\n * Endings must be pre-sorted longest-first.\n */\n protected tryConjugationEndings(word: string): NormalizationResult | null {\n const endings = this.config.endings;\n if (!endings) return null;\n\n const minStem = this.config.minStemLength ?? 2;\n\n for (const rule of endings) {\n if (!word.endsWith(rule.ending)) continue;\n\n const stemBase = word.slice(0, -rule.ending.length);\n if (stemBase.length < minStem) continue;\n\n const infinitive = stemBase + rule.stem;\n return normalized(infinitive, rule.confidence, {\n removedSuffixes: [rule.ending],\n conjugationType: rule.type,\n });\n }\n\n return null;\n }\n\n /**\n * Try SuffixRule-style normalization.\n * Rules must be pre-sorted longest-first.\n */\n protected trySuffixRules(word: string): NormalizationResult | null {\n const rules = this.config.suffixRules;\n if (!rules) return null;\n\n const defaultMinStem = this.config.minStemLength ?? 2;\n\n for (const rule of rules) {\n if (!word.endsWith(rule.pattern)) continue;\n\n const stem = word.slice(0, -rule.pattern.length);\n const minStem = rule.minStemLength ?? defaultMinStem;\n if (stem.length < minStem) continue;\n\n const result = stem + (rule.replacement || '');\n return normalized(result, rule.confidence, {\n removedSuffixes: [rule.pattern],\n ...(rule.conjugationType && { conjugationType: rule.conjugationType }),\n });\n }\n\n return null;\n }\n\n /**\n * Try PrefixRule-style normalization.\n */\n protected tryPrefixRules(word: string): NormalizationResult | null {\n const rules = this.config.prefixRules;\n if (!rules) return null;\n\n for (const rule of rules) {\n if (!word.startsWith(rule.pattern)) continue;\n\n const remainder = word.slice(rule.pattern.length);\n const minRemaining = rule.minRemaining ?? this.config.minStemLength ?? 2;\n if (remainder.length < minRemaining) continue;\n\n return normalized(remainder, 1.0 - rule.confidencePenalty, {\n removedPrefixes: [rule.pattern],\n });\n }\n\n return null;\n }\n}\n","/**\n * JSONL Writer\n *\n * Exports training pairs in JSONL (JSON Lines) format,\n * compatible with standard fine-tuning pipelines.\n */\n\nimport type { TrainingPair } from './types';\n\n/**\n * Convert training pairs to JSONL format (one JSON object per line).\n *\n * Each line contains:\n * - id: unique pair identifier\n * - prompt: the natural language input\n * - completion: the LSE bracket syntax output\n * - metadata: domain, action, language, source, quality\n */\nexport function toJSONL(pairs: readonly TrainingPair[]): string {\n return pairs.map(pair => JSON.stringify(toJSONLRow(pair))).join('\\n');\n}\n\n/**\n * Convert a single training pair to a JSONL row.\n */\nexport function toJSONLRow(pair: TrainingPair): JSONLRow {\n return {\n id: pair.id,\n prompt: pair.natural,\n completion: pair.explicit,\n metadata: {\n domain: pair.domain,\n action: pair.action,\n language: pair.language,\n source: pair.source,\n quality: pair.quality,\n ...(pair.confidence !== undefined && { confidence: pair.confidence }),\n },\n };\n}\n\n/**\n * Parse JSONL back into rows (for validation/roundtrip testing).\n */\nexport function parseJSONL(text: string): JSONLRow[] {\n return text\n .split('\\n')\n .filter(line => line.trim().length > 0)\n .map(line => JSON.parse(line) as JSONLRow);\n}\n\n/**\n * A single row in JSONL format.\n */\nexport interface JSONLRow {\n readonly id: string;\n readonly prompt: string;\n readonly completion: string;\n readonly metadata: {\n readonly domain: string;\n readonly action: string;\n readonly language: string;\n readonly source: string;\n readonly quality: number;\n readonly confidence?: number;\n };\n}\n","/**\n * Confidence-Aware Disambiguation\n *\n * When parse confidence is borderline (between low and high thresholds),\n * generates a disambiguation request with alternative interpretations\n * instead of blindly accepting or rejecting.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport type { DisambiguationRequest, DisambiguationCandidate } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Check whether a confidence score falls in the disambiguation range.\n *\n * @returns true if the confidence is ambiguous (between low and high thresholds)\n */\nexport function needsDisambiguation(\n confidence: number,\n low: number = 0.5,\n high: number = 0.7\n): boolean {\n return confidence >= low && confidence < high;\n}\n\n/**\n * Build a disambiguation request from candidate interpretations.\n *\n * @param input - The original ambiguous input\n * @param candidates - Alternative interpretations with confidence scores\n */\nexport function buildDisambiguation(\n input: string,\n candidates: ReadonlyArray<{\n action: string;\n confidence: number;\n node: SemanticNode;\n description?: string;\n }>\n): DisambiguationRequest {\n const sortedCandidates = [...candidates].sort((a, b) => b.confidence - a.confidence);\n\n const disambiguationCandidates: DisambiguationCandidate[] = sortedCandidates.map((c, i) => ({\n action: c.action,\n confidence: c.confidence,\n explicit: renderExplicit(c.node),\n description: c.description || `${c.action} (option ${String.fromCharCode(97 + i)})`,\n }));\n\n const optionLines = disambiguationCandidates.map(\n (c, i) =>\n ` (${String.fromCharCode(97 + i)}) ${c.explicit} — ${c.description} (conf: ${c.confidence.toFixed(2)})`\n );\n\n const question = [\n `Your input parsed with confidence ${sortedCandidates[0]?.confidence.toFixed(2) ?? '?'}.`,\n ...optionLines,\n 'Which did you mean?',\n ].join('\\n');\n\n return {\n input,\n candidates: disambiguationCandidates,\n question,\n };\n}\n","/**\n * Pattern Hit-Rate Tracker\n *\n * Records pattern events in a ring buffer and computes hit-rate\n * statistics by command, language, and diagnostic code. Patterns\n * with high rejected/attempts ratios indicate miscalibrated confidence.\n */\n\nimport type { PatternEvent, HitRate, PatternTrackerSummary, TopFailure } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\nexport class PatternTracker {\n private events: PatternEvent[] = [];\n private readonly maxEvents: number;\n\n constructor(maxEvents: number = 1000) {\n this.maxEvents = maxEvents;\n }\n\n /**\n * Record a pattern event.\n */\n record(event: PatternEvent): void {\n this.events.push(event);\n // Ring buffer: drop oldest when full\n if (this.events.length > this.maxEvents) {\n this.events = this.events.slice(this.events.length - this.maxEvents);\n }\n }\n\n /**\n * Get hit rate by command action.\n */\n getHitRateByCommand(): Record<string, HitRate> {\n return this.computeHitRate(e => e.action);\n }\n\n /**\n * Get hit rate by language.\n */\n getHitRateByLanguage(): Record<string, HitRate> {\n return this.computeHitRate(e => e.language);\n }\n\n /**\n * Get the most frequent failure diagnostic codes.\n */\n getTopFailures(limit: number = 10): TopFailure[] {\n const codeMap = new Map<string, { count: number; actions: Set<string> }>();\n\n for (const event of this.events) {\n if (event.outcome !== 'rejected' || !event.diagnosticCodes) continue;\n for (const code of event.diagnosticCodes) {\n const entry = codeMap.get(code) || { count: 0, actions: new Set() };\n entry.count++;\n entry.actions.add(event.action);\n codeMap.set(code, entry);\n }\n }\n\n return Array.from(codeMap.entries())\n .map(([code, { count, actions }]) => ({\n code,\n count,\n actions: Array.from(actions),\n }))\n .sort((a, b) => b.count - a.count)\n .slice(0, limit);\n }\n\n /**\n * Get a complete summary of tracking data.\n */\n getSummary(): PatternTrackerSummary {\n const byOutcome: Record<string, number> = {};\n for (const event of this.events) {\n byOutcome[event.outcome] = (byOutcome[event.outcome] || 0) + 1;\n }\n\n return {\n totalEvents: this.events.length,\n byOutcome,\n byCommand: this.getHitRateByCommand(),\n byLanguage: this.getHitRateByLanguage(),\n topFailures: this.getTopFailures(),\n };\n }\n\n /**\n * Export all events as JSONL.\n */\n exportJSONL(): string {\n return this.events.map(e => JSON.stringify(e)).join('\\n');\n }\n\n /**\n * Get the number of recorded events.\n */\n get size(): number {\n return this.events.length;\n }\n\n /**\n * Clear all events.\n */\n clear(): void {\n this.events = [];\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private computeHitRate(keyFn: (e: PatternEvent) => string): Record<string, HitRate> {\n const map = new Map<string, { attempts: number; successes: number }>();\n\n for (const event of this.events) {\n const key = keyFn(event);\n const entry = map.get(key) || { attempts: 0, successes: 0 };\n entry.attempts++;\n if (event.outcome === 'accepted') {\n entry.successes++;\n }\n map.set(key, entry);\n }\n\n const result: Record<string, HitRate> = {};\n for (const [key, { attempts, successes }] of map) {\n result[key] = {\n attempts,\n successes,\n rate: attempts > 0 ? successes / attempts : 0,\n };\n }\n return result;\n }\n}\n","/**\n * Multi-statement parser for domain DSLs.\n *\n * Provides generic mechanics for parsing multi-line/multi-statement DSL input:\n * - Statement splitting (line-based or delimiter-based)\n * - Keyword classification (SVO start / SOV end detection)\n * - Block accumulation (grouping lines into blocks)\n * - Error collection with line numbers\n *\n * Domains provide the semantics (what keywords mean, preprocessing, hierarchy).\n * The framework provides the mechanics.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL } from '../api/create-dsl';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Word order affects keyword detection position.\n */\nexport type WordOrderHint = 'SVO' | 'SOV' | 'VSO';\n\n/**\n * How to split input into individual statements.\n */\nexport interface SplitConfig {\n /**\n * Split mode:\n * - 'line': split on newlines (for indentation-based DSLs)\n * - 'delimiter': split on language-specific delimiters\n */\n readonly mode: 'line' | 'delimiter';\n\n /**\n * Language-specific delimiter patterns (used when mode='delimiter').\n * Key is language code, value is regex pattern.\n * Example: { en: /,\\s*|\\n\\s*/, ja: /、|。|\\n\\s*/ }\n */\n readonly delimiters?: Readonly<Record<string, RegExp>>;\n\n /**\n * Default delimiter when language not in delimiters map.\n */\n readonly defaultDelimiter?: RegExp;\n\n /**\n * Whether to trim each statement after splitting.\n * Default: true\n */\n readonly trim?: boolean;\n\n /**\n * Comment prefixes to strip. Lines starting with these are skipped.\n * Default: ['--', '//']\n */\n readonly commentPrefixes?: readonly string[];\n}\n\n/**\n * A keyword category with its translations.\n * Maps language code to array of keyword variants.\n */\nexport type KeywordMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Configuration for keyword classification.\n */\nexport interface KeywordConfig {\n /**\n * Named keyword categories with their per-language translations.\n * Example: { test: { en: ['test'], ja: ['テスト'], es: ['prueba'] } }\n */\n readonly categories: Readonly<Record<string, KeywordMap>>;\n\n /**\n * Word order hint per language (affects where keywords are detected).\n * Default for unlisted languages: 'SVO'\n */\n readonly wordOrders?: Readonly<Record<string, WordOrderHint>>;\n}\n\n/**\n * Configuration for continuation resolution (e.g., BDD's \"and\" keyword).\n */\nexport interface ContinuationConfig {\n /**\n * The keyword(s) that signal continuation, per language.\n * Example: { en: ['and'], es: ['y'], ja: ['かつ'], ar: ['و'] }\n */\n readonly keywords: KeywordMap;\n\n /**\n * How to resolve continuation: re-prefix with previous step's keyword.\n * The function receives (content after 'and', previous step's category, language)\n * and returns the re-prefixed string for re-parsing.\n *\n * Default: `(content, prevCategory, language, categoryKeywords) =>\n * categoryKeywords[prevCategory]?.[language]?.[0] + ' ' + content`\n */\n readonly resolve?: (\n content: string,\n prevCategory: string,\n language: string,\n categoryKeywords: Record<string, KeywordMap>\n ) => string;\n}\n\n/**\n * A parsed statement with its line context.\n */\nexport interface ParsedStatement {\n /** The parsed semantic node */\n readonly node: SemanticNode;\n /** Original source line/text */\n readonly source: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Detected keyword category (e.g., 'test', 'given', 'when') */\n readonly category?: string;\n /** Indentation level (number of leading spaces, 0-based) */\n readonly indent: number;\n}\n\n/**\n * A parse error with location information.\n */\nexport interface StatementError {\n /** Error message */\n readonly message: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Original source line/text */\n readonly source: string;\n /** Error code for programmatic handling */\n readonly code?: 'parse-error' | 'unexpected-line' | 'continuation-error';\n}\n\n/**\n * Result of multi-statement parsing.\n */\nexport interface MultiStatementResult {\n /** Successfully parsed statements */\n readonly statements: readonly ParsedStatement[];\n /** Errors encountered during parsing */\n readonly errors: readonly StatementError[];\n}\n\n/**\n * Preprocessor function called before each statement is parsed.\n * Returns the modified string to parse, or null to skip the line.\n */\nexport type StatementPreprocessor = (\n line: string,\n category: string | undefined,\n language: string,\n context: PreprocessorContext\n) => string | null;\n\n/**\n * Context available to preprocessors.\n */\nexport interface PreprocessorContext {\n /** The previous parsed statement, if any */\n readonly previous?: ParsedStatement;\n /** Line number (1-based) */\n readonly lineNumber: number;\n /** Indentation level */\n readonly indent: number;\n}\n\n/**\n * Full configuration for multi-statement parser.\n */\nexport interface MultiStatementConfig {\n /** How to split input into statements */\n readonly split: SplitConfig;\n /** Keyword classification (optional — if omitted, no category detection) */\n readonly keywords?: KeywordConfig;\n /** Continuation resolution (optional — e.g., BDD 'and') */\n readonly continuation?: ContinuationConfig;\n /** Statement preprocessor (optional — for article stripping, expect-prepending, etc.) */\n readonly preprocessor?: StatementPreprocessor;\n}\n\n// =============================================================================\n// Multi-Statement Parser\n// =============================================================================\n\n/**\n * A reusable multi-statement parser.\n * Created via `createMultiStatementParser()`.\n */\nexport interface MultiStatementParser {\n /**\n * Parse multi-statement input into an array of parsed statements.\n */\n parse(input: string, language: string): MultiStatementResult;\n}\n\n/**\n * Create a multi-statement parser that wraps a `MultilingualDSL` instance.\n *\n * The parser handles splitting, keyword detection, continuation resolution,\n * preprocessing, and error collection. It delegates single-statement parsing\n * to the provided DSL's `parse()` method.\n *\n * @example\n * ```typescript\n * const parser = createMultiStatementParser(myDSL, {\n * split: { mode: 'line', commentPrefixes: ['--', '//'] },\n * keywords: {\n * categories: {\n * given: { en: ['given'], ja: ['前提'], es: ['dado'] },\n * when: { en: ['when'], ja: ['もし'], es: ['cuando'] },\n * then: { en: ['then'], ja: ['ならば'], es: ['entonces'] },\n * },\n * wordOrders: { ja: 'SOV', ar: 'VSO' },\n * },\n * continuation: {\n * keywords: { en: ['and'], es: ['y'], ja: ['かつ'] },\n * },\n * });\n *\n * const result = parser.parse(`\n * given #login is visible\n * when click on #submit\n * then #dashboard appears\n * `, 'en');\n * ```\n */\nexport function createMultiStatementParser(\n dsl: MultilingualDSL,\n config: MultiStatementConfig\n): MultiStatementParser {\n return new MultiStatementParserImpl(dsl, config);\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nclass MultiStatementParserImpl implements MultiStatementParser {\n constructor(\n private readonly dsl: MultilingualDSL,\n private readonly config: MultiStatementConfig\n ) {}\n\n parse(input: string, language: string): MultiStatementResult {\n const rawStatements = this.splitStatements(input, language);\n const statements: ParsedStatement[] = [];\n const errors: StatementError[] = [];\n let previous: ParsedStatement | undefined;\n\n for (const raw of rawStatements) {\n // Detect keyword category\n const category = this.classifyLine(raw.text, language);\n\n // Handle continuation (e.g., 'and')\n let textToParse = raw.text;\n if (this.config.continuation) {\n const resolved = this.resolveContinuation(raw.text, language, previous?.category);\n if (resolved !== null) {\n textToParse = resolved;\n }\n }\n\n // Run preprocessor\n if (this.config.preprocessor) {\n const processed = this.config.preprocessor(textToParse, category, language, {\n ...(previous != null && { previous }),\n lineNumber: raw.line,\n indent: raw.indent,\n });\n if (processed === null) continue; // skip line\n textToParse = processed;\n }\n\n // Parse with DSL\n try {\n const node = this.dsl.parse(textToParse, language);\n const stmt: ParsedStatement = {\n node,\n source: raw.text,\n line: raw.line,\n ...(category != null && { category }),\n indent: raw.indent,\n };\n statements.push(stmt);\n previous = stmt;\n } catch (err) {\n errors.push({\n message: err instanceof Error ? err.message : String(err),\n line: raw.line,\n source: raw.text,\n code: 'parse-error',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Split input into raw statement lines with metadata.\n */\n private splitStatements(\n input: string,\n language: string\n ): Array<{ text: string; line: number; indent: number }> {\n const { mode, trim = true, commentPrefixes = ['--', '//'] } = this.config.split;\n\n if (mode === 'delimiter') {\n return this.splitByDelimiter(input, language, trim, commentPrefixes);\n }\n\n // Line-based splitting\n const lines = input.split('\\n');\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i];\n const indent = raw.length - raw.trimStart().length;\n const text = trim ? raw.trim() : raw;\n\n // Skip empty lines\n if (!text) continue;\n\n // Skip comments\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent });\n }\n\n return result;\n }\n\n /**\n * Split by language-specific delimiters.\n */\n private splitByDelimiter(\n input: string,\n language: string,\n trim: boolean,\n commentPrefixes: readonly string[]\n ): Array<{ text: string; line: number; indent: number }> {\n const delimiter =\n this.config.split.delimiters?.[language] ??\n this.config.split.defaultDelimiter ??\n /,\\s*|\\n\\s*/;\n\n const parts = input.split(delimiter);\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < parts.length; i++) {\n const raw = parts[i];\n const text = trim ? raw.trim() : raw;\n\n if (!text) continue;\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent: 0 });\n }\n\n return result;\n }\n\n /**\n * Classify a line by its keyword category.\n * Returns the category name or undefined if no match.\n */\n private classifyLine(line: string, language: string): string | undefined {\n if (!this.config.keywords) return undefined;\n\n const lower = line.toLowerCase();\n const wordOrder = this.config.keywords.wordOrders?.[language] ?? 'SVO';\n\n for (const [category, keywordMap] of Object.entries(this.config.keywords.categories)) {\n const keywords = keywordMap[language] ?? keywordMap['en'] ?? [];\n for (const kw of keywords) {\n const kwLower = kw.toLowerCase();\n if (wordOrder === 'SOV') {\n // SOV: check end of line first, then start\n if (lower.endsWith(kwLower) || lower.startsWith(kwLower)) {\n return category;\n }\n } else {\n // SVO/VSO: check start of line\n if (lower.startsWith(kwLower)) {\n return category;\n }\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Resolve continuation keywords (e.g., 'and' → re-prefix with previous step type).\n * Returns the resolved string, or null if not a continuation.\n */\n private resolveContinuation(\n text: string,\n language: string,\n prevCategory: string | undefined\n ): string | null {\n if (!this.config.continuation || !prevCategory) return null;\n\n const contKeywords =\n this.config.continuation.keywords[language] ?? this.config.continuation.keywords['en'] ?? [];\n\n const lower = text.toLowerCase();\n for (const kw of contKeywords) {\n const kwLower = kw.toLowerCase();\n if (lower.startsWith(kwLower)) {\n const content = text.slice(kw.length).trim();\n if (!content) return null;\n\n if (this.config.continuation.resolve) {\n return this.config.continuation.resolve(\n content,\n prevCategory,\n language,\n this.config.keywords?.categories ?? {}\n );\n }\n\n // Default: prepend previous category's keyword\n const prevKeywords =\n this.config.keywords?.categories[prevCategory]?.[language] ??\n this.config.keywords?.categories[prevCategory]?.['en'];\n if (prevKeywords?.[0]) {\n return prevKeywords[0] + ' ' + content;\n }\n\n return null;\n }\n }\n\n return null;\n }\n}\n\n// =============================================================================\n// Block Accumulator (for grouped/nested structures)\n// =============================================================================\n\n/**\n * A block of accumulated statements, grouped by a block-opening keyword.\n */\nexport interface StatementBlock<TMeta = unknown> {\n /** Block type (e.g., 'test', 'feature', 'scenario') */\n readonly type: string;\n /** Block name, if any (e.g., test name from quotes) */\n readonly name?: string;\n /** Statements within this block */\n readonly statements: readonly ParsedStatement[];\n /** Child blocks (for nested structures) */\n readonly children: readonly StatementBlock<TMeta>[];\n /** Starting line number */\n readonly line: number;\n /** Indentation level of the block opener */\n readonly indent: number;\n /** Domain-specific metadata */\n readonly meta?: TMeta;\n}\n\n/**\n * Configuration for block accumulation.\n */\nexport interface BlockConfig {\n /**\n * Block-opening keyword categories.\n * Statements classified in these categories start new blocks.\n */\n readonly blockTypes: readonly string[];\n\n /**\n * How to determine block nesting:\n * - 'indent': indentation-based (deeper indent = child block)\n * - 'flat': all blocks at same level (no nesting)\n */\n readonly nesting: 'indent' | 'flat';\n\n /**\n * Extract block name from statement text.\n * Default: extracts quoted string after keyword (e.g., test \"Login\" → \"Login\")\n */\n readonly extractName?: (text: string, category: string) => string | undefined;\n}\n\n/**\n * Result of block accumulation.\n */\nexport interface BlockResult<TMeta = unknown> {\n /** Top-level blocks */\n readonly blocks: readonly StatementBlock<TMeta>[];\n /** Statements not inside any block */\n readonly orphans: readonly ParsedStatement[];\n}\n\n/**\n * Accumulate parsed statements into blocks based on keyword categories.\n *\n * This groups statements into hierarchical blocks based on block-opening keywords\n * and indentation levels. Useful for test/feature/scenario structures.\n *\n * @example\n * ```typescript\n * const result = accumulateBlocks(statements, {\n * blockTypes: ['test', 'feature', 'setup'],\n * nesting: 'indent',\n * extractName: (text, category) => {\n * const match = text.match(/\"([^\"]+)\"/);\n * return match?.[1];\n * },\n * });\n * ```\n */\nexport function accumulateBlocks<TMeta = unknown>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n if (config.nesting === 'flat') {\n return accumulateFlat(statements, config);\n }\n return accumulateIndented(statements, config);\n}\n\nfunction accumulateFlat<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const blocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n let current: {\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n line: number;\n indent: number;\n } | null = null;\n\n const flush = () => {\n if (current) {\n blocks.push({\n type: current.type,\n ...(current.name != null && { name: current.name }),\n statements: current.stmts,\n children: [],\n line: current.line,\n indent: current.indent,\n });\n current = null;\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n flush();\n const name = config.extractName?.(stmt.source, stmt.category);\n current = {\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n line: stmt.line,\n indent: stmt.indent,\n };\n } else if (current) {\n current.stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n flush();\n return { blocks, orphans };\n}\n\nfunction accumulateIndented<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const rootBlocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n\n // Stack of open blocks with their indent level\n const stack: Array<{\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n children: StatementBlock<TMeta>[];\n line: number;\n indent: number;\n }> = [];\n\n const flushTo = (targetIndent: number) => {\n while (stack.length > 0) {\n const top = stack[stack.length - 1];\n if (top.indent >= targetIndent) {\n stack.pop();\n const block: StatementBlock<TMeta> = {\n type: top.type,\n ...(top.name != null && { name: top.name }),\n statements: top.stmts,\n children: top.children,\n line: top.line,\n indent: top.indent,\n };\n if (stack.length > 0) {\n stack[stack.length - 1].children.push(block);\n } else {\n rootBlocks.push(block);\n }\n } else {\n break;\n }\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n // Flush blocks at same or deeper indent\n flushTo(stmt.indent);\n const name = config.extractName?.(stmt.source, stmt.category);\n stack.push({\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n children: [],\n line: stmt.line,\n indent: stmt.indent,\n });\n } else if (stack.length > 0) {\n stack[stack.length - 1].stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n // Flush remaining\n flushTo(-1);\n\n return { blocks: rootBlocks, orphans };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AC9B,cAAM,IAAI;AACV,cAAM,QAA+B;AAAA,UACnC,MAAM,IAAI;AAAA,UACV,GAAI,IAAI,QAAQ,QAAQ,EAAE,MAAM,IAAI,KAAK;AAAA,UACzC,YAAY,IAAI;AAAA,UAChB,UAAU,IAAI;AAAA,UACd,MAAM,IAAI;AAAA,UACV,QAAQ,IAAI;AAAA,QACd;AACA,YAAI,MAAM,SAAS,GAAG;AACpB,gBAAM,MAAM,SAAS,CAAC,EAAE,SAAS,KAAK,KAAK;AAAA,QAC7C,OAAO;AACL,qBAAW,KAAK,KAAK;AAAA,QACvB;AAAA,MACF,OAAO;AACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,aAAW,QAAQ,YAAY;AAC7B,QAAI,KAAK,YAAY,OAAO,WAAW,SAAS,KAAK,QAAQ,GAAG;AAE9D,cAAQ,KAAK,MAAM;AACnB,YAAM,OAAO,OAAO,cAAc,KAAK,QAAQ,KAAK,QAAQ;AAC5D,YAAM,KAAK;AAAA,QACT,MAAM,KAAK;AAAA,QACX,GAAI,QAAQ,QAAQ,EAAE,KAAK;AAAA,QAC3B,OAAO,CAAC,IAAI;AAAA,QACZ,UAAU,CAAC;AAAA,QACX,MAAM,KAAK;AAAA,QACX,QAAQ,KAAK;AAAA,MACf,CAAC;AAAA,IACH,WAAW,MAAM,SAAS,GAAG;AAC3B,YAAM,MAAM,SAAS,CAAC,EAAE,MAAM,KAAK,IAAI;AAAA,IACzC,OAAO;AACL,cAAQ,KAAK,IAAI;AAAA,IACnB;AAAA,EACF;AAGA,UAAQ,EAAE;AAEV,SAAO,EAAE,QAAQ,YAAY,QAAQ;AACvC;","names":["num","length","import_intent","import_intent","import_intent","roles","import_intent","convertCommand","detectSelectorKind","generateRoleCombinations","sampleValue","toSemanticValue","sampleSelector","sampleLiteral","sampleExpression","detectSelectorKind","toSemanticValue","import_intent","import_intent","value","kind","position","normalized","normalized"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/core/types.ts","../src/core/logger.ts","../src/core/pattern-matching/utils/type-validation.ts","../src/core/pattern-matching/utils/possessive-keywords.ts","../src/core/pattern-matching/pattern-matcher.ts","../src/generation/pattern-generator.ts","../src/generation/renderer.ts","../src/grammar/types.ts","../src/grammar/transformer.ts","../src/interfaces/dictionary.ts","../src/interfaces/profile-provider.ts","../src/interfaces/value-extractor.ts","../src/ir/references.ts","../src/ir/explicit-parser.ts","../src/ir/explicit-renderer.ts","../src/ir/json-schema.ts","../src/ir/protocol-json.ts","../src/ir/from-interchange.ts","../src/ir/to-runtime-ast.ts","../src/api/create-dsl.ts","../src/prompts/prompt-generator.ts","../src/training/schema-synthesizer.ts","../src/feedback/feedback-formatter.ts","../src/api/domain-registry.ts","../src/api/dispatcher.ts","../src/aot/domain-scanner.ts","../src/aot/aot-orchestrator.ts","../src/aot/registry-bridge.ts","../src/schema/command-schema.ts","../src/generation/diagnostics.ts","../src/core/tokenization/token-utils.ts","../src/core/tokenization/extractors.ts","../src/core/tokenization/extractors/operator.ts","../src/core/tokenization/extractors/punctuation.ts","../src/core/tokenization/default-extractors.ts","../src/core/tokenization/base-tokenizer.ts","../src/multilingual/builders.ts","../src/core/tokenization/char-classifiers.ts","../src/core/tokenization/morphology/types.ts","../src/core/tokenization/morphology/base-normalizer.ts","../src/training/jsonl-writer.ts","../src/feedback/confidence-gate.ts","../src/feedback/pattern-tracker.ts","../src/parsing/multi-statement.ts"],"sourcesContent":["/**\n * @lokascript/framework - Generic framework for building multilingual DSLs\n *\n * This framework provides the building blocks for creating domain-specific languages\n * that work across multiple human languages (English, Japanese, Spanish, etc.) with\n * semantic parsing and grammar transformation.\n *\n * @example\n * ```typescript\n * import { createMultilingualDSL } from '@lokascript/framework';\n *\n * const myDSL = createMultilingualDSL({\n * schemas: [{ action: 'select', roles: [...] }],\n * languages: [{ code: 'en', profile: {...}, tokenizer: {...} }],\n * codeGenerator: (node) => generateSQL(node)\n * });\n *\n * myDSL.parse('select name from users', 'en');\n * myDSL.translate('select name from users', 'en', 'ja');\n * ```\n */\n\n// Main API\nexport * from './api';\n\n// AOT (generalized ahead-of-time compilation)\nexport * from './aot';\n\n// Interfaces (for dependency injection)\nexport * from './interfaces';\n\n// Core modules\nexport * from './schema';\nexport * from './generation';\n\n// Grammar exports - explicitly list to avoid PatternMatcher conflict with core\nexport { GrammarTransformer } from './grammar/transformer';\nexport type { TransformerConfig } from './grammar/transformer';\nexport { reorderRoles, insertMarkers, joinTokens } from './grammar/types';\nexport type {\n LanguageProfile,\n PatternTransform,\n ParsedElement,\n WordOrder,\n GrammaticalMarker,\n AdpositionType,\n} from './grammar/types';\n\n// Multilingual bridge — inject semantic language profiles into domain DSLs\n// (explicit list: the module also re-exports grammar types already exported above)\nexport {\n buildPatternProfile,\n buildDomainTokenizer,\n buildLanguageConfig,\n deriveRoleMarkers,\n} from './multilingual';\nexport type {\n GrammarProfileSlice,\n DomainVocabulary,\n DomainKeywordTranslation,\n DomainKeywordEntry,\n RoleMarkerSlice,\n TokenizationSlice,\n VerbSlice,\n DomainTokenizerOptions,\n LanguageConfigMeta,\n} from './multilingual';\n\n// Core - export classes and utilities\nexport * from './core';\n\n// Re-export key types for convenience\nexport type {\n ActionType,\n SemanticRole as SemanticRoleType,\n SemanticValue,\n SemanticNode,\n CommandSemanticNode,\n EventHandlerSemanticNode,\n ConditionalSemanticNode,\n CompoundSemanticNode,\n LoopSemanticNode,\n LiteralValue,\n SelectorValue,\n ReferenceValue,\n PropertyPathValue,\n ExpressionValue,\n SemanticMetadata,\n SourcePosition,\n LanguageToken,\n TokenStream,\n LanguageTokenizer,\n LanguagePattern,\n // v1.2 types\n Annotation,\n ProtocolDiagnostic,\n AsyncVariant,\n MatchArm,\n LSEEnvelope,\n} from './core/types';\n\nexport type { CommandSchema, RoleSpec } from './schema';\n\n// Renderer\nexport type {\n NaturalLanguageRenderer,\n KeywordTable,\n MarkerTable,\n RendererConfig,\n DomainRenderFn,\n DomainRendererConfig,\n} from './generation/renderer';\nexport {\n lookupKeyword,\n lookupMarker,\n buildPhrase,\n buildTablesFromProfiles,\n detectWordOrders,\n createSchemaRenderer,\n createDomainRenderer,\n} from './generation/renderer';\n\n// Diagnostics\nexport type {\n DiagnosticSeverity,\n Diagnostic,\n DiagnosticResult,\n DiagnosticSummary,\n DiagnosticCollector,\n DiagnosticOptions,\n} from './generation/diagnostics';\nexport { createDiagnosticCollector, fromError, filterBySeverity } from './generation/diagnostics';\n\nexport type {\n LanguageConfig,\n DSLConfig,\n MultilingualDSL,\n CodeGenerator,\n DomainExtension,\n ExtensionVocabulary,\n ValidationResult,\n CompileResult,\n DomainDescriptor,\n MCPToolDefinition,\n MCPToolResponse,\n DispatchResult,\n CompositeParseResult,\n CompositeStatement,\n CompositeError,\n DispatcherOptions,\n} from './api';\n\n// `createMultilingualDSL` is the package's primary entry point, so it is\n// exported by name rather than reaching consumers only through `export * from\n// './api'` above.\nexport { createMultilingualDSL, DomainRegistry, CrossDomainDispatcher } from './api';\n\n// Re-export helper functions\nexport {\n createLiteral,\n createSelector,\n createReference,\n createPropertyPath,\n createExpression,\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createCompoundNode,\n createLoopNode,\n extractValue,\n extractRoleValue,\n // v1.2 factories\n createTryNode,\n createAsyncNode,\n createMatchNode,\n} from './core/types';\n\nexport { defineCommand, defineRole } from './schema';\nexport { createSimpleTokenizer } from './core/tokenization/base-tokenizer';\nexport type { SimpleTokenizerConfig } from './core/tokenization/base-tokenizer';\n\n// Morphological normalization base class and types\nexport { BaseMorphologicalNormalizer } from './core/tokenization/morphology/base-normalizer';\nexport type {\n ConjugationEnding,\n NormalizerConfig,\n} from './core/tokenization/morphology/base-normalizer';\n\n// IR (Intermediate Representation) — explicit syntax, JSON conversion, reference validation\nexport * from './ir';\n\n// LLM Prompt Generation — auto-generate system prompts from CommandSchema[]\nexport * from './prompts';\n\n// Training Data Generation — synthesize (natural_language, LSE) pairs from schemas\nexport * from './training';\n\n// Feedback Loop — structured errors, disambiguation, pattern tracking\nexport * from './feedback';\n\n// Multi-statement parser\nexport { createMultiStatementParser, accumulateBlocks } from './parsing/multi-statement';\nexport type {\n MultiStatementParser,\n MultiStatementConfig,\n MultiStatementResult,\n ParsedStatement,\n StatementError,\n StatementBlock,\n BlockConfig,\n BlockResult,\n KeywordMap,\n WordOrderHint,\n} from './parsing/multi-statement';\n","/**\n * Core Types — re-exported from @lokascript/intent + framework-specific extensions\n *\n * The universal semantic types (SemanticNode, SemanticValue, etc.) now live in\n * @lokascript/intent and are re-exported here for backward compatibility.\n *\n * Framework-specific types (tokenization, pattern matching) are defined below.\n */\n\n// =============================================================================\n// Re-export everything from @lokascript/intent\n// =============================================================================\n\nexport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n ExpectedType,\n LiteralValue,\n SelectorValue,\n ReferenceValue,\n PropertyPathValue,\n ExpressionValue,\n FlagValue,\n Annotation,\n ProtocolDiagnostic,\n AsyncVariant,\n MatchArm,\n SemanticNode,\n SemanticMetadata,\n SourcePosition,\n CommandSemanticNode,\n EventHandlerSemanticNode,\n EventModifiers,\n ConditionalSemanticNode,\n CompoundSemanticNode,\n LoopVariant,\n LoopSemanticNode,\n LSEEnvelope,\n} from '@lokascript/intent';\n\nexport {\n createLiteral,\n createSelector,\n createReference,\n createPropertyPath,\n createExpression,\n createFlag,\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createCompoundNode,\n createLoopNode,\n createTryNode,\n createAsyncNode,\n createMatchNode,\n extractValue,\n extractRoleValue,\n getRoleValue,\n} from '@lokascript/intent';\n\n// =============================================================================\n// Framework-specific types (multilingual DSL infrastructure)\n// =============================================================================\n\nimport type {\n ActionType,\n SemanticRole,\n SemanticValue,\n SelectorValue,\n ExpectedType,\n SourcePosition,\n} from '@lokascript/intent';\n\n/**\n * Token kind - categorizes what type of token this is.\n */\nexport type TokenKind =\n | 'keyword' // Command or modifier keyword\n | 'selector' // CSS selector or identifier (#id, .class, table-name)\n | 'literal' // String or number literal\n | 'particle' // Grammatical particle (を, に, من)\n | 'conjunction' // Grammatical conjunction\n | 'event-modifier' // Event modifier (.once, .debounce(300))\n | 'identifier' // Generic identifier\n | 'operator' // Operators (., +, -, etc.)\n | 'punctuation' // Punctuation (parentheses, etc.)\n | 'url'; // URL or path\n\n/**\n * A language token - the result of tokenization.\n */\nexport interface LanguageToken {\n readonly value: string;\n readonly kind: TokenKind;\n readonly position: SourcePosition;\n readonly normalized?: string;\n readonly stem?: string;\n readonly stemConfidence?: number;\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Token stream - provides sequential access to tokens with backtracking.\n */\nexport interface TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n peek(offset?: number): LanguageToken | null;\n advance(): LanguageToken;\n isAtEnd(): boolean;\n mark(): StreamMark;\n reset(mark: StreamMark): void;\n position(): number;\n}\n\nexport interface StreamMark {\n readonly position: number;\n}\n\n/**\n * Language tokenizer interface - converts text to tokens.\n */\nexport interface LanguageTokenizer {\n readonly language: string;\n readonly direction: 'ltr' | 'rtl';\n tokenize(input: string): TokenStream;\n classifyToken(token: string): TokenKind;\n}\n\n// =============================================================================\n// Pattern Matching Types\n// =============================================================================\n\nexport interface LanguagePattern {\n readonly id: string;\n readonly language: string;\n readonly command: ActionType;\n readonly priority: number;\n readonly template: PatternTemplate;\n readonly extraction: ExtractionRules;\n readonly constraints?: PatternConstraints;\n}\n\nexport interface PatternTemplate {\n readonly format: string;\n readonly tokens: PatternToken[];\n}\n\nexport type PatternToken = LiteralPatternToken | RolePatternToken | GroupPatternToken;\n\nexport interface LiteralPatternToken {\n readonly type: 'literal';\n readonly value: string;\n readonly alternatives?: string[];\n}\n\nexport interface RolePatternToken {\n readonly type: 'role';\n readonly role: SemanticRole;\n readonly optional?: boolean;\n readonly expectedTypes?: Array<ExpectedType>;\n readonly greedy?: boolean;\n}\n\nexport interface GroupPatternToken {\n readonly type: 'group';\n readonly tokens: PatternToken[];\n readonly optional?: boolean;\n}\n\nexport interface ExtractionRules {\n readonly [role: string]: ExtractionRule;\n}\n\nexport interface ExtractionRule {\n readonly position?: number;\n readonly marker?: string;\n readonly markerAlternatives?: string[];\n readonly transform?: (raw: string) => SemanticValue;\n readonly default?: SemanticValue;\n readonly value?: string;\n readonly fromRole?: string;\n}\n\nexport interface PatternConstraints {\n readonly requiredRoles?: SemanticRole[];\n readonly forbiddenRoles?: SemanticRole[];\n readonly validPatientTypes?: Array<SelectorValue['selectorKind']>;\n readonly conflictsWith?: string[];\n}\n\nexport interface PatternMatchResult {\n readonly pattern: LanguagePattern;\n readonly captured: ReadonlyMap<SemanticRole, SemanticValue>;\n readonly consumedTokens: number;\n readonly confidence: number;\n}\n\nexport interface PatternMatchError {\n readonly message: string;\n readonly position: SourcePosition;\n readonly expectedPatterns?: string[];\n readonly partialMatch?: Partial<PatternMatchResult>;\n}\n","/**\n * Debug Logging System\n *\n * Provides environment-aware debug logging for the framework.\n * Enable via DEBUG environment variable or programmatically.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n isEnabled(): boolean;\n}\n\nclass DebugLogger {\n private enabled: boolean;\n private namespace: string;\n\n constructor(namespace: string) {\n this.namespace = namespace;\n this.enabled = this.checkEnabled();\n }\n\n private checkEnabled(): boolean {\n // Check if running in Node.js\n if (typeof process !== 'undefined' && process.env) {\n const DEBUG = process.env.DEBUG || '';\n // Enable if DEBUG=* or DEBUG=framework:* or DEBUG=framework:namespace\n return (\n DEBUG === '*' ||\n DEBUG.includes('framework:*') ||\n DEBUG.includes(`framework:${this.namespace}`)\n );\n }\n return false;\n }\n\n private log(level: LogLevel, message: string, ...args: any[]): void {\n if (!this.enabled) return;\n\n const prefix = `[framework:${this.namespace}]`;\n const timestamp = new Date().toISOString();\n\n switch (level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(`${timestamp} ${prefix} INFO:`, message, ...args);\n break;\n case 'warn':\n // eslint-disable-next-line no-console\n console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);\n break;\n case 'error':\n // eslint-disable-next-line no-console\n console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);\n break;\n }\n }\n\n debug(message: string, ...args: any[]): void {\n this.log('debug', message, ...args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.log('error', message, ...args);\n }\n\n /**\n * Check if logging is enabled for this namespace.\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n\n /**\n * Programmatically enable logging for this namespace.\n */\n enable(): void {\n this.enabled = true;\n }\n\n /**\n * Programmatically disable logging for this namespace.\n */\n disable(): void {\n this.enabled = false;\n }\n}\n\n/**\n * Create a logger for a specific namespace.\n *\n * @param namespace - Logger namespace (e.g., 'pattern-matcher', 'tokenizer')\n * @returns Logger instance\n *\n * @example\n * const logger = createLogger('pattern-matcher');\n * logger.debug('Matching pattern:', pattern.id);\n * logger.warn('Low confidence match:', confidence);\n */\nexport function createLogger(namespace: string): Logger {\n return new DebugLogger(namespace);\n}\n\n/**\n * No-op logger that does nothing.\n * Useful for disabling logging in production builds.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n isEnabled: () => false,\n};\n","/**\n * Type Validation Utility\n *\n * Shared utilities for validating semantic value types against expected types.\n * Used by pattern-matcher to validate captured role values.\n */\n\nimport type { SemanticValue } from '../../types';\n\n/**\n * Semantic value type strings.\n */\nexport type SemanticValueType = SemanticValue['type'];\n\n/**\n * Check if a value type matches any of the expected types.\n *\n * The 'expression' type is treated as a wildcard that matches any value.\n * The 'property-path' type is compatible with selector, reference, and expression.\n *\n * @param actualType The actual type of the value\n * @param expectedTypes Array of expected types\n * @returns True if the type is compatible\n */\nexport function isTypeCompatible(\n actualType: SemanticValueType | string,\n expectedTypes: (SemanticValueType | string)[]\n): boolean {\n // Empty expected types means any type is valid\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n // Direct match\n if (expectedTypes.includes(actualType)) {\n return true;\n }\n\n // 'expression' is always compatible (wildcard)\n if (expectedTypes.includes('expression')) {\n return true;\n }\n\n // 'property-path' is compatible with selector, reference, and expression\n if (actualType === 'property-path') {\n return expectedTypes.some(t => ['selector', 'reference', 'expression'].includes(t));\n }\n\n return false;\n}\n\n/**\n * Validate a semantic value against expected types.\n *\n * @param value The semantic value to validate\n * @param expectedTypes Array of expected types (empty means any type is valid)\n * @returns True if the value type is valid\n */\nexport function validateValueType(\n value: SemanticValue,\n expectedTypes?: (SemanticValueType | string)[]\n): boolean {\n if (!expectedTypes || expectedTypes.length === 0) {\n return true;\n }\n\n return isTypeCompatible(value.type, expectedTypes);\n}\n\n/**\n * Check if a value is a CSS selector.\n */\nexport function isCSSSelector(value: string): boolean {\n return value.startsWith('.') || value.startsWith('#') || value.startsWith('<');\n}\n\n/**\n * Check if a value is a class name (starts with .).\n */\nexport function isClassName(value: string): boolean {\n return value.startsWith('.');\n}\n\n/**\n * Check if a value is an ID selector (starts with #).\n */\nexport function isIdSelector(value: string): boolean {\n return value.startsWith('#');\n}\n\n/**\n * Check if a value is a CSS property reference (starts with *).\n */\nexport function isCSSPropertyRef(value: string): boolean {\n return value.startsWith('*');\n}\n\n/**\n * Check if a value is a numeric value.\n */\nexport function isNumericValue(value: string): boolean {\n // Handle duration values (e.g., \"100ms\", \"2s\")\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n return true;\n }\n\n // Plain number\n const num = parseFloat(value);\n return !isNaN(num) && isFinite(num);\n}\n\n/**\n * Check if a value is a property name (identifier-like).\n */\nexport function isPropertyName(value: string): boolean {\n // Property names are identifiers (start with letter or _, contain alphanumeric)\n return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);\n}\n\n/**\n * Check if a value is a variable reference (starts with :).\n */\nexport function isVariableRef(value: string): boolean {\n return value.startsWith(':');\n}\n\n/**\n * Check if a value is a built-in reference (me, you, it, etc.).\n */\nexport function isBuiltInReference(value: string): boolean {\n const builtIns = new Set(['me', 'you', 'it', 'result', 'event', 'target', 'body']);\n return builtIns.has(value.toLowerCase());\n}\n","/**\n * Possessive Keywords Utility\n *\n * Provides functions to look up possessive keywords from language profiles.\n * Used by pattern-matcher to recognize possessive expressions like \"my value\".\n */\n\n/**\n * Minimal profile interface for possessive keyword lookup.\n */\nexport interface PossessiveProfile {\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n/**\n * Get the reference for a possessive keyword from a profile.\n *\n * @param profile Language profile\n * @param keyword Possessive keyword (e.g., 'my', 'your', 'its')\n * @returns The reference (e.g., 'me', 'you', 'it') or undefined if not found\n */\nexport function getPossessiveReference(\n profile: PossessiveProfile | undefined,\n keyword: string\n): string | undefined {\n return profile?.possessive?.keywords?.[keyword];\n}\n\n/**\n * Check if a keyword is a possessive keyword in the given profile.\n *\n * @param profile Language profile\n * @param keyword Keyword to check\n * @returns True if the keyword is a possessive keyword\n */\nexport function isPossessiveKeyword(\n profile: PossessiveProfile | undefined,\n keyword: string\n): boolean {\n return profile?.possessive?.keywords?.[keyword] !== undefined;\n}\n\n/**\n * Get all possessive keywords from a profile.\n *\n * @param profile Language profile\n * @returns Record of possessive keywords to references, or empty object\n */\nexport function getAllPossessiveKeywords(\n profile: PossessiveProfile | undefined\n): Record<string, string> {\n return profile?.possessive?.keywords ?? {};\n}\n","/**\n * Pattern Matcher\n *\n * Matches tokenized input against language patterns to extract semantic roles.\n * This is the core algorithm for multilingual parsing.\n */\n\nimport type {\n LanguagePattern,\n PatternToken,\n PatternMatchResult,\n ReferenceValue,\n SemanticRole,\n SemanticValue,\n TokenStream,\n LanguageToken,\n} from '../types';\nimport { createSelector, createLiteral, createReference, createPropertyPath } from '../types';\nimport { createLogger } from '../logger';\n\n/**\n * Helper to check if a value is a built-in reference.\n * In the generic framework, we don't assume any built-in references.\n * DSLs that need references (like hyperscript's 'me', 'it', 'you') should\n * handle them in their tokenizer or provide a custom reference validator.\n *\n * For generic DSLs, identifiers are treated as expressions by default.\n */\nfunction isValidReference(_value: string): boolean {\n // In generic framework, no built-in references\n // Identifiers should be expressions\n return false;\n}\nimport { isTypeCompatible } from './utils/type-validation';\nimport { getPossessiveReference } from './utils/possessive-keywords';\n\n/**\n * Minimal profile interface needed by PatternMatcher.\n * DSLs can provide this to enable possessive handling and language-specific features.\n */\nexport interface PatternMatcherProfile {\n readonly code: string;\n readonly possessive?: {\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Pattern Matcher\n// =============================================================================\n\nexport class PatternMatcher {\n /** Maximum tokens to scan ahead when looking for a group's leading marker */\n private static readonly MAX_MARKER_SCAN = 3;\n\n /** Debug logger */\n private logger = createLogger('pattern-matcher');\n\n /** Current language profile for the pattern being matched */\n private currentProfile: PatternMatcherProfile | undefined;\n\n /**\n * Safely convert a value to lowercase string.\n * Provides protection against non-string values at runtime.\n */\n private safeToLowerCase(value: unknown): string {\n if (typeof value === 'string') {\n return value.toLowerCase();\n }\n if (value === null || value === undefined) {\n return '';\n }\n return String(value).toLowerCase();\n }\n\n /**\n * Try to match a single pattern against the token stream.\n * Returns the match result or null if no match.\n *\n * @param tokens - Token stream to match against\n * @param pattern - Pattern to match\n * @param profile - Optional language profile for possessive handling\n */\n matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern,\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const mark = tokens.mark();\n const captured = new Map<SemanticRole, SemanticValue>();\n\n // Debug logging\n this.logger.debug('========================================');\n this.logger.debug('matchPattern ENTRY');\n this.logger.debug('Pattern ID:', pattern.id);\n this.logger.debug('Pattern command:', pattern.command);\n this.logger.debug('Pattern language:', pattern.language);\n this.logger.debug('Pattern template:', JSON.stringify(pattern.template, null, 2));\n\n if (this.logger.isEnabled()) {\n const firstTokens = [];\n for (let i = 0; i < 10; i++) {\n const t = tokens.peek(i);\n if (t)\n firstTokens.push({\n type: (t as any).type,\n value: (t as any).value,\n kind: (t as any).kind,\n });\n else break;\n }\n this.logger.debug('Input tokens (first 10):', firstTokens);\n this.logger.debug('Profile code:', profile?.code);\n }\n\n // Use provided profile for possessive keyword lookup\n this.currentProfile = profile;\n\n // Reset match counters for this pattern\n this.stemMatchCount = 0;\n this.totalKeywordMatches = 0;\n\n this.logger.debug('--- Calling matchTokenSequence ---');\n this.logger.debug('Pattern tokens to match:', JSON.stringify(pattern.template.tokens, null, 2));\n const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);\n this.logger.debug('matchTokenSequence returned:', success);\n this.logger.debug(\n 'Captured roles:',\n Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])\n );\n\n if (!success) {\n this.logger.debug('>>> MATCH FAILED - resetting token position');\n tokens.reset(mark);\n return null;\n }\n\n // Calculate confidence BEFORE applying defaults\n // This ensures defaulted roles don't artificially inflate confidence\n const confidence = this.calculateConfidence(pattern, captured);\n\n // Apply extraction rules to fill in any missing roles with defaults\n this.applyExtractionRules(pattern, captured);\n\n return {\n pattern,\n captured,\n consumedTokens: tokens.position() - mark.position,\n confidence,\n };\n }\n\n /**\n * Try to match multiple patterns, return the best match.\n *\n * @param tokens - Token stream to match against\n * @param patterns - Candidate patterns to try\n * @param profile - Optional language profile for possessive handling\n */\n matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[],\n profile?: PatternMatcherProfile\n ): PatternMatchResult | null {\n const matches: PatternMatchResult[] = [];\n\n for (const pattern of patterns) {\n const mark = tokens.mark();\n const result = this.matchPattern(tokens, pattern, profile);\n\n if (result) {\n matches.push(result);\n }\n\n tokens.reset(mark);\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort by confidence and priority\n matches.sort((a, b) => {\n // First by priority\n const priorityDiff = b.pattern.priority - a.pattern.priority;\n if (priorityDiff !== 0) return priorityDiff;\n\n // Then by confidence\n const confidenceDiff = b.confidence - a.confidence;\n if (Math.abs(confidenceDiff) > 0.001) return confidenceDiff;\n\n // Then by tokens consumed (prefer more complete matches)\n return b.consumedTokens - a.consumedTokens;\n });\n\n // Re-consume tokens for the best match\n const best = matches[0];\n this.matchPattern(tokens, best.pattern);\n\n return best;\n }\n\n /**\n * Match a sequence of pattern tokens against the token stream.\n *\n * Supports bounded single-step backtracking: if an optional role consumes\n * a token and the immediately following pattern token fails, the matcher\n * resets to before the optional role and retries the failed token.\n */\n private matchTokenSequence(\n tokens: TokenStream,\n patternTokens: PatternToken[],\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n // Skip leading conjunctions for Arabic (proclitics: و, ف, ول, وب, etc.)\n // BUT NOT if the pattern explicitly expects a conjunction (proclitic patterns)\n const firstPatternToken = patternTokens[0];\n const patternExpectsConjunction =\n firstPatternToken?.type === 'literal' &&\n (firstPatternToken.value === 'and' ||\n firstPatternToken.value === 'then' ||\n firstPatternToken.alternatives?.includes('and') ||\n firstPatternToken.alternatives?.includes('then'));\n\n if (this.currentProfile?.code === 'ar' && !patternExpectsConjunction) {\n while (tokens.peek()?.kind === 'conjunction') {\n tokens.advance();\n }\n }\n\n // Backtracking state: track the most recent optional role that consumed a token\n let prevOptionalMark: ReturnType<TokenStream['mark']> | null = null;\n let prevOptionalRole: SemanticRole | null = null;\n\n for (let i = 0; i < patternTokens.length; i++) {\n const patternToken = patternTokens[i];\n this.logger.debug(' >> Matching pattern token:', JSON.stringify(patternToken, null, 2));\n const currTok = tokens.peek();\n this.logger.debug(\n ' >> Current input token:',\n currTok\n ? JSON.stringify({\n type: (currTok as any).type,\n value: (currTok as any).value,\n kind: (currTok as any).kind,\n })\n : 'EOF'\n );\n\n // Greedy role capture: consume all remaining tokens until the next\n // recognized marker keyword or end of input\n if (patternToken.type === 'role' && patternToken.greedy) {\n const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n // Merge parent-level stop markers so greedy roles inside groups\n // know when to stop for tokens outside the group (e.g., SOV verb keywords)\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) stopMarkers.add(m);\n }\n const values: string[] = [];\n while (!tokens.isAtEnd()) {\n const nextToken = tokens.peek();\n if (!nextToken) break;\n if (this.isStopMarker(nextToken, stopMarkers)) break;\n values.push(nextToken.value);\n tokens.advance();\n }\n if (values.length > 0) {\n captured.set(patternToken.role, { type: 'expression', raw: values.join(' ') });\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n } else if (patternToken.optional) {\n continue;\n } else {\n return false;\n }\n }\n\n // Group tokens: compute sibling stop markers and forward to inner matching\n if (patternToken.type === 'group') {\n const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);\n if (parentStopMarkers) {\n for (const m of parentStopMarkers) siblingStopMarkers.add(m);\n }\n const groupMatched = this.matchGroupToken(\n tokens,\n patternToken as PatternToken & { type: 'group' },\n captured,\n siblingStopMarkers\n );\n if (groupMatched) {\n prevOptionalMark = null;\n prevOptionalRole = null;\n continue;\n }\n if (this.isOptional(patternToken)) {\n continue;\n }\n return false;\n }\n\n // Save stream position before attempting optional roles\n const isOptionalRole = patternToken.type === 'role' && patternToken.optional === true;\n const markBefore = isOptionalRole ? tokens.mark() : null;\n\n // SOV marker-stealing guard: before matching a required role, check if\n // the current input token would match the immediately-following pattern\n // literal (the role's own postpositional marker). If so, skip consuming\n // this token as a role value — it should be matched as the literal instead.\n const isRoleToken = patternToken.type === 'role';\n if (isRoleToken && !isOptionalRole) {\n const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;\n if (nextPT?.type === 'literal') {\n const currentToken = tokens.peek();\n if (currentToken && this.getMatchType(currentToken, nextPT.value) !== 'none') {\n // Current token is the marker literal, not a role value — treat role as failed\n this.logger.debug(\n ' >> MARKER-STEAL GUARD: current token matches next literal, skipping role'\n );\n // Fall through to failure handling below\n // (which will trigger backtracking of previous optional role)\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n }\n }\n\n const matched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Match result:', matched);\n\n if (matched) {\n if (isOptionalRole) {\n // Track this consumption so we can undo it if the next token fails\n prevOptionalMark = markBefore;\n prevOptionalRole = patternToken.role;\n } else {\n // Non-optional succeeded — clear backtrack state\n prevOptionalMark = null;\n prevOptionalRole = null;\n }\n continue;\n }\n\n // Match failed\n this.logger.debug(' >> Token match FAILED');\n\n if (this.isOptional(patternToken)) {\n continue;\n }\n\n // Required token failed — try backtracking over the previous optional role\n if (prevOptionalMark && prevOptionalRole) {\n this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);\n tokens.reset(prevOptionalMark);\n captured.delete(prevOptionalRole);\n prevOptionalMark = null;\n prevOptionalRole = null;\n\n // Retry the current (failed) pattern token from the restored position\n const retryMatched = this.matchPatternToken(tokens, patternToken, captured);\n this.logger.debug(' >> Backtrack retry result:', retryMatched);\n if (retryMatched) {\n continue;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Match a single pattern token against the current position in the stream.\n */\n private matchPatternToken(\n tokens: TokenStream,\n patternToken: PatternToken,\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n switch (patternToken.type) {\n case 'literal':\n return this.matchLiteralToken(tokens, patternToken);\n\n case 'role':\n return this.matchRoleToken(tokens, patternToken, captured);\n\n case 'group':\n return this.matchGroupToken(tokens, patternToken, captured);\n\n default:\n return false;\n }\n }\n\n /**\n * Match a literal pattern token (keyword or particle).\n */\n private matchLiteralToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'literal' }\n ): boolean {\n const token = tokens.peek();\n this.logger.debug(' >>> matchLiteralToken: expecting', patternToken.value);\n this.logger.debug(\n ' >>> matchLiteralToken: got token',\n token\n ? JSON.stringify({\n type: (token as any).type,\n value: (token as any).value,\n kind: (token as any).kind,\n })\n : 'null'\n );\n if (!token) {\n this.logger.debug(' >>> matchLiteralToken: FAIL - no token');\n return false;\n }\n\n // Check main value\n const matchType = this.getMatchType(token, patternToken.value);\n this.logger.debug(\n ' >>> matchType for',\n token.value,\n 'vs',\n patternToken.value,\n ':',\n matchType\n );\n if (matchType !== 'none') {\n this.totalKeywordMatches++;\n if (matchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n\n // Check alternatives\n if (patternToken.alternatives) {\n for (const alt of patternToken.alternatives) {\n const altMatchType = this.getMatchType(token, alt);\n if (altMatchType !== 'none') {\n this.totalKeywordMatches++;\n if (altMatchType === 'stem') {\n this.stemMatchCount++;\n }\n tokens.advance();\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Match a role pattern token (captures a semantic value).\n * Handles multi-token expressions like:\n * - 'my value' (possessive keyword + property)\n * - '#dialog.showModal()' (method call)\n * - \"#element's *opacity\" (possessive selector + property)\n */\n private matchRoleToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'role' },\n captured: Map<SemanticRole, SemanticValue>\n ): boolean {\n this.logger.debug(' >>> matchRoleToken ENTRY: capturing role', patternToken.role);\n this.logger.debug(' >>> matchRoleToken: expected types', patternToken.expectedTypes);\n this.logger.debug(' >>> matchRoleToken: optional?', patternToken.optional);\n // Skip noise words like \"the\" before selectors (English idiom support)\n this.skipNoiseWords(tokens);\n\n const token = tokens.peek();\n this.logger.debug(\n ' >>> After skipNoiseWords, current token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n if (!token) {\n return patternToken.optional || false;\n }\n\n // Check for possessive expression (e.g., 'my value', 'its innerHTML')\n const possessiveValue = this.tryMatchPossessiveExpression(tokens);\n if (possessiveValue) {\n // Validate expected types if specified\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveValue);\n return true;\n }\n\n // Check for method call expression (e.g., '#dialog.showModal()')\n const methodCallValue = this.tryMatchMethodCallExpression(tokens);\n if (methodCallValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, methodCallValue);\n return true;\n }\n\n // Check for possessive selector expression (e.g., \"#element's *opacity\")\n const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);\n if (possessiveSelectorValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n // property-path is compatible with selector, reference, and expression\n if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, possessiveSelectorValue);\n return true;\n }\n\n // Check for property access expression (e.g., 'userData.name', 'it.data')\n const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);\n if (propertyAccessValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, propertyAccessValue);\n return true;\n }\n\n // Check for selector + property expression (e.g., '#output.innerText')\n // This handles cases where the tokenizer produces two selector tokens\n const selectorPropertyValue = this.tryMatchSelectorPropertyExpression(tokens);\n if (selectorPropertyValue) {\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {\n return patternToken.optional || false;\n }\n }\n captured.set(patternToken.role, selectorPropertyValue);\n return true;\n }\n\n // Try to extract a semantic value from the token\n this.logger.debug(\n ' >>> Trying tokenToSemanticValue for token:',\n token ? JSON.stringify({ value: (token as any).value, kind: (token as any).kind }) : 'null'\n );\n const value = this.tokenToSemanticValue(token);\n this.logger.debug(\n ' >>> tokenToSemanticValue returned:',\n value ? JSON.stringify(value) : 'null'\n );\n if (!value) {\n return patternToken.optional || false;\n }\n\n // Validate expected types if specified\n this.logger.debug(\n ' >>> Validating type:',\n value.type,\n 'against expected:',\n patternToken.expectedTypes\n );\n if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {\n if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {\n this.logger.debug(' >>> TYPE MISMATCH - returning', patternToken.optional || false);\n return patternToken.optional || false;\n }\n }\n this.logger.debug(' >>> Type validation PASSED');\n\n captured.set(patternToken.role, value);\n tokens.advance();\n return true;\n }\n\n /**\n * Try to match a possessive expression like 'my value' or 'its innerHTML'.\n * Returns the PropertyPathValue if matched, or null if not.\n */\n private tryMatchPossessiveExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Use profile-based possessive keyword lookup\n if (!this.currentProfile) return null;\n\n const tokenValue = token.normalized || token.value;\n const tokenLower = this.safeToLowerCase(tokenValue);\n const baseRef = getPossessiveReference(this.currentProfile, tokenLower);\n\n if (!baseRef) return null;\n\n // We have a possessive keyword, look ahead for property name\n const mark = tokens.mark();\n tokens.advance();\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n // Just the possessive keyword, no property - revert\n tokens.reset(mark);\n return null;\n }\n\n // Property should be an identifier, keyword (not structural), or selector (for style/dot/attr)\n // Examples: \"my value\", \"my innerHTML\", \"my *background\", \"my *opacity\", \"my @data-count\"\n // Also handles dot-property access: \"my.textContent\" tokenized as \"my\" + \".textContent\"\n if (\n propertyToken.kind === 'identifier' ||\n (propertyToken.kind === 'keyword' && !this.isStructuralKeyword(propertyToken.value)) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('*')) ||\n (propertyToken.kind === 'selector' && propertyToken.value.startsWith('@')) ||\n (propertyToken.kind === 'selector' &&\n propertyToken.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyToken.value))\n ) {\n tokens.advance();\n\n // For dot-property selectors (.textContent), strip the leading dot\n let propertyName = propertyToken.value;\n if (\n propertyToken.kind === 'selector' &&\n propertyName.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(propertyName)\n ) {\n propertyName = propertyName.substring(1);\n }\n\n // Consume chained dot-property access (.parentElement.style.display)\n let chainedProps = propertyName;\n while (\n tokens.peek()?.kind === 'selector' &&\n tokens.peek()!.value.startsWith('.') &&\n /^\\.[a-zA-Z_]\\w*/.test(tokens.peek()!.value)\n ) {\n chainedProps += tokens.peek()!.value; // keep the dots for chaining\n tokens.advance();\n }\n\n // Check for method call — next token is '(' in the value (e.g., .getAttribute(\"data-id\"))\n const nextPeek = tokens.peek();\n if (nextPeek?.kind === 'literal' && nextPeek.value.startsWith('(')) {\n // Consume method args\n chainedProps += nextPeek.value;\n tokens.advance();\n }\n\n // Create property-path: my value -> { object: me, property: 'value' }\n // baseRef from getPossessiveReference is always a valid reference ('me', 'you', 'it', etc.)\n return createPropertyPath(createReference(baseRef as ReferenceValue['value']), chainedProps);\n }\n\n // Not a valid property, revert\n tokens.reset(mark);\n return null;\n }\n\n /**\n * Check if a keyword is a structural keyword (preposition, control flow, etc.)\n * that shouldn't be consumed as a property name.\n */\n private isStructuralKeyword(value: string): boolean {\n const structural = new Set([\n // Prepositions\n 'into',\n 'in',\n 'to',\n 'from',\n 'at',\n 'by',\n 'with',\n 'without',\n 'before',\n 'after',\n 'of',\n 'as',\n 'on',\n // Control flow\n 'then',\n 'end',\n 'else',\n 'if',\n 'repeat',\n 'while',\n 'for',\n // Commands (shouldn't be property names)\n 'toggle',\n 'add',\n 'remove',\n 'put',\n 'set',\n 'show',\n 'hide',\n 'increment',\n 'decrement',\n 'send',\n 'trigger',\n 'call',\n ]);\n return structural.has(value.toLowerCase());\n }\n\n /**\n * Try to match a method call expression like '#dialog.showModal()'.\n * Pattern: selector + '.' + identifier + '(' + [args] + ')'\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchMethodCallExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: . identifier (\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const methodToken = tokens.peek();\n if (!methodToken || methodToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume method name\n\n const openParen = tokens.peek();\n if (!openParen || openParen.kind !== 'punctuation' || openParen.value !== '(') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume (\n\n // Consume arguments until we find ) (with depth limit for security)\n const args: string[] = [];\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n tokens.advance(); // consume )\n break;\n }\n // Skip commas\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value: #dialog.showModal()\n const methodCall = `${token.value}.${methodToken.value}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n /**\n * Try to match a property access expression like 'userData.name' or 'it.data'.\n * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]\n * Returns an expression value if matched, or null if not.\n */\n private tryMatchPropertyAccessExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token) return null;\n\n // Must start with an identifier or keyword reference\n if (token.kind !== 'identifier' && token.kind !== 'keyword') return null;\n\n // Look ahead for: . identifier\n const mark = tokens.mark();\n tokens.advance(); // consume first token\n\n const dotToken = tokens.peek();\n if (!dotToken || dotToken.kind !== 'operator' || dotToken.value !== '.') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume .\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property name\n\n // Build the property chain\n let chain = `${token.value}.${propertyToken.value}`;\n let depth = 1; // Already have one property access\n\n // Continue for nested property access (e.g., userData.address.city)\n // With depth limit for security\n while (!tokens.isAtEnd() && depth < PatternMatcher.MAX_PROPERTY_DEPTH) {\n const nextDot = tokens.peek();\n if (!nextDot || nextDot.kind !== 'operator' || nextDot.value !== '.') {\n break;\n }\n tokens.advance(); // consume .\n\n const nextProp = tokens.peek();\n if (!nextProp || nextProp.kind !== 'identifier') {\n // Dot without property - put the dot back and stop\n // Can't easily put a single token back, so we'll include it\n break;\n }\n tokens.advance(); // consume property\n chain += `.${nextProp.value}`;\n depth++;\n }\n\n // Check for method call: chain + '(' + args + ')'\n // e.g., me.insertBefore(draggedItem, dropTarget)\n const openParen = tokens.peek();\n if (openParen && openParen.kind === 'punctuation' && openParen.value === '(') {\n tokens.advance(); // consume (\n\n // Collect arguments (comma-separated values)\n const args: string[] = [];\n let argDepth = 0; // Track nested parentheses\n while (!tokens.isAtEnd() && args.length < PatternMatcher.MAX_METHOD_ARGS) {\n const argToken = tokens.peek();\n if (!argToken) break;\n\n // Handle close paren - respecting nesting\n if (argToken.kind === 'punctuation' && argToken.value === ')') {\n if (argDepth === 0) {\n tokens.advance(); // consume )\n break;\n }\n argDepth--;\n }\n // Track nested open parens\n if (argToken.kind === 'punctuation' && argToken.value === '(') {\n argDepth++;\n }\n // Skip commas between arguments\n if (argToken.kind === 'punctuation' && argToken.value === ',') {\n tokens.advance();\n continue;\n }\n // Collect arg value\n args.push(argToken.value);\n tokens.advance();\n }\n\n // Create expression value with method call: me.insertBefore(a, b)\n const methodCall = `${chain}(${args.join(', ')})`;\n return {\n type: 'expression',\n raw: methodCall,\n } as SemanticValue;\n }\n\n // Create expression value: userData.name\n return {\n type: 'expression',\n raw: chain,\n } as SemanticValue;\n }\n\n /**\n * Try to match a possessive selector expression like \"#element's *opacity\".\n * Pattern: selector + \"'s\" + (selector | identifier)\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchPossessiveSelectorExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Look ahead for: 's (possessive marker)\n const mark = tokens.mark();\n tokens.advance(); // consume selector\n\n const possessiveToken = tokens.peek();\n if (\n !possessiveToken ||\n possessiveToken.kind !== 'punctuation' ||\n possessiveToken.value !== \"'s\"\n ) {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume 's\n\n const propertyToken = tokens.peek();\n if (!propertyToken) {\n tokens.reset(mark);\n return null;\n }\n\n // Property can be a selector (*opacity) or identifier\n if (propertyToken.kind !== 'selector' && propertyToken.kind !== 'identifier') {\n tokens.reset(mark);\n return null;\n }\n tokens.advance(); // consume property\n\n // Create property-path: #element's *opacity\n return createPropertyPath(createSelector(token.value), propertyToken.value);\n }\n\n /**\n * Try to match a selector + property expression like \"#output.innerText\".\n * This handles cases where the tokenizer produces two selector tokens:\n * - #output (id selector)\n * - .innerText (looks like class selector, but is actually property)\n *\n * Pattern: id-selector + class-selector-that-is-actually-property\n * Returns a property-path value if matched, or null if not.\n */\n private tryMatchSelectorPropertyExpression(tokens: TokenStream): SemanticValue | null {\n const token = tokens.peek();\n if (!token || token.kind !== 'selector') return null;\n\n // Must be an ID selector (starts with #)\n if (typeof token.value !== 'string' || !token.value.startsWith('#')) return null;\n\n // Look ahead for: selector that looks like a property (.something)\n const mark = tokens.mark();\n tokens.advance(); // consume first selector\n\n const propertyToken = tokens.peek();\n if (!propertyToken || propertyToken.kind !== 'selector') {\n tokens.reset(mark);\n return null;\n }\n\n // Second token must look like a class selector (starts with .)\n // but we interpret it as a property access\n if (!propertyToken.value.startsWith('.')) {\n tokens.reset(mark);\n return null;\n }\n\n // Verify the next token is not a selector (to avoid consuming too many)\n // This helps distinguish \"#output.innerText\" from \"#box .child\"\n const peek2 = tokens.peek(1);\n if (peek2 && peek2.kind === 'selector') {\n // Could be a compound selector chain - only take first two\n }\n\n tokens.advance(); // consume property selector\n\n // Create property-path: #output.innerText\n // Extract property name without the leading dot\n const propertyName = propertyToken.value.slice(1);\n\n return createPropertyPath(createSelector(token.value), propertyName);\n }\n\n /**\n * Match a group pattern token (optional sequence).\n * When the group's leading marker isn't at the current position, scans ahead\n * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens\n * (e.g., a value like 'hello') to sit between groups without blocking later\n * marker matches.\n */\n private matchGroupToken(\n tokens: TokenStream,\n patternToken: PatternToken & { type: 'group' },\n captured: Map<SemanticRole, SemanticValue>,\n parentStopMarkers?: Set<string>\n ): boolean {\n const mark = tokens.mark();\n const capturedBefore = new Set(captured.keys());\n\n const success = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (success) return true;\n\n // Reset from failed attempt\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n\n if (!patternToken.optional) return false;\n\n // Marker scan: look ahead for the group's leading marker past intervening tokens.\n // This handles cases like \"types 'hello' into #search\" where 'hello' blocks the\n // 'into' marker from being found at the current position.\n const leadingMarker = this.getGroupLeadingMarker(patternToken);\n if (leadingMarker) {\n for (let offset = 1; offset <= PatternMatcher.MAX_MARKER_SCAN; offset++) {\n const ahead = tokens.peek(offset);\n if (!ahead) break;\n const aheadValue = (ahead.normalized || ahead.value).toLowerCase();\n if (aheadValue === leadingMarker) {\n this.logger.debug(\n ' >> MARKER SCAN: found',\n leadingMarker,\n 'at offset',\n offset,\n '- skipping intervening tokens'\n );\n // Advance past intervening tokens to reach the marker\n for (let s = 0; s < offset; s++) tokens.advance();\n\n // Retry group match from marker position\n const retrySuccess = this.matchTokenSequence(\n tokens,\n patternToken.tokens,\n captured,\n parentStopMarkers\n );\n if (retrySuccess) return true;\n\n // Retry failed — full reset\n tokens.reset(mark);\n for (const role of captured.keys()) {\n if (!capturedBefore.has(role)) captured.delete(role);\n }\n break;\n }\n }\n }\n\n return true; // Optional group, just skip\n }\n\n /**\n * Get the leading marker literal from an optional group.\n * Returns the lowercase marker value, or null if the group\n * doesn't start with a literal token (e.g., SOV groups where\n * the role comes before the marker).\n */\n private getGroupLeadingMarker(group: PatternToken & { type: 'group' }): string | null {\n const first = group.tokens[0];\n if (first?.type === 'literal') return first.value.toLowerCase();\n return null;\n }\n\n /**\n * Get the type of match for a token against a value.\n * Used for confidence calculation.\n */\n private getMatchType(\n token: LanguageToken,\n value: string\n ): 'exact' | 'normalized' | 'stem' | 'case-insensitive' | 'none' {\n // Exact match (highest confidence)\n if (token.value === value) return 'exact';\n\n // Explicit keyword map normalized match (high confidence)\n if (token.normalized === value) return 'normalized';\n\n // Morphologically normalized stem match (medium-high confidence)\n // Only accept if stem confidence is reasonable\n if (token.stem === value && token.stemConfidence !== undefined && token.stemConfidence >= 0.7) {\n return 'stem';\n }\n\n // Case-insensitive match for keywords (medium confidence)\n if (token.kind === 'keyword' && this.safeToLowerCase(token.value) === value.toLowerCase()) {\n return 'case-insensitive';\n }\n\n return 'none';\n }\n\n /**\n * Collect literal values from upcoming pattern tokens that act as stop markers\n * for greedy role capture. Returns the set of lowercase values.\n */\n private collectStopMarkers(patternTokens: PatternToken[], startIndex: number): Set<string> {\n const markers = new Set<string>();\n for (let j = startIndex; j < patternTokens.length; j++) {\n const pt = patternTokens[j];\n if (pt.type === 'literal') {\n markers.add(pt.value.toLowerCase());\n if (pt.alternatives) {\n for (const alt of pt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n if (pt.type === 'group') {\n for (const gt of pt.tokens) {\n if (gt.type === 'literal') {\n markers.add(gt.value.toLowerCase());\n if (gt.alternatives) {\n for (const alt of gt.alternatives) {\n markers.add(alt.toLowerCase());\n }\n }\n break;\n }\n }\n // For optional groups, continue scanning past them so the greedy\n // capture also sees subsequent required literals (e.g., the SOV verb\n // keyword after an optional WHERE group).\n if (!pt.optional) break;\n }\n }\n return markers;\n }\n\n /**\n * Check if a token matches any stop marker for greedy capture.\n */\n private isStopMarker(token: LanguageToken, stopMarkers: Set<string>): boolean {\n if (stopMarkers.size === 0) return false;\n // Check both raw value and normalized form against stop markers.\n // Pattern literals use native keywords (e.g., '選択') while tokenizers may\n // set normalized to the English equivalent (e.g., 'select'). Both must match.\n if (stopMarkers.has(token.value.toLowerCase())) return true;\n if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;\n return false;\n }\n\n /**\n * Track stem matches for confidence calculation.\n * This is set during matching and read during confidence calculation.\n */\n private stemMatchCount: number = 0;\n private totalKeywordMatches: number = 0;\n\n // ==========================================================================\n // Depth Limits for Expression Parsing (security hardening)\n // ==========================================================================\n\n /** Maximum depth for nested property access (e.g., a.b.c.d...) */\n private static readonly MAX_PROPERTY_DEPTH = 10;\n\n /** Maximum number of arguments in method calls */\n private static readonly MAX_METHOD_ARGS = 20;\n\n /**\n * Convert a language token to a semantic value.\n */\n private tokenToSemanticValue(token: LanguageToken): SemanticValue | null {\n switch (token.kind) {\n case 'selector':\n return createSelector(token.value);\n\n case 'literal':\n return this.parseLiteralValue(token.value);\n\n case 'keyword':\n // Keywords might be references or values\n const tokenValue = token.normalized || token.value;\n const lower = this.safeToLowerCase(tokenValue);\n if (isValidReference(lower)) {\n return createReference(lower);\n }\n return createLiteral(token.normalized || token.value);\n\n case 'identifier':\n // Check if it's a variable reference (:varname)\n // Note: :varname doesn't match the ReferenceValue union but is used as a\n // reference token downstream — this cast preserves existing behavior\n if (typeof token.value === 'string' && token.value.startsWith(':')) {\n return createReference(token.value as ReferenceValue['value']);\n }\n // Check if it's a built-in reference\n const identLower = this.safeToLowerCase(token.value);\n if (isValidReference(identLower)) {\n return createReference(identLower);\n }\n // Regular identifiers are variable references - use 'expression' type\n // which gets converted to 'identifier' AST nodes by semantic-integration.ts\n return { type: 'expression', raw: token.value } as const;\n\n case 'url':\n // URLs are treated as string literals (paths/URLs for navigation/fetch)\n return createLiteral(token.value, 'string');\n\n default:\n return null;\n }\n }\n\n /**\n * Parse a literal value (string, number, boolean).\n */\n private parseLiteralValue(value: string): SemanticValue {\n // String literal\n if (\n value.startsWith('\"') ||\n value.startsWith(\"'\") ||\n value.startsWith('`') ||\n value.startsWith('「')\n ) {\n const inner = value.slice(1, -1);\n return createLiteral(inner, 'string');\n }\n\n // Boolean\n if (value === 'true') return createLiteral(true, 'boolean');\n if (value === 'false') return createLiteral(false, 'boolean');\n\n // Duration (number with suffix)\n const durationMatch = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)?$/);\n if (durationMatch) {\n const num = parseFloat(durationMatch[1]);\n const unit = durationMatch[2];\n if (unit) {\n return createLiteral(value, 'duration');\n }\n return createLiteral(num, 'number');\n }\n\n // Plain number\n const num = parseFloat(value);\n if (!isNaN(num)) {\n return createLiteral(num, 'number');\n }\n\n // Default to string\n return createLiteral(value, 'string');\n }\n\n /**\n * Apply extraction rules to fill in static values and defaults for missing roles.\n */\n private applyExtractionRules(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): void {\n for (const [role, rule] of Object.entries(pattern.extraction)) {\n if (!captured.has(role as SemanticRole)) {\n if (rule.value !== undefined) {\n // Static value extraction (e.g., action: { value: \"toggle\" })\n captured.set(role as SemanticRole, { type: 'literal', value: rule.value });\n } else if (rule.default) {\n captured.set(role as SemanticRole, rule.default);\n }\n }\n }\n }\n\n /**\n * Check if a pattern token is optional.\n */\n private isOptional(patternToken: PatternToken): boolean {\n return patternToken.type !== 'literal' && patternToken.optional === true;\n }\n\n /**\n * Calculate confidence score for a match (0-1).\n *\n * Confidence is reduced for:\n * - Stem matches (morphological normalization has inherent uncertainty)\n * - Missing optional roles (but less penalty if role has a default value)\n *\n * Confidence is increased for:\n * - VSO languages (Arabic) when pattern starts with a verb\n */\n private calculateConfidence(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n let score = 0;\n let maxScore = 0;\n\n // Helper to check if a role has a default value in extraction rules\n const hasDefault = (role: SemanticRole): boolean => {\n return pattern.extraction?.[role]?.default !== undefined;\n };\n\n // Score based on captured roles\n for (const token of pattern.template.tokens) {\n if (token.type === 'role') {\n maxScore += 1;\n if (captured.has(token.role)) {\n score += 1;\n }\n } else if (token.type === 'group') {\n // Group tokens are optional - weight depends on whether they have defaults\n for (const subToken of token.tokens) {\n if (subToken.type === 'role') {\n const roleHasDefault = hasDefault(subToken.role);\n const weight = 0.8; // Optional roles: 80% weight\n maxScore += weight;\n\n if (captured.has(subToken.role)) {\n // Role was explicitly provided by user\n score += weight;\n } else if (roleHasDefault) {\n // Role has a default - give 60% partial credit since command is semantically complete\n // This prevents penalizing common patterns like \"toggle .active\" (default: me)\n score += weight * 0.6;\n }\n // If no default and not captured, score += 0 (true penalty for missing info)\n }\n }\n }\n }\n\n let baseConfidence = maxScore > 0 ? score / maxScore : 1;\n\n // Apply penalty for stem matches\n // Each stem match reduces confidence slightly (e.g., 5% per stem match)\n // This ensures exact matches are preferred over morphological matches\n if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {\n const stemPenalty = (this.stemMatchCount / this.totalKeywordMatches) * 0.15;\n baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);\n }\n\n // Apply VSO confidence boost for Arabic verb-first patterns\n const vsoBoost = this.calculateVSOConfidenceBoost(pattern);\n baseConfidence = Math.min(1.0, baseConfidence + vsoBoost);\n\n // Apply preposition disambiguation adjustment for Arabic\n const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);\n baseConfidence = Math.max(0.0, Math.min(1.0, baseConfidence + prepositionAdjustment));\n\n return baseConfidence;\n }\n\n /**\n * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.\n * Arabic naturally uses VSO word order, so patterns that start with a verb\n * should receive a confidence boost.\n *\n * Returns +0.15 confidence boost if:\n * - Language is Arabic ('ar')\n * - Pattern's first token is a verb keyword\n *\n * @param pattern The language pattern being matched\n * @returns Confidence boost (0 or 0.15)\n */\n private calculateVSOConfidenceBoost(pattern: LanguagePattern): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n // Check if first token in pattern is a literal (keyword)\n const firstToken = pattern.template.tokens[0];\n if (!firstToken || firstToken.type !== 'literal') {\n return 0;\n }\n\n // List of Arabic verb keywords (command verbs)\n const ARABIC_VERBS = new Set([\n 'بدل',\n 'غير',\n 'أضف',\n 'أزل',\n 'ضع',\n 'اجعل',\n 'عين',\n 'زد',\n 'انقص',\n 'سجل',\n 'أظهر',\n 'أخف',\n 'شغل',\n 'أرسل',\n 'ركز',\n 'شوش',\n 'توقف',\n 'انسخ',\n 'احذف',\n 'اصنع',\n 'انتظر',\n 'انتقال',\n 'أو',\n ]);\n\n // Check if first token value is a verb\n if (ARABIC_VERBS.has(firstToken.value)) {\n return 0.15;\n }\n\n // Check alternatives\n if (firstToken.alternatives) {\n for (const alt of firstToken.alternatives) {\n if (ARABIC_VERBS.has(alt)) {\n return 0.15;\n }\n }\n }\n\n return 0;\n }\n\n /**\n * Arabic preposition disambiguation for confidence adjustment.\n *\n * Different Arabic prepositions are more or less natural for different semantic roles:\n * - على (on/upon) is preferred for patient/target roles (element selectors)\n * - إلى (to) is preferred for destination roles\n * - من (from) is preferred for source roles\n * - في (in) is preferred for location roles\n *\n * This method analyzes the prepositions used with captured semantic roles and\n * adjusts confidence based on idiomaticity:\n * - +0.10 for highly idiomatic preposition choices\n * - -0.10 for less natural preposition choices\n *\n * @param pattern The language pattern being matched\n * @param captured The captured semantic values\n * @returns Confidence adjustment (-0.10 to +0.10)\n */\n private arabicPrepositionDisambiguation(\n pattern: LanguagePattern,\n captured: Map<SemanticRole, SemanticValue>\n ): number {\n // Only apply to Arabic\n if (pattern.language !== 'ar') {\n return 0;\n }\n\n let adjustment = 0;\n\n // Preferred prepositions for each semantic role\n // Only including roles that commonly use prepositions in Arabic\n const PREFERRED_PREPOSITIONS: Partial<Record<SemanticRole, string[]>> = {\n patient: ['على'], // element selectors prefer على (on/upon)\n destination: ['إلى', 'الى'], // destination prefers إلى (to)\n source: ['من'], // source prefers من (from)\n agent: ['من'], // agent/by prefers من (from/by)\n manner: ['ب'], // manner prefers ب (with/by)\n style: ['ب'], // style prefers ب (with)\n goal: ['إلى', 'الى'], // target state prefers إلى (to)\n method: ['ب'], // method prefers ب (with/by)\n };\n\n // Check each captured role for preposition metadata\n for (const [role, value] of captured.entries()) {\n // Skip if no preferred prepositions defined for this role\n const preferred = PREFERRED_PREPOSITIONS[role];\n if (!preferred || preferred.length === 0) {\n continue;\n }\n\n // Check if the value has preposition metadata (from Arabic tokenizer)\n // This metadata is attached when a preposition particle token is consumed\n const metadata =\n 'metadata' in value ? (value as { metadata: Record<string, unknown> }).metadata : undefined;\n if (metadata && typeof metadata.prepositionValue === 'string') {\n const usedPreposition = metadata.prepositionValue;\n\n // Check if the used preposition is in the preferred list\n if (preferred.includes(usedPreposition)) {\n // Idiomatic choice - boost confidence\n adjustment += 0.1;\n } else {\n // Less natural choice - reduce confidence\n adjustment -= 0.1;\n }\n }\n }\n\n // Cap total adjustment at ±0.10 (even if multiple roles analyzed)\n return Math.max(-0.1, Math.min(0.1, adjustment));\n }\n\n // ===========================================================================\n // English Idiom Support - Noise Word Handling\n // ===========================================================================\n\n /**\n * Noise words that can be skipped in English for more natural syntax.\n * - \"the\" before selectors: \"toggle the .active\" → \"toggle .active\"\n * - \"class\" after class selectors: \"add the .visible class\" → \"add .visible\"\n */\n private static readonly ENGLISH_NOISE_WORDS = new Set(['the', 'a', 'an']);\n\n /**\n * Skip noise words like \"the\" before selectors.\n * This enables more natural English syntax like \"toggle the .active\".\n */\n private skipNoiseWords(tokens: TokenStream): void {\n const token = tokens.peek();\n if (!token) return;\n\n const tokenLower = this.safeToLowerCase(token.value);\n\n // Check if current token is a noise word (like \"the\")\n if (PatternMatcher.ENGLISH_NOISE_WORDS.has(tokenLower)) {\n // Look ahead to see if the next token is a selector\n const mark = tokens.mark();\n tokens.advance();\n const nextToken = tokens.peek();\n\n if (nextToken && nextToken.kind === 'selector') {\n // Keep the position after \"the\" - effectively skipping it\n return;\n }\n\n // Not followed by a selector, revert\n tokens.reset(mark);\n }\n\n // Also handle \"class\" after class selectors: \".visible class\" → \".visible\"\n // This is handled when the selector has already been consumed,\n // so we check if current token is \"class\" and skip it\n if (tokenLower === 'class') {\n // Skip \"class\" as it's just noise after a class selector\n tokens.advance();\n }\n }\n\n /**\n * Extract event modifiers from the token stream.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n * that can appear after event names.\n *\n * Returns EventModifiers object or undefined if no modifiers found.\n */\n extractEventModifiers(tokens: TokenStream): import('../types').EventModifiers | undefined {\n const modifiers: {\n once?: boolean;\n debounce?: number;\n throttle?: number;\n queue?: 'first' | 'last' | 'all' | 'none';\n from?: SemanticValue;\n } = {};\n\n let foundModifier = false;\n\n // Consume all consecutive event modifier tokens\n while (!tokens.isAtEnd()) {\n const token = tokens.peek();\n if (!token || token.kind !== 'event-modifier') {\n break;\n }\n\n const metadata = token.metadata as\n { modifierName: string; value?: number | string } | undefined;\n if (!metadata) {\n break;\n }\n\n foundModifier = true;\n\n switch (metadata.modifierName) {\n case 'once':\n modifiers.once = true;\n break;\n case 'debounce':\n if (typeof metadata.value === 'number') {\n modifiers.debounce = metadata.value;\n }\n break;\n case 'throttle':\n if (typeof metadata.value === 'number') {\n modifiers.throttle = metadata.value;\n }\n break;\n case 'queue':\n if (\n metadata.value === 'first' ||\n metadata.value === 'last' ||\n metadata.value === 'all' ||\n metadata.value === 'none'\n ) {\n modifiers.queue = metadata.value;\n }\n break;\n }\n\n tokens.advance();\n }\n\n return foundModifier ? modifiers : undefined;\n }\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * Singleton pattern matcher instance.\n */\nexport const patternMatcher = new PatternMatcher();\n\n/**\n * Match tokens against a pattern.\n */\nexport function matchPattern(\n tokens: TokenStream,\n pattern: LanguagePattern\n): PatternMatchResult | null {\n return patternMatcher.matchPattern(tokens, pattern);\n}\n\n/**\n * Match tokens against multiple patterns, return best match.\n */\nexport function matchBest(\n tokens: TokenStream,\n patterns: LanguagePattern[]\n): PatternMatchResult | null {\n return patternMatcher.matchBest(tokens, patterns);\n}\n","/**\n * Pattern Generator\n *\n * Generates LanguagePattern objects from CommandSchema + LanguageProfile.\n * This solves the pattern explosion problem by deriving patterns from\n * high-level schema definitions rather than hand-writing each one.\n */\n\nimport type { LanguagePattern, PatternToken, ExtractionRule } from '../core/types';\nimport type { CommandSchema, RoleSpec } from '../schema';\n\n/**\n * Minimal language profile interface for pattern generation.\n */\nexport interface PatternGenLanguageProfile {\n readonly code: string;\n readonly wordOrder: 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OSV' | 'OVS' | 'free';\n readonly keywords: Record<string, { primary: string; alternatives?: string[] }>;\n readonly roleMarkers?: Record<\n string,\n { primary: string; alternatives?: string[]; position?: 'before' | 'after' }\n >;\n}\n\n/**\n * Configuration for pattern generation.\n */\nexport interface GeneratorConfig {\n /** Base priority for generated patterns (default: 100) */\n readonly basePriority?: number;\n /** Include optional role variants (default: true) */\n readonly includeOptionalVariants?: boolean;\n}\n\nconst defaultConfig: GeneratorConfig = {\n basePriority: 100,\n includeOptionalVariants: true,\n};\n\n/**\n * Generate a language pattern from a command schema and language profile.\n *\n * @param schema - Command schema defining the command structure\n * @param profile - Language profile with word order and keywords\n * @param config - Optional configuration\n * @returns Generated language pattern\n */\nexport function generatePattern(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern {\n const id = `${schema.action}-${profile.code}-generated`;\n const priority = config.basePriority ?? 100;\n\n // Get keyword translation\n const keyword = profile.keywords[schema.action];\n if (!keyword) {\n throw new Error(`No keyword translation for '${schema.action}' in ${profile.code}`);\n }\n\n // Build tokens based on word order\n const tokens = buildTokens(schema, profile, keyword.primary, keyword.alternatives);\n\n // Build extraction rules\n const extraction = buildExtractionRules(schema, profile);\n\n // Build format string for documentation\n const format = buildFormatString(schema, profile, keyword.primary);\n\n return {\n id,\n language: profile.code,\n command: schema.action,\n priority,\n template: {\n format,\n tokens,\n },\n extraction,\n };\n}\n\n/**\n * Build pattern tokens based on word order and role markers.\n */\nfunction buildTokens(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string,\n alternatives?: string[]\n): PatternToken[] {\n const tokens: PatternToken[] = [];\n const keywordToken: PatternToken = {\n type: 'literal',\n value: keyword,\n ...(alternatives?.length && { alternatives }),\n };\n\n // Sort roles by word order\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n\n // For SVO: [action, patient, destination, source, ...]\n if (profile.wordOrder === 'SVO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // For SOV: [patient, destination, source, ..., action, postVerb roles...]\n else if (profile.wordOrder === 'SOV') {\n // `sovSlot: 'postVerb'` moves a role AFTER the verb, which is what the\n // renderer does (`renderer.ts` buckets by the same field). Generation has\n // to mirror it: a role the renderer writes post-verb but the pattern\n // expects pre-verb produces a faithful surface its own parser drops the\n // argument from — voice's `戻る 2` re-parsing as a bare `back`.\n const preVerb: PatternToken[] = [];\n const postVerb: PatternToken[] = [];\n\n for (const role of sortedRoles) {\n addRoleWithMarker(role.sovSlot === 'postVerb' ? postVerb : preVerb, role, profile);\n }\n\n tokens.push(...preVerb, keywordToken, ...postVerb);\n }\n // For VSO: [action, destination, patient, source, ...]\n else if (profile.wordOrder === 'VSO') {\n // Add keyword first\n tokens.push(keywordToken);\n\n // Add roles with markers\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n // Other word orders can be added as needed\n else {\n // Fallback to SVO-style ordering\n tokens.push(keywordToken);\n for (const role of sortedRoles) {\n addRoleWithMarker(tokens, role, profile);\n }\n }\n\n return tokens;\n}\n\n/**\n * Add a role token with its grammatical marker if needed.\n * For optional roles, wraps the role + marker in a group.\n */\nfunction addRoleWithMarker(\n tokens: PatternToken[],\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): void {\n const marker = getMarkerForRole(roleSpec, profile);\n const isOptional = !roleSpec.required;\n\n // Build the role token\n const roleToken: PatternToken = {\n type: 'role',\n role: roleSpec.role,\n optional: isOptional,\n expectedTypes: roleSpec.expectedTypes,\n ...(roleSpec.greedy && { greedy: true }),\n };\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[roleSpec.role];\n // Priority: schema markerPosition → profile roleMarkers position → word-order default\n const defaultPosition = profile.wordOrder === 'SOV' ? 'after' : 'before';\n const position = roleSpec.markerPosition ?? markerInfo?.position ?? defaultPosition;\n\n if (isOptional) {\n // Optional role: wrap marker + role in optional group\n if (position === 'before') {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [{ type: 'literal', value: marker }, roleToken],\n });\n } else {\n tokens.push({\n type: 'group',\n optional: true,\n tokens: [roleToken, { type: 'literal', value: marker }],\n });\n }\n } else {\n // Required role: add marker + role separately\n if (position === 'before') {\n tokens.push({ type: 'literal', value: marker });\n tokens.push(roleToken);\n } else {\n tokens.push(roleToken);\n tokens.push({ type: 'literal', value: marker });\n }\n }\n } else {\n // No marker - just add the role\n tokens.push(roleToken);\n }\n}\n\n/**\n * Get the grammatical marker for a role from the profile.\n */\nfunction getMarkerForRole(\n roleSpec: RoleSpec,\n profile: PatternGenLanguageProfile\n): string | undefined {\n // Check for role-specific override first\n if (roleSpec.markerOverride?.[profile.code]) {\n return roleSpec.markerOverride[profile.code];\n }\n\n // Use profile's default marker for this role\n return profile.roleMarkers?.[roleSpec.role]?.primary;\n}\n\n/**\n * Sort roles by word order for pattern building.\n *\n * Exported so the renderer sorts with exactly this comparator — a rendered\n * surface whose role order differs from the generated pattern would not re-parse.\n */\nexport function sortRolesByWordOrder(roles: RoleSpec[], wordOrder: string): RoleSpec[] {\n const sorted = [...roles];\n\n if (wordOrder === 'SVO') {\n // Sort by svoPosition (higher = earlier)\n sorted.sort((a, b) => (b.svoPosition ?? 0) - (a.svoPosition ?? 0));\n } else if (wordOrder === 'SOV') {\n // Sort by sovPosition (higher = earlier)\n sorted.sort((a, b) => (b.sovPosition ?? 0) - (a.sovPosition ?? 0));\n }\n // VSO and others use SVO-style ordering\n\n return sorted;\n}\n\n/**\n * Build extraction rules for capturing role values during parsing.\n */\nfunction buildExtractionRules(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile\n): Record<string, ExtractionRule> {\n const rules: Record<string, ExtractionRule> = {};\n\n for (const roleSpec of schema.roles) {\n // Build the rule object correctly with readonly properties\n const marker = getMarkerForRole(roleSpec, profile);\n\n const rule: ExtractionRule = {\n ...(roleSpec.default !== undefined && { default: roleSpec.default }),\n ...(marker && { marker }),\n };\n\n rules[roleSpec.role] = rule;\n }\n\n return rules;\n}\n\n/**\n * Build a human-readable format string for the pattern.\n */\nfunction buildFormatString(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n keyword: string\n): string {\n const isSOV = profile.wordOrder === 'SOV';\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n // Order roles the same way buildTokens does (descending position). Iterating\n // declaration order here would disagree with the token order whenever a\n // schema's roles are declared in a different order than their positions imply.\n const sortedRoles = sortRolesByWordOrder(schema.roles, profile.wordOrder);\n for (const role of sortedRoles) {\n const marker = getMarkerForRole(role, profile);\n const roleName = `{${role.role}}`;\n // Same pre/post-verb split buildTokens applies, so the documented format\n // string keeps describing the tokens it is generated alongside.\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n\n if (marker) {\n const markerInfo = profile.roleMarkers?.[role.role];\n if (markerInfo?.position === 'after') {\n bucket.push(`${roleName} ${marker}`);\n } else {\n bucket.push(`${marker} ${roleName}`);\n }\n } else {\n bucket.push(roleName);\n }\n }\n\n return (isSOV ? [...preVerb, keyword, ...postVerb] : [keyword, ...preVerb, ...postVerb]).join(\n ' '\n );\n}\n\n/**\n * Generate multiple pattern variants (with and without optional roles).\n */\nexport function generatePatternVariants(\n schema: CommandSchema,\n profile: PatternGenLanguageProfile,\n config: GeneratorConfig = defaultConfig\n): LanguagePattern[] {\n const patterns: LanguagePattern[] = [];\n\n // Main pattern (all roles)\n patterns.push(generatePattern(schema, profile, config));\n\n // TODO: Generate variants with optional roles omitted\n // This can be added later when needed\n\n return patterns;\n}\n","/**\n * Natural Language Renderer\n *\n * Interface and utilities for rendering SemanticNode → human-readable text\n * in any supported language. This is the inverse of parsing: it converts\n * a language-neutral semantic representation back to natural-language syntax.\n *\n * Every domain that supports `translate()` needs a renderer.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { extractRoleValue, extractValue } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { sortRolesByWordOrder, type PatternGenLanguageProfile } from './pattern-generator';\n\n// =============================================================================\n// Renderer Interface\n// =============================================================================\n\n/**\n * Renders a SemanticNode to human-readable text in a target language.\n */\nexport interface NaturalLanguageRenderer {\n render(node: SemanticNode, language: string): string;\n}\n\n// =============================================================================\n// Renderer Helpers\n// =============================================================================\n\n/**\n * Keyword table: action → language → translated keyword.\n *\n * @example\n * ```typescript\n * const KEYWORDS: KeywordTable = {\n * select: { en: 'select', ja: '選択', es: 'seleccionar' },\n * insert: { en: 'insert', ja: '挿入', es: 'insertar' },\n * };\n * ```\n */\nexport type KeywordTable = Record<string, Record<string, string>>;\n\n/**\n * Marker table: marker name → language → translated marker.\n *\n * @example\n * ```typescript\n * const MARKERS: MarkerTable = {\n * from: { en: 'from', ja: 'から', es: 'de' },\n * into: { en: 'into', ja: 'に', es: 'en' },\n * };\n * ```\n */\nexport type MarkerTable = Record<string, Record<string, string>>;\n\n/**\n * Configuration for building a renderer from schemas and profiles.\n */\nexport interface RendererConfig {\n /** Command keyword translations per language */\n readonly keywords: KeywordTable;\n\n /** Role marker translations per language (prepositions/particles) */\n readonly markers: MarkerTable;\n\n /** Languages that use SOV word order */\n readonly sovLanguages: ReadonlySet<string>;\n\n /** Languages that use VSO word order (optional, defaults to empty) */\n readonly vsoLanguages?: ReadonlySet<string>;\n}\n\n/**\n * Look up a command keyword in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupKeyword(keywords: KeywordTable, action: string, language: string): string {\n return keywords[action]?.[language] ?? action;\n}\n\n/**\n * Look up a role marker in the target language.\n * Falls back to the key itself if no translation found.\n */\nexport function lookupMarker(markers: MarkerTable, marker: string, language: string): string {\n return markers[marker]?.[language] ?? marker;\n}\n\n/**\n * Build a phrase from parts, filtering empty strings and joining with space.\n *\n * @example\n * ```typescript\n * buildPhrase('select', '', 'name', 'from', 'users')\n * // → 'select name from users'\n * ```\n */\nexport function buildPhrase(...parts: string[]): string {\n return parts.filter(Boolean).join(' ');\n}\n\n/**\n * Build keyword and marker tables from schemas and language profiles.\n * Extracts translations from the profile's keyword definitions and\n * role marker overrides.\n *\n * @example\n * ```typescript\n * const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n * ```\n */\nexport function buildTablesFromProfiles(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): { keywords: KeywordTable; markers: MarkerTable } {\n const keywords: KeywordTable = {};\n const markers: MarkerTable = {};\n\n // Build keyword table from profiles\n for (const profile of profiles) {\n for (const [action, kw] of Object.entries(profile.keywords)) {\n if (!keywords[action]) keywords[action] = {};\n keywords[action][profile.code] = kw.primary;\n }\n }\n\n // Build marker table from schema markerOverrides\n for (const schema of schemas) {\n for (const role of schema.roles) {\n if (role.markerOverride) {\n // Use role name as marker key\n const markerKey = role.role;\n if (!markers[markerKey]) markers[markerKey] = {};\n for (const [lang, markerText] of Object.entries(role.markerOverride)) {\n markers[markerKey][lang] = markerText;\n }\n }\n }\n }\n\n // Also extract role markers from profiles\n for (const profile of profiles) {\n if (profile.roleMarkers) {\n for (const [markerKey, markerDef] of Object.entries(profile.roleMarkers)) {\n if (!markers[markerKey]) markers[markerKey] = {};\n markers[markerKey][profile.code] = markerDef.primary;\n }\n }\n }\n\n return { keywords, markers };\n}\n\n/**\n * Detect word order from language profiles.\n * Returns sets of SOV and VSO language codes.\n */\nexport function detectWordOrders(profiles: readonly PatternGenLanguageProfile[]): {\n sovLanguages: Set<string>;\n vsoLanguages: Set<string>;\n} {\n const sovLanguages = new Set<string>();\n const vsoLanguages = new Set<string>();\n\n for (const profile of profiles) {\n if (profile.wordOrder === 'SOV') sovLanguages.add(profile.code);\n if (profile.wordOrder === 'VSO') vsoLanguages.add(profile.code);\n }\n\n return { sovLanguages, vsoLanguages };\n}\n\n/**\n * Create a basic renderer from schemas and profiles.\n *\n * This generates a renderer that handles word-order reordering automatically.\n * For each command, it constructs the output by placing the keyword and\n * role values in the correct order for the target language.\n *\n * For complex domain-specific rendering, implement `NaturalLanguageRenderer`\n * directly instead.\n *\n * @example\n * ```typescript\n * const renderer = createSchemaRenderer(schemas, profiles);\n * renderer.render(node, 'ja'); // → \"users から name 選択\"\n * ```\n */\nexport function createSchemaRenderer(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): NaturalLanguageRenderer {\n const tables = buildRenderTables(schemas, profiles);\n\n return {\n render(node: SemanticNode, language: string): string {\n // An action with no schema still has a name — render that rather than\n // nothing. `createDomainRenderer` returns null for this case instead.\n return renderFromSchema(node, language, tables) ?? node.action;\n },\n };\n}\n\n// =============================================================================\n// Domain renderer (hand-written cases + schema fallthrough)\n// =============================================================================\n\n/**\n * Renders a SemanticNode, or returns `null` when the action cannot be rendered.\n *\n * The nullable counterpart to {@link NaturalLanguageRenderer}: `null` means \"I\n * do not know this action\", which callers can act on. A domain that signals the\n * same condition with a sentinel string forces consumers into string matching.\n */\nexport type DomainRenderFn = (node: SemanticNode, language: string) => string | null;\n\n/**\n * Configuration for {@link createDomainRenderer}.\n */\nexport interface DomainRendererConfig {\n /** Schemas for this domain's commands, including any extensions. */\n readonly schemas: readonly CommandSchema[];\n\n /** Language profiles supplying keywords and role markers. */\n readonly profiles: readonly PatternGenLanguageProfile[];\n\n /**\n * Hand-written renderers per action. These take absolute precedence over the\n * schema-driven path, so a domain's existing output is preserved byte for byte.\n *\n * An override returning `null` means \"this action cannot be rendered\" and is\n * passed straight through — it does not fall through to the schema path,\n * since a hand-written renderer knows more about its action than the schema does.\n */\n readonly overrides?: Readonly<Record<string, DomainRenderFn>>;\n}\n\n/**\n * Create a renderer that composes a domain's hand-written per-action renderers\n * with the schema-driven fallback.\n *\n * Resolution order:\n * 1. `overrides[node.action]` — the domain's own rendering, unchanged\n * 2. schema-driven rendering — any action with a schema but no hand-written case\n * 3. `null` — no override and no schema\n *\n * Step 2 is what makes a domain extensible: a consumer that adds a command\n * schema (with per-language keywords in the profiles) gets correct word order,\n * markers and keywords for free, without the domain package having to know\n * about that command.\n *\n * @example\n * ```typescript\n * const render = createDomainRenderer({\n * schemas: allSchemas,\n * profiles: allProfiles,\n * overrides: { select: renderSelect, insert: renderInsert },\n * });\n * render(node, 'ja'); // hand-written for `select`, schema-driven otherwise\n * render(bogusNode, 'en'); // → null\n * ```\n */\nexport function createDomainRenderer(config: DomainRendererConfig): DomainRenderFn {\n const { schemas, profiles, overrides } = config;\n\n // Built on first render — a domain module can construct its renderer at import\n // time without paying for table construction it may never use.\n let tables: RenderTables | undefined;\n\n return (node: SemanticNode, language: string): string | null => {\n const override = overrides?.[node.action];\n if (override) return override(node, language);\n\n tables ??= buildRenderTables(schemas, profiles);\n return renderFromSchema(node, language, tables);\n };\n}\n\n// =============================================================================\n// Shared schema-driven rendering\n// =============================================================================\n\ninterface RenderTables {\n readonly keywords: KeywordTable;\n readonly markers: MarkerTable;\n /** Marker side per role per language, from each profile's roleMarkers. */\n readonly markerPositions: Record<string, Record<string, 'before' | 'after'>>;\n readonly sovLanguages: ReadonlySet<string>;\n readonly schemaMap: ReadonlyMap<string, CommandSchema>;\n}\n\nfunction buildRenderTables(\n schemas: readonly CommandSchema[],\n profiles: readonly PatternGenLanguageProfile[]\n): RenderTables {\n const { keywords, markers } = buildTablesFromProfiles(schemas, profiles);\n const { sovLanguages } = detectWordOrders(profiles);\n\n const markerPositions: Record<string, Record<string, 'before' | 'after'>> = {};\n for (const profile of profiles) {\n for (const [role, markerDef] of Object.entries(profile.roleMarkers ?? {})) {\n if (!markerDef.position) continue;\n markerPositions[role] ??= {};\n markerPositions[role][profile.code] = markerDef.position;\n }\n }\n\n const schemaMap = new Map<string, CommandSchema>();\n for (const s of schemas) schemaMap.set(s.action, s);\n return { keywords, markers, markerPositions, sovLanguages, schemaMap };\n}\n\n/**\n * The one schema-driven rendering algorithm, shared by `createSchemaRenderer`\n * and `createDomainRenderer` so the two can never drift.\n *\n * Returns `null` when the action has no schema.\n */\nfunction renderFromSchema(\n node: SemanticNode,\n language: string,\n tables: RenderTables\n): string | null {\n const schema = tables.schemaMap.get(node.action);\n if (!schema) return null;\n\n const keyword = lookupKeyword(tables.keywords, node.action, language);\n const isSOV = tables.sovLanguages.has(language);\n\n // Order roles by their declared positions, using the SAME comparator pattern\n // generation uses. Rendering in declaration order instead would produce a\n // surface the generated pattern cannot re-parse whenever the two disagree.\n const ordered = sortRolesByWordOrder([...schema.roles], isSOV ? 'SOV' : 'SVO');\n\n // Roles rendered before the verb, and (SOV only) after it.\n const preVerb: string[] = [];\n const postVerb: string[] = [];\n\n for (const role of ordered) {\n let value = extractRoleValue(node, role.role);\n if (!value && role.default !== undefined) {\n value = String(extractValue(role.default));\n }\n // A role with no value is skipped entirely — including its marker. Emitting\n // the marker of an absent role produces dangling text (\"analyze #content as\",\n // \"#content として 分析\"), which is never valid surface syntax. This applies to\n // required roles too: a required role with no value is a malformed node, and\n // a dangling marker is a worse rendering of it than simply leaving it out.\n if (!value) continue;\n\n if (role.quoteMultiword && /\\s/.test(value) && !/^([\"']).*\\1$/.test(value)) {\n value = `\"${value}\"`;\n }\n\n // Marker resolution, most specific first. `renderOverride` for this exact\n // language is the most specific statement; `''` means \"render this role\n // bare\" (a marker that exists only to help the parser). The `'*'` key is a\n // blanket statement about the PROFILE default, so it ranks below a\n // per-language markerOverride — which is how SQL's `get` renders bare in\n // SVO languages while keeping its SOV source particles.\n const markerText =\n role.renderOverride?.[language] ??\n role.markerOverride?.[language] ??\n role.renderOverride?.['*'] ??\n tables.markers[role.role]?.[language];\n\n const markerPosition =\n role.markerPositionOverride?.[language] ??\n role.markerPosition ??\n tables.markerPositions[role.role]?.[language] ??\n (isSOV ? 'after' : 'before');\n\n const bucket = isSOV && role.sovSlot === 'postVerb' ? postVerb : preVerb;\n if (markerText && markerPosition === 'before') {\n bucket.push(markerText, value);\n } else if (markerText) {\n bucket.push(value, markerText);\n } else {\n bucket.push(value);\n }\n }\n\n return isSOV\n ? buildPhrase(...preVerb, keyword, ...postVerb)\n : buildPhrase(keyword, ...preVerb, ...postVerb);\n}\n","/**\n * Generalized Grammar System for Multilingual Hyperscript\n *\n * This system abstracts grammatical patterns across language families,\n * enabling deep multilingual support without per-language hardcoding.\n *\n * Key Linguistic Concepts:\n * - Word Order: SVO, SOV, VSO (and variations)\n * - Adposition Type: Preposition (English) vs Postposition (Japanese/Korean)\n * - Morphology: Isolating (Chinese) vs Agglutinative (Turkish) vs Fusional (Arabic)\n * - Text Direction: LTR vs RTL\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Semantic roles in hyperscript commands.\n * These are universal across all 13 supported languages - only the surface form changes.\n *\n * ## Core Thematic Roles (from linguistic theory)\n * | Role | Usage | Purpose | Example |\n * |-------------|-------|-----------------------------|---------------------------|\n * | action | 100% | Command verb | toggle, put, fetch |\n * | patient | 90% | What is acted upon | .active, #count |\n * | destination | 40% | Where something goes | into #output, to .class |\n * | source | 13% | Where something comes from | from #input, from URL |\n * | event | 106% | Trigger events | click, keydown, submit |\n * | condition | 8% | Boolean expressions | if x > 5, when visible |\n * | agent | 0% | Who performs action | Reserved for future use |\n * | goal | 1% | Target value/state | to 'red' (in transition) |\n *\n * ## Quantitative Roles (answer \"how much/long\")\n * | Role | Usage | Purpose | Example |\n * |----------|-------|----------------|----------------------|\n * | quantity | 7% | Numeric amount | by 5, 3 times |\n * | duration | 1% | Time span | for 5 seconds, 500ms |\n *\n * ## Adverbial/Modifier Roles (answer \"how/by what means\")\n * | Role | Usage | Purpose | Example |\n * |--------------|-------|---------------------------|-------------------|\n * | style | 2% | Animation/behavior | with fade |\n * | manner | 2% | Insertion position | before, after |\n * | method | 1% | HTTP method/technique | via POST, as GET |\n * | responseType | 1% | Response format | as json, as html |\n *\n * ## Control Flow Roles\n * | Role | Usage | Purpose | Example |\n * |----------|-------|--------------|-----------------------|\n * | loopType | 6% | Loop variant | forever, until, times |\n *\n * ## Design Notes\n * - Low-usage roles (agent, goal, method, responseType) are intentionally kept for:\n * - Linguistic completeness across all 13 languages\n * - Future extensibility (AI agents, server-side execution)\n * - Command-specific semantics (fetch, transition)\n * - Each role has distinct grammatical markers per language (see profiles/index.ts)\n * - Usage percentages based on pattern database analysis\n */\nexport type SemanticRole =\n // Core thematic roles\n | 'action' // The command/verb (increment, put, toggle)\n | 'agent' // Who/what performs action (reserved for future: AI agents, server-side)\n | 'patient' // What is acted upon (the counter, .active)\n | 'source' // Origin (from #input, from URL)\n | 'destination' // Target location (into #output, to .class)\n | 'goal' // Target value/state (to 'red', to 100)\n | 'event' // Trigger (click, input, keydown)\n | 'condition' // Boolean expression (if x > 5)\n // Quantitative roles\n | 'quantity' // Numeric amount (by 5, 3 times)\n | 'duration' // Time span (for 5 seconds, over 500ms)\n // Adverbial roles\n | 'responseType' // Response format (as json, as text, as html)\n | 'method' // HTTP method/technique (via POST, using GET)\n | 'style' // Visual/behavioral manner (with fade, smoothly)\n | 'manner' // Insertion position (before, after)\n // Control flow roles\n | 'loopType' // Loop variant: forever, times, for, while, until, until-event\n // Structural roles (for parser control)\n | 'continues'; // Continuation marker (then-chains)\n\n/**\n * Word order patterns\n * These represent the major typological categories\n */\nexport type WordOrder = 'SVO' | 'SOV' | 'VSO' | 'VOS' | 'OVS' | 'OSV' | 'free';\n\n/**\n * Where grammatical markers appear relative to their noun/verb\n */\nexport type AdpositionType = 'preposition' | 'postposition' | 'circumposition' | 'none';\n\n/**\n * Morphological typology - how words are constructed\n */\nexport type MorphologyType =\n | 'isolating' // Chinese - no inflection, word order matters\n | 'agglutinative' // Turkish, Japanese - morphemes stack predictably\n | 'fusional' // Arabic, Spanish - morphemes blend together\n | 'polysynthetic'; // Quechua - complex words encode full sentences\n\n/**\n * A grammatical marker (particle, case ending, preposition)\n */\nexport interface GrammaticalMarker {\n form: string; // The actual text (を, に, to, 的)\n role: SemanticRole; // What semantic role it marks\n position: AdpositionType; // Where it appears\n required: boolean; // Is it mandatory?\n alternatives?: string[]; // Alternative forms (e.g., 을/를 in Korean)\n}\n\n/**\n * Metadata for preserving line structure during translation.\n * Tracks indentation and blank lines so output maintains the same format.\n */\nexport interface LineMetadata {\n /** Trimmed line content (empty string for blank lines) */\n content: string;\n /** Leading whitespace (tabs/spaces) from original line */\n originalIndent: string;\n /** True if the line was empty or whitespace-only */\n isBlank: boolean;\n}\n\n// =============================================================================\n// Language Profile\n// =============================================================================\n\n/**\n * Complete grammatical profile for a language\n * This captures the essential typological features needed for transformation\n */\nexport interface LanguageProfile {\n code: string; // ISO 639-1 code\n name: string; // Native name\n\n // Typological features\n wordOrder: WordOrder;\n adpositionType: AdpositionType;\n morphology: MorphologyType;\n direction: 'ltr' | 'rtl';\n\n // Grammatical markers for each semantic role\n markers: GrammaticalMarker[];\n\n // Role ordering - which semantic roles come in what order\n // E.g., Japanese: ['patient', 'source', 'destination', 'action']\n // E.g., English: ['action', 'patient', 'source', 'destination']\n canonicalOrder: SemanticRole[];\n\n // Special rules\n rules?: GrammarRule[];\n}\n\n/**\n * Pattern for transforming hyperscript structures\n */\nexport interface GrammarRule {\n name: string;\n description: string;\n\n // Pattern matching (in canonical English form)\n match: PatternMatcher;\n\n // How to transform for this language\n transform: PatternTransform;\n\n // Priority (higher = checked first)\n priority: number;\n}\n\n/**\n * Matches a hyperscript pattern\n */\nexport interface PatternMatcher {\n // Command type(s) this matches\n commands?: string[];\n\n // Required semantic roles\n requiredRoles: SemanticRole[];\n\n // Optional roles\n optionalRoles?: SemanticRole[];\n\n // Custom predicate for complex matching\n predicate?: (parsed: ParsedStatement) => boolean;\n}\n\n/**\n * Defines how to transform a matched pattern\n */\nexport interface PatternTransform {\n // Reorder roles for target language\n roleOrder: SemanticRole[];\n\n // Insert markers between roles\n insertMarkers?: boolean;\n\n // Custom transformation function\n custom?: (parsed: ParsedStatement, profile: LanguageProfile) => string;\n}\n\n// =============================================================================\n// Parsed Structures\n// =============================================================================\n\n/**\n * A parsed hyperscript statement broken into semantic components\n */\nexport interface ParsedStatement {\n type: 'event-handler' | 'command' | 'conditional' | 'loop';\n roles: Map<SemanticRole, ParsedElement>;\n original: string;\n}\n\n/**\n * A single element with its semantic role\n */\nexport interface ParsedElement {\n role: SemanticRole;\n value: string; // Original English value\n translated?: string; // Translated value\n isSelector?: boolean; // CSS selector (don't translate)\n isLiteral?: boolean; // Literal value (don't translate)\n}\n\n// =============================================================================\n// Universal Pattern Templates\n// =============================================================================\n\n/**\n * Universal templates for common hyperscript patterns\n * These define the semantic structure independent of surface form\n */\nexport const UNIVERSAL_PATTERNS = {\n // on click increment #count\n eventIncrement: {\n name: 'event-increment',\n roles: ['event', 'action', 'patient'] as SemanticRole[],\n english: 'on {event} {action} {patient}',\n },\n\n // put X into Y\n putInto: {\n name: 'put-into',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} into {destination}',\n },\n\n // add .class to element\n addTo: {\n name: 'add-to',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} to {destination}',\n },\n\n // toggle .class on element\n toggleOn: {\n name: 'toggle-on',\n roles: ['action', 'patient', 'destination'] as SemanticRole[],\n english: '{action} {patient} on {destination}',\n },\n\n // wait 2 seconds\n waitDuration: {\n name: 'wait-duration',\n roles: ['action', 'quantity'] as SemanticRole[],\n english: '{action} {quantity}',\n },\n\n // if condition then ... end\n conditional: {\n name: 'conditional',\n roles: ['action', 'condition'] as SemanticRole[],\n english: '{action} {condition} then ... end',\n },\n\n // fetch URL as type\n fetchAs: {\n name: 'fetch-as',\n roles: ['action', 'source', 'method'] as SemanticRole[],\n english: '{action} {source} as {method}',\n },\n\n // show element with animation\n showWith: {\n name: 'show-with',\n roles: ['action', 'patient', 'style'] as SemanticRole[],\n english: '{action} {patient} with {style}',\n },\n\n // transition property over duration\n transitionOver: {\n name: 'transition-over',\n roles: ['action', 'patient', 'duration'] as SemanticRole[],\n english: '{action} {patient} over {duration}',\n },\n} as const;\n\n// =============================================================================\n// Language Family Defaults\n// =============================================================================\n\n/**\n * Default profiles for major language families\n * Individual languages inherit and override these\n */\nexport const LANGUAGE_FAMILY_DEFAULTS: Record<string, Partial<LanguageProfile>> = {\n // Germanic (English, German, Dutch)\n germanic: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Romance (Spanish, French, Italian, Portuguese)\n romance: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'fusional',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Japonic (Japanese)\n japonic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Koreanic (Korean)\n koreanic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Turkic (Turkish, Azerbaijani)\n turkic: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Sinitic (Chinese, Cantonese)\n sinitic: {\n wordOrder: 'SVO', // Topic-prominent, flexible\n adpositionType: 'preposition',\n morphology: 'isolating',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Semitic (Arabic, Hebrew)\n semitic: {\n wordOrder: 'VSO',\n adpositionType: 'preposition',\n morphology: 'fusional', // Root-pattern system\n direction: 'rtl',\n canonicalOrder: [\n 'action',\n 'agent',\n 'patient',\n 'destination',\n 'source',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Austronesian (Indonesian, Tagalog)\n austronesian: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n\n // Quechuan (Quechua)\n quechuan: {\n wordOrder: 'SOV',\n adpositionType: 'postposition',\n morphology: 'agglutinative', // Actually polysynthetic but simplified\n direction: 'ltr',\n canonicalOrder: [\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n 'action',\n ],\n },\n\n // Bantu (Swahili)\n bantu: {\n wordOrder: 'SVO',\n adpositionType: 'preposition',\n morphology: 'agglutinative',\n direction: 'ltr',\n canonicalOrder: [\n 'action',\n 'patient',\n 'source',\n 'destination',\n 'quantity',\n 'duration',\n 'method',\n 'style',\n ],\n },\n};\n\n// =============================================================================\n// Transformation Utilities\n// =============================================================================\n\n/**\n * Reorder semantic roles according to target language.\n * Includes a safety net to append any roles present in input\n * but missing from the target order, preventing data loss.\n */\nexport function reorderRoles(\n roles: Map<SemanticRole, ParsedElement>,\n targetOrder: SemanticRole[]\n): ParsedElement[] {\n const result: ParsedElement[] = [];\n const usedRoles = new Set<SemanticRole>();\n\n // 1. Add roles that are explicitly in the canonical order\n for (const role of targetOrder) {\n const element = roles.get(role);\n if (element) {\n result.push(element);\n usedRoles.add(role);\n }\n }\n\n // 2. Safety Net: Append any roles present in input but missing from target order\n // This prevents data loss (e.g., if 'manner' or 'instrument' isn't in the profile)\n for (const [role, element] of roles) {\n if (!usedRoles.has(role)) {\n result.push(element);\n }\n }\n\n return result;\n}\n\n/**\n * Insert grammatical markers between elements\n */\nexport function insertMarkers(\n elements: ParsedElement[],\n markers: GrammaticalMarker[],\n adpositionType: AdpositionType\n): string[] {\n const result: string[] = [];\n\n for (const element of elements) {\n const marker = markers.find(m => m.role === element.role);\n\n if (marker) {\n if (adpositionType === 'preposition') {\n // Marker before element: \"to element\"\n if (marker.form) result.push(marker.form);\n result.push(element.translated || element.value);\n } else if (adpositionType === 'postposition') {\n // Marker after element: \"element を\"\n result.push(element.translated || element.value);\n if (marker.form) result.push(marker.form);\n } else {\n result.push(element.translated || element.value);\n }\n } else {\n result.push(element.translated || element.value);\n }\n }\n\n return result;\n}\n\n/**\n * Intelligently joins tokens, handling agglutinative suffixes and prefixes.\n *\n * Rules:\n * 1. If a token ends with '-' (prefix marker), no space after it\n * 2. If a token starts with '-' (suffix marker), no space before it\n * 3. Removes the hyphen indicators from the final output\n *\n * Examples:\n * - ['#count', '-ta'] → '#countta' (Quechua accusative suffix)\n * - ['بـ-', 'الماوس'] → 'بـالماوس' (Arabic prefix attachment)\n * - ['value', 'を'] → 'value を' (Japanese particle, normal spacing)\n */\nexport function joinTokens(tokens: string[]): string {\n if (tokens.length === 0) return '';\n\n let result = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n const nextToken = tokens[i + 1];\n\n // Check if current token is a prefix (ends with -)\n const isPrefix = token.endsWith('-');\n // Check if current token is a suffix (starts with -)\n const isSuffix = token.startsWith('-');\n\n // Get the display form (strip hyphen markers)\n let displayToken = token;\n if (isPrefix) displayToken = token.slice(0, -1);\n if (isSuffix) displayToken = token.substring(1);\n\n result += displayToken;\n\n // Determine if we need a space before the next token\n if (nextToken) {\n const nextIsSuffix = nextToken.startsWith('-');\n\n // Don't add space if:\n // - Current token is a prefix (ends with -)\n // - Next token is a suffix (starts with -)\n if (!isPrefix && !nextIsSuffix) {\n result += ' ';\n }\n }\n }\n\n return result;\n}\n\n/**\n * Transform a parsed statement to target language\n */\nexport function transformStatement(\n parsed: ParsedStatement,\n _sourceProfile: LanguageProfile,\n targetProfile: LanguageProfile\n): string {\n // 1. Reorder roles for target language\n const reordered = reorderRoles(parsed.roles, targetProfile.canonicalOrder);\n\n // 2. Insert grammatical markers\n const withMarkers = insertMarkers(reordered, targetProfile.markers, targetProfile.adpositionType);\n\n // 3. Join with intelligent spacing for agglutinative languages\n // (handles suffixes like -ta, prefixes like بـ-, etc.)\n return joinTokens(withMarkers);\n}\n","/**\n * Grammar Transformer - Dependency Injection Architecture\n *\n * Transforms statements between languages using injected dependencies.\n * This makes the transformer completely domain-agnostic.\n */\n\nimport type { LanguageProfile, ParsedElement, SemanticRole } from './types';\nimport { reorderRoles, insertMarkers, joinTokens } from './types';\nimport type { Dictionary } from '../interfaces/dictionary';\nimport type { ProfileProvider } from '../interfaces/profile-provider';\n\n/**\n * Configuration for grammar transformer.\n */\nexport interface TransformerConfig {\n /** Dictionary for keyword translation */\n readonly dictionary: Dictionary;\n\n /** Profile provider for grammar rules */\n readonly profileProvider: ProfileProvider;\n}\n\n/**\n * Generic grammar transformer using dependency injection.\n *\n * @example\n * const transformer = new GrammarTransformer({\n * dictionary: new InMemoryDictionary(translations),\n * profileProvider: new InMemoryProfileProvider(profiles)\n * });\n *\n * const japanese = transformer.transform('select name from users', 'en', 'ja');\n * // → \"users から name を 選択\"\n */\nexport class GrammarTransformer {\n private dictionary: Dictionary;\n private profileProvider: ProfileProvider;\n\n constructor(config: TransformerConfig) {\n this.dictionary = config.dictionary;\n this.profileProvider = config.profileProvider;\n }\n\n /**\n * Transform a statement from one language to another.\n *\n * @param input - Statement in source language\n * @param fromLanguage - Source language code\n * @param toLanguage - Target language code\n * @returns Transformed statement in target language\n *\n * @throws Error if profiles not found or translation fails\n */\n transform(input: string, fromLanguage: string, toLanguage: string): string {\n // Get language profiles\n const fromProfile = this.profileProvider.getProfile(fromLanguage);\n const toProfile = this.profileProvider.getProfile(toLanguage);\n\n if (!fromProfile) {\n throw new Error(`No profile found for language: ${fromLanguage}`);\n }\n if (!toProfile) {\n throw new Error(`No profile found for language: ${toLanguage}`);\n }\n\n // Parse statement to semantic roles\n const parsed = this.parseStatement(input, fromLanguage, fromProfile);\n\n // Translate each word\n const translated = this.translateRoles(parsed, fromLanguage, toLanguage);\n\n // Reorder and insert markers\n const reordered = reorderRoles(translated, toProfile.canonicalOrder);\n\n const withMarkers = insertMarkers(reordered, toProfile.markers, toProfile.adpositionType);\n\n return joinTokens(withMarkers);\n }\n\n /**\n * Parse statement into semantic roles.\n * This is a simplified generic parser - DSLs can provide custom parsers.\n */\n private parseStatement(\n input: string,\n language: string,\n profile: LanguageProfile\n ): Map<SemanticRole, string> {\n const roles = new Map<SemanticRole, string>();\n const tokens = input.split(/\\s+/);\n\n // Simple parsing: extract roles based on markers\n let i = 0;\n while (i < tokens.length) {\n const token = tokens[i];\n\n // Check if token is a marker\n const marker = profile.markers.find(m => m.form === token);\n\n if (marker) {\n // Next token is the value for this role\n if (i + 1 < tokens.length) {\n roles.set(marker.role, tokens[i + 1]);\n i += 2;\n } else {\n i++;\n }\n } else {\n // Look up token in dictionary to find its role\n const canonical = this.dictionary.lookup(token, language);\n\n if (canonical) {\n // Assume it's the action (command keyword)\n roles.set('action', canonical);\n } else {\n // Assume it's a value (selector, identifier, etc.)\n // Try to guess the role based on syntax\n if (token.startsWith('#') || token.startsWith('.')) {\n roles.set('patient', token);\n } else {\n // Default to patient for unknown values\n roles.set('patient', token);\n }\n }\n\n i++;\n }\n }\n\n return roles;\n }\n\n /**\n * Translate roles using injected dictionary.\n * Returns a Map of ParsedElement objects expected by reorderRoles.\n */\n private translateRoles(\n roles: Map<SemanticRole, string>,\n _fromLanguage: string,\n toLanguage: string\n ): Map<SemanticRole, ParsedElement> {\n const result = new Map<SemanticRole, ParsedElement>();\n\n for (const [role, value] of roles) {\n // Translate using dictionary\n const translated = this.dictionary.translate(value, toLanguage);\n\n // Create ParsedElement with role, value, and translated\n result.set(role, {\n role,\n value, // Original value\n translated: translated ?? value, // Translated value or original if no translation\n });\n }\n\n return result;\n }\n}\n","/**\n * Dictionary Interface - Keyword Translation\n *\n * Provides keyword translations between languages.\n * DSLs implement this to provide their domain-specific translations.\n */\n\n/**\n * Dictionary provides keyword translations between languages.\n */\nexport interface Dictionary {\n /**\n * Look up canonical form from localized keyword.\n *\n * @param localizedWord - Word in target language (e.g., 'トグル', 'alternar')\n * @param language - Language code\n * @returns Canonical form (e.g., 'toggle') or undefined\n *\n * @example\n * dictionary.lookup('トグル', 'ja') // → 'toggle'\n * dictionary.lookup('alternar', 'es') // → 'toggle'\n */\n lookup(localizedWord: string, language: string): string | undefined;\n\n /**\n * Translate canonical keyword to target language.\n *\n * @param canonical - Canonical form (e.g., 'toggle')\n * @param targetLanguage - Target language code\n * @returns Localized form or undefined\n *\n * @example\n * dictionary.translate('toggle', 'ja') // → 'トグル'\n * dictionary.translate('toggle', 'es') // → 'alternar'\n */\n translate(canonical: string, targetLanguage: string): string | undefined;\n\n /**\n * Get all translations of a word across all supported languages.\n *\n * @param word - Word to translate\n * @param sourceLanguage - Source language\n * @returns Map of language code to translation\n *\n * @example\n * dictionary.getAllTranslations('toggle', 'en')\n * // → { ja: 'トグル', es: 'alternar', ko: '토글', ... }\n */\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string>;\n\n /**\n * Optional: Find what category a word belongs to.\n * Useful for organizing translations by domain (commands, modifiers, events, etc.).\n */\n getCategory?(word: string, language: string): string | undefined;\n}\n\n/**\n * Simple in-memory dictionary implementation.\n * Suitable for small DSLs or prototyping.\n */\nexport class InMemoryDictionary implements Dictionary {\n /**\n * @param translations - Map of language code to canonical→localized mappings\n *\n * @example\n * new InMemoryDictionary({\n * en: { select: 'select', insert: 'insert' },\n * es: { select: 'seleccionar', insert: 'insertar' },\n * ja: { select: '選択', insert: '挿入' }\n * })\n */\n constructor(private translations: Record<string, Record<string, string>>) {}\n\n lookup(word: string, language: string): string | undefined {\n const langDict = this.translations[language];\n if (!langDict) return undefined;\n\n // Reverse lookup: find key where value = word\n const wordLower = word.toLowerCase();\n for (const [canonical, localized] of Object.entries(langDict)) {\n if (localized.toLowerCase() === wordLower) {\n return canonical;\n }\n }\n return undefined;\n }\n\n translate(canonical: string, targetLanguage: string): string | undefined {\n return this.translations[targetLanguage]?.[canonical];\n }\n\n getAllTranslations(word: string, sourceLanguage: string): Record<string, string> {\n const canonical = this.lookup(word, sourceLanguage);\n if (!canonical) return {};\n\n const result: Record<string, string> = {};\n for (const [lang, dict] of Object.entries(this.translations)) {\n const translation = dict[canonical];\n if (translation) {\n result[lang] = translation;\n }\n }\n return result;\n }\n}\n\n/**\n * Null dictionary - no translations (useful for single-language DSLs).\n */\nexport class NullDictionary implements Dictionary {\n lookup(word: string, _language: string): string | undefined {\n return word; // Identity: word is its own canonical form\n }\n\n translate(canonical: string, _targetLanguage: string): string | undefined {\n return canonical; // Identity: no translation\n }\n\n getAllTranslations(word: string, _sourceLanguage: string): Record<string, string> {\n return { en: word }; // Only source language\n }\n}\n","/**\n * Profile Provider Interface - Language Profile Access\n *\n * Provides language profiles for grammar transformation.\n * DSLs implement this to provide their domain-specific profiles.\n */\n\nimport type { LanguageProfile } from '../grammar';\n\n/**\n * Provides language profiles for transformation.\n */\nexport interface ProfileProvider {\n /**\n * Get language profile by code.\n *\n * @param language - ISO 639-1 code (e.g., 'en', 'ja', 'es')\n * @returns Language profile or undefined if not supported\n *\n * @example\n * const profile = provider.getProfile('ja');\n * console.log(profile.wordOrder); // 'SOV'\n */\n getProfile(language: string): LanguageProfile | undefined;\n\n /**\n * Get all supported language codes.\n *\n * @returns Array of ISO 639-1 codes\n *\n * @example\n * provider.getSupportedLanguages() // → ['en', 'ja', 'es', 'ko']\n */\n getSupportedLanguages(): string[];\n\n /**\n * Check if a language is supported.\n *\n * @param language - Language code to check\n * @returns True if language is supported\n */\n hasLanguage(language: string): boolean;\n}\n\n/**\n * Simple in-memory profile provider.\n */\nexport class InMemoryProfileProvider implements ProfileProvider {\n /**\n * @param profiles - Map of language code to profile\n *\n * @example\n * new InMemoryProfileProvider({\n * en: { code: 'en', wordOrder: 'SVO', ... },\n * ja: { code: 'ja', wordOrder: 'SOV', ... }\n * })\n */\n constructor(private profiles: Record<string, LanguageProfile>) {}\n\n getProfile(language: string): LanguageProfile | undefined {\n return this.profiles[language];\n }\n\n getSupportedLanguages(): string[] {\n return Object.keys(this.profiles);\n }\n\n hasLanguage(language: string): boolean {\n return language in this.profiles;\n }\n}\n\n/**\n * Null profile provider - for DSLs that don't need grammar transformation.\n */\nexport class NullProfileProvider implements ProfileProvider {\n getProfile(_language: string): LanguageProfile | undefined {\n return undefined;\n }\n\n getSupportedLanguages(): string[] {\n return [];\n }\n\n hasLanguage(_language: string): boolean {\n return false;\n }\n}\n","/**\n * Value Extractor Interface - Pluggable Tokenization\n *\n * Extracts typed values from input strings.\n * DSLs can provide custom extractors for their domain-specific syntax.\n *\n * Includes the ContextAwareExtractor extension for extractors that need\n * access to tokenizer state (keyword maps, morphological normalizers, etc.).\n */\n\nimport type { MorphologicalNormalizer } from '../core/tokenization/morphology/types';\n\n// =============================================================================\n// Keyword Entry (needed by TokenizerContext)\n// =============================================================================\n\n/**\n * Keyword entry for tokenizer - maps native word to normalized English form.\n * Re-exported here so ContextAwareExtractor consumers can use it without\n * depending on the base-tokenizer module directly.\n */\nexport interface KeywordEntry {\n readonly native: string;\n readonly normalized: string;\n}\n\n// =============================================================================\n// Core Extractor Types\n// =============================================================================\n\n/**\n * Extraction result with value and consumed length.\n */\nexport interface ExtractionResult {\n /** The extracted value */\n readonly value: string;\n\n /** Number of characters consumed */\n readonly length: number;\n\n /** Optional metadata about the extraction */\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Value extractor - identifies and extracts typed values from input.\n */\nexport interface ValueExtractor {\n /** Name of this extractor (for debugging) */\n readonly name: string;\n\n /**\n * Check if this extractor can handle input at position.\n *\n * @param input - Full input string\n * @param position - Current position\n * @returns True if this extractor should try\n *\n * @example\n * // CSS selector extractor\n * canExtract('#button', 0) // → true (starts with #)\n * canExtract('button', 0) // → false\n */\n canExtract(input: string, position: number): boolean;\n\n /**\n * Extract value from input at position.\n *\n * @param input - Full input string\n * @param position - Start position\n * @returns Extraction result or null if extraction failed\n *\n * @example\n * extract('#button', 0) // → { value: '#button', length: 7 }\n * extract('button', 0) // → null (can't extract CSS selector)\n */\n extract(input: string, position: number): ExtractionResult | null;\n}\n\n/**\n * String literal extractor - handles quoted strings.\n */\nexport class StringLiteralExtractor implements ValueExtractor {\n readonly name = 'string-literal';\n\n canExtract(input: string, position: number): boolean {\n const char = input[position];\n // An ASCII apostrophe glued to the END of a word is the possessive marker\n // (`#price's value`, `my's` never occurs but `it's`/`#qty's` do), not a\n // string opener. Reading it as a quote paired it with the NEXT possessive:\n // `(#price's value * #qty's value)` lexed `'s value * #qty'` as one string\n // literal, which swallowed the operator and hid the property noun from\n // translation in every language that renders `'s`. A quote that opens a\n // string always follows whitespace, punctuation, or the start of input.\n if (char === \"'\" && position > 0 && /[\\p{L}\\p{N}_)\\]]/u.test(input[position - 1])) {\n return false;\n }\n return (\n char === '\"' ||\n char === \"'\" ||\n char === '`' ||\n char === '\\u201C' || // Chinese double quote open \"\n char === '\\u2018' // Chinese single quote open '\n );\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n const quote = input[position];\n\n // Chinese double quotes \" ... \"\n if (quote === '\\u201C') {\n let length = 1;\n while (position + length < input.length) {\n if (input[position + length] === '\\u201D') {\n length++;\n return { value: input.substring(position, position + length), length };\n }\n length++;\n }\n return null;\n }\n\n // Chinese single quotes ' ... '\n if (quote === '\\u2018') {\n let length = 1;\n while (position + length < input.length) {\n if (input[position + length] === '\\u2019') {\n length++;\n return { value: input.substring(position, position + length), length };\n }\n length++;\n }\n return null;\n }\n\n // ASCII quotes (same open/close, support escaping)\n let length = 1;\n let escaped = false;\n\n while (position + length < input.length) {\n const char = input[position + length];\n\n if (escaped) {\n escaped = false;\n length++;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n length++;\n continue;\n }\n\n if (char === quote) {\n length++; // Include closing quote\n return {\n value: input.substring(position, position + length),\n length,\n };\n }\n\n length++;\n }\n\n // Unterminated string\n return null;\n }\n}\n\n/**\n * Number extractor - handles integers and floats.\n */\nexport class NumberExtractor implements ValueExtractor {\n readonly name = 'number';\n\n canExtract(input: string, position: number): boolean {\n return /\\d/.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n let hasDecimal = false;\n\n while (position + length < input.length) {\n const char = input[position + length];\n\n if (/\\d/.test(char)) {\n length++;\n } else if (char === '.' && !hasDecimal) {\n hasDecimal = true;\n length++;\n } else {\n break;\n }\n }\n\n if (length === 0) return null;\n\n const numValue = input.substring(position, position + length);\n const afterNum = position + length;\n\n // Check for time unit suffixes\n if (afterNum < input.length) {\n const remaining = input.slice(afterNum);\n\n // CJK multi-char time units (longest first)\n const cjkMultiUnits: { pattern: string; suffix: string }[] = [\n { pattern: '毫秒', suffix: 'ms' }, // Chinese milliseconds\n { pattern: '分钟', suffix: 'm' }, // Chinese minutes\n { pattern: '小时', suffix: 'h' }, // Chinese hours\n { pattern: 'ミリ秒', suffix: 'ms' }, // Japanese milliseconds\n { pattern: '時間', suffix: 'h' }, // Japanese hours\n ];\n for (const unit of cjkMultiUnits) {\n if (remaining.startsWith(unit.pattern)) {\n return {\n value: numValue + unit.suffix,\n length: length + unit.pattern.length,\n metadata: { hasTimeUnit: true },\n };\n }\n }\n\n // ASCII 'ms' (2 chars, must check before single-char)\n if (remaining.startsWith('ms')) {\n return {\n value: numValue + 'ms',\n length: length + 2,\n metadata: { hasTimeUnit: true },\n };\n }\n\n // CJK single-char time units\n const cjkSingleUnits: { pattern: string; suffix: string }[] = [\n { pattern: '秒', suffix: 's' }, // CJK seconds\n { pattern: '分', suffix: 'm' }, // CJK minutes\n ];\n for (const unit of cjkSingleUnits) {\n if (remaining.startsWith(unit.pattern)) {\n return {\n value: numValue + unit.suffix,\n length: length + 1,\n metadata: { hasTimeUnit: true },\n };\n }\n }\n\n // ASCII single-char units: s, m, h (with word boundary check)\n if (/^[smh](?![a-zA-Z])/.test(remaining)) {\n return {\n value: numValue + remaining[0],\n length: length + 1,\n metadata: { hasTimeUnit: true },\n };\n }\n }\n\n return { value: numValue, length };\n }\n}\n\n/**\n * Identifier extractor - handles variable/property names.\n */\nexport class IdentifierExtractor implements ValueExtractor {\n readonly name = 'identifier';\n\n canExtract(input: string, position: number): boolean {\n return /[a-zA-Z_]/.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n\n while (position + length < input.length) {\n const char = input[position + length];\n if (/[a-zA-Z0-9_]/.test(char)) {\n length++;\n } else {\n break;\n }\n }\n\n return length > 0\n ? {\n value: input.substring(position, position + length),\n length,\n }\n : null;\n }\n}\n\n/**\n * Unicode identifier extractor - handles non-Latin scripts.\n *\n * Matches contiguous runs of Unicode letters, numbers, and combining marks\n * that aren't ASCII (ASCII identifiers are handled by IdentifierExtractor).\n * Essential for DSLs supporting CJK, Arabic, Cyrillic, Devanagari, etc.\n */\nexport class UnicodeIdentifierExtractor implements ValueExtractor {\n readonly name = 'unicode-identifier';\n\n canExtract(input: string, position: number): boolean {\n const code = input.charCodeAt(position);\n // Skip ASCII range (handled by IdentifierExtractor)\n if (code < 0x80) return false;\n // Match any Unicode letter\n return /\\p{L}/u.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n\n while (position + length < input.length) {\n const char = input[position + length];\n // Match Unicode letters, numbers, and combining marks (e.g., Arabic diacritics)\n if (/[\\p{L}\\p{N}\\p{M}]/u.test(char)) {\n length++;\n } else {\n break;\n }\n }\n\n return length > 0 ? { value: input.substring(position, position + length), length } : null;\n }\n}\n\n/**\n * Latin Extended identifier extractor — handles Latin-script languages with\n * diacritics (Spanish ñ/á/é/í/ó/ú; French é/à/ù/ç; Turkish ç/ş/ı/ü/ğ/ö;\n * Portuguese ã/õ; German ä/ö/ü/ß; etc).\n *\n * Use this in addition to (or instead of) the default `IdentifierExtractor`\n * for any tokenizer whose language is Latin-script and may contain diacritic\n * characters in identifiers. Without it, words like `añadir` tokenize as\n * `[\"a\", \"ñadir\"]` because the default ASCII extractor stops at `ñ` and the\n * Unicode extractor only kicks in when a token *starts* with a non-ASCII\n * character.\n *\n * Matches contiguous runs of `/[\\p{L}\\p{N}_-]/u` — any Unicode letter or\n * number, plus underscore and hyphen.\n */\nexport class LatinExtendedIdentifierExtractor implements ValueExtractor {\n readonly name = 'latin-extended-identifier';\n\n canExtract(input: string, position: number): boolean {\n return /\\p{L}/u.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let end = position;\n while (end < input.length && /[\\p{L}\\p{N}_-]/u.test(input[end])) {\n end++;\n }\n if (end === position) return null;\n return { value: input.slice(position, end), length: end - position };\n }\n}\n\n/**\n * CSS selector extractor — keeps `#id` and `.class` a SINGLE token.\n *\n * Without it the sigil is split off as its own token and the role capture keeps\n * only that sigil: `add .active to #button` parses with patient `\".\"` and\n * destination `\"#\"`, silently, in every language. Five domain DSLs each carried\n * a private copy of this class and four (learn, todo, sql, jsx) had none — this\n * is the shared one; register it via `customExtractors`.\n *\n * The character after the sigil must be a letter, `_` or `-`: a CSS identifier\n * cannot start with a digit, and refusing to claim a bare `.`/`#` leaves\n * property access and other uses of those characters to the extractors that own\n * them.\n *\n * The body is Unicode so diacritics survive (`.año`, not `.a`) but STOPS at Han,\n * kana and Hangul. Those scripts are where the SOV languages write their\n * particles, and a selector is written adjacent to them with no space:\n * `#buttonに .activeを 追加` must yield `#button` + `に`, not a `#buttonに` that\n * swallows the particle and takes the role marker with it.\n */\nconst SELECTOR_BODY_CHAR = /[\\p{L}\\p{N}_-]/u;\nconst PARTICLE_SCRIPT_CHAR = /[\\p{sc=Han}\\p{sc=Hiragana}\\p{sc=Katakana}\\p{sc=Hangul}]/u;\n\nfunction isSelectorBodyChar(char: string): boolean {\n return SELECTOR_BODY_CHAR.test(char) && !PARTICLE_SCRIPT_CHAR.test(char);\n}\n\nexport class CssSelectorExtractor implements ValueExtractor {\n readonly name = 'css-selector';\n\n canExtract(input: string, position: number): boolean {\n const char = input[position];\n if (char !== '#' && char !== '.') return false;\n const next = input[position + 1];\n if (next === undefined) return false;\n return (\n next === '_' || next === '-' || (/\\p{L}/u.test(next) && !PARTICLE_SCRIPT_CHAR.test(next))\n );\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let end = position + 1;\n while (end < input.length && isSelectorBodyChar(input[end])) {\n end++;\n }\n if (end === position + 1) return null;\n return { value: input.slice(position, end), length: end - position };\n }\n}\n\n/**\n * Whitespace extractor - handles spaces, tabs, newlines.\n */\nexport class WhitespaceExtractor implements ValueExtractor {\n readonly name = 'whitespace';\n\n canExtract(input: string, position: number): boolean {\n return /\\s/.test(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n let length = 0;\n\n while (position + length < input.length && /\\s/.test(input[position + length])) {\n length++;\n }\n\n return length > 0\n ? {\n value: input.substring(position, position + length),\n length,\n }\n : null;\n }\n}\n\n// =============================================================================\n// Context-Aware Extractor System\n// =============================================================================\n\n/**\n * Tokenizer context provided to context-aware extractors.\n * Gives extractors access to tokenizer state without tight coupling.\n */\nexport interface TokenizerContext {\n /** ISO 639-1 language code */\n readonly language: string;\n\n /** Text direction */\n readonly direction: 'ltr' | 'rtl';\n\n /**\n * Look up a keyword by its native form.\n * Returns keyword entry with normalized form, or undefined if not found.\n */\n lookupKeyword(native: string): KeywordEntry | undefined;\n\n /**\n * Check if a word is a known keyword.\n */\n isKeyword(native: string): boolean;\n\n /**\n * Check if a known keyword starts at the given position.\n * Useful for word boundary detection in non-space languages.\n */\n isKeywordStart(input: string, position: number): boolean;\n\n /**\n * Like `isKeywordStart`, but only true when the keyword match ends at a\n * word boundary (end of input or a char rejected by `isWordChar`).\n * Space-delimited languages must use this for word-walk break checks —\n * the keyword table includes English canonical fallbacks (me, it, you, …),\n * so the raw check splits native words mid-word (e.g. Quechua ñit'iy\n * contains \"it\"). Optional for backward compatibility with hand-rolled\n * contexts; callers should treat absence as \"no boundary keyword here\".\n */\n isKeywordStartAtBoundary?(\n input: string,\n position: number,\n isWordChar?: (char: string) => boolean\n ): boolean;\n\n /**\n * Optional morphological normalizer for this language.\n */\n readonly normalizer?: MorphologicalNormalizer;\n}\n\n/**\n * Context-aware extractor - has access to tokenizer state.\n *\n * Use this for extractors that need:\n * - Keyword lookup (for normalization)\n * - Morphological analysis (for conjugation handling)\n * - Language-specific rules\n *\n * For stateless extractors (strings, numbers, operators), use ValueExtractor.\n */\nexport interface ContextAwareExtractor extends ValueExtractor {\n /**\n * Set the tokenizer context.\n * Called once by the tokenizer during registration.\n */\n setContext(context: TokenizerContext): void;\n}\n\n/**\n * Type guard to check if an extractor is context-aware.\n */\nexport function isContextAwareExtractor(\n extractor: ValueExtractor | ContextAwareExtractor\n): extractor is ContextAwareExtractor {\n return 'setContext' in extractor && typeof extractor.setContext === 'function';\n}\n\n/**\n * Create a TokenizerContext from a tokenizer instance.\n * Works with any object that exposes the required methods.\n */\nexport function createTokenizerContext(tokenizer: {\n language: string;\n direction: 'ltr' | 'rtl';\n lookupKeyword(native: string): KeywordEntry | undefined;\n isKeyword(native: string): boolean;\n isKeywordStart(input: string, position: number): boolean;\n isKeywordStartAtBoundary?(\n input: string,\n position: number,\n isWordChar?: (char: string) => boolean\n ): boolean;\n normalizer?: MorphologicalNormalizer;\n}): TokenizerContext {\n const ctx: TokenizerContext = {\n language: tokenizer.language,\n direction: tokenizer.direction,\n lookupKeyword: tokenizer.lookupKeyword.bind(tokenizer),\n isKeyword: tokenizer.isKeyword.bind(tokenizer),\n isKeywordStart: tokenizer.isKeywordStart.bind(tokenizer),\n ...(tokenizer.isKeywordStartAtBoundary\n ? { isKeywordStartAtBoundary: tokenizer.isKeywordStartAtBoundary.bind(tokenizer) }\n : {}),\n };\n\n if (tokenizer.normalizer) {\n return { ...ctx, normalizer: tokenizer.normalizer };\n }\n\n return ctx;\n}\n","/**\n * Reference Validation — re-exported from @lokascript/intent\n */\n\nexport { DEFAULT_REFERENCES, isValidReference } from '@lokascript/intent';\n","/**\n * Explicit Syntax Parser — re-exported from @lokascript/intent\n */\n\nexport {\n STRUCTURAL_ROLES,\n parseExplicit,\n isExplicitSyntax,\n parseCompound,\n parseDocument,\n isCompoundSyntax,\n isDocumentSyntax,\n} from '@lokascript/intent';\n","/**\n * Explicit Syntax Renderer — re-exported from @lokascript/intent\n */\n\nexport { renderExplicit, renderDocument } from '@lokascript/intent';\n","/**\n * LLM JSON Schema Conversion (DEPRECATED)\n *\n * These functions are superseded by the unified protocol JSON functions in\n * protocol-json.ts. `fromProtocolJSON()` now accepts optional `kind` (defaults\n * to \"command\") and `trigger` sugar, making these wrappers unnecessary.\n *\n * Use instead:\n * - `validateProtocolJSON()` instead of `validateSemanticJSON()`\n * - `fromProtocolJSON()` instead of `jsonToSemanticNode()`\n * - `toProtocolJSON()` instead of `semanticNodeToJSON()`\n *\n * These functions are kept for backward compatibility and will be removed\n * in a future major version.\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n SemanticRole,\n EventHandlerSemanticNode,\n CompoundSemanticNode,\n} from '../core/types';\nimport {\n createCommandNode,\n createEventHandlerNode,\n createSelector,\n createLiteral,\n createReference,\n createExpression,\n createFlag,\n} from '../core/types';\nimport type { SemanticJSON, SemanticJSONValue, IRDiagnostic } from './types';\n\n// =============================================================================\n// Validation\n// =============================================================================\n\nconst VALID_VALUE_TYPES = new Set([\n 'selector',\n 'literal',\n 'reference',\n 'expression',\n 'property-path',\n 'flag',\n]);\n\n/**\n * Validate LLM JSON input structure.\n * Returns diagnostics (empty array = valid).\n * @deprecated Use `validateProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function validateSemanticJSON(input: SemanticJSON): IRDiagnostic[] {\n const diagnostics: IRDiagnostic[] = [];\n\n // Action is required and must be a string\n if (!input.action || typeof input.action !== 'string') {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_ACTION',\n message: 'Field \"action\" is required and must be a string.',\n suggestion: 'Provide a command name like \"toggle\", \"add\", \"set\", etc.',\n });\n return diagnostics; // Can't proceed without action\n }\n\n // Roles validation\n if (input.roles && typeof input.roles === 'object') {\n for (const [role, value] of Object.entries(input.roles)) {\n if (!value || typeof value !== 'object') {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_ROLE_VALUE',\n message: `Role \"${role}\" must be an object with \"type\" and \"value\" fields.`,\n suggestion: 'Use: { \"type\": \"selector\", \"value\": \".active\" }',\n });\n continue;\n }\n\n const v = value as SemanticJSONValue;\n if (!VALID_VALUE_TYPES.has(v.type)) {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_VALUE_TYPE',\n message: `Role \"${role}\" has invalid type \"${v.type}\".`,\n suggestion: 'Valid types: selector, literal, reference, expression, property-path.',\n });\n }\n\n if (v.value === undefined || v.value === null) {\n diagnostics.push({\n severity: 'error',\n code: 'MISSING_VALUE',\n message: `Role \"${role}\" is missing the \"value\" field.`,\n });\n }\n }\n }\n\n // Trigger validation (optional)\n if (input.trigger) {\n if (!input.trigger.event || typeof input.trigger.event !== 'string') {\n diagnostics.push({\n severity: 'error',\n code: 'INVALID_TRIGGER',\n message: 'Trigger \"event\" is required and must be a string.',\n suggestion: 'Use an event name like \"click\", \"mouseover\", \"keydown\".',\n });\n }\n }\n\n return diagnostics;\n}\n\n// =============================================================================\n// JSON → SemanticNode\n// =============================================================================\n\n/**\n * Convert validated SemanticJSON to a SemanticNode.\n *\n * Returns a properly typed SemanticNode using the framework's factory functions.\n * If `trigger` is present, wraps the command in an event handler node.\n * @deprecated Use `fromProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function jsonToSemanticNode(input: SemanticJSON): SemanticNode {\n const roles = new Map<SemanticRole, SemanticValue>();\n\n if (input.roles) {\n for (const [role, value] of Object.entries(input.roles)) {\n roles.set(role as SemanticRole, convertJSONValue(value));\n }\n }\n\n // Event handler wrapping\n if (input.trigger) {\n // Set the event role\n roles.set('event' as SemanticRole, createLiteral(input.trigger.event, 'string'));\n\n // Build body as a single command node\n const bodyRoles = new Map(roles);\n bodyRoles.delete('event' as SemanticRole);\n const bodyNode = createCommandNode(input.action, bodyRoles);\n\n return createEventHandlerNode(\n 'on',\n roles,\n [bodyNode],\n { sourceLanguage: 'json' },\n (input.trigger.modifiers as Record<string, unknown> | undefined) ?? {}\n );\n }\n\n return createCommandNode(input.action, roles, {\n sourceLanguage: 'json',\n });\n}\n\n// =============================================================================\n// SemanticNode → JSON\n// =============================================================================\n\n/**\n * Convert a SemanticNode to SemanticJSON format.\n *\n * This is the inverse of jsonToSemanticNode(). For event handlers,\n * the event is extracted into the `trigger` field.\n * @deprecated Use `toProtocolJSON()` from `protocol-json.ts` instead.\n */\nexport function semanticNodeToJSON(node: SemanticNode): SemanticJSON {\n if (node.kind === 'compound') {\n // Compound nodes: use first statement's action, flatten roles\n const compound = node as CompoundSemanticNode;\n if (compound.statements.length > 0) {\n return semanticNodeToJSON(compound.statements[0]);\n }\n return { action: 'compound', roles: {} };\n }\n\n if (node.kind === 'event-handler') {\n const eventNode = node as EventHandlerSemanticNode;\n const bodyAction = eventNode.body?.[0]?.action ?? node.action;\n const roles: Record<string, SemanticJSONValue> = {};\n\n // Convert body's roles (not the event handler's)\n if (eventNode.body?.[0]) {\n for (const [role, value] of eventNode.body[0].roles) {\n roles[role] = semanticValueToJSON(value);\n }\n }\n\n // Extract event from roles\n const eventValue = node.roles.get('event');\n const eventName = eventValue\n ? 'value' in eventValue\n ? String(eventValue.value)\n : 'raw' in eventValue\n ? eventValue.raw\n : 'unknown'\n : 'unknown';\n\n const result: SemanticJSON = {\n action: bodyAction === 'on' ? (eventNode.body?.[0]?.action ?? 'on') : bodyAction,\n roles,\n trigger: {\n event: eventName,\n },\n };\n\n if (eventNode.eventModifiers && Object.keys(eventNode.eventModifiers).length > 0) {\n result.trigger!.modifiers = eventNode.eventModifiers as Record<string, unknown>;\n }\n\n return result;\n }\n\n // Regular command\n const roles: Record<string, SemanticJSONValue> = {};\n for (const [role, value] of node.roles) {\n roles[role] = semanticValueToJSON(value);\n }\n\n return { action: node.action, roles };\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Convert a SemanticJSONValue to a SemanticValue.\n */\nfunction convertJSONValue(value: SemanticJSONValue): SemanticValue {\n switch (value.type) {\n case 'selector':\n return createSelector(String(value.value), detectSelectorKind(String(value.value)));\n\n case 'literal':\n return createLiteral(\n value.value,\n typeof value.value === 'number'\n ? 'number'\n : typeof value.value === 'boolean'\n ? 'boolean'\n : 'string'\n );\n\n case 'reference':\n return createReference(String(value.value));\n\n case 'expression':\n return createExpression(String(value.value));\n\n case 'property-path':\n // Property paths in JSON are represented as dot-separated strings\n return createExpression(String(value.value));\n\n case 'flag':\n return createFlag(String(value.value), true);\n\n default:\n return createLiteral(String(value.value), 'string');\n }\n}\n\n/**\n * Convert a SemanticValue to a SemanticJSONValue.\n */\nfunction semanticValueToJSON(value: SemanticValue): SemanticJSONValue {\n switch (value.type) {\n case 'selector':\n return { type: 'selector', value: value.value };\n\n case 'literal':\n return { type: 'literal', value: value.value };\n\n case 'reference':\n return { type: 'reference', value: value.value };\n\n case 'expression':\n return { type: 'expression', value: value.raw };\n\n case 'property-path':\n return {\n type: 'property-path',\n value: `${semanticValueToJSON(value.object).value}.${value.property}`,\n };\n\n case 'flag':\n return { type: 'flag', value: value.enabled };\n }\n}\n\nfunction detectSelectorKind(selector: string): 'id' | 'class' | 'attribute' | 'complex' {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n","/**\n * Protocol JSON Serialization — re-exported from @lokascript/intent\n */\n\nexport {\n toProtocolJSON,\n fromProtocolJSON,\n validateProtocolJSON,\n toEnvelopeJSON,\n fromEnvelopeJSON,\n isEnvelope,\n} from '@lokascript/intent';\n","/**\n * InterchangeNode → SemanticNode Converter\n *\n * Converts the expression-level InterchangeNode AST (from core/semantic parsers)\n * into the command-level SemanticNode IR used by LSE, MCP tools, and domain DSLs.\n *\n * This bridges the two IR pipelines in the monorepo:\n * - Pipeline A (InterchangeNode): full expression trees, 16 node types\n * - Pipeline B (SemanticNode): command-level semantics, opaque expression values\n *\n * Expression subtrees are intentionally collapsed to ExpressionValue { raw: string }\n * — LSE deliberately abstracts away expression-level detail.\n *\n * Uses structural typing for the input to avoid a dependency on the core package.\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n SemanticRole,\n LoopVariant,\n EventModifiers as SemanticEventModifiers,\n} from '../core/types';\nimport {\n createCommandNode,\n createEventHandlerNode,\n createConditionalNode,\n createLoopNode,\n createLiteral,\n createSelector,\n createReference,\n createExpression,\n createPropertyPath,\n} from '../core/types';\nimport { DEFAULT_REFERENCES } from './references';\n\n// =============================================================================\n// Structural Input Types (no core package dependency)\n// =============================================================================\n\n/**\n * Minimal interface matching InterchangeNode's structural shape.\n * Uses the `type` discriminant for dispatch. Additional fields are\n * accessed dynamically — this keeps the framework free of core imports.\n */\ninterface INode {\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Convert an InterchangeNode (expression-level AST) to a SemanticNode (command-level IR).\n *\n * Handles all 16 InterchangeNode types:\n * - Command/event nodes map to corresponding SemanticNode kinds\n * - Control flow nodes (if, repeat, foreach, while) map to conditional/loop kinds\n * - Expression nodes are wrapped as `get` commands with the value as patient role\n *\n * @param node - An InterchangeNode (or structurally compatible object)\n * @returns A SemanticNode suitable for LSE rendering, protocol JSON, or MCP tools\n */\nexport function fromInterchangeNode(node: INode): SemanticNode {\n if (!node || typeof node !== 'object') {\n return createCommandNode('unknown', {});\n }\n\n switch (node.type) {\n case 'event':\n return convertEvent(node);\n\n case 'command':\n return convertCommand(node);\n\n case 'if':\n return convertIf(node);\n\n case 'repeat':\n return convertRepeat(node);\n\n case 'foreach':\n return convertForEach(node);\n\n case 'while':\n return convertWhile(node);\n\n // Expression nodes — wrap as `get` command with patient role\n default:\n return createCommandNode('get', { patient: convertValue(node) });\n }\n}\n\n// =============================================================================\n// Node Converters\n// =============================================================================\n\nfunction convertEvent(node: INode): SemanticNode {\n const event = String(node.event ?? 'click');\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n\n const roles: Record<SemanticRole, SemanticValue> = {\n event: createLiteral(event),\n };\n\n // Preserve event target if present\n if (node.target && typeof node.target === 'object') {\n roles.source = convertValue(node.target as INode);\n }\n\n // Bridge event modifiers\n const modifiers = node.modifiers as Record<string, unknown> | undefined;\n let eventModifiers: SemanticEventModifiers | undefined;\n\n if (modifiers) {\n eventModifiers = bridgeEventModifiers(modifiers);\n\n // InterchangeNode-only modifiers → encode as roles\n if (modifiers.prevent) roles.prevent = createLiteral(true);\n if (modifiers.stop) roles.stop = createLiteral(true);\n if (modifiers.passive) roles.passive = createLiteral(true);\n if (modifiers.capture) roles.capture = createLiteral(true);\n }\n\n return createEventHandlerNode('on', roles, body, undefined, eventModifiers);\n}\n\nfunction convertCommand(node: INode): SemanticNode {\n const name = String(node.name ?? 'unknown');\n const args = Array.isArray(node.args) ? (node.args as INode[]) : [];\n const target =\n node.target && typeof node.target === 'object' ? (node.target as INode) : undefined;\n const existingRoles = node.roles as Record<string, INode> | undefined;\n const modifiers = node.modifiers as Record<string, unknown> | undefined;\n\n let roles: Record<SemanticRole, SemanticValue>;\n\n if (existingRoles && typeof existingRoles === 'object' && Object.keys(existingRoles).length > 0) {\n // Semantic parser path: roles already present\n roles = {};\n for (const [role, value] of Object.entries(existingRoles)) {\n if (value && typeof value === 'object' && 'type' in value) {\n roles[role] = convertValue(value as INode);\n }\n }\n } else {\n // Core parser path: infer roles from command name\n roles = inferRoles(name, args, modifiers, target);\n }\n\n return createCommandNode(name, roles);\n}\n\nfunction convertIf(node: INode): SemanticNode {\n const condition =\n node.condition && typeof node.condition === 'object'\n ? convertValue(node.condition as INode)\n : createExpression('true');\n\n const thenBody = Array.isArray(node.thenBranch) ? (node.thenBranch as INode[]) : [];\n const thenBranch = thenBody.map(fromInterchangeNode);\n\n // Handle else branch — may include chained else-if\n let elseBranch: SemanticNode[] | undefined;\n\n const elseIfBranches = node.elseIfBranches as\n ReadonlyArray<{ condition: INode; body: INode[] }> | undefined;\n\n if (elseIfBranches && elseIfBranches.length > 0) {\n // Chain else-if branches as nested conditionals\n elseBranch = [chainElseIfs(elseIfBranches, node.elseBranch as INode[] | undefined)];\n } else if (Array.isArray(node.elseBranch) && (node.elseBranch as INode[]).length > 0) {\n elseBranch = (node.elseBranch as INode[]).map(fromInterchangeNode);\n }\n\n const roles: Record<SemanticRole, SemanticValue> = { condition };\n return createConditionalNode('if', roles, thenBranch, elseBranch);\n}\n\nfunction chainElseIfs(\n branches: ReadonlyArray<{ condition: INode; body: INode[] }>,\n finalElse: INode[] | undefined\n): SemanticNode {\n const [first, ...rest] = branches;\n const condition = convertValue(first.condition as INode);\n const thenBranch = first.body.map(fromInterchangeNode);\n\n let elseBranch: SemanticNode[] | undefined;\n if (rest.length > 0) {\n elseBranch = [chainElseIfs(rest, finalElse)];\n } else if (finalElse && finalElse.length > 0) {\n elseBranch = finalElse.map(fromInterchangeNode);\n }\n\n return createConditionalNode('if', { condition }, thenBranch, elseBranch);\n}\n\nfunction convertRepeat(node: INode): SemanticNode {\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n let variant: LoopVariant;\n\n if (node.count !== undefined && node.count !== null) {\n variant = 'times';\n if (typeof node.count === 'number') {\n roles.quantity = createLiteral(node.count, 'number');\n } else if (typeof node.count === 'object') {\n roles.quantity = convertValue(node.count as INode);\n }\n } else if (node.whileCondition && typeof node.whileCondition === 'object') {\n variant = 'while';\n roles.condition = convertValue(node.whileCondition as INode);\n } else if (typeof node.untilEvent === 'string') {\n variant = 'until';\n roles.condition = createLiteral(node.untilEvent);\n } else {\n variant = 'forever';\n }\n\n return createLoopNode('repeat', roles, variant, body);\n}\n\nfunction convertForEach(node: INode): SemanticNode {\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n if (node.collection && typeof node.collection === 'object') {\n roles.source = convertValue(node.collection as INode);\n }\n\n const itemName = typeof node.itemName === 'string' ? node.itemName : undefined;\n const indexName = typeof node.indexName === 'string' ? node.indexName : undefined;\n\n return createLoopNode('repeat', roles, 'for', body, itemName, indexName);\n}\n\nfunction convertWhile(node: INode): SemanticNode {\n const bodyNodes = Array.isArray(node.body) ? (node.body as INode[]) : [];\n const body = bodyNodes.map(fromInterchangeNode);\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n if (node.condition && typeof node.condition === 'object') {\n roles.condition = convertValue(node.condition as INode);\n }\n\n return createLoopNode('repeat', roles, 'while', body);\n}\n\n// =============================================================================\n// Value Conversion\n// =============================================================================\n\n/**\n * Convert an InterchangeNode to a SemanticValue.\n *\n * Simple nodes map directly to typed SemanticValue variants.\n * Complex expression nodes are collapsed to ExpressionValue { raw: string }.\n */\nexport function convertValue(node: INode): SemanticValue {\n switch (node.type) {\n case 'literal':\n return convertLiteral(node);\n\n case 'selector':\n return createSelector(String(node.value ?? ''), inferSelectorKind(String(node.value ?? '')));\n\n case 'identifier':\n return convertIdentifier(node);\n\n case 'variable':\n return convertVariable(node);\n\n case 'possessive':\n return createPropertyPath(\n node.object && typeof node.object === 'object'\n ? convertValue(node.object as INode)\n : createReference('me'),\n String(node.property ?? '')\n );\n\n // Complex expressions → collapse to raw string\n case 'binary':\n case 'unary':\n case 'member':\n case 'call':\n case 'positional':\n return createExpression(renderExpr(node));\n\n default:\n // Unknown type — render as expression\n if ('value' in node) return createLiteral(String(node.value ?? ''));\n return createExpression(renderExpr(node));\n }\n}\n\nfunction convertLiteral(node: INode): SemanticValue {\n const value = node.value;\n if (value === null || value === undefined) return createLiteral('null');\n\n const dataType =\n typeof value === 'number'\n ? ('number' as const)\n : typeof value === 'boolean'\n ? ('boolean' as const)\n : undefined;\n\n return createLiteral(value as string | number | boolean, dataType);\n}\n\nfunction convertIdentifier(node: INode): SemanticValue {\n const value = String(node.value ?? '');\n if (DEFAULT_REFERENCES.has(value)) {\n return createReference(value);\n }\n return createLiteral(value);\n}\n\nfunction convertVariable(node: INode): SemanticValue {\n const name = String(node.name ?? '');\n const scope = String(node.scope ?? 'local');\n\n switch (scope) {\n case 'element':\n return createExpression(`:${name}`);\n case 'global':\n return createExpression(`$${name}`);\n default:\n return createExpression(name);\n }\n}\n\n// =============================================================================\n// Expression Renderer\n// =============================================================================\n\n/**\n * Recursively render an InterchangeNode expression tree to a string.\n * Used to collapse complex expressions into ExpressionValue.raw.\n */\nexport function renderExpr(node: INode): string {\n if (!node || typeof node !== 'object') return '';\n\n switch (node.type) {\n case 'literal': {\n const v = node.value;\n if (v === null || v === undefined) return 'null';\n if (typeof v === 'string') return /\\s/.test(v) ? `\"${v}\"` : v;\n return String(v);\n }\n\n case 'identifier':\n return String(node.value ?? '');\n\n case 'selector':\n return String(node.value ?? '');\n\n case 'variable': {\n const name = String(node.name ?? '');\n const scope = String(node.scope ?? 'local');\n if (scope === 'element') return `:${name}`;\n if (scope === 'global') return `$${name}`;\n return name;\n }\n\n case 'binary': {\n const left = node.left && typeof node.left === 'object' ? renderExpr(node.left as INode) : '';\n const right =\n node.right && typeof node.right === 'object' ? renderExpr(node.right as INode) : '';\n return `${left} ${node.operator ?? ''} ${right}`;\n }\n\n case 'unary': {\n const operand =\n node.operand && typeof node.operand === 'object' ? renderExpr(node.operand as INode) : '';\n return `${node.operator ?? ''} ${operand}`;\n }\n\n case 'member': {\n const obj =\n node.object && typeof node.object === 'object' ? renderExpr(node.object as INode) : '';\n if (node.computed && node.property && typeof node.property === 'object') {\n return `${obj}[${renderExpr(node.property as INode)}]`;\n }\n const prop =\n typeof node.property === 'string'\n ? node.property\n : node.property && typeof node.property === 'object'\n ? renderExpr(node.property as INode)\n : '';\n return `${obj}.${prop}`;\n }\n\n case 'possessive': {\n const obj =\n node.object && typeof node.object === 'object' ? renderExpr(node.object as INode) : '';\n return `${obj}'s ${node.property ?? ''}`;\n }\n\n case 'call': {\n const callee =\n node.callee && typeof node.callee === 'object' ? renderExpr(node.callee as INode) : '';\n const args = Array.isArray(node.args)\n ? (node.args as INode[]).map(a => renderExpr(a)).join(', ')\n : '';\n return `${callee}(${args})`;\n }\n\n case 'positional': {\n const target =\n node.target && typeof node.target === 'object' ? renderExpr(node.target as INode) : '';\n return target ? `${node.position ?? ''} ${target}` : String(node.position ?? '');\n }\n\n default:\n if ('value' in node) return String(node.value ?? '');\n return '';\n }\n}\n\n// =============================================================================\n// Role Inference\n// =============================================================================\n\n/**\n * Marker-keyword sets — mirror the runtime command parsers' skip lists so the\n * inferred roles point at the real value, not the literal marker word.\n */\nconst SCROLL_MARKERS: ReadonlySet<string> = new Set([\n 'to',\n 'of',\n 'the',\n 'top',\n 'bottom',\n 'middle',\n 'center',\n 'nearest',\n 'left',\n 'right',\n 'smoothly',\n 'instantly',\n]);\nconst URL_MARKERS: ReadonlySet<string> = new Set(['url']);\nconst PARTIALS_IN_MARKERS: ReadonlySet<string> = new Set(['partials', 'in']);\n\n/**\n * Return the first arg that isn't a marker identifier from the given set.\n * Identifier args carry the marker word in `name` (or `value` as a fallback).\n */\nfunction firstNonMarkerArg(args: INode[], markers: ReadonlySet<string>): INode | undefined {\n for (const a of args) {\n if (a.type === 'identifier') {\n const ident = a as { name?: unknown; value?: unknown };\n const word = typeof ident.name === 'string' ? ident.name : ident.value;\n if (typeof word === 'string' && markers.has(word)) continue;\n }\n return a;\n }\n return undefined;\n}\n\n/**\n * Infer semantic roles from command name, positional args, modifiers, and target.\n * Mirrors the heuristics in core's from-core.ts inferRoles() function.\n */\nfunction inferRoles(\n name: string,\n args: INode[],\n modifiers: Record<string, unknown> | undefined,\n target: INode | undefined\n): Record<SemanticRole, SemanticValue> {\n const roles: Record<SemanticRole, SemanticValue> = {};\n\n switch (name) {\n case 'set': {\n if (args[0]) roles.destination = convertValue(args[0]);\n const toVal = modifiers?.to;\n if (toVal && typeof toVal === 'object' && 'type' in (toVal as object)) {\n roles.patient = convertValue(toVal as INode);\n } else if (args[1]) {\n roles.patient = convertValue(args[1]);\n }\n break;\n }\n\n case 'put': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (modifiers) {\n for (const key of ['into', 'before', 'after'] as const) {\n const val = modifiers[key];\n if (val && typeof val === 'object' && 'type' in (val as object)) {\n roles.destination = convertValue(val as INode);\n roles.method = createLiteral(key);\n break;\n }\n }\n }\n if (!roles.destination && target) {\n roles.destination = convertValue(target);\n }\n break;\n }\n\n case 'increment':\n case 'decrement': {\n if (args[0]) roles.destination = convertValue(args[0]);\n const byVal = modifiers?.by;\n if (byVal && typeof byVal === 'object' && 'type' in (byVal as object)) {\n roles.quantity = convertValue(byVal as INode);\n } else if (args[1]) {\n roles.quantity = convertValue(args[1]);\n }\n break;\n }\n\n case 'fetch': {\n if (args[0]) roles.source = convertValue(args[0]);\n const asVal = modifiers?.as;\n if (asVal && typeof asVal === 'object' && 'type' in (asVal as object)) {\n roles.responseType = convertValue(asVal as INode);\n } else if (typeof asVal === 'string') {\n roles.responseType = createLiteral(asVal);\n }\n break;\n }\n\n case 'wait':\n case 'settle': {\n if (args[0]) roles.duration = convertValue(args[0]);\n break;\n }\n\n case 'toggle':\n case 'add':\n case 'show':\n case 'hide': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.destination = convertValue(target);\n break;\n }\n\n case 'remove': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.source = convertValue(target);\n break;\n }\n\n case 'send':\n case 'trigger': {\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.destination = convertValue(target);\n break;\n }\n\n case 'log': {\n if (args[0]) roles.patient = convertValue(args[0]);\n break;\n }\n\n // scroll [to] [position] target [smoothly|instantly] → destination=target\n case 'scroll': {\n const t = firstNonMarkerArg(args, SCROLL_MARKERS);\n if (t) roles.destination = convertValue(t);\n break;\n }\n\n // push|replace url <X> → patient=X\n case 'push':\n case 'replace': {\n const t = firstNonMarkerArg(args, URL_MARKERS);\n if (t) roles.patient = convertValue(t);\n break;\n }\n\n // process partials in <X> → patient=X\n case 'process': {\n const t = firstNonMarkerArg(args, PARTIALS_IN_MARKERS);\n if (t) roles.patient = convertValue(t);\n break;\n }\n\n default: {\n // Generic fallback: first arg as patient, target as destination\n if (args[0]) roles.patient = convertValue(args[0]);\n if (target) roles.destination = convertValue(target);\n break;\n }\n }\n\n return roles;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Infer selectorKind from a CSS selector string.\n */\nfunction inferSelectorKind(\n value: string\n): 'id' | 'class' | 'attribute' | 'element' | 'complex' | undefined {\n if (!value) return undefined;\n if (value.startsWith('#')) return 'id';\n if (value.startsWith('.')) return 'class';\n if (value.startsWith('[')) return 'attribute';\n if (value.startsWith('<') || value.startsWith('*')) return 'element';\n // Check for combinators indicating complex selectors\n if (/[>\\+~ ]/.test(value) && value.length > 1) return 'complex';\n return undefined;\n}\n\n/**\n * Infer a SemanticValue from a string (for event modifier `from` bridging).\n */\nfunction inferValueFromString(value: string): SemanticValue {\n if (DEFAULT_REFERENCES.has(value)) return createReference(value);\n const kind = inferSelectorKind(value);\n if (kind) return createSelector(value, kind);\n return createLiteral(value);\n}\n\n/**\n * Bridge InterchangeNode EventModifiers to SemanticNode EventModifiers.\n */\nfunction bridgeEventModifiers(mods: Record<string, unknown>): SemanticEventModifiers | undefined {\n const once = mods.once === true ? true : undefined;\n const debounce = typeof mods.debounce === 'number' ? mods.debounce : undefined;\n const throttle = typeof mods.throttle === 'number' ? mods.throttle : undefined;\n const from = typeof mods.from === 'string' ? inferValueFromString(mods.from) : undefined;\n\n if (\n once === undefined &&\n debounce === undefined &&\n throttle === undefined &&\n from === undefined\n ) {\n return undefined;\n }\n\n return {\n ...(once !== undefined ? { once } : {}),\n ...(debounce !== undefined ? { debounce } : {}),\n ...(throttle !== undefined ? { throttle } : {}),\n ...(from !== undefined ? { from } : {}),\n };\n}\n","/**\n * SemanticNode → Runtime AST Converter\n *\n * Converts framework SemanticNode (LSE IR) to a structural AST format\n * that the core runtime can execute directly. Uses structural typing\n * to avoid a dependency on the core package.\n *\n * This is the canonical converter — AOT compiler delegates to it.\n *\n * The output matches the core runtime's expected node shapes:\n * - `{ type: 'command', name, args, roles }` → processCommand()\n * - `{ type: 'event', event, modifiers, body }` → adapted to executeEventHandler()\n */\n\nimport type {\n SemanticNode,\n SemanticValue,\n EventHandlerSemanticNode,\n ConditionalSemanticNode,\n LoopSemanticNode,\n} from '../core/types';\n\n// =============================================================================\n// Structural output types (no core package dependency)\n// =============================================================================\n\n/** Minimal AST node that the core runtime can execute. */\nexport interface RuntimeASTNode {\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\n/** Command node shape expected by runtime's processCommand(). */\nexport interface RuntimeCommandNode extends RuntimeASTNode {\n readonly type: 'command';\n readonly name: string;\n readonly args: RuntimeASTNode[];\n readonly roles?: Readonly<Record<string, RuntimeASTNode>>;\n readonly modifiers?: Record<string, unknown>;\n}\n\n/** Event node shape expected by runtime's event adapter. */\nexport interface RuntimeEventNode extends RuntimeASTNode {\n readonly type: 'event';\n readonly event: string;\n readonly modifiers: Record<string, unknown>;\n readonly body: RuntimeASTNode[];\n}\n\n// =============================================================================\n// Converter\n// =============================================================================\n\n/**\n * Convert a SemanticNode to a RuntimeASTNode that the core runtime can execute.\n *\n * @example\n * ```typescript\n * import { parseExplicit } from '@lokascript/framework/ir';\n * import { semanticNodeToRuntimeAST } from '@lokascript/framework/ir';\n *\n * const node = parseExplicit('[toggle patient:.active]');\n * const ast = semanticNodeToRuntimeAST(node);\n * // { type: 'command', name: 'toggle', args: [{ type: 'selector', value: '.active' }], roles: { patient: ... } }\n * ```\n */\nexport function semanticNodeToRuntimeAST(node: SemanticNode): RuntimeASTNode {\n switch (node.kind) {\n case 'event-handler':\n return convertEventHandler(node as EventHandlerSemanticNode);\n\n case 'conditional':\n return convertConditional(node as ConditionalSemanticNode);\n\n case 'loop':\n return convertLoop(node as LoopSemanticNode);\n\n case 'compound': {\n const compound = node as SemanticNode & { statements?: SemanticNode[]; chainType?: string };\n const commands = (compound.statements ?? []).map(semanticNodeToRuntimeAST);\n return {\n type: 'CommandSequence',\n commands,\n };\n }\n\n case 'command':\n default:\n return convertCommand(node);\n }\n}\n\nfunction convertEventHandler(eh: EventHandlerSemanticNode): RuntimeEventNode {\n const eventValue = eh.roles.get('event');\n const eventName = eventValue && 'value' in eventValue ? String(eventValue.value) : 'click';\n\n const modifiers: Record<string, unknown> = {};\n if (eh.eventModifiers) {\n if (eh.eventModifiers.once) modifiers.once = true;\n if (eh.eventModifiers.debounce) modifiers.debounce = eh.eventModifiers.debounce;\n if (eh.eventModifiers.throttle) modifiers.throttle = eh.eventModifiers.throttle;\n if (eh.eventModifiers.queue) modifiers.queue = eh.eventModifiers.queue;\n }\n\n return {\n type: 'event',\n event: eventName,\n modifiers,\n body: (eh.body ?? []).map(semanticNodeToRuntimeAST),\n };\n}\n\nfunction convertCommand(node: SemanticNode): RuntimeCommandNode {\n const roles: Record<string, RuntimeASTNode> = {};\n const args: RuntimeASTNode[] = [];\n\n for (const [roleName, value] of node.roles) {\n const astValue = semanticValueToAST(value);\n roles[roleName] = astValue;\n args.push(astValue);\n }\n\n return {\n type: 'command',\n name: node.action,\n args,\n roles,\n };\n}\n\nfunction convertConditional(node: ConditionalSemanticNode): RuntimeASTNode {\n const conditionValue = node.roles.get('condition');\n return {\n type: 'command',\n name: 'if',\n args: conditionValue ? [semanticValueToAST(conditionValue)] : [],\n condition: conditionValue ? semanticValueToAST(conditionValue) : undefined,\n thenBranch: (node.thenBranch ?? []).map(semanticNodeToRuntimeAST),\n elseBranch: (node.elseBranch ?? []).map(semanticNodeToRuntimeAST),\n };\n}\n\nfunction convertLoop(node: LoopSemanticNode): RuntimeASTNode {\n const countValue = node.roles.get('patient') || node.roles.get('count');\n return {\n type: 'command',\n name: 'repeat',\n args: countValue ? [semanticValueToAST(countValue)] : [],\n loopVariant: node.loopVariant ?? 'forever',\n body: (node.body ?? []).map(semanticNodeToRuntimeAST),\n loopVariable: node.loopVariable,\n indexVariable: node.indexVariable,\n };\n}\n\n/**\n * Convert a SemanticValue to a RuntimeASTNode.\n */\nexport function semanticValueToAST(value: SemanticValue): RuntimeASTNode {\n switch (value.type) {\n case 'selector':\n return { type: 'selector', value: value.value as string };\n\n case 'reference':\n return { type: 'identifier', value: value.value as string };\n\n case 'literal': {\n const lit = value as { value: unknown; dataType?: string };\n if (lit.dataType === 'duration') {\n const str = String(lit.value);\n const match = /^(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(str);\n if (match) {\n const ms = match[2] === 's' ? parseFloat(match[1]) * 1000 : parseFloat(match[1]);\n return { type: 'literal', value: ms };\n }\n }\n return { type: 'literal', value: lit.value as string | number | boolean | null };\n }\n\n case 'property-path': {\n const pp = value as import('../core/types').PropertyPathValue;\n const objectAST = semanticValueToAST(pp.object);\n return {\n type: 'member',\n object: objectAST,\n property: pp.property,\n };\n }\n\n case 'expression': {\n const expr = value as { raw: string };\n return { type: 'expression', value: expr.raw };\n }\n\n case 'flag': {\n const flag = value as { name: string; enabled: boolean };\n return { type: 'literal', value: flag.enabled };\n }\n\n default:\n return { type: 'literal', value: String((value as { value?: unknown }).value ?? '') };\n }\n}\n","/**\n * Main API for creating multilingual DSLs\n */\n\nimport type { SemanticNode, LanguageTokenizer, LanguagePattern } from '../core/types';\nimport type { CommandSchema } from '../schema';\nimport { PatternMatcher, type PatternMatcherProfile } from '../core/pattern-matching';\nimport { generatePattern, type PatternGenLanguageProfile } from '../generation/pattern-generator';\nimport { createDomainRenderer, type DomainRenderFn } from '../generation/renderer';\nimport { GrammarTransformer, type LanguageProfile as GrammarProfile } from '../grammar';\nimport {\n type Dictionary,\n type ProfileProvider,\n type ValueExtractor,\n InMemoryDictionary,\n InMemoryProfileProvider,\n} from '../interfaces';\nimport { isExplicitSyntax, parseExplicit } from '../ir';\nimport type { SchemaLookup } from '../ir';\n\n/**\n * Language configuration for a DSL.\n */\nexport interface LanguageConfig {\n /** ISO 639-1 language code */\n readonly code: string;\n /** English name of the language */\n readonly name: string;\n /** Native name of the language */\n readonly nativeName: string;\n /** Language tokenizer */\n readonly tokenizer: LanguageTokenizer;\n /** Language profile for pattern generation */\n readonly patternProfile: PatternGenLanguageProfile;\n /**\n * Language profile for grammar transformation.\n *\n * Optional everywhere: `translate()` primarily works parse→render through\n * the schema-driven renderer, which needs no grammar profile. Configure this\n * only to enable the whole-string GrammarTransformer FALLBACK for input the\n * pattern matcher cannot parse (or actions render() cannot cover).\n */\n readonly grammarProfile?: GrammarProfile;\n}\n\n/**\n * Code generator function that transforms semantic AST to target code.\n */\nexport interface CodeGenerator {\n generate(node: SemanticNode): string;\n}\n\n/**\n * Per-language vocabulary for a command added via {@link DomainExtension}.\n *\n * This is the same shape a language profile uses, narrowed to the parts a\n * single new command needs.\n */\nexport interface ExtensionVocabulary {\n /** The command's verb in this language. */\n readonly keyword: PatternGenLanguageProfile['keywords'][string];\n /**\n * Markers for roles this language does not already cover in its profile.\n * Usually unnecessary: role markers are shared across a domain's commands.\n */\n readonly roleMarkers?: PatternGenLanguageProfile['roleMarkers'];\n}\n\n/**\n * A command added to a DSL from outside the package that defines it.\n *\n * Supplying a schema plus one vocabulary entry per language is enough to parse,\n * render and translate the command in every one of them — word order, role\n * markers and keyword placement all follow from the schema and the language\n * profiles. `render` and `generate` are only needed when the command's surface\n * form or output cannot be derived.\n *\n * @example\n * ```typescript\n * const research: DomainExtension = {\n * schema: defineCommand({\n * action: 'research',\n * roles: [\n * defineRole({ role: 'patient', required: true, expectedTypes: ['expression'] }),\n * defineRole({\n * role: 'source', required: true, expectedTypes: ['expression'],\n * markerOverride: { en: 'from', ja: 'から', ar: 'من' },\n * }),\n * ],\n * }),\n * vocabulary: {\n * en: { keyword: { primary: 'research' } },\n * ja: { keyword: { primary: '調査' } },\n * ar: { keyword: { primary: 'ابحث' } },\n * },\n * };\n *\n * const llm = createLLMDSL({ extensions: [research] });\n * llm.parse('research \"climate\" from #wiki', 'en');\n * llm.render(node, 'ja'); // → '\"climate\" #wiki から 調査'\n * ```\n */\nexport interface DomainExtension {\n /** Schema for the new command. Its action must not collide with an existing one. */\n readonly schema: CommandSchema;\n\n /**\n * Vocabulary per language code. Codes must be configured on the DSL; an\n * unknown code is a configuration error, not a silent no-op.\n *\n * A subset is allowed — a command can be added in six of a DSL's eleven\n * languages. The languages left out simply do not parse it, so vocabulary\n * can be filled in over time rather than all at once.\n */\n readonly vocabulary: Readonly<Record<string, ExtensionVocabulary>>;\n\n /** Custom rendering for this action; takes precedence over the schema-driven path. */\n readonly render?: DomainRenderFn;\n\n /** Custom code generation for this action; takes precedence over the DSL's generator. */\n readonly generate?: (node: SemanticNode) => string;\n}\n\n/**\n * DSL configuration with dependency injection support.\n */\nexport interface DSLConfig {\n /** DSL name (for debugging/documentation) */\n readonly name?: string;\n\n /** Command schemas defining the DSL grammar */\n readonly schemas: readonly CommandSchema[];\n\n /** Language configurations */\n readonly languages: readonly LanguageConfig[];\n\n // === Dependency Injection (Optional) ===\n\n /** Dictionary for keyword translation (default: built from language configs) */\n readonly dictionary?: Dictionary;\n\n /** Profile provider for grammar transformation (default: built from language configs) */\n readonly profileProvider?: ProfileProvider;\n\n /** Value extractors for tokenization (default: generic extractors) */\n readonly valueExtractors?: ValueExtractor[];\n\n /** Code generator for compilation (default: none) */\n readonly codeGenerator?: CodeGenerator;\n\n /**\n * The domain's natural-language renderer, consulted by {@link MultilingualDSL.render}.\n * Actions it returns `null` for fall through to the schema-driven renderer.\n */\n readonly renderer?: DomainRenderFn;\n\n /**\n * Commands added from outside this package. Their schemas and vocabulary are\n * merged into the DSL before pattern generation, so they parse, render and\n * compile like built-in commands.\n */\n readonly extensions?: readonly DomainExtension[];\n\n // === Options ===\n\n /** Auto-generate patterns from schemas (default: true) */\n readonly generatePatterns?: boolean;\n\n /** Custom patterns to supplement generated ones */\n readonly customPatterns?: LanguagePattern[];\n}\n\n/**\n * Validation result.\n */\nexport interface ValidationResult {\n readonly valid: boolean;\n readonly node?: SemanticNode;\n readonly errors?: string[];\n}\n\n/**\n * Compilation result.\n */\nexport interface CompileResult {\n readonly ok: boolean;\n readonly code?: string;\n readonly errors?: string[];\n readonly node?: SemanticNode;\n readonly metadata?: {\n readonly parser: string;\n readonly confidence: number;\n };\n}\n\n/**\n * Main multilingual DSL interface.\n */\nexport interface MultilingualDSL {\n // Parsing\n parse(input: string, language: string): SemanticNode;\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number };\n\n // Validation\n validate(input: string, language: string): ValidationResult;\n\n // Compilation\n compile(input: string, language: string): CompileResult;\n\n // Translation\n translate(input: string, fromLanguage: string, toLanguage: string): string;\n\n /**\n * Render a parsed node back to natural language.\n *\n * Returns `null` when the action cannot be rendered — no custom renderer, no\n * domain renderer, and no schema. Optional so that third-party implementers\n * of this interface are not broken by its addition; `createMultilingualDSL`\n * always provides it.\n */\n render?(node: SemanticNode, language: string): string | null;\n\n // Language support\n getSupportedLanguages(): string[];\n}\n\n/**\n * Internal registry for DSL configuration.\n */\nclass DSLRegistry {\n private patterns = new Map<string, LanguagePattern[]>();\n private tokenizers = new Map<string, LanguageTokenizer>();\n private schemas: readonly CommandSchema[];\n private partiallyTranslatedActions: ReadonlySet<string>;\n\n /**\n * @param partiallyTranslatedActions Actions permitted to lack a keyword in\n * some configured languages — extension commands, which may be added for a\n * subset of the DSL's languages. A built-in command missing a keyword stays\n * an error, since that is a domain-authoring mistake.\n */\n constructor(config: DSLConfig, partiallyTranslatedActions: ReadonlySet<string> = new Set()) {\n this.schemas = config.schemas;\n this.partiallyTranslatedActions = partiallyTranslatedActions;\n\n // Register each language\n for (const lang of config.languages) {\n this.registerLanguage(lang);\n }\n }\n\n private registerLanguage(lang: LanguageConfig): void {\n // Register tokenizer\n this.tokenizers.set(lang.code, lang.tokenizer);\n\n // Generate patterns for this language\n const patterns: LanguagePattern[] = [];\n for (const schema of this.schemas) {\n if (\n this.partiallyTranslatedActions.has(schema.action) &&\n !lang.patternProfile.keywords[schema.action]\n ) {\n continue; // this extension command was not translated into this language\n }\n const pattern = generatePattern(schema, lang.patternProfile);\n patterns.push(pattern);\n }\n\n this.patterns.set(lang.code, patterns);\n }\n\n getPatterns(language: string): LanguagePattern[] {\n return this.patterns.get(language) || [];\n }\n\n getTokenizer(language: string): LanguageTokenizer | undefined {\n return this.tokenizers.get(language);\n }\n\n getSupportedLanguages(): string[] {\n return Array.from(this.patterns.keys());\n }\n}\n\n/**\n * Implementation of MultilingualDSL.\n */\nclass MultilingualDSLImpl implements MultilingualDSL {\n private registry: DSLRegistry;\n private matcher: PatternMatcher;\n private transformer: GrammarTransformer;\n private profileProvider: ProfileProvider;\n private codeGenerator?: CodeGenerator;\n private schemaLookup: SchemaLookup;\n private domainRenderer?: DomainRenderFn;\n private extensionRenderers: Map<string, DomainRenderFn>;\n private schemaFallbackRenderer: DomainRenderFn;\n\n constructor(\n config: DSLConfig,\n registry: DSLRegistry,\n transformer: GrammarTransformer,\n profileProvider: ProfileProvider\n ) {\n this.registry = registry;\n this.matcher = new PatternMatcher();\n this.transformer = transformer;\n this.profileProvider = profileProvider;\n if (config.codeGenerator) {\n this.codeGenerator = config.codeGenerator;\n }\n if (config.renderer) {\n this.domainRenderer = config.renderer;\n }\n\n this.extensionRenderers = new Map();\n for (const extension of config.extensions ?? []) {\n if (extension.render) this.extensionRenderers.set(extension.schema.action, extension.render);\n }\n\n // Last resort for render(): covers extension commands with no custom\n // renderer, and any built-in action the domain renderer declines. Lazy, so\n // a DSL that never renders pays nothing.\n this.schemaFallbackRenderer = createDomainRenderer({\n schemas: config.schemas,\n profiles: config.languages.map(l => l.patternProfile),\n });\n\n // Build SchemaLookup from config schemas for explicit syntax validation\n const schemaMap = new Map(config.schemas.map(s => [s.action, s]));\n this.schemaLookup = {\n getSchema: (action: string) => schemaMap.get(action),\n };\n }\n\n parse(input: string, language: string): SemanticNode {\n const result = this.parseWithConfidence(input, language);\n return result.node;\n }\n\n parseWithConfidence(input: string, language: string): { node: SemanticNode; confidence: number } {\n // Try explicit bracket syntax first (language-agnostic)\n if (isExplicitSyntax(input)) {\n const node = parseExplicit(input, { schemaLookup: this.schemaLookup });\n // Only match if this DSL has a schema for the action\n if (!this.schemaLookup.getSchema(node.action)) {\n throw new Error(`No schema for action \"${node.action}\" in this DSL`);\n }\n return { node, confidence: 1.0 };\n }\n\n // Get tokenizer for language\n const tokenizer = this.registry.getTokenizer(language);\n if (!tokenizer) {\n throw new Error(`No tokenizer registered for language: ${language}`);\n }\n\n // Tokenize input\n const tokens = tokenizer.tokenize(input);\n\n // Get patterns for language\n const patterns = this.registry.getPatterns(language);\n\n // Create profile for matcher\n const profile: PatternMatcherProfile = {\n code: language,\n };\n\n // Try to match each pattern\n for (const pattern of patterns) {\n const match = this.matcher.matchPattern(tokens, pattern, profile);\n if (match) {\n // Build semantic node\n const node: SemanticNode = {\n kind: 'command',\n action: pattern.command,\n roles: match.captured,\n metadata: {\n sourceLanguage: language,\n sourceText: input,\n patternId: pattern.id,\n confidence: match.confidence,\n },\n };\n\n return { node, confidence: match.confidence };\n }\n }\n\n throw new Error(`No pattern matched for input: ${input}`);\n }\n\n validate(input: string, language: string): ValidationResult {\n try {\n const result = this.parseWithConfidence(input, language);\n return {\n valid: true,\n node: result.node,\n };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n translate(input: string, fromLanguage: string, toLanguage: string): string {\n // Explicit syntax is language-agnostic — return unchanged\n if (isExplicitSyntax(input)) return input;\n\n // Primary route: parse in the source language, render in the target — the\n // same parse→render path DomainRegistry.translate uses. The schema-driven\n // renderer covers every configured language, so this needs NO grammar\n // profiles (before 2026-08 translate() required them and therefore threw\n // for every domain in the family — none configures one).\n let node: SemanticNode;\n try {\n node = this.parseWithConfidence(input, fromLanguage).node;\n } catch (parseError) {\n // Whole-string grammar transformation can sometimes translate input the\n // pattern matcher cannot parse — but only when profiles are configured.\n if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n throw parseError;\n }\n\n // Only consult render() for a CONFIGURED target language — the schema\n // renderer's lookup tables fall back to raw action/marker names for\n // unknown languages, which would silently return wrong-language output.\n const rendered = this.registry.getSupportedLanguages().includes(toLanguage)\n ? this.render(node, toLanguage)\n : null;\n if (rendered != null) return rendered;\n\n // render() covered nothing for this action/language pair; fall back to the\n // grammar transformer when profiles exist, otherwise name both remedies.\n if (this.hasGrammarProfile(fromLanguage) && this.hasGrammarProfile(toLanguage)) {\n return this.transformer.transform(input, fromLanguage, toLanguage);\n }\n throw new Error(\n `translate() could not render action \"${node.action}\" in language \"${toLanguage}\": no ` +\n `custom renderer, domain renderer, or schema pattern covers it, and no grammar ` +\n `profile is configured for the transformer fallback. Either add \"${toLanguage}\" to ` +\n `the DSL's languages/renderer, or set 'grammarProfile' on its LanguageConfig in ` +\n `createMultilingualDSL() (parse/validate/compile do not need it).`\n );\n }\n\n private hasGrammarProfile(language: string): boolean {\n return this.profileProvider.getProfile(language) != null;\n }\n\n compile(input: string, language: string): CompileResult {\n if (!this.codeGenerator) {\n return {\n ok: false,\n errors: ['No code generator configured for this DSL'],\n };\n }\n\n try {\n const result = this.parseWithConfidence(input, language);\n const code = this.codeGenerator.generate(result.node);\n\n return {\n ok: true,\n code,\n node: result.node,\n metadata: {\n parser: 'semantic',\n confidence: result.confidence,\n },\n };\n } catch (error) {\n return {\n ok: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n }\n\n render(node: SemanticNode, language: string): string | null {\n // 1. An extension's own renderer, if it supplied one\n const extensionRenderer = this.extensionRenderers.get(node.action);\n if (extensionRenderer) {\n const rendered = extensionRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 2. The domain's renderer — its hand-written cases are authoritative\n if (this.domainRenderer) {\n const rendered = this.domainRenderer(node, language);\n if (rendered != null) return rendered;\n }\n\n // 3. Schema-driven, which is how extension commands render by default\n return this.schemaFallbackRenderer(node, language);\n }\n\n getSupportedLanguages(): string[] {\n return this.registry.getSupportedLanguages();\n }\n}\n\n/**\n * Create a new multilingual DSL instance.\n *\n * @param config - DSL configuration\n * @returns MultilingualDSL instance\n *\n * @example\n * ```typescript\n * const myDSL = createMultilingualDSL({\n * schemas: [\n * defineCommand('select', [\n * defineRole('field', 'identifier', true),\n * defineRole('source', 'identifier', true),\n * ]),\n * ],\n * languages: [\n * {\n * code: 'en',\n * name: 'English',\n * nativeName: 'English',\n * tokenizer: englishTokenizer,\n * patternProfile: englishProfile,\n * },\n * ],\n * codeGenerator: {\n * generate: (node) => generateSQL(node),\n * },\n * });\n *\n * const result = myDSL.compile('select name from users', 'en');\n * ```\n */\n/**\n * Create default dictionary from language configurations.\n */\nfunction createDefaultDictionary(config: DSLConfig): Dictionary {\n const translations: Record<string, Record<string, string>> = {};\n\n for (const lang of config.languages) {\n // Convert keyword objects to simple string mappings\n const keywords: Record<string, string> = {};\n for (const [canonical, keywordDef] of Object.entries(lang.patternProfile.keywords)) {\n keywords[canonical] = keywordDef.primary;\n }\n translations[lang.code] = keywords;\n }\n\n return new InMemoryDictionary(translations);\n}\n\n/**\n * Create default profile provider from language configurations.\n */\nfunction createDefaultProfileProvider(config: DSLConfig): ProfileProvider {\n const profiles: Record<string, GrammarProfile> = {};\n\n for (const lang of config.languages) {\n if (lang.grammarProfile) {\n profiles[lang.code] = lang.grammarProfile;\n }\n }\n\n return new InMemoryProfileProvider(profiles);\n}\n\n/**\n * Fold extensions into the config so that everything downstream — pattern\n * generation, the dictionary, explicit-syntax lookup, rendering — sees\n * extension commands exactly as it sees built-in ones.\n *\n * Done up front rather than by mutating a live DSL: `DSLRegistry` generates\n * every language's patterns in its constructor, so a command registered later\n * would compile and render but silently fail to parse.\n */\nfunction applyExtensions(config: DSLConfig): DSLConfig {\n const extensions = config.extensions;\n if (!extensions || extensions.length === 0) return config;\n\n const configuredLanguages = new Set(config.languages.map(l => l.code));\n const actions = new Set(config.schemas.map(s => s.action));\n\n for (const extension of extensions) {\n const { action } = extension.schema;\n if (actions.has(action)) {\n throw new Error(\n `Extension command \"${action}\" collides with a command this DSL already defines. ` +\n `Pick a different action name.`\n );\n }\n actions.add(action);\n\n for (const code of Object.keys(extension.vocabulary)) {\n if (!configuredLanguages.has(code)) {\n throw new Error(\n `Extension command \"${action}\" supplies vocabulary for language \"${code}\", which is ` +\n `not configured on this DSL. Configured languages: ` +\n `${[...configuredLanguages].join(', ')}.`\n );\n }\n }\n }\n\n const schemas = [...config.schemas, ...extensions.map(e => e.schema)];\n\n const languages = config.languages.map(lang => {\n const keywords = { ...lang.patternProfile.keywords };\n let roleMarkers = lang.patternProfile.roleMarkers;\n\n for (const extension of extensions) {\n const vocabulary = extension.vocabulary[lang.code];\n if (!vocabulary) continue;\n keywords[extension.schema.action] = { ...vocabulary.keyword };\n if (vocabulary.roleMarkers) {\n roleMarkers = { ...roleMarkers, ...vocabulary.roleMarkers };\n }\n }\n\n return {\n ...lang,\n patternProfile: {\n ...lang.patternProfile,\n keywords,\n ...(roleMarkers !== undefined && { roleMarkers }),\n },\n };\n });\n\n // Extension code generators dispatch ahead of the domain's own generator,\n // whose `default` branch would otherwise throw on an action it never knew.\n const extensionGenerators = new Map(\n extensions.filter(e => e.generate).map(e => [e.schema.action, e.generate!])\n );\n const baseGenerator = config.codeGenerator;\n const codeGenerator: CodeGenerator | undefined =\n extensionGenerators.size > 0\n ? {\n generate(node: SemanticNode): string {\n const generate = extensionGenerators.get(node.action);\n if (generate) return generate(node);\n if (!baseGenerator) {\n throw new Error(`No code generator for action \"${node.action}\"`);\n }\n return baseGenerator.generate(node);\n },\n }\n : baseGenerator;\n\n return {\n ...config,\n schemas,\n languages,\n ...(codeGenerator !== undefined && { codeGenerator }),\n };\n}\n\nexport function createMultilingualDSL(config: DSLConfig): MultilingualDSL {\n // Extensions must be folded in before anything reads the config\n const effectiveConfig = applyExtensions(config);\n const extensionActions = new Set((config.extensions ?? []).map(e => e.schema.action));\n\n // Create or use provided dictionary\n const dictionary = effectiveConfig.dictionary ?? createDefaultDictionary(effectiveConfig);\n\n // Create or use provided profile provider\n const profileProvider =\n effectiveConfig.profileProvider ?? createDefaultProfileProvider(effectiveConfig);\n\n // Create grammar transformer with injected dependencies\n const transformer = new GrammarTransformer({\n dictionary,\n profileProvider,\n });\n\n // Create registry and implementation\n const registry = new DSLRegistry(effectiveConfig, extensionActions);\n return new MultilingualDSLImpl(effectiveConfig, registry, transformer, profileProvider);\n}\n","/**\n * LLM Prompt Generator\n *\n * Auto-generates LLM system prompts from CommandSchema[]. Given a set of\n * domain schemas, produces a structured markdown prompt that teaches LLMs\n * to output valid LSE bracket syntax and/or LLM-simplified JSON.\n *\n * The generated prompt includes:\n * - Protocol overview (LSE syntax summary)\n * - Value type reference\n * - Per-command documentation with role descriptions\n * - Synthetic examples in both formats\n * - Output format specification\n * - Error recovery instructions\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type {\n PromptGeneratorConfig,\n GeneratedPrompt,\n PromptSection,\n PromptMetadata,\n} from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Generate an LLM system prompt from domain command schemas.\n *\n * @example\n * ```typescript\n * import { generatePrompt } from '@lokascript/framework';\n * import { allSchemas } from '@lokascript/domains/flow';\n *\n * const prompt = generatePrompt({\n * domain: 'flow',\n * description: 'Reactive data flow pipelines',\n * schemas: allSchemas,\n * });\n *\n * console.log(prompt.text); // Full markdown system prompt\n * ```\n */\nexport function generatePrompt(config: PromptGeneratorConfig): GeneratedPrompt {\n const outputFormat = config.outputFormat ?? 'both';\n const examplesPerCommand = config.examplesPerCommand ?? 2;\n\n const sections: PromptSection[] = [\n buildProtocolSection(),\n buildValueTypeSection(),\n buildCommandsSection(config.schemas, outputFormat, examplesPerCommand),\n buildOutputFormatSection(outputFormat),\n buildErrorRecoverySection(),\n ];\n\n // Apply token budget if specified\n let finalSections = sections;\n if (config.maxTokens && config.maxTokens > 0) {\n finalSections = truncateToTokenBudget(sections, config.maxTokens);\n }\n\n const text = finalSections.map(s => `## ${s.title}\\n\\n${s.content}`).join('\\n\\n---\\n\\n');\n\n const totalRoles = config.schemas.reduce((sum, s) => sum + s.roles.length, 0);\n const approximateTokens = estimateTokens(text);\n\n const metadata: PromptMetadata = {\n domain: config.domain,\n commandCount: config.schemas.length,\n roleCount: totalRoles,\n approximateTokens,\n };\n\n return { text, sections: finalSections, metadata };\n}\n\n/**\n * Generate synthetic LSE examples from a single command schema.\n * Used by both the prompt generator and training data synthesizer.\n */\nexport function generateExamples(\n schema: CommandSchema,\n count: number = 2\n): Array<{ explicit: string; json: SemanticJSON }> {\n const combos = generateRoleCombinations(schema);\n const examples: Array<{ explicit: string; json: SemanticJSON }> = [];\n\n for (let i = 0; i < Math.min(count, combos.length); i++) {\n const combo = combos[i];\n const roles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of combo) {\n const sample = sampleValue(role);\n roles.set(role.role, sample);\n }\n\n // Build SemanticNode for rendering to bracket syntax\n const nodeRoles = new Map<\n string,\n {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n }\n >();\n for (const [roleName, sample] of roles) {\n nodeRoles.set(roleName, toSemanticValue(sample));\n }\n\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [roleName, sample] of roles) {\n jsonRoles[roleName] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n examples.push({ explicit, json });\n }\n\n return examples;\n}\n\n/**\n * Generate a condensed LSE protocol reference (for MCP resources).\n */\nexport function generateProtocolReference(): string {\n const protocol = buildProtocolSection();\n const valueTypes = buildValueTypeSection();\n return `# LokaScript Explicit Syntax (LSE) Quick Reference\\n\\n${protocol.content}\\n\\n${valueTypes.content}`;\n}\n\n// =============================================================================\n// Section Builders\n// =============================================================================\n\nfunction buildProtocolSection(): PromptSection {\n const content = `LokaScript Explicit Syntax (LSE) is a bracket-based format for imperative commands.\n\n### Syntax\n\n\\`\\`\\`\n[command role1:value1 role2:value2 +flag1 ~flag2]\n\\`\\`\\`\n\n- **Command**: The first token inside brackets (lowercased)\n- **Role pair**: \\`name:value\\` — a named semantic role with a typed value (no space around colon)\n- **Enabled flag**: \\`+name\\` — boolean attribute present\n- **Disabled flag**: \\`~name\\` — boolean attribute negated\n- **Nested body**: \\`body:[command ...]\\` — a bracket command inside a role value\n\n### Rules\n\n1. Commands are always lowercased\n2. Role names preserve their original case\n3. No spaces around the colon in role:value pairs\n4. Strings with spaces must be quoted: \\`patient:\"hello world\"\\`\n5. Selectors start with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`\n6. A selector containing a space, a combinator (\\`>\\` \\`+\\` \\`~\\`), or a comma must use a selector literal: \\`patient:<ul > li/>\\`, \\`patient:<.a, .b/>\\`\n7. Inside a structural role (\\`body\\`, \\`then\\`, \\`else\\`, \\`condition\\`, \\`loop-body\\`, \\`variable\\`, \\`catch\\`, \\`finally\\`) a \\`[...]\\` value is always a nested command. Write an attribute selector there as \\`condition:<[data-active]/>\\`\n8. Output must be valid bracket syntax: \\`[action role:value ...]\\``;\n\n return {\n id: 'protocol',\n title: 'LSE Protocol',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildValueTypeSection(): PromptSection {\n const content = `Values in LSE are classified by their syntactic form (first match wins):\n\n| Type | Syntax | Example |\n|------|--------|---------|\n| Selector literal | Delimited by \\`<\\` and \\`/>\\` | \\`<ul > li/>\\`, \\`<.a, .b/>\\`, \\`<[data-id]/>\\` |\n| Selector | Starts with \\`#\\` \\`.\\` \\`[\\` \\`@\\` \\`*\\` | \\`#button\\`, \\`.active\\`, \\`[data-id]\\` |\n| String | Quoted with \\`\"\\` or \\`'\\` | \\`\"hello world\"\\`, \\`'json'\\` |\n| Boolean | Exact: \\`true\\` / \\`false\\` | \\`visible:true\\` |\n| Reference | Built-in name | \\`me\\`, \\`you\\`, \\`it\\`, \\`result\\`, \\`event\\`, \\`target\\`, \\`body\\` |\n| Duration | Number + suffix | \\`500ms\\`, \\`2s\\`, \\`1m\\`, \\`1h\\` |\n| Number | Digits with optional decimal | \\`5\\`, \\`3.14\\`, \\`-1\\` |\n| Plain | Fallback (any non-whitespace) | \\`/api/users\\`, \\`json\\`, \\`production\\` |\n\n**Important**: Classification is by prefix, not by intent. \\`#true\\` is a selector (not boolean). \\`event\\` as a value is a reference (not plain text).`;\n\n return {\n id: 'value-types',\n title: 'Value Types',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildCommandsSection(\n schemas: readonly CommandSchema[],\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): PromptSection {\n const parts: string[] = [];\n\n for (const schema of schemas) {\n parts.push(formatCommandDoc(schema, outputFormat, examplesPerCommand));\n }\n\n const content = parts.join('\\n\\n');\n\n return {\n id: 'commands',\n title: 'Available Commands',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildOutputFormatSection(outputFormat: 'explicit' | 'json' | 'both'): PromptSection {\n let content: string;\n\n if (outputFormat === 'explicit') {\n content = `Output valid LSE bracket syntax. Each command must be wrapped in brackets:\n\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\nDo NOT output JSON. Only use bracket syntax.`;\n } else if (outputFormat === 'json') {\n content = `Output valid JSON in the LLM-simplified format:\n\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nValid value types: \\`selector\\`, \\`literal\\`, \\`reference\\`, \\`expression\\`.\nDo NOT output bracket syntax. Only use JSON.`;\n } else {\n content = `You may output EITHER format:\n\n**Bracket syntax** (preferred for single commands):\n\\`\\`\\`\n[command role:value ...]\n\\`\\`\\`\n\n**JSON format** (preferred when structured data is needed):\n\\`\\`\\`json\n{\n \"action\": \"command-name\",\n \"roles\": {\n \"roleName\": { \"type\": \"valueType\", \"value\": \"theValue\" }\n }\n}\n\\`\\`\\`\n\nBoth formats are equally valid. Use whichever is more natural for the context.`;\n }\n\n return {\n id: 'output-format',\n title: 'Output Format',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\nfunction buildErrorRecoverySection(): PromptSection {\n const content = `If you're unsure about a command or role:\n\n1. **Unknown command**: Use the closest matching command from the Available Commands section. Do not invent commands.\n2. **Unknown role**: Use only the roles listed for each command. Do not add roles not in the schema.\n3. **Ambiguous value type**: When in doubt, use \\`expression\\` type (it's the most permissive).\n4. **Missing required role**: Always include all required roles. Check the Required/Optional labels.\n5. **Selector vs plain value**: If a value starts with \\`#\\`, \\`.\\`, \\`[\\`, \\`@\\`, or \\`*\\`, it's a selector. URLs like \\`/api/data\\` are plain values.\n\nWhen generating LSE, prefer explicit role labeling over positional guessing. Every value should have a role name.`;\n\n return {\n id: 'error-recovery',\n title: 'Error Recovery',\n content,\n approximateTokens: estimateTokens(content),\n };\n}\n\n// =============================================================================\n// Command Documentation\n// =============================================================================\n\nfunction formatCommandDoc(\n schema: CommandSchema,\n outputFormat: 'explicit' | 'json' | 'both',\n examplesPerCommand: number\n): string {\n const lines: string[] = [];\n\n // Header\n lines.push(`### \\`${schema.action}\\` — ${schema.description}`);\n lines.push('');\n\n // Roles\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n if (required.length > 0) {\n lines.push('**Required roles:**');\n for (const role of required) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n if (optional.length > 0) {\n lines.push('**Optional roles:**');\n for (const role of optional) {\n lines.push(`- \\`${role.role}\\`: ${role.description} (type: ${formatExpectedTypes(role)})`);\n }\n }\n\n // Examples\n const examples = generateExamples(schema, examplesPerCommand);\n if (examples.length > 0) {\n lines.push('');\n if (outputFormat === 'explicit' || outputFormat === 'both') {\n lines.push('**Bracket syntax:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`\\n${ex.explicit}\\n\\`\\`\\``);\n }\n }\n if (outputFormat === 'json' || outputFormat === 'both') {\n lines.push('**JSON format:**');\n for (const ex of examples) {\n lines.push(`\\`\\`\\`json\\n${JSON.stringify(ex.json, null, 2)}\\n\\`\\`\\``);\n }\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatExpectedTypes(role: RoleSpec): string {\n return role.expectedTypes.join(' | ');\n}\n\n// =============================================================================\n// Example Generation Helpers\n// =============================================================================\n\n/**\n * Generate role combinations for example synthesis.\n * Returns arrays of RoleSpec[] representing different valid input combinations:\n * 1. Required roles only\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (if different from #1 and #2)\n */\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if there are 2+ optional roles)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if schema has no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n/**\n * Sample a value for a role based on its expected types and name.\n */\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n // Use role name as a heuristic for realistic values\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\n/**\n * Convert a sampled value into a SemanticValue for renderExplicit().\n */\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n\n// =============================================================================\n// Token Budget\n// =============================================================================\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction truncateToTokenBudget(sections: PromptSection[], maxTokens: number): PromptSection[] {\n const result: PromptSection[] = [];\n let budget = maxTokens;\n\n for (const section of sections) {\n if (section.approximateTokens <= budget) {\n result.push(section);\n budget -= section.approximateTokens;\n } else {\n // Truncate the section to fit remaining budget (always include at least something)\n const charBudget = Math.max(budget * 4, 40);\n const truncatedContent = section.content.slice(0, charBudget) + '\\n\\n*(truncated)*';\n result.push({\n ...section,\n content: truncatedContent,\n approximateTokens: estimateTokens(truncatedContent),\n });\n break;\n }\n }\n\n return result;\n}\n","/**\n * Schema Synthesizer\n *\n * Generates synthetic (natural_language, LSE) training pairs from\n * CommandSchema[]. Enumerates valid role combinations and produces\n * examples in both bracket syntax and JSON wire format.\n */\n\nimport type { CommandSchema, RoleSpec } from '../schema/command-schema';\nimport type { SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { TrainingPair, SynthesisConfig, SynthesisResult, SynthesisMetadata } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Synthesize training pairs from command schemas.\n *\n * Generates multiple examples per command by enumerating role combinations:\n * 1. Required roles only (minimum viable)\n * 2. Required + each optional role individually\n * 3. Required + all optional roles (maximum)\n * 4. Shuffled role order variants (teaches role-label independence)\n */\nexport function synthesizeFromSchemas(\n schemas: readonly CommandSchema[],\n config: SynthesisConfig\n): SynthesisResult {\n const maxPerCommand = config.maxPairsPerCommand ?? 5;\n const minQuality = config.minQuality ?? 0.5;\n const shuffleRoles = config.shuffleRoles ?? true;\n const languages = config.languages ?? ['en'];\n\n const pairs: TrainingPair[] = [];\n let idCounter = 0;\n\n for (const schema of schemas) {\n const combos = generateRoleCombinations(schema);\n\n for (const language of languages) {\n let commandPairCount = 0;\n\n for (const combo of combos) {\n if (commandPairCount >= maxPerCommand) break;\n\n const pair = buildTrainingPair(\n schema,\n combo,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n\n if (pair.quality >= minQuality) {\n pairs.push(pair);\n commandPairCount++;\n }\n\n // Generate shuffled variant\n if (shuffleRoles && combo.length >= 2 && commandPairCount < maxPerCommand) {\n const shuffled = [...combo].reverse();\n const shuffledPair = buildTrainingPair(\n schema,\n shuffled,\n language,\n config.domain,\n `${config.domain}-synth-${idCounter++}`\n );\n if (shuffledPair.quality >= minQuality) {\n pairs.push(shuffledPair);\n commandPairCount++;\n }\n }\n }\n }\n }\n\n const metadata: SynthesisMetadata = {\n domain: config.domain,\n commandCount: schemas.length,\n pairCount: pairs.length,\n bySource: { synthetic: pairs.length },\n languages,\n };\n\n return { pairs, metadata };\n}\n\n// =============================================================================\n// Role Combination Generation\n// =============================================================================\n\nfunction generateRoleCombinations(schema: CommandSchema): RoleSpec[][] {\n const required = schema.roles.filter(r => r.required);\n const optional = schema.roles.filter(r => !r.required);\n\n const combos: RoleSpec[][] = [];\n\n // 1. Required only\n if (required.length > 0) {\n combos.push(required);\n }\n\n // 2. Required + each optional individually\n for (const opt of optional) {\n combos.push([...required, opt]);\n }\n\n // 3. Required + all optional (if 2+ optional)\n if (optional.length >= 2) {\n combos.push([...required, ...optional]);\n }\n\n // Fallback: if no required roles, use all roles\n if (combos.length === 0) {\n combos.push(schema.roles.slice());\n }\n\n return combos;\n}\n\n// =============================================================================\n// Pair Building\n// =============================================================================\n\nfunction buildTrainingPair(\n schema: CommandSchema,\n roles: RoleSpec[],\n language: string,\n domain: string,\n id: string\n): TrainingPair {\n const sampledRoles = new Map<string, { type: string; value: string | number | boolean }>();\n\n for (const role of roles) {\n sampledRoles.set(role.role, sampleValue(role));\n }\n\n // Build SemanticNode for bracket syntax\n const nodeRoles = new Map<string, unknown>();\n for (const [name, sample] of sampledRoles) {\n nodeRoles.set(name, toSemanticValue(sample));\n }\n const node = createCommandNode(schema.action, nodeRoles as never);\n const explicit = renderExplicit(node);\n\n // Build JSON format\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n for (const [name, sample] of sampledRoles) {\n jsonRoles[name] = sample as SemanticJSONValue;\n }\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n // Build natural language form\n const natural = buildNaturalForm(schema, sampledRoles, language);\n\n // Quality: synthetic pairs get a base quality, higher if more roles are filled\n const requiredCount = schema.roles.filter(r => r.required).length;\n const filledRequired = roles.filter(r => r.required).length;\n const quality = requiredCount > 0 ? filledRequired / requiredCount : 0.8;\n\n return {\n id,\n natural,\n language,\n explicit,\n json,\n domain,\n action: schema.action,\n source: 'synthetic',\n quality,\n };\n}\n\n/**\n * Build a natural language form from sampled roles.\n * Uses marker overrides for the given language when available.\n */\nfunction buildNaturalForm(\n schema: CommandSchema,\n roles: Map<string, { type: string; value: string | number | boolean }>,\n language: string\n): string {\n const parts: string[] = [schema.action];\n\n for (const roleSpec of schema.roles) {\n const sample = roles.get(roleSpec.role);\n if (!sample) continue;\n\n const marker = roleSpec.markerOverride?.[language];\n if (marker) {\n parts.push(marker);\n }\n parts.push(String(sample.value));\n }\n\n return parts.join(' ');\n}\n\n// =============================================================================\n// Value Sampling\n// =============================================================================\n\nfunction sampleValue(role: RoleSpec): { type: string; value: string | number | boolean } {\n const primaryType = role.expectedTypes[0] || 'expression';\n\n switch (primaryType) {\n case 'selector':\n return sampleSelector(role.role);\n case 'literal':\n return sampleLiteral(role.role);\n case 'reference':\n return { type: 'reference', value: 'me' };\n case 'expression':\n return sampleExpression(role.role);\n case 'flag':\n return { type: 'flag', value: true };\n default:\n return { type: 'literal', value: 'example' };\n }\n}\n\nfunction sampleSelector(roleName: string): { type: string; value: string } {\n const selectors: Record<string, string> = {\n patient: '.active',\n destination: '#output',\n source: '#input',\n target: '#target',\n };\n return { type: 'selector', value: selectors[roleName] || `#${roleName}` };\n}\n\nfunction sampleLiteral(roleName: string): { type: string; value: string | number } {\n const literals: Record<string, string | number> = {\n duration: '30s',\n interval: '5s',\n delay: '500ms',\n timeout: '10s',\n quantity: 5,\n limit: 10,\n style: 'json',\n manner: 'rolling',\n format: 'html',\n };\n return { type: 'literal', value: literals[roleName] || roleName };\n}\n\nfunction sampleExpression(roleName: string): { type: string; value: string } {\n const expressions: Record<string, string> = {\n source: '/api/data',\n destination: '#output',\n patient: '.active',\n instrument: 'toUpperCase',\n condition: 'age > 18',\n style: 'json',\n duration: '5s',\n url: '/api/users',\n };\n return { type: 'expression', value: expressions[roleName] || `/api/${roleName}` };\n}\n\nfunction toSemanticValue(sample: { type: string; value: string | number | boolean }): {\n type: string;\n value: string | number | boolean;\n raw?: string;\n dataType?: string;\n selectorKind?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return {\n type: 'selector',\n value: String(sample.value),\n selectorKind: detectSelectorKind(String(sample.value)),\n };\n case 'literal':\n return {\n type: 'literal',\n value: sample.value,\n dataType:\n typeof sample.value === 'number'\n ? 'number'\n : typeof sample.value === 'boolean'\n ? 'boolean'\n : 'string',\n };\n case 'reference':\n return { type: 'reference', value: String(sample.value) };\n case 'expression':\n return { type: 'expression', value: String(sample.value), raw: String(sample.value) };\n case 'flag':\n return { type: 'flag', value: sample.value };\n default:\n return { type: 'literal', value: String(sample.value), dataType: 'string' };\n }\n}\n\nfunction detectSelectorKind(selector: string): string {\n if (selector.startsWith('#')) return 'id';\n if (selector.startsWith('.')) return 'class';\n if (selector.startsWith('[')) return 'attribute';\n return 'complex';\n}\n","/**\n * Feedback Formatter\n *\n * Maps diagnostics to machine-actionable LSEFeedback with hints,\n * corrected examples, and schema context. Enables LLMs to self-correct\n * based on structured error information.\n */\n\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup, SemanticJSON, SemanticJSONValue } from '../ir/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport { createCommandNode } from '../core/types';\nimport type { LSEFeedback, FeedbackDiagnostic, FixType } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Build structured feedback from diagnostics and optional schema context.\n *\n * @param input - The original input text\n * @param inputFormat - Format of the input\n * @param diagnostics - Error diagnostics from validation/parsing\n * @param schemaLookup - Optional schema lookup for generating hints and corrections\n * @param action - The attempted command action (if identifiable)\n */\nexport function buildFeedback(\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): LSEFeedback {\n const hasErrors = diagnostics.some(d => d.severity === 'error');\n const feedbackDiagnostics = diagnostics.map(d => toFeedbackDiagnostic(d));\n const hints = generateHints(feedbackDiagnostics, schemaLookup, action);\n\n let schemaInfo: LSEFeedback['schema'] | undefined;\n let correctedExample: LSEFeedback['correctedExample'] | undefined;\n\n if (action && schemaLookup) {\n const schema = schemaLookup.getSchema(action);\n if (schema) {\n schemaInfo = extractSchemaInfo(schema);\n if (hasErrors) {\n correctedExample = generateCorrectedExample(schema);\n }\n }\n }\n\n return {\n accepted: !hasErrors,\n input: { format: inputFormat, text: input },\n diagnostics: feedbackDiagnostics,\n hints,\n ...(schemaInfo && { schema: schemaInfo }),\n ...(correctedExample && { correctedExample }),\n };\n}\n\n// =============================================================================\n// Diagnostic Classification\n// =============================================================================\n\n/**\n * Map a framework Diagnostic to a FeedbackDiagnostic with fix type.\n */\nfunction toFeedbackDiagnostic(d: Diagnostic): FeedbackDiagnostic {\n const fixType = classifyFixType(d);\n return {\n severity: d.severity,\n code: d.code || 'unknown',\n message: d.message,\n ...(d.suggestions?.[0] && { suggestion: d.suggestions[0] }),\n ...(fixType && { fixType }),\n };\n}\n\n/**\n * Classify a diagnostic into a machine-actionable fix type.\n */\nfunction classifyFixType(d: Diagnostic): FixType | undefined {\n const code = (d.code || '').toLowerCase();\n const msg = d.message.toLowerCase();\n\n // Missing required role\n if (\n code.includes('missing-role') ||\n code.includes('missing_role') ||\n msg.includes('required role') ||\n msg.includes('missing role')\n ) {\n return 'missing_role';\n }\n\n // Invalid value type\n if (\n code.includes('invalid-type') ||\n code.includes('invalid_type') ||\n code.includes('type-mismatch') ||\n msg.includes('invalid type') ||\n msg.includes('expected type')\n ) {\n return 'invalid_type';\n }\n\n // Unknown command\n if (\n code.includes('unknown-command') ||\n code.includes('unknown_command') ||\n msg.includes('unknown command') ||\n (msg.includes('not recognized') && msg.includes('command'))\n ) {\n return 'unknown_command';\n }\n\n // Unknown role\n if (\n code.includes('unknown-role') ||\n code.includes('unknown_role') ||\n msg.includes('unknown role') ||\n (msg.includes('not recognized') && msg.includes('role'))\n ) {\n return 'unknown_role';\n }\n\n // Syntax error (catch-all for parse errors)\n if (\n code.includes('parse') ||\n code.includes('syntax') ||\n msg.includes('syntax error') ||\n msg.includes('parse error') ||\n msg.includes('unexpected')\n ) {\n return 'syntax_error';\n }\n\n return undefined;\n}\n\n// =============================================================================\n// Hint Generation\n// =============================================================================\n\nfunction generateHints(\n diagnostics: readonly FeedbackDiagnostic[],\n schemaLookup?: SchemaLookup,\n action?: string\n): string[] {\n const hints: string[] = [];\n const schema = action && schemaLookup ? schemaLookup.getSchema(action) : undefined;\n\n for (const d of diagnostics) {\n if (d.severity !== 'error') continue;\n\n switch (d.fixType) {\n case 'missing_role': {\n if (schema) {\n const required = schema.roles\n .filter(r => r.required)\n .map(r => `'${r.role}' (${r.description}, type: ${r.expectedTypes.join('|')})`)\n .join(', ');\n hints.push(`Required roles for '${action}': ${required}`);\n } else {\n hints.push('Check that all required roles are present.');\n }\n break;\n }\n\n case 'unknown_command': {\n hints.push(\n `Command not recognized. Ensure you're using a valid command from the domain schema.`\n );\n break;\n }\n\n case 'unknown_role': {\n if (schema) {\n const validRoles = schema.roles.map(r => `'${r.role}'`).join(', ');\n hints.push(`Valid roles for '${action}': ${validRoles}`);\n } else {\n hints.push('Use only roles defined in the command schema.');\n }\n break;\n }\n\n case 'invalid_type': {\n hints.push(\n 'Check value types: selectors start with #.[@*, strings use quotes, numbers are plain digits.'\n );\n break;\n }\n\n case 'syntax_error': {\n hints.push('Ensure bracket syntax: [command role:value ...]. No spaces around the colon.');\n break;\n }\n\n default: {\n if (d.suggestion) {\n hints.push(d.suggestion);\n }\n }\n }\n }\n\n // Deduplicate\n return [...new Set(hints)];\n}\n\n// =============================================================================\n// Schema Info Extraction\n// =============================================================================\n\nfunction extractSchemaInfo(schema: CommandSchema): LSEFeedback['schema'] {\n const requiredRoles: string[] = [];\n const optionalRoles: string[] = [];\n const roleDescriptions: Record<string, string> = {};\n\n for (const role of schema.roles) {\n if (role.required) {\n requiredRoles.push(role.role);\n } else {\n optionalRoles.push(role.role);\n }\n roleDescriptions[role.role] = role.description;\n }\n\n return {\n action: schema.action,\n requiredRoles,\n optionalRoles,\n roleDescriptions,\n };\n}\n\n// =============================================================================\n// Corrected Example Generation\n// =============================================================================\n\nfunction generateCorrectedExample(schema: CommandSchema): { explicit: string; json: SemanticJSON } {\n const roles = new Map<string, unknown>();\n const jsonRoles: Record<string, SemanticJSONValue> = {};\n\n for (const role of schema.roles) {\n if (!role.required) continue;\n const sample = sampleDefaultValue(role.role, role.expectedTypes[0] || 'expression');\n roles.set(role.role, toSemanticValue(sample));\n jsonRoles[role.role] = sample as SemanticJSONValue;\n }\n\n const node = createCommandNode(schema.action, roles as never);\n const explicit = renderExplicit(node);\n const json: SemanticJSON = { action: schema.action, roles: jsonRoles };\n\n return { explicit, json };\n}\n\nfunction sampleDefaultValue(\n roleName: string,\n expectedType: string\n): { type: string; value: string } {\n switch (expectedType) {\n case 'selector':\n return { type: 'selector', value: `#${roleName}` };\n case 'expression':\n return { type: 'expression', value: `<${roleName}-value>` };\n case 'literal':\n return { type: 'literal', value: `<${roleName}-value>` };\n case 'reference':\n return { type: 'reference', value: 'me' };\n default:\n return { type: 'expression', value: `<${roleName}-value>` };\n }\n}\n\nfunction toSemanticValue(sample: { type: string; value: string }): {\n type: string;\n value: string;\n raw?: string;\n selectorKind?: string;\n dataType?: string;\n} {\n switch (sample.type) {\n case 'selector':\n return { type: 'selector', value: sample.value, selectorKind: 'id' };\n case 'expression':\n return { type: 'expression', value: sample.value, raw: sample.value };\n case 'literal':\n return { type: 'literal', value: sample.value, dataType: 'string' };\n case 'reference':\n return { type: 'reference', value: sample.value };\n default:\n return { type: 'literal', value: sample.value, dataType: 'string' };\n }\n}\n","/**\n * Domain Registry\n *\n * Provides auto-discovery and registration of framework domains for MCP servers.\n * Instead of hardcoding tool definitions and dispatch logic per domain, domains\n * export a `DomainDescriptor` and the registry generates everything automatically.\n *\n * @example\n * ```typescript\n * import { DomainRegistry } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n *\n * // Register domains (each provides a descriptor)\n * registry.register({\n * name: 'sql',\n * description: 'Natural language SQL',\n * languages: ['en', 'es', 'ja', 'ar'],\n * inputLabel: 'query',\n * inputDescription: 'SQL query in natural language',\n * getDSL: () => import('@lokascript/domains/sql').then(m => m.createSQLDSL()),\n * getRenderer: () => import('@lokascript/domains/sql').then(m => m.renderSQL),\n * });\n *\n * // Auto-generate MCP tool definitions\n * const tools = registry.getToolDefinitions();\n *\n * // Dispatch a tool call\n * const result = await registry.handleToolCall('parse_sql', { query: 'select name from users' });\n * ```\n */\n\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport type { NaturalLanguageRenderer, DomainRenderFn } from '../generation/renderer';\nimport type { CommandSchema } from '../schema/command-schema';\nimport type { SchemaLookup } from '../ir/types';\nimport type { Diagnostic } from '../generation/diagnostics';\nimport type { GeneratedPrompt, PromptGeneratorConfig } from '../prompts/types';\nimport type { SynthesisConfig, SynthesisResult } from '../training/types';\nimport type { LSEFeedback } from '../feedback/types';\nimport { generatePrompt as _generatePrompt } from '../prompts/prompt-generator';\nimport { synthesizeFromSchemas as _synthesizeFromSchemas } from '../training/schema-synthesizer';\nimport { buildFeedback as _buildFeedback } from '../feedback/feedback-formatter';\nimport { parseExplicit as _parseExplicit } from '../ir/explicit-parser';\n\n// =============================================================================\n// Descriptor Interface\n// =============================================================================\n\n/**\n * Describes a domain for auto-registration in MCP servers.\n *\n * Domains provide this descriptor to the registry, which generates\n * tool definitions and handles dispatch automatically.\n */\nexport interface DomainDescriptor {\n /** Short identifier (used in tool names: parse_{name}, compile_{name}, etc.) */\n readonly name: string;\n\n /** Human-readable description */\n readonly description: string;\n\n /** Supported language codes */\n readonly languages: readonly string[];\n\n /** Label for the primary input parameter (e.g., 'query', 'scenario', 'code') */\n readonly inputLabel: string;\n\n /** Description of the primary input parameter */\n readonly inputDescription: string;\n\n /** What compile_{name} produces (e.g., \"a SQL query string\"). Used in tool description. */\n readonly outputDescription?: string;\n\n /**\n * Factory to lazily create the DSL instance.\n * Called once on first tool use. The result is cached.\n */\n readonly getDSL: () => MultilingualDSL | Promise<MultilingualDSL>;\n\n /**\n * Factory to lazily create the renderer.\n * Required for translate_{name} tool. Called once on first use.\n *\n * The function form may return `null` for an action it cannot render; the\n * translate tool reports that as an unsuccessful translation.\n */\n readonly getRenderer?: () =>\n NaturalLanguageRenderer | DomainRenderFn | Promise<NaturalLanguageRenderer | DomainRenderFn>;\n\n /**\n * Which standard tools to generate. Default: all four.\n */\n readonly tools?: readonly ('parse' | 'compile' | 'validate' | 'translate')[];\n\n /**\n * Optional command schemas for this domain.\n * When provided, enables system prompt generation, training data synthesis,\n * and structured feedback via the registry's convenience methods.\n */\n readonly schemas?: readonly CommandSchema[];\n\n /**\n * Optional scan configuration for AOT compilation and Vite plugin.\n * Declares which HTML attributes/script types this domain uses.\n */\n readonly scanConfig?: {\n /** Attribute names to scan for (e.g., ['data-sql', '_sql']) */\n readonly attributes: readonly string[];\n /** Script tag types to scan for (e.g., ['text/sql-dsl']) */\n readonly scriptTypes?: readonly string[];\n /** Default language when not specified on element */\n readonly defaultLanguage?: string;\n /** Keywords for detection, keyed by language code */\n readonly keywords?: Readonly<Record<string, readonly string[]>>;\n };\n}\n\n// =============================================================================\n// MCP Tool Types (minimal — compatible with @modelcontextprotocol/server)\n// =============================================================================\n\n/**\n * MCP tool definition. Compatible with the MCP SDK's tool schema.\n */\nexport interface MCPToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: {\n readonly type: 'object';\n readonly properties: Record<string, unknown>;\n readonly required: readonly string[];\n };\n}\n\n/**\n * MCP tool response. Compatible with the MCP SDK's response format.\n */\nexport interface MCPToolResponse {\n readonly content: ReadonlyArray<{ readonly type: string; readonly text: string }>;\n readonly isError?: boolean;\n}\n\n// =============================================================================\n// Domain Registry\n// =============================================================================\n\n/**\n * Registry for framework domains.\n *\n * Manages domain descriptors, generates MCP tool definitions,\n * and dispatches tool calls to the appropriate domain.\n */\nexport class DomainRegistry {\n private descriptors = new Map<string, DomainDescriptor>();\n private dslCache = new Map<string, MultilingualDSL>();\n private rendererCache = new Map<string, NaturalLanguageRenderer | DomainRenderFn>();\n\n /**\n * Register a domain.\n * @throws if a domain with the same name is already registered\n */\n register(descriptor: DomainDescriptor): void {\n if (this.descriptors.has(descriptor.name)) {\n throw new Error(`Domain already registered: ${descriptor.name}`);\n }\n this.descriptors.set(descriptor.name, descriptor);\n }\n\n /**\n * Attach schemas to an already-registered domain.\n * Useful for lazy loading schemas after initial registration.\n */\n setSchemas(name: string, schemas: readonly CommandSchema[]): void {\n const existing = this.descriptors.get(name);\n if (!existing) {\n throw new Error(`Domain not registered: ${name}`);\n }\n // Create a new descriptor with schemas attached\n this.descriptors.set(name, { ...existing, schemas });\n }\n\n /**\n * Get all registered domain names.\n */\n getDomainNames(): string[] {\n return Array.from(this.descriptors.keys());\n }\n\n /**\n * Get a specific domain descriptor.\n */\n getDescriptor(name: string): DomainDescriptor | undefined {\n return this.descriptors.get(name);\n }\n\n /**\n * Generate MCP tool definitions for all registered domains.\n */\n getToolDefinitions(): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n for (const desc of this.descriptors.values()) {\n tools.push(...generateToolDefinitions(desc));\n }\n return tools;\n }\n\n /**\n * Check if a tool name belongs to a registered domain.\n */\n canHandle(toolName: string): boolean {\n const parsed = parseToolName(toolName);\n if (!parsed) return false;\n return this.descriptors.has(parsed.domain);\n }\n\n /**\n * Handle a tool call by dispatching to the appropriate domain.\n * Returns null if the tool name doesn't match any registered domain.\n */\n async handleToolCall(\n toolName: string,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse | null> {\n const parsed = parseToolName(toolName);\n if (!parsed) return null;\n\n const descriptor = this.descriptors.get(parsed.domain);\n if (!descriptor) return null;\n\n try {\n const dsl = await this.getDSL(descriptor);\n\n switch (parsed.operation) {\n case 'parse':\n return await this.handleParse(descriptor, dsl, args);\n case 'compile':\n return await this.handleCompile(descriptor, dsl, args);\n case 'validate':\n return await this.handleValidate(descriptor, dsl, args);\n case 'translate':\n return await this.handleTranslate(descriptor, dsl, args);\n default:\n return jsonResponse({ error: `Unknown operation: ${parsed.operation}` }, true);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return jsonResponse({ error: `${descriptor.name} tool error: ${message}` }, true);\n }\n }\n\n /**\n * Get the DSL instance for a named domain.\n * Returns null if the domain is not registered.\n * The DSL is lazily created and cached.\n */\n async getDSLForDomain(name: string): Promise<MultilingualDSL | null> {\n const descriptor = this.descriptors.get(name);\n if (!descriptor) return null;\n return this.getDSL(descriptor);\n }\n\n // ---------------------------------------------------------------------------\n // LLM ↔ LSE Convenience Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Generate an LLM system prompt for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generatePrompt(domain: string, config?: Partial<PromptGeneratorConfig>): GeneratedPrompt | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _generatePrompt({\n domain,\n description: descriptor.description,\n schemas: descriptor.schemas,\n ...config,\n });\n }\n\n /**\n * Synthesize training data for a domain from its schemas.\n * Returns null if the domain is not registered or has no schemas.\n */\n generateTrainingData(domain: string, config?: Partial<SynthesisConfig>): SynthesisResult | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n return _synthesizeFromSchemas(descriptor.schemas, {\n domain,\n ...config,\n });\n }\n\n /**\n * Build structured feedback for a failed LSE input in a domain.\n * Returns null if the domain is not registered or has no schemas.\n */\n buildFeedback(\n domain: string,\n input: string,\n inputFormat: 'explicit' | 'json' | 'natural',\n diagnostics: readonly Diagnostic[]\n ): LSEFeedback | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas || descriptor.schemas.length === 0) return null;\n\n const schemaLookup = this.createSchemaLookup(descriptor.schemas);\n\n // Try to extract the action from the input\n let action: string | undefined;\n try {\n if (inputFormat === 'explicit') {\n const node = _parseExplicit(input, { schemaLookup });\n action = node.action;\n }\n } catch {\n // Action detection failed — still build feedback without it\n }\n\n return _buildFeedback(input, inputFormat, diagnostics, schemaLookup, action);\n }\n\n /**\n * Get schemas for a domain (if available).\n */\n getSchemas(domain: string): readonly CommandSchema[] | null {\n const descriptor = this.descriptors.get(domain);\n if (!descriptor?.schemas) return null;\n return descriptor.schemas;\n }\n\n /**\n * Create a SchemaLookup from a domain's schemas.\n */\n private createSchemaLookup(schemas: readonly CommandSchema[]): SchemaLookup {\n const map = new Map<string, CommandSchema>();\n for (const s of schemas) {\n map.set(s.action, s);\n }\n return { getSchema: (action: string) => map.get(action) };\n }\n\n // ---------------------------------------------------------------------------\n // Private: DSL/renderer lifecycle\n // ---------------------------------------------------------------------------\n\n private async getDSL(descriptor: DomainDescriptor): Promise<MultilingualDSL> {\n const cached = this.dslCache.get(descriptor.name);\n if (cached) return cached;\n\n const dsl = await descriptor.getDSL();\n this.dslCache.set(descriptor.name, dsl);\n return dsl;\n }\n\n private async getRenderer(\n descriptor: DomainDescriptor\n ): Promise<NaturalLanguageRenderer | DomainRenderFn | null> {\n if (!descriptor.getRenderer) return null;\n\n const cached = this.rendererCache.get(descriptor.name);\n if (cached) return cached;\n\n const renderer = await descriptor.getRenderer();\n this.rendererCache.set(descriptor.name, renderer);\n return renderer;\n }\n\n // ---------------------------------------------------------------------------\n // Private: Tool handlers\n // ---------------------------------------------------------------------------\n\n private async handleParse(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const node = dsl.parse(input, language);\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n action: node.action,\n roles,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleCompile(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: CompileResult = dsl.compile(input, language);\n\n return jsonResponse({\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n language,\n input,\n });\n }\n\n private async handleValidate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const language = getString(args, 'language', 'en');\n\n const result: ValidationResult = dsl.validate(input, language);\n\n return jsonResponse({\n valid: result.valid,\n errors: result.errors,\n language,\n [descriptor.inputLabel]: input,\n });\n }\n\n private async handleTranslate(\n descriptor: DomainDescriptor,\n dsl: MultilingualDSL,\n args: Record<string, unknown>\n ): Promise<MCPToolResponse> {\n const input = getString(args, descriptor.inputLabel);\n if (!input) return missingParam(descriptor.inputLabel);\n const from = getString(args, 'from');\n if (!from) return missingParam('from');\n const to = getString(args, 'to');\n if (!to) return missingParam('to');\n\n // Parse in source language\n const node = dsl.parse(input, from);\n\n // Compile (language-neutral output)\n const compiled = dsl.compile(input, from);\n\n // Render to target language\n let rendered: string | null = null;\n const renderer = await this.getRenderer(descriptor);\n if (renderer) {\n try {\n rendered = typeof renderer === 'function' ? renderer(node, to) : renderer.render(node, to);\n } catch {\n // Fall through with rendered = null\n }\n } else if (dsl.render) {\n // A descriptor without an explicit renderer can still render: the DSL\n // knows its own domain renderer and its schema fallback.\n try {\n rendered = dsl.render(node, to);\n } catch {\n // Fall through with rendered = null\n }\n }\n\n const roles: Record<string, unknown> = {};\n for (const [key, value] of node.roles) {\n roles[key] = value;\n }\n\n return jsonResponse({\n input: { [descriptor.inputLabel]: input, language: from },\n ...(rendered != null && { rendered: { text: rendered, language: to } }),\n semantic: { action: node.action, roles },\n ...(compiled.ok && compiled.code != null && { compiled: compiled.code }),\n });\n }\n}\n\n// =============================================================================\n// Tool Definition Generator\n// =============================================================================\n\nfunction generateToolDefinitions(desc: DomainDescriptor): MCPToolDefinition[] {\n const tools: MCPToolDefinition[] = [];\n const ops = desc.tools ?? (['parse', 'compile', 'validate', 'translate'] as const);\n const langList = desc.languages.join(', ');\n\n for (const op of ops) {\n switch (op) {\n case 'parse':\n tools.push({\n name: `parse_${desc.name}`,\n description: `Parse a ${desc.description} input into a semantic representation (action, roles, confidence). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'compile':\n tools.push({\n name: `compile_${desc.name}`,\n description: `Compile a ${desc.description} input to ${desc.outputDescription ?? 'target code'}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: desc.inputDescription,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'validate':\n tools.push({\n name: `validate_${desc.name}`,\n description: `Check ${desc.description} syntax for errors. Returns {valid, errors[]}. Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to validate`,\n },\n language: {\n type: 'string',\n description: `Language code: ${langList}`,\n default: 'en',\n },\n },\n required: [desc.inputLabel],\n },\n });\n break;\n\n case 'translate':\n tools.push({\n name: `translate_${desc.name}`,\n description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}.`,\n inputSchema: {\n type: 'object',\n properties: {\n [desc.inputLabel]: {\n type: 'string',\n description: `${desc.inputDescription} to translate`,\n },\n from: {\n type: 'string',\n description: `Source language code: ${langList}`,\n },\n to: {\n type: 'string',\n description: `Target language code: ${langList}`,\n },\n },\n required: [desc.inputLabel, 'from', 'to'],\n },\n });\n break;\n }\n }\n\n return tools;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction parseToolName(name: string): { operation: string; domain: string } | null {\n const match = name.match(/^(parse|compile|validate|translate)_(.+)$/);\n if (!match) return null;\n return { operation: match[1], domain: match[2] };\n}\n\nfunction getString(args: Record<string, unknown>, name: string, defaultValue = ''): string {\n const value = args[name];\n return typeof value === 'string' ? value : defaultValue;\n}\n\nfunction jsonResponse(data: unknown, isError?: boolean): MCPToolResponse {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n ...(isError && { isError: true }),\n };\n}\n\nfunction missingParam(param: string): MCPToolResponse {\n return jsonResponse({ error: `Missing required parameter: ${param}` }, true);\n}\n","/**\n * Cross-Domain Dispatcher\n *\n * Routes natural-language input to the correct domain by trying all registered\n * domains and picking the highest-confidence match. Supports auto-detection,\n * composite multi-line parsing, and confidence-based routing.\n *\n * @example\n * ```typescript\n * import { DomainRegistry, CrossDomainDispatcher } from '@lokascript/framework';\n *\n * const registry = new DomainRegistry();\n * registry.register(sqlDescriptor);\n * registry.register(bddDescriptor);\n *\n * const dispatcher = new CrossDomainDispatcher(registry);\n *\n * // Auto-detect which domain handles the input\n * const result = await dispatcher.detect('select name from users', 'en');\n * // → { domain: 'sql', node: ..., confidence: 0.95, dsl: ... }\n *\n * // Parse multi-line input across domains\n * const composite = await dispatcher.parseComposite(`\n * select name from users\n * given page http://localhost\n * `, 'en');\n * ```\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl';\nimport { DomainRegistry } from './domain-registry';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Result of domain auto-detection */\nexport interface DispatchResult {\n /** The domain that matched */\n readonly domain: string;\n /** Parsed semantic node */\n readonly node: SemanticNode;\n /** Confidence score (0-1) */\n readonly confidence: number;\n /** The DSL instance that parsed it */\n readonly dsl: MultilingualDSL;\n}\n\n/** A single statement in a composite parse result */\nexport interface CompositeStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly node: SemanticNode;\n readonly confidence: number;\n}\n\n/** An error from a composite parse */\nexport interface CompositeError {\n readonly line: number;\n readonly input: string;\n readonly message: string;\n}\n\n/** Result of multi-domain composite parsing */\nexport interface CompositeParseResult {\n /** Successfully parsed statements */\n readonly statements: readonly CompositeStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** A single compiled statement in a composite compile result */\nexport interface CompositeCompileStatement {\n readonly line: number;\n readonly input: string;\n readonly domain: string;\n readonly ok: boolean;\n readonly code?: string | undefined;\n readonly errors?: string[] | undefined;\n}\n\n/** Result of multi-domain composite compilation */\nexport interface CompositeCompileResult {\n /** Successfully detected and compiled statements */\n readonly statements: readonly CompositeCompileStatement[];\n /** Lines that could not be matched to any domain */\n readonly errors: readonly CompositeError[];\n}\n\n/** Dispatcher configuration options */\nexport interface DispatcherOptions {\n /** Minimum confidence to accept a match (default: 0.5) */\n readonly minConfidence?: number;\n /** Domain priority order — earlier domains win on confidence ties */\n readonly priority?: readonly string[];\n}\n\n// =============================================================================\n// Comment line detection\n// =============================================================================\n\nconst COMMENT_PATTERN = /^\\s*(\\/\\/|--|#)/;\n\nfunction isSkippableLine(line: string): boolean {\n const trimmed = line.trim();\n return trimmed === '' || COMMENT_PATTERN.test(trimmed);\n}\n\n// =============================================================================\n// CrossDomainDispatcher\n// =============================================================================\n\n/**\n * Dispatcher that routes input to the correct domain by confidence scoring.\n *\n * Built on top of DomainRegistry — uses registered domains' DSL instances\n * to try parsing input and picks the highest-confidence match.\n */\nexport class CrossDomainDispatcher {\n private registry: DomainRegistry;\n private minConfidence: number;\n private priority: readonly string[];\n\n constructor(registry: DomainRegistry, options?: DispatcherOptions) {\n this.registry = registry;\n this.minConfidence = options?.minConfidence ?? 0.5;\n this.priority = options?.priority ?? [];\n }\n\n /**\n * Auto-detect which domain handles the input.\n * Tries all registered domains and returns the highest-confidence match.\n * Returns null if no domain matches above minConfidence.\n */\n async detect(input: string, language = 'en'): Promise<DispatchResult | null> {\n const domainNames = this.registry.getDomainNames();\n if (domainNames.length === 0) return null;\n\n const candidates: DispatchResult[] = [];\n\n for (const name of domainNames) {\n try {\n const dsl = await this.registry.getDSLForDomain(name);\n if (!dsl) continue;\n\n const { node, confidence } = dsl.parseWithConfidence(input, language);\n if (confidence >= this.minConfidence) {\n candidates.push({ domain: name, node, confidence, dsl });\n }\n } catch {\n // Domain could not be loaded or parse this input — skip\n }\n }\n\n if (candidates.length === 0) return null;\n\n // Sort by priority first, then confidence within each priority tier.\n // Simpler schemas (fewer roles) often score higher confidence than more\n // specific ones — e.g., voice's \"select [patient:greedy]\" gets 1.0 while\n // sql's \"select [columns] from [source]\" gets 0.71 for the same input.\n // Priority ordering ensures domain specificity wins when both match.\n if (this.priority.length > 0) {\n candidates.sort((a, b) => {\n const pa = this.getPriorityIndex(a.domain);\n const pb = this.getPriorityIndex(b.domain);\n if (pa !== pb) return pa - pb;\n return b.confidence - a.confidence;\n });\n } else {\n // No priority configured: pure confidence ordering\n candidates.sort((a, b) => b.confidence - a.confidence);\n }\n\n return candidates[0];\n }\n\n /**\n * Parse multi-line input where each line may belong to a different domain.\n * Empty lines and comment lines (starting with //, --, or #) are skipped.\n */\n async parseComposite(input: string, language = 'en'): Promise<CompositeParseResult> {\n const lines = input.split('\\n');\n const statements: CompositeStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const result = await this.detect(trimmed, language);\n\n if (result) {\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: result.domain,\n node: result.node,\n confidence: result.confidence,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Compile input using auto-detected domain.\n * Returns the compilation result with the domain name.\n */\n async compile(\n input: string,\n language = 'en'\n ): Promise<(CompileResult & { domain: string }) | null> {\n const detected = await this.detect(input, language);\n if (!detected) return null;\n\n const result = detected.dsl.compile(input, language);\n return { ...result, domain: detected.domain };\n }\n\n /**\n * Compile multi-line input where each line may belong to a different domain.\n * Detects the domain for each line and compiles it, returning per-line results.\n * Empty lines and comment lines are skipped.\n */\n async compileComposite(input: string, language = 'en'): Promise<CompositeCompileResult> {\n const lines = input.split('\\n');\n const statements: CompositeCompileStatement[] = [];\n const errors: CompositeError[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (isSkippableLine(line)) continue;\n\n const trimmed = line.trim();\n const detected = await this.detect(trimmed, language);\n\n if (detected) {\n const result = detected.dsl.compile(trimmed, language);\n statements.push({\n line: i + 1,\n input: trimmed,\n domain: detected.domain,\n ok: result.ok,\n code: result.code,\n errors: result.errors,\n });\n } else {\n errors.push({\n line: i + 1,\n input: trimmed,\n message: 'No domain matched this input',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Validate input against all domains, returning the best match.\n */\n async validate(input: string, language = 'en'): Promise<ValidationResult & { domain?: string }> {\n const detected = await this.detect(input, language);\n if (!detected) {\n return { valid: false, errors: ['No domain matched this input'] };\n }\n\n const result = detected.dsl.validate(input, language);\n return { ...result, domain: detected.domain };\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private getPriorityIndex(domain: string): number {\n const idx = this.priority.indexOf(domain);\n return idx === -1 ? this.priority.length : idx;\n }\n}\n","/**\n * Domain-Aware Scanner\n *\n * Extracts DSL snippets from HTML/template files based on domain-declared\n * attribute patterns and script types. Unlike the hyperscript-specific\n * HTMLScanner, this scanner is configured dynamically from DomainScanConfig.\n */\n\nimport type { DomainScanConfig, ExtractedSnippet } from './types';\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Build regex patterns for extracting attribute values.\n * Handles double-quoted, single-quoted, and backtick-quoted values.\n */\nfunction buildAttributePatterns(attributes: readonly string[]): RegExp[] {\n const patterns: RegExp[] = [];\n for (const attr of attributes) {\n const escaped = attr.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Match: attr=\"value\", attr='value', attr=`value`\n patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*\"([^\"]+)\"`, 'g'));\n patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*'([^']+)'`, 'g'));\n patterns.push(new RegExp(`${escaped}\\\\s*=\\\\s*\\`([^\\`]+)\\``, 'g'));\n }\n return patterns;\n}\n\n/**\n * Build regex patterns for extracting script tag contents.\n */\nfunction buildScriptPatterns(scriptTypes: readonly string[]): RegExp[] {\n return scriptTypes.map(type => {\n const escaped = type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`<script[^>]*type=[\"']?${escaped}[\"']?[^>]*>([\\\\s\\\\S]*?)<\\\\/script>`, 'gi');\n });\n}\n\n/**\n * Count newlines before a position to determine line number.\n */\nfunction getLineNumber(source: string, position: number): number {\n let line = 1;\n for (let i = 0; i < position && i < source.length; i++) {\n if (source[i] === '\\n') line++;\n }\n return line;\n}\n\n/**\n * Try to extract an element ID near the matched attribute.\n * Looks backward in the source for an id=\"...\" on the same element.\n */\nfunction extractElementId(source: string, matchIndex: number): string | undefined {\n // Find the opening < before this attribute\n const before = source.lastIndexOf('<', matchIndex);\n if (before === -1) return undefined;\n\n const tagChunk = source.slice(before, matchIndex + 200);\n const idMatch = tagChunk.match(/\\bid=[\"']([^\"']+)[\"']/);\n return idMatch?.[1];\n}\n\n/**\n * Try to extract a lang attribute from the element.\n */\nfunction extractLangAttribute(source: string, matchIndex: number): string | undefined {\n const before = source.lastIndexOf('<', matchIndex);\n if (before === -1) return undefined;\n\n const tagChunk = source.slice(before, matchIndex + 200);\n const langMatch = tagChunk.match(/\\blang=[\"']([^\"']+)[\"']/);\n return langMatch?.[1];\n}\n\n// =============================================================================\n// DomainAwareScanner\n// =============================================================================\n\n/**\n * Scans HTML/template files for domain-specific snippets.\n *\n * Configured by DomainScanConfig objects, each declaring which\n * HTML attributes and script types a domain uses.\n */\nexport class DomainAwareScanner {\n private configs: readonly DomainScanConfig[];\n\n constructor(configs: readonly DomainScanConfig[]) {\n this.configs = configs;\n }\n\n /**\n * Extract all domain snippets from an HTML source string.\n */\n extract(source: string, filename: string): ExtractedSnippet[] {\n const snippets: ExtractedSnippet[] = [];\n\n for (const config of this.configs) {\n const defaultLang = config.defaultLanguage ?? 'en';\n\n // Extract from attributes\n const attrPatterns = buildAttributePatterns(config.attributes);\n for (const pattern of attrPatterns) {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(source))) {\n const code = match[1].trim();\n if (!code) continue;\n\n const line = getLineNumber(source, match.index);\n const elementId = extractElementId(source, match.index);\n const langAttr = extractLangAttribute(source, match.index);\n\n snippets.push({\n domain: config.domain,\n code,\n language: langAttr ?? defaultLang,\n file: filename,\n line,\n column: 1,\n ...(elementId != null && { elementId }),\n });\n }\n }\n\n // Extract from script tags\n if (config.scriptTypes) {\n const scriptPatterns = buildScriptPatterns(config.scriptTypes);\n for (const pattern of scriptPatterns) {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(source))) {\n const code = match[1].trim();\n if (!code) continue;\n\n const line = getLineNumber(source, match.index);\n\n snippets.push({\n domain: config.domain,\n code,\n language: defaultLang,\n file: filename,\n line,\n column: 1,\n });\n }\n }\n }\n }\n\n return snippets;\n }\n\n /**\n * Extract snippets from multiple files.\n */\n async extractFromFiles(\n files: string[],\n readFile: (path: string) => Promise<string>\n ): Promise<ExtractedSnippet[]> {\n const allSnippets: ExtractedSnippet[] = [];\n\n for (const file of files) {\n try {\n const source = await readFile(file);\n const snippets = this.extract(source, file);\n allSnippets.push(...snippets);\n } catch {\n // Skip files that can't be read\n }\n }\n\n return allSnippets;\n }\n}\n","/**\n * Generalized AOT Orchestrator\n *\n * Coordinates scan → parse → compile → collect for any domain.\n * Each domain provides a DomainCompilationBackend (DSL + CodeGenerator + scan config),\n * and the orchestrator handles the rest.\n *\n * @example\n * ```typescript\n * import { AOTOrchestrator } from '@lokascript/framework';\n *\n * const orchestrator = new AOTOrchestrator();\n *\n * orchestrator.registerBackend({\n * domain: 'sql',\n * dsl: createSQLDSL(),\n * codeGenerator: sqlCodeGenerator,\n * scanConfig: {\n * domain: 'sql',\n * attributes: ['data-sql'],\n * scriptTypes: ['text/sql-dsl'],\n * },\n * });\n *\n * const result = await orchestrator.compileFiles(\n * ['index.html', 'about.html'],\n * (path) => fs.promises.readFile(path, 'utf-8')\n * );\n * ```\n */\n\nimport type { MultilingualDSL, CodeGenerator } from '../api/create-dsl';\nimport type {\n DomainScanConfig,\n ExtractedSnippet,\n CompiledSnippet,\n AOTBatchResult,\n GeneralizedAOTOptions,\n OutputOptions,\n} from './types';\nimport { DomainAwareScanner } from './domain-scanner';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Per-domain compilation backend.\n * Provides everything needed to scan, parse, and compile a domain's syntax.\n */\nexport interface DomainCompilationBackend {\n /** Domain name (must match scanConfig.domain) */\n readonly domain: string;\n /** The DSL instance for parsing and compilation */\n readonly dsl: MultilingualDSL;\n /** Code generator for producing target code from semantic nodes */\n readonly codeGenerator: CodeGenerator;\n /** Scan configuration declaring HTML attribute patterns */\n readonly scanConfig: DomainScanConfig;\n}\n\n// =============================================================================\n// AOTOrchestrator\n// =============================================================================\n\n/**\n * Generalized AOT orchestrator for any domain.\n */\nexport class AOTOrchestrator {\n private backends = new Map<string, DomainCompilationBackend>();\n private options: Required<GeneralizedAOTOptions>;\n\n constructor(options?: GeneralizedAOTOptions) {\n this.options = {\n confidenceThreshold: options?.confidenceThreshold ?? 0.7,\n continueOnError: options?.continueOnError ?? true,\n debug: options?.debug ?? false,\n };\n }\n\n /**\n * Register a domain compilation backend.\n * @throws if a backend with the same domain name is already registered\n */\n registerBackend(backend: DomainCompilationBackend): void {\n if (this.backends.has(backend.domain)) {\n throw new Error(`Backend already registered for domain: ${backend.domain}`);\n }\n this.backends.set(backend.domain, backend);\n }\n\n /**\n * Scan source files and compile all domain snippets.\n */\n async compileFiles(\n files: string[],\n readFile: (path: string) => Promise<string>\n ): Promise<AOTBatchResult> {\n // Build scanner from all backends' scan configs\n const configs = Array.from(this.backends.values()).map(b => b.scanConfig);\n const scanner = new DomainAwareScanner(configs);\n\n // Extract all snippets\n const snippets = await scanner.extractFromFiles(files, readFile);\n\n if (this.options.debug) {\n console.log(`[aot] Extracted ${snippets.length} snippets from ${files.length} files`);\n }\n\n // Compile each snippet\n const compiled: CompiledSnippet[] = [];\n const errors: AOTBatchResult['errors'][number][] = [];\n const domainBreakdown: Record<string, number> = {};\n\n for (const snippet of snippets) {\n domainBreakdown[snippet.domain] = (domainBreakdown[snippet.domain] ?? 0) + 1;\n\n const result = this.compileSnippet(snippet);\n if ('error' in result) {\n errors.push({\n domain: snippet.domain,\n source: snippet.code,\n file: snippet.file,\n line: snippet.line,\n message: result.error,\n });\n if (!this.options.continueOnError) break;\n } else {\n compiled.push(result);\n }\n }\n\n return {\n compiled,\n errors,\n stats: {\n totalSnippets: snippets.length,\n compiledCount: compiled.length,\n errorCount: errors.length,\n domainBreakdown,\n },\n };\n }\n\n /**\n * Compile a single extracted snippet.\n * Returns the compiled result or an error object.\n */\n compileSnippet(snippet: ExtractedSnippet): CompiledSnippet | { error: string } {\n const backend = this.backends.get(snippet.domain);\n if (!backend) {\n return { error: `No backend registered for domain: ${snippet.domain}` };\n }\n\n try {\n const result = backend.dsl.compile(snippet.code, snippet.language);\n if (!result.ok || !result.code) {\n return { error: result.errors?.join('; ') ?? 'Compilation failed' };\n }\n\n return {\n domain: snippet.domain,\n source: snippet.code,\n compiled: result.code,\n language: snippet.language,\n file: snippet.file,\n line: snippet.line,\n };\n } catch (err) {\n return { error: err instanceof Error ? err.message : String(err) };\n }\n }\n\n /**\n * Generate combined output from compilation results.\n */\n generateOutput(result: AOTBatchResult, options?: OutputOptions): string {\n const format = options?.format ?? 'esm';\n const includeComments = options?.includeComments ?? true;\n const groupByDomain = options?.groupByDomain ?? true;\n\n const sections: string[] = [];\n\n if (includeComments) {\n sections.push(`// Generated by @lokascript/framework AOT compiler`);\n sections.push(\n `// ${result.stats.compiledCount} snippets compiled, ${result.stats.errorCount} errors`\n );\n sections.push('');\n }\n\n if (groupByDomain) {\n // Group by domain\n const grouped = new Map<string, CompiledSnippet[]>();\n for (const snippet of result.compiled) {\n const list = grouped.get(snippet.domain) ?? [];\n list.push(snippet);\n grouped.set(snippet.domain, list);\n }\n\n for (const [domain, snippets] of grouped) {\n if (includeComments) {\n sections.push(`// === Domain: ${domain} ===`);\n sections.push('');\n }\n\n for (const snippet of snippets) {\n if (includeComments) {\n sections.push(`// Source: ${snippet.file}:${snippet.line}`);\n sections.push(`// Language: ${snippet.language}`);\n }\n sections.push(snippet.compiled);\n sections.push('');\n }\n }\n } else {\n for (const snippet of result.compiled) {\n if (includeComments) {\n sections.push(`// [${snippet.domain}] ${snippet.file}:${snippet.line}`);\n }\n sections.push(snippet.compiled);\n sections.push('');\n }\n }\n\n const body = sections.join('\\n').trimEnd();\n\n switch (format) {\n case 'cjs':\n return `'use strict';\\n\\n${body}\\n`;\n case 'iife':\n return `(function() {\\n${body}\\n})();\\n`;\n case 'esm':\n default:\n return `${body}\\n`;\n }\n }\n}\n","/**\n * Registry-to-AOT Bridge\n *\n * Converts DomainRegistry entries into DomainCompilationBackend instances\n * for use with AOTOrchestrator. Only domains that have scanConfig defined\n * are included.\n *\n * @example\n * ```typescript\n * const registry = new DomainRegistry();\n * // ... register domains with scanConfig ...\n *\n * const backends = await registryToAOTBackends(registry);\n * const orchestrator = new AOTOrchestrator();\n * for (const backend of backends) {\n * orchestrator.registerBackend(backend);\n * }\n * ```\n */\n\nimport type { DomainCompilationBackend } from './aot-orchestrator';\nimport type { DomainScanConfig } from './types';\nimport type { DomainRegistry } from '../api/domain-registry';\nimport type { CodeGenerator } from '../api/create-dsl';\nimport type { SemanticNode } from '../core/types';\n\n/**\n * Convert all registry entries with scanConfig into AOT backends.\n * Domains without scanConfig are skipped.\n */\nexport async function registryToAOTBackends(\n registry: DomainRegistry\n): Promise<DomainCompilationBackend[]> {\n const backends: DomainCompilationBackend[] = [];\n\n for (const name of registry.getDomainNames()) {\n const descriptor = registry.getDescriptor(name);\n if (!descriptor?.scanConfig) continue;\n\n const dsl = await registry.getDSLForDomain(name);\n if (!dsl) continue;\n\n const scanConfig: DomainScanConfig = {\n domain: name,\n attributes: [...descriptor.scanConfig.attributes],\n ...(descriptor.scanConfig.scriptTypes\n ? { scriptTypes: [...descriptor.scanConfig.scriptTypes] }\n : {}),\n defaultLanguage: descriptor.scanConfig.defaultLanguage ?? 'en',\n };\n\n // The AOTOrchestrator only calls backend.dsl.compile(), not codeGenerator directly.\n // Provide a thin adapter that parses then generates via the DSL's internal pipeline.\n const codeGenerator: CodeGenerator = {\n generate(node: SemanticNode): string {\n // Fallback: compile through the DSL by reconstructing explicit syntax.\n // In practice, AOTOrchestrator uses dsl.compile() directly.\n return JSON.stringify({ action: node.action, roles: Object.fromEntries(node.roles) });\n },\n };\n\n backends.push({ domain: name, dsl, codeGenerator, scanConfig });\n }\n\n return backends;\n}\n","/**\n * Command Schema Types — re-exported from @lokascript/intent\n */\n\nexport type { CommandSchema, RoleSpec } from '@lokascript/intent';\nexport { defineCommand, defineRole, getRoleSpec } from '@lokascript/intent';\n","/**\n * Structured Error Diagnostics\n *\n * Re-exported from @lokascript/intent.\n * This module is the framework's re-export point for the diagnostic types\n * that live in the universal intent package.\n */\n\nexport type {\n DiagnosticSeverity,\n Diagnostic,\n DiagnosticResult,\n DiagnosticSummary,\n DiagnosticCollector,\n DiagnosticOptions,\n} from '@lokascript/intent';\n\nexport { createDiagnosticCollector, fromError, filterBySeverity } from '@lokascript/intent';\n","/**\n * Token Utilities\n *\n * Core token creation, stream implementation, and character classification.\n * These are the foundational building blocks used by all tokenizers.\n */\n\nimport type { LanguageToken, TokenKind, TokenStream, StreamMark, SourcePosition } from '../types';\n\n// =============================================================================\n// Time Unit Configuration\n// =============================================================================\n\n/**\n * Configuration for a native language time unit pattern.\n * Used by tryNumberWithTimeUnits() to match language-specific time units.\n */\nexport interface TimeUnitMapping {\n /** The pattern to match (e.g., 'segundos', 'ミリ秒') */\n readonly pattern: string;\n /** The standard suffix to use (ms, s, m, h) */\n readonly suffix: string;\n /** Length of the pattern (for optimization) */\n readonly length: number;\n /** Whether to check for word boundary after the pattern */\n readonly checkBoundary?: boolean;\n /** Character that cannot follow the pattern (e.g., 's' for 'm' to avoid 'ms') */\n readonly notFollowedBy?: string;\n /** Whether to do case-insensitive matching */\n readonly caseInsensitive?: boolean;\n}\n\n// =============================================================================\n// Token Stream Implementation\n// =============================================================================\n\n/**\n * Concrete implementation of TokenStream.\n */\nexport class TokenStreamImpl implements TokenStream {\n readonly tokens: readonly LanguageToken[];\n readonly language: string;\n private pos: number = 0;\n\n constructor(tokens: LanguageToken[], language: string) {\n this.tokens = tokens;\n this.language = language;\n }\n\n peek(offset: number = 0): LanguageToken | null {\n const index = this.pos + offset;\n if (index < 0 || index >= this.tokens.length) {\n return null;\n }\n return this.tokens[index];\n }\n\n advance(): LanguageToken {\n if (this.isAtEnd()) {\n throw new Error('Unexpected end of token stream');\n }\n return this.tokens[this.pos++];\n }\n\n isAtEnd(): boolean {\n return this.pos >= this.tokens.length;\n }\n\n mark(): StreamMark {\n return { position: this.pos };\n }\n\n reset(mark: StreamMark): void {\n this.pos = mark.position;\n }\n\n position(): number {\n return this.pos;\n }\n\n /**\n * Get remaining tokens as an array.\n */\n remaining(): LanguageToken[] {\n return this.tokens.slice(this.pos);\n }\n\n /**\n * Consume tokens while predicate is true.\n */\n takeWhile(predicate: (token: LanguageToken) => boolean): LanguageToken[] {\n const result: LanguageToken[] = [];\n while (!this.isAtEnd() && predicate(this.peek()!)) {\n result.push(this.advance());\n }\n return result;\n }\n\n /**\n * Skip tokens while predicate is true.\n */\n skipWhile(predicate: (token: LanguageToken) => boolean): void {\n while (!this.isAtEnd() && predicate(this.peek()!)) {\n this.advance();\n }\n }\n}\n\n// =============================================================================\n// Shared Tokenization Utilities\n// =============================================================================\n\n/**\n * Create a source position from start and end offsets.\n */\nexport function createPosition(start: number, end: number): SourcePosition {\n return { start, end };\n}\n\n/**\n * Options for creating a token with optional morphological data.\n */\nexport interface CreateTokenOptions {\n /** Explicitly normalized form from keyword map */\n normalized?: string;\n /** Morphologically normalized stem */\n stem?: string;\n /** Confidence in the stem (0.0-1.0) */\n stemConfidence?: number;\n /** Additional metadata for specific token types (e.g., event modifier data) */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Token creation options (object style).\n */\nexport interface TokenCreationParams extends CreateTokenOptions {\n value: string;\n kind: TokenKind;\n position: SourcePosition;\n}\n\n/**\n * Create a language token (object style).\n */\nexport function createToken(params: TokenCreationParams): LanguageToken;\n\n/**\n * Create a language token (separate parameters style).\n */\nexport function createToken(\n value: string,\n kind: TokenKind,\n position: SourcePosition,\n normalizedOrOptions?: string | CreateTokenOptions\n): LanguageToken;\n\n/**\n * Create a language token.\n * Supports both object style and separate parameters style.\n */\nexport function createToken(\n valueOrParams: string | TokenCreationParams,\n kind?: TokenKind,\n position?: SourcePosition,\n normalizedOrOptions?: string | CreateTokenOptions\n): LanguageToken {\n // Handle object style\n if (typeof valueOrParams === 'object') {\n const { value, kind, position, normalized, stem, stemConfidence, metadata } = valueOrParams;\n return {\n value,\n kind,\n position,\n ...(normalized !== undefined && { normalized }),\n ...(stem !== undefined && { stem }),\n ...(stemConfidence !== undefined && { stemConfidence }),\n ...(metadata !== undefined && { metadata }),\n };\n }\n\n // Handle separate parameters style\n const value = valueOrParams;\n if (!kind || !position) {\n throw new Error('createToken requires kind and position parameters');\n }\n // Handle legacy string argument for backward compatibility\n if (typeof normalizedOrOptions === 'string') {\n return { value, kind, position, normalized: normalizedOrOptions };\n }\n\n // Handle options object\n if (normalizedOrOptions) {\n const { normalized, stem, stemConfidence, metadata } = normalizedOrOptions;\n return {\n value,\n kind,\n position,\n ...(normalized !== undefined && { normalized }),\n ...(stem !== undefined && { stem }),\n ...(stemConfidence !== undefined && { stemConfidence }),\n ...(metadata !== undefined && { metadata }),\n };\n }\n\n return { value, kind, position };\n}\n\n/**\n * Check if a character is whitespace.\n */\nexport function isWhitespace(char: string): boolean {\n return /\\s/.test(char);\n}\n\n/**\n * Check if a string starts with a CSS selector prefix.\n * Includes JSX-style element selectors: <form />, <div>\n */\nexport function isSelectorStart(char: string): boolean {\n return (\n char === '#' || char === '.' || char === '[' || char === '@' || char === '*' || char === '<'\n );\n}\n\n/**\n * Check if a character is a quote (string delimiter).\n */\nexport function isQuote(char: string): boolean {\n return char === '\"' || char === \"'\" || char === '`' || char === '「' || char === '」';\n}\n\n/**\n * Check if a character is a digit.\n */\nexport function isDigit(char: string): boolean {\n return /\\d/.test(char);\n}\n\n/**\n * Strip diacritical marks that are OPTIONAL in their script — currently Arabic\n * harakat (U+064B–U+0652: fatha, kasra, damma, sukun, shadda…) and the\n * superscript alif (U+0670).\n *\n * `بدّل` and `بَدِّل` are the same word; Arabic prose writes either. So any place\n * that compares an Arabic surface form against a declared keyword has to compare\n * stripped, or the same word fails to match itself.\n *\n * Deliberately Arabic-only. Latin diacritics are NOT optional — `obtén`, `récupère`\n * and `vá` differ from their unaccented spellings in meaning or validity — and\n * Hebrew niqqud (U+05B0–U+05BC) is out of range too, so this is inert for every\n * other script.\n */\nexport function stripOptionalDiacritics(word: string): string {\n return word.replace(/[\\u064b-\\u0652\\u0670]/g, '');\n}\n\n/**\n * Check if a character is an ASCII letter.\n */\nexport function isAsciiLetter(char: string): boolean {\n return /[a-zA-Z]/.test(char);\n}\n\n/**\n * Check if a character is part of an ASCII identifier.\n */\nexport function isAsciiIdentifierChar(char: string): boolean {\n return /[a-zA-Z0-9_-]/.test(char);\n}\n","/**\n * Extraction Utilities\n *\n * Pure functions for extracting CSS selectors, string literals, URLs, and numbers\n * from input strings. These are language-independent and used by all tokenizers.\n */\n\nimport {\n isSelectorStart,\n isWhitespace,\n isAsciiIdentifierChar,\n isAsciiLetter,\n isQuote,\n isDigit,\n} from './token-utils';\n\n// =============================================================================\n// CSS Selector Tokenization\n// =============================================================================\n\n/**\n * Extract a CSS selector from the input string starting at pos.\n * CSS selectors are universal across languages.\n *\n * Supported formats:\n * - #id\n * - .class\n * - [attribute]\n * - [attribute=value]\n * - @attribute (shorthand)\n * - *property (CSS property shorthand)\n * - Complex selectors with combinators (limited)\n *\n * Method call handling:\n * - #dialog.showModal() → stops after #dialog (method call, not compound selector)\n * - #box.active → compound selector (no parens)\n *\n * NOTE: intentionally diverges from the semantic package's copy\n * (packages/semantic/src/tokenizers/extractors/css-selector.ts), which also\n * consumes pseudo-class/pseudo-element segments (#x:hover, .a:not(.b)). This\n * legacy version is only used by BaseTokenizer.trySelector (no semantic call\n * sites) and stays as-is.\n */\nexport function extractCssSelector(input: string, startPos: number): string | null {\n if (startPos >= input.length) return null;\n\n const char = input[startPos];\n if (!isSelectorStart(char)) return null;\n\n let pos = startPos;\n let selector = '';\n\n // Handle different selector types\n if (char === '#' || char === '.') {\n // ID or class selector: #id, .class\n selector += input[pos++];\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n // Must have at least one character after prefix\n if (selector.length <= 1) return null;\n\n // Check for method call pattern: #id.method() or .class.method()\n // If we see .identifier followed by (, don't consume it - it's a method call\n if (pos < input.length && input[pos] === '.' && char === '#') {\n // Look ahead to see if this is a method call\n const methodStart = pos + 1;\n let methodEnd = methodStart;\n while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {\n methodEnd++;\n }\n // If followed by (, it's a method call - stop here\n if (methodEnd < input.length && input[methodEnd] === '(') {\n return selector;\n }\n }\n } else if (char === '[') {\n // Attribute selector: [attr] or [attr=value] or [attr=\"value\"]\n // Need to track quote state to avoid counting brackets inside quotes\n let depth = 1;\n let inQuote = false;\n let quoteChar: string | null = null;\n let escaped = false;\n\n selector += input[pos++]; // [\n\n while (pos < input.length && depth > 0) {\n const c = input[pos];\n selector += c;\n\n if (escaped) {\n // Skip escaped character\n escaped = false;\n } else if (c === '\\\\') {\n // Next character is escaped\n escaped = true;\n } else if (inQuote) {\n // Inside a quoted string\n if (c === quoteChar) {\n inQuote = false;\n quoteChar = null;\n }\n } else {\n // Not inside a quoted string\n if (c === '\"' || c === \"'\" || c === '`') {\n inQuote = true;\n quoteChar = c;\n } else if (c === '[') {\n depth++;\n } else if (c === ']') {\n depth--;\n }\n }\n pos++;\n }\n if (depth !== 0) return null;\n } else if (char === '@') {\n // Attribute shorthand: @disabled\n selector += input[pos++];\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n if (selector.length <= 1) return null;\n } else if (char === '*') {\n // CSS property shorthand: *display\n selector += input[pos++];\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n if (selector.length <= 1) return null;\n } else if (char === '<') {\n // HTML literal selector with optional modifiers and attributes:\n // - <div>\n // - <div.class>\n // - <div#id>\n // - <div.class#id>\n // - <button[disabled]/>\n // - <div.card/>\n // - <div.class#id[attr=\"value\"]/>\n selector += input[pos++]; // <\n\n // Must be followed by an identifier (tag name)\n if (pos >= input.length || !isAsciiLetter(input[pos])) return null;\n\n // Extract tag name\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n\n // Process modifiers and attributes\n // Can have multiple .class, one #id, and multiple [attr] in any order\n while (pos < input.length) {\n const modChar = input[pos];\n\n if (modChar === '.') {\n // Class modifier\n selector += input[pos++]; // .\n if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {\n return null; // Invalid - class name required after .\n }\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n } else if (modChar === '#') {\n // ID modifier\n selector += input[pos++]; // #\n if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {\n return null; // Invalid - ID required after #\n }\n while (pos < input.length && isAsciiIdentifierChar(input[pos])) {\n selector += input[pos++];\n }\n } else if (modChar === '[') {\n // Attribute modifier: [disabled] or [type=\"button\"]\n // Need to track quote state to avoid counting brackets inside quotes\n let depth = 1;\n let inQuote = false;\n let quoteChar: string | null = null;\n let escaped = false;\n\n selector += input[pos++]; // [\n\n while (pos < input.length && depth > 0) {\n const c = input[pos];\n selector += c;\n\n if (escaped) {\n escaped = false;\n } else if (c === '\\\\') {\n escaped = true;\n } else if (inQuote) {\n if (c === quoteChar) {\n inQuote = false;\n quoteChar = null;\n }\n } else {\n if (c === '\"' || c === \"'\" || c === '`') {\n inQuote = true;\n quoteChar = c;\n } else if (c === '[') {\n depth++;\n } else if (c === ']') {\n depth--;\n }\n }\n pos++;\n }\n if (depth !== 0) return null; // Unclosed bracket\n } else {\n // No more modifiers\n break;\n }\n }\n\n // Skip whitespace before optional self-closing /\n while (pos < input.length && isWhitespace(input[pos])) {\n selector += input[pos++];\n }\n\n // Optional self-closing /\n if (pos < input.length && input[pos] === '/') {\n selector += input[pos++];\n // Skip whitespace after /\n while (pos < input.length && isWhitespace(input[pos])) {\n selector += input[pos++];\n }\n }\n\n // Must end with >\n if (pos >= input.length || input[pos] !== '>') return null;\n selector += input[pos++]; // >\n }\n\n return selector || null;\n}\n\n// =============================================================================\n// String Literal Tokenization\n// =============================================================================\n\n/**\n * Check if a single quote at pos is a possessive marker ('s).\n * Returns true if this looks like possessive, not a string start.\n *\n * Examples:\n * - #element's *opacity → possessive (returns true)\n * - 'hello' → string (returns false)\n * - it's value → possessive (returns true)\n */\nexport function isPossessiveMarker(input: string, pos: number): boolean {\n if (pos >= input.length || input[pos] !== \"'\") return false;\n\n // Check if followed by 's' or 'S'\n if (pos + 1 >= input.length) return false;\n const nextChar = input[pos + 1].toLowerCase();\n if (nextChar !== 's') return false;\n\n // After 's, should be end, whitespace, or special char (not alphanumeric)\n if (pos + 2 >= input.length) return true; // end of input\n const afterS = input[pos + 2];\n return isWhitespace(afterS) || afterS === '*' || !isAsciiIdentifierChar(afterS);\n}\n\n/**\n * Extract a string literal from the input starting at pos.\n * Handles both ASCII quotes and Unicode quotes.\n *\n * Note: Single quotes that look like possessive markers ('s) are skipped.\n */\nexport function extractStringLiteral(input: string, startPos: number): string | null {\n if (startPos >= input.length) return null;\n\n const openQuote = input[startPos];\n if (!isQuote(openQuote)) return null;\n\n // Check for possessive marker - don't treat as string\n if (openQuote === \"'\" && isPossessiveMarker(input, startPos)) {\n return null;\n }\n\n // Map opening quotes to closing quotes\n const closeQuoteMap: Record<string, string> = {\n '\"': '\"',\n \"'\": \"'\",\n '`': '`',\n '「': '」',\n };\n\n const closeQuote = closeQuoteMap[openQuote];\n if (!closeQuote) return null;\n\n let pos = startPos + 1;\n let literal = openQuote;\n let escaped = false;\n\n while (pos < input.length) {\n const char = input[pos];\n literal += char;\n\n if (escaped) {\n escaped = false;\n } else if (char === '\\\\') {\n escaped = true;\n } else if (char === closeQuote) {\n // Found closing quote\n return literal;\n }\n pos++;\n }\n\n // Unclosed string - return what we have\n return literal;\n}\n\n// =============================================================================\n// URL Tokenization\n// =============================================================================\n\n/**\n * Check if the input at position starts a URL.\n * Detects: /path, ./path, ../path, //domain.com, http://, https://\n */\nexport function isUrlStart(input: string, pos: number): boolean {\n if (pos >= input.length) return false;\n\n const char = input[pos];\n const next = input[pos + 1] || '';\n const third = input[pos + 2] || '';\n\n // Absolute path: /something (but not just /)\n // Must be followed by alphanumeric or path char, not another / (that's protocol-relative)\n if (char === '/' && next !== '/' && /[a-zA-Z0-9._-]/.test(next)) {\n return true;\n }\n\n // Protocol-relative: //domain.com\n if (char === '/' && next === '/' && /[a-zA-Z]/.test(third)) {\n return true;\n }\n\n // Relative path: ./ or ../\n if (char === '.' && (next === '/' || (next === '.' && third === '/'))) {\n return true;\n }\n\n // Full URL: http:// or https://\n const slice = input.slice(pos, pos + 8).toLowerCase();\n if (slice.startsWith('http://') || slice.startsWith('https://')) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Extract a URL from the input starting at pos.\n * Handles paths, query strings, and fragments.\n *\n * Fragment (#) handling:\n * - /page#section → includes fragment as part of URL\n * - #id alone → not a URL (CSS selector)\n */\nexport function extractUrl(input: string, startPos: number): string | null {\n if (!isUrlStart(input, startPos)) return null;\n\n let pos = startPos;\n let url = '';\n\n // Core URL characters (RFC 3986 unreserved + sub-delims + path/query chars)\n // Includes: letters, digits, and - . _ ~ : / ? # [ ] @ ! $ & ' ( ) * + , ; = %\n const urlChars = /[a-zA-Z0-9/:._\\-?&=%@+~!$'()*,;[\\]]/;\n\n while (pos < input.length) {\n const char = input[pos];\n\n // Special handling for #\n if (char === '#') {\n // Only include # if we have path content before it (it's a fragment)\n // If # appears at URL start or after certain chars, stop (might be CSS selector)\n if (url.length > 0 && /[a-zA-Z0-9/.]$/.test(url)) {\n // Include fragment\n url += char;\n pos++;\n // Consume fragment identifier (letters, digits, underscore, hyphen)\n while (pos < input.length && /[a-zA-Z0-9_-]/.test(input[pos])) {\n url += input[pos++];\n }\n }\n // Stop either way - fragment consumed or # is separate token\n break;\n }\n\n if (urlChars.test(char)) {\n url += char;\n pos++;\n } else {\n break;\n }\n }\n\n // Minimum length validation\n if (url.length < 2) return null;\n\n return url;\n}\n\n// =============================================================================\n// Number Tokenization\n// =============================================================================\n\n/**\n * Extract a number from the input starting at pos.\n * Handles integers and decimals.\n */\nexport function extractNumber(input: string, startPos: number): string | null {\n if (startPos >= input.length) return null;\n\n const char = input[startPos];\n if (!isDigit(char) && char !== '-' && char !== '+') return null;\n\n let pos = startPos;\n let number = '';\n\n // Optional sign\n if (input[pos] === '-' || input[pos] === '+') {\n number += input[pos++];\n }\n\n // Must have at least one digit\n if (pos >= input.length || !isDigit(input[pos])) {\n return null;\n }\n\n // Integer part\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n\n // Optional decimal part\n if (pos < input.length && input[pos] === '.') {\n number += input[pos++];\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n }\n\n // Optional duration suffix (s, ms, m, h)\n if (pos < input.length) {\n const suffix = input.slice(pos, pos + 2);\n if (suffix === 'ms') {\n number += 'ms';\n } else if (input[pos] === 's' || input[pos] === 'm' || input[pos] === 'h') {\n number += input[pos];\n }\n }\n\n return number;\n}\n","/**\n * Operator Extractor - Handles programming language operators\n *\n * Extracts operators like +, -, *, /, =, >, <, >=, <=, !=, ===, etc.\n * Supports multi-character operators with longest-match priority.\n */\n\nimport type { ValueExtractor, ExtractionResult } from '../../../interfaces/value-extractor';\n\n/**\n * Default operators for most programming languages.\n * Sorted longest-first for greedy matching.\n */\nexport const DEFAULT_OPERATORS = [\n // Three-character operators\n '===',\n '!==',\n '->',\n // Two-character operators\n '==',\n '!=',\n '<=',\n '>=',\n '&&',\n '||',\n '**',\n '+=',\n '-=',\n '*=',\n '/=',\n // Single-character operators\n '+',\n '-',\n '*',\n '/',\n '=',\n '>',\n '<',\n '!',\n '&',\n '|',\n '%',\n '^',\n '~',\n];\n\n/**\n * OperatorExtractor - Extracts programming language operators.\n */\nexport class OperatorExtractor implements ValueExtractor {\n readonly name = 'operator';\n\n constructor(private operators: string[] = DEFAULT_OPERATORS) {\n // Sort operators longest-first for greedy matching\n this.operators = [...operators].sort((a, b) => b.length - a.length);\n }\n\n canExtract(input: string, position: number): boolean {\n return this.operators.some(op => input.startsWith(op, position));\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n // Find longest matching operator\n for (const op of this.operators) {\n if (input.startsWith(op, position)) {\n return {\n value: op,\n length: op.length,\n };\n }\n }\n\n return null;\n }\n}\n","/**\n * Punctuation Extractor - Handles punctuation characters\n *\n * Extracts punctuation like parentheses, brackets, braces, commas, colons, semicolons.\n * Each character is extracted individually (no multi-character punctuation).\n */\n\nimport type { ValueExtractor, ExtractionResult } from '../../../interfaces/value-extractor';\n\n/**\n * Default punctuation characters for most programming languages.\n */\nexport const DEFAULT_PUNCTUATION = '()[]{},:;';\n\n/**\n * PunctuationExtractor - Extracts punctuation characters.\n */\nexport class PunctuationExtractor implements ValueExtractor {\n readonly name = 'punctuation';\n\n constructor(private punctuation: string = DEFAULT_PUNCTUATION) {}\n\n canExtract(input: string, position: number): boolean {\n return this.punctuation.includes(input[position]);\n }\n\n extract(input: string, position: number): ExtractionResult | null {\n const char = input[position];\n\n if (this.punctuation.includes(char)) {\n return {\n value: char,\n length: 1,\n };\n }\n\n return null;\n }\n}\n","/**\n * Default Extractor Sets\n *\n * Provides pre-configured sets of extractors for common use cases.\n * DSLs can use these as a starting point and add domain-specific extractors.\n */\n\nimport type { ValueExtractor } from '../../interfaces/value-extractor';\nimport {\n StringLiteralExtractor,\n NumberExtractor,\n IdentifierExtractor,\n UnicodeIdentifierExtractor,\n} from '../../interfaces/value-extractor';\nimport { OperatorExtractor, PunctuationExtractor } from './extractors/index';\n\n/**\n * Get default extractors for generic programming-language-style DSLs.\n * These work for most DSLs (SQL, config files, scripts, etc.).\n *\n * Included extractors:\n * - String literals: \"double\", 'single', `backtick`\n * - Numbers: 123, 45.67\n * - Operators: +, -, *, /, =, ==, !=, >=, <=, etc.\n * - Punctuation: ( ) [ ] { } , : ;\n * - Identifiers: variable_names, functionNames\n * - Unicode identifiers: CJK, Arabic, Cyrillic, etc.\n *\n * @returns Array of default extractors\n *\n * @example\n * ```typescript\n * class MyDSLTokenizer extends BaseTokenizer {\n * constructor() {\n * super();\n * this.registerExtractors(getDefaultExtractors());\n * }\n * }\n * ```\n */\nexport function getDefaultExtractors(): ValueExtractor[] {\n return [\n new StringLiteralExtractor(), // \"strings\", 'strings', `strings`\n new NumberExtractor(), // 123, 45.67\n new OperatorExtractor(), // +, -, *, /, =, >, <, etc.\n new PunctuationExtractor(), // ( ) [ ] { } , : ;\n new IdentifierExtractor(), // variable_names, functionNames (ASCII)\n new UnicodeIdentifierExtractor(), // CJK, Arabic, Cyrillic, etc.\n ];\n}\n\n/**\n * Auto-register default extractors in a tokenizer.\n * Convenience helper for chaining.\n *\n * @param tokenizer - Tokenizer to configure\n * @returns The same tokenizer (for chaining)\n *\n * @example\n * ```typescript\n * const tokenizer = withDefaultExtractors(new MyTokenizer());\n * ```\n */\nexport function withDefaultExtractors<\n T extends { registerExtractors(extractors: ValueExtractor[]): void },\n>(tokenizer: T): T {\n tokenizer.registerExtractors(getDefaultExtractors());\n return tokenizer;\n}\n","/**\n * Base Tokenizer Class\n *\n * Abstract base class for language-specific tokenizers.\n * Provides keyword management, morphological normalization,\n * and high-level token extraction methods.\n */\n\nimport type { LanguageToken, TokenKind, TokenStream, LanguageTokenizer } from '../types';\nimport type { MorphologicalNormalizer, NormalizationResult } from './morphology/types';\nimport {\n type ValueExtractor,\n type KeywordEntry,\n isContextAwareExtractor,\n createTokenizerContext,\n} from '../../interfaces/value-extractor';\nimport {\n createToken,\n createPosition,\n isWhitespace,\n isDigit,\n isAsciiIdentifierChar,\n stripOptionalDiacritics,\n TokenStreamImpl,\n type TimeUnitMapping,\n type CreateTokenOptions,\n} from './token-utils';\nimport { extractCssSelector, extractStringLiteral, extractNumber, extractUrl } from './extractors';\nimport { DEFAULT_OPERATORS } from './extractors/operator';\nimport { getDefaultExtractors } from './default-extractors';\n\n// Module-scope operator set for O(1) lookup in createSimpleTokenizer.\n// Uses the canonical list from OperatorExtractor to avoid duplication.\nconst SIMPLE_TOKENIZER_OPERATOR_SET = new Set(DEFAULT_OPERATORS);\n\n/**\n * Normalized concepts that are matched via the pattern matcher's ROLE-MARKER\n * MECHANISM (the source/destination/event clause matchers in\n * `packages/semantic/src/parser/pattern-matcher.ts`), which peeks/advances a\n * SINGLE token and checks `.value`/`.normalized`. A multi-word phrase carrying\n * one of these must NOT be pre-matched as a single keyword token — doing so\n * shadows the single-word marker those clause matchers expect (e.g. id\n * `ke dalam`=into hides the `ke` destination marker; ko `할 때`=eventMarker\n * pre-empts SOV event extraction).\n *\n * NOTE — what is *not* here. Prepositional modifiers that the generated patterns\n * expose as ordinary pattern LITERALS (`before`/`after` in put-before/after,\n * `until` in repeat-until) are deliberately absent: those are read by\n * `matchLiteralToken`, which compares the whole token by exact value OR\n * normalized form (`getMatchType`), so a multi-word marker token (`से पहले`,\n * `cho đến khi`) matches the literal's value/alternatives directly with no\n * special handling. Keeping them out lets `tryMultiWordKeyword` emit them as one\n * token — the profile-driven replacement for the per-language hardcoded compound\n * lists (Task #10). `into` stays excluded because it IS consumed by the role\n * mechanism in some languages (id destination `ke`), and `from`/`to`/`with`/\n * `on`/`at`/`of`/`as`/`by`/`in` are genuine role markers. Command verbs /\n * control-flow / event names were always absent. See `multiWordKeywords` /\n * `tryMultiWordKeyword`.\n */\nconst MARKER_CONCEPT_NORMALIZEDS: ReadonlySet<string> = new Set([\n // Role-marker role names (profile.roleMarkers normalizeds)\n 'patient',\n 'destination',\n 'source',\n 'style',\n 'event',\n 'eventMarker',\n 'agent',\n 'goal',\n 'manner',\n // Prepositional / positional modifier concepts matched via the role mechanism\n // (profile.keywords \"Modifiers\"). `before`/`after`/`until` are intentionally\n // NOT here — they are pattern literals (see the note above).\n 'into',\n 'from',\n 'to',\n 'with',\n 'at',\n 'of',\n 'as',\n 'by',\n 'in',\n 'on',\n 'over',\n 'under',\n 'between',\n 'through',\n 'without',\n]);\n\n/**\n * A hyphen-JOINED keyword surface (`na-żywo`, `ao-vivo`): letters on both sides\n * of every hyphen. A leading/trailing hyphen (qu's `-kama` / `-manta` suffix\n * alternatives) or a bare `-` is not one — those stay with the word walk.\n */\nfunction isHyphenatedWord(native: string): boolean {\n return native.includes('-') && /^[\\p{L}\\p{N}_]+(-[\\p{L}\\p{N}_]+)+$/u.test(native);\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\n// KeywordEntry is imported from interfaces/value-extractor and re-exported\n// for backward compatibility with code importing from this module.\nexport type { KeywordEntry };\n\n/**\n * Standard DOM event names recognized in every language as universal fallbacks.\n * The i18n grammar transformer emits these verbatim (no native dictionary form),\n * so each tokenizer must accept them or English-named event handlers won't parse.\n * Kept to genuine DOM event names (not command verbs) to minimize collisions; the\n * registration is `!has`-guarded so any native keyword of the same spelling wins.\n */\nconst ENGLISH_DOM_EVENT_NAMES: readonly string[] = [\n 'click',\n 'dblclick',\n 'input',\n 'change',\n 'submit',\n 'keydown',\n 'keyup',\n 'keypress',\n 'mousedown',\n 'mouseup',\n 'mouseover',\n 'mouseout',\n 'mouseenter',\n 'mouseleave',\n 'mousemove',\n 'pointerdown',\n 'pointerup',\n 'pointermove',\n 'focus',\n 'blur',\n 'load',\n 'resize',\n 'scroll',\n];\n\n/**\n * Profile interface for keyword derivation.\n * Matches the structure of LanguageProfile but only includes fields needed for tokenization.\n */\nexport interface TokenizerProfile {\n readonly keywords?: Record<\n string,\n { primary: string; alternatives?: string[]; normalized?: string }\n >;\n readonly references?: Record<string, string>;\n readonly roleMarkers?: Record<\n string,\n { primary: string; alternatives?: string[]; position?: string }\n >;\n readonly possessive?: {\n readonly marker: string;\n readonly markerPosition: 'after-object' | 'between' | 'before-property';\n readonly specialForms?: Record<string, string>;\n readonly usePossessiveAdjectives?: boolean;\n readonly keywords?: Record<string, string>;\n };\n}\n\n// =============================================================================\n// Base Tokenizer Class\n// =============================================================================\n\n/**\n * Abstract base class for language-specific tokenizers.\n * Provides common functionality for CSS selectors, strings, and numbers.\n */\nexport abstract class BaseTokenizer implements LanguageTokenizer {\n abstract readonly language: string;\n abstract readonly direction: 'ltr' | 'rtl';\n\n /** Optional morphological normalizer for this language */\n protected normalizer?: MorphologicalNormalizer;\n\n /** Keywords derived from profile, sorted longest-first for greedy matching */\n protected profileKeywords: KeywordEntry[] = [];\n\n /**\n * Space-containing profile keywords (multi-word phrases), longest-first.\n * Used by `tryMultiWordKeyword` so natural spaced forms (hi `मेल खाता`,\n * vi `chuyển đổi`, es `tecla abajo`, …) tokenize as ONE keyword — the\n * profile-driven replacement for the per-language hardcoded compound lists.\n * Empty for no-space (CJK) languages, so they are unaffected.\n */\n protected multiWordKeywords: KeywordEntry[] = [];\n\n /** Map for O(1) keyword lookups by lowercase native word */\n protected profileKeywordMap: Map<string, KeywordEntry> = new Map();\n\n /**\n * The raw EXTRAS list passed to initializeKeywordsFromProfile, kept pre-dedup.\n * The keyword map is keyed by native word with last-wins insertion, so a\n * duplicate native word inside the extras silently shadows the earlier entry\n * (e.g. a `nächste→closest` entry shadowing `nächste→next` broke German\n * positional expressions). Exposed so consistency tests can detect such\n * intra-extras collisions, which are invisible in the deduplicated map.\n */\n private rawExtraEntries: KeywordEntry[] = [];\n\n /** Raw extras as passed in, pre-dedup — for consistency tests. */\n getExtraKeywordEntries(): readonly KeywordEntry[] {\n return this.rawExtraEntries;\n }\n\n /**\n * Pluggable value extractors for domain-specific syntax.\n * When registered, BaseTokenizer will use extractor-based tokenization instead of legacy methods.\n */\n protected extractors: ValueExtractor[] = [];\n\n /**\n * Tokenize input string to token stream.\n * Delegates to extractor-based tokenization if extractors are registered,\n * otherwise subclass must override this method.\n *\n * @param input - Input string to tokenize\n * @returns Token stream\n */\n tokenize(input: string): TokenStream {\n if (this.isUsingExtractors()) {\n return this.tokenizeWithExtractors(input);\n }\n\n // If no extractors registered, subclass must provide implementation\n throw new Error(\n `${this.constructor.name}: tokenize() not implemented and no extractors registered. ` +\n 'Either register extractors or override tokenize() method.'\n );\n }\n\n abstract classifyToken(token: string): TokenKind;\n\n /**\n * Register a value extractor for domain-specific syntax.\n * Extractors are tried in registration order during tokenization.\n * Context-aware extractors automatically receive the tokenizer context.\n *\n * @param extractor - Value extractor to register\n */\n registerExtractor(extractor: ValueExtractor): void {\n if (isContextAwareExtractor(extractor)) {\n extractor.setContext(createTokenizerContext(this as any));\n }\n this.extractors.push(extractor);\n }\n\n /**\n * Register multiple value extractors at once.\n *\n * @param extractors - Array of value extractors to register\n */\n registerExtractors(extractors: ValueExtractor[]): void {\n for (const extractor of extractors) {\n this.registerExtractor(extractor);\n }\n }\n\n /**\n * Clear all registered extractors.\n * Returns tokenizer to legacy mode.\n */\n clearExtractors(): void {\n this.extractors = [];\n }\n\n /**\n * Check if this tokenizer is using extractor-based tokenization.\n * Returns true if any extractors are registered.\n */\n protected isUsingExtractors(): boolean {\n return this.extractors.length > 0;\n }\n\n /**\n * Tokenize input using registered value extractors.\n * This is the new path - extractors handle all syntax detection.\n *\n * @param input - Input string to tokenize\n * @returns Token stream\n */\n protected tokenizeWithExtractors(input: string): TokenStream {\n const tokens: LanguageToken[] = [];\n let pos = 0;\n\n while (pos < input.length) {\n // Skip whitespace\n while (pos < input.length && isWhitespace(input[pos])) {\n pos++;\n }\n if (pos >= input.length) break;\n\n // Multi-word keyword pre-match: a profile keyword containing a space\n // (e.g. hi `मेल खाता`, vi `chuyển đổi`, es `tecla abajo`) is matched as ONE\n // keyword token at a word boundary, longest-first. Runs before the\n // per-language extractors so natural spaced multi-word keywords tokenize\n // without each tokenizer hardcoding a compound list. No-op for single-word\n // and no-space (CJK) languages (multiWordKeywords is empty).\n const multiWord = this.tryMultiWordKeyword(input, pos);\n if (multiWord) {\n tokens.push(multiWord);\n pos = multiWord.position.end;\n continue;\n }\n\n // Try registered extractors in order\n let extracted = false;\n for (const extractor of this.extractors) {\n if (extractor.canExtract(input, pos)) {\n const result = extractor.extract(input, pos);\n if (result) {\n // Promote normalized/stem/stemConfidence from metadata to top-level token options\n const normalized = result.metadata?.normalized as string | undefined;\n const stem = result.metadata?.stem as string | undefined;\n const stemConfidence = result.metadata?.stemConfidence as number | undefined;\n\n // Build clean metadata without promoted fields\n const cleanMetadata: Record<string, unknown> = {};\n if (result.metadata) {\n for (const [key, value] of Object.entries(result.metadata)) {\n if (key !== 'normalized' && key !== 'stem' && key !== 'stemConfidence') {\n cleanMetadata[key] = value;\n }\n }\n }\n\n const options: CreateTokenOptions = {};\n if (normalized) options.normalized = normalized;\n if (stem) options.stem = stem;\n if (stemConfidence !== undefined) options.stemConfidence = stemConfidence;\n if (Object.keys(cleanMetadata).length > 0) options.metadata = cleanMetadata;\n\n tokens.push(\n createToken(\n result.value,\n this.classifyToken(result.value),\n createPosition(pos, pos + result.length),\n Object.keys(options).length > 0 ? options : undefined\n )\n );\n pos += result.length;\n extracted = true;\n break;\n }\n }\n }\n\n // Fallback: single character as operator/punctuation\n if (!extracted) {\n const char = input[pos];\n const kind = this.classifyUnknownChar(char);\n tokens.push(createToken(char, kind, createPosition(pos, pos + 1)));\n pos++;\n }\n }\n\n return new TokenStreamImpl(this.mergeColonQualifiedNames(tokens), this.language);\n }\n\n /**\n * ASCII word of the shape the English word-walker produces. Excludes `:`, so a\n * token that already carries a qualifier never merges again — `a:b:c` yields\n * `a:b` + `:c`, byte-matching the English extractor's single-segment merge.\n */\n private static readonly ASCII_WORD = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n /** `:name` — only a variable-ref-style extractor ever emits this token shape. */\n private static readonly COLON_QUALIFIER = /^:[A-Za-z_][A-Za-z0-9_]*$/;\n\n /**\n * Fuse `name` + `:qualifier` into ONE identifier (`draggable:start`).\n *\n * `:name` is hyperscript's local-variable sigil, but a colon IMMEDIATELY\n * preceded by an identifier is a qualifier (custom event namespace), not a\n * sigil. The English tokenizer already merges these inside\n * EnglishKeywordExtractor; this post-pass gives the other 23 languages the\n * same stream. Strict position adjacency is the discriminator: whitespace\n * between the tokens (`trigger :start`) breaks `end === start`, so a spaced\n * local-variable reference survives untouched.\n *\n * Self-gating for non-hyperscript tokenizers (domain DSLs): their extractor\n * sets tokenize `:` as bare punctuation (length 1), which never matches\n * COLON_QUALIFIER, so this pass is a no-op for them.\n */\n protected mergeColonQualifiedNames(tokens: LanguageToken[]): LanguageToken[] {\n const out: LanguageToken[] = [];\n for (const tok of tokens) {\n const prev = out[out.length - 1];\n // No kind gate: the English extractor merges before classification, so a\n // word some language classifies as particle/keyword (es `a`, tr `i`)\n // must fuse the same way. ASCII_WORD already excludes every non-word\n // kind structurally (selectors, urls, numbers, strings, operators).\n if (\n prev &&\n BaseTokenizer.ASCII_WORD.test(prev.value) &&\n BaseTokenizer.COLON_QUALIFIER.test(tok.value) &&\n prev.position.end === tok.position.start\n ) {\n const merged = prev.value + tok.value;\n // Re-classify and drop normalized/stem/metadata — the merged word is no\n // longer the keyword the pieces may have been (matches the en shape).\n out[out.length - 1] = createToken(\n merged,\n this.classifyToken(merged),\n createPosition(prev.position.start, tok.position.end)\n );\n continue;\n }\n out.push(tok);\n }\n return out;\n }\n\n /**\n * Classify an unknown character when no extractor matches.\n * Provides sensible defaults for common syntax.\n *\n * @param char - Character to classify\n * @returns Token kind\n */\n protected classifyUnknownChar(char: string): TokenKind {\n if ('()[]{},:;'.includes(char)) return 'punctuation';\n if ('+-*/<>=!&|'.includes(char)) return 'operator';\n return 'identifier';\n }\n\n /**\n * Check if current position is a property access (obj.prop) vs CSS selector (.active).\n * Property access: no whitespace before '.', previous token is identifier/keyword/selector.\n * Also detects standalone method calls: .identifier( pattern.\n *\n * Returns true if '.' was emitted as an operator token and pos should advance by 1.\n * Returns false if this is a CSS selector and should be handled by trySelector().\n */\n protected tryPropertyAccess(input: string, pos: number, tokens: LanguageToken[]): boolean {\n if (input[pos] !== '.') return false;\n\n const lastToken = tokens[tokens.length - 1];\n // Property access requires NO whitespace between tokens (e.g., \"obj.prop\")\n const hasWhitespaceBefore = lastToken && lastToken.position.end < pos;\n const isPropertyAccess =\n lastToken &&\n !hasWhitespaceBefore &&\n (lastToken.kind === 'identifier' ||\n lastToken.kind === 'keyword' ||\n lastToken.kind === 'selector');\n\n if (isPropertyAccess) {\n tokens.push(createToken('.', 'operator', createPosition(pos, pos + 1)));\n return true;\n }\n\n // Check for method call pattern at start: .identifier(\n const methodStart = pos + 1;\n let methodEnd = methodStart;\n while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {\n methodEnd++;\n }\n if (methodEnd < input.length && input[methodEnd] === '(') {\n tokens.push(createToken('.', 'operator', createPosition(pos, pos + 1)));\n return true;\n }\n\n return false;\n }\n\n /**\n * Initialize keyword mappings from a language profile.\n * Builds a list of native→english mappings from:\n * - profile.keywords (primary + alternatives)\n * - profile.references (me, it, you, etc.)\n * - profile.roleMarkers (into, from, with, etc.)\n *\n * Results are sorted longest-first for greedy matching (important for non-space languages).\n * Extras take precedence over profile entries when there are duplicates.\n *\n * @param profile - Language profile containing keyword translations\n * @param extras - Additional keyword entries to include (literals, positional, events)\n */\n protected initializeKeywordsFromProfile(\n profile: TokenizerProfile,\n extras: KeywordEntry[] = []\n ): void {\n // Use a Map to deduplicate, with extras taking precedence\n const keywordMap = new Map<string, KeywordEntry>();\n this.rawExtraEntries = extras;\n\n // Extract from keywords (command translations)\n if (profile.keywords) {\n for (const [normalized, translation] of Object.entries(profile.keywords)) {\n // Primary translation\n keywordMap.set(translation.primary, {\n native: translation.primary,\n normalized: translation.normalized || normalized,\n });\n\n // Alternative forms\n if (translation.alternatives) {\n for (const alt of translation.alternatives) {\n keywordMap.set(alt, {\n native: alt,\n normalized: translation.normalized || normalized,\n });\n }\n }\n }\n }\n\n // Extract from references (me, it, you, etc.)\n if (profile.references) {\n for (const [normalized, native] of Object.entries(profile.references)) {\n keywordMap.set(native, { native, normalized });\n }\n // Also register English canonical forms as universal fallbacks.\n // Users frequently mix English references (me, it, you) into non-English\n // hyperscript (e.g., \"alternar .active on me\"). Without this, the English\n // word \"me\" would be unrecognized in non-English token streams.\n for (const canonical of Object.keys(profile.references)) {\n if (!keywordMap.has(canonical)) {\n keywordMap.set(canonical, { native: canonical, normalized: canonical });\n }\n }\n }\n\n // Extract from roleMarkers (into, from, with, etc.)\n if (profile.roleMarkers) {\n for (const [role, marker] of Object.entries(profile.roleMarkers)) {\n if (marker.primary) {\n keywordMap.set(marker.primary, { native: marker.primary, normalized: role });\n }\n if (marker.alternatives) {\n for (const alt of marker.alternatives) {\n keywordMap.set(alt, { native: alt, normalized: role });\n }\n }\n }\n }\n\n // Extract from possessive keywords (e.g., ñuqapa, qampa for Quechua)\n if (profile.possessive?.keywords) {\n for (const [native, normalized] of Object.entries(profile.possessive.keywords)) {\n keywordMap.set(native, { native, normalized });\n }\n }\n\n // Register English DOM event names as universal fallbacks. The i18n grammar\n // transformer has no native form for most DOM events, so it passes them\n // through verbatim (`on keyup …` → `<on-marker> keyup …`). Without these,\n // non-English token streams treat `keyup`/`keydown`/`resize`/… as bare\n // identifiers, and event handlers using them (often with `[key==…]` guards)\n // fail to parse. Guarded by `!has` so any native mapping wins (same policy\n // as the English-reference fallbacks above). Generalizes the per-language\n // registration introduced for Hebrew in #272.\n for (const evt of ENGLISH_DOM_EVENT_NAMES) {\n if (!keywordMap.has(evt)) {\n keywordMap.set(evt, { native: evt, normalized: evt });\n }\n }\n\n // Add extra entries (literals, positional, events) - these OVERRIDE profile entries\n for (const extra of extras) {\n keywordMap.set(extra.native, extra);\n }\n\n // Convert to array and sort longest-first for greedy matching\n this.profileKeywords = Array.from(keywordMap.values()).sort(\n (a, b) => b.native.length - a.native.length\n );\n\n // Multi-word keywords — space-containing (hi `मेल खाता`, vi `chuyển đổi`)\n // or HYPHENATED (pl `na-żywo`, pt `ao-vivo`, fr `point-arrêt`) — for\n // longest-phrase matching at a token boundary. Already longest-first\n // (profileKeywords is sorted above). Hyphenated ones were left to the word\n // walk, which stops at the `-` and hands the parts to whatever they happen\n // to be: pl `na-żywo` (live) read as `na`(→destination) + `-` + `żywo`, so\n // every pl `live … koniec` render parsed back as a handler with the `live`\n // action gone; es `en-vivo` / pt `ao-vivo` survived only because their\n // second half is a `live` alternative.\n // Marker/modifier concepts are EXCLUDED: those are matched positionally by\n // the pattern matcher (role markers), and greedily consuming a multi-word\n // marker phrase shadows the single-word marker patterns rely on — e.g. id\n // `ke dalam` (into) would swallow the `ke` destination marker, and ko `할 때`\n // (eventMarker) would pre-empt the SOV event extraction. Command verbs,\n // control-flow, and event-name keywords (vi `với mỗi`=for, es `tecla abajo`=\n // keydown, bn `তৈরি করুন`=make) are kept — the pattern matcher treats those\n // as keyword literals, so one-token matching is strictly better.\n this.multiWordKeywords = this.profileKeywords.filter(\n k =>\n (k.native.includes(' ') || isHyphenatedWord(k.native)) &&\n !MARKER_CONCEPT_NORMALIZEDS.has(k.normalized)\n );\n\n // Build Map for O(1) lookups (case-insensitive + diacritic-insensitive)\n // This allows matching both 'بدّل' (with shadda) and 'بدل' (without) to the same entry\n this.profileKeywordMap = new Map();\n for (const keyword of this.profileKeywords) {\n // Add original form (with diacritics if present)\n this.profileKeywordMap.set(keyword.native.toLowerCase(), keyword);\n\n // Add diacritic-normalized form (for Arabic, Turkish, etc.)\n const normalized = this.removeDiacritics(keyword.native);\n if (normalized !== keyword.native && !this.profileKeywordMap.has(normalized.toLowerCase())) {\n this.profileKeywordMap.set(normalized.toLowerCase(), keyword);\n }\n }\n }\n\n /**\n * Remove diacritical marks from a word for normalization.\n * Primarily for Arabic (shadda, fatha, kasra, damma, sukun, etc.)\n * but could be extended for other languages.\n *\n * @param word - Word to normalize\n * @returns Word without diacritics\n */\n protected removeDiacritics(word: string): string {\n return stripOptionalDiacritics(word);\n }\n\n /**\n * Try to match a keyword from profile at the current position.\n * Uses longest-first greedy matching (important for non-space languages).\n *\n * @param input - Input string\n * @param pos - Current position\n * @returns Token if matched, null otherwise\n */\n protected tryProfileKeyword(input: string, pos: number): LanguageToken | null {\n for (const entry of this.profileKeywords) {\n if (input.slice(pos).startsWith(entry.native)) {\n return createToken(\n entry.native,\n 'keyword',\n createPosition(pos, pos + entry.native.length),\n entry.normalized\n );\n }\n }\n return null;\n }\n\n /**\n * Match the longest multi-word (space-containing) profile keyword at `pos`,\n * requiring the match to end at a word boundary. The profile-driven\n * counterpart of the per-language hardcoded compound lists (the hindi and\n * vietnamese keyword extractors). Returns a keyword token (with the normalized\n * form) or null. Case-sensitive against the stored native form, mirroring\n * `tryProfileKeyword`/`isKeywordStart` (the i18n dicts emit a fixed surface\n * case). No-op when `multiWordKeywords` is empty (no-space/CJK languages).\n *\n * @param input - Input string\n * @param pos - Current position (must be a token-start boundary)\n * @param isWordChar - End-boundary predicate (defaults to Unicode letter/digit/_)\n */\n protected tryMultiWordKeyword(\n input: string,\n pos: number,\n isWordChar: (char: string) => boolean = ch => /[\\p{L}\\p{N}_]/u.test(ch)\n ): LanguageToken | null {\n if (this.multiWordKeywords.length === 0) return null;\n const rest = input.slice(pos);\n for (const entry of this.multiWordKeywords) {\n if (!rest.startsWith(entry.native)) continue;\n const after = input[pos + entry.native.length];\n if (after !== undefined && isWordChar(after)) continue; // not a word boundary\n return createToken(\n entry.native,\n 'keyword',\n createPosition(pos, pos + entry.native.length),\n entry.normalized\n );\n }\n return null;\n }\n\n /**\n * Check if the remaining input starts with any known keyword.\n * Useful for non-space languages to detect word boundaries.\n *\n * @param input - Input string\n * @param pos - Current position\n * @returns true if a keyword starts at this position\n */\n protected isKeywordStart(input: string, pos: number): boolean {\n const remaining = input.slice(pos);\n return this.profileKeywords.some(entry => remaining.startsWith(entry.native));\n }\n\n /**\n * Check if a known keyword starts at the given position AND ends at a word\n * boundary (end of input or a non-word character).\n *\n * Space-delimited languages must use this (not `isKeywordStart`) for\n * word-walk break checks: the keyword table includes English canonical\n * fallbacks (me, it, you, …), so a raw `startsWith` check splits any native\n * word with an embedded fallback mid-word (e.g. Quechua ñit'iy contains\n * \"it\"). CJK/no-space tokenizers rely on mid-text keyword starts and must\n * keep using `isKeywordStart`.\n *\n * @param input - Input string\n * @param pos - Current position\n * @param isWordChar - Language-specific word-character predicate; pass the\n * tokenizer's letter classifier so e.g. the Quechua glottal apostrophe\n * counts as part of a word. Defaults to Unicode letters/digits/underscore.\n * @returns true if a keyword starts here and is not followed by a word char\n */\n protected isKeywordStartAtBoundary(\n input: string,\n pos: number,\n isWordChar: (char: string) => boolean = ch => /[\\p{L}\\p{N}_]/u.test(ch)\n ): boolean {\n const remaining = input.slice(pos);\n return this.profileKeywords.some(entry => {\n if (!remaining.startsWith(entry.native)) return false;\n const after = input[pos + entry.native.length];\n return after === undefined || !isWordChar(after);\n });\n }\n\n /**\n * Look up a keyword by native word (case-insensitive, diacritic-insensitive).\n * O(1) lookup using the keyword map.\n *\n * The map is INDEXED both with and without diacritics (see\n * `initializeKeywordsFromProfile`), so a stripped QUERY is the other half of\n * that: it lets a surface form carrying harakat the profile does not happen to\n * spell still find its entry. Only consulted after the exact lookup misses, so\n * every previously-matching word resolves byte-identically.\n *\n * Half-implementing this — indexing stripped but querying exact — is what made\n * diacritized `بَدِّل` (toggle) tokenize as `kind=particle normalized=with`:\n * `isKeyword` returned false, so the guard in `ArabicProcliticExtractor` that\n * exists to prevent exactly that handed the word on, and the single-char `ب`\n * bi- proclitic claimed it. A wrong CONCEPT, not a failed parse.\n *\n * @param native - Native word to look up\n * @returns KeywordEntry if found, undefined otherwise\n */\n protected lookupKeyword(native: string): KeywordEntry | undefined {\n const exact = this.profileKeywordMap.get(native.toLowerCase());\n if (exact) return exact;\n const stripped = this.removeDiacritics(native);\n if (stripped === native) return undefined;\n return this.profileKeywordMap.get(stripped.toLowerCase());\n }\n\n /**\n * Check if a word is a known keyword (case-insensitive, diacritic-insensitive).\n * O(1) lookup using the keyword map. See {@link lookupKeyword}.\n *\n * @param native - Native word to check\n * @returns true if the word is a keyword\n */\n protected isKeyword(native: string): boolean {\n return this.lookupKeyword(native) !== undefined;\n }\n\n /**\n * Set the morphological normalizer for this tokenizer.\n */\n setNormalizer(normalizer: MorphologicalNormalizer): void {\n this.normalizer = normalizer;\n }\n\n /**\n * Try to normalize a word using the morphological normalizer.\n * Returns null if no normalizer is set or normalization fails.\n *\n * Note: We don't check isNormalizable() here because the individual tokenizers\n * historically called normalize() directly without that check. The normalize()\n * method itself handles returning noChange() for words that can't be normalized.\n */\n protected tryNormalize(word: string): NormalizationResult | null {\n if (!this.normalizer) return null;\n\n const result = this.normalizer.normalize(word);\n\n // Only return if actually normalized (stem differs from input)\n if (result.stem !== word && result.confidence >= 0.7) {\n return result;\n }\n\n return null;\n }\n\n /**\n * Try morphological normalization and keyword lookup.\n *\n * If the word can be normalized to a stem that matches a known keyword,\n * returns a keyword token with morphological metadata (stem, stemConfidence).\n *\n * This is the common pattern for handling conjugated verbs across languages:\n * 1. Normalize the word (e.g., \"toggled\" → \"toggle\")\n * 2. Look up the stem in the keyword map\n * 3. Create a token with both the original form and stem metadata\n *\n * @param word - The word to normalize and look up\n * @param startPos - Start position for the token\n * @param endPos - End position for the token\n * @returns Token if stem matches a keyword, null otherwise\n */\n protected tryMorphKeywordMatch(\n word: string,\n startPos: number,\n endPos: number\n ): LanguageToken | null {\n const result = this.tryNormalize(word);\n if (!result) return null;\n\n // Check if the stem is a known keyword\n const stemEntry = this.lookupKeyword(result.stem);\n if (!stemEntry) return null;\n\n const tokenOptions: CreateTokenOptions = {\n normalized: stemEntry.normalized,\n stem: result.stem,\n stemConfidence: result.confidence,\n };\n return createToken(word, 'keyword', createPosition(startPos, endPos), tokenOptions);\n }\n\n /**\n * Try to extract a CSS selector at the current position.\n */\n protected trySelector(input: string, pos: number): LanguageToken | null {\n const selector = extractCssSelector(input, pos);\n if (selector) {\n return createToken(selector, 'selector', createPosition(pos, pos + selector.length));\n }\n return null;\n }\n\n /**\n * Try to extract an event modifier at the current position.\n * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)\n */\n protected tryEventModifier(input: string, pos: number): LanguageToken | null {\n // Must start with a dot\n if (input[pos] !== '.') {\n return null;\n }\n\n // Match pattern: .(once|debounce|throttle|queue) followed by optional (value)\n const match = input\n .slice(pos)\n .match(/^\\.(?:once|debounce|throttle|queue)(?:\\(([^)]+)\\))?(?:\\s|$|\\.)/);\n if (!match) {\n return null;\n }\n\n const fullMatch = match[0].replace(/(\\s|\\.)$/, ''); // Remove trailing space or dot\n const modifierName = fullMatch.slice(1).split('(')[0]; // Extract modifier name\n const value = match[1]; // Extract value from parentheses if present\n\n // Create token with metadata\n const token = createToken(\n fullMatch,\n 'event-modifier',\n createPosition(pos, pos + fullMatch.length)\n );\n\n // Add metadata for the modifier\n return {\n ...token,\n metadata: {\n modifierName,\n value: value ? (modifierName === 'queue' ? value : parseInt(value, 10)) : undefined,\n },\n };\n }\n\n /**\n * Try to extract a string literal at the current position.\n */\n protected tryString(input: string, pos: number): LanguageToken | null {\n const literal = extractStringLiteral(input, pos);\n if (literal) {\n return createToken(literal, 'literal', createPosition(pos, pos + literal.length));\n }\n return null;\n }\n\n /**\n * Try to extract a number at the current position.\n */\n protected tryNumber(input: string, pos: number): LanguageToken | null {\n const number = extractNumber(input, pos);\n if (number) {\n return createToken(number, 'literal', createPosition(pos, pos + number.length));\n }\n return null;\n }\n\n /**\n * Configuration for native language time units.\n * Maps patterns to their standard suffix (ms, s, m, h).\n */\n protected static readonly STANDARD_TIME_UNITS: readonly TimeUnitMapping[] = [\n { pattern: 'ms', suffix: 'ms', length: 2 },\n { pattern: 's', suffix: 's', length: 1, checkBoundary: true },\n { pattern: 'm', suffix: 'm', length: 1, checkBoundary: true, notFollowedBy: 's' },\n { pattern: 'h', suffix: 'h', length: 1, checkBoundary: true },\n ];\n\n /**\n * Try to match a time unit from a list of patterns.\n *\n * @param input - Input string\n * @param pos - Position after the number\n * @param timeUnits - Array of time unit mappings (native pattern → standard suffix)\n * @param skipWhitespace - Whether to skip whitespace before time unit (default: false)\n * @returns Object with matched suffix and new position, or null if no match\n */\n protected tryMatchTimeUnit(\n input: string,\n pos: number,\n timeUnits: readonly TimeUnitMapping[],\n skipWhitespace = false\n ): { suffix: string; endPos: number } | null {\n let unitPos = pos;\n\n // Optionally skip whitespace before time unit\n if (skipWhitespace) {\n while (unitPos < input.length && isWhitespace(input[unitPos])) {\n unitPos++;\n }\n }\n\n const remaining = input.slice(unitPos);\n\n // Check each time unit pattern\n for (const unit of timeUnits) {\n const candidate = remaining.slice(0, unit.length);\n const matches = unit.caseInsensitive\n ? candidate.toLowerCase() === unit.pattern.toLowerCase()\n : candidate === unit.pattern;\n\n if (matches) {\n // Check notFollowedBy constraint (e.g., 'm' should not match 'ms')\n if (unit.notFollowedBy) {\n const nextChar = remaining[unit.length] || '';\n if (nextChar === unit.notFollowedBy) continue;\n }\n\n // Check word boundary if required\n if (unit.checkBoundary) {\n const nextChar = remaining[unit.length] || '';\n if (isAsciiIdentifierChar(nextChar)) continue;\n }\n\n return { suffix: unit.suffix, endPos: unitPos + unit.length };\n }\n }\n\n return null;\n }\n\n /**\n * Parse a base number (sign, integer, decimal) without time units.\n * Returns the number string and end position.\n *\n * @param input - Input string\n * @param startPos - Start position\n * @param allowSign - Whether to allow +/- sign (default: true)\n * @returns Object with number string and end position, or null\n */\n protected parseBaseNumber(\n input: string,\n startPos: number,\n allowSign = true\n ): { number: string; endPos: number } | null {\n let pos = startPos;\n let number = '';\n\n // Optional sign\n if (allowSign && (input[pos] === '-' || input[pos] === '+')) {\n number += input[pos++];\n }\n\n // Must have at least one digit\n if (pos >= input.length || !isDigit(input[pos])) {\n return null;\n }\n\n // Integer part\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n\n // Optional decimal\n if (pos < input.length && input[pos] === '.') {\n number += input[pos++];\n while (pos < input.length && isDigit(input[pos])) {\n number += input[pos++];\n }\n }\n\n if (!number || number === '-' || number === '+') return null;\n\n return { number, endPos: pos };\n }\n\n /**\n * Try to extract a number with native language time units.\n *\n * This is a template method that handles the common pattern:\n * 1. Parse the base number (sign, integer, decimal)\n * 2. Try to match native language time units\n * 3. Fall back to standard time units (ms, s, m, h)\n *\n * @param input - Input string\n * @param pos - Start position\n * @param nativeTimeUnits - Language-specific time unit mappings\n * @param options - Configuration options\n * @returns Token if number found, null otherwise\n */\n protected tryNumberWithTimeUnits(\n input: string,\n pos: number,\n nativeTimeUnits: readonly TimeUnitMapping[],\n options: { allowSign?: boolean; skipWhitespace?: boolean } = {}\n ): LanguageToken | null {\n const { allowSign = true, skipWhitespace = false } = options;\n\n // Parse base number\n const baseResult = this.parseBaseNumber(input, pos, allowSign);\n if (!baseResult) return null;\n\n let { number, endPos } = baseResult;\n\n // Try native time units first, then standard\n const allUnits = [...nativeTimeUnits, ...BaseTokenizer.STANDARD_TIME_UNITS];\n const timeMatch = this.tryMatchTimeUnit(input, endPos, allUnits, skipWhitespace);\n\n if (timeMatch) {\n number += timeMatch.suffix;\n endPos = timeMatch.endPos;\n }\n\n return createToken(number, 'literal', createPosition(pos, endPos));\n }\n\n /**\n * Try to extract a URL at the current position.\n * Handles /path, ./path, ../path, //domain.com, http://, https://\n */\n protected tryUrl(input: string, pos: number): LanguageToken | null {\n const url = extractUrl(input, pos);\n if (url) {\n return createToken(url, 'url', createPosition(pos, pos + url.length));\n }\n return null;\n }\n\n /**\n * Try to extract a variable reference (:varname) at the current position.\n * In hyperscript, :x refers to a local variable named x.\n */\n protected tryVariableRef(input: string, pos: number): LanguageToken | null {\n if (input[pos] !== ':') return null;\n if (pos + 1 >= input.length) return null;\n if (!isAsciiIdentifierChar(input[pos + 1])) return null;\n\n let endPos = pos + 1;\n while (endPos < input.length && isAsciiIdentifierChar(input[endPos])) {\n endPos++;\n }\n\n const varRef = input.slice(pos, endPos);\n return createToken(varRef, 'identifier', createPosition(pos, endPos));\n }\n\n /**\n * Try to extract an operator or punctuation token at the current position.\n * Handles two-character operators (==, !=, etc.) and single-character operators.\n */\n protected tryOperator(input: string, pos: number): LanguageToken | null {\n // Two-character operators\n const twoChar = input.slice(pos, pos + 2);\n if (['==', '!=', '<=', '>=', '&&', '||', '->'].includes(twoChar)) {\n return createToken(twoChar, 'operator', createPosition(pos, pos + 2));\n }\n\n // Single-character operators\n const oneChar = input[pos];\n if (['<', '>', '!', '+', '-', '*', '/', '='].includes(oneChar)) {\n return createToken(oneChar, 'operator', createPosition(pos, pos + 1));\n }\n\n // Punctuation\n if (['(', ')', '{', '}', ',', ';', ':'].includes(oneChar)) {\n return createToken(oneChar, 'punctuation', createPosition(pos, pos + 1));\n }\n\n return null;\n }\n\n /**\n * Try to match a multi-character particle from a list.\n *\n * Used by languages like Japanese, Korean, and Chinese that have\n * multi-character particles (e.g., Japanese から, まで, より).\n *\n * @param input - Input string\n * @param pos - Current position\n * @param particles - Array of multi-character particles to match\n * @returns Token if matched, null otherwise\n */\n protected tryMultiCharParticle(\n input: string,\n pos: number,\n particles: readonly string[]\n ): LanguageToken | null {\n for (const particle of particles) {\n if (input.slice(pos, pos + particle.length) === particle) {\n return createToken(particle, 'particle', createPosition(pos, pos + particle.length));\n }\n }\n return null;\n }\n}\n\n// =============================================================================\n// Simple Tokenizer Factory\n// =============================================================================\n\n/**\n * Configuration for createSimpleTokenizer.\n *\n * Creates a tokenizer from declarative config instead of a class definition.\n * Covers the common pattern used by domain packages (SQL, BDD, JSX).\n *\n * **Keyword resolution** uses two additive paths:\n * 1. `keywords` — explicit list, checked first. Respects `caseInsensitive`.\n * 2. `keywordProfile` — populates BaseTokenizer's profile keyword map via\n * `initializeKeywordsFromProfile()`. Checked second via `isKeyword()`, which\n * always lowercases (harmless for CJK/Arabic; notable for Latin scripts\n * with `caseInsensitive: false`). Provides normalization metadata for\n * non-Latin scripts.\n */\nexport interface SimpleTokenizerConfig {\n /** ISO 639-1 language code */\n language: string;\n /** Text direction (default: 'ltr') */\n direction?: 'ltr' | 'rtl';\n /** Keywords to recognize (lowercased for lookup if caseInsensitive) */\n keywords: string[];\n /** Extra keyword entries for non-Latin normalization */\n keywordExtras?: KeywordEntry[];\n /** Profile for initializeKeywordsFromProfile (for non-Latin scripts) */\n keywordProfile?: TokenizerProfile;\n /** Include operator classification (default: false). Uses DEFAULT_OPERATORS from OperatorExtractor. */\n includeOperators?: boolean;\n /** Case-insensitive keyword matching (default: true) */\n caseInsensitive?: boolean;\n /** Custom extractors registered BEFORE default extractors */\n customExtractors?: ValueExtractor[];\n}\n\n/**\n * Create a tokenizer from declarative configuration.\n *\n * Eliminates the boilerplate of extending BaseTokenizer for simple domain tokenizers.\n * Handles keyword classification, optional operator support, and non-Latin keyword setup.\n *\n * @example\n * ```typescript\n * const englishSQL = createSimpleTokenizer({\n * language: 'en',\n * keywords: ['select', 'insert', 'update', 'delete', 'from', 'into', 'where', 'set', 'values'],\n * includeOperators: true,\n * caseInsensitive: true,\n * });\n * ```\n */\nexport function createSimpleTokenizer(config: SimpleTokenizerConfig): LanguageTokenizer {\n const {\n language,\n direction = 'ltr',\n keywords,\n keywordExtras,\n keywordProfile,\n includeOperators = false,\n caseInsensitive = true,\n customExtractors,\n } = config;\n\n const keywordSet = new Set(caseInsensitive ? keywords.map(k => k.toLowerCase()) : keywords);\n\n class SimpleTokenizer extends BaseTokenizer {\n readonly language = language;\n readonly direction = direction;\n\n constructor() {\n super();\n if (customExtractors) {\n this.registerExtractors(customExtractors);\n }\n this.registerExtractors(getDefaultExtractors());\n if (keywordProfile) {\n this.initializeKeywordsFromProfile(keywordProfile, keywordExtras);\n }\n }\n\n classifyToken(token: string): TokenKind {\n // Fast path: explicit keywords from config (respects caseInsensitive)\n const lookup = caseInsensitive ? token.toLowerCase() : token;\n if (keywordSet.has(lookup)) return 'keyword';\n // Profile path: non-Latin normalization (always lowercases via profileKeywordMap)\n if (this.isKeyword(token)) return 'keyword';\n if (/^\\d/.test(token)) return 'literal';\n if (/^['\"]/.test(token)) return 'literal';\n if (includeOperators && SIMPLE_TOKENIZER_OPERATOR_SET.has(token)) return 'operator';\n return 'identifier';\n }\n }\n\n return new SimpleTokenizer();\n}\n","/**\n * Framework ↔ Semantic bridge builders.\n *\n * Pure functions that combine an injected {@link GrammarProfileSlice} (the\n * per-language grammar facts, typically a `@lokascript/semantic`\n * `LanguageProfile`) with a {@link DomainVocabulary} (the only thing a domain\n * authors per language) into the shapes `createMultilingualDSL` consumes:\n * a `PatternGenLanguageProfile`, a `LanguageTokenizer`, or a complete\n * `LanguageConfig`.\n */\n\nimport type { LanguageTokenizer } from '../core/types';\nimport type { PatternGenLanguageProfile } from '../generation/pattern-generator';\nimport type { LanguageConfig } from '../api/create-dsl';\nimport type { LanguageProfile as GrammarProfile } from '../grammar';\nimport { createSimpleTokenizer, type TokenizerProfile } from '../core/tokenization/base-tokenizer';\nimport {\n LatinExtendedIdentifierExtractor,\n type ValueExtractor,\n} from '../interfaces/value-extractor';\nimport type { DomainVocabulary, GrammarProfileSlice, RoleMarkerSlice } from './types';\n\n/** Mutable role-marker shape shared by PatternGenLanguageProfile and TokenizerProfile. */\ntype MergedRoleMarker = { primary: string; alternatives?: string[]; position?: 'before' | 'after' };\n\n/**\n * Merge the slice's language-default role markers with the vocabulary's\n * domain-specific overrides (vocabulary wins). Empty-string primaries are\n * dropped — an empty override means \"bare positional arg, no marker\".\n */\nfunction mergeRoleMarkers(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary\n): Record<string, MergedRoleMarker> {\n const merged: Record<string, MergedRoleMarker> = {};\n const add = (role: string, marker: RoleMarkerSlice | undefined) => {\n if (!marker?.primary) {\n delete merged[role];\n return;\n }\n merged[role] = {\n primary: marker.primary,\n ...(marker.alternatives?.length && { alternatives: [...marker.alternatives] }),\n ...(marker.position && { position: marker.position }),\n };\n };\n for (const [role, marker] of Object.entries(slice.roleMarkers ?? {})) add(role, marker);\n for (const [role, marker] of Object.entries(vocab.roleMarkerOverrides ?? {})) add(role, marker);\n return merged;\n}\n\n/**\n * Build a pattern-generation profile: domain keywords + slice grammar\n * (word order, role markers). The result feeds `generatePattern` /\n * `generatePatternVariants` and `LanguageConfig.patternProfile`.\n */\nexport function buildPatternProfile(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary\n): PatternGenLanguageProfile {\n const keywords: Record<string, { primary: string; alternatives?: string[] }> = {};\n for (const [action, translation] of Object.entries(vocab.keywords)) {\n keywords[action] = {\n primary: translation.primary,\n ...(translation.alternatives?.length && { alternatives: [...translation.alternatives] }),\n };\n }\n\n const roleMarkers = mergeRoleMarkers(slice, vocab);\n\n return {\n code: slice.code,\n wordOrder: slice.wordOrder,\n keywords,\n ...(Object.keys(roleMarkers).length > 0 && { roleMarkers }),\n };\n}\n\n/** Options for {@link buildDomainTokenizer}, overriding the slice-derived defaults. */\nexport interface DomainTokenizerOptions {\n /**\n * Recognize operator tokens (default: false, matching `createSimpleTokenizer`).\n * Domains whose grammar contains operators (e.g. SQL's `WHERE age > 18`) pass\n * `true`; most natural-language DSLs leave it off.\n */\n readonly includeOperators?: boolean;\n /**\n * Case-insensitive keyword matching. Defaults to true for bicameral scripts\n * (`latin`, `cyrillic`, or when the slice omits `script`), false otherwise.\n */\n readonly caseInsensitive?: boolean;\n /** Extra extractors, registered before the slice-derived ones */\n readonly customExtractors?: readonly ValueExtractor[];\n}\n\nfunction defaultCaseInsensitive(script: string | undefined): boolean {\n return script === undefined || script === 'latin' || script === 'cyrillic';\n}\n\n/**\n * Build a domain tokenizer from a grammar slice + domain vocabulary, wrapping\n * `createSimpleTokenizer`. Derived from the slice:\n *\n * - `direction` (rtl for e.g. Arabic/Hebrew slices)\n * - keyword set: vocabulary verbs (primary + alternatives), role markers\n * (slice defaults merged with `vocab.roleMarkerOverrides`), tokenization\n * particles, and `vocab.tokenizerKeywords`\n * - keyword-normalization profile (native verb → action name, marker → role)\n * - a `LatinExtendedIdentifierExtractor` when `slice.script === 'latin'`, so\n * diacritics (ñ, é, ş, …) never split identifiers\n * - case-insensitivity for bicameral scripts\n */\nexport function buildDomainTokenizer(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary,\n options: DomainTokenizerOptions = {}\n): LanguageTokenizer {\n const roleMarkers = mergeRoleMarkers(slice, vocab);\n\n // Flat keyword list for token classification.\n const keywords = new Set<string>();\n for (const translation of Object.values(vocab.keywords)) {\n keywords.add(translation.primary);\n for (const alt of translation.alternatives ?? []) keywords.add(alt);\n }\n for (const marker of Object.values(roleMarkers)) {\n keywords.add(marker.primary);\n for (const alt of marker.alternatives ?? []) keywords.add(alt);\n }\n for (const particle of slice.tokenization?.particles ?? []) keywords.add(particle);\n for (const extra of vocab.tokenizerKeywords ?? []) keywords.add(extra);\n\n // Normalization profile: native verb forms → action names, markers → roles.\n const profileKeywords: NonNullable<TokenizerProfile['keywords']> = {};\n for (const [action, translation] of Object.entries(vocab.keywords)) {\n profileKeywords[action] = {\n primary: translation.primary,\n ...(translation.alternatives?.length && { alternatives: [...translation.alternatives] }),\n normalized: translation.normalized ?? action,\n };\n }\n const keywordProfile: TokenizerProfile = {\n keywords: profileKeywords,\n ...(Object.keys(roleMarkers).length > 0 && { roleMarkers }),\n };\n\n const customExtractors: ValueExtractor[] = [\n ...(options.customExtractors ?? []),\n ...(slice.script === 'latin' ? [new LatinExtendedIdentifierExtractor()] : []),\n ];\n\n return createSimpleTokenizer({\n language: slice.code,\n direction: slice.direction ?? 'ltr',\n keywords: [...keywords],\n ...(vocab.keywordExtras?.length && { keywordExtras: vocab.keywordExtras.map(e => ({ ...e })) }),\n keywordProfile,\n includeOperators: options.includeOperators ?? false,\n caseInsensitive: options.caseInsensitive ?? defaultCaseInsensitive(slice.script),\n ...(customExtractors.length > 0 && { customExtractors }),\n });\n}\n\n/** Metadata / overrides for {@link buildLanguageConfig}. */\nexport interface LanguageConfigMeta {\n /** English name (default: `slice.name`, falling back to `slice.code`) */\n readonly name?: string;\n /** Native name (default: `slice.nativeName`, falling back to the English name) */\n readonly nativeName?: string;\n /** Grammar-transformation profile to attach (optional, as on `LanguageConfig`) */\n readonly grammarProfile?: GrammarProfile;\n /** Use this tokenizer instead of the slice-derived one */\n readonly tokenizer?: LanguageTokenizer;\n /** Options for the slice-derived tokenizer (ignored when `tokenizer` is given) */\n readonly tokenizerOptions?: DomainTokenizerOptions;\n}\n\n/**\n * The one-call path into `createMultilingualDSL`: build a complete\n * `LanguageConfig` (tokenizer + pattern profile + names) from a grammar slice\n * and a domain vocabulary.\n */\nexport function buildLanguageConfig(\n slice: GrammarProfileSlice,\n vocab: DomainVocabulary,\n meta: LanguageConfigMeta = {}\n): LanguageConfig {\n const name = meta.name ?? slice.name ?? slice.code;\n return {\n code: slice.code,\n name,\n nativeName: meta.nativeName ?? slice.nativeName ?? name,\n tokenizer: meta.tokenizer ?? buildDomainTokenizer(slice, vocab, meta.tokenizerOptions),\n patternProfile: buildPatternProfile(slice, vocab),\n ...(meta.grammarProfile && { grammarProfile: meta.grammarProfile }),\n };\n}\n\n/**\n * Derive schema `markerOverride` defaults for ONE language from the slice's\n * role markers, given a domain-role → semantic-role mapping. Returns\n * `{ domainRole: primaryMarker }` with entries only where the slice has a\n * marker for the mapped semantic role.\n *\n * ```ts\n * deriveRoleMarkers(jaSlice, { table: 'source', target: 'destination' });\n * // → { table: 'から', target: 'に' }\n * ```\n *\n * Explicitly authored `markerOverride` entries stay authoritative — when\n * assembling a per-language marker map for a schema role, spread the explicit\n * entries after the derived defaults.\n */\nexport function deriveRoleMarkers(\n slice: GrammarProfileSlice,\n roleMapping: Readonly<Record<string, string>>\n): Record<string, string> {\n const derived: Record<string, string> = {};\n for (const [domainRole, semanticRole] of Object.entries(roleMapping)) {\n const marker = slice.roleMarkers?.[semanticRole];\n if (marker?.primary) derived[domainRole] = marker.primary;\n }\n return derived;\n}\n","/**\n * Character Classifiers\n *\n * Unicode range classification and Latin character classifier factories.\n * Used by language-specific tokenizers to define character sets.\n */\n\n// =============================================================================\n// Unicode Range Classification\n// =============================================================================\n\n/**\n * Unicode range tuple: [start, end] (inclusive).\n */\nexport type UnicodeRange = readonly [number, number];\n\n/**\n * Create a character classifier for Unicode ranges.\n * Returns a function that checks if a character's code point falls within any of the ranges.\n *\n * @example\n * // Japanese Hiragana\n * const isHiragana = createUnicodeRangeClassifier([[0x3040, 0x309f]]);\n *\n * // Korean (Hangul syllables + Jamo)\n * const isKorean = createUnicodeRangeClassifier([\n * [0xac00, 0xd7a3], // Hangul syllables\n * [0x1100, 0x11ff], // Hangul Jamo\n * [0x3130, 0x318f], // Hangul Compatibility Jamo\n * ]);\n */\nexport function createUnicodeRangeClassifier(\n ranges: readonly UnicodeRange[]\n): (char: string) => boolean {\n return (char: string): boolean => {\n const code = char.charCodeAt(0);\n return ranges.some(([start, end]) => code >= start && code <= end);\n };\n}\n\n/**\n * Combine multiple character classifiers into one.\n * Returns true if any of the classifiers return true.\n *\n * @example\n * const isJapanese = combineClassifiers(isHiragana, isKatakana, isKanji);\n */\nexport function combineClassifiers(\n ...classifiers: Array<(char: string) => boolean>\n): (char: string) => boolean {\n return (char: string): boolean => classifiers.some(fn => fn(char));\n}\n\n/**\n * Character classifiers for a Latin-based language.\n */\nexport interface LatinCharClassifiers {\n /** Check if character is a letter in this language (including accented chars). */\n isLetter: (char: string) => boolean;\n /** Check if character is part of an identifier (letter, digit, underscore, hyphen). */\n isIdentifierChar: (char: string) => boolean;\n}\n\n/**\n * Create character classifiers for a Latin-based language.\n * Returns isLetter and isIdentifierChar functions based on the provided regex.\n *\n * @example\n * // Spanish letters\n * const { isLetter, isIdentifierChar } = createLatinCharClassifiers(/[a-zA-Z\\u00e1\\u00e9\\u00ed\\u00f3\\u00fa\\u00fc\\u00f1\\u00c1\\u00c9\\u00cd\\u00d3\\u00da\\u00dc\\u00d1]/);\n *\n * // German letters\n * const { isLetter, isIdentifierChar } = createLatinCharClassifiers(/[a-zA-Z\\u00e4\\u00f6\\u00fc\\u00c4\\u00d6\\u00dc\\u00df]/);\n */\nexport function createLatinCharClassifiers(letterPattern: RegExp): LatinCharClassifiers {\n const isLetter = (char: string): boolean => letterPattern.test(char);\n const isIdentifierChar = (char: string): boolean => isLetter(char) || /[0-9_-]/.test(char);\n return { isLetter, isIdentifierChar };\n}\n","/**\n * Morphological Normalizer Types\n *\n * Defines interfaces for language-specific morphological analysis.\n * Normalizers reduce conjugated/inflected forms to canonical stems\n * that can be matched against keyword dictionaries.\n */\n\n/**\n * Result of morphological normalization.\n */\nexport interface NormalizationResult {\n /** The extracted stem/root form */\n readonly stem: string;\n\n /** Confidence in the normalization (0.0-1.0) */\n readonly confidence: number;\n\n /** Optional metadata about the transformation */\n readonly metadata?: NormalizationMetadata;\n}\n\n/**\n * Metadata about morphological transformations applied.\n */\nexport interface NormalizationMetadata {\n /** Prefixes that were removed */\n readonly removedPrefixes?: readonly string[];\n\n /** Suffixes that were removed */\n readonly removedSuffixes?: readonly string[];\n\n /** Type of conjugation detected */\n readonly conjugationType?: ConjugationType;\n\n /** Original form classification */\n readonly originalForm?: string;\n\n /** Applied transformation rules (for debugging) */\n readonly appliedRules?: readonly string[];\n}\n\n/**\n * Types of verb conjugation/inflection.\n */\nexport type ConjugationType =\n // Tense\n | 'present'\n | 'past'\n | 'future'\n | 'progressive'\n | 'perfect'\n // Mood\n | 'imperative'\n | 'subjunctive'\n | 'conditional'\n // Voice\n | 'passive'\n | 'causative'\n // Politeness (Japanese/Korean)\n | 'polite'\n | 'humble'\n | 'honorific'\n // Form\n | 'negative'\n | 'potential'\n | 'volitional'\n // Japanese conditional forms\n | 'conditional-tara' // たら/したら - if/when (completed action)\n | 'conditional-to' // と/すると - when (habitual/expected)\n | 'conditional-ba' // ば/すれば - if (hypothetical)\n // Korean-specific\n | 'connective' // 하고, 해서 etc.\n | 'conditional-myeon' // -(으)면 - if/when (general conditional)\n | 'temporal-ttae' // -(으)ㄹ 때 - when (at the time of)\n | 'causal-nikka' // -(으)니까 - because/since\n // Korean honorific forms (-시- infix)\n | 'honorific-conditional' // -하시면 - if (honorific)\n | 'honorific-temporal' // -하실 때 - when (honorific)\n | 'honorific-causal' // -하시니까 - because (honorific)\n | 'honorific-past' // -하셨어요 - past (honorific)\n | 'honorific-polite' // -하십니다 - polite (honorific)\n // Korean sequential forms\n | 'sequential-after' // -고 나서 - after doing\n | 'sequential-before' // -기 전에 - before doing\n | 'immediate' // -자마자 - as soon as\n | 'obligation' // -아야/어야 해 - must do, should do\n // Spanish-specific\n | 'reflexive'\n | 'reflexive-imperative'\n | 'gerund'\n | 'participle'\n // Arabic-specific\n | 'conditional-idha' // إذا - if/when (hypothetical)\n | 'temporal-indama' // عندما - when (temporal conjunction)\n | 'temporal-hina' // حين - at the time of\n | 'temporal-lamma' // لمّا - when (past emphasis)\n | 'past-verb' // فعل ماضي - past tense verb\n // Turkish-specific\n | 'conditional-se' // -se/-sa - if (hypothetical)\n | 'temporal-ince' // -ince/-ınca/-unca/-ünce - when/as\n | 'temporal-dikce' // -dikçe/-dıkça/-dukça/-dükçe - as/while\n | 'aorist' // -ir/-ar - habitual/general\n | 'optative' // -eyim/-ayım/-elim/-alım - let me/us\n | 'necessitative' // -meli/-malı - must/should\n // Japanese request/contracted forms\n | 'request' // てください/でください - polite request\n | 'casual-request' // てくれ/でくれ - casual request\n | 'contracted' // ちゃう/じゃう - contracted completion (てしまう)\n | 'contracted-past' // ちゃった/じゃった - contracted past completion\n // Compound\n | 'compound' // Multi-layer suffixes (ていなかった, 하고나서였어)\n | 'te-form' // Japanese て-form\n | 'dictionary'; // Base/infinitive form\n\n/**\n * Interface for language-specific morphological normalizers.\n *\n * Normalizers attempt to reduce inflected word forms to their\n * canonical stems. This enables matching conjugated verbs against\n * keyword dictionaries that only contain base forms.\n *\n * Example (Japanese):\n * 切り替えた (past) → { stem: '切り替え', confidence: 0.85 }\n * 切り替えます (polite) → { stem: '切り替え', confidence: 0.85 }\n *\n * Example (Spanish):\n * mostrarse (reflexive infinitive) → { stem: 'mostrar', confidence: 0.85 }\n * alternando (gerund) → { stem: 'alternar', confidence: 0.85 }\n */\nexport interface MorphologicalNormalizer {\n /** Language code this normalizer handles */\n readonly language: string;\n\n /**\n * Normalize a word to its canonical stem form.\n *\n * @param word - The word to normalize\n * @returns Normalization result with stem and confidence\n */\n normalize(word: string): NormalizationResult;\n\n /**\n * Check if a word appears to be a verb form that can be normalized.\n * Optional optimization to skip normalization for non-verb tokens.\n *\n * @param word - The word to check\n * @returns true if the word might be a normalizable verb form\n */\n isNormalizable?(word: string): boolean;\n}\n\n/**\n * Configuration for suffix-based normalization rules.\n * Used by agglutinative languages (Japanese, Korean, Turkish).\n */\nexport interface SuffixRule {\n /** The suffix pattern to match */\n readonly pattern: string;\n\n /** Confidence when this suffix is stripped */\n readonly confidence: number;\n\n /** What to replace the suffix with (empty string for simple removal) */\n readonly replacement?: string;\n\n /** Conjugation type this suffix indicates */\n readonly conjugationType?: ConjugationType;\n\n /** Minimum stem length after stripping (to avoid over-stripping) */\n readonly minStemLength?: number;\n}\n\n/**\n * Configuration for prefix-based normalization rules.\n * Used primarily by Arabic for article/conjunction prefixes.\n */\nexport interface PrefixRule {\n /** The prefix pattern to match */\n readonly pattern: string;\n\n /** Confidence penalty when this prefix is stripped */\n readonly confidencePenalty: number;\n\n /** What the prefix indicates (for metadata) */\n readonly prefixType?: 'article' | 'conjunction' | 'preposition' | 'verb-marker';\n\n /** Minimum remaining characters after stripping (to avoid over-stripping) */\n readonly minRemaining?: number;\n}\n\n/**\n * Helper to create a \"no change\" normalization result.\n */\nexport function noChange(word: string): NormalizationResult {\n return { stem: word, confidence: 1.0 };\n}\n\n/**\n * Helper to create a normalization result with metadata.\n */\nexport function normalized(\n stem: string,\n confidence: number,\n metadata?: NormalizationMetadata\n): NormalizationResult {\n if (metadata) {\n return { stem, confidence, metadata };\n }\n return { stem, confidence };\n}\n","/**\n * BaseMorphologicalNormalizer — Shared base class for language normalizers.\n *\n * Provides the common suffix/prefix stripping loop, reflexive verb handling,\n * and normalize() pipeline. Language-specific normalizers extend this class\n * and provide their conjugation rules.\n *\n * Phase 3.1 of parser-ecosystem-plan-v3.\n */\n\nimport type {\n MorphologicalNormalizer,\n NormalizationResult,\n ConjugationType,\n SuffixRule,\n PrefixRule,\n} from './types';\nimport { noChange, normalized } from './types';\n\n/**\n * Conjugation ending rule for verb classes (Romance languages etc.)\n * Broader than SuffixRule — includes the replacement stem (e.g., strip -ando, add -ar).\n */\nexport interface ConjugationEnding {\n readonly ending: string;\n readonly stem: string;\n readonly confidence: number;\n readonly type: ConjugationType;\n}\n\n/**\n * Configuration for BaseMorphologicalNormalizer.\n * Subclasses provide this in their constructor.\n */\nexport interface NormalizerConfig {\n /** Language code */\n readonly language: string;\n\n /** Minimum word length to attempt normalization */\n readonly minWordLength?: number;\n\n /** Minimum stem length after stripping (default: 2) */\n readonly minStemLength?: number;\n\n /** Conjugation endings sorted longest-first */\n readonly endings?: readonly ConjugationEnding[];\n\n /** Suffix rules (for SuffixRule-style normalizers) */\n readonly suffixRules?: readonly SuffixRule[];\n\n /** Prefix rules */\n readonly prefixRules?: readonly PrefixRule[];\n\n /** Reflexive suffixes (for Romance languages) */\n readonly reflexiveSuffixes?: readonly string[];\n\n /** Infinitive endings (for checking if already normalized) */\n readonly infinitiveEndings?: readonly string[];\n}\n\n/**\n * Abstract base class for morphological normalizers.\n *\n * Subclasses must implement `isNormalizable()` and can override any\n * normalization step. The default `normalize()` pipeline is:\n *\n * 1. Check if already in dictionary form → noChange\n * 2. Try reflexive normalization (if reflexiveSuffixes configured)\n * 3. Try conjugation endings (if endings configured)\n * 4. Try suffix rules (if suffixRules configured)\n * 5. Try prefix rules (if prefixRules configured)\n * 6. Return noChange\n */\nexport abstract class BaseMorphologicalNormalizer implements MorphologicalNormalizer {\n readonly language: string;\n protected readonly config: NormalizerConfig;\n\n constructor(config: NormalizerConfig) {\n this.language = config.language;\n this.config = {\n minWordLength: 3,\n minStemLength: 2,\n ...config,\n };\n }\n\n /**\n * Check if a word can be normalized. Subclasses must implement this\n * with language-specific script/character detection.\n */\n abstract isNormalizable(word: string): boolean;\n\n /**\n * Standard normalization pipeline. Override for custom behavior.\n */\n normalize(word: string): NormalizationResult {\n const lower = word.toLowerCase();\n\n // Check if already in dictionary form\n if (this.isAlreadyNormalized(lower)) {\n return noChange(word);\n }\n\n // Try reflexive normalization (Romance languages)\n if (this.config.reflexiveSuffixes) {\n const reflexive = this.tryReflexiveNormalization(lower);\n if (reflexive) return reflexive;\n }\n\n // Try conjugation endings\n if (this.config.endings) {\n const conjugation = this.tryConjugationEndings(lower);\n if (conjugation) return conjugation;\n }\n\n // Try suffix rules\n if (this.config.suffixRules) {\n const suffix = this.trySuffixRules(lower);\n if (suffix) return suffix;\n }\n\n // Try prefix rules\n if (this.config.prefixRules) {\n const prefix = this.tryPrefixRules(lower);\n if (prefix) return prefix;\n }\n\n return noChange(word);\n }\n\n /**\n * Check if word is already in dictionary form (e.g., ends in -ar/-er/-ir).\n * Override for language-specific checks.\n */\n protected isAlreadyNormalized(word: string): boolean {\n if (this.config.infinitiveEndings) {\n return this.config.infinitiveEndings.some(e => word.endsWith(e));\n }\n return false;\n }\n\n /**\n * Try to strip reflexive suffixes and normalize the remainder.\n * Common in Romance languages (Spanish, Portuguese, French).\n */\n protected tryReflexiveNormalization(word: string): NormalizationResult | null {\n const suffixes = this.config.reflexiveSuffixes;\n if (!suffixes) return null;\n\n for (const suffix of suffixes) {\n if (!word.endsWith(suffix)) continue;\n const remainder = word.slice(0, -suffix.length);\n\n // Check if remainder is already an infinitive\n if (this.isAlreadyNormalized(remainder)) {\n return normalized(remainder, 0.88, {\n removedSuffixes: [suffix],\n conjugationType: 'reflexive',\n });\n }\n\n // Try to normalize the remainder\n const inner = this.tryConjugationEndings(remainder) || this.trySuffixRules(remainder);\n if (inner && inner.stem !== remainder) {\n return normalized(inner.stem, inner.confidence * 0.95, {\n removedSuffixes: [suffix, ...(inner.metadata?.removedSuffixes || [])],\n conjugationType: 'reflexive',\n });\n }\n }\n\n return null;\n }\n\n /**\n * Try conjugation endings (verb class endings like -ar/-er/-ir patterns).\n * Endings must be pre-sorted longest-first.\n */\n protected tryConjugationEndings(word: string): NormalizationResult | null {\n const endings = this.config.endings;\n if (!endings) return null;\n\n const minStem = this.config.minStemLength ?? 2;\n\n for (const rule of endings) {\n if (!word.endsWith(rule.ending)) continue;\n\n const stemBase = word.slice(0, -rule.ending.length);\n if (stemBase.length < minStem) continue;\n\n const infinitive = stemBase + rule.stem;\n return normalized(infinitive, rule.confidence, {\n removedSuffixes: [rule.ending],\n conjugationType: rule.type,\n });\n }\n\n return null;\n }\n\n /**\n * Try SuffixRule-style normalization.\n * Rules must be pre-sorted longest-first.\n */\n protected trySuffixRules(word: string): NormalizationResult | null {\n const rules = this.config.suffixRules;\n if (!rules) return null;\n\n const defaultMinStem = this.config.minStemLength ?? 2;\n\n for (const rule of rules) {\n if (!word.endsWith(rule.pattern)) continue;\n\n const stem = word.slice(0, -rule.pattern.length);\n const minStem = rule.minStemLength ?? defaultMinStem;\n if (stem.length < minStem) continue;\n\n const result = stem + (rule.replacement || '');\n return normalized(result, rule.confidence, {\n removedSuffixes: [rule.pattern],\n ...(rule.conjugationType && { conjugationType: rule.conjugationType }),\n });\n }\n\n return null;\n }\n\n /**\n * Try PrefixRule-style normalization.\n */\n protected tryPrefixRules(word: string): NormalizationResult | null {\n const rules = this.config.prefixRules;\n if (!rules) return null;\n\n for (const rule of rules) {\n if (!word.startsWith(rule.pattern)) continue;\n\n const remainder = word.slice(rule.pattern.length);\n const minRemaining = rule.minRemaining ?? this.config.minStemLength ?? 2;\n if (remainder.length < minRemaining) continue;\n\n return normalized(remainder, 1.0 - rule.confidencePenalty, {\n removedPrefixes: [rule.pattern],\n });\n }\n\n return null;\n }\n}\n","/**\n * JSONL Writer\n *\n * Exports training pairs in JSONL (JSON Lines) format,\n * compatible with standard fine-tuning pipelines.\n */\n\nimport type { TrainingPair } from './types';\n\n/**\n * Convert training pairs to JSONL format (one JSON object per line).\n *\n * Each line contains:\n * - id: unique pair identifier\n * - prompt: the natural language input\n * - completion: the LSE bracket syntax output\n * - metadata: domain, action, language, source, quality\n */\nexport function toJSONL(pairs: readonly TrainingPair[]): string {\n return pairs.map(pair => JSON.stringify(toJSONLRow(pair))).join('\\n');\n}\n\n/**\n * Convert a single training pair to a JSONL row.\n */\nexport function toJSONLRow(pair: TrainingPair): JSONLRow {\n return {\n id: pair.id,\n prompt: pair.natural,\n completion: pair.explicit,\n metadata: {\n domain: pair.domain,\n action: pair.action,\n language: pair.language,\n source: pair.source,\n quality: pair.quality,\n ...(pair.confidence !== undefined && { confidence: pair.confidence }),\n },\n };\n}\n\n/**\n * Parse JSONL back into rows (for validation/roundtrip testing).\n */\nexport function parseJSONL(text: string): JSONLRow[] {\n return text\n .split('\\n')\n .filter(line => line.trim().length > 0)\n .map(line => JSON.parse(line) as JSONLRow);\n}\n\n/**\n * A single row in JSONL format.\n */\nexport interface JSONLRow {\n readonly id: string;\n readonly prompt: string;\n readonly completion: string;\n readonly metadata: {\n readonly domain: string;\n readonly action: string;\n readonly language: string;\n readonly source: string;\n readonly quality: number;\n readonly confidence?: number;\n };\n}\n","/**\n * Confidence-Aware Disambiguation\n *\n * When parse confidence is borderline (between low and high thresholds),\n * generates a disambiguation request with alternative interpretations\n * instead of blindly accepting or rejecting.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport { renderExplicit } from '../ir/explicit-renderer';\nimport type { DisambiguationRequest, DisambiguationCandidate } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Check whether a confidence score falls in the disambiguation range.\n *\n * @returns true if the confidence is ambiguous (between low and high thresholds)\n */\nexport function needsDisambiguation(\n confidence: number,\n low: number = 0.5,\n high: number = 0.7\n): boolean {\n return confidence >= low && confidence < high;\n}\n\n/**\n * Build a disambiguation request from candidate interpretations.\n *\n * @param input - The original ambiguous input\n * @param candidates - Alternative interpretations with confidence scores\n */\nexport function buildDisambiguation(\n input: string,\n candidates: ReadonlyArray<{\n action: string;\n confidence: number;\n node: SemanticNode;\n description?: string;\n }>\n): DisambiguationRequest {\n const sortedCandidates = [...candidates].sort((a, b) => b.confidence - a.confidence);\n\n const disambiguationCandidates: DisambiguationCandidate[] = sortedCandidates.map((c, i) => ({\n action: c.action,\n confidence: c.confidence,\n explicit: renderExplicit(c.node),\n description: c.description || `${c.action} (option ${String.fromCharCode(97 + i)})`,\n }));\n\n const optionLines = disambiguationCandidates.map(\n (c, i) =>\n ` (${String.fromCharCode(97 + i)}) ${c.explicit} — ${c.description} (conf: ${c.confidence.toFixed(2)})`\n );\n\n const question = [\n `Your input parsed with confidence ${sortedCandidates[0]?.confidence.toFixed(2) ?? '?'}.`,\n ...optionLines,\n 'Which did you mean?',\n ].join('\\n');\n\n return {\n input,\n candidates: disambiguationCandidates,\n question,\n };\n}\n","/**\n * Pattern Hit-Rate Tracker\n *\n * Records pattern events in a ring buffer and computes hit-rate\n * statistics by command, language, and diagnostic code. Patterns\n * with high rejected/attempts ratios indicate miscalibrated confidence.\n */\n\nimport type { PatternEvent, HitRate, PatternTrackerSummary, TopFailure } from './types';\n\n// =============================================================================\n// Public API\n// =============================================================================\n\nexport class PatternTracker {\n private events: PatternEvent[] = [];\n private readonly maxEvents: number;\n\n constructor(maxEvents: number = 1000) {\n this.maxEvents = maxEvents;\n }\n\n /**\n * Record a pattern event.\n */\n record(event: PatternEvent): void {\n this.events.push(event);\n // Ring buffer: drop oldest when full\n if (this.events.length > this.maxEvents) {\n this.events = this.events.slice(this.events.length - this.maxEvents);\n }\n }\n\n /**\n * Get hit rate by command action.\n */\n getHitRateByCommand(): Record<string, HitRate> {\n return this.computeHitRate(e => e.action);\n }\n\n /**\n * Get hit rate by language.\n */\n getHitRateByLanguage(): Record<string, HitRate> {\n return this.computeHitRate(e => e.language);\n }\n\n /**\n * Get the most frequent failure diagnostic codes.\n */\n getTopFailures(limit: number = 10): TopFailure[] {\n const codeMap = new Map<string, { count: number; actions: Set<string> }>();\n\n for (const event of this.events) {\n if (event.outcome !== 'rejected' || !event.diagnosticCodes) continue;\n for (const code of event.diagnosticCodes) {\n const entry = codeMap.get(code) || { count: 0, actions: new Set() };\n entry.count++;\n entry.actions.add(event.action);\n codeMap.set(code, entry);\n }\n }\n\n return Array.from(codeMap.entries())\n .map(([code, { count, actions }]) => ({\n code,\n count,\n actions: Array.from(actions),\n }))\n .sort((a, b) => b.count - a.count)\n .slice(0, limit);\n }\n\n /**\n * Get a complete summary of tracking data.\n */\n getSummary(): PatternTrackerSummary {\n const byOutcome: Record<string, number> = {};\n for (const event of this.events) {\n byOutcome[event.outcome] = (byOutcome[event.outcome] || 0) + 1;\n }\n\n return {\n totalEvents: this.events.length,\n byOutcome,\n byCommand: this.getHitRateByCommand(),\n byLanguage: this.getHitRateByLanguage(),\n topFailures: this.getTopFailures(),\n };\n }\n\n /**\n * Export all events as JSONL.\n */\n exportJSONL(): string {\n return this.events.map(e => JSON.stringify(e)).join('\\n');\n }\n\n /**\n * Get the number of recorded events.\n */\n get size(): number {\n return this.events.length;\n }\n\n /**\n * Clear all events.\n */\n clear(): void {\n this.events = [];\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private computeHitRate(keyFn: (e: PatternEvent) => string): Record<string, HitRate> {\n const map = new Map<string, { attempts: number; successes: number }>();\n\n for (const event of this.events) {\n const key = keyFn(event);\n const entry = map.get(key) || { attempts: 0, successes: 0 };\n entry.attempts++;\n if (event.outcome === 'accepted') {\n entry.successes++;\n }\n map.set(key, entry);\n }\n\n const result: Record<string, HitRate> = {};\n for (const [key, { attempts, successes }] of map) {\n result[key] = {\n attempts,\n successes,\n rate: attempts > 0 ? successes / attempts : 0,\n };\n }\n return result;\n }\n}\n","/**\n * Multi-statement parser for domain DSLs.\n *\n * Provides generic mechanics for parsing multi-line/multi-statement DSL input:\n * - Statement splitting (line-based or delimiter-based)\n * - Keyword classification (SVO start / SOV end detection)\n * - Block accumulation (grouping lines into blocks)\n * - Error collection with line numbers\n *\n * Domains provide the semantics (what keywords mean, preprocessing, hierarchy).\n * The framework provides the mechanics.\n */\n\nimport type { SemanticNode } from '../core/types';\nimport type { MultilingualDSL } from '../api/create-dsl';\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Word order affects keyword detection position.\n */\nexport type WordOrderHint = 'SVO' | 'SOV' | 'VSO';\n\n/**\n * How to split input into individual statements.\n */\nexport interface SplitConfig {\n /**\n * Split mode:\n * - 'line': split on newlines (for indentation-based DSLs)\n * - 'delimiter': split on language-specific delimiters\n */\n readonly mode: 'line' | 'delimiter';\n\n /**\n * Language-specific delimiter patterns (used when mode='delimiter').\n * Key is language code, value is regex pattern.\n * Example: { en: /,\\s*|\\n\\s*/, ja: /、|。|\\n\\s*/ }\n */\n readonly delimiters?: Readonly<Record<string, RegExp>>;\n\n /**\n * Default delimiter when language not in delimiters map.\n */\n readonly defaultDelimiter?: RegExp;\n\n /**\n * Whether to trim each statement after splitting.\n * Default: true\n */\n readonly trim?: boolean;\n\n /**\n * Comment prefixes to strip. Lines starting with these are skipped.\n * Default: ['--', '//']\n */\n readonly commentPrefixes?: readonly string[];\n}\n\n/**\n * A keyword category with its translations.\n * Maps language code to array of keyword variants.\n */\nexport type KeywordMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Configuration for keyword classification.\n */\nexport interface KeywordConfig {\n /**\n * Named keyword categories with their per-language translations.\n * Example: { test: { en: ['test'], ja: ['テスト'], es: ['prueba'] } }\n */\n readonly categories: Readonly<Record<string, KeywordMap>>;\n\n /**\n * Word order hint per language (affects where keywords are detected).\n * Default for unlisted languages: 'SVO'\n */\n readonly wordOrders?: Readonly<Record<string, WordOrderHint>>;\n}\n\n/**\n * Configuration for continuation resolution (e.g., BDD's \"and\" keyword).\n */\nexport interface ContinuationConfig {\n /**\n * The keyword(s) that signal continuation, per language.\n * Example: { en: ['and'], es: ['y'], ja: ['かつ'], ar: ['و'] }\n */\n readonly keywords: KeywordMap;\n\n /**\n * How to resolve continuation: re-prefix with previous step's keyword.\n * The function receives (content after 'and', previous step's category, language)\n * and returns the re-prefixed string for re-parsing.\n *\n * Default: `(content, prevCategory, language, categoryKeywords) =>\n * categoryKeywords[prevCategory]?.[language]?.[0] + ' ' + content`\n */\n readonly resolve?: (\n content: string,\n prevCategory: string,\n language: string,\n categoryKeywords: Record<string, KeywordMap>\n ) => string;\n}\n\n/**\n * A parsed statement with its line context.\n */\nexport interface ParsedStatement {\n /** The parsed semantic node */\n readonly node: SemanticNode;\n /** Original source line/text */\n readonly source: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Detected keyword category (e.g., 'test', 'given', 'when') */\n readonly category?: string;\n /** Indentation level (number of leading spaces, 0-based) */\n readonly indent: number;\n}\n\n/**\n * A parse error with location information.\n */\nexport interface StatementError {\n /** Error message */\n readonly message: string;\n /** Line number (1-based) in original input */\n readonly line: number;\n /** Original source line/text */\n readonly source: string;\n /** Error code for programmatic handling */\n readonly code?: 'parse-error' | 'unexpected-line' | 'continuation-error';\n}\n\n/**\n * Result of multi-statement parsing.\n */\nexport interface MultiStatementResult {\n /** Successfully parsed statements */\n readonly statements: readonly ParsedStatement[];\n /** Errors encountered during parsing */\n readonly errors: readonly StatementError[];\n}\n\n/**\n * Preprocessor function called before each statement is parsed.\n * Returns the modified string to parse, or null to skip the line.\n */\nexport type StatementPreprocessor = (\n line: string,\n category: string | undefined,\n language: string,\n context: PreprocessorContext\n) => string | null;\n\n/**\n * Context available to preprocessors.\n */\nexport interface PreprocessorContext {\n /** The previous parsed statement, if any */\n readonly previous?: ParsedStatement;\n /** Line number (1-based) */\n readonly lineNumber: number;\n /** Indentation level */\n readonly indent: number;\n}\n\n/**\n * Full configuration for multi-statement parser.\n */\nexport interface MultiStatementConfig {\n /** How to split input into statements */\n readonly split: SplitConfig;\n /** Keyword classification (optional — if omitted, no category detection) */\n readonly keywords?: KeywordConfig;\n /** Continuation resolution (optional — e.g., BDD 'and') */\n readonly continuation?: ContinuationConfig;\n /** Statement preprocessor (optional — for article stripping, expect-prepending, etc.) */\n readonly preprocessor?: StatementPreprocessor;\n}\n\n// =============================================================================\n// Multi-Statement Parser\n// =============================================================================\n\n/**\n * A reusable multi-statement parser.\n * Created via `createMultiStatementParser()`.\n */\nexport interface MultiStatementParser {\n /**\n * Parse multi-statement input into an array of parsed statements.\n */\n parse(input: string, language: string): MultiStatementResult;\n}\n\n/**\n * Create a multi-statement parser that wraps a `MultilingualDSL` instance.\n *\n * The parser handles splitting, keyword detection, continuation resolution,\n * preprocessing, and error collection. It delegates single-statement parsing\n * to the provided DSL's `parse()` method.\n *\n * @example\n * ```typescript\n * const parser = createMultiStatementParser(myDSL, {\n * split: { mode: 'line', commentPrefixes: ['--', '//'] },\n * keywords: {\n * categories: {\n * given: { en: ['given'], ja: ['前提'], es: ['dado'] },\n * when: { en: ['when'], ja: ['もし'], es: ['cuando'] },\n * then: { en: ['then'], ja: ['ならば'], es: ['entonces'] },\n * },\n * wordOrders: { ja: 'SOV', ar: 'VSO' },\n * },\n * continuation: {\n * keywords: { en: ['and'], es: ['y'], ja: ['かつ'] },\n * },\n * });\n *\n * const result = parser.parse(`\n * given #login is visible\n * when click on #submit\n * then #dashboard appears\n * `, 'en');\n * ```\n */\nexport function createMultiStatementParser(\n dsl: MultilingualDSL,\n config: MultiStatementConfig\n): MultiStatementParser {\n return new MultiStatementParserImpl(dsl, config);\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\nclass MultiStatementParserImpl implements MultiStatementParser {\n constructor(\n private readonly dsl: MultilingualDSL,\n private readonly config: MultiStatementConfig\n ) {}\n\n parse(input: string, language: string): MultiStatementResult {\n const rawStatements = this.splitStatements(input, language);\n const statements: ParsedStatement[] = [];\n const errors: StatementError[] = [];\n let previous: ParsedStatement | undefined;\n\n for (const raw of rawStatements) {\n // Detect keyword category\n const category = this.classifyLine(raw.text, language);\n\n // Handle continuation (e.g., 'and')\n let textToParse = raw.text;\n if (this.config.continuation) {\n const resolved = this.resolveContinuation(raw.text, language, previous?.category);\n if (resolved !== null) {\n textToParse = resolved;\n }\n }\n\n // Run preprocessor\n if (this.config.preprocessor) {\n const processed = this.config.preprocessor(textToParse, category, language, {\n ...(previous != null && { previous }),\n lineNumber: raw.line,\n indent: raw.indent,\n });\n if (processed === null) continue; // skip line\n textToParse = processed;\n }\n\n // Parse with DSL\n try {\n const node = this.dsl.parse(textToParse, language);\n const stmt: ParsedStatement = {\n node,\n source: raw.text,\n line: raw.line,\n ...(category != null && { category }),\n indent: raw.indent,\n };\n statements.push(stmt);\n previous = stmt;\n } catch (err) {\n errors.push({\n message: err instanceof Error ? err.message : String(err),\n line: raw.line,\n source: raw.text,\n code: 'parse-error',\n });\n }\n }\n\n return { statements, errors };\n }\n\n /**\n * Split input into raw statement lines with metadata.\n */\n private splitStatements(\n input: string,\n language: string\n ): Array<{ text: string; line: number; indent: number }> {\n const { mode, trim = true, commentPrefixes = ['--', '//'] } = this.config.split;\n\n if (mode === 'delimiter') {\n return this.splitByDelimiter(input, language, trim, commentPrefixes);\n }\n\n // Line-based splitting\n const lines = input.split('\\n');\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i];\n const indent = raw.length - raw.trimStart().length;\n const text = trim ? raw.trim() : raw;\n\n // Skip empty lines\n if (!text) continue;\n\n // Skip comments\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent });\n }\n\n return result;\n }\n\n /**\n * Split by language-specific delimiters.\n */\n private splitByDelimiter(\n input: string,\n language: string,\n trim: boolean,\n commentPrefixes: readonly string[]\n ): Array<{ text: string; line: number; indent: number }> {\n const delimiter =\n this.config.split.delimiters?.[language] ??\n this.config.split.defaultDelimiter ??\n /,\\s*|\\n\\s*/;\n\n const parts = input.split(delimiter);\n const result: Array<{ text: string; line: number; indent: number }> = [];\n\n for (let i = 0; i < parts.length; i++) {\n const raw = parts[i];\n const text = trim ? raw.trim() : raw;\n\n if (!text) continue;\n if (commentPrefixes.some(p => text.startsWith(p))) continue;\n\n result.push({ text, line: i + 1, indent: 0 });\n }\n\n return result;\n }\n\n /**\n * Classify a line by its keyword category.\n * Returns the category name or undefined if no match.\n */\n private classifyLine(line: string, language: string): string | undefined {\n if (!this.config.keywords) return undefined;\n\n const lower = line.toLowerCase();\n const wordOrder = this.config.keywords.wordOrders?.[language] ?? 'SVO';\n\n for (const [category, keywordMap] of Object.entries(this.config.keywords.categories)) {\n const keywords = keywordMap[language] ?? keywordMap['en'] ?? [];\n for (const kw of keywords) {\n const kwLower = kw.toLowerCase();\n if (wordOrder === 'SOV') {\n // SOV: check end of line first, then start\n if (lower.endsWith(kwLower) || lower.startsWith(kwLower)) {\n return category;\n }\n } else {\n // SVO/VSO: check start of line\n if (lower.startsWith(kwLower)) {\n return category;\n }\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Resolve continuation keywords (e.g., 'and' → re-prefix with previous step type).\n * Returns the resolved string, or null if not a continuation.\n */\n private resolveContinuation(\n text: string,\n language: string,\n prevCategory: string | undefined\n ): string | null {\n if (!this.config.continuation || !prevCategory) return null;\n\n const contKeywords =\n this.config.continuation.keywords[language] ?? this.config.continuation.keywords['en'] ?? [];\n\n const lower = text.toLowerCase();\n for (const kw of contKeywords) {\n const kwLower = kw.toLowerCase();\n if (lower.startsWith(kwLower)) {\n const content = text.slice(kw.length).trim();\n if (!content) return null;\n\n if (this.config.continuation.resolve) {\n return this.config.continuation.resolve(\n content,\n prevCategory,\n language,\n this.config.keywords?.categories ?? {}\n );\n }\n\n // Default: prepend previous category's keyword\n const prevKeywords =\n this.config.keywords?.categories[prevCategory]?.[language] ??\n this.config.keywords?.categories[prevCategory]?.['en'];\n if (prevKeywords?.[0]) {\n return prevKeywords[0] + ' ' + content;\n }\n\n return null;\n }\n }\n\n return null;\n }\n}\n\n// =============================================================================\n// Block Accumulator (for grouped/nested structures)\n// =============================================================================\n\n/**\n * A block of accumulated statements, grouped by a block-opening keyword.\n */\nexport interface StatementBlock<TMeta = unknown> {\n /** Block type (e.g., 'test', 'feature', 'scenario') */\n readonly type: string;\n /** Block name, if any (e.g., test name from quotes) */\n readonly name?: string;\n /** Statements within this block */\n readonly statements: readonly ParsedStatement[];\n /** Child blocks (for nested structures) */\n readonly children: readonly StatementBlock<TMeta>[];\n /** Starting line number */\n readonly line: number;\n /** Indentation level of the block opener */\n readonly indent: number;\n /** Domain-specific metadata */\n readonly meta?: TMeta;\n}\n\n/**\n * Configuration for block accumulation.\n */\nexport interface BlockConfig {\n /**\n * Block-opening keyword categories.\n * Statements classified in these categories start new blocks.\n */\n readonly blockTypes: readonly string[];\n\n /**\n * How to determine block nesting:\n * - 'indent': indentation-based (deeper indent = child block)\n * - 'flat': all blocks at same level (no nesting)\n */\n readonly nesting: 'indent' | 'flat';\n\n /**\n * Extract block name from statement text.\n * Default: extracts quoted string after keyword (e.g., test \"Login\" → \"Login\")\n */\n readonly extractName?: (text: string, category: string) => string | undefined;\n}\n\n/**\n * Result of block accumulation.\n */\nexport interface BlockResult<TMeta = unknown> {\n /** Top-level blocks */\n readonly blocks: readonly StatementBlock<TMeta>[];\n /** Statements not inside any block */\n readonly orphans: readonly ParsedStatement[];\n}\n\n/**\n * Accumulate parsed statements into blocks based on keyword categories.\n *\n * This groups statements into hierarchical blocks based on block-opening keywords\n * and indentation levels. Useful for test/feature/scenario structures.\n *\n * @example\n * ```typescript\n * const result = accumulateBlocks(statements, {\n * blockTypes: ['test', 'feature', 'setup'],\n * nesting: 'indent',\n * extractName: (text, category) => {\n * const match = text.match(/\"([^\"]+)\"/);\n * return match?.[1];\n * },\n * });\n * ```\n */\nexport function accumulateBlocks<TMeta = unknown>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n if (config.nesting === 'flat') {\n return accumulateFlat(statements, config);\n }\n return accumulateIndented(statements, config);\n}\n\nfunction accumulateFlat<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const blocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n let current: {\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n line: number;\n indent: number;\n } | null = null;\n\n const flush = () => {\n if (current) {\n blocks.push({\n type: current.type,\n ...(current.name != null && { name: current.name }),\n statements: current.stmts,\n children: [],\n line: current.line,\n indent: current.indent,\n });\n current = null;\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n flush();\n const name = config.extractName?.(stmt.source, stmt.category);\n current = {\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n line: stmt.line,\n indent: stmt.indent,\n };\n } else if (current) {\n current.stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n flush();\n return { blocks, orphans };\n}\n\nfunction accumulateIndented<TMeta>(\n statements: readonly ParsedStatement[],\n config: BlockConfig\n): BlockResult<TMeta> {\n const rootBlocks: StatementBlock<TMeta>[] = [];\n const orphans: ParsedStatement[] = [];\n\n // Stack of open blocks with their indent level\n const stack: Array<{\n type: string;\n name?: string;\n stmts: ParsedStatement[];\n children: StatementBlock<TMeta>[];\n line: number;\n indent: number;\n }> = [];\n\n const flushTo = (targetIndent: number) => {\n while (stack.length > 0) {\n const top = stack[stack.length - 1];\n if (top.indent >= targetIndent) {\n stack.pop();\n const block: StatementBlock<TMeta> = {\n type: top.type,\n ...(top.name != null && { name: top.name }),\n statements: top.stmts,\n children: top.children,\n line: top.line,\n indent: top.indent,\n };\n if (stack.length > 0) {\n stack[stack.length - 1].children.push(block);\n } else {\n rootBlocks.push(block);\n }\n } else {\n break;\n }\n }\n };\n\n for (const stmt of statements) {\n if (stmt.category && config.blockTypes.includes(stmt.category)) {\n // Flush blocks at same or deeper indent\n flushTo(stmt.indent);\n const name = config.extractName?.(stmt.source, stmt.category);\n stack.push({\n type: stmt.category,\n ...(name != null && { name }),\n stmts: [stmt],\n children: [],\n line: stmt.line,\n indent: stmt.indent,\n });\n } else if (stack.length > 0) {\n stack[stack.length - 1].stmts.push(stmt);\n } else {\n orphans.push(stmt);\n }\n }\n\n // Flush remaining\n flushTo(-1);\n\n return { blocks: rootBlocks, orphans };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AQ,EAAE;AAEV,SAAO,EAAE,QAAQ,YAAY,QAAQ;AACvC;","names":["num","length","import_intent","import_intent","import_intent","roles","import_intent","convertCommand","detectSelectorKind","generateRoleCombinations","sampleValue","toSemanticValue","sampleSelector","sampleLiteral","sampleExpression","detectSelectorKind","toSemanticValue","import_intent","import_intent","value","kind","position","normalized","normalized"]}
|