@thinkingos/vsl-mcp-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,20 +6,16 @@ VSL MCP Server — интеграция Visual Scene Language с AI-агента
6
6
 
7
7
  ## Быстрая установка (одна команда)
8
8
 
9
- # Через npx — автоматически скачивает пакет и запускает интерактивный setup:
10
-
11
9
 
10
+ # Через npx — автоматически скачивает пакет и запускает интерактивный setup:
12
11
  npx -p @thinkingos/vsl-mcp-server mcp-server-setup
13
12
 
14
13
 
15
14
  Setup скрипт поможет вам:
16
15
  1. Проверить Node.js >= 18
17
16
  2. Установить Playwright (опционально, для браузерных инструментов)
18
- 3. Настроить API ключи для vision-backend (OpenAI / Anthropic / Custom)
19
- 4. Проверить работоспособность API (тестовый запрос)
20
- 5. Сохранить конфигурацию в `~/.vsl/config.json`
21
- 6. Получить инструкции для подключения к агенту
22
-
17
+ 3. Сохранить конфигурацию в `~/.vsl/config.json`
18
+ 4. Получить инструкции для подключения к агенту
23
19
  ## Установка из исходников (для разработчиков)
24
20
 
25
21
  ### Из корня monorepo
@@ -36,18 +32,19 @@ cd packages/mcp-server
36
32
  npm run build
37
33
  ### Интерактивная настройка (рекомендуется)
38
34
 
35
+
39
36
  # Из корня monorepo:
40
37
  node packages/mcp-server/bin/setup.js
41
38
 
42
39
  # Или из директории packages/mcp-server:
43
40
  npm run setup
41
+
42
+
44
43
  Setup скрипт поможет вам:
45
44
  1. Проверить Node.js >= 18
46
45
  2. Установить Playwright (опционально, для браузерных инструментов)
47
- 3. Настроить API ключи для vision-backend (OpenAI, Anthropic, или любой OpenAI-compatible провайдер)
48
- 4. Проверить работоспособность API (тестовый запрос)
49
- 5. Сохранить конфигурацию в `~/.vsl/config.json`
50
- 6. Получить инструкции для подключения к агенту
46
+ 3. Сохранить конфигурацию в `~/.vsl/config.json`
47
+ 4. Получить инструкции для подключения к агенту
51
48
 
52
49
  ## Конфигурация
53
50
 
package/bin/setup.js CHANGED
@@ -6,10 +6,8 @@
6
6
  * Бесшовная установка:
7
7
  * 1. Проверка Node.js >= 18
8
8
  * 2. Проверка/установка Playwright (chromium)
9
- * 3. Настройка API ключей для vision-backend (OpenAI / Anthropic / Custom)
10
- * 4. Валидация API ключа (тестовый запрос)
11
- * 5. Сохранение конфигурации в ~/.vsl/config.json
12
- * 6. Вывод инструкций для подключения к агенту
9
+ * 3. Сохранение конфигурации в ~/.vsl/config.json
10
+ * 4. Вывод инструкций для подключения к агенту
13
11
  *
14
12
  * Usage:
15
13
  * # Из корня monorepo:
@@ -18,6 +16,7 @@
18
16
  * npm run setup
19
17
  */
20
18
 
19
+
21
20
  import { createInterface } from 'readline';
22
21
  import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
23
22
  import { join } from 'path';
