@lokascript/framework 4.8.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/dist/api/create-dsl.d.ts +9 -10
  3. package/dist/api/create-dsl.d.ts.map +1 -1
  4. package/dist/api/index.js +835 -1670
  5. package/dist/api/index.js.map +1 -1
  6. package/dist/core/index.d.ts +0 -1
  7. package/dist/core/index.d.ts.map +1 -1
  8. package/dist/core/index.js +549 -1132
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/matching/index.d.ts +2 -0
  11. package/dist/core/matching/index.d.ts.map +1 -1
  12. package/dist/core/matching/possessive-keywords.d.ts.map +1 -0
  13. package/dist/core/matching/stock-confidence.d.ts +3 -4
  14. package/dist/core/matching/stock-confidence.d.ts.map +1 -1
  15. package/dist/core/matching/stock-reading.d.ts +4 -4
  16. package/dist/core/{pattern-matching/utils → matching}/type-validation.d.ts +1 -1
  17. package/dist/core/matching/type-validation.d.ts.map +1 -0
  18. package/dist/generation/index.d.ts +1 -1
  19. package/dist/generation/index.d.ts.map +1 -1
  20. package/dist/generation/index.js +20 -169
  21. package/dist/generation/index.js.map +1 -1
  22. package/dist/generation/profile.d.ts +30 -0
  23. package/dist/generation/profile.d.ts.map +1 -0
  24. package/dist/generation/renderer.d.ts +1 -1
  25. package/dist/generation/renderer.d.ts.map +1 -1
  26. package/dist/generation/schema-patterns.d.ts +3 -3
  27. package/dist/index.cjs +929 -1674
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.js +929 -1668
  30. package/dist/index.js.map +1 -1
  31. package/dist/multilingual/builders.d.ts +3 -3
  32. package/dist/multilingual/builders.d.ts.map +1 -1
  33. package/dist/multilingual/index.js.map +1 -1
  34. package/dist/parsing/index.d.ts +0 -1
  35. package/dist/parsing/index.d.ts.map +1 -1
  36. package/dist/parsing/index.js +0 -1145
  37. package/dist/parsing/index.js.map +1 -1
  38. package/dist/testing/gate/lint/types.d.ts +1 -1
  39. package/dist/testing/gate/lint/types.d.ts.map +1 -1
  40. package/package.json +3 -8
  41. package/src/__test__/test-utils.ts +1 -1
  42. package/src/api/create-dsl-engine.test.ts +60 -35
  43. package/src/api/create-dsl.ts +24 -35
  44. package/src/core/index.ts +0 -1
  45. package/src/core/matching/index.ts +2 -0
  46. package/src/core/matching/stock-confidence.ts +3 -4
  47. package/src/core/matching/stock-reading.ts +6 -6
  48. package/src/core/{pattern-matching/utils → matching}/type-validation.test.ts +2 -2
  49. package/src/core/{pattern-matching/utils → matching}/type-validation.ts +1 -1
  50. package/src/generation/domain-renderer.test.ts +1 -1
  51. package/src/generation/index.ts +1 -1
  52. package/src/generation/profile.ts +41 -0
  53. package/src/generation/renderer.test.ts +1 -1
  54. package/src/generation/renderer.ts +1 -1
  55. package/src/generation/schema-patterns.ts +3 -3
  56. package/src/multilingual/bridge.test.ts +31 -23
  57. package/src/multilingual/builders.ts +3 -3
  58. package/src/parsing/index.ts +0 -1
  59. package/src/testing/gate/lint/types.ts +1 -1
  60. package/dist/core/pattern-matching/index.d.ts +0 -6
  61. package/dist/core/pattern-matching/index.d.ts.map +0 -1
  62. package/dist/core/pattern-matching/index.js +0 -1211
  63. package/dist/core/pattern-matching/index.js.map +0 -1
  64. package/dist/core/pattern-matching/pattern-matcher.d.ts +0 -122
  65. package/dist/core/pattern-matching/pattern-matcher.d.ts.map +0 -1
  66. package/dist/core/pattern-matching/utils/index.d.ts +0 -6
  67. package/dist/core/pattern-matching/utils/index.d.ts.map +0 -1
  68. package/dist/core/pattern-matching/utils/possessive-keywords.d.ts.map +0 -1
  69. package/dist/core/pattern-matching/utils/type-validation.d.ts.map +0 -1
  70. package/dist/generation/pattern-generator.d.ts +0 -55
  71. package/dist/generation/pattern-generator.d.ts.map +0 -1
  72. package/src/core/pattern-matching/index.ts +0 -6
  73. package/src/core/pattern-matching/pattern-matcher.test.ts +0 -1031
  74. package/src/core/pattern-matching/pattern-matcher.ts +0 -765
  75. package/src/core/pattern-matching/utils/index.ts +0 -6
  76. package/src/generation/pattern-generator.test.ts +0 -532
  77. package/src/generation/pattern-generator.ts +0 -327
  78. /package/dist/core/{pattern-matching/utils → matching}/possessive-keywords.d.ts +0 -0
  79. /package/src/core/{pattern-matching/utils → matching}/possessive-keywords.ts +0 -0
