@lokascript/framework 2.0.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.
Files changed (181) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +142 -0
  3. package/dist/aot/aot-orchestrator.d.ts +75 -0
  4. package/dist/aot/aot-orchestrator.d.ts.map +1 -0
  5. package/dist/aot/domain-scanner.d.ts +27 -0
  6. package/dist/aot/domain-scanner.d.ts.map +1 -0
  7. package/dist/aot/index.d.ts +8 -0
  8. package/dist/aot/index.d.ts.map +1 -0
  9. package/dist/aot/types.d.ts +103 -0
  10. package/dist/aot/types.d.ts.map +1 -0
  11. package/dist/api/create-dsl.d.ts +91 -0
  12. package/dist/api/create-dsl.d.ts.map +1 -0
  13. package/dist/api/dispatcher.d.ts +108 -0
  14. package/dist/api/dispatcher.d.ts.map +1 -0
  15. package/dist/api/domain-registry.d.ts +152 -0
  16. package/dist/api/domain-registry.d.ts.map +1 -0
  17. package/dist/api/index.d.ts +7 -0
  18. package/dist/api/index.d.ts.map +1 -0
  19. package/dist/api/index.js +2082 -0
  20. package/dist/api/index.js.map +1 -0
  21. package/dist/core/index.d.ts +7 -0
  22. package/dist/core/index.d.ts.map +1 -0
  23. package/dist/core/index.js +2674 -0
  24. package/dist/core/index.js.map +1 -0
  25. package/dist/core/logger.d.ts +32 -0
  26. package/dist/core/logger.d.ts.map +1 -0
  27. package/dist/core/pattern-matching/index.d.ts +6 -0
  28. package/dist/core/pattern-matching/index.d.ts.map +1 -0
  29. package/dist/core/pattern-matching/index.js +1239 -0
  30. package/dist/core/pattern-matching/index.js.map +1 -0
  31. package/dist/core/pattern-matching/pattern-matcher.d.ts +239 -0
  32. package/dist/core/pattern-matching/pattern-matcher.d.ts.map +1 -0
  33. package/dist/core/pattern-matching/utils/index.d.ts +6 -0
  34. package/dist/core/pattern-matching/utils/index.d.ts.map +1 -0
  35. package/dist/core/pattern-matching/utils/possessive-keywords.d.ts +38 -0
  36. package/dist/core/pattern-matching/utils/possessive-keywords.d.ts.map +1 -0
  37. package/dist/core/pattern-matching/utils/type-validation.d.ts +63 -0
  38. package/dist/core/pattern-matching/utils/type-validation.d.ts.map +1 -0
  39. package/dist/core/tokenization/base-tokenizer.d.ts +344 -0
  40. package/dist/core/tokenization/base-tokenizer.d.ts.map +1 -0
  41. package/dist/core/tokenization/char-classifiers.d.ts +56 -0
  42. package/dist/core/tokenization/char-classifiers.d.ts.map +1 -0
  43. package/dist/core/tokenization/default-extractors.d.ts +48 -0
  44. package/dist/core/tokenization/default-extractors.d.ts.map +1 -0
  45. package/dist/core/tokenization/extractors/index.d.ts +9 -0
  46. package/dist/core/tokenization/extractors/index.d.ts.map +1 -0
  47. package/dist/core/tokenization/extractors/operator.d.ts +23 -0
  48. package/dist/core/tokenization/extractors/operator.d.ts.map +1 -0
  49. package/dist/core/tokenization/extractors/punctuation.d.ts +22 -0
  50. package/dist/core/tokenization/extractors/punctuation.d.ts.map +1 -0
  51. package/dist/core/tokenization/extractors.d.ts +61 -0
  52. package/dist/core/tokenization/extractors.d.ts.map +1 -0
  53. package/dist/core/tokenization/index.d.ts +11 -0
  54. package/dist/core/tokenization/index.d.ts.map +1 -0
  55. package/dist/core/tokenization/index.js +1345 -0
  56. package/dist/core/tokenization/index.js.map +1 -0
  57. package/dist/core/tokenization/morphology/index.d.ts +5 -0
  58. package/dist/core/tokenization/morphology/index.d.ts.map +1 -0
  59. package/dist/core/tokenization/morphology/types.d.ts +110 -0
  60. package/dist/core/tokenization/morphology/types.d.ts.map +1 -0
  61. package/dist/core/tokenization/token-utils.d.ts +111 -0
  62. package/dist/core/tokenization/token-utils.d.ts.map +1 -0
  63. package/dist/core/types.d.ts +382 -0
  64. package/dist/core/types.d.ts.map +1 -0
  65. package/dist/core/types.js +108 -0
  66. package/dist/core/types.js.map +1 -0
  67. package/dist/generation/diagnostics.d.ts +120 -0
  68. package/dist/generation/diagnostics.d.ts.map +1 -0
  69. package/dist/generation/index.d.ts +7 -0
  70. package/dist/generation/index.d.ts.map +1 -0
  71. package/dist/generation/index.js +339 -0
  72. package/dist/generation/index.js.map +1 -0
  73. package/dist/generation/pattern-generator.d.ts +48 -0
  74. package/dist/generation/pattern-generator.d.ts.map +1 -0
  75. package/dist/generation/renderer.d.ts +115 -0
  76. package/dist/generation/renderer.d.ts.map +1 -0
  77. package/dist/grammar/index.d.ts +10 -0
  78. package/dist/grammar/index.d.ts.map +1 -0
  79. package/dist/grammar/index.js +391 -0
  80. package/dist/grammar/index.js.map +1 -0
  81. package/dist/grammar/transformer.d.ts +56 -0
  82. package/dist/grammar/transformer.d.ts.map +1 -0
  83. package/dist/grammar/types.d.ts +236 -0
  84. package/dist/grammar/types.d.ts.map +1 -0
  85. package/dist/index.cjs +4454 -0
  86. package/dist/index.cjs.map +1 -0
  87. package/dist/index.d.ts +46 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +4336 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/interfaces/dictionary.d.ts +82 -0
  92. package/dist/interfaces/dictionary.d.ts.map +1 -0
  93. package/dist/interfaces/index.d.ts +10 -0
  94. package/dist/interfaces/index.d.ts.map +1 -0
  95. package/dist/interfaces/profile-provider.d.ts +67 -0
  96. package/dist/interfaces/profile-provider.d.ts.map +1 -0
  97. package/dist/interfaces/value-extractor.d.ts +168 -0
  98. package/dist/interfaces/value-extractor.d.ts.map +1 -0
  99. package/dist/multilingual/index.d.ts +8 -0
  100. package/dist/multilingual/index.d.ts.map +1 -0
  101. package/dist/multilingual/index.js +1 -0
  102. package/dist/multilingual/index.js.map +1 -0
  103. package/dist/parsing/index.d.ts +8 -0
  104. package/dist/parsing/index.d.ts.map +1 -0
  105. package/dist/parsing/index.js +1415 -0
  106. package/dist/parsing/index.js.map +1 -0
  107. package/dist/parsing/multi-statement.d.ts +265 -0
  108. package/dist/parsing/multi-statement.d.ts.map +1 -0
  109. package/dist/schema/command-schema.d.ts +78 -0
  110. package/dist/schema/command-schema.d.ts.map +1 -0
  111. package/dist/schema/index.d.ts +5 -0
  112. package/dist/schema/index.d.ts.map +1 -0
  113. package/dist/schema/index.js +25 -0
  114. package/dist/schema/index.js.map +1 -0
  115. package/dist/test-setup.d.ts +9 -0
  116. package/dist/test-setup.d.ts.map +1 -0
  117. package/dist/testing/index.d.ts +50 -0
  118. package/dist/testing/index.d.ts.map +1 -0
  119. package/dist/testing/index.js +16969 -0
  120. package/dist/testing/index.js.map +1 -0
  121. package/package.json +122 -0
  122. package/src/__test__/fixtures/sql-dsl.ts +232 -0
  123. package/src/__test__/sql-integration.test.ts +189 -0
  124. package/src/__test__/test-utils.ts +260 -0
  125. package/src/aot/aot-orchestrator.test.ts +413 -0
  126. package/src/aot/aot-orchestrator.ts +238 -0
  127. package/src/aot/domain-scanner.ts +178 -0
  128. package/src/aot/index.ts +8 -0
  129. package/src/aot/types.ts +124 -0
  130. package/src/api/create-dsl.ts +367 -0
  131. package/src/api/dispatcher.test.ts +336 -0
  132. package/src/api/dispatcher.ts +222 -0
  133. package/src/api/domain-registry.test.ts +336 -0
  134. package/src/api/domain-registry.ts +500 -0
  135. package/src/api/index.ts +7 -0
  136. package/src/core/index.ts +7 -0
  137. package/src/core/logger.ts +130 -0
  138. package/src/core/pattern-matching/index.ts +6 -0
  139. package/src/core/pattern-matching/pattern-matcher.test.ts +900 -0
  140. package/src/core/pattern-matching/pattern-matcher.ts +1548 -0
  141. package/src/core/pattern-matching/pattern-matcher.ts.backup +1267 -0
  142. package/src/core/pattern-matching/utils/index.ts +6 -0
  143. package/src/core/pattern-matching/utils/possessive-keywords.ts +55 -0
  144. package/src/core/pattern-matching/utils/type-validation.test.ts +316 -0
  145. package/src/core/pattern-matching/utils/type-validation.ts +134 -0
  146. package/src/core/tokenization/base-tokenizer.ts +916 -0
  147. package/src/core/tokenization/char-classifiers.ts +79 -0
  148. package/src/core/tokenization/create-simple-tokenizer.test.ts +260 -0
  149. package/src/core/tokenization/default-extractors.ts +69 -0
  150. package/src/core/tokenization/extractors/index.ts +9 -0
  151. package/src/core/tokenization/extractors/operator.ts +75 -0
  152. package/src/core/tokenization/extractors/punctuation.ts +39 -0
  153. package/src/core/tokenization/extractors.ts +452 -0
  154. package/src/core/tokenization/index.ts +11 -0
  155. package/src/core/tokenization/morphology/index.ts +5 -0
  156. package/src/core/tokenization/morphology/types.ts +211 -0
  157. package/src/core/tokenization/token-utils.ts +252 -0
  158. package/src/core/types.ts +589 -0
  159. package/src/generation/diagnostics.test.ts +171 -0
  160. package/src/generation/diagnostics.ts +239 -0
  161. package/src/generation/index.ts +7 -0
  162. package/src/generation/pattern-generator.test.ts +430 -0
  163. package/src/generation/pattern-generator.ts +315 -0
  164. package/src/generation/renderer.test.ts +266 -0
  165. package/src/generation/renderer.ts +244 -0
  166. package/src/grammar/index.ts +12 -0
  167. package/src/grammar/transformer.ts +159 -0
  168. package/src/grammar/types.ts +630 -0
  169. package/src/index.ts +157 -0
  170. package/src/interfaces/dictionary.ts +123 -0
  171. package/src/interfaces/index.ts +10 -0
  172. package/src/interfaces/profile-provider.ts +88 -0
  173. package/src/interfaces/value-extractor.ts +435 -0
  174. package/src/multilingual/index.ts +9 -0
  175. package/src/parsing/index.ts +27 -0
  176. package/src/parsing/multi-statement.test.ts +480 -0
  177. package/src/parsing/multi-statement.ts +648 -0
  178. package/src/schema/command-schema.ts +118 -0
  179. package/src/schema/index.ts +5 -0
  180. package/src/test-setup.ts +45 -0
  181. package/src/testing/index.ts +137 -0