@@ -438,10 +437,8 @@ async function main() {
438
437
  log('Этот скрипт поможет вам:');
439
438
  log(' 1. Проверить Node.js');
440
439
  log(' 2. Установить Playwright (для браузерных инструментов)');
441
- log(' 3. Настроить API ключи для vision-backend');
442
- log(' 4. Проверить работоспособность API');
443
- log(' 5. Сохранить конфигурацию');
444
- log(' 6. Получить инструкции для подключения к агенту');
440
+ log(' 3. Сохранить конфигурацию');
441
+ log(' 4. Получить инструкции для подключения к агенту');
445
442
  log('');
446
443
 
447
444
  // Шаг 1: Node.js
@@ -452,39 +449,16 @@ async function main() {
452
449
  // Шаг 2: Playwright
453
450
  await setupPlaywright();
454
451
 
455
- // Шаг 3: API config
456
- const visionConfig = await setupApiConfig();
457
-
458
- // Шаг 4: Валидация
459
- if (visionConfig) {
460
- await validateApiKey(visionConfig);
461
- }
462
-
463
- // Шаг 5: Сохранение конфига
464
- step(5, 'Сохранение конфигурации');
452
+ // Шаг 3: Сохранение конфига
453
+ step(3, 'Сохранение конфигурации');
465
454
 
466
455
  const configPath = join(ensureConfigDir(), 'config.json');
467
456
  const config = loadOrCreateConfig(configPath);
457
+ saveConfig(configPath, config);
458
+ ok(`Конфигурация сохранена: ${configPath}`);
468
459
 
469
- if (visionConfig) {
470
- config.vision = {
471
- provider: visionConfig.provider,
472
- model: visionConfig.model,
473
- apiKey: visionConfig.apiKey,
474
- ...(visionConfig.baseUrl ? { baseUrl: visionConfig.baseUrl } : {}),
475
- };
476
- saveConfig(configPath, config);
477
- ok(`Конфигурация сохранена: ${configPath}`);
478
- } else {
479
- warn('Vision-backend не настроен. Вы можете настроить его позже.');
480
- info(`Через config file: ${C.dim}~/.vsl/config.json${C.reset}`);
481
- info(`Через env vars: ${C.dim}VSL_VISION_PROVIDER, VSL_VISION_BASE_URL, VSL_VISION_API_KEY, VSL_VISION_MODEL${C.reset}`);
482
- }
483
-
484
- // Шаг 6: Инструкции
485
- if (visionConfig) {
486
- printAgentInstructions(visionConfig);
487
- }
460
+ // Шаг 4: Инструкции
461
+ printAgentInstructions(null);
488
462
 
489
463
  // Финал
490
464
  log(`${C.bold}✨ Готово!${C.reset}`);
package/dist/index.js CHANGED
@@ -72,7 +72,7 @@ import {
72
72
  } from "@modelcontextprotocol/sdk/types.js";
73
73
 
74
74
  // src/tools/getSnapshot.ts
75
- import { segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
75
+ import { isVslDiff } from "@thinkingos/vsl-sdk";
76
76
  function extractDomTreeInBrowser() {
77
77
  const NON_RENDERABLE_TAGS = /* @__PURE__ */ new Set([
78
78
  "script",
@@ -180,7 +180,7 @@ async function handleGetSnapshot(args, browser, session, _config) {
180
180
  if (!isAvailable) {
181
181
  return {
182
182
  status: "error",
183
- error: 'Playwright is not installed. Install it with: npm install playwright\nOr use vsl_read_page with mode="http" for static pages.'
183
+ error: "Playwright is not installed. Install it with: npm install playwright"
184
184
  };
185
185
  }
186
186
  const extractedElements = await browser.evaluate(extractDomTreeInBrowser);
@@ -188,14 +188,19 @@ async function handleGetSnapshot(args, browser, session, _config) {
188
188
  width: window.innerWidth,
189
189
  height: window.innerHeight
190
190
  }));
191
+ const url = args.url || await browser.evaluate(() => window.location.href);
191
192
  const title = await browser.evaluate(() => document.title);
192
- const segmentedElements = segmentTree(extractedElements);
193
- const vslDocument = buildVslDocument(segmentedElements, {
193
+ const input = {
194
194
  viewport,
195
- url: args.url || await browser.evaluate(() => window.location.href),
195
+ url,
196
196
  title,
197
197
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
198
- });
198
+ };
199
+ const result = session.snapshotFromElements(
200
+ extractedElements,
201
+ input
202
+ );
203
+ const currentDoc = isVslDiff(result) ? session.getSnapshot() : result;
199
204
  await browser.evaluate(
200
205
  (objects) => {
201
206
  function visit(obj) {
@@ -221,12 +226,11 @@ async function handleGetSnapshot(args, browser, session, _config) {
221
226
  visit(obj);
222
227
  }
223
228
  },
224
- vslDocument.objects
229
+ currentDoc.objects
225
230
  );
226
- session.setSnapshot(vslDocument);
227
231
  return {
228
232
  status: "success",
229
- data: vslDocument
233
+ data: result
230
234
  };
231
235
  } catch (error) {
232
236
  return {
@@ -538,15 +542,15 @@ async function handleGetVisual(args, browser) {
538
542
  try {
539
543
  if (!args.element_id || typeof args.element_id !== "string") {
540
544
  return {
541
- status: "error",
542
- error: "element_id is required"
545
+ content: [{ type: "text", text: "Error: element_id is required" }],
546
+ isError: true
543
547
  };
544
548
  }
545
549
  const isAvailable = await browser.isAvailable();
546
550
  if (!isAvailable) {
547
551
  return {
548
- status: "error",
549
- error: "Playwright is not installed. Install it with: npm install playwright"
552
+ content: [{ type: "text", text: "Error: Playwright is not installed. Install it with: npm install playwright" }],
553
+ isError: true
550
554
  };
551
555
  }
552
556
  if (args.element_id === "root_0") {
@@ -554,12 +558,10 @@ async function handleGetVisual(args, browser) {
554
558
  const screenshotBuffer2 = await page2.screenshot({ type: "png", fullPage: false });
555
559
  const base64Image2 = screenshotBuffer2.toString("base64");
556
560
  return {
557
- status: "success",
558
- data: {
559
- element_id: args.element_id,
560
- image: base64Image2,
561
- mediaType: "image/png"
562
- }
561
+ content: [
562
+ { type: "image", data: base64Image2, mimeType: "image/png" },
563
+ { type: "text", text: `Full page screenshot (${args.element_id})` }
564
+ ]
563
565
  };
564
566
  }
565
567
  const selector = `[data-vsl-id="${args.element_id}"], #${args.element_id}, [id="${args.element_id}"]`;
@@ -568,8 +570,8 @@ async function handleGetVisual(args, browser) {
568
570
  }, selector);
569
571
  if (!elementExists) {
570
572
  return {
571
- status: "error",
572
- error: `Element not found: ${args.element_id}. Note: vsl_get_visual works with IDs from vsl_get_snapshot (browser DOM), not vsl_read_page (semantic IDs).`
573
+ content: [{ type: "text", text: `Error: Element not found: ${args.element_id}. Note: vsl_get_visual works with IDs from vsl_get_snapshot (browser DOM), not vsl_read_page (semantic IDs).` }],
574
+ isError: true
573
575
  };
574
576
  }
575
577
  const page = await browser.getPage();
@@ -581,8 +583,8 @@ async function handleGetVisual(args, browser) {
581
583
  }, selector);
582
584
  if (!rect) {
583
585
  return {
584
- status: "error",
585
- error: `Could not get bounding box for element: ${args.element_id}`
586
+ content: [{ type: "text", text: `Error: Could not get bounding box for element: ${args.element_id}` }],
587
+ isError: true
586
588
  };
587
589
  }
588
590
  const screenshotBuffer = await page.screenshot({
@@ -591,17 +593,15 @@ async function handleGetVisual(args, browser) {
591
593
  });
592
594
  const base64Image = screenshotBuffer.toString("base64");
593
595
  return {
594
- status: "success",
595
- data: {
596
- element_id: args.element_id,
597
- image: base64Image,
598
- mediaType: "image/png"
599
- }
596
+ content: [
597
+ { type: "image", data: base64Image, mimeType: "image/png" },
598
+ { type: "text", text: `Screenshot of element: ${args.element_id}` }
599
+ ]
600
600
  };
601
601
  } catch (error) {
602
602
  return {
603
- status: "error",
604
- error: `vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}`
603
+ content: [{ type: "text", text: `Error: vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}` }],
604
+ isError: true
605
605
  };
606
606
  }
607
607
  }
@@ -941,47 +941,66 @@ async function handleReadPage(args, browser, session, _config) {
941
941
  }
942
942
  };
943
943
  } catch (error) {
944
+ const stack = error instanceof Error ? error.stack : String(error);
945
+ console.error("vsl_read_page error:", stack);
944
946
  return {
945
947
  status: "error",
946
- error: `vsl_read_page failed: ${error instanceof Error ? error.message : String(error)}`
948
+ error: `vsl_read_page failed: ${error instanceof Error ? error.message : String(error)}
949
+ Stack: ${stack}`
947
950
  };
948
951
  }
949
952
  }
950
953
  async function extractVslFromPage(browser) {
951
- const domTree = await browser.evaluate(() => {
952
- const extractElement = (el) => {
953
- const rect = el.getBoundingClientRect();
954
- const computedStyle = window.getComputedStyle(el);
955
- return {
956
- tag: el.tagName.toLowerCase(),
957
- id: el.id || void 0,
958
- className: el.className || void 0,
959
- text: el.textContent?.trim().substring(0, 100) || void 0,
960
- rect: {
961
- x: rect.x,
962
- y: rect.y,
963
- width: rect.width,
964
- height: rect.height
965
- },
966
- role: el.getAttribute("role") || void 0,
967
- ariaLabel: el.getAttribute("aria-label") || void 0,
968
- ariaHidden: el.getAttribute("aria-hidden") || void 0,
969
- display: computedStyle.display,
970
- visibility: computedStyle.visibility,
971
- children: Array.from(el.children).filter((child) => {
972
- const style = window.getComputedStyle(child);
973
- return style.display !== "none" && style.visibility !== "hidden";
974
- }).map(extractElement)
954
+ let domTree = null;
955
+ try {
956
+ domTree = await browser.evaluate(() => {
957
+ const extractElement = (el) => {
958
+ const rect2 = el.getBoundingClientRect();
959
+ const computedStyle = window.getComputedStyle(el);
960
+ return {
961
+ tag: el.tagName.toLowerCase(),
962
+ id: el.id || void 0,
963
+ className: el.className || void 0,
964
+ text: el.textContent?.trim().substring(0, 100) || void 0,
965
+ rect: {
966
+ x: rect2.x,
967
+ y: rect2.y,
968
+ width: rect2.width,
969
+ height: rect2.height
970
+ },
971
+ role: el.getAttribute("role") || void 0,
972
+ ariaLabel: el.getAttribute("aria-label") || void 0,
973
+ ariaHidden: el.getAttribute("aria-hidden") || void 0,
974
+ display: computedStyle.display,
975
+ visibility: computedStyle.visibility,
976
+ children: Array.from(el.children).filter((child) => {
977
+ const style = window.getComputedStyle(child);
978
+ return style.display !== "none" && style.visibility !== "hidden";
979
+ }).map(extractElement)
980
+ };
975
981
  };
982
+ return extractElement(document.documentElement);
983
+ });
984
+ } catch (error) {
985
+ console.error("extractVslFromPage: browser.evaluate failed:", error);
986
+ domTree = null;
987
+ }
988
+ if (!domTree || typeof domTree !== "object") {
989
+ domTree = {
990
+ tag: "html",
991
+ rect: { x: 0, y: 0, width: 1280, height: 800 },
992
+ children: []
976
993
  };
977
- return extractElement(document.documentElement);
978
- });
994
+ }
995
+ const rect = domTree.rect;
996
+ const viewportWidth = rect?.width ?? 1280;
997
+ const viewportHeight = rect?.height ?? 800;
979
998
  return {
980
999
  vsl_version: "1.0.0",
981
1000
  canvas: {
982
1001
  viewport: {
983
- width: domTree.rect ? domTree.rect.width : 1280,
984
- height: domTree.rect ? domTree.rect.height : 800,
1002
+ width: viewportWidth,
1003
+ height: viewportHeight,
985
1004
  unit: "px"
986
1005
  },
987
1006
  background: "#ffffff",
@@ -1262,7 +1281,7 @@ var VSL_TOOLS = [
1262
1281
  },
1263
1282
  {
1264
1283
  name: "vsl_read_page",
1265
- description: "\u0413\u0438\u0431\u0440\u0438\u0434\u043D\u043E\u0435 \u0447\u0442\u0435\u043D\u0438\u0435 \u0432\u0435\u0431-\u0441\u0442\u0440\u0430\u043D\u0438\u0446. mode=auto (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E): \u0441\u0442\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0447\u0438\u0442\u0430\u044E\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 HTTP (\u0431\u044B\u0441\u0442\u0440\u043E), SPA \u0440\u0435\u043D\u0434\u0435\u0440\u044F\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. mode=http: \u0442\u043E\u043B\u044C\u043A\u043E HTTP (\u0431\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0430). mode=render: \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0435\u043D\u0434\u0435\u0440\u0438\u0442\u044C \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. readable=true: \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0435\u0442 \u0448\u0443\u043C (\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F, \u0444\u0443\u0442\u0435\u0440\u044B, cookie-\u0431\u0430\u043D\u043D\u0435\u0440\u044B) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430. \u041F\u0440\u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u044B\u0445 \u0432\u044B\u0437\u043E\u0432\u0430\u0445 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff (\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F), \u0430 \u043D\u0435 \u043F\u043E\u043B\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442. \u041F\u0440\u0438\u043C\u0435\u0440: {url:https://example.com, mode:auto, readable:true}.",
1284
+ description: '\u0427\u0442\u0435\u043D\u0438\u0435 \u0432\u0435\u0431-\u0441\u0442\u0440\u0430\u043D\u0438\u0446. \u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u0435\u0442 \u0441\u0442\u0440\u0430\u0442\u0435\u0433\u0438\u044E: \u0441\u0442\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0447\u0438\u0442\u0430\u044E\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 HTTP (\u0431\u044B\u0441\u0442\u0440\u043E), SPA \u0440\u0435\u043D\u0434\u0435\u0440\u044F\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. readable=true \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0435\u0442 \u0448\u0443\u043C (\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F, \u0444\u0443\u0442\u0435\u0440\u044B, cookie-\u0431\u0430\u043D\u043D\u0435\u0440\u044B) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430. \u041F\u0440\u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u044B\u0445 \u0432\u044B\u0437\u043E\u0432\u0430\u0445 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff (\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F), \u0430 \u043D\u0435 \u043F\u043E\u043B\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442. \u041F\u0440\u0438\u043C\u0435\u0440: {url:"https://example.com", readable:true}.',
1266
1285
  inputSchema: {
1267
1286
  type: "object",
1268
1287
  properties: {
@@ -1270,11 +1289,6 @@ var VSL_TOOLS = [
1270
1289
  type: "string",
1271
1290
  description: "URL \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F"
1272
1291
  },
1273
- mode: {
1274
- type: "string",
1275
- enum: ["auto", "http", "render"],
1276
- description: "\u0420\u0435\u0436\u0438\u043C \u0447\u0442\u0435\u043D\u0438\u044F: auto (\u0430\u0432\u0442\u043E-\u0434\u0435\u0442\u0435\u043A\u0442), http (\u0442\u043E\u043B\u044C\u043A\u043E HTTP), render (\u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0435\u043D\u0434\u0435\u0440\u0438\u0442\u044C)"
1277
- },
1278
1292
  readable: {
1279
1293
  type: "boolean",
1280
1294
  description: "Readable-\u0440\u0435\u0436\u0438\u043C: \u0444\u0438\u043B\u044C\u0442\u0440\u0430\u0446\u0438\u044F \u0448\u0443\u043C\u0430 (nav, footer, cookie banners) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430"
@@ -1358,8 +1372,7 @@ function registerTools(server, config, browser, session) {
1358
1372
  result = await handleClearCache(session);
1359
1373
  break;
1360
1374
  case "vsl_get_visual":
1361
- result = await handleGetVisual(args, browser);
1362
- break;
1375
+ return await handleGetVisual(args, browser);
1363
1376
  case "vsl_read_page":
1364
1377
  result = await handleReadPage(args, browser, session, config);
1365
1378
  break;
@@ -1552,7 +1565,7 @@ var BrowserManager = class {
1552
1565
  const pw = await this.loadPlaywright();
1553
1566
  if (!pw) {
1554
1567
  throw new Error(
1555
- 'Playwright is not installed. Install it with: npm install playwright\nOr use vsl_read_page with mode="http" for static pages (no browser required).'
1568
+ "Playwright is not installed. Install it with: npm install playwright"
1556
1569
  );
1557
1570
  }
1558
1571
  this.browser = await pw.chromium.launch({
@@ -1781,11 +1794,14 @@ var BrowserManager = class {
1781
1794
  };
1782
1795
 
1783
1796
  // src/session/serverSession.ts
1784
- import { diffVslDocuments } from "@thinkingos/vsl-sdk";
1797
+ import { VslSnapshotSession, diffVslDocuments } from "@thinkingos/vsl-sdk";
1785
1798
  var ServerSession = class {
1786
- currentSnapshot = null;
1787
- previousSnapshot = null;
1799
+ sdkSession;
1800
+ previousDocument = null;
1788
1801
  onSnapshotChange = null;
1802
+ constructor() {
1803
+ this.sdkSession = new VslSnapshotSession();
1804
+ }
1789
1805
  /**
1790
1806
  * Регистрирует callback для уведомлений об изменении snapshot.
1791
1807
  * Вызывается при каждом вызове setSnapshot().
@@ -1794,49 +1810,86 @@ var ServerSession = class {
1794
1810
  this.onSnapshotChange = callback;
1795
1811
  }
1796
1812
  /**
1797
- * Устанавливает новый snapshot.
1798
- * Предыдущий snapshot сохраняется для вычисления diff.
1799
- * Вызывает onSnapshotChange callback если зарегистрирован.
1813
+ * Устанавливает новый snapshot напрямую (VslDocument).
1814
+ * Для обратной совместимости с кодом, который уже имеет готовый VslDocument.
1815
+ * Предпочтительный способ: snapshotFromElements() для нового pipeline.
1800
1816
  */
1801
1817
  setSnapshot(doc) {
1802
- this.previousSnapshot = this.currentSnapshot;
1803
- this.currentSnapshot = doc;
1818
+ const currentDoc = this.sdkSession.getLastDocument();
1819
+ if (currentDoc) {
1820
+ this.previousDocument = currentDoc;
1821
+ }
1822
+ this.sdkSession.clear();
1823
+ this.sdkSession.lastDocument = doc;
1824
+ this.sdkSession.lastUrl = doc.canvas.url ?? null;
1825
+ this.sdkSession.lastViewport = {
1826
+ width: doc.canvas.viewport.width,
1827
+ height: doc.canvas.viewport.height
1828
+ };
1829
+ this.sdkSession.version = 1;
1804
1830
  if (this.onSnapshotChange) {
1805
1831
  this.onSnapshotChange();
1806
1832
  }
1807
1833
  }
1808
1834
  /**
1809
- * Возвращает текущий snapshot.
1835
+ * Делает snapshot из pre-extracted elements через SDK pipeline.
1836
+ * Это ПРЕДПОЧТИТЕЛЬНЫЙ способ — использует полный pipeline SDK:
1837
+ * segmentTree → buildVslDocument → cache → diff.
1838
+ */
1839
+ snapshotFromElements(extractedElements, input) {
1840
+ const result = this.sdkSession.snapshotFromElements(
1841
+ extractedElements,
1842
+ input
1843
+ );
1844
+ if (this.onSnapshotChange) {
1845
+ this.onSnapshotChange();
1846
+ }
1847
+ return result;
1848
+ }
1849
+ /**
1850
+ * Возвращает текущий snapshot (последний полный документ).
1810
1851
  * @throws Error если snapshot не установлен
1811
1852
  */
1812
1853
  getSnapshot() {
1813
- if (!this.currentSnapshot) {
1854
+ const doc = this.sdkSession.getLastDocument();
1855
+ if (!doc) {
1814
1856
  throw new Error("No snapshot available. Call vsl_get_snapshot first.");
1815
1857
  }
1816
- return this.currentSnapshot;
1858
+ return doc;
1817
1859
  }
1818
1860
  /**
1819
1861
  * Проверяет, есть ли текущий snapshot.
1820
1862
  */
1821
1863
  hasSnapshot() {
1822
- return this.currentSnapshot !== null;
1864
+ return this.sdkSession.getLastDocument() !== null;
1823
1865
  }
1824
1866
  /**
1825
1867
  * Вычисляет diff между текущим и предыдущим snapshot.
1868
+ * Использует SDK функцию diffVslDocuments.
1826
1869
  * @returns VslDiff или null если нет предыдущего snapshot
1827
1870
  */
1828
1871
  getDiff() {
1829
- if (!this.currentSnapshot || !this.previousSnapshot) {
1872
+ const currentDoc = this.sdkSession.getLastDocument();
1873
+ if (!currentDoc || !this.previousDocument) {
1830
1874
  return null;
1831
1875
  }
1832
- return diffVslDocuments(this.previousSnapshot, this.currentSnapshot, { diffVersion: 2, baseVersion: 1 });
1876
+ return diffVslDocuments(this.previousDocument, currentDoc, {
1877
+ diffVersion: this.sdkSession.getVersion() + 1,
1878
+ baseVersion: this.sdkSession.getVersion()
1879
+ });
1833
1880
  }
1834
1881
  /**
1835
1882
  * Сбрасывает сессию (кэш).
1836
1883
  */
1837
1884
  clear() {
1838
- this.currentSnapshot = null;
1839
- this.previousSnapshot = null;
1885
+ this.sdkSession.clear();
1886
+ }
1887
+ /**
1888
+ * Возвращает базовую VslSnapshotSession из SDK.
1889
+ * Для продвинутого использования (прямой доступ к SDK pipeline).
1890
+ */
1891
+ getSession() {
1892
+ return this.sdkSession;
1840
1893
  }
1841
1894
  };
1842
1895