@@ -1,1147 +1,3 @@
1
- // src/core/logger.ts
2
- var DebugLogger = class {
3
- constructor(namespace) {
4
- this.namespace = namespace;
5
- this.enabled = this.checkEnabled();
6
- }
7
- checkEnabled() {
8
- if (typeof process !== "undefined" && process.env) {
9
- const DEBUG = process.env.DEBUG || "";
10
- return DEBUG === "*" || DEBUG.includes("framework:*") || DEBUG.includes(`framework:${this.namespace}`);
11
- }
12
- return false;
13
- }
14
- log(level, message, ...args) {
15
- if (!this.enabled) return;
16
- const prefix = `[framework:${this.namespace}]`;
17
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18
- switch (level) {
19
- case "debug":
20
- console.debug(`${timestamp} ${prefix} DEBUG:`, message, ...args);
21
- break;
22
- case "info":
23
- console.info(`${timestamp} ${prefix} INFO:`, message, ...args);
24
- break;
25
- case "warn":
26
- console.warn(`${timestamp} ${prefix} WARN:`, message, ...args);
27
- break;
28
- case "error":
29
- console.error(`${timestamp} ${prefix} ERROR:`, message, ...args);
30
- break;
31
- }
32
- }
33
- debug(message, ...args) {
34
- this.log("debug", message, ...args);
35
- }
36
- info(message, ...args) {
37
- this.log("info", message, ...args);
38
- }
39
- warn(message, ...args) {
40
- this.log("warn", message, ...args);
41
- }
42
- error(message, ...args) {
43
- this.log("error", message, ...args);
44
- }
45
- /**
46
- * Check if logging is enabled for this namespace.
47
- */
48
- isEnabled() {
49
- return this.enabled;
50
- }
51
- /**
52
- * Programmatically enable logging for this namespace.
53
- */
54
- enable() {
55
- this.enabled = true;
56
- }
57
- /**
58
- * Programmatically disable logging for this namespace.
59
- */
60
- disable() {
61
- this.enabled = false;
62
- }
63
- };
64
- function createLogger(namespace) {
65
- return new DebugLogger(namespace);
66
- }
67
-
68
- // src/core/types.ts
69
- import {
70
- createLiteral,
71
- createSelector,
72
- createReference,
73
- createPropertyPath,
74
- createExpression,
75
- createFlag,
76
- createCommandNode,
77
- createEventHandlerNode,
78
- createConditionalNode,
79
- createCompoundNode,
80
- createLoopNode,
81
- createTryNode,
82
- createAsyncNode,
83
- createMatchNode,
84
- extractValue,
85
- extractRoleValue,
86
- getRoleValue
87
- } from "@lokascript/intent";
88
-
89
- // src/core/pattern-matching/utils/type-validation.ts
90
- function isTypeCompatible(actualType, expectedTypes) {
91
- if (!expectedTypes || expectedTypes.length === 0) {
92
- return true;
93
- }
94
- if (expectedTypes.includes(actualType)) {
95
- return true;
96
- }
97
- if (expectedTypes.includes("expression")) {
98
- return true;
99
- }
100
- if (actualType === "property-path") {
101
- return expectedTypes.some((t) => ["selector", "reference", "expression"].includes(t));
102
- }
103
- return false;
104
- }
105
-
106
- // src/core/pattern-matching/utils/possessive-keywords.ts
107
- function getPossessiveReference(profile, keyword) {
108
- return profile?.possessive?.keywords?.[keyword];
109
- }
110
-
111
- // src/core/matching/stock-reading.ts
112
- function isValidReference(_value) {
113
- return false;
114
- }
115
- function safeToLowerCase(value) {
116
- if (typeof value === "string") {
117
- return value.toLowerCase();
118
- }
119
- if (value === null || value === void 0) {
120
- return "";
121
- }
122
- return String(value).toLowerCase();
123
- }
124
- function readRoleValue(tokens, patternToken, captured, profile) {
125
- skipNoiseWords(tokens);
126
- const token = tokens.peek();
127
- if (!token) {
128
- return patternToken.optional || false;
129
- }
130
- const possessiveValue = tryMatchPossessiveExpression(tokens, profile);
131
- if (possessiveValue) {
132
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
133
- if (!isTypeCompatible(possessiveValue.type, patternToken.expectedTypes)) {
134
- return patternToken.optional || false;
135
- }
136
- }
137
- captured.set(patternToken.role, possessiveValue);
138
- return true;
139
- }
140
- const methodCallValue = tryMatchMethodCallExpression(tokens);
141
- if (methodCallValue) {
142
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
143
- if (!isTypeCompatible(methodCallValue.type, patternToken.expectedTypes)) {
144
- return patternToken.optional || false;
145
- }
146
- }
147
- captured.set(patternToken.role, methodCallValue);
148
- return true;
149
- }
150
- const possessiveSelectorValue = tryMatchPossessiveSelectorExpression(tokens);
151
- if (possessiveSelectorValue) {
152
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
153
- if (!isTypeCompatible(possessiveSelectorValue.type, patternToken.expectedTypes)) {
154
- return patternToken.optional || false;
155
- }
156
- }
157
- captured.set(patternToken.role, possessiveSelectorValue);
158
- return true;
159
- }
160
- const propertyAccessValue = tryMatchPropertyAccessExpression(tokens);
161
- if (propertyAccessValue) {
162
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
163
- if (!isTypeCompatible(propertyAccessValue.type, patternToken.expectedTypes)) {
164
- return patternToken.optional || false;
165
- }
166
- }
167
- captured.set(patternToken.role, propertyAccessValue);
168
- return true;
169
- }
170
- const selectorPropertyValue = tryMatchSelectorPropertyExpression(tokens);
171
- if (selectorPropertyValue) {
172
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
173
- if (!isTypeCompatible(selectorPropertyValue.type, patternToken.expectedTypes)) {
174
- return patternToken.optional || false;
175
- }
176
- }
177
- captured.set(patternToken.role, selectorPropertyValue);
178
- return true;
179
- }
180
- const value = tokenToSemanticValue(token);
181
- if (!value) {
182
- return patternToken.optional || false;
183
- }
184
- if (patternToken.expectedTypes && patternToken.expectedTypes.length > 0) {
185
- if (!isTypeCompatible(value.type, patternToken.expectedTypes)) {
186
- return patternToken.optional || false;
187
- }
188
- }
189
- captured.set(patternToken.role, value);
190
- tokens.advance();
191
- return true;
192
- }
193
- function tryMatchPossessiveExpression(tokens, profile) {
194
- const token = tokens.peek();
195
- if (!token) return null;
196
- if (!profile) return null;
197
- const tokenValue = token.normalized || token.value;
198
- const tokenLower = safeToLowerCase(tokenValue);
199
- const baseRef = getPossessiveReference(profile, tokenLower);
200
- if (!baseRef) return null;
201
- const mark = tokens.mark();
202
- tokens.advance();
203
- const propertyToken = tokens.peek();
204
- if (!propertyToken) {
205
- tokens.reset(mark);
206
- return null;
207
- }
208
- if (propertyToken.kind === "identifier" || propertyToken.kind === "keyword" && !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)) {
209
- tokens.advance();
210
- let propertyName = propertyToken.value;
211
- if (propertyToken.kind === "selector" && propertyName.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(propertyName)) {
212
- propertyName = propertyName.substring(1);
213
- }
214
- let chainedProps = propertyName;
215
- while (tokens.peek()?.kind === "selector" && tokens.peek().value.startsWith(".") && /^\.[a-zA-Z_]\w*/.test(tokens.peek().value)) {
216
- chainedProps += tokens.peek().value;
217
- tokens.advance();
218
- }
219
- const nextPeek = tokens.peek();
220
- if (nextPeek?.kind === "literal" && nextPeek.value.startsWith("(")) {
221
- chainedProps += nextPeek.value;
222
- tokens.advance();
223
- }
224
- return createPropertyPath(createReference(baseRef), chainedProps);
225
- }
226
- tokens.reset(mark);
227
- return null;
228
- }
229
- function isStructuralKeyword(value) {
230
- const structural = /* @__PURE__ */ new Set([
231
- // Prepositions
232
- "into",
233
- "in",
234
- "to",
235
- "from",
236
- "at",
237
- "by",
238
- "with",
239
- "without",
240
- "before",
241
- "after",
242
- "of",
243
- "as",
244
- "on",
245
- // Control flow
246
- "then",
247
- "end",
248
- "else",
249
- "if",
250
- "repeat",
251
- "while",
252
- "for",
253
- // Commands (shouldn't be property names)
254
- "toggle",
255
- "add",
256
- "remove",
257
- "put",
258
- "set",
259
- "show",
260
- "hide",
261
- "increment",
262
- "decrement",
263
- "send",
264
- "trigger",
265
- "call"
266
- ]);
267
- return structural.has(value.toLowerCase());
268
- }
269
- function tryMatchMethodCallExpression(tokens) {
270
- const token = tokens.peek();
271
- if (!token || token.kind !== "selector") return null;
272
- const mark = tokens.mark();
273
- tokens.advance();
274
- const dotToken = tokens.peek();
275
- if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
276
- tokens.reset(mark);
277
- return null;
278
- }
279
- tokens.advance();
280
- const methodToken = tokens.peek();
281
- if (!methodToken || methodToken.kind !== "identifier") {
282
- tokens.reset(mark);
283
- return null;
284
- }
285
- tokens.advance();
286
- const openParen = tokens.peek();
287
- if (!openParen || openParen.kind !== "punctuation" || openParen.value !== "(") {
288
- tokens.reset(mark);
289
- return null;
290
- }
291
- tokens.advance();
292
- const args = [];
293
- while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {
294
- const argToken = tokens.peek();
295
- if (!argToken) break;
296
- if (argToken.kind === "punctuation" && argToken.value === ")") {
297
- tokens.advance();
298
- break;
299
- }
300
- if (argToken.kind === "punctuation" && argToken.value === ",") {
301
- tokens.advance();
302
- continue;
303
- }
304
- args.push(argToken.value);
305
- tokens.advance();
306
- }
307
- const methodCall = `${token.value}.${methodToken.value}(${args.join(", ")})`;
308
- return {
309
- type: "expression",
310
- raw: methodCall
311
- };
312
- }
313
- function tryMatchPropertyAccessExpression(tokens) {
314
- const token = tokens.peek();
315
- if (!token) return null;
316
- if (token.kind !== "identifier" && token.kind !== "keyword") return null;
317
- const mark = tokens.mark();
318
- tokens.advance();
319
- const dotToken = tokens.peek();
320
- if (!dotToken || dotToken.kind !== "operator" || dotToken.value !== ".") {
321
- tokens.reset(mark);
322
- return null;
323
- }
324
- tokens.advance();
325
- const propertyToken = tokens.peek();
326
- if (!propertyToken || propertyToken.kind !== "identifier") {
327
- tokens.reset(mark);
328
- return null;
329
- }
330
- tokens.advance();
331
- let chain = `${token.value}.${propertyToken.value}`;
332
- let depth = 1;
333
- while (!tokens.isAtEnd() && depth < MAX_PROPERTY_DEPTH) {
334
- const nextDot = tokens.peek();
335
- if (!nextDot || nextDot.kind !== "operator" || nextDot.value !== ".") {
336
- break;
337
- }
338
- tokens.advance();
339
- const nextProp = tokens.peek();
340
- if (!nextProp || nextProp.kind !== "identifier") {
341
- break;
342
- }
343
- tokens.advance();
344
- chain += `.${nextProp.value}`;
345
- depth++;
346
- }
347
- const openParen = tokens.peek();
348
- if (openParen && openParen.kind === "punctuation" && openParen.value === "(") {
349
- tokens.advance();
350
- const args = [];
351
- let argDepth = 0;
352
- while (!tokens.isAtEnd() && args.length < MAX_METHOD_ARGS) {
353
- const argToken = tokens.peek();
354
- if (!argToken) break;
355
- if (argToken.kind === "punctuation" && argToken.value === ")") {
356
- if (argDepth === 0) {
357
- tokens.advance();
358
- break;
359
- }
360
- argDepth--;
361
- }
362
- if (argToken.kind === "punctuation" && argToken.value === "(") {
363
- argDepth++;
364
- }
365
- if (argToken.kind === "punctuation" && argToken.value === ",") {
366
- tokens.advance();
367
- continue;
368
- }
369
- args.push(argToken.value);
370
- tokens.advance();
371
- }
372
- const methodCall = `${chain}(${args.join(", ")})`;
373
- return {
374
- type: "expression",
375
- raw: methodCall
376
- };
377
- }
378
- return {
379
- type: "expression",
380
- raw: chain
381
- };
382
- }
383
- function tryMatchPossessiveSelectorExpression(tokens) {
384
- const token = tokens.peek();
385
- if (!token || token.kind !== "selector") return null;
386
- const mark = tokens.mark();
387
- tokens.advance();
388
- const possessiveToken = tokens.peek();
389
- if (!possessiveToken || possessiveToken.kind !== "punctuation" || possessiveToken.value !== "'s") {
390
- tokens.reset(mark);
391
- return null;
392
- }
393
- tokens.advance();
394
- const propertyToken = tokens.peek();
395
- if (!propertyToken) {
396
- tokens.reset(mark);
397
- return null;
398
- }
399
- if (propertyToken.kind !== "selector" && propertyToken.kind !== "identifier") {
400
- tokens.reset(mark);
401
- return null;
402
- }
403
- tokens.advance();
404
- return createPropertyPath(createSelector(token.value), propertyToken.value);
405
- }
406
- function tryMatchSelectorPropertyExpression(tokens) {
407
- const token = tokens.peek();
408
- if (!token || token.kind !== "selector") return null;
409
- if (typeof token.value !== "string" || !token.value.startsWith("#")) return null;
410
- const mark = tokens.mark();
411
- tokens.advance();
412
- const propertyToken = tokens.peek();
413
- if (!propertyToken || propertyToken.kind !== "selector") {
414
- tokens.reset(mark);
415
- return null;
416
- }
417
- if (!propertyToken.value.startsWith(".")) {
418
- tokens.reset(mark);
419
- return null;
420
- }
421
- const peek2 = tokens.peek(1);
422
- if (peek2 && peek2.kind === "selector") {
423
- }
424
- tokens.advance();
425
- const propertyName = propertyToken.value.slice(1);
426
- return createPropertyPath(createSelector(token.value), propertyName);
427
- }
428
- var MAX_PROPERTY_DEPTH = 10;
429
- var MAX_METHOD_ARGS = 20;
430
- function tokenToSemanticValue(token) {
431
- switch (token.kind) {
432
- case "selector":
433
- return createSelector(token.value);
434
- case "literal":
435
- return parseLiteralValue(token.value);
436
- case "keyword": {
437
- const tokenValue = token.normalized || token.value;
438
- const lower = safeToLowerCase(tokenValue);
439
- if (isValidReference(lower)) {
440
- return createReference(lower);
441
- }
442
- return createLiteral(token.normalized || token.value);
443
- }
444
- case "identifier": {
445
- if (typeof token.value === "string" && token.value.startsWith(":")) {
446
- return createReference(token.value);
447
- }
448
- const identLower = safeToLowerCase(token.value);
449
- if (isValidReference(identLower)) {
450
- return createReference(identLower);
451
- }
452
- return { type: "expression", raw: token.value };
453
- }
454
- case "url":
455
- return createLiteral(token.value, "string");
456
- default:
457
- return null;
458
- }
459
- }
460
- function parseLiteralValue(value) {
461
- if (value.startsWith('"') || value.startsWith("'") || value.startsWith("`") || value.startsWith("\u300C")) {
462
- const inner = value.slice(1, -1);
463
- return createLiteral(inner, "string");
464
- }
465
- if (value === "true") return createLiteral(true, "boolean");
466
- if (value === "false") return createLiteral(false, "boolean");
467
- const durationMatch = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
468
- if (durationMatch) {
469
- const num2 = parseFloat(durationMatch[1]);
470
- const unit = durationMatch[2];
471
- if (unit) {
472
- return createLiteral(value, "duration");
473
- }
474
- return createLiteral(num2, "number");
475
- }
476
- const num = parseFloat(value);
477
- if (!isNaN(num)) {
478
- return createLiteral(num, "number");
479
- }
480
- return createLiteral(value, "string");
481
- }
482
- var ENGLISH_NOISE_WORDS = /* @__PURE__ */ new Set(["the", "a", "an"]);
483
- function skipNoiseWords(tokens) {
484
- const token = tokens.peek();
485
- if (!token) return;
486
- const tokenLower = safeToLowerCase(token.value);
487
- if (ENGLISH_NOISE_WORDS.has(tokenLower)) {
488
- const mark = tokens.mark();
489
- tokens.advance();
490
- const nextToken = tokens.peek();
491
- if (nextToken && nextToken.kind === "selector") {
492
- return;
493
- }
494
- tokens.reset(mark);
495
- }
496
- if (tokenLower === "class") {
497
- tokens.advance();
498
- }
499
- }
500
-
501
- // src/core/matching/stock-confidence.ts
502
- function scoreParts(ctx) {
503
- const { pattern, captured } = ctx;
504
- let score = 0;
505
- let maxScore = 0;
506
- const hasDefault = (role) => {
507
- return pattern.extraction?.[role]?.default !== void 0;
508
- };
509
- for (const token of pattern.template.tokens) {
510
- if (token.type === "role") {
511
- maxScore += 1;
512
- if (captured.has(token.role)) {
513
- score += 1;
514
- }
515
- } else if (token.type === "group") {
516
- for (const subToken of token.tokens) {
517
- if (subToken.type === "role") {
518
- const roleHasDefault = hasDefault(subToken.role);
519
- const weight = 0.8;
520
- maxScore += weight;
521
- if (captured.has(subToken.role)) {
522
- score += weight;
523
- } else if (roleHasDefault) {
524
- score += weight * 0.6;
525
- }
526
- }
527
- }
528
- }
529
- }
530
- const roleCoverage = maxScore > 0 ? score / maxScore : 1;
531
- let baseConfidence = roleCoverage;
532
- let stemPenalty = 0;
533
- if (ctx.stemMatchCount > 0 && ctx.totalKeywordMatches > 0) {
534
- stemPenalty = ctx.stemMatchCount / ctx.totalKeywordMatches * 0.15;
535
- baseConfidence = Math.max(0.5, baseConfidence - stemPenalty);
536
- }
537
- const vsoBoost = calculateVSOConfidenceBoost(pattern);
538
- baseConfidence = Math.min(1, baseConfidence + vsoBoost);
539
- const prepositionAdjustment = arabicPrepositionDisambiguation(pattern, captured);
540
- baseConfidence = Math.max(0, Math.min(1, baseConfidence + prepositionAdjustment));
541
- return {
542
- roleCoverage,
543
- stemPenalty,
544
- languageBoost: vsoBoost,
545
- languageAdjustment: prepositionAdjustment,
546
- final: baseConfidence
547
- };
548
- }
549
- function calculateVSOConfidenceBoost(pattern) {
550
- if (pattern.language !== "ar") {
551
- return 0;
552
- }
553
- const firstToken = pattern.template.tokens[0];
554
- if (!firstToken || firstToken.type !== "literal") {
555
- return 0;
556
- }
557
- const ARABIC_VERBS = /* @__PURE__ */ new Set([
558
- "\u0628\u062F\u0644",
559
- "\u063A\u064A\u0631",
560
- "\u0623\u0636\u0641",
561
- "\u0623\u0632\u0644",
562
- "\u0636\u0639",
563
- "\u0627\u062C\u0639\u0644",
564
- "\u0639\u064A\u0646",
565
- "\u0632\u062F",
566
- "\u0627\u0646\u0642\u0635",
567
- "\u0633\u062C\u0644",
568
- "\u0623\u0638\u0647\u0631",
569
- "\u0623\u062E\u0641",
570
- "\u0634\u063A\u0644",
571
- "\u0623\u0631\u0633\u0644",
572
- "\u0631\u0643\u0632",
573
- "\u0634\u0648\u0634",
574
- "\u062A\u0648\u0642\u0641",
575
- "\u0627\u0646\u0633\u062E",
576
- "\u0627\u062D\u0630\u0641",
577
- "\u0627\u0635\u0646\u0639",
578
- "\u0627\u0646\u062A\u0638\u0631",
579
- "\u0627\u0646\u062A\u0642\u0627\u0644",
580
- "\u0623\u0648"
581
- ]);
582
- if (ARABIC_VERBS.has(firstToken.value)) {
583
- return 0.15;
584
- }
585
- if (firstToken.alternatives) {
586
- for (const alt of firstToken.alternatives) {
587
- if (ARABIC_VERBS.has(alt)) {
588
- return 0.15;
589
- }
590
- }
591
- }
592
- return 0;
593
- }
594
- function arabicPrepositionDisambiguation(pattern, captured) {
595
- if (pattern.language !== "ar") {
596
- return 0;
597
- }
598
- let adjustment = 0;
599
- const PREFERRED_PREPOSITIONS = {
600
- patient: ["\u0639\u0644\u0649"],
601
- // element selectors prefer على (on/upon)
602
- destination: ["\u0625\u0644\u0649", "\u0627\u0644\u0649"],
603
- // destination prefers إلى (to)
604
- source: ["\u0645\u0646"],
605
- // source prefers من (from)
606
- agent: ["\u0645\u0646"],
607
- // agent/by prefers من (from/by)
608
- manner: ["\u0628"],
609
- // manner prefers ب (with/by)
610
- style: ["\u0628"],
611
- // style prefers ب (with)
612
- goal: ["\u0625\u0644\u0649", "\u0627\u0644\u0649"],
613
- // target state prefers إلى (to)
614
- method: ["\u0628"]
615
- // method prefers ب (with/by)
616
- };
617
- for (const [role, value] of captured.entries()) {
618
- const preferred = PREFERRED_PREPOSITIONS[role];
619
- if (!preferred || preferred.length === 0) {
620
- continue;
621
- }
622
- const metadata = "metadata" in value ? value.metadata : void 0;
623
- if (metadata && typeof metadata.prepositionValue === "string") {
624
- const usedPreposition = metadata.prepositionValue;
625
- if (preferred.includes(usedPreposition)) {
626
- adjustment += 0.1;
627
- } else {
628
- adjustment -= 0.1;
629
- }
630
- }
631
- }
632
- return Math.max(-0.1, Math.min(0.1, adjustment));
633
- }
634
- var stockConfidenceModel = {
635
- calculate: (ctx) => scoreParts(ctx).final,
636
- calculateWithBreakdown: (ctx) => scoreParts(ctx)
637
- };
638
-
639
- // src/core/pattern-matching/pattern-matcher.ts
640
- var _PatternMatcher = class _PatternMatcher {
641
- constructor() {
642
- /** Debug logger */
643
- this.logger = createLogger("pattern-matcher");
644
- /**
645
- * Track stem matches for confidence calculation.
646
- * This is set during matching and read during confidence calculation.
647
- */
648
- this.stemMatchCount = 0;
649
- this.totalKeywordMatches = 0;
650
- }
651
- /**
652
- * Try to match a single pattern against the token stream.
653
- * Returns the match result or null if no match.
654
- *
655
- * @param tokens - Token stream to match against
656
- * @param pattern - Pattern to match
657
- * @param profile - Optional language profile for possessive handling
658
- */
659
- matchPattern(tokens, pattern, profile) {
660
- const mark = tokens.mark();
661
- const captured = /* @__PURE__ */ new Map();
662
- this.logger.debug("========================================");
663
- this.logger.debug("matchPattern ENTRY");
664
- this.logger.debug("Pattern ID:", pattern.id);
665
- this.logger.debug("Pattern command:", pattern.command);
666
- this.logger.debug("Pattern language:", pattern.language);
667
- this.logger.debug("Pattern template:", JSON.stringify(pattern.template, null, 2));
668
- if (this.logger.isEnabled()) {
669
- const firstTokens = [];
670
- for (let i = 0; i < 10; i++) {
671
- const t = tokens.peek(i);
672
- if (t)
673
- firstTokens.push({
674
- type: t.type,
675
- value: t.value,
676
- kind: t.kind
677
- });
678
- else break;
679
- }
680
- this.logger.debug("Input tokens (first 10):", firstTokens);
681
- this.logger.debug("Profile code:", profile?.code);
682
- }
683
- this.currentProfile = profile;
684
- this.stemMatchCount = 0;
685
- this.totalKeywordMatches = 0;
686
- this.logger.debug("--- Calling matchTokenSequence ---");
687
- this.logger.debug("Pattern tokens to match:", JSON.stringify(pattern.template.tokens, null, 2));
688
- const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);
689
- this.logger.debug("matchTokenSequence returned:", success);
690
- this.logger.debug(
691
- "Captured roles:",
692
- Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])
693
- );
694
- if (!success) {
695
- this.logger.debug(">>> MATCH FAILED - resetting token position");
696
- tokens.reset(mark);
697
- return null;
698
- }
699
- const confidence = stockConfidenceModel.calculate({
700
- pattern,
701
- captured,
702
- stemMatchCount: this.stemMatchCount,
703
- totalKeywordMatches: this.totalKeywordMatches
704
- });
705
- this.applyExtractionRules(pattern, captured);
706
- return {
707
- pattern,
708
- captured,
709
- consumedTokens: tokens.position() - mark.position,
710
- confidence
711
- };
712
- }
713
- /**
714
- * Try to match multiple patterns, return the best match.
715
- *
716
- * @param tokens - Token stream to match against
717
- * @param patterns - Candidate patterns to try
718
- * @param profile - Optional language profile for possessive handling
719
- */
720
- matchBest(tokens, patterns, profile) {
721
- const matches = [];
722
- for (const pattern of patterns) {
723
- const mark = tokens.mark();
724
- const result = this.matchPattern(tokens, pattern, profile);
725
- if (result) {
726
- matches.push(result);
727
- }
728
- tokens.reset(mark);
729
- }
730
- if (matches.length === 0) {
731
- return null;
732
- }
733
- matches.sort((a, b) => {
734
- const priorityDiff = b.pattern.priority - a.pattern.priority;
735
- if (priorityDiff !== 0) return priorityDiff;
736
- const confidenceDiff = b.confidence - a.confidence;
737
- if (Math.abs(confidenceDiff) > 1e-3) return confidenceDiff;
738
- return b.consumedTokens - a.consumedTokens;
739
- });
740
- const best = matches[0];
741
- this.matchPattern(tokens, best.pattern);
742
- return best;
743
- }
744
- /**
745
- * Match a sequence of pattern tokens against the token stream.
746
- *
747
- * Supports bounded single-step backtracking: if an optional role consumes
748
- * a token and the immediately following pattern token fails, the matcher
749
- * resets to before the optional role and retries the failed token.
750
- */
751
- matchTokenSequence(tokens, patternTokens, captured, parentStopMarkers) {
752
- const firstPatternToken = patternTokens[0];
753
- const patternExpectsConjunction = firstPatternToken?.type === "literal" && (firstPatternToken.value === "and" || firstPatternToken.value === "then" || firstPatternToken.alternatives?.includes("and") || firstPatternToken.alternatives?.includes("then"));
754
- if (this.currentProfile?.code === "ar" && !patternExpectsConjunction) {
755
- while (tokens.peek()?.kind === "conjunction") {
756
- tokens.advance();
757
- }
758
- }
759
- let prevOptionalMark = null;
760
- let prevOptionalRole = null;
761
- for (let i = 0; i < patternTokens.length; i++) {
762
- const patternToken = patternTokens[i];
763
- this.logger.debug(" >> Matching pattern token:", JSON.stringify(patternToken, null, 2));
764
- const currTok = tokens.peek();
765
- this.logger.debug(
766
- " >> Current input token:",
767
- currTok ? JSON.stringify({
768
- type: currTok.type,
769
- value: currTok.value,
770
- kind: currTok.kind
771
- }) : "EOF"
772
- );
773
- if (patternToken.type === "role" && patternToken.greedy) {
774
- const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);
775
- if (parentStopMarkers) {
776
- for (const m of parentStopMarkers) stopMarkers.add(m);
777
- }
778
- const values = [];
779
- while (!tokens.isAtEnd()) {
780
- const nextToken = tokens.peek();
781
- if (!nextToken) break;
782
- if (this.isStopMarker(nextToken, stopMarkers)) break;
783
- values.push(nextToken.value);
784
- tokens.advance();
785
- }
786
- if (values.length > 0) {
787
- captured.set(patternToken.role, { type: "expression", raw: values.join(" ") });
788
- prevOptionalMark = null;
789
- prevOptionalRole = null;
790
- continue;
791
- } else if (patternToken.optional) {
792
- continue;
793
- } else {
794
- return false;
795
- }
796
- }
797
- if (patternToken.type === "group") {
798
- const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);
799
- if (parentStopMarkers) {
800
- for (const m of parentStopMarkers) siblingStopMarkers.add(m);
801
- }
802
- const groupMatched = this.matchGroupToken(
803
- tokens,
804
- patternToken,
805
- captured,
806
- siblingStopMarkers
807
- );
808
- if (groupMatched) {
809
- prevOptionalMark = null;
810
- prevOptionalRole = null;
811
- continue;
812
- }
813
- if (this.isOptional(patternToken)) {
814
- continue;
815
- }
816
- return false;
817
- }
818
- const isOptionalRole = patternToken.type === "role" && patternToken.optional === true;
819
- const markBefore = isOptionalRole ? tokens.mark() : null;
820
- const isRoleToken = patternToken.type === "role";
821
- if (isRoleToken && !isOptionalRole) {
822
- const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;
823
- if (nextPT?.type === "literal") {
824
- const currentToken = tokens.peek();
825
- if (currentToken && this.getMatchType(currentToken, nextPT.value) !== "none") {
826
- this.logger.debug(
827
- " >> MARKER-STEAL GUARD: current token matches next literal, skipping role"
828
- );
829
- this.logger.debug(" >> Token match FAILED");
830
- if (this.isOptional(patternToken)) {
831
- continue;
832
- }
833
- if (prevOptionalMark && prevOptionalRole) {
834
- this.logger.debug(" >> BACKTRACKING: undoing optional role", prevOptionalRole);
835
- tokens.reset(prevOptionalMark);
836
- captured.delete(prevOptionalRole);
837
- prevOptionalMark = null;
838
- prevOptionalRole = null;
839
- const retryMatched = this.matchPatternToken(tokens, patternToken, captured);
840
- this.logger.debug(" >> Backtrack retry result:", retryMatched);
841
- if (retryMatched) {
842
- continue;
843
- }
844
- }
845
- return false;
846
- }
847
- }
848
- }
849
- const matched = this.matchPatternToken(tokens, patternToken, captured);
850
- this.logger.debug(" >> Match result:", matched);
851
- if (matched) {
852
- if (isOptionalRole) {
853
- prevOptionalMark = markBefore;
854
- prevOptionalRole = patternToken.role;
855
- } else {
856
- prevOptionalMark = null;
857
- prevOptionalRole = null;
858
- }
859
- continue;
860
- }
861
- this.logger.debug(" >> Token match FAILED");
862
- if (this.isOptional(patternToken)) {
863
- continue;
864
- }
865
- if (prevOptionalMark && prevOptionalRole) {
866
- this.logger.debug(" >> BACKTRACKING: undoing optional role", prevOptionalRole);
867
- tokens.reset(prevOptionalMark);
868
- captured.delete(prevOptionalRole);
869
- prevOptionalMark = null;
870
- prevOptionalRole = null;
871
- const retryMatched = this.matchPatternToken(tokens, patternToken, captured);
872
- this.logger.debug(" >> Backtrack retry result:", retryMatched);
873
- if (retryMatched) {
874
- continue;
875
- }
876
- }
877
- return false;
878
- }
879
- return true;
880
- }
881
- /**
882
- * Match a single pattern token against the current position in the stream.
883
- */
884
- matchPatternToken(tokens, patternToken, captured) {
885
- switch (patternToken.type) {
886
- case "literal":
887
- return this.matchLiteralToken(tokens, patternToken);
888
- case "role":
889
- return readRoleValue(tokens, patternToken, captured, this.currentProfile);
890
- case "group":
891
- return this.matchGroupToken(tokens, patternToken, captured);
892
- default:
893
- return false;
894
- }
895
- }
896
- /**
897
- * Match a literal pattern token (keyword or particle).
898
- */
899
- matchLiteralToken(tokens, patternToken) {
900
- const token = tokens.peek();
901
- this.logger.debug(" >>> matchLiteralToken: expecting", patternToken.value);
902
- this.logger.debug(
903
- " >>> matchLiteralToken: got token",
904
- token ? JSON.stringify({
905
- type: token.type,
906
- value: token.value,
907
- kind: token.kind
908
- }) : "null"
909
- );
910
- if (!token) {
911
- this.logger.debug(" >>> matchLiteralToken: FAIL - no token");
912
- return false;
913
- }
914
- const matchType = this.getMatchType(token, patternToken.value);
915
- this.logger.debug(
916
- " >>> matchType for",
917
- token.value,
918
- "vs",
919
- patternToken.value,
920
- ":",
921
- matchType
922
- );
923
- if (matchType !== "none") {
924
- this.totalKeywordMatches++;
925
- if (matchType === "stem") {
926
- this.stemMatchCount++;
927
- }
928
- tokens.advance();
929
- return true;
930
- }
931
- if (patternToken.alternatives) {
932
- for (const alt of patternToken.alternatives) {
933
- const altMatchType = this.getMatchType(token, alt);
934
- if (altMatchType !== "none") {
935
- this.totalKeywordMatches++;
936
- if (altMatchType === "stem") {
937
- this.stemMatchCount++;
938
- }
939
- tokens.advance();
940
- return true;
941
- }
942
- }
943
- }
944
- return false;
945
- }
946
- /**
947
- * Match a group pattern token (optional sequence).
948
- * When the group's leading marker isn't at the current position, scans ahead
949
- * up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens
950
- * (e.g., a value like 'hello') to sit between groups without blocking later
951
- * marker matches.
952
- */
953
- matchGroupToken(tokens, patternToken, captured, parentStopMarkers) {
954
- const mark = tokens.mark();
955
- const capturedBefore = new Set(captured.keys());
956
- const success = this.matchTokenSequence(
957
- tokens,
958
- patternToken.tokens,
959
- captured,
960
- parentStopMarkers
961
- );
962
- if (success) return true;
963
- tokens.reset(mark);
964
- for (const role of captured.keys()) {
965
- if (!capturedBefore.has(role)) captured.delete(role);
966
- }
967
- if (!patternToken.optional) return false;
968
- const leadingMarker = this.getGroupLeadingMarker(patternToken);
969
- if (leadingMarker) {
970
- for (let offset = 1; offset <= _PatternMatcher.MAX_MARKER_SCAN; offset++) {
971
- const ahead = tokens.peek(offset);
972
- if (!ahead) break;
973
- const aheadValue = (ahead.normalized || ahead.value).toLowerCase();
974
- if (aheadValue === leadingMarker) {
975
- this.logger.debug(
976
- " >> MARKER SCAN: found",
977
- leadingMarker,
978
- "at offset",
979
- offset,
980
- "- skipping intervening tokens"
981
- );
982
- for (let s = 0; s < offset; s++) tokens.advance();
983
- const retrySuccess = this.matchTokenSequence(
984
- tokens,
985
- patternToken.tokens,
986
- captured,
987
- parentStopMarkers
988
- );
989
- if (retrySuccess) return true;
990
- tokens.reset(mark);
991
- for (const role of captured.keys()) {
992
- if (!capturedBefore.has(role)) captured.delete(role);
993
- }
994
- break;
995
- }
996
- }
997
- }
998
- return true;
999
- }
1000
- /**
1001
- * Get the leading marker literal from an optional group.
1002
- * Returns the lowercase marker value, or null if the group
1003
- * doesn't start with a literal token (e.g., SOV groups where
1004
- * the role comes before the marker).
1005
- */
1006
- getGroupLeadingMarker(group) {
1007
- const first = group.tokens[0];
1008
- if (first?.type === "literal") return first.value.toLowerCase();
1009
- return null;
1010
- }
1011
- /**
1012
- * Get the type of match for a token against a value.
1013
- * Used for confidence calculation.
1014
- */
1015
- getMatchType(token, value) {
1016
- if (token.value === value) return "exact";
1017
- if (token.normalized === value) return "normalized";
1018
- if (token.stem === value && token.stemConfidence !== void 0 && token.stemConfidence >= 0.7) {
1019
- return "stem";
1020
- }
1021
- if (token.kind === "keyword" && safeToLowerCase(token.value) === value.toLowerCase()) {
1022
- return "case-insensitive";
1023
- }
1024
- return "none";
1025
- }
1026
- /**
1027
- * Collect literal values from upcoming pattern tokens that act as stop markers
1028
- * for greedy role capture. Returns the set of lowercase values.
1029
- */
1030
- collectStopMarkers(patternTokens, startIndex) {
1031
- const markers = /* @__PURE__ */ new Set();
1032
- for (let j = startIndex; j < patternTokens.length; j++) {
1033
- const pt = patternTokens[j];
1034
- if (pt.type === "literal") {
1035
- markers.add(pt.value.toLowerCase());
1036
- if (pt.alternatives) {
1037
- for (const alt of pt.alternatives) {
1038
- markers.add(alt.toLowerCase());
1039
- }
1040
- }
1041
- break;
1042
- }
1043
- if (pt.type === "group") {
1044
- for (const gt of pt.tokens) {
1045
- if (gt.type === "literal") {
1046
- markers.add(gt.value.toLowerCase());
1047
- if (gt.alternatives) {
1048
- for (const alt of gt.alternatives) {
1049
- markers.add(alt.toLowerCase());
1050
- }
1051
- }
1052
- break;
1053
- }
1054
- }
1055
- if (!pt.optional) break;
1056
- }
1057
- }
1058
- return markers;
1059
- }
1060
- /**
1061
- * Check if a token matches any stop marker for greedy capture.
1062
- */
1063
- isStopMarker(token, stopMarkers) {
1064
- if (stopMarkers.size === 0) return false;
1065
- if (stopMarkers.has(token.value.toLowerCase())) return true;
1066
- if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;
1067
- return false;
1068
- }
1069
- // ==========================================================================
1070
- // Depth Limits for Expression Parsing (security hardening)
1071
- // ==========================================================================
1072
- /**
1073
- * Apply extraction rules to fill in static values and defaults for missing roles.
1074
- */
1075
- applyExtractionRules(pattern, captured) {
1076
- for (const [role, rule] of Object.entries(pattern.extraction)) {
1077
- if (!captured.has(role)) {
1078
- if (rule.value !== void 0) {
1079
- captured.set(role, { type: "literal", value: rule.value });
1080
- } else if (rule.default) {
1081
- captured.set(role, rule.default);
1082
- }
1083
- }
1084
- }
1085
- }
1086
- /**
1087
- * Check if a pattern token is optional.
1088
- */
1089
- isOptional(patternToken) {
1090
- return patternToken.type !== "literal" && patternToken.optional === true;
1091
- }
1092
- // ===========================================================================
1093
- // English Idiom Support - Noise Word Handling
1094
- // ===========================================================================
1095
- /**
1096
- * Extract event modifiers from the token stream.
1097
- * Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)
1098
- * that can appear after event names.
1099
- *
1100
- * Returns EventModifiers object or undefined if no modifiers found.
1101
- */
1102
- extractEventModifiers(tokens) {
1103
- const modifiers = {};
1104
- let foundModifier = false;
1105
- while (!tokens.isAtEnd()) {
1106
- const token = tokens.peek();
1107
- if (!token || token.kind !== "event-modifier") {
1108
- break;
1109
- }
1110
- const metadata = token.metadata;
1111
- if (!metadata) {
1112
- break;
1113
- }
1114
- foundModifier = true;
1115
- switch (metadata.modifierName) {
1116
- case "once":
1117
- modifiers.once = true;
1118
- break;
1119
- case "debounce":
1120
- if (typeof metadata.value === "number") {
1121
- modifiers.debounce = metadata.value;
1122
- }
1123
- break;
1124
- case "throttle":
1125
- if (typeof metadata.value === "number") {
1126
- modifiers.throttle = metadata.value;
1127
- }
1128
- break;
1129
- case "queue":
1130
- if (metadata.value === "first" || metadata.value === "last" || metadata.value === "all" || metadata.value === "none") {
1131
- modifiers.queue = metadata.value;
1132
- }
1133
- break;
1134
- }
1135
- tokens.advance();
1136
- }
1137
- return foundModifier ? modifiers : void 0;
1138
- }
1139
- };
1140
- /** Maximum tokens to scan ahead when looking for a group's leading marker */
1141
- _PatternMatcher.MAX_MARKER_SCAN = 3;
1142
- var PatternMatcher = _PatternMatcher;
1143
- var patternMatcher = new PatternMatcher();
1144
-
1145
1
  // src/parsing/multi-statement.ts
1146
2
  function createMultiStatementParser(dsl, config) {
1147
3
  return new MultiStatementParserImpl(dsl, config);
@@ -1380,7 +236,6 @@ function accumulateIndented(statements, config) {
1380
236
  return { blocks: rootBlocks, orphans };
1381
237
  }
1382
238
  export {
1383
- PatternMatcher,
1384
239
  accumulateBlocks,
1385
240
  createMultiStatementParser
1386
241
  };