@@ -0,0 +1,2674 @@
1
+ // src/core/types.ts
2
+ function createLiteral(value, dataType) {
3
+ return dataType ? { type: "literal", value, dataType } : { type: "literal", value };
4
+ }
5
+ function createSelector(value, selectorKind) {
6
+ return selectorKind ? { type: "selector", value, selectorKind } : { type: "selector", value };
7
+ }
8
+ function createReference(value) {
9
+ return { type: "reference", value };
10
+ }
11
+ function createPropertyPath(object, property) {
12
+ return { type: "property-path", object, property };
13
+ }
14
+ function createExpression(raw) {
15
+ return { type: "expression", raw };
16
+ }
17
+ function createCommandNode(action, roles, metadata) {
18
+ const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));
19
+ const node = {
20
+ kind: "command",
21
+ action,
22
+ roles: rolesMap
23
+ };
24
+ if (metadata) {
25
+ return { ...node, metadata };
26
+ }
27
+ return node;
28
+ }
29
+ function createEventHandlerNode(action, roles, body, metadata, eventModifiers) {
30
+ const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));
31
+ const base = {
32
+ kind: "event-handler",
33
+ action,
34
+ roles: rolesMap,
35
+ body
36
+ };
37
+ return {
38
+ ...base,
39
+ ...eventModifiers && { eventModifiers },
40
+ ...metadata && { metadata }
41
+ };
42
+ }
43
+ function createConditionalNode(action, roles, thenBranch, elseBranch, metadata) {
44
+ const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));
45
+ const base = {
46
+ kind: "conditional",
47
+ action,
48
+ roles: rolesMap,
49
+ thenBranch
50
+ };
51
+ return {
52
+ ...base,
53
+ ...elseBranch && { elseBranch },
54
+ ...metadata && { metadata }
55
+ };
56
+ }
57
+ function createCompoundNode(statements, chainType = "sequential", metadata) {
58
+ const base = {
59
+ kind: "compound",
60
+ action: "compound",
61
+ roles: /* @__PURE__ */ new Map(),
62
+ statements,
63
+ chainType
64
+ };
65
+ return metadata ? { ...base, metadata } : base;
66
+ }
67
+ function extractValue(value) {
68
+ if ("raw" in value && value.raw !== void 0) return String(value.raw);
69
+ if ("value" in value && value.value !== void 0) return String(value.value);
70
+ if (value.type === "property-path") return `${extractValue(value.object)}.${value.property}`;
71
+ return "";
72
+ }
73
+ function extractRoleValue(node, role) {
74
+ const value = node.roles.get(role);
75
+ if (!value) return "";
76
+ return extractValue(value);
77
+ }
78
+ function createLoopNode(action, roles, loopVariant, body, loopVariable, indexVariable, metadata) {
79
+ const rolesMap = roles instanceof Map ? roles : new Map(Object.entries(roles));
80
+ const base = {
81
+ kind: "loop",
82
+ action,
83
+ roles: rolesMap,
84
+ loopVariant,
85
+ body
86
+ };
87
+ return {
88
+ ...base,
89
+ ...loopVariable && { loopVariable },
90
+ ...indexVariable && { indexVariable },
91
+ ...metadata && { metadata }
92
+ };
93
+ }
94
+
95
+ // src/core/tokenization/token-utils.ts
96
+ var TokenStreamImpl = class {
97
+ constructor(tokens, language) {
98
+ this.pos = 0;
99
+ this.tokens = tokens;
100
+ this.language = language;
101
+ }
102
+ peek(offset = 0) {
103
+ const index = this.pos + offset;
104
+ if (index < 0 || index >= this.tokens.length) {
105
+ return null;
106
+ }
107
+ return this.tokens[index];
108
+ }
109
+ advance() {
110
+ if (this.isAtEnd()) {
111
+ throw new Error("Unexpected end of token stream");
112
+ }
113
+ return this.tokens[this.pos++];
114
+ }
115
+ isAtEnd() {
116
+ return this.pos >= this.tokens.length;
117
+ }
118
+ mark() {
119
+ return { position: this.pos };
120
+ }
121
+ reset(mark) {
122
+ this.pos = mark.position;
123
+ }
124
+ position() {
125
+ return this.pos;
126
+ }
127
+ /**
128
+ * Get remaining tokens as an array.
129
+ */
130
+ remaining() {
131
+ return this.tokens.slice(this.pos);
132
+ }
133
+ /**
134
+ * Consume tokens while predicate is true.
135
+ */
136
+ takeWhile(predicate) {
137
+ const result = [];
138
+ while (!this.isAtEnd() && predicate(this.peek())) {
139
+ result.push(this.advance());
140
+ }
141
+ return result;
142
+ }
143
+ /**
144
+ * Skip tokens while predicate is true.
145
+ */
146
+ skipWhile(predicate) {
147
+ while (!this.isAtEnd() && predicate(this.peek())) {
148
+ this.advance();
149
+ }
150
+ }
151
+ };
152
+ function createPosition(start, end) {
153
+ return { start, end };
154
+ }
155
+ function createToken(valueOrParams, kind, position, normalizedOrOptions) {
156
+ if (typeof valueOrParams === "object") {
157
+ const { value: value2, kind: kind2, position: position2, normalized: normalized2, stem, stemConfidence, metadata } = valueOrParams;
158
+ return {
159
+ value: value2,
160
+ kind: kind2,
161
+ position: position2,
162
+ ...normalized2 !== void 0 && { normalized: normalized2 },
163
+ ...stem !== void 0 && { stem },
164
+ ...stemConfidence !== void 0 && { stemConfidence },
165
+ ...metadata !== void 0 && { metadata }
166
+ };
167
+ }
168
+ const value = valueOrParams;
169
+ if (!kind || !position) {
170
+ throw new Error("createToken requires kind and position parameters");
171
+ }
172
+ if (typeof normalizedOrOptions === "string") {
173
+ return { value, kind, position, normalized: normalizedOrOptions };
174
+ }
175
+ if (normalizedOrOptions) {
176
+ const { normalized: normalized2, stem, stemConfidence, metadata } = normalizedOrOptions;
177
+ return {
178
+ value,
179
+ kind,
180
+ position,
181
+ ...normalized2 !== void 0 && { normalized: normalized2 },
182
+ ...stem !== void 0 && { stem },
183
+ ...stemConfidence !== void 0 && { stemConfidence },
184
+ ...metadata !== void 0 && { metadata }
185
+ };
186
+ }
187
+ return { value, kind, position };
188
+ }
189
+ function isWhitespace(char) {
190
+ return /\s/.test(char);
191
+ }
192
+ function isSelectorStart(char) {
193
+ return char === "#" || char === "." || char === "[" || char === "@" || char === "*" || char === "<";
194
+ }
195
+ function isQuote(char) {
196
+ return char === '"' || char === "'" || char === "`" || char === "\u300C" || char === "\u300D";
197
+ }
198
+ function isDigit(char) {
199
+ return /\d/.test(char);
200
+ }
201
+ function isAsciiLetter(char) {
202
+ return /[a-zA-Z]/.test(char);
203
+ }
204
+ function isAsciiIdentifierChar(char) {
205
+ return /[a-zA-Z0-9_-]/.test(char);
206
+ }
207
+
208
+ // src/core/tokenization/extractors.ts
209
+ function extractCssSelector(input, startPos) {
210
+ if (startPos >= input.length) return null;
211
+ const char = input[startPos];
212
+ if (!isSelectorStart(char)) return null;
213
+ let pos = startPos;
214
+ let selector = "";
215
+ if (char === "#" || char === ".") {
216
+ selector += input[pos++];
217
+ while (pos < input.length && isAsciiIdentifierChar(input[pos])) {
218
+ selector += input[pos++];
219
+ }
220
+ if (selector.length <= 1) return null;
221
+ if (pos < input.length && input[pos] === "." && char === "#") {
222
+ const methodStart = pos + 1;
223
+ let methodEnd = methodStart;
224
+ while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {
225
+ methodEnd++;
226
+ }
227
+ if (methodEnd < input.length && input[methodEnd] === "(") {
228
+ return selector;
229
+ }
230
+ }
231
+ } else if (char === "[") {
232
+ let depth = 1;
233
+ let inQuote = false;
234
+ let quoteChar = null;
235
+ let escaped = false;
236
+ selector += input[pos++];
237
+ while (pos < input.length && depth > 0) {
238
+ const c = input[pos];
239
+ selector += c;
240
+ if (escaped) {
241
+ escaped = false;
242
+ } else if (c === "\\") {
243
+ escaped = true;
244
+ } else if (inQuote) {
245
+ if (c === quoteChar) {
246
+ inQuote = false;
247
+ quoteChar = null;
248
+ }
249
+ } else {
250
+ if (c === '"' || c === "'" || c === "`") {
251
+ inQuote = true;
252
+ quoteChar = c;
253
+ } else if (c === "[") {
254
+ depth++;
255
+ } else if (c === "]") {
256
+ depth--;
257
+ }
258
+ }
259
+ pos++;
260
+ }
261
+ if (depth !== 0) return null;
262
+ } else if (char === "@") {
263
+ selector += input[pos++];
264
+ while (pos < input.length && isAsciiIdentifierChar(input[pos])) {
265
+ selector += input[pos++];
266
+ }
267
+ if (selector.length <= 1) return null;
268
+ } else if (char === "*") {
269
+ selector += input[pos++];
270
+ while (pos < input.length && isAsciiIdentifierChar(input[pos])) {
271
+ selector += input[pos++];
272
+ }
273
+ if (selector.length <= 1) return null;
274
+ } else if (char === "<") {
275
+ selector += input[pos++];
276
+ if (pos >= input.length || !isAsciiLetter(input[pos])) return null;
277
+ while (pos < input.length && isAsciiIdentifierChar(input[pos])) {
278
+ selector += input[pos++];
279
+ }
280
+ while (pos < input.length) {
281
+ const modChar = input[pos];
282
+ if (modChar === ".") {
283
+ selector += input[pos++];
284
+ if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {
285
+ return null;
286
+ }
287
+ while (pos < input.length && isAsciiIdentifierChar(input[pos])) {
288
+ selector += input[pos++];
289
+ }
290
+ } else if (modChar === "#") {
291
+ selector += input[pos++];
292
+ if (pos >= input.length || !isAsciiIdentifierChar(input[pos])) {
293
+ return null;
294
+ }
295
+ while (pos < input.length && isAsciiIdentifierChar(input[pos])) {
296
+ selector += input[pos++];
297
+ }
298
+ } else if (modChar === "[") {
299
+ let depth = 1;
300
+ let inQuote = false;
301
+ let quoteChar = null;
302
+ let escaped = false;
303
+ selector += input[pos++];
304
+ while (pos < input.length && depth > 0) {
305
+ const c = input[pos];
306
+ selector += c;
307
+ if (escaped) {
308
+ escaped = false;
309
+ } else if (c === "\\") {
310
+ escaped = true;
311
+ } else if (inQuote) {
312
+ if (c === quoteChar) {
313
+ inQuote = false;
314
+ quoteChar = null;
315
+ }
316
+ } else {
317
+ if (c === '"' || c === "'" || c === "`") {
318
+ inQuote = true;
319
+ quoteChar = c;
320
+ } else if (c === "[") {
321
+ depth++;
322
+ } else if (c === "]") {
323
+ depth--;
324
+ }
325
+ }
326
+ pos++;
327
+ }
328
+ if (depth !== 0) return null;
329
+ } else {
330
+ break;
331
+ }
332
+ }
333
+ while (pos < input.length && isWhitespace(input[pos])) {
334
+ selector += input[pos++];
335
+ }
336
+ if (pos < input.length && input[pos] === "/") {
337
+ selector += input[pos++];
338
+ while (pos < input.length && isWhitespace(input[pos])) {
339
+ selector += input[pos++];
340
+ }
341
+ }
342
+ if (pos >= input.length || input[pos] !== ">") return null;
343
+ selector += input[pos++];
344
+ }
345
+ return selector || null;
346
+ }
347
+ function isPossessiveMarker(input, pos) {
348
+ if (pos >= input.length || input[pos] !== "'") return false;
349
+ if (pos + 1 >= input.length) return false;
350
+ const nextChar = input[pos + 1].toLowerCase();
351
+ if (nextChar !== "s") return false;
352
+ if (pos + 2 >= input.length) return true;
353
+ const afterS = input[pos + 2];
354
+ return isWhitespace(afterS) || afterS === "*" || !isAsciiIdentifierChar(afterS);
355
+ }
356
+ function extractStringLiteral(input, startPos) {
357
+ if (startPos >= input.length) return null;
358
+ const openQuote = input[startPos];
359
+ if (!isQuote(openQuote)) return null;
360
+ if (openQuote === "'" && isPossessiveMarker(input, startPos)) {
361
+ return null;
362
+ }
363
+ const closeQuoteMap = {
364
+ '"': '"',
365
+ "'": "'",
366
+ "`": "`",
367
+ "\u300C": "\u300D"
368
+ };
369
+ const closeQuote = closeQuoteMap[openQuote];
370
+ if (!closeQuote) return null;
371
+ let pos = startPos + 1;
372
+ let literal = openQuote;
373
+ let escaped = false;
374
+ while (pos < input.length) {
375
+ const char = input[pos];
376
+ literal += char;
377
+ if (escaped) {
378
+ escaped = false;
379
+ } else if (char === "\\") {
380
+ escaped = true;
381
+ } else if (char === closeQuote) {
382
+ return literal;
383
+ }
384
+ pos++;
385
+ }
386
+ return literal;
387
+ }
388
+ function isUrlStart(input, pos) {
389
+ if (pos >= input.length) return false;
390
+ const char = input[pos];
391
+ const next = input[pos + 1] || "";
392
+ const third = input[pos + 2] || "";
393
+ if (char === "/" && next !== "/" && /[a-zA-Z0-9._-]/.test(next)) {
394
+ return true;
395
+ }
396
+ if (char === "/" && next === "/" && /[a-zA-Z]/.test(third)) {
397
+ return true;
398
+ }
399
+ if (char === "." && (next === "/" || next === "." && third === "/")) {
400
+ return true;
401
+ }
402
+ const slice = input.slice(pos, pos + 8).toLowerCase();
403
+ if (slice.startsWith("http://") || slice.startsWith("https://")) {
404
+ return true;
405
+ }
406
+ return false;
407
+ }
408
+ function extractUrl(input, startPos) {
409
+ if (!isUrlStart(input, startPos)) return null;
410
+ let pos = startPos;
411
+ let url = "";
412
+ const urlChars = /[a-zA-Z0-9/:._\-?&=%@+~!$'()*,;[\]]/;
413
+ while (pos < input.length) {
414
+ const char = input[pos];
415
+ if (char === "#") {
416
+ if (url.length > 0 && /[a-zA-Z0-9/.]$/.test(url)) {
417
+ url += char;
418
+ pos++;
419
+ while (pos < input.length && /[a-zA-Z0-9_-]/.test(input[pos])) {
420
+ url += input[pos++];
421
+ }
422
+ }
423
+ break;
424
+ }
425
+ if (urlChars.test(char)) {
426
+ url += char;
427
+ pos++;
428
+ } else {
429
+ break;
430
+ }
431
+ }
432
+ if (url.length < 2) return null;
433
+ return url;
434
+ }
435
+ function extractNumber(input, startPos) {
436
+ if (startPos >= input.length) return null;
437
+ const char = input[startPos];
438
+ if (!isDigit(char) && char !== "-" && char !== "+") return null;
439
+ let pos = startPos;
440
+ let number = "";
441
+ if (input[pos] === "-" || input[pos] === "+") {
442
+ number += input[pos++];
443
+ }
444
+ if (pos >= input.length || !isDigit(input[pos])) {
445
+ return null;
446
+ }
447
+ while (pos < input.length && isDigit(input[pos])) {
448
+ number += input[pos++];
449
+ }
450
+ if (pos < input.length && input[pos] === ".") {
451
+ number += input[pos++];
452
+ while (pos < input.length && isDigit(input[pos])) {
453
+ number += input[pos++];
454
+ }
455
+ }
456
+ if (pos < input.length) {
457
+ const suffix = input.slice(pos, pos + 2);
458
+ if (suffix === "ms") {
459
+ number += "ms";
460
+ } else if (input[pos] === "s" || input[pos] === "m" || input[pos] === "h") {
461
+ number += input[pos];
462
+ }
463
+ }
464
+ return number;
465
+ }
466
+
467
+ // src/core/tokenization/extractors/operator.ts
468
+ var DEFAULT_OPERATORS = [
469
+ // Three-character operators
470
+ "===",
471
+ "!==",
472
+ "->",
473
+ // Two-character operators
474
+ "==",
475
+ "!=",
476
+ "<=",
477
+ ">=",
478
+ "&&",
479
+ "||",
480
+ "**",
481
+ "+=",
482
+ "-=",
483
+ "*=",
484
+ "/=",
485
+ // Single-character operators
486
+ "+",
487
+ "-",
488
+ "*",
489
+ "/",
490
+ "=",
491
+ ">",
492
+ "<",
493
+ "!",
494
+ "&",
495
+ "|",
496
+ "%",
497
+ "^",
498
+ "~"
499
+ ];
500
+ var OperatorExtractor = class {
501
+ constructor(operators = DEFAULT_OPERATORS) {
502
+ this.operators = operators;
503
+ this.name = "operator";
504
+ this.operators = [...operators].sort((a, b) => b.length - a.length);
505
+ }
506
+ canExtract(input, position) {
507
+ return this.operators.some((op) => input.startsWith(op, position));
508
+ }
509
+ extract(input, position) {
510
+ for (const op of this.operators) {
511
+ if (input.startsWith(op, position)) {
512
+ return {
513
+ value: op,
514
+ length: op.length
515
+ };
516
+ }
517
+ }
518
+ return null;
519
+ }
520
+ };
521
+
522
+ // src/core/tokenization/extractors/punctuation.ts
523
+ var DEFAULT_PUNCTUATION = "()[]{},:;";
524
+ var PunctuationExtractor = class {
525
+ constructor(punctuation = DEFAULT_PUNCTUATION) {
526
+ this.punctuation = punctuation;
527
+ this.name = "punctuation";
528
+ }
529
+ canExtract(input, position) {
530
+ return this.punctuation.includes(input[position]);
531
+ }
532
+ extract(input, position) {
533
+ const char = input[position];
534
+ if (this.punctuation.includes(char)) {
535
+ return {
536
+ value: char,
537
+ length: 1
538
+ };
539
+ }
540
+ return null;
541
+ }
542
+ };
543
+
544
+ // src/interfaces/value-extractor.ts
545
+ var StringLiteralExtractor = class {
546
+ constructor() {
547
+ this.name = "string-literal";
548
+ }
549
+ canExtract(input, position) {
550
+ const char = input[position];
551
+ return char === '"' || char === "'" || char === "`" || char === "\u201C" || // Chinese double quote open "
552
+ char === "\u2018";
553
+ }
554
+ extract(input, position) {
555
+ const quote = input[position];
556
+ if (quote === "\u201C") {
557
+ let length2 = 1;
558
+ while (position + length2 < input.length) {
559
+ if (input[position + length2] === "\u201D") {
560
+ length2++;
561
+ return { value: input.substring(position, position + length2), length: length2 };
562
+ }
563
+ length2++;
564
+ }
565
+ return null;
566
+ }
567
+ if (quote === "\u2018") {
568
+ let length2 = 1;
569
+ while (position + length2 < input.length) {
570
+ if (input[position + length2] === "\u2019") {
571
+ length2++;
572
+ return { value: input.substring(position, position + length2), length: length2 };
573
+ }
574
+ length2++;
575
+ }
576
+ return null;
577
+ }
578
+ let length = 1;
579
+ let escaped = false;
580
+ while (position + length < input.length) {
581
+ const char = input[position + length];
582
+ if (escaped) {
583
+ escaped = false;
584
+ length++;
585
+ continue;
586
+ }
587
+ if (char === "\\") {
588
+ escaped = true;
589
+ length++;
590
+ continue;
591
+ }
592
+ if (char === quote) {
593
+ length++;
594
+ return {
595
+ value: input.substring(position, position + length),
596
+ length
597
+ };
598
+ }
599
+ length++;
600
+ }
601
+ return null;
602
+ }
603
+ };
604
+ var NumberExtractor = class {
605
+ constructor() {
606
+ this.name = "number";
607
+ }
608
+ canExtract(input, position) {
609
+ return /\d/.test(input[position]);
610
+ }
611
+ extract(input, position) {
612
+ let length = 0;
613
+ let hasDecimal = false;
614
+ while (position + length < input.length) {
615
+ const char = input[position + length];
616
+ if (/\d/.test(char)) {
617
+ length++;
618
+ } else if (char === "." && !hasDecimal) {
619
+ hasDecimal = true;
620
+ length++;
621
+ } else {
622
+ break;
623
+ }
624
+ }
625
+ if (length === 0) return null;
626
+ const numValue = input.substring(position, position + length);
627
+ const afterNum = position + length;
628
+ if (afterNum < input.length) {
629
+ const remaining = input.slice(afterNum);
630
+ const cjkMultiUnits = [
631
+ { pattern: "\u6BEB\u79D2", suffix: "ms" },
632
+ // Chinese milliseconds
633
+ { pattern: "\u5206\u949F", suffix: "m" },
634
+ // Chinese minutes
635
+ { pattern: "\u5C0F\u65F6", suffix: "h" },
636
+ // Chinese hours
637
+ { pattern: "\u30DF\u30EA\u79D2", suffix: "ms" },
638
+ // Japanese milliseconds
639
+ { pattern: "\u6642\u9593", suffix: "h" }
640
+ // Japanese hours
641
+ ];
642
+ for (const unit of cjkMultiUnits) {
643
+ if (remaining.startsWith(unit.pattern)) {
644
+ return {
645
+ value: numValue + unit.suffix,
646
+ length: length + unit.pattern.length,
647
+ metadata: { hasTimeUnit: true }
648
+ };
649
+ }
650
+ }
651
+ if (remaining.startsWith("ms")) {
652
+ return {
653
+ value: numValue + "ms",
654
+ length: length + 2,
655
+ metadata: { hasTimeUnit: true }
656
+ };
657
+ }
658
+ const cjkSingleUnits = [
659
+ { pattern: "\u79D2", suffix: "s" },
660
+ // CJK seconds
661
+ { pattern: "\u5206", suffix: "m" }
662
+ // CJK minutes
663
+ ];
664
+ for (const unit of cjkSingleUnits) {
665
+ if (remaining.startsWith(unit.pattern)) {
666
+ return {
667
+ value: numValue + unit.suffix,
668
+ length: length + 1,
669
+ metadata: { hasTimeUnit: true }
670
+ };
671
+ }
672
+ }
673
+ if (/^[smh](?![a-zA-Z])/.test(remaining)) {
674
+ return {
675
+ value: numValue + remaining[0],
676
+ length: length + 1,
677
+ metadata: { hasTimeUnit: true }
678
+ };
679
+ }
680
+ }
681
+ return { value: numValue, length };
682
+ }
683
+ };
684
+ var IdentifierExtractor = class {
685
+ constructor() {
686
+ this.name = "identifier";
687
+ }
688
+ canExtract(input, position) {
689
+ return /[a-zA-Z_]/.test(input[position]);
690
+ }
691
+ extract(input, position) {
692
+ let length = 0;
693
+ while (position + length < input.length) {
694
+ const char = input[position + length];
695
+ if (/[a-zA-Z0-9_]/.test(char)) {
696
+ length++;
697
+ } else {
698
+ break;
699
+ }
700
+ }
701
+ return length > 0 ? {
702
+ value: input.substring(position, position + length),
703
+ length
704
+ } : null;
705
+ }
706
+ };
707
+ var UnicodeIdentifierExtractor = class {
708
+ constructor() {
709
+ this.name = "unicode-identifier";
710
+ }
711
+ canExtract(input, position) {
712
+ const code = input.charCodeAt(position);
713
+ if (code < 128) return false;
714
+ return /\p{L}/u.test(input[position]);
715
+ }
716
+ extract(input, position) {
717
+ let length = 0;
718
+ while (position + length < input.length) {
719
+ const char = input[position + length];
720
+ if (/[\p{L}\p{N}\p{M}]/u.test(char)) {
721
+ length++;
722
+ } else {
723
+ break;
724
+ }
725
+ }
726
+ return length > 0 ? { value: input.substring(position, position + length), length } : null;
727
+ }
728
+ };
729
+ function isContextAwareExtractor(extractor) {
730
+ return "setContext" in extractor && typeof extractor.setContext === "function";
731
+ }
732
+ function createTokenizerContext(tokenizer) {
733
+ const ctx = {
734
+ language: tokenizer.language,
735
+ direction: tokenizer.direction,
736
+ lookupKeyword: tokenizer.lookupKeyword.bind(tokenizer),
737
+ isKeyword: tokenizer.isKeyword.bind(tokenizer),
738
+ isKeywordStart: tokenizer.isKeywordStart.bind(tokenizer)
739
+ };
740
+ if (tokenizer.normalizer) {
741
+ return { ...ctx, normalizer: tokenizer.normalizer };
742
+ }
743
+ return ctx;
744
+ }
745
+
746
+ // src/core/tokenization/default-extractors.ts
747
+ function getDefaultExtractors() {
748
+ return [
749
+ new StringLiteralExtractor(),
750
+ // "strings", 'strings', `strings`
751
+ new NumberExtractor(),
752
+ // 123, 45.67
753
+ new OperatorExtractor(),
754
+ // +, -, *, /, =, >, <, etc.
755
+ new PunctuationExtractor(),
756
+ // ( ) [ ] { } , : ;
757
+ new IdentifierExtractor(),
758
+ // variable_names, functionNames (ASCII)
759
+ new UnicodeIdentifierExtractor()
760
+ // CJK, Arabic, Cyrillic, etc.
761
+ ];
762
+ }
763
+ function withDefaultExtractors(tokenizer) {
764
+ tokenizer.registerExtractors(getDefaultExtractors());
765
+ return tokenizer;
766
+ }
767
+
768
+ // src/core/tokenization/char-classifiers.ts
769
+ function createUnicodeRangeClassifier(ranges) {
770
+ return (char) => {
771
+ const code = char.charCodeAt(0);
772
+ return ranges.some(([start, end]) => code >= start && code <= end);
773
+ };
774
+ }
775
+ function combineClassifiers(...classifiers) {
776
+ return (char) => classifiers.some((fn) => fn(char));
777
+ }
778
+ function createLatinCharClassifiers(letterPattern) {
779
+ const isLetter = (char) => letterPattern.test(char);
780
+ const isIdentifierChar = (char) => isLetter(char) || /[0-9_-]/.test(char);
781
+ return { isLetter, isIdentifierChar };
782
+ }
783
+
784
+ // src/core/tokenization/base-tokenizer.ts
785
+ var SIMPLE_TOKENIZER_OPERATOR_SET = new Set(DEFAULT_OPERATORS);
786
+ var _BaseTokenizer = class _BaseTokenizer {
787
+ constructor() {
788
+ /** Keywords derived from profile, sorted longest-first for greedy matching */
789
+ this.profileKeywords = [];
790
+ /** Map for O(1) keyword lookups by lowercase native word */
791
+ this.profileKeywordMap = /* @__PURE__ */ new Map();
792
+ /**
793
+ * Pluggable value extractors for domain-specific syntax.
794
+ * When registered, BaseTokenizer will use extractor-based tokenization instead of legacy methods.
795
+ */
796
+ this.extractors = [];
797
+ }
798
+ /**
799
+ * Tokenize input string to token stream.
800
+ * Delegates to extractor-based tokenization if extractors are registered,
801
+ * otherwise subclass must override this method.
802
+ *
803
+ * @param input - Input string to tokenize
804
+ * @returns Token stream
805
+ */
806
+ tokenize(input) {
807
+ if (this.isUsingExtractors()) {
808
+ return this.tokenizeWithExtractors(input);
809
+ }
810
+ throw new Error(
811
+ `${this.constructor.name}: tokenize() not implemented and no extractors registered. Either register extractors or override tokenize() method.`
812
+ );
813
+ }
814
+ /**
815
+ * Register a value extractor for domain-specific syntax.
816
+ * Extractors are tried in registration order during tokenization.
817
+ * Context-aware extractors automatically receive the tokenizer context.
818
+ *
819
+ * @param extractor - Value extractor to register
820
+ */
821
+ registerExtractor(extractor) {
822
+ if (isContextAwareExtractor(extractor)) {
823
+ extractor.setContext(createTokenizerContext(this));
824
+ }
825
+ this.extractors.push(extractor);
826
+ }
827
+ /**
828
+ * Register multiple value extractors at once.
829
+ *
830
+ * @param extractors - Array of value extractors to register
831
+ */
832
+ registerExtractors(extractors) {
833
+ for (const extractor of extractors) {
834
+ this.registerExtractor(extractor);
835
+ }
836
+ }
837
+ /**
838
+ * Clear all registered extractors.
839
+ * Returns tokenizer to legacy mode.
840
+ */
841
+ clearExtractors() {
842
+ this.extractors = [];
843
+ }
844
+ /**
845
+ * Check if this tokenizer is using extractor-based tokenization.
846
+ * Returns true if any extractors are registered.
847
+ */
848
+ isUsingExtractors() {
849
+ return this.extractors.length > 0;
850
+ }
851
+ /**
852
+ * Tokenize input using registered value extractors.
853
+ * This is the new path - extractors handle all syntax detection.
854
+ *
855
+ * @param input - Input string to tokenize
856
+ * @returns Token stream
857
+ */
858
+ tokenizeWithExtractors(input) {
859
+ const tokens = [];
860
+ let pos = 0;
861
+ while (pos < input.length) {
862
+ while (pos < input.length && isWhitespace(input[pos])) {
863
+ pos++;
864
+ }
865
+ if (pos >= input.length) break;
866
+ let extracted = false;
867
+ for (const extractor of this.extractors) {
868
+ if (extractor.canExtract(input, pos)) {
869
+ const result = extractor.extract(input, pos);
870
+ if (result) {
871
+ const normalized2 = result.metadata?.normalized;
872
+ const stem = result.metadata?.stem;
873
+ const stemConfidence = result.metadata?.stemConfidence;
874
+ const cleanMetadata = {};
875
+ if (result.metadata) {
876
+ for (const [key, value] of Object.entries(result.metadata)) {
877
+ if (key !== "normalized" && key !== "stem" && key !== "stemConfidence") {
878
+ cleanMetadata[key] = value;
879
+ }
880
+ }
881
+ }
882
+ const options = {};
883
+ if (normalized2) options.normalized = normalized2;
884
+ if (stem) options.stem = stem;
885
+ if (stemConfidence !== void 0) options.stemConfidence = stemConfidence;
886
+ if (Object.keys(cleanMetadata).length > 0) options.metadata = cleanMetadata;
887
+ tokens.push(
888
+ createToken(
889
+ result.value,
890
+ this.classifyToken(result.value),
891
+ createPosition(pos, pos + result.length),
892
+ Object.keys(options).length > 0 ? options : void 0
893
+ )
894
+ );
895
+ pos += result.length;
896
+ extracted = true;
897
+ break;
898
+ }
899
+ }
900
+ }
901
+ if (!extracted) {
902
+ const char = input[pos];
903
+ const kind = this.classifyUnknownChar(char);
904
+ tokens.push(createToken(char, kind, createPosition(pos, pos + 1)));
905
+ pos++;
906
+ }
907
+ }
908
+ return new TokenStreamImpl(tokens, this.language);
909
+ }
910
+ /**
911
+ * Classify an unknown character when no extractor matches.
912
+ * Provides sensible defaults for common syntax.
913
+ *
914
+ * @param char - Character to classify
915
+ * @returns Token kind
916
+ */
917
+ classifyUnknownChar(char) {
918
+ if ("()[]{},:;".includes(char)) return "punctuation";
919
+ if ("+-*/<>=!&|".includes(char)) return "operator";
920
+ return "identifier";
921
+ }
922
+ /**
923
+ * Check if current position is a property access (obj.prop) vs CSS selector (.active).
924
+ * Property access: no whitespace before '.', previous token is identifier/keyword/selector.
925
+ * Also detects standalone method calls: .identifier( pattern.
926
+ *
927
+ * Returns true if '.' was emitted as an operator token and pos should advance by 1.
928
+ * Returns false if this is a CSS selector and should be handled by trySelector().
929
+ */
930
+ tryPropertyAccess(input, pos, tokens) {
931
+ if (input[pos] !== ".") return false;
932
+ const lastToken = tokens[tokens.length - 1];
933
+ const hasWhitespaceBefore = lastToken && lastToken.position.end < pos;
934
+ const isPropertyAccess = lastToken && !hasWhitespaceBefore && (lastToken.kind === "identifier" || lastToken.kind === "keyword" || lastToken.kind === "selector");
935
+ if (isPropertyAccess) {
936
+ tokens.push(createToken(".", "operator", createPosition(pos, pos + 1)));
937
+ return true;
938
+ }
939
+ const methodStart = pos + 1;
940
+ let methodEnd = methodStart;
941
+ while (methodEnd < input.length && isAsciiIdentifierChar(input[methodEnd])) {
942
+ methodEnd++;
943
+ }
944
+ if (methodEnd < input.length && input[methodEnd] === "(") {
945
+ tokens.push(createToken(".", "operator", createPosition(pos, pos + 1)));
946
+ return true;
947
+ }
948
+ return false;
949
+ }
950
+ /**
951
+ * Initialize keyword mappings from a language profile.
952
+ * Builds a list of native→english mappings from:
953
+ * - profile.keywords (primary + alternatives)
954
+ * - profile.references (me, it, you, etc.)
955
+ * - profile.roleMarkers (into, from, with, etc.)
956
+ *
957
+ * Results are sorted longest-first for greedy matching (important for non-space languages).
958
+ * Extras take precedence over profile entries when there are duplicates.
959
+ *
960
+ * @param profile - Language profile containing keyword translations
961
+ * @param extras - Additional keyword entries to include (literals, positional, events)
962
+ */
963
+ initializeKeywordsFromProfile(profile, extras = []) {
964
+ const keywordMap = /* @__PURE__ */ new Map();
965
+ if (profile.keywords) {
966
+ for (const [normalized2, translation] of Object.entries(profile.keywords)) {
967
+ keywordMap.set(translation.primary, {
968
+ native: translation.primary,
969
+ normalized: translation.normalized || normalized2
970
+ });
971
+ if (translation.alternatives) {
972
+ for (const alt of translation.alternatives) {
973
+ keywordMap.set(alt, {
974
+ native: alt,
975
+ normalized: translation.normalized || normalized2
976
+ });
977
+ }
978
+ }
979
+ }
980
+ }
981
+ if (profile.references) {
982
+ for (const [normalized2, native] of Object.entries(profile.references)) {
983
+ keywordMap.set(native, { native, normalized: normalized2 });
984
+ }
985
+ for (const canonical of Object.keys(profile.references)) {
986
+ if (!keywordMap.has(canonical)) {
987
+ keywordMap.set(canonical, { native: canonical, normalized: canonical });
988
+ }
989
+ }
990
+ }
991
+ if (profile.roleMarkers) {
992
+ for (const [role, marker] of Object.entries(profile.roleMarkers)) {
993
+ if (marker.primary) {
994
+ keywordMap.set(marker.primary, { native: marker.primary, normalized: role });
995
+ }
996
+ if (marker.alternatives) {
997
+ for (const alt of marker.alternatives) {
998
+ keywordMap.set(alt, { native: alt, normalized: role });
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ if (profile.possessive?.keywords) {
1004
+ for (const [native, normalized2] of Object.entries(profile.possessive.keywords)) {
1005
+ keywordMap.set(native, { native, normalized: normalized2 });
1006
+ }
1007
+ }
1008
+ for (const extra of extras) {
1009
+ keywordMap.set(extra.native, extra);
1010
+ }
1011
+ this.profileKeywords = Array.from(keywordMap.values()).sort(
1012
+ (a, b) => b.native.length - a.native.length
1013
+ );
1014
+ this.profileKeywordMap = /* @__PURE__ */ new Map();
1015
+ for (const keyword of this.profileKeywords) {
1016
+ this.profileKeywordMap.set(keyword.native.toLowerCase(), keyword);
1017
+ const normalized2 = this.removeDiacritics(keyword.native);
1018
+ if (normalized2 !== keyword.native && !this.profileKeywordMap.has(normalized2.toLowerCase())) {
1019
+ this.profileKeywordMap.set(normalized2.toLowerCase(), keyword);
1020
+ }
1021
+ }
1022
+ }
1023
+ /**
1024
+ * Remove diacritical marks from a word for normalization.
1025
+ * Primarily for Arabic (shadda, fatha, kasra, damma, sukun, etc.)
1026
+ * but could be extended for other languages.
1027
+ *
1028
+ * @param word - Word to normalize
1029
+ * @returns Word without diacritics
1030
+ */
1031
+ removeDiacritics(word) {
1032
+ return word.replace(/[\u064B-\u0652\u0670]/g, "");
1033
+ }
1034
+ /**
1035
+ * Try to match a keyword from profile at the current position.
1036
+ * Uses longest-first greedy matching (important for non-space languages).
1037
+ *
1038
+ * @param input - Input string
1039
+ * @param pos - Current position
1040
+ * @returns Token if matched, null otherwise
1041
+ */
1042
+ tryProfileKeyword(input, pos) {
1043
+ for (const entry of this.profileKeywords) {
1044
+ if (input.slice(pos).startsWith(entry.native)) {
1045
+ return createToken(
1046
+ entry.native,
1047
+ "keyword",
1048
+ createPosition(pos, pos + entry.native.length),
1049
+ entry.normalized
1050
+ );
1051
+ }
1052
+ }
1053
+ return null;
1054
+ }
1055
+ /**
1056
+ * Check if the remaining input starts with any known keyword.
1057
+ * Useful for non-space languages to detect word boundaries.
1058
+ *
1059
+ * @param input - Input string
1060
+ * @param pos - Current position
1061
+ * @returns true if a keyword starts at this position
1062
+ */
1063
+ isKeywordStart(input, pos) {
1064
+ const remaining = input.slice(pos);
1065
+ return this.profileKeywords.some((entry) => remaining.startsWith(entry.native));
1066
+ }
1067
+ /**
1068
+ * Look up a keyword by native word (case-insensitive).
1069
+ * O(1) lookup using the keyword map.
1070
+ *
1071
+ * @param native - Native word to look up
1072
+ * @returns KeywordEntry if found, undefined otherwise
1073
+ */
1074
+ lookupKeyword(native) {
1075
+ return this.profileKeywordMap.get(native.toLowerCase());
1076
+ }
1077
+ /**
1078
+ * Check if a word is a known keyword (case-insensitive).
1079
+ * O(1) lookup using the keyword map.
1080
+ *
1081
+ * @param native - Native word to check
1082
+ * @returns true if the word is a keyword
1083
+ */
1084
+ isKeyword(native) {
1085
+ return this.profileKeywordMap.has(native.toLowerCase());
1086
+ }
1087
+ /**
1088
+ * Set the morphological normalizer for this tokenizer.
1089
+ */
1090
+ setNormalizer(normalizer) {
1091
+ this.normalizer = normalizer;
1092
+ }
1093
+ /**
1094
+ * Try to normalize a word using the morphological normalizer.
1095
+ * Returns null if no normalizer is set or normalization fails.
1096
+ *
1097
+ * Note: We don't check isNormalizable() here because the individual tokenizers
1098
+ * historically called normalize() directly without that check. The normalize()
1099
+ * method itself handles returning noChange() for words that can't be normalized.
1100
+ */
1101
+ tryNormalize(word) {
1102
+ if (!this.normalizer) return null;
1103
+ const result = this.normalizer.normalize(word);
1104
+ if (result.stem !== word && result.confidence >= 0.7) {
1105
+ return result;
1106
+ }
1107
+ return null;
1108
+ }
1109
+ /**
1110
+ * Try morphological normalization and keyword lookup.
1111
+ *
1112
+ * If the word can be normalized to a stem that matches a known keyword,
1113
+ * returns a keyword token with morphological metadata (stem, stemConfidence).
1114
+ *
1115
+ * This is the common pattern for handling conjugated verbs across languages:
1116
+ * 1. Normalize the word (e.g., "toggled" → "toggle")
1117
+ * 2. Look up the stem in the keyword map
1118
+ * 3. Create a token with both the original form and stem metadata
1119
+ *
1120
+ * @param word - The word to normalize and look up
1121
+ * @param startPos - Start position for the token
1122
+ * @param endPos - End position for the token
1123
+ * @returns Token if stem matches a keyword, null otherwise
1124
+ */
1125
+ tryMorphKeywordMatch(word, startPos, endPos) {
1126
+ const result = this.tryNormalize(word);
1127
+ if (!result) return null;
1128
+ const stemEntry = this.lookupKeyword(result.stem);
1129
+ if (!stemEntry) return null;
1130
+ const tokenOptions = {
1131
+ normalized: stemEntry.normalized,
1132
+ stem: result.stem,
1133
+ stemConfidence: result.confidence
1134
+ };
1135
+ return createToken(word, "keyword", createPosition(startPos, endPos), tokenOptions);
1136
+ }
1137
+ /**
1138
+ * Try to extract a CSS selector at the current position.
1139
+ */
1140
+ trySelector(input, pos) {
1141
+ const selector = extractCssSelector(input, pos);
1142
+ if (selector) {
1143
+ return createToken(selector, "selector", createPosition(pos, pos + selector.length));
1144
+ }
1145
+ return null;
1146
+ }
1147
+ /**
1148
+ * Try to extract an event modifier at the current position.
1149
+ * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)
1150
+ */
1151
+ tryEventModifier(input, pos) {
1152
+ if (input[pos] !== ".") {
1153
+ return null;
1154
+ }
1155
+ const match = input.slice(pos).match(/^\.(?:once|debounce|throttle|queue)(?:\(([^)]+)\))?(?:\s|$|\.)/);
1156
+ if (!match) {
1157
+ return null;
1158
+ }
1159
+ const fullMatch = match[0].replace(/(\s|\.)$/, "");
1160
+ const modifierName = fullMatch.slice(1).split("(")[0];
1161
+ const value = match[1];
1162
+ const token = createToken(
1163
+ fullMatch,
1164
+ "event-modifier",
1165
+ createPosition(pos, pos + fullMatch.length)
1166
+ );
1167
+ return {
1168
+ ...token,
1169
+ metadata: {
1170
+ modifierName,
1171
+ value: value ? modifierName === "queue" ? value : parseInt(value, 10) : void 0
1172
+ }
1173
+ };
1174
+ }
1175
+ /**
1176
+ * Try to extract a string literal at the current position.
1177
+ */
1178
+ tryString(input, pos) {
1179
+ const literal = extractStringLiteral(input, pos);
1180
+ if (literal) {
1181
+ return createToken(literal, "literal", createPosition(pos, pos + literal.length));
1182
+ }
1183
+ return null;
1184
+ }
1185
+ /**
1186
+ * Try to extract a number at the current position.
1187
+ */
1188
+ tryNumber(input, pos) {
1189
+ const number = extractNumber(input, pos);
1190
+ if (number) {
1191
+ return createToken(number, "literal", createPosition(pos, pos + number.length));
1192
+ }
1193
+ return null;
1194
+ }
1195
+ /**
1196
+ * Try to match a time unit from a list of patterns.
1197
+ *
1198
+ * @param input - Input string
1199
+ * @param pos - Position after the number
1200
+ * @param timeUnits - Array of time unit mappings (native pattern → standard suffix)
1201
+ * @param skipWhitespace - Whether to skip whitespace before time unit (default: false)
1202
+ * @returns Object with matched suffix and new position, or null if no match
1203
+ */
1204
+ tryMatchTimeUnit(input, pos, timeUnits, skipWhitespace = false) {
1205
+ let unitPos = pos;
1206
+ if (skipWhitespace) {
1207
+ while (unitPos < input.length && isWhitespace(input[unitPos])) {
1208
+ unitPos++;
1209
+ }
1210
+ }
1211
+ const remaining = input.slice(unitPos);
1212
+ for (const unit of timeUnits) {
1213
+ const candidate = remaining.slice(0, unit.length);
1214
+ const matches = unit.caseInsensitive ? candidate.toLowerCase() === unit.pattern.toLowerCase() : candidate === unit.pattern;
1215
+ if (matches) {
1216
+ if (unit.notFollowedBy) {
1217
+ const nextChar = remaining[unit.length] || "";
1218
+ if (nextChar === unit.notFollowedBy) continue;
1219
+ }
1220
+ if (unit.checkBoundary) {
1221
+ const nextChar = remaining[unit.length] || "";
1222
+ if (isAsciiIdentifierChar(nextChar)) continue;
1223
+ }
1224
+ return { suffix: unit.suffix, endPos: unitPos + unit.length };
1225
+ }
1226
+ }
1227
+ return null;
1228
+ }
1229
+ /**
1230
+ * Parse a base number (sign, integer, decimal) without time units.
1231
+ * Returns the number string and end position.
1232
+ *
1233
+ * @param input - Input string
1234
+ * @param startPos - Start position
1235
+ * @param allowSign - Whether to allow +/- sign (default: true)
1236
+ * @returns Object with number string and end position, or null
1237
+ */
1238
+ parseBaseNumber(input, startPos, allowSign = true) {
1239
+ let pos = startPos;
1240
+ let number = "";
1241
+ if (allowSign && (input[pos] === "-" || input[pos] === "+")) {
1242
+ number += input[pos++];
1243
+ }
1244
+ if (pos >= input.length || !isDigit(input[pos])) {
1245
+ return null;
1246
+ }
1247
+ while (pos < input.length && isDigit(input[pos])) {
1248
+ number += input[pos++];
1249
+ }
1250
+ if (pos < input.length && input[pos] === ".") {
1251
+ number += input[pos++];
1252
+ while (pos < input.length && isDigit(input[pos])) {
1253
+ number += input[pos++];
1254
+ }
1255
+ }
1256
+ if (!number || number === "-" || number === "+") return null;
1257
+ return { number, endPos: pos };
1258
+ }
1259
+ /**
1260
+ * Try to extract a number with native language time units.
1261
+ *
1262
+ * This is a template method that handles the common pattern:
1263
+ * 1. Parse the base number (sign, integer, decimal)
1264
+ * 2. Try to match native language time units
1265
+ * 3. Fall back to standard time units (ms, s, m, h)
1266
+ *
1267
+ * @param input - Input string
1268
+ * @param pos - Start position
1269
+ * @param nativeTimeUnits - Language-specific time unit mappings
1270
+ * @param options - Configuration options
1271
+ * @returns Token if number found, null otherwise
1272
+ */
1273
+ tryNumberWithTimeUnits(input, pos, nativeTimeUnits, options = {}) {
1274
+ const { allowSign = true, skipWhitespace = false } = options;
1275
+ const baseResult = this.parseBaseNumber(input, pos, allowSign);
1276
+ if (!baseResult) return null;
1277
+ let { number, endPos } = baseResult;
1278
+ const allUnits = [...nativeTimeUnits, ..._BaseTokenizer.STANDARD_TIME_UNITS];
1279
+ const timeMatch = this.tryMatchTimeUnit(input, endPos, allUnits, skipWhitespace);
1280
+ if (timeMatch) {
1281
+ number += timeMatch.suffix;
1282
+ endPos = timeMatch.endPos;
1283
+ }
1284
+ return createToken(number, "literal", createPosition(pos, endPos));
1285
+ }
1286
+ /**
1287
+ * Try to extract a URL at the current position.
1288
+ * Handles /path, ./path, ../path, //domain.com, http://, https://
1289
+ */
1290
+ tryUrl(input, pos) {
1291
+ const url = extractUrl(input, pos);
1292
+ if (url) {
1293
+ return createToken(url, "url", createPosition(pos, pos + url.length));
1294
+ }
1295
+ return null;
1296
+ }
1297
+ /**
1298
+ * Try to extract a variable reference (:varname) at the current position.
1299
+ * In hyperscript, :x refers to a local variable named x.
1300
+ */
1301
+ tryVariableRef(input, pos) {
1302
+ if (input[pos] !== ":") return null;
1303
+ if (pos + 1 >= input.length) return null;
1304
+ if (!isAsciiIdentifierChar(input[pos + 1])) return null;
1305
+ let endPos = pos + 1;
1306
+ while (endPos < input.length && isAsciiIdentifierChar(input[endPos])) {
1307
+ endPos++;
1308
+ }
1309
+ const varRef = input.slice(pos, endPos);
1310
+ return createToken(varRef, "identifier", createPosition(pos, endPos));
1311
+ }
1312
+ /**
1313
+ * Try to extract an operator or punctuation token at the current position.
1314
+ * Handles two-character operators (==, !=, etc.) and single-character operators.
1315
+ */
1316
+ tryOperator(input, pos) {
1317
+ const twoChar = input.slice(pos, pos + 2);
1318
+ if (["==", "!=", "<=", ">=", "&&", "||", "->"].includes(twoChar)) {
1319
+ return createToken(twoChar, "operator", createPosition(pos, pos + 2));
1320
+ }
1321
+ const oneChar = input[pos];
1322
+ if (["<", ">", "!", "+", "-", "*", "/", "="].includes(oneChar)) {
1323
+ return createToken(oneChar, "operator", createPosition(pos, pos + 1));
1324
+ }
1325
+ if (["(", ")", "{", "}", ",", ";", ":"].includes(oneChar)) {
1326
+ return createToken(oneChar, "punctuation", createPosition(pos, pos + 1));
1327
+ }
1328
+ return null;
1329
+ }
1330
+ /**
1331
+ * Try to match a multi-character particle from a list.
1332
+ *
1333
+ * Used by languages like Japanese, Korean, and Chinese that have
1334
+ * multi-character particles (e.g., Japanese から, まで, より).
1335
+ *
1336
+ * @param input - Input string
1337
+ * @param pos - Current position
1338
+ * @param particles - Array of multi-character particles to match
1339
+ * @returns Token if matched, null otherwise
1340
+ */
1341
+ tryMultiCharParticle(input, pos, particles) {
1342
+ for (const particle of particles) {
1343
+ if (input.slice(pos, pos + particle.length) === particle) {
1344
+ return createToken(particle, "particle", createPosition(pos, pos + particle.length));
1345
+ }
1346
+ }
1347
+ return null;
1348
+ }
1349
+ };
1350
+ /**
1351
+ * Configuration for native language time units.
1352
+ * Maps patterns to their standard suffix (ms, s, m, h).
1353
+ */
1354
+ _BaseTokenizer.STANDARD_TIME_UNITS = [
1355
+ { pattern: "ms", suffix: "ms", length: 2 },
1356
+ { pattern: "s", suffix: "s", length: 1, checkBoundary: true },
1357
+ { pattern: "m", suffix: "m", length: 1, checkBoundary: true, notFollowedBy: "s" },
1358
+ { pattern: "h", suffix: "h", length: 1, checkBoundary: true }
1359
+ ];
1360
+ var BaseTokenizer = _BaseTokenizer;
1361
+ function createSimpleTokenizer(config) {
1362
+ const {
1363
+ language,
1364
+ direction = "ltr",
1365
+ keywords,
1366
+ keywordExtras,
1367
+ keywordProfile,
1368
+ includeOperators = false,
1369
+ caseInsensitive = true,
1370
+ customExtractors
1371
+ } = config;
1372
+ const keywordSet = new Set(caseInsensitive ? keywords.map((k) => k.toLowerCase()) : keywords);
1373
+ class SimpleTokenizer extends BaseTokenizer {
1374
+ constructor() {
1375
+ super();
1376
+ this.language = language;
1377
+ this.direction = direction;
1378
+ if (customExtractors) {
1379
+ this.registerExtractors(customExtractors);
1380
+ }
1381
+ this.registerExtractors(getDefaultExtractors());
1382
+ if (keywordProfile) {
1383
+ this.initializeKeywordsFromProfile(keywordProfile, keywordExtras);
1384
+ }
1385
+ }
1386
+ classifyToken(token) {
1387
+ const lookup = caseInsensitive ? token.toLowerCase() : token;
1388
+ if (keywordSet.has(lookup)) return "keyword";
1389
+ if (this.isKeyword(token)) return "keyword";
1390
+ if (/^\d/.test(token)) return "literal";
1391
+ if (/^['"]/.test(token)) return "literal";
1392
+ if (includeOperators && SIMPLE_TOKENIZER_OPERATOR_SET.has(token)) return "operator";
1393
+ return "identifier";
1394
+ }
1395
+ }
1396
+ return new SimpleTokenizer();
1397
+ }
1398
+
1399
+ // src/core/tokenization/morphology/types.ts
1400
+ function noChange(word) {
1401
+ return { stem: word, confidence: 1 };
1402
+ }
1403
+ function normalized(stem, confidence, metadata) {
1404
+ if (metadata) {
1405
+ return { stem, confidence, metadata };
1406
+ }
1407
+ return { stem, confidence };
1408
+ }
1409
+
1410
+ // src/core/logger.ts
1411
+ var DebugLogger = class {
1412
+ constructor(namespace) {
1413
+ this.namespace = namespace;
1414
+ this.enabled = this.checkEnabled();
1415
+ }
1416
+ checkEnabled() {
1417
+ if (typeof process !== "undefined" && process.env) {
1418
+ const DEBUG = process.env.DEBUG || "";
1419
+ return DEBUG === "*" || DEBUG.includes("framework:*") || DEBUG.includes(`framework:${this.namespace}`);
1420
+ }
1421
+ return false;
1422
+ }
1423
+ log(level, message, ...args) {
1424
+ if (!this.enabled) return;
1425
+ const prefix = `[framework:${this.namespace}]`;
1426
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1427
+ switch (level) {
1428
+ case "debug":
1429
+ console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);
1430
+ break;
1431
+ case "info":
1432
+ console.info(`${timestamp} ${prefix} INFO:`, message, ...args);
1433
+ break;
1434
+ case "warn":
1435
+ console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);
1436
+ break;
1437
+ case "error":
1438
+ console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);
1439
+ break;
1440
+ }
1441
+ }
1442
+ debug(message, ...args) {
1443
+ this.log("debug", message, ...args);
1444
+ }
1445
+ info(message, ...args) {
1446
+ this.log("info", message, ...args);
1447
+ }
1448
+ warn(message, ...args) {
1449
+ this.log("warn", message, ...args);
1450
+ }
1451
+ error(message, ...args) {
1452
+ this.log("error", message, ...args);
1453
+ }
1454
+ /**
1455
+ * Check if logging is enabled for this namespace.
1456
+ */
1457
+ isEnabled() {
1458
+ return this.enabled;
1459
+ }
1460
+ /**
1461
+ * Programmatically enable logging for this namespace.
1462
+ */
1463
+ enable() {
1464
+ this.enabled = true;
1465
+ }
1466
+ /**
1467
+ * Programmatically disable logging for this namespace.
1468
+ */
1469
+ disable() {
1470
+ this.enabled = false;
1471
+ }
1472
+ };
1473
+ function createLogger(namespace) {
1474
+ return new DebugLogger(namespace);
1475
+ }
1476
+
1477
+ // src/core/pattern-matching/utils/type-validation.ts
1478
+ function isTypeCompatible(actualType, expectedTypes) {
1479
+ if (!expectedTypes || expectedTypes.length === 0) {
1480
+ return true;
1481
+ }
1482
+ if (expectedTypes.includes(actualType)) {
1483
+ return true;
1484
+ }
1485
+ if (expectedTypes.includes("expression")) {
1486
+ return true;
1487
+ }
1488
+ if (actualType === "property-path") {
1489
+ return expectedTypes.some((t) => ["selector", "reference", "expression"].includes(t));
1490
+ }
1491
+ return false;
1492
+ }
1493
+ function validateValueType(value, expectedTypes) {
1494
+ if (!expectedTypes || expectedTypes.length === 0) {
1495
+ return true;
1496
+ }
1497
+ return isTypeCompatible(value.type, expectedTypes);
1498
+ }
1499
+ function isCSSSelector(value) {
1500
+ return value.startsWith(".") || value.startsWith("#") || value.startsWith("<");
1501
+ }
1502
+ function isClassName(value) {
1503
+ return value.startsWith(".");
1504
+ }
1505
+ function isIdSelector(value) {
1506
+ return value.startsWith("#");
1507
+ }
1508
+ function isCSSPropertyRef(value) {
1509
+ return value.startsWith("*");
1510
+ }
1511
+ function isNumericValue(value) {
1512
+ const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
1513
+ if (durationMatch) {
1514
+ return true;
1515
+ }
1516
+ const num = parseFloat(value);
1517
+ return !isNaN(num) && isFinite(num);
1518
+ }
1519
+ function isPropertyName(value) {
1520
+ return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);
1521
+ }
1522
+ function isVariableRef(value) {
1523
+ return value.startsWith(":");
1524
+ }
1525
+ function isBuiltInReference(value) {
1526
+ const builtIns = /* @__PURE__ */ new Set(["me", "you", "it", "result", "event", "target", "body"]);
1527
+ return builtIns.has(value.toLowerCase());
1528
+ }
1529
+
1530
+ // src/core/pattern-matching/utils/possessive-keywords.ts
1531
+ function getPossessiveReference(profile, keyword) {
1532
+ return profile?.possessive?.keywords?.[keyword];
1533
+ }
1534
+ function isPossessiveKeyword(profile, keyword) {
1535
+ return profile?.possessive?.keywords?.[keyword] !== void 0;
1536
+ }
1537
+ function getAllPossessiveKeywords(profile) {
1538
+ return profile?.possessive?.keywords ?? {};
1539
+ }
1540
+
1541
+ // src/core/pattern-matching/pattern-matcher.ts
1542
+ function isValidReference(_value) {
1543
+ return false;
1544
+ }
1545
+ var _PatternMatcher = class _PatternMatcher {
1546
+ constructor() {
1547
+ /** Debug logger */
1548
+ this.logger = createLogger("pattern-matcher");
1549
+ /**
1550
+ * Track stem matches for confidence calculation.
1551
+ * This is set during matching and read during confidence calculation.
1552
+ */
1553
+ this.stemMatchCount = 0;
1554
+ this.totalKeywordMatches = 0;
1555
+ }
1556
+ /**
1557
+ * Safely convert a value to lowercase string.
1558
+ * Provides protection against non-string values at runtime.
1559
+ */
1560
+ safeToLowerCase(value) {
1561
+ if (typeof value === "string") {
1562
+ return value.toLowerCase();
1563
+ }
1564
+ if (value === null || value === void 0) {
1565
+ return "";
1566
+ }
1567
+ return String(value).toLowerCase();
1568
+ }
1569
+ /**
1570
+ * Try to match a single pattern against the token stream.
1571
+ * Returns the match result or null if no match.
1572
+ *
1573
+ * @param tokens - Token stream to match against
1574
+ * @param pattern - Pattern to match
1575
+ * @param profile - Optional language profile for possessive handling
1576
+ */
1577
+ matchPattern(tokens, pattern, profile) {
1578
+ const mark = tokens.mark();
1579
+ const captured = /* @__PURE__ */ new Map();
1580
+ this.logger.debug("========================================");
1581
+ this.logger.debug("matchPattern ENTRY");
1582
+ this.logger.debug("Pattern ID:", pattern.id);
1583
+ this.logger.debug("Pattern command:", pattern.command);
1584
+ this.logger.debug("Pattern language:", pattern.language);
1585
+ this.logger.debug("Pattern template:", JSON.stringify(pattern.template, null, 2));
1586
+ if (this.logger.isEnabled()) {
1587
+ const firstTokens = [];
1588
+ for (let i = 0; i < 10; i++) {
1589
+ const t = tokens.peek(i);
1590
+ if (t)
1591
+ firstTokens.push({
1592
+ type: t.type,
1593
+ value: t.value,
1594
+ kind: t.kind
1595
+ });
1596
+ else break;
1597
+ }
1598
+ this.logger.debug("Input tokens (first 10):", firstTokens);
1599
+ this.logger.debug("Profile code:", profile?.code);
1600
+ }
1601
+ this.currentProfile = profile;
1602
+ this.stemMatchCount = 0;
1603
+ this.totalKeywordMatches = 0;
1604
+ this.logger.debug("--- Calling matchTokenSequence ---");
1605
+ this.logger.debug("Pattern tokens to match:", JSON.stringify(pattern.template.tokens, null, 2));
1606
+ const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);
1607
+ this.logger.debug("matchTokenSequence returned:", success);
1608
+ this.logger.debug(
1609
+ "Captured roles:",
1610
+ Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])
1611
+ );
1612
+ if (!success) {
1613
+ this.logger.debug(">>> MATCH FAILED - resetting token position");
1614
+ tokens.reset(mark);
1615
+ return null;
1616
+ }
1617
+ const confidence = this.calculateConfidence(pattern, captured);
1618
+ this.applyExtractionRules(pattern, captured);
1619
+ return {
1620
+ pattern,
1621
+ captured,
1622
+ consumedTokens: tokens.position() - mark.position,
1623
+ confidence
1624
+ };
1625
+ }
1626
+ /**
1627
+ * Try to match multiple patterns, return the best match.
1628
+ *
1629
+ * @param tokens - Token stream to match against
1630
+ * @param patterns - Candidate patterns to try
1631
+ * @param profile - Optional language profile for possessive handling
1632
+ */
1633
+ matchBest(tokens, patterns, profile) {
1634
+ const matches = [];
1635
+ for (const pattern of patterns) {
1636
+ const mark = tokens.mark();
1637
+ const result = this.matchPattern(tokens, pattern, profile);
1638
+ if (result) {
1639
+ matches.push(result);
1640
+ }
1641
+ tokens.reset(mark);
1642
+ }
1643
+ if (matches.length === 0) {
1644
+ return null;
1645
+ }
1646
+ matches.sort((a, b) => {
1647
+ const priorityDiff = b.pattern.priority - a.pattern.priority;
1648
+ if (priorityDiff !== 0) return priorityDiff;
1649
+ const confidenceDiff = b.confidence - a.confidence;
1650
+ if (Math.abs(confidenceDiff) > 1e-3) return confidenceDiff;
1651
+ return b.consumedTokens - a.consumedTokens;
1652
+ });
1653
+ const best = matches[0];
1654
+ this.matchPattern(tokens, best.pattern);
1655
+ return best;
1656
+ }
1657
+ /**
1658
+ * Match a sequence of pattern tokens against the token stream.
1659
+ *
1660
+ * Supports bounded single-step backtracking: if an optional role consumes
1661
+ * a token and the immediately following pattern token fails, the matcher
1662
+ * resets to before the optional role and retries the failed token.
1663
+ */
1664
+ matchTokenSequence(tokens, patternTokens, captured) {
1665
+ const firstPatternToken = patternTokens[0];
1666
+ const patternExpectsConjunction = firstPatternToken?.type === "literal" && (firstPatternToken.value === "and" || firstPatternToken.value === "then" || firstPatternToken.alternatives?.includes("and") || firstPatternToken.alternatives?.includes("then"));
1667
+ if (this.currentProfile?.code === "ar" && !patternExpectsConjunction) {
1668
+ while (tokens.peek()?.kind === "conjunction") {
1669
+ tokens.advance();
1670
+ }
1671
+ }
1672
+ let prevOptionalMark = null;
1673
+ let prevOptionalRole = null;
1674
+ for (let i = 0; i < patternTokens.length; i++) {
1675
+ const patternToken = patternTokens[i];
1676
+ this.logger.debug(" >> Matching pattern token:", JSON.stringify(patternToken, null, 2));
1677
+ const currTok = tokens.peek();
1678
+ this.logger.debug(
1679
+ " >> Current input token:",
1680
+ currTok ? JSON.stringify({
1681
+ type: currTok.type,
1682
+ value: currTok.value,
1683
+ kind: currTok.kind
1684
+ }) : "EOF"
1685
+ );
1686
+ if (patternToken.type === "role" && patternToken.greedy) {
1687
+ const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);
1688
+ const values = [];
1689
+ while (!tokens.isAtEnd()) {
1690
+ const nextToken = tokens.peek();
1691
+ if (!nextToken) break;
1692
+ if (this.isStopMarker(nextToken, stopMarkers)) break;
1693
+ values.push(nextToken.value);
1694
+ tokens.advance();
1695
+ }
1696
+ if (values.length > 0) {
1697
+ captured.set(patternToken.role, { type: "expression", raw: values.join(" ") });
1698
+ prevOptionalMark = null;
1699
+ prevOptionalRole = null;
1700
+ continue;
1701
+ } else if (patternToken.optional) {
1702
+ continue;
1703
+ } else {
1704
+ return false;
1705
+ }
1706
+ }
1707
+ const isOptionalRole = patternToken.type === "role" && patternToken.optional === true;
1708
+ const markBefore = isOptionalRole ? tokens.mark() : null;
1709
+ const matched = this.matchPatternToken(tokens, patternToken, captured);
1710
+ this.logger.debug(" >> Match result:", matched);
1711
+ if (matched) {
1712
+ if (isOptionalRole) {
1713
+ prevOptionalMark = markBefore;
1714
+ prevOptionalRole = patternToken.role;
1715
+ } else {
1716
+ prevOptionalMark = null;
1717
+ prevOptionalRole = null;
1718
+ }
1719
+ continue;
1720
+ }
1721
+ this.logger.debug(" >> Token match FAILED");
1722
+ if (this.isOptional(patternToken)) {
1723
+ continue;
1724
+ }
1725
+ if (prevOptionalMark && prevOptionalRole) {
1726
+ this.logger.debug(" >> BACKTRACKING: undoing optional role", prevOptionalRole);
1727
+ tokens.reset(prevOptionalMark);
1728
+ captured.delete(prevOptionalRole);
1729
+ prevOptionalMark = null;
1730
+ prevOptionalRole = null;
1731
+ const retryMatched = this.matchPatternToken(tokens, patternToken, captured);
1732
+ this.logger.debug(" >> Backtrack retry result:", retryMatched);
1733
+ if (retryMatched) {
1734
+ continue;
1735
+ }
1736
+ }
1737
+ return false;
1738
+ }
1739
+ return true;
1740
+ }
1741
+ /**
1742
+ * Match a single pattern token against the current position in the stream.
1743
+ */
1744
+ matchPatternToken(tokens, patternToken, captured) {
1745
+ switch (patternToken.type) {
1746
+ case "literal":
1747
+ return this.matchLiteralToken(tokens, patternToken);
1748
+ case "role":
1749
+ return this.matchRoleToken(tokens, patternToken, captured);
1750
+ case "group":
1751
+ return this.matchGroupToken(tokens, patternToken, captured);
1752
+ default:
1753
+ return false;
1754
+ }
1755
+ }
1756
+ /**
1757
+ * Match a literal pattern token (keyword or particle).
1758
+ */
1759
+ matchLiteralToken(tokens, patternToken) {
1760
+ const token = tokens.peek();
1761
+ this.logger.debug(" >>> matchLiteralToken: expecting", patternToken.value);
1762
+ this.logger.debug(
1763
+ " >>> matchLiteralToken: got token",
1764
+ token ? JSON.stringify({
1765
+ type: token.type,
1766
+ value: token.value,
1767
+ kind: token.kind
1768
+ }) : "null"
1769
+ );
1770
+ if (!token) {
1771
+ this.logger.debug(" >>> matchLiteralToken: FAIL - no token");
1772
+ return false;
1773
+ }
1774
+ const matchType = this.getMatchType(token, patternToken.value);
1775
+ this.logger.debug(
1776
+ " >>> matchType for",
1777
+ token.value,
1778
+ "vs",
1779
+ patternToken.value,
1780
+ ":",
1781
+ matchType
1782
+ );
1783
+ if (matchType !== "none") {
1784
+ this.totalKeywordMatches++;
1785
+ if (matchType === "stem") {
1786
+ this.stemMatchCount++;
1787
+ }
1788
+ tokens.advance();
1789
+ return true;
1790
+ }
1791
+ if (patternToken.alternatives) {
1792
+ for (const alt of patternToken.alternatives) {
1793
+ const altMatchType = this.getMatchType(token, alt);
1794
+ if (altMatchType !== "none") {
1795
+ this.totalKeywordMatches++;
1796
+ if (altMatchType === "stem") {
1797
+ this.stemMatchCount++;
1798
+ }
1799
+ tokens.advance();
1800
+ return true;
1801
+ }
1802
+ }
1803
+ }
1804
+ return false;
1805
+ }
1806
+ /**
1807
+ * Match a role pattern token (captures a semantic value).
1808
+ * Handles multi-token expressions like:
1809
+ * - 'my value' (possessive keyword + property)
1810
+ * - '#dialog.showModal()' (method call)
1811
+ * - "#element's *opacity" (possessive selector + property)
1812
+ */
1813
+ matchRoleToken(tokens, patternToken, captured) {
1814
+ this.logger.debug(" >>> matchRoleToken ENTRY: capturing role", patternToken.role);
1815
+ this.logger.debug(" >>> matchRoleToken: expected types", patternToken.expectedTypes);
1816
+ this.logger.debug(" >>> matchRoleToken: optional?", patternToken.optional);
1817
+ this.skipNoiseWords(tokens);
1818
+ const token = tokens.peek();
1819
+ this.logger.debug(
1820
+ " >>> After skipNoiseWords, current token:",
1821
+ token ? JSON.stringify({ value: token.value, kind: token.kind }) : "null"
1822
+ );
1823
+ if (!token) {
1824
+ return patternToken.optional || false;
1825
+ }
1826
+ const possessiveValue = this.tryMatchPossessiveExpression(tokens);
1827
+ if (possessiveValue) {
1828
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
1829
+ if (!patternToken.expectedTypes.includes(possessiveValue.type) && !patternToken.expectedTypes.includes("expression")) {
1830
+ return patternToken.optional || false;
1831
+ }
1832
+ }
1833
+ captured.set(patternToken.role, possessiveValue);
1834
+ return true;
1835
+ }
1836
+ const methodCallValue = this.tryMatchMethodCallExpression(tokens);
1837
+ if (methodCallValue) {
1838
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
1839
+ if (!patternToken.expectedTypes.includes(methodCallValue.type) && !patternToken.expectedTypes.includes("expression")) {
1840
+ return patternToken.optional || false;
1841
+ }
1842
+ }
1843
+ captured.set(patternToken.role, methodCallValue);
1844
+ return true;
1845
+ }
1846
+ const possessiveSelectorValue = this.tryMatchPossessiveSelectorExpression(tokens);
1847
+ if (possessiveSelectorValue) {
1848
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
1849
+ if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {
1850
+ return patternToken.optional || false;
1851
+ }
1852
+ }
1853
+ captured.set(patternToken.role, possessiveSelectorValue);
1854
+ return true;
1855
+ }
1856
+ const propertyAccessValue = this.tryMatchPropertyAccessExpression(tokens);
1857
+ if (propertyAccessValue) {
1858
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
1859
+ if (!patternToken.expectedTypes.includes(propertyAccessValue.type) && !patternToken.expectedTypes.includes("expression")) {
1860
+ return patternToken.optional || false;
1861
+ }
1862
+ }
1863
+ captured.set(patternToken.role, propertyAccessValue);
1864
+ return true;
1865
+ }
1866
+ const selectorPropertyValue = this.tryMatchSelectorPropertyExpression(tokens);
1867
+ if (selectorPropertyValue) {
1868
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
1869
+ if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {
1870
+ return patternToken.optional || false;
1871
+ }
1872
+ }
1873
+ captured.set(patternToken.role, selectorPropertyValue);
1874
+ return true;
1875
+ }
1876
+ this.logger.debug(
1877
+ " >>> Trying tokenToSemanticValue for token:",
1878
+ token ? JSON.stringify({ value: token.value, kind: token.kind }) : "null"
1879
+ );
1880
+ const value = this.tokenToSemanticValue(token);
1881
+ this.logger.debug(
1882
+ " >>> tokenToSemanticValue returned:",
1883
+ value ? JSON.stringify(value) : "null"
1884
+ );
1885
+ if (!value) {
1886
+ return patternToken.optional || false;
1887
+ }
1888
+ this.logger.debug(
1889
+ " >>> Validating type:",
1890
+ value.type,
1891
+ "against expected:",
1892
+ patternToken.expectedTypes
1893
+ );
1894
+ if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
1895
+ if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {
1896
+ this.logger.debug(" >>> TYPE MISMATCH - returning", patternToken.optional || false);
1897
+ return patternToken.optional || false;
1898
+ }
1899
+ }
1900
+ this.logger.debug(" >>> Type validation PASSED");
1901
+ captured.set(patternToken.role, value);
1902
+ tokens.advance();
1903
+ return true;
1904
+ }
1905
+ /**
1906
+ * Try to match a possessive expression like 'my value' or 'its innerHTML'.
1907
+ * Returns the PropertyPathValue if matched, or null if not.
1908
+ */
1909
+ tryMatchPossessiveExpression(tokens) {
1910
+ const token = tokens.peek();
1911
+ if (!token) return null;
1912
+ if (!this.currentProfile) return null;
1913
+ const tokenValue = token.normalized || token.value;
1914
+ const tokenLower = this.safeToLowerCase(tokenValue);
1915
+ const baseRef = getPossessiveReference(this.currentProfile, tokenLower);
1916
+ if (!baseRef) return null;
1917
+ const mark = tokens.mark();
1918
+ tokens.advance();
1919
+ const propertyToken = tokens.peek();
1920
+ if (!propertyToken) {
1921
+ tokens.reset(mark);
1922
+ return null;
1923
+ }
1924
+ if (propertyToken.kind === "identifier" || propertyToken.kind === "keyword" && !this.isStructuralKeyword(propertyToken.value) || propertyToken.kind === "selector" && propertyToken.value.startsWith("*") || propertyToken.kind === "selector" && propertyToken.value.startsWith("@") || propertyToken.kind === "selector" && propertyToken.value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyToken.value)) {
1925
+ tokens.advance();
1926
+ let propertyName = propertyToken.value;
1927
+ if (propertyToken.kind === "selector" && propertyName.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyName)) {
1928
+ propertyName = propertyName.substring(1);
1929
+ }
1930
+ let chainedProps = propertyName;
1931
+ while (tokens.peek()?.kind === "selector" && tokens.peek().value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(tokens.peek().value)) {
1932
+ chainedProps += tokens.peek().value;
1933
+ tokens.advance();
1934
+ }
1935
+ const nextPeek = tokens.peek();
1936
+ if (nextPeek?.kind === "literal" && nextPeek.value.startsWith("(")) {
1937
+ chainedProps += nextPeek.value;
1938
+ tokens.advance();
1939
+ }
1940
+ return createPropertyPath(createReference(baseRef), chainedProps);
1941
+ }
1942
+ tokens.reset(mark);
1943
+ return null;
1944
+ }
1945
+ /**
1946
+ * Check if a keyword is a structural keyword (preposition, control flow, etc.)
1947
+ * that shouldn't be consumed as a property name.
1948
+ */
1949
+ isStructuralKeyword(value) {
1950
+ const structural = /* @__PURE__ */ new Set([
1951
+ // Prepositions
1952
+ "into",
1953
+ "in",
1954
+ "to",
1955
+ "from",
1956
+ "at",
1957
+ "by",
1958
+ "with",
1959
+ "without",
1960
+ "before",
1961
+ "after",
1962
+ "of",
1963
+ "as",
1964
+ "on",
1965
+ // Control flow
1966
+ "then",
1967
+ "end",
1968
+ "else",
1969
+ "if",
1970
+ "repeat",
1971
+ "while",
1972
+ "for",
1973
+ // Commands (shouldn't be property names)
1974
+ "toggle",
1975
+ "add",
1976
+ "remove",
1977
+ "put",
1978
+ "set",
1979
+ "show",
1980
+ "hide",
1981
+ "increment",
1982
+ "decrement",
1983
+ "send",
1984
+ "trigger",
1985
+ "call"
1986
+ ]);
1987
+ return structural.has(value.toLowerCase());
1988
+ }
1989
+ /**
1990
+ * Try to match a method call expression like '#dialog.showModal()'.
1991
+ * Pattern: selector + '.' + identifier + '(' + [args] + ')'
1992
+ * Returns an expression value if matched, or null if not.
1993
+ */
1994
+ tryMatchMethodCallExpression(tokens) {
1995
+ const token = tokens.peek();
1996
+ if (!token || token.kind !== "selector") return null;
1997
+ const mark = tokens.mark();
1998
+ tokens.advance();
1999
+ const dotToken = tokens.peek();
2000
+ if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
2001
+ tokens.reset(mark);
2002
+ return null;
2003
+ }
2004
+ tokens.advance();
2005
+ const methodToken = tokens.peek();
2006
+ if (!methodToken || methodToken.kind !== "identifier") {
2007
+ tokens.reset(mark);
2008
+ return null;
2009
+ }
2010
+ tokens.advance();
2011
+ const openParen = tokens.peek();
2012
+ if (!openParen || openParen.kind !== "punctuation" || openParen.value !== "(") {
2013
+ tokens.reset(mark);
2014
+ return null;
2015
+ }
2016
+ tokens.advance();
2017
+ const args = [];
2018
+ while (!tokens.isAtEnd() && args.length < _PatternMatcher.MAX_METHOD_ARGS) {
2019
+ const argToken = tokens.peek();
2020
+ if (!argToken) break;
2021
+ if (argToken.kind === "punctuation" && argToken.value === ")") {
2022
+ tokens.advance();
2023
+ break;
2024
+ }
2025
+ if (argToken.kind === "punctuation" && argToken.value === ",") {
2026
+ tokens.advance();
2027
+ continue;
2028
+ }
2029
+ args.push(argToken.value);
2030
+ tokens.advance();
2031
+ }
2032
+ const methodCall = `${token.value}.${methodToken.value}(${args.join(", ")})`;
2033
+ return {
2034
+ type: "expression",
2035
+ raw: methodCall
2036
+ };
2037
+ }
2038
+ /**
2039
+ * Try to match a property access expression like 'userData.name' or 'it.data'.
2040
+ * Pattern: (identifier | keyword) + '.' + identifier [+ '.' + identifier ...]
2041
+ * Returns an expression value if matched, or null if not.
2042
+ */
2043
+ tryMatchPropertyAccessExpression(tokens) {
2044
+ const token = tokens.peek();
2045
+ if (!token) return null;
2046
+ if (token.kind !== "identifier" && token.kind !== "keyword") return null;
2047
+ const mark = tokens.mark();
2048
+ tokens.advance();
2049
+ const dotToken = tokens.peek();
2050
+ if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
2051
+ tokens.reset(mark);
2052
+ return null;
2053
+ }
2054
+ tokens.advance();
2055
+ const propertyToken = tokens.peek();
2056
+ if (!propertyToken || propertyToken.kind !== "identifier") {
2057
+ tokens.reset(mark);
2058
+ return null;
2059
+ }
2060
+ tokens.advance();
2061
+ let chain = `${token.value}.${propertyToken.value}`;
2062
+ let depth = 1;
2063
+ while (!tokens.isAtEnd() && depth < _PatternMatcher.MAX_PROPERTY_DEPTH) {
2064
+ const nextDot = tokens.peek();
2065
+ if (!nextDot || nextDot.kind !== "operator" || nextDot.value !== ".") {
2066
+ break;
2067
+ }
2068
+ tokens.advance();
2069
+ const nextProp = tokens.peek();
2070
+ if (!nextProp || nextProp.kind !== "identifier") {
2071
+ break;
2072
+ }
2073
+ tokens.advance();
2074
+ chain += `.${nextProp.value}`;
2075
+ depth++;
2076
+ }
2077
+ const openParen = tokens.peek();
2078
+ if (openParen && openParen.kind === "punctuation" && openParen.value === "(") {
2079
+ tokens.advance();
2080
+ const args = [];
2081
+ let argDepth = 0;
2082
+ while (!tokens.isAtEnd() && args.length < _PatternMatcher.MAX_METHOD_ARGS) {
2083
+ const argToken = tokens.peek();
2084
+ if (!argToken) break;
2085
+ if (argToken.kind === "punctuation" && argToken.value === ")") {
2086
+ if (argDepth === 0) {
2087
+ tokens.advance();
2088
+ break;
2089
+ }
2090
+ argDepth--;
2091
+ }
2092
+ if (argToken.kind === "punctuation" && argToken.value === "(") {
2093
+ argDepth++;
2094
+ }
2095
+ if (argToken.kind === "punctuation" && argToken.value === ",") {
2096
+ tokens.advance();
2097
+ continue;
2098
+ }
2099
+ args.push(argToken.value);
2100
+ tokens.advance();
2101
+ }
2102
+ const methodCall = `${chain}(${args.join(", ")})`;
2103
+ return {
2104
+ type: "expression",
2105
+ raw: methodCall
2106
+ };
2107
+ }
2108
+ return {
2109
+ type: "expression",
2110
+ raw: chain
2111
+ };
2112
+ }
2113
+ /**
2114
+ * Try to match a possessive selector expression like "#element's *opacity".
2115
+ * Pattern: selector + "'s" + (selector | identifier)
2116
+ * Returns a property-path value if matched, or null if not.
2117
+ */
2118
+ tryMatchPossessiveSelectorExpression(tokens) {
2119
+ const token = tokens.peek();
2120
+ if (!token || token.kind !== "selector") return null;
2121
+ const mark = tokens.mark();
2122
+ tokens.advance();
2123
+ const possessiveToken = tokens.peek();
2124
+ if (!possessiveToken || possessiveToken.kind !== "punctuation" || possessiveToken.value !== "'s") {
2125
+ tokens.reset(mark);
2126
+ return null;
2127
+ }
2128
+ tokens.advance();
2129
+ const propertyToken = tokens.peek();
2130
+ if (!propertyToken) {
2131
+ tokens.reset(mark);
2132
+ return null;
2133
+ }
2134
+ if (propertyToken.kind !== "selector" && propertyToken.kind !== "identifier") {
2135
+ tokens.reset(mark);
2136
+ return null;
2137
+ }
2138
+ tokens.advance();
2139
+ return createPropertyPath(createSelector(token.value), propertyToken.value);
2140
+ }
2141
+ /**
2142
+ * Try to match a selector + property expression like "#output.innerText".
2143
+ * This handles cases where the tokenizer produces two selector tokens:
2144
+ * - #output (id selector)
2145
+ * - .innerText (looks like class selector, but is actually property)
2146
+ *
2147
+ * Pattern: id-selector + class-selector-that-is-actually-property
2148
+ * Returns a property-path value if matched, or null if not.
2149
+ */
2150
+ tryMatchSelectorPropertyExpression(tokens) {
2151
+ const token = tokens.peek();
2152
+ if (!token || token.kind !== "selector") return null;
2153
+ if (typeof token.value !== "string" || !token.value.startsWith("#")) return null;
2154
+ const mark = tokens.mark();
2155
+ tokens.advance();
2156
+ const propertyToken = tokens.peek();
2157
+ if (!propertyToken || propertyToken.kind !== "selector") {
2158
+ tokens.reset(mark);
2159
+ return null;
2160
+ }
2161
+ if (!propertyToken.value.startsWith(".")) {
2162
+ tokens.reset(mark);
2163
+ return null;
2164
+ }
2165
+ const peek2 = tokens.peek(1);
2166
+ if (peek2 && peek2.kind === "selector") {
2167
+ }
2168
+ tokens.advance();
2169
+ const propertyName = propertyToken.value.slice(1);
2170
+ return createPropertyPath(createSelector(token.value), propertyName);
2171
+ }
2172
+ /**
2173
+ * Match a group pattern token (optional sequence).
2174
+ * When the group's leading marker isn't at the current position, scans ahead
2175
+ * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens
2176
+ * (e.g., a value like 'hello') to sit between groups without blocking later
2177
+ * marker matches.
2178
+ */
2179
+ matchGroupToken(tokens, patternToken, captured) {
2180
+ const mark = tokens.mark();
2181
+ const capturedBefore = new Set(captured.keys());
2182
+ const success = this.matchTokenSequence(tokens, patternToken.tokens, captured);
2183
+ if (success) return true;
2184
+ tokens.reset(mark);
2185
+ for (const role of captured.keys()) {
2186
+ if (!capturedBefore.has(role)) captured.delete(role);
2187
+ }
2188
+ if (!patternToken.optional) return false;
2189
+ const leadingMarker = this.getGroupLeadingMarker(patternToken);
2190
+ if (leadingMarker) {
2191
+ for (let offset = 1; offset <= _PatternMatcher.MAX_MARKER_SCAN; offset++) {
2192
+ const ahead = tokens.peek(offset);
2193
+ if (!ahead) break;
2194
+ const aheadValue = (ahead.normalized || ahead.value).toLowerCase();
2195
+ if (aheadValue === leadingMarker) {
2196
+ this.logger.debug(
2197
+ " >> MARKER SCAN: found",
2198
+ leadingMarker,
2199
+ "at offset",
2200
+ offset,
2201
+ "- skipping intervening tokens"
2202
+ );
2203
+ for (let s = 0; s < offset; s++) tokens.advance();
2204
+ const retrySuccess = this.matchTokenSequence(tokens, patternToken.tokens, captured);
2205
+ if (retrySuccess) return true;
2206
+ tokens.reset(mark);
2207
+ for (const role of captured.keys()) {
2208
+ if (!capturedBefore.has(role)) captured.delete(role);
2209
+ }
2210
+ break;
2211
+ }
2212
+ }
2213
+ }
2214
+ return true;
2215
+ }
2216
+ /**
2217
+ * Get the leading marker literal from an optional group.
2218
+ * Returns the lowercase marker value, or null if the group
2219
+ * doesn't start with a literal token (e.g., SOV groups where
2220
+ * the role comes before the marker).
2221
+ */
2222
+ getGroupLeadingMarker(group) {
2223
+ const first = group.tokens[0];
2224
+ if (first?.type === "literal") return first.value.toLowerCase();
2225
+ return null;
2226
+ }
2227
+ /**
2228
+ * Get the type of match for a token against a value.
2229
+ * Used for confidence calculation.
2230
+ */
2231
+ getMatchType(token, value) {
2232
+ if (token.value === value) return "exact";
2233
+ if (token.normalized === value) return "normalized";
2234
+ if (token.stem === value && token.stemConfidence !== void 0 && token.stemConfidence >= 0.7) {
2235
+ return "stem";
2236
+ }
2237
+ if (token.kind === "keyword" && this.safeToLowerCase(token.value) === value.toLowerCase()) {
2238
+ return "case-insensitive";
2239
+ }
2240
+ return "none";
2241
+ }
2242
+ /**
2243
+ * Collect literal values from upcoming pattern tokens that act as stop markers
2244
+ * for greedy role capture. Returns the set of lowercase values.
2245
+ */
2246
+ collectStopMarkers(patternTokens, startIndex) {
2247
+ const markers = /* @__PURE__ */ new Set();
2248
+ for (let j = startIndex; j < patternTokens.length; j++) {
2249
+ const pt = patternTokens[j];
2250
+ if (pt.type === "literal") {
2251
+ markers.add(pt.value.toLowerCase());
2252
+ if (pt.alternatives) {
2253
+ for (const alt of pt.alternatives) {
2254
+ markers.add(alt.toLowerCase());
2255
+ }
2256
+ }
2257
+ break;
2258
+ }
2259
+ if (pt.type === "group") {
2260
+ for (const gt of pt.tokens) {
2261
+ if (gt.type === "literal") {
2262
+ markers.add(gt.value.toLowerCase());
2263
+ if (gt.alternatives) {
2264
+ for (const alt of gt.alternatives) {
2265
+ markers.add(alt.toLowerCase());
2266
+ }
2267
+ }
2268
+ break;
2269
+ }
2270
+ }
2271
+ break;
2272
+ }
2273
+ }
2274
+ return markers;
2275
+ }
2276
+ /**
2277
+ * Check if a token matches any stop marker for greedy capture.
2278
+ */
2279
+ isStopMarker(token, stopMarkers) {
2280
+ if (stopMarkers.size === 0) return false;
2281
+ const value = (token.normalized || token.value).toLowerCase();
2282
+ return stopMarkers.has(value);
2283
+ }
2284
+ /**
2285
+ * Convert a language token to a semantic value.
2286
+ */
2287
+ tokenToSemanticValue(token) {
2288
+ switch (token.kind) {
2289
+ case "selector":
2290
+ return createSelector(token.value);
2291
+ case "literal":
2292
+ return this.parseLiteralValue(token.value);
2293
+ case "keyword":
2294
+ const tokenValue = token.normalized || token.value;
2295
+ const lower = this.safeToLowerCase(tokenValue);
2296
+ if (isValidReference(lower)) {
2297
+ return createReference(lower);
2298
+ }
2299
+ return createLiteral(token.normalized || token.value);
2300
+ case "identifier":
2301
+ if (typeof token.value === "string" && token.value.startsWith(":")) {
2302
+ return createReference(token.value);
2303
+ }
2304
+ const identLower = this.safeToLowerCase(token.value);
2305
+ if (isValidReference(identLower)) {
2306
+ return createReference(identLower);
2307
+ }
2308
+ return { type: "expression", raw: token.value };
2309
+ case "url":
2310
+ return createLiteral(token.value, "string");
2311
+ default:
2312
+ return null;
2313
+ }
2314
+ }
2315
+ /**
2316
+ * Parse a literal value (string, number, boolean).
2317
+ */
2318
+ parseLiteralValue(value) {
2319
+ if (value.startsWith('"') || value.startsWith("'") || value.startsWith("`") || value.startsWith("\u300C")) {
2320
+ const inner = value.slice(1, -1);
2321
+ return createLiteral(inner, "string");
2322
+ }
2323
+ if (value === "true") return createLiteral(true, "boolean");
2324
+ if (value === "false") return createLiteral(false, "boolean");
2325
+ const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
2326
+ if (durationMatch) {
2327
+ const num2 = parseFloat(durationMatch[1]);
2328
+ const unit = durationMatch[2];
2329
+ if (unit) {
2330
+ return createLiteral(value, "duration");
2331
+ }
2332
+ return createLiteral(num2, "number");
2333
+ }
2334
+ const num = parseFloat(value);
2335
+ if (!isNaN(num)) {
2336
+ return createLiteral(num, "number");
2337
+ }
2338
+ return createLiteral(value, "string");
2339
+ }
2340
+ /**
2341
+ * Apply extraction rules to fill in static values and defaults for missing roles.
2342
+ */
2343
+ applyExtractionRules(pattern, captured) {
2344
+ for (const [role, rule] of Object.entries(pattern.extraction)) {
2345
+ if (!captured.has(role)) {
2346
+ if (rule.value !== void 0) {
2347
+ captured.set(role, { type: "literal", value: rule.value });
2348
+ } else if (rule.default) {
2349
+ captured.set(role, rule.default);
2350
+ }
2351
+ }
2352
+ }
2353
+ }
2354
+ /**
2355
+ * Check if a pattern token is optional.
2356
+ */
2357
+ isOptional(patternToken) {
2358
+ return patternToken.type !== "literal" && patternToken.optional === true;
2359
+ }
2360
+ /**
2361
+ * Calculate confidence score for a match (0-1).
2362
+ *
2363
+ * Confidence is reduced for:
2364
+ * - Stem matches (morphological normalization has inherent uncertainty)
2365
+ * - Missing optional roles (but less penalty if role has a default value)
2366
+ *
2367
+ * Confidence is increased for:
2368
+ * - VSO languages (Arabic) when pattern starts with a verb
2369
+ */
2370
+ calculateConfidence(pattern, captured) {
2371
+ let score = 0;
2372
+ let maxScore = 0;
2373
+ const hasDefault = (role) => {
2374
+ return pattern.extraction?.[role]?.default !== void 0;
2375
+ };
2376
+ for (const token of pattern.template.tokens) {
2377
+ if (token.type === "role") {
2378
+ maxScore += 1;
2379
+ if (captured.has(token.role)) {
2380
+ score += 1;
2381
+ }
2382
+ } else if (token.type === "group") {
2383
+ for (const subToken of token.tokens) {
2384
+ if (subToken.type === "role") {
2385
+ const roleHasDefault = hasDefault(subToken.role);
2386
+ const weight = 0.8;
2387
+ maxScore += weight;
2388
+ if (captured.has(subToken.role)) {
2389
+ score += weight;
2390
+ } else if (roleHasDefault) {
2391
+ score += weight * 0.6;
2392
+ }
2393
+ }
2394
+ }
2395
+ }
2396
+ }
2397
+ let baseConfidence = maxScore > 0 ? score / maxScore : 1;
2398
+ if (this.stemMatchCount > 0 && this.totalKeywordMatches > 0) {
2399
+ const stemPenalty = this.stemMatchCount / this.totalKeywordMatches * 0.15;
2400
+ baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);
2401
+ }
2402
+ const vsoBoost = this.calculateVSOConfidenceBoost(pattern);
2403
+ baseConfidence = Math.min(1, baseConfidence + vsoBoost);
2404
+ const prepositionAdjustment = this.arabicPrepositionDisambiguation(pattern, captured);
2405
+ baseConfidence = Math.max(0, Math.min(1, baseConfidence + prepositionAdjustment));
2406
+ return baseConfidence;
2407
+ }
2408
+ /**
2409
+ * Calculate confidence boost for VSO (Verb-Subject-Object) language patterns.
2410
+ * Arabic naturally uses VSO word order, so patterns that start with a verb
2411
+ * should receive a confidence boost.
2412
+ *
2413
+ * Returns +0.15 confidence boost if:
2414
+ * - Language is Arabic ('ar')
2415
+ * - Pattern's first token is a verb keyword
2416
+ *
2417
+ * @param pattern The language pattern being matched
2418
+ * @returns Confidence boost (0 or 0.15)
2419
+ */
2420
+ calculateVSOConfidenceBoost(pattern) {
2421
+ if (pattern.language !== "ar") {
2422
+ return 0;
2423
+ }
2424
+ const firstToken = pattern.template.tokens[0];
2425
+ if (!firstToken || firstToken.type !== "literal") {
2426
+ return 0;
2427
+ }
2428
+ const ARABIC_VERBS = /* @__PURE__ */ new Set([
2429
+ "\u0628\u062F\u0644",
2430
+ "\u063A\u064A\u0631",
2431
+ "\u0623\u0636\u0641",
2432
+ "\u0623\u0632\u0644",
2433
+ "\u0636\u0639",
2434
+ "\u0627\u062C\u0639\u0644",
2435
+ "\u0639\u064A\u0646",
2436
+ "\u0632\u062F",
2437
+ "\u0627\u0646\u0642\u0635",
2438
+ "\u0633\u062C\u0644",
2439
+ "\u0623\u0638\u0647\u0631",
2440
+ "\u0623\u062E\u0641",
2441
+ "\u0634\u063A\u0644",
2442
+ "\u0623\u0631\u0633\u0644",
2443
+ "\u0631\u0643\u0632",
2444
+ "\u0634\u0648\u0634",
2445
+ "\u062A\u0648\u0642\u0641",
2446
+ "\u0627\u0646\u0633\u062E",
2447
+ "\u0627\u062D\u0630\u0641",
2448
+ "\u0627\u0635\u0646\u0639",
2449
+ "\u0627\u0646\u062A\u0638\u0631",
2450
+ "\u0627\u0646\u062A\u0642\u0627\u0644",
2451
+ "\u0623\u0648"
2452
+ ]);
2453
+ if (ARABIC_VERBS.has(firstToken.value)) {
2454
+ return 0.15;
2455
+ }
2456
+ if (firstToken.alternatives) {
2457
+ for (const alt of firstToken.alternatives) {
2458
+ if (ARABIC_VERBS.has(alt)) {
2459
+ return 0.15;
2460
+ }
2461
+ }
2462
+ }
2463
+ return 0;
2464
+ }
2465
+ /**
2466
+ * Arabic preposition disambiguation for confidence adjustment.
2467
+ *
2468
+ * Different Arabic prepositions are more or less natural for different semantic roles:
2469
+ * - على (on/upon) is preferred for patient/target roles (element selectors)
2470
+ * - إلى (to) is preferred for destination roles
2471
+ * - من (from) is preferred for source roles
2472
+ * - في (in) is preferred for location roles
2473
+ *
2474
+ * This method analyzes the prepositions used with captured semantic roles and
2475
+ * adjusts confidence based on idiomaticity:
2476
+ * - +0.10 for highly idiomatic preposition choices
2477
+ * - -0.10 for less natural preposition choices
2478
+ *
2479
+ * @param pattern The language pattern being matched
2480
+ * @param captured The captured semantic values
2481
+ * @returns Confidence adjustment (-0.10 to +0.10)
2482
+ */
2483
+ arabicPrepositionDisambiguation(pattern, captured) {
2484
+ if (pattern.language !== "ar") {
2485
+ return 0;
2486
+ }
2487
+ let adjustment = 0;
2488
+ const PREFERRED_PREPOSITIONS = {
2489
+ patient: ["\u0639\u0644\u0649"],
2490
+ // element selectors prefer على (on/upon)
2491
+ destination: ["\u0625\u0644\u0649", "\u0627\u0644\u0649"],
2492
+ // destination prefers إلى (to)
2493
+ source: ["\u0645\u0646"],
2494
+ // source prefers من (from)
2495
+ agent: ["\u0645\u0646"],
2496
+ // agent/by prefers من (from/by)
2497
+ manner: ["\u0628"],
2498
+ // manner prefers ب (with/by)
2499
+ style: ["\u0628"],
2500
+ // style prefers ب (with)
2501
+ goal: ["\u0625\u0644\u0649", "\u0627\u0644\u0649"],
2502
+ // target state prefers إلى (to)
2503
+ method: ["\u0628"]
2504
+ // method prefers ب (with/by)
2505
+ };
2506
+ for (const [role, value] of captured.entries()) {
2507
+ const preferred = PREFERRED_PREPOSITIONS[role];
2508
+ if (!preferred || preferred.length === 0) {
2509
+ continue;
2510
+ }
2511
+ const metadata = "metadata" in value ? value.metadata : void 0;
2512
+ if (metadata && typeof metadata.prepositionValue === "string") {
2513
+ const usedPreposition = metadata.prepositionValue;
2514
+ if (preferred.includes(usedPreposition)) {
2515
+ adjustment += 0.1;
2516
+ } else {
2517
+ adjustment -= 0.1;
2518
+ }
2519
+ }
2520
+ }
2521
+ return Math.max(-0.1, Math.min(0.1, adjustment));
2522
+ }
2523
+ /**
2524
+ * Skip noise words like "the" before selectors.
2525
+ * This enables more natural English syntax like "toggle the .active".
2526
+ */
2527
+ skipNoiseWords(tokens) {
2528
+ const token = tokens.peek();
2529
+ if (!token) return;
2530
+ const tokenLower = this.safeToLowerCase(token.value);
2531
+ if (_PatternMatcher.ENGLISH_NOISE_WORDS.has(tokenLower)) {
2532
+ const mark = tokens.mark();
2533
+ tokens.advance();
2534
+ const nextToken = tokens.peek();
2535
+ if (nextToken && nextToken.kind === "selector") {
2536
+ return;
2537
+ }
2538
+ tokens.reset(mark);
2539
+ }
2540
+ if (tokenLower === "class") {
2541
+ tokens.advance();
2542
+ }
2543
+ }
2544
+ /**
2545
+ * Extract event modifiers from the token stream.
2546
+ * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)
2547
+ * that can appear after event names.
2548
+ *
2549
+ * Returns EventModifiers object or undefined if no modifiers found.
2550
+ */
2551
+ extractEventModifiers(tokens) {
2552
+ const modifiers = {};
2553
+ let foundModifier = false;
2554
+ while (!tokens.isAtEnd()) {
2555
+ const token = tokens.peek();
2556
+ if (!token || token.kind !== "event-modifier") {
2557
+ break;
2558
+ }
2559
+ const metadata = token.metadata;
2560
+ if (!metadata) {
2561
+ break;
2562
+ }
2563
+ foundModifier = true;
2564
+ switch (metadata.modifierName) {
2565
+ case "once":
2566
+ modifiers.once = true;
2567
+ break;
2568
+ case "debounce":
2569
+ if (typeof metadata.value === "number") {
2570
+ modifiers.debounce = metadata.value;
2571
+ }
2572
+ break;
2573
+ case "throttle":
2574
+ if (typeof metadata.value === "number") {
2575
+ modifiers.throttle = metadata.value;
2576
+ }
2577
+ break;
2578
+ case "queue":
2579
+ if (metadata.value === "first" || metadata.value === "last" || metadata.value === "all" || metadata.value === "none") {
2580
+ modifiers.queue = metadata.value;
2581
+ }
2582
+ break;
2583
+ }
2584
+ tokens.advance();
2585
+ }
2586
+ return foundModifier ? modifiers : void 0;
2587
+ }
2588
+ };
2589
+ /** Maximum tokens to scan ahead when looking for a group's leading marker */
2590
+ _PatternMatcher.MAX_MARKER_SCAN = 3;
2591
+ // ==========================================================================
2592
+ // Depth Limits for Expression Parsing (security hardening)
2593
+ // ==========================================================================
2594
+ /** Maximum depth for nested property access (e.g., a.b.c.d...) */
2595
+ _PatternMatcher.MAX_PROPERTY_DEPTH = 10;
2596
+ /** Maximum number of arguments in method calls */
2597
+ _PatternMatcher.MAX_METHOD_ARGS = 20;
2598
+ // ===========================================================================
2599
+ // English Idiom Support - Noise Word Handling
2600
+ // ===========================================================================
2601
+ /**
2602
+ * Noise words that can be skipped in English for more natural syntax.
2603
+ * - "the" before selectors: "toggle the .active" → "toggle .active"
2604
+ * - "class" after class selectors: "add the .visible class" → "add .visible"
2605
+ */
2606
+ _PatternMatcher.ENGLISH_NOISE_WORDS = /* @__PURE__ */ new Set(["the", "a", "an"]);
2607
+ var PatternMatcher = _PatternMatcher;
2608
+ var patternMatcher = new PatternMatcher();
2609
+ function matchPattern(tokens, pattern) {
2610
+ return patternMatcher.matchPattern(tokens, pattern);
2611
+ }
2612
+ function matchBest(tokens, patterns) {
2613
+ return patternMatcher.matchBest(tokens, patterns);
2614
+ }
2615
+ export {
2616
+ BaseTokenizer,
2617
+ DEFAULT_OPERATORS,
2618
+ DEFAULT_PUNCTUATION,
2619
+ OperatorExtractor,
2620
+ PatternMatcher,
2621
+ PunctuationExtractor,
2622
+ TokenStreamImpl,
2623
+ combineClassifiers,
2624
+ createCommandNode,
2625
+ createCompoundNode,
2626
+ createConditionalNode,
2627
+ createEventHandlerNode,
2628
+ createExpression,
2629
+ createLatinCharClassifiers,
2630
+ createLiteral,
2631
+ createLoopNode,
2632
+ createPosition,
2633
+ createPropertyPath,
2634
+ createReference,
2635
+ createSelector,
2636
+ createSimpleTokenizer,
2637
+ createToken,
2638
+ createUnicodeRangeClassifier,
2639
+ extractCssSelector,
2640
+ extractNumber,
2641
+ extractRoleValue,
2642
+ extractStringLiteral,
2643
+ extractUrl,
2644
+ extractValue,
2645
+ getAllPossessiveKeywords,
2646
+ getDefaultExtractors,
2647
+ getPossessiveReference,
2648
+ isAsciiIdentifierChar,
2649
+ isAsciiLetter,
2650
+ isBuiltInReference,
2651
+ isCSSPropertyRef,
2652
+ isCSSSelector,
2653
+ isClassName,
2654
+ isDigit,
2655
+ isIdSelector,
2656
+ isNumericValue,
2657
+ isPossessiveKeyword,
2658
+ isPossessiveMarker,
2659
+ isPropertyName,
2660
+ isQuote,
2661
+ isSelectorStart,
2662
+ isTypeCompatible,
2663
+ isUrlStart,
2664
+ isVariableRef,
2665
+ isWhitespace,
2666
+ matchBest,
2667
+ matchPattern,
2668
+ noChange,
2669
+ normalized,
2670
+ patternMatcher,
2671
+ validateValueType,
2672
+ withDefaultExtractors
2673
+ };
2674
+ //# sourceMappingURL=index.js.map