@thinkingos/vsl-mcp-server 1.2.12 → 1.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -76,7 +76,7 @@ import { isVslDiff } from "@thinkingos/vsl-sdk";
76
76
 
77
77
  // src/utils/injectVslIds.ts
78
78
  function buildInjectionScript() {
79
- return (objects) => {
79
+ return (objects, semanticMap) => {
80
80
  function parseVslId(id) {
81
81
  const match = id.match(/^([a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*)_(\d+(?:_\d+)*)$/);
82
82
  if (!match) return null;
@@ -84,20 +84,62 @@ function buildInjectionScript() {
84
84
  const indexPath = match[2].split("_").map(Number);
85
85
  return { tag, indexPath };
86
86
  }
87
- function visit(obj) {
88
- const parsed = parseVslId(obj.id);
89
- if (!parsed) return;
90
- const indexPath = parsed.indexPath;
87
+ function findByIndexPath(indexPath) {
91
88
  let current = document.body;
92
89
  for (const idx of indexPath) {
93
90
  if (!current) break;
94
91
  const elementChildren = Array.from(current.children);
95
92
  current = elementChildren[idx] || null;
96
93
  }
97
- if (current) {
98
- current.setAttribute("data-vsl-id", obj.id);
94
+ return current;
95
+ }
96
+ function findBySemantic(semantic) {
97
+ try {
98
+ if (semantic.role && semantic.ariaLabel) {
99
+ const selector = `[role="${semantic.role}"][aria-label="${semantic.ariaLabel}"]`;
100
+ const el = document.querySelector(selector);
101
+ if (el) return el;
102
+ }
103
+ if (semantic.role && semantic.ariaLabelledBy) {
104
+ const selector = `[role="${semantic.role}"][aria-labelledby="${semantic.ariaLabelledBy}"]`;
105
+ const el = document.querySelector(selector);
106
+ if (el) return el;
107
+ }
108
+ if (semantic.role) {
109
+ const selector = `[role="${semantic.role}"]`;
110
+ const el = document.querySelector(selector);
111
+ if (el) return el;
112
+ }
113
+ if (semantic.ariaLabel) {
114
+ const selector = `[aria-label="${semantic.ariaLabel}"]`;
115
+ const el = document.querySelector(selector);
116
+ if (el) return el;
117
+ }
118
+ return null;
119
+ } catch (error) {
120
+ console.warn("[VSL] Semantic selector error:", error);
121
+ return null;
122
+ }
123
+ }
124
+ function visit(obj) {
125
+ const parsed = parseVslId(obj.id);
126
+ if (!parsed) return;
127
+ const indexPath = parsed.indexPath;
128
+ const indexPathKey = indexPath.join("_");
129
+ let target = findByIndexPath(indexPath);
130
+ if (!target) {
131
+ const semantic = semanticMap[indexPathKey];
132
+ if (semantic) {
133
+ target = findBySemantic(semantic);
134
+ if (target) {
135
+ console.log(`[VSL] Fallback to semantic selector for ${obj.id}: indexPath=[${indexPathKey}] \u2192 semantic={role:${semantic.role}, ariaLabel:${semantic.ariaLabel}}`);
136
+ }
137
+ }
138
+ }
139
+ if (target) {
140
+ target.setAttribute("data-vsl-id", obj.id);
99
141
  } else {
100
- console.warn(`[VSL] Failed to inject data-vsl-id="${obj.id}": element not found at indexPath [${indexPath.join(", ")}]`);
142
+ console.warn(`[VSL] Failed to inject data-vsl-id="${obj.id}": element not found at indexPath [${indexPathKey}] and no semantic fallback available`);
101
143
  }
102
144
  if (obj.ch) {
103
145
  for (const child of obj.ch) {
@@ -110,14 +152,22 @@ function buildInjectionScript() {
110
152
  }
111
153
  };
112
154
  }
113
- async function injectVslIdsIntoDom(browser, objects) {
155
+ async function injectVslIdsIntoDom(browser, objects, semanticMap = /* @__PURE__ */ new Map()) {
114
156
  const page = await browser.getPage();
115
157
  await page.waitForTimeout(50);
116
- await browser.evaluate(buildInjectionScript(), objects);
158
+ const semanticMapObj = {};
159
+ for (const [key, value] of semanticMap) {
160
+ semanticMapObj[key] = value;
161
+ }
162
+ await browser.evaluate(buildInjectionScript(), objects, semanticMapObj);
117
163
  }
118
- async function injectVslIdsIntoFrame(browser, frame, objects) {
164
+ async function injectVslIdsIntoFrame(browser, frame, objects, semanticMap = /* @__PURE__ */ new Map()) {
119
165
  try {
120
- await browser.evaluateInFrame(frame, buildInjectionScript(), objects);
166
+ const semanticMapObj = {};
167
+ for (const [key, value] of semanticMap) {
168
+ semanticMapObj[key] = value;
169
+ }
170
+ await browser.evaluateInFrame(frame, buildInjectionScript(), objects, semanticMapObj);
121
171
  } catch (error) {
122
172
  console.warn("[VSL] Failed to inject data-vsl-id into iframe:", error);
123
173
  }
@@ -483,6 +533,30 @@ function countObjects(objects) {
483
533
  }
484
534
  return count;
485
535
  }
536
+ function buildSemanticMap(elements) {
537
+ const map = /* @__PURE__ */ new Map();
538
+ function visit(el) {
539
+ const elem = el;
540
+ if (!elem.indexPath) return;
541
+ if (elem.role || elem.ariaLabel || elem.ariaLabelledBy) {
542
+ const key = elem.indexPath.join("_");
543
+ const semantic = {};
544
+ if (elem.role) semantic.role = elem.role;
545
+ if (elem.ariaLabel) semantic.ariaLabel = elem.ariaLabel;
546
+ if (elem.ariaLabelledBy) semantic.ariaLabelledBy = elem.ariaLabelledBy;
547
+ map.set(key, semantic);
548
+ }
549
+ if (elem.children && Array.isArray(elem.children)) {
550
+ for (const child of elem.children) {
551
+ visit(child);
552
+ }
553
+ }
554
+ }
555
+ for (const el of elements) {
556
+ visit(el);
557
+ }
558
+ return map;
559
+ }
486
560
  function extractDomTreeInBrowser() {
487
561
  const viewportWidth = window.innerWidth;
488
562
  const viewportHeight = window.innerHeight;
@@ -590,7 +664,11 @@ function extractDomTreeInBrowser() {
590
664
  text: ownText(child) || null,
591
665
  attributes,
592
666
  css,
593
- children
667
+ children,
668
+ // Semantic attributes for fallback selectors
669
+ role: attributes["role"],
670
+ ariaLabel: attributes["aria-label"],
671
+ ariaLabelledBy: attributes["aria-labelledby"]
594
672
  });
595
673
  });
596
674
  return result;
@@ -727,12 +805,13 @@ async function handleGetSnapshot(args, browser, session, _config) {
727
805
  const viewport = extraction.viewport;
728
806
  const url = args.url || await browser.evaluate(() => window.location.href);
729
807
  const title = await browser.evaluate(() => document.title);
808
+ const semanticMap = buildSemanticMap(extractedElements);
730
809
  const iframeElementsRaw = await browser.evaluate(extractIframesInBrowser);
731
810
  const iframeElements = Array.isArray(iframeElementsRaw) ? iframeElementsRaw : [];
732
811
  if (iframeElements.length > 0) {
733
- console.log(`[VSL] Found ${iframeElements.length} iframe elements:`);
812
+ console.error(`[VSL] Found ${iframeElements.length} iframe elements:`);
734
813
  for (const iframe of iframeElements) {
735
- console.log(` - URL: ${iframe.url}, name: ${iframe.name}, id: ${iframe.id}`);
814
+ console.error(` - URL: ${iframe.url}, name: ${iframe.name}, id: ${iframe.id}`);
736
815
  }
737
816
  }
738
817
  const iframeSubDocs = [];
@@ -746,10 +825,10 @@ async function handleGetSnapshot(args, browser, session, _config) {
746
825
  });
747
826
  if (!frame) {
748
827
  console.warn(`[VSL] No Playwright frame found for iframe URL: ${iframeInfo.url}`);
749
- console.log(`[VSL] Available frames:`, allFrames.map((f) => f.url()));
828
+ console.error(`[VSL] Available frames:`, allFrames.map((f) => f.url()));
750
829
  continue;
751
830
  }
752
- console.log(`[VSL] \u2705 Matched Playwright frame for iframe: ${iframeInfo.url} \u2192 ${frame.url()}`);
831
+ console.error(`[VSL] \u2705 Matched Playwright frame for iframe: ${iframeInfo.url} \u2192 ${frame.url()}`);
753
832
  const iframeExtraction = await extractDomTreeFromFrame(browser, frame);
754
833
  const iframeViewport = iframeExtraction.viewport;
755
834
  const { segmentTree: segmentTree2, buildVslDocument: buildVslDocument2 } = await import("@thinkingos/vsl-sdk");
@@ -768,7 +847,7 @@ async function handleGetSnapshot(args, browser, session, _config) {
768
847
  // сохраняем PlaywrightFrame для injectVslIdsIntoFrame
769
848
  });
770
849
  iframeFrameRegistry.set(iframeSubDocs.length - 1, iframeInfo.url);
771
- console.log(`[VSL] \u2705 Successfully extracted DOM from iframe: ${iframeInfo.url} (${iframeDoc.objects.length} objects)`);
850
+ console.error(`[VSL] \u2705 Successfully extracted DOM from iframe: ${iframeInfo.url} (${iframeDoc.objects.length} objects)`);
772
851
  } catch (error) {
773
852
  console.warn(`[VSL] \u274C Failed to extract iframe ${iframeInfo.url}:`, error);
774
853
  }
@@ -786,7 +865,7 @@ async function handleGetSnapshot(args, browser, session, _config) {
786
865
  );
787
866
  const currentDoc = isVslDiff(result) ? session.getSnapshot() : result;
788
867
  if (iframeSubDocs.length > 0) {
789
- console.log(`[VSL] Adding ${iframeSubDocs.length} iframe objects to snapshot`);
868
+ console.error(`[VSL] Adding ${iframeSubDocs.length} iframe objects to snapshot`);
790
869
  const iframeObjects = iframeSubDocs.map((iframeInfo, index) => ({
791
870
  id: `iframe_${index}`,
792
871
  t: "iframe",
@@ -799,11 +878,12 @@ async function handleGetSnapshot(args, browser, session, _config) {
799
878
  }
800
879
  }));
801
880
  currentDoc.objects.push(...iframeObjects);
881
+ session.rebuildIdMaps();
802
882
  for (const iframeInfo of iframeSubDocs) {
803
- await injectVslIdsIntoFrame(browser, iframeInfo.frame, iframeInfo.doc.objects);
883
+ await injectVslIdsIntoFrame(browser, iframeInfo.frame, iframeInfo.doc.objects, semanticMap);
804
884
  }
805
885
  }
806
- await injectVslIdsIntoDom(browser, currentDoc.objects);
886
+ await injectVslIdsIntoDom(browser, currentDoc.objects, semanticMap);
807
887
  const scrollContext = session.getScrollContext();
808
888
  const win = computeVisibleWindow(currentDoc.canvas.viewport, scrollContext);
809
889
  const scrollable = computeScrollable(currentDoc.canvas.viewport, scrollContext);
@@ -1143,14 +1223,12 @@ async function handleExecuteAction(args, browser, session) {
1143
1223
  };
1144
1224
  session.snapshotFromElements(extraction.elements, input);
1145
1225
  }
1146
- const idMap = session.getIdMap();
1147
- const resolvedId = idMap.get(args.target_id) || args.target_id;
1148
1226
  let targetFrame = null;
1149
- let localId = resolvedId;
1150
- const frameMatch = resolvedId.match(/^iframe_(\d+):(.+)$/);
1227
+ let localShortId = args.target_id;
1228
+ const frameMatch = args.target_id.match(/^iframe_(\d+):(.+)$/);
1151
1229
  if (frameMatch) {
1152
1230
  const frameIndex = parseInt(frameMatch[1], 10);
1153
- localId = frameMatch[2];
1231
+ localShortId = frameMatch[2];
1154
1232
  const frameUrl = iframeFrameRegistry.get(frameIndex);
1155
1233
  if (!frameUrl) {
1156
1234
  return {
@@ -1170,14 +1248,60 @@ async function handleExecuteAction(args, browser, session) {
1170
1248
  };
1171
1249
  }
1172
1250
  }
1251
+ const idMap = session.getIdMap();
1252
+ const resolvedId = idMap.get(localShortId) || localShortId;
1253
+ const localId = resolvedId;
1173
1254
  const selector = `[data-vsl-id="${localId}"], #${localId}, .${localId}`;
1174
1255
  const page = await browser.getPage();
1175
1256
  const target = targetFrame || page;
1176
1257
  switch (args.action) {
1177
- case "click":
1178
- await target.locator(selector).click({ timeout: 5e3 });
1258
+ case "click": {
1259
+ try {
1260
+ await target.locator(selector).click({ timeout: 5e3 });
1261
+ } catch (locatorError) {
1262
+ let findObjectById2 = function(objects, targetId) {
1263
+ for (const obj of objects) {
1264
+ const o = obj;
1265
+ if (o.id === targetId) return o;
1266
+ if (o.ch && Array.isArray(o.ch)) {
1267
+ const found = findObjectById2(o.ch, targetId);
1268
+ if (found) return found;
1269
+ }
1270
+ }
1271
+ return null;
1272
+ };
1273
+ var findObjectById = findObjectById2;
1274
+ console.warn(`[VSL] Standard locator failed for ${args.target_id}, trying positional mapping fallback`);
1275
+ const snapshotDoc = session.getSnapshot();
1276
+ const snapshotObjects = snapshotDoc.objects ?? [];
1277
+ const snapshotObj = findObjectById2(snapshotObjects, localId);
1278
+ if (!snapshotObj || !snapshotObj.rect) {
1279
+ console.error(`[VSL] Positional mapping failed: element ${localId} not found in snapshot or has no rect`);
1280
+ throw locatorError;
1281
+ }
1282
+ const rect = snapshotObj.rect;
1283
+ const centerX = rect.x + rect.width / 2;
1284
+ const centerY = rect.y + rect.height / 2;
1285
+ const elementFound = await target.evaluate(
1286
+ ([x, y]) => {
1287
+ const el = document.elementFromPoint(x, y);
1288
+ if (el) {
1289
+ el.click();
1290
+ return true;
1291
+ }
1292
+ return false;
1293
+ },
1294
+ [centerX, centerY]
1295
+ );
1296
+ if (!elementFound) {
1297
+ console.error(`[VSL] Positional mapping failed: no element found at (${centerX}, ${centerY})`);
1298
+ throw locatorError;
1299
+ }
1300
+ console.log(`[VSL] Positional mapping succeeded: clicked element at (${centerX}, ${centerY}) for ${args.target_id}`);
1301
+ }
1179
1302
  await page.waitForTimeout(100);
1180
1303
  break;
1304
+ }
1181
1305
  case "fill":
1182
1306
  case "type":
1183
1307
  if (!args.value) {
@@ -3012,6 +3136,31 @@ var ServerSession = class {
3012
3136
  getReverseIdMap() {
3013
3137
  return this.reverseIdMap;
3014
3138
  }
3139
+ /**
3140
+ * Перестраивает карты маппинга ID (idMap и reverseIdMap) на основе текущего документа.
3141
+ * Используется после добавления iframe объектов в currentDoc.objects,
3142
+ * чтобы reverseIdMap содержал маппинг для iframe элементов.
3143
+ *
3144
+ * Context: snapshotFromElements() строит карты ДО добавления iframe объектов,
3145
+ * поэтому iframe элементы не попадают в reverseIdMap. Этот метод вызывается
3146
+ * после добавления iframe объектов для перестроения карт.
3147
+ */
3148
+ rebuildIdMaps() {
3149
+ if (!this.currentDocument) return;
3150
+ const currentObjects = this.currentDocument.objects ?? [];
3151
+ const previousObjects = this.previousDocument?.objects ?? [];
3152
+ const unionObjects = [...currentObjects, ...previousObjects];
3153
+ if (currentObjects.length > 0) {
3154
+ this.idMap = buildIdMap(currentObjects);
3155
+ } else {
3156
+ this.idMap = /* @__PURE__ */ new Map();
3157
+ }
3158
+ if (unionObjects.length > 0) {
3159
+ this.reverseIdMap = buildReverseIdMap(unionObjects);
3160
+ } else {
3161
+ this.reverseIdMap = /* @__PURE__ */ new Map();
3162
+ }
3163
+ }
3015
3164
  };
3016
3165
 
3017
3166
  // src/session/sessionManager.ts
@@ -3144,7 +3293,7 @@ var SessionManager = class {
3144
3293
  };
3145
3294
 
3146
3295
  // src/version.ts
3147
- var VSL_MCP_SERVER_VERSION = "1.2.12";
3296
+ var VSL_MCP_SERVER_VERSION = "1.2.14";
3148
3297
 
3149
3298
  // src/index.ts
3150
3299
  async function main() {