@iwsdk/vite-plugin-dev 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/dist/index.js ADDED
@@ -0,0 +1,1145 @@
1
+ import { spawn, execFile } from 'child_process';
2
+ import { randomUUID } from 'crypto';
3
+ import * as fs from 'fs';
4
+ import { existsSync, readFileSync } from 'fs';
5
+ import { readFile, mkdir, writeFile, unlink } from 'fs/promises';
6
+ import * as path from 'path';
7
+ import { WebSocketServer } from 'ws';
8
+ import * as os from 'os';
9
+ import { chromium } from 'playwright';
10
+ import sharp from 'sharp';
11
+ import { fileURLToPath } from 'url';
12
+
13
+ /**
14
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
15
+ *
16
+ * This source code is licensed under the MIT license found in the
17
+ * LICENSE file in the root directory of this source tree.
18
+ */
19
+ const MAX_LOGS = 1000;
20
+ /** Map Playwright console message types to our LogLevel. */
21
+ const PLAYWRIGHT_TYPE_MAP = {
22
+ log: 'log',
23
+ info: 'info',
24
+ warning: 'warn',
25
+ error: 'error',
26
+ debug: 'debug',
27
+ trace: 'trace',
28
+ assert: 'error',
29
+ };
30
+ /**
31
+ * Server-side console capture that accumulates Playwright console events.
32
+ */
33
+ class ServerSideConsoleCapture {
34
+ constructor() {
35
+ this.logs = [];
36
+ }
37
+ add(level, message) {
38
+ // Log compaction: if the last entry has the same level + message,
39
+ // increment repeatCount instead of adding a new entry.
40
+ const last = this.logs[this.logs.length - 1];
41
+ if (last && last.level === level && last.message === message) {
42
+ last.repeatCount = (last.repeatCount ?? 1) + 1;
43
+ last.timestamp = Date.now();
44
+ return;
45
+ }
46
+ this.logs.push({
47
+ timestamp: Date.now(),
48
+ level,
49
+ message,
50
+ args: [message],
51
+ });
52
+ if (this.logs.length > MAX_LOGS) {
53
+ this.logs.shift();
54
+ }
55
+ }
56
+ query(options = {}) {
57
+ let result = [...this.logs];
58
+ if (options.level) {
59
+ const levels = Array.isArray(options.level)
60
+ ? options.level
61
+ : [options.level];
62
+ if (levels.length > 0) {
63
+ result = result.filter((log) => levels.includes(log.level));
64
+ }
65
+ }
66
+ if (options.since) {
67
+ result = result.filter((log) => log.timestamp >= options.since);
68
+ }
69
+ if (options.until) {
70
+ result = result.filter((log) => log.timestamp <= options.until);
71
+ }
72
+ if (options.pattern) {
73
+ const regex = new RegExp(options.pattern, 'i');
74
+ result = result.filter((log) => regex.test(log.message));
75
+ }
76
+ if (options.count && options.count > 0) {
77
+ result = result.slice(-options.count);
78
+ }
79
+ return result;
80
+ }
81
+ }
82
+ let chromiumInstalled = false;
83
+ let installPromise = null;
84
+ /**
85
+ * Verify the Chromium binary exists and install it automatically if missing.
86
+ * Uses a Promise guard so concurrent callers share one install attempt.
87
+ * On install failure the flag stays unset so the next retry can try again.
88
+ */
89
+ async function ensureChromiumInstalled() {
90
+ if (chromiumInstalled)
91
+ return;
92
+ if (installPromise)
93
+ return installPromise;
94
+ const execPath = chromium.executablePath();
95
+ if (fs.existsSync(execPath)) {
96
+ chromiumInstalled = true;
97
+ return;
98
+ }
99
+ installPromise = doChromiumInstall().finally(() => {
100
+ installPromise = null;
101
+ });
102
+ return installPromise;
103
+ }
104
+ async function doChromiumInstall() {
105
+ console.log('\nšŸ”§ IWSDK: Chromium browser not found. Installing (first time only)...\n');
106
+ await new Promise((resolve, reject) => {
107
+ const child = spawn('npx', ['playwright', 'install', 'chromium'], {
108
+ stdio: 'inherit',
109
+ shell: true,
110
+ });
111
+ child.on('close', (code) => {
112
+ if (code === 0) {
113
+ chromiumInstalled = true;
114
+ console.log('\nāœ… IWSDK: Chromium installed successfully.\n');
115
+ resolve();
116
+ }
117
+ else {
118
+ reject(new Error(`Chromium installation failed (exit code ${code}). ` +
119
+ 'Try running manually: npx playwright install chromium'));
120
+ }
121
+ });
122
+ child.on('error', (err) => {
123
+ reject(new Error(`Failed to start Chromium installer: ${err.message}. ` +
124
+ 'Try running manually: npx playwright install chromium'));
125
+ });
126
+ });
127
+ }
128
+ async function launchManagedBrowser(url, headless, verbose, viewport = null, screenshotSize = {
129
+ width: 800,
130
+ height: 800,
131
+ }) {
132
+ await ensureChromiumInstalled();
133
+ // Select GPU backend based on platform
134
+ const angleBackend = os.platform() === 'darwin'
135
+ ? 'metal'
136
+ : os.platform() === 'win32'
137
+ ? 'd3d11'
138
+ : 'gl';
139
+ const browser = await chromium.launch({
140
+ headless,
141
+ args: [
142
+ '--enable-webgl', // Ensure WebGL is available
143
+ '--use-gl=angle', // Use ANGLE for WebGL
144
+ `--use-angle=${angleBackend}`, // Platform-specific GPU backend
145
+ '--disable-background-timer-throttling', // No rAF throttling
146
+ '--disable-renderer-backgrounding',
147
+ ],
148
+ });
149
+ const context = await browser.newContext({
150
+ ignoreHTTPSErrors: true, // Accept self-signed certs (e.g. from mkcert)
151
+ viewport, // null = freely resizable; { width, height } = fixed viewport
152
+ });
153
+ const page = await context.newPage();
154
+ // Server-side console capture — accumulates logs from Playwright via CDP
155
+ const consoleCapture = new ServerSideConsoleCapture();
156
+ page.on('console', (msg) => {
157
+ const type = msg.type();
158
+ const text = msg.text();
159
+ const level = PLAYWRIGHT_TYPE_MAP[type];
160
+ // Accumulate into server-side buffer
161
+ if (level) {
162
+ consoleCapture.add(level, text);
163
+ }
164
+ // Also forward to Node console for debugging
165
+ if (type === 'error') {
166
+ console.error('[browser]', text);
167
+ }
168
+ else if (verbose) {
169
+ console.log(`[browser:${type}]`, text);
170
+ }
171
+ });
172
+ // Capture uncaught page errors (with full stack traces)
173
+ page.on('pageerror', (err) => {
174
+ // err.stack already includes "ErrorName: message" as its first line
175
+ const text = err.stack || (err.name ? `${err.name}: ${err.message}` : err.message);
176
+ consoleCapture.add('error', `[uncaught] ${text}`);
177
+ console.error('[browser:pageerror]', text);
178
+ });
179
+ // Capture unhandled promise rejections by re-emitting as console.error
180
+ // (which Playwright's page.on('console') already captures via CDP)
181
+ await page.addInitScript(() => {
182
+ window.addEventListener('unhandledrejection', (event) => {
183
+ const reason = event.reason;
184
+ // reason.stack already includes "ErrorName: message" as its first line
185
+ const text = reason instanceof Error
186
+ ? reason.stack || `${reason.name}: ${reason.message}`
187
+ : String(reason);
188
+ console.error(`[unhandledrejection] ${text}`);
189
+ });
190
+ });
191
+ // Mark this tab as the Playwright-managed tab. The injection template
192
+ // checks this flag and only initializes the MCP WebSocket client when
193
+ // present, so manually-opened browser tabs are not remote-controlled.
194
+ await page.addInitScript(() => {
195
+ window.__IWER_MCP_MANAGED = true;
196
+ });
197
+ await page.goto(url, { waitUntil: 'networkidle' });
198
+ // Wait for IWER to inject and XR device to be available
199
+ await page.waitForFunction(() => window.IWER_DEVICE !== undefined, {
200
+ timeout: 15000,
201
+ });
202
+ if (verbose) {
203
+ console.log(headless
204
+ ? 'šŸ–„ļø IWSDK: Headless browser launched'
205
+ : 'šŸ–„ļø IWSDK: Browser launched');
206
+ }
207
+ // Track intentional vs unexpected closure
208
+ let intentionalClose = false;
209
+ let closeCallback = null;
210
+ let closeFired = false;
211
+ const fireCloseCallback = () => {
212
+ if (!intentionalClose && closeCallback && !closeFired) {
213
+ closeFired = true;
214
+ closeCallback();
215
+ }
216
+ };
217
+ page.on('close', fireCloseCallback);
218
+ browser.on('disconnected', fireCloseCallback);
219
+ return {
220
+ close: async () => {
221
+ intentionalClose = true;
222
+ try {
223
+ await context.close();
224
+ }
225
+ finally {
226
+ await browser.close();
227
+ }
228
+ },
229
+ page,
230
+ queryLogs: (options) => consoleCapture.query(options),
231
+ screenshot: async () => {
232
+ const raw = await page.screenshot({ type: 'png' });
233
+ // In non-agent modes (viewport is null / freely resizable), downscale
234
+ // the screenshot to fit within screenshotSize bounds.
235
+ if (viewport === null) {
236
+ return sharp(raw)
237
+ .resize(screenshotSize.width, screenshotSize.height, {
238
+ fit: 'inside',
239
+ withoutEnlargement: true,
240
+ })
241
+ .png()
242
+ .toBuffer();
243
+ }
244
+ return raw;
245
+ },
246
+ onClose: (callback) => {
247
+ closeCallback = callback;
248
+ },
249
+ isClosed: () => page.isClosed(),
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
255
+ *
256
+ * This source code is licensed under the MIT license found in the
257
+ * LICENSE file in the root directory of this source tree.
258
+ */
259
+ /**
260
+ * hzdb telemetry integration for IWSDK.
261
+ *
262
+ * Reports MCP tool calls, session lifecycle, and errors through hzdb's
263
+ * DeveloperTelemetry pipeline via the `hzdb xxiwsdk` subcommand.
264
+ * All calls are fire-and-forget — telemetry never blocks or breaks the tool.
265
+ *
266
+ * Uses `npx @meta-quest/hzdb` so we don't need to resolve the binary path.
267
+ * If hzdb is not installed, npx fails and the error is silently swallowed.
268
+ */
269
+ function hzdbTelemetry(args, clientVersion) {
270
+ const globalArgs = ['@meta-quest/hzdb', 'xxiwsdk'];
271
+ if (clientVersion) {
272
+ globalArgs.push('--client-version', clientVersion);
273
+ }
274
+ const child = execFile('npx', [...globalArgs, ...args], {
275
+ timeout: 5000,
276
+ shell: true,
277
+ });
278
+ child.on('error', () => { });
279
+ }
280
+ function reportSessionStart(sessionId, opts) {
281
+ const args = ['session-start', '--session-id', sessionId];
282
+ if (opts?.iwsdkVersion) {
283
+ args.push('--iwsdk-version', opts.iwsdkVersion);
284
+ }
285
+ if (opts?.device) {
286
+ args.push('--device', opts.device);
287
+ }
288
+ if (opts?.port) {
289
+ args.push('--port', String(opts.port));
290
+ }
291
+ hzdbTelemetry(args, opts?.clientVersion);
292
+ }
293
+ function reportSessionEnd(sessionId, opts) {
294
+ const args = ['session-end', '--session-id', sessionId];
295
+ if (opts?.durationMs != null) {
296
+ args.push('--duration-ms', String(Math.round(opts.durationMs)));
297
+ }
298
+ if (opts?.reason) {
299
+ args.push('--reason', opts.reason);
300
+ }
301
+ hzdbTelemetry(args, opts?.clientVersion);
302
+ }
303
+
304
+ /**
305
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
306
+ *
307
+ * This source code is licensed under the MIT license found in the
308
+ * LICENSE file in the root directory of this source tree.
309
+ */
310
+ // Get __dirname equivalent for ES modules
311
+ const __filename$1 = fileURLToPath(import.meta.url);
312
+ const __dirname$1 = path.dirname(__filename$1);
313
+ /**
314
+ * Load and customize the pre-built injection bundle
315
+ */
316
+ async function buildInjectionBundle(options) {
317
+ try {
318
+ if (options.verbose) {
319
+ console.log('šŸ”„ Loading pre-built IWSDK injection bundle...');
320
+ }
321
+ // Load the pre-built injection bundle
322
+ const bundlePath = path.resolve(__dirname$1, 'injection-bundle.js');
323
+ let bundleCode = await readFile(bundlePath, 'utf8');
324
+ // Create the configuration object to inject
325
+ const config = {
326
+ device: options.device,
327
+ activation: options.activation instanceof RegExp
328
+ ? `/${options.activation.source}/`
329
+ : options.activation,
330
+ verbose: options.verbose,
331
+ sem: options.sem || null,
332
+ ai: options.ai || null,
333
+ userAgentException: options.userAgentException instanceof RegExp
334
+ ? `/${options.userAgentException.source}/`
335
+ : options.userAgentException,
336
+ };
337
+ // Replace the CONFIG token with actual configuration
338
+ const configReplacement = JSON.stringify(config, null, 2);
339
+ bundleCode = bundleCode.replace('"__IWSDK_DEV_CONFIG__"', configReplacement);
340
+ const size = Buffer.byteLength(bundleCode, 'utf8');
341
+ if (options.verbose) {
342
+ console.log(`āœ… IWSDK injection bundle loaded and configured (${(size / 1024).toFixed(1)}KB)`);
343
+ }
344
+ return { code: bundleCode, size };
345
+ }
346
+ catch (error) {
347
+ console.error('āŒ Failed to load IWSDK injection bundle:', error);
348
+ console.error('Make sure to run "pnpm build:injection" first to create the pre-built bundle.');
349
+ throw error;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
355
+ *
356
+ * This source code is licensed under the MIT license found in the
357
+ * LICENSE file in the root directory of this source tree.
358
+ */
359
+ /** WebSocket OPEN readyState constant */
360
+ const WS_OPEN = 1;
361
+ /**
362
+ * Create a relay handler that implements first-response-wins message routing.
363
+ *
364
+ * When multiple browser tabs are connected, a request from the MCP server is
365
+ * broadcast to all tabs. Each tab processes it and responds. The relay
366
+ * forwards only the FIRST response for each request ID and silently drops
367
+ * duplicates.
368
+ */
369
+ function createRelayHandler(options) {
370
+ const verbose = options?.verbose ?? false;
371
+ // Track pending request IDs for first-response-wins deduplication.
372
+ const pendingRelayRequests = new Map();
373
+ function onMessage(senderWs, data, clients) {
374
+ let parsed = null;
375
+ try {
376
+ parsed = JSON.parse(data);
377
+ }
378
+ catch {
379
+ // Not JSON — broadcast as-is for backward compatibility
380
+ }
381
+ if (parsed && typeof parsed.id === 'string') {
382
+ const isRequest = typeof parsed.method === 'string';
383
+ const isResponse = !parsed.method &&
384
+ (parsed.result !== undefined || parsed.error !== undefined);
385
+ if (isRequest) {
386
+ // Track this request for deduplication
387
+ pendingRelayRequests.set(parsed.id, {
388
+ timestamp: Date.now(),
389
+ sourceWs: senderWs,
390
+ });
391
+ // Broadcast request to all OTHER clients (all browser tabs)
392
+ clients.forEach((client) => {
393
+ if (client !== senderWs && client.readyState === WS_OPEN) {
394
+ client.send(data);
395
+ }
396
+ });
397
+ return;
398
+ }
399
+ if (isResponse) {
400
+ const pending = pendingRelayRequests.get(parsed.id);
401
+ if (pending) {
402
+ // First response wins — forward to the original requester
403
+ pendingRelayRequests.delete(parsed.id);
404
+ if (pending.sourceWs.readyState === WS_OPEN) {
405
+ pending.sourceWs.send(data);
406
+ }
407
+ if (verbose) {
408
+ console.log(`[MCP-IWER] Response for ${parsed.id} forwarded (first-wins)`);
409
+ }
410
+ }
411
+ else if (verbose) {
412
+ console.log(`[MCP-IWER] Duplicate response for ${parsed.id} dropped`);
413
+ }
414
+ return;
415
+ }
416
+ }
417
+ // Unknown message shape — broadcast for backward compatibility
418
+ clients.forEach((client) => {
419
+ if (client !== senderWs && client.readyState === WS_OPEN) {
420
+ client.send(data);
421
+ }
422
+ });
423
+ }
424
+ function pendingCount() {
425
+ return pendingRelayRequests.size;
426
+ }
427
+ function cleanStale(maxAgeMs) {
428
+ const now = Date.now();
429
+ for (const [id, entry] of pendingRelayRequests) {
430
+ if (now - entry.timestamp > maxAgeMs) {
431
+ pendingRelayRequests.delete(id);
432
+ }
433
+ }
434
+ }
435
+ return { onMessage, pendingCount, cleanStale };
436
+ }
437
+
438
+ /**
439
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
440
+ *
441
+ * This source code is licensed under the MIT license found in the
442
+ * LICENSE file in the root directory of this source tree.
443
+ */
444
+ const MCP_CONFIG_TARGETS = {
445
+ claude: { file: '.mcp.json', jsonKey: 'mcpServers', format: 'json' },
446
+ cursor: { file: '.cursor/mcp.json', jsonKey: 'mcpServers', format: 'json' },
447
+ copilot: { file: '.vscode/mcp.json', jsonKey: 'servers', format: 'json' },
448
+ codex: { file: '.codex/config.toml', jsonKey: null, format: 'toml' },
449
+ };
450
+ const TOML_BLOCK_START = '# --- IWER managed (do not edit) ---';
451
+ const TOML_BLOCK_END = '# --- end IWER managed ---';
452
+ /**
453
+ * Merge our server entries into an existing (or new) JSON config file.
454
+ * When `managedKeys` is provided, any key in that list that is NOT in
455
+ * `serverEntries` is removed — this prevents stale entries from surviving
456
+ * across config changes (e.g. uninstalling an optional MCP server).
457
+ * Returns true if the file was newly created.
458
+ */
459
+ async function mergeJsonConfig(filePath, serverEntries, jsonKey, managedKeys) {
460
+ let existing = {};
461
+ let created = false;
462
+ try {
463
+ const raw = await readFile(filePath, 'utf-8');
464
+ existing = JSON.parse(raw);
465
+ }
466
+ catch {
467
+ created = true;
468
+ }
469
+ const section = existing[jsonKey] ?? {};
470
+ if (managedKeys) {
471
+ for (const key of managedKeys) {
472
+ if (!(key in serverEntries)) {
473
+ delete section[key];
474
+ }
475
+ }
476
+ }
477
+ Object.assign(section, serverEntries);
478
+ existing[jsonKey] = section;
479
+ await mkdir(path.dirname(filePath), { recursive: true });
480
+ await writeFile(filePath, JSON.stringify(existing, null, 2) + '\n');
481
+ return created;
482
+ }
483
+ /**
484
+ * Remove our managed server keys from a JSON config file.
485
+ * If we originally created the file and the servers section is now empty
486
+ * with no other top-level keys, delete the file entirely.
487
+ *
488
+ * @internal Not called by the plugin at runtime (MCP configs are left in
489
+ * place on shutdown). Kept as a tested utility for potential external use.
490
+ */
491
+ async function unmergeJsonConfig(filePath, serverKeys, jsonKey, weCreatedFile) {
492
+ let raw;
493
+ try {
494
+ raw = await readFile(filePath, 'utf-8');
495
+ }
496
+ catch {
497
+ return; // file doesn't exist — no-op
498
+ }
499
+ let existing;
500
+ try {
501
+ existing = JSON.parse(raw);
502
+ }
503
+ catch {
504
+ return; // invalid JSON — leave it alone
505
+ }
506
+ const section = existing[jsonKey];
507
+ if (section) {
508
+ for (const key of serverKeys) {
509
+ delete section[key];
510
+ }
511
+ if (Object.keys(section).length === 0) {
512
+ delete existing[jsonKey];
513
+ }
514
+ }
515
+ if (weCreatedFile && Object.keys(existing).length === 0) {
516
+ try {
517
+ await unlink(filePath);
518
+ }
519
+ catch { }
520
+ }
521
+ else {
522
+ await writeFile(filePath, JSON.stringify(existing, null, 2) + '\n');
523
+ }
524
+ }
525
+ /**
526
+ * Merge our managed TOML block into an existing (or new) config file.
527
+ * Returns true if the file was newly created.
528
+ */
529
+ async function mergeTomlConfig(filePath, serverEntries) {
530
+ let existing = '';
531
+ let created = false;
532
+ try {
533
+ existing = await readFile(filePath, 'utf-8');
534
+ }
535
+ catch {
536
+ created = true;
537
+ }
538
+ // Remove any old managed block
539
+ const startIdx = existing.indexOf(TOML_BLOCK_START);
540
+ const endIdx = existing.indexOf(TOML_BLOCK_END);
541
+ if (startIdx !== -1 && endIdx !== -1 && startIdx < endIdx) {
542
+ existing =
543
+ existing.slice(0, startIdx).trimEnd() +
544
+ '\n' +
545
+ existing.slice(endIdx + TOML_BLOCK_END.length).trimStart();
546
+ existing = existing.trim();
547
+ }
548
+ // Build new managed block
549
+ const tomlLines = [TOML_BLOCK_START];
550
+ for (const [name, entry] of Object.entries(serverEntries)) {
551
+ tomlLines.push(`[mcp_servers.${name}]`);
552
+ tomlLines.push(`command = ${JSON.stringify(entry.command)}`);
553
+ tomlLines.push(`args = [${entry.args.map((a) => JSON.stringify(a)).join(', ')}]`);
554
+ tomlLines.push('');
555
+ }
556
+ tomlLines.push(TOML_BLOCK_END);
557
+ const newContent = existing
558
+ ? existing.trimEnd() + '\n\n' + tomlLines.join('\n') + '\n'
559
+ : tomlLines.join('\n') + '\n';
560
+ await mkdir(path.dirname(filePath), { recursive: true });
561
+ await writeFile(filePath, newContent);
562
+ return created;
563
+ }
564
+ /**
565
+ * Remove our managed TOML block from a config file.
566
+ * If we originally created the file and it's now effectively empty, delete it.
567
+ *
568
+ * @internal Not called by the plugin at runtime (MCP configs are left in
569
+ * place on shutdown). Kept as a tested utility for potential external use.
570
+ */
571
+ async function unmergeTomlConfig(filePath, weCreatedFile) {
572
+ let existing;
573
+ try {
574
+ existing = await readFile(filePath, 'utf-8');
575
+ }
576
+ catch {
577
+ return; // file doesn't exist — no-op
578
+ }
579
+ const startIdx = existing.indexOf(TOML_BLOCK_START);
580
+ const endIdx = existing.indexOf(TOML_BLOCK_END);
581
+ if (startIdx === -1 || endIdx === -1 || startIdx >= endIdx) {
582
+ // No managed block found — nothing to remove
583
+ if (weCreatedFile && existing.trim() === '') {
584
+ try {
585
+ await unlink(filePath);
586
+ }
587
+ catch { }
588
+ }
589
+ return;
590
+ }
591
+ const cleaned = existing.slice(0, startIdx).trimEnd() +
592
+ '\n' +
593
+ existing.slice(endIdx + TOML_BLOCK_END.length).trimStart();
594
+ const result = cleaned.trim();
595
+ if (weCreatedFile && result === '') {
596
+ try {
597
+ await unlink(filePath);
598
+ }
599
+ catch { }
600
+ }
601
+ else {
602
+ await writeFile(filePath, result + '\n');
603
+ }
604
+ }
605
+ /**
606
+ * Warm up the RAG MCP server by spawning it and waiting for initialization.
607
+ * This downloads the HuggingFace embedding model if not already cached.
608
+ * The process is killed after initialization completes.
609
+ */
610
+ function warmupRagMcp(ragMcpServerPath, verbose) {
611
+ if (!existsSync(ragMcpServerPath)) {
612
+ if (verbose) {
613
+ console.log('[RAG-MCP] Server not found, skipping warmup');
614
+ }
615
+ return;
616
+ }
617
+ console.log('šŸ“š RAG-MCP: Warming up (downloading model if needed)...');
618
+ const warmupProcess = spawn('node', [ragMcpServerPath], {
619
+ stdio: ['pipe', 'pipe', 'pipe'],
620
+ });
621
+ let initialized = false;
622
+ warmupProcess.stderr?.on('data', (data) => {
623
+ const output = data.toString();
624
+ if (verbose) {
625
+ // Print warmup progress
626
+ process.stderr.write(`[RAG-MCP Warmup] ${output}`);
627
+ }
628
+ // Check if initialization is complete
629
+ if (output.includes('IWSDK RAG MCP Server is ready')) {
630
+ initialized = true;
631
+ clearTimeout(warmupTimeout);
632
+ console.log('šŸ“š RAG-MCP: Model cached successfully');
633
+ warmupProcess.kill('SIGTERM');
634
+ }
635
+ });
636
+ warmupProcess.on('error', (error) => {
637
+ if (verbose) {
638
+ console.error('[RAG-MCP] Warmup error:', error.message);
639
+ }
640
+ });
641
+ warmupProcess.on('exit', (code) => {
642
+ if (!initialized && code !== 0 && verbose) {
643
+ console.warn(`[RAG-MCP] Warmup process exited with code ${code}`);
644
+ }
645
+ });
646
+ // Safety timeout - kill after 5 minutes if still running
647
+ const warmupTimeout = setTimeout(() => {
648
+ if (!initialized && !warmupProcess.killed) {
649
+ console.warn('[RAG-MCP] Warmup timeout, killing process');
650
+ warmupProcess.kill('SIGTERM');
651
+ }
652
+ }, 5 * 60 * 1000);
653
+ }
654
+ /**
655
+ * Derive internal headless / devUI / viewport settings from the AI mode.
656
+ */
657
+ const MODE_SETTINGS = {
658
+ agent: { headless: true, devUI: false, fixedViewport: true },
659
+ oversight: { headless: false, devUI: false, fixedViewport: false },
660
+ collaborate: { headless: false, devUI: true, fixedViewport: false },
661
+ };
662
+ /**
663
+ * Process and normalize plugin options with defaults
664
+ */
665
+ function processOptions(options = {}) {
666
+ const emulator = options.emulator ?? {};
667
+ const processed = {
668
+ device: emulator.device || 'metaQuest3',
669
+ injectOnBuild: emulator.injectOnBuild || false,
670
+ activation: emulator.activation || 'localhost',
671
+ verbose: options.verbose || false,
672
+ userAgentException: emulator.userAgentException || new RegExp('OculusBrowser'),
673
+ };
674
+ // Process SEM options from emulator.environment
675
+ if (emulator.environment) {
676
+ processed.sem = {
677
+ defaultScene: emulator.environment,
678
+ };
679
+ }
680
+ // AI is opt-in: omit `ai` to disable entirely
681
+ if (options.ai) {
682
+ const mode = options.ai.mode ?? 'agent';
683
+ const settings = MODE_SETTINGS[mode];
684
+ if (!settings) {
685
+ const valid = Object.keys(MODE_SETTINGS).join(', ');
686
+ throw new Error(`[IWSDK] Invalid ai.mode "${mode}". Valid modes: ${valid}`);
687
+ }
688
+ const ssInput = options.ai.screenshotSize;
689
+ const ssWidth = ssInput?.width;
690
+ const ssHeight = ssInput?.height;
691
+ const screenshotSize = {
692
+ width: ssWidth ?? ssHeight ?? 800,
693
+ height: ssHeight ?? ssWidth ?? 800,
694
+ };
695
+ processed.ai = {
696
+ mode,
697
+ tools: options.ai.tools ?? ['claude'],
698
+ headless: settings.headless,
699
+ devUI: settings.devUI,
700
+ viewport: settings.fixedViewport ? screenshotSize : null,
701
+ screenshotSize,
702
+ };
703
+ }
704
+ return processed;
705
+ }
706
+ /**
707
+ * Vite plugin for IWSDK development — XR emulation, AI agent tooling, and Playwright browser
708
+ */
709
+ function iwsdkDev(options = {}) {
710
+ const pluginOptions = processOptions(options);
711
+ let injectionBundle = null;
712
+ let config;
713
+ let mcpWss = null;
714
+ let mcpClients = null;
715
+ let managedBrowser = null;
716
+ const VIRTUAL_ID = '/@iwer-injection-runtime';
717
+ const RESOLVED_VIRTUAL_ID = '\0' + VIRTUAL_ID;
718
+ return {
719
+ name: 'iwsdk-dev',
720
+ config(userConfig) {
721
+ // In oversight/collaborate mode the Playwright window IS the visible
722
+ // browser, so suppress Vite's auto-open to avoid a duplicate tab.
723
+ if (pluginOptions.ai && !pluginOptions.ai.headless) {
724
+ if (userConfig.server) {
725
+ userConfig.server.open = false;
726
+ }
727
+ else {
728
+ userConfig.server = { open: false };
729
+ }
730
+ }
731
+ },
732
+ configResolved(resolvedConfig) {
733
+ config = resolvedConfig;
734
+ if (pluginOptions.verbose) {
735
+ console.log('šŸ”§ IWSDK Dev Configuration:');
736
+ console.log(` - Device: ${pluginOptions.device}`);
737
+ console.log(` - SEM: ${pluginOptions.sem ? 'enabled (' + pluginOptions.sem.defaultScene + ')' : 'disabled'}`);
738
+ console.log(` - AI: ${pluginOptions.ai ? `enabled (${pluginOptions.ai.mode} mode)` : 'disabled'}`);
739
+ console.log(` - Activation: ${pluginOptions.activation}`);
740
+ if (pluginOptions.userAgentException) {
741
+ console.log(' - UA exception: enabled');
742
+ }
743
+ console.log(` - Inject on build: ${pluginOptions.injectOnBuild}`);
744
+ }
745
+ },
746
+ configureServer(server) {
747
+ if (!pluginOptions.ai) {
748
+ return;
749
+ }
750
+ // Closure-scoped state for browser auto-recovery
751
+ let browserLaunchPromise = null;
752
+ let serverShuttingDown = false;
753
+ let browserUrl = '';
754
+ let consecutiveFailures = 0;
755
+ const MAX_LAUNCH_FAILURES = 3;
756
+ /**
757
+ * Launch (or re-launch) the Playwright-managed browser.
758
+ * Guards against concurrent launches via `browserLaunchPromise`.
759
+ * Stops retrying after MAX_LAUNCH_FAILURES consecutive failures.
760
+ */
761
+ const launchBrowser = () => {
762
+ if (browserLaunchPromise) {
763
+ return browserLaunchPromise;
764
+ }
765
+ browserLaunchPromise = (async () => {
766
+ try {
767
+ const browser = await launchManagedBrowser(browserUrl, pluginOptions.ai.headless, pluginOptions.verbose, pluginOptions.ai.viewport, pluginOptions.ai.screenshotSize);
768
+ managedBrowser = browser;
769
+ consecutiveFailures = 0;
770
+ // On unexpected close, mark as null. The browser will be
771
+ // relaunched lazily on the next MCP request via ensureBrowser().
772
+ browser.onClose(() => {
773
+ managedBrowser = null;
774
+ if (!serverShuttingDown) {
775
+ console.log('šŸ”„ IWSDK: Browser closed. Will relaunch on next MCP request.');
776
+ }
777
+ });
778
+ }
779
+ catch (error) {
780
+ consecutiveFailures++;
781
+ console.error('āŒ IWSDK: Failed to launch browser:', error);
782
+ if (consecutiveFailures >= MAX_LAUNCH_FAILURES) {
783
+ console.error(`āŒ IWSDK: ${MAX_LAUNCH_FAILURES} consecutive launch failures, giving up. ` +
784
+ 'Restart the dev server to retry.');
785
+ }
786
+ }
787
+ finally {
788
+ browserLaunchPromise = null;
789
+ }
790
+ })();
791
+ return browserLaunchPromise;
792
+ };
793
+ /**
794
+ * Return the current managed browser, re-launching if it was closed.
795
+ * `relaunched` is true when the browser was just freshly launched
796
+ * (meaning the previous page state was lost).
797
+ */
798
+ const ensureBrowser = async () => {
799
+ const current = managedBrowser;
800
+ if (current && !current.isClosed()) {
801
+ return { browser: current, relaunched: false };
802
+ }
803
+ managedBrowser = null;
804
+ if (consecutiveFailures >= MAX_LAUNCH_FAILURES) {
805
+ return { browser: null, relaunched: false };
806
+ }
807
+ await launchBrowser();
808
+ return { browser: managedBrowser, relaunched: managedBrowser !== null };
809
+ };
810
+ // Initialize WebSocket server and client tracking
811
+ mcpClients = new Set();
812
+ mcpWss = new WebSocketServer({ noServer: true });
813
+ // First-response-wins relay handler (extracted for testability)
814
+ const relay = createRelayHandler({
815
+ verbose: pluginOptions.verbose,
816
+ });
817
+ // Clean up stale entries every 60 seconds
818
+ const relayCleanupInterval = setInterval(() => {
819
+ relay.cleanStale(60000);
820
+ }, 60000);
821
+ relayCleanupInterval.unref();
822
+ mcpWss.on('connection', (ws) => {
823
+ mcpClients.add(ws);
824
+ if (pluginOptions.verbose) {
825
+ console.log('[IWSDK-MCP] Client connected');
826
+ }
827
+ ws.on('message', async (data) => {
828
+ const message = data.toString();
829
+ if (pluginOptions.verbose) {
830
+ console.log('[IWSDK-MCP] Message received:', message.substring(0, 100));
831
+ }
832
+ // Intercept server-side tools that use Playwright directly.
833
+ // These respond from the Node process without a browser round-trip.
834
+ let intercepted = false;
835
+ try {
836
+ const parsed = JSON.parse(message);
837
+ const BROWSER_RELAUNCHED_RESULT = {
838
+ status: 'browser_relaunched',
839
+ message: 'Browser was closed and has been relaunched. ' +
840
+ 'The page state has been reset — please retry your request.',
841
+ };
842
+ // Console logs: Playwright captures via CDP
843
+ if (parsed.method === 'get_console_logs' && parsed.id) {
844
+ intercepted = true;
845
+ const { browser, relaunched } = await ensureBrowser();
846
+ if (relaunched) {
847
+ ws.send(JSON.stringify({
848
+ id: parsed.id,
849
+ result: BROWSER_RELAUNCHED_RESULT,
850
+ }));
851
+ }
852
+ else {
853
+ const params = parsed.params ?? {};
854
+ if (!params.level) {
855
+ params.level = ['log', 'info', 'warn', 'error'];
856
+ }
857
+ const result = browser ? browser.queryLogs(params) : [];
858
+ ws.send(JSON.stringify({ id: parsed.id, result }));
859
+ }
860
+ }
861
+ // Screenshot: Playwright captures via CDP compositor
862
+ if (!intercepted && parsed.method === 'screenshot' && parsed.id) {
863
+ intercepted = true;
864
+ try {
865
+ const { browser, relaunched } = await ensureBrowser();
866
+ if (relaunched) {
867
+ ws.send(JSON.stringify({
868
+ id: parsed.id,
869
+ result: BROWSER_RELAUNCHED_RESULT,
870
+ }));
871
+ }
872
+ else if (browser) {
873
+ const buffer = await browser.screenshot();
874
+ const base64 = buffer.toString('base64');
875
+ ws.send(JSON.stringify({
876
+ id: parsed.id,
877
+ result: { imageData: base64, mimeType: 'image/png' },
878
+ }));
879
+ }
880
+ else {
881
+ ws.send(JSON.stringify({
882
+ id: parsed.id,
883
+ error: { code: -32000, message: 'Browser not ready' },
884
+ }));
885
+ }
886
+ }
887
+ catch (err) {
888
+ ws.send(JSON.stringify({
889
+ id: parsed.id,
890
+ error: {
891
+ code: -32000,
892
+ message: err instanceof Error ? err.message : String(err),
893
+ },
894
+ }));
895
+ }
896
+ }
897
+ }
898
+ catch {
899
+ // Not JSON — fall through to relay
900
+ }
901
+ if (!intercepted) {
902
+ relay.onMessage(ws, message, mcpClients);
903
+ }
904
+ });
905
+ ws.on('close', () => {
906
+ mcpClients.delete(ws);
907
+ if (pluginOptions.verbose) {
908
+ console.log('[IWSDK-MCP] Client disconnected');
909
+ }
910
+ });
911
+ ws.on('error', (error) => {
912
+ if (pluginOptions.verbose) {
913
+ console.error('[IWSDK-MCP] WebSocket error:', error);
914
+ }
915
+ });
916
+ });
917
+ // Set up WebSocket endpoint for MCP - handle upgrade requests
918
+ server.httpServer?.on('upgrade', (request, socket, head) => {
919
+ if (request.url !== '/__iwer_mcp') {
920
+ return;
921
+ }
922
+ if (pluginOptions.verbose) {
923
+ console.log('[IWSDK-MCP] WebSocket upgrade request received');
924
+ }
925
+ mcpWss.handleUpgrade(request, socket, head, (ws) => {
926
+ mcpWss.emit('connection', ws, request);
927
+ });
928
+ });
929
+ if (pluginOptions.verbose) {
930
+ console.log('šŸ”Œ IWSDK-MCP: WebSocket endpoint registered at /__iwer_mcp');
931
+ }
932
+ // Generate MCP config files for selected AI tools after server starts
933
+ // We wait for the 'listening' event to get the actual port (in case configured port was busy)
934
+ // Find the path to the MCP server script
935
+ // It's installed in node_modules/@iwsdk/vite-plugin-dev/dist/mcp-server.js
936
+ const mcpServerPath = path.join(config.root, 'node_modules', '@iwsdk', 'vite-plugin-dev', 'dist', 'mcp-server.js');
937
+ // Find the path to the RAG MCP server
938
+ const ragMcpServerPath = path.join(config.root, 'node_modules', '@felixtz', 'iwsdk-rag-mcp', 'dist', 'index.js');
939
+ // Check if hzdb is installed (for MCP config — telemetry uses npx and fails silently)
940
+ const hzdbInstalled = existsSync(path.join(config.root, 'node_modules', '@meta-quest', 'hzdb'));
941
+ // Resolve IWSDK version for telemetry attribution
942
+ let iwsdkVersion;
943
+ try {
944
+ const pluginPkgPath = path.join(config.root, 'node_modules', '@iwsdk', 'vite-plugin-dev', 'package.json');
945
+ const pluginPkg = JSON.parse(readFileSync(pluginPkgPath, 'utf-8'));
946
+ iwsdkVersion = pluginPkg.version;
947
+ }
948
+ catch {
949
+ // Version detection is best-effort
950
+ }
951
+ // Session tracking for telemetry
952
+ const sessionId = randomUUID();
953
+ const sessionStartTime = Date.now();
954
+ const writeMcpConfigs = async (actualPort) => {
955
+ const mcpServerArgs = [mcpServerPath, '--port', String(actualPort)];
956
+ if (iwsdkVersion) {
957
+ mcpServerArgs.push('--client-version', iwsdkVersion);
958
+ }
959
+ // Build the full set of all possible managed entries, then remove
960
+ // those whose packages aren't installed. The full key list is passed
961
+ // as managedKeys so mergeJsonConfig can clean up stale entries from
962
+ // previous runs where a package was present but has since been removed.
963
+ const serverEntries = {
964
+ 'iwsdk-dev-mcp': {
965
+ command: 'node',
966
+ args: mcpServerArgs,
967
+ },
968
+ 'iwsdk-rag-local': existsSync(ragMcpServerPath)
969
+ ? { command: 'node', args: [ragMcpServerPath] }
970
+ : undefined,
971
+ hzdb: hzdbInstalled
972
+ ? { command: 'npx', args: ['@meta-quest/hzdb', 'mcp', 'server'] }
973
+ : undefined,
974
+ };
975
+ const managedKeys = Object.keys(serverEntries);
976
+ const activeEntries = {};
977
+ for (const [key, value] of Object.entries(serverEntries)) {
978
+ if (value) {
979
+ activeEntries[key] = value;
980
+ }
981
+ }
982
+ const tools = pluginOptions.ai.tools;
983
+ const writes = [];
984
+ for (const tool of tools) {
985
+ const target = MCP_CONFIG_TARGETS[tool];
986
+ const filePath = path.join(config.root, target.file);
987
+ if (target.format === 'json') {
988
+ writes.push(mergeJsonConfig(filePath, activeEntries, target.jsonKey, managedKeys));
989
+ }
990
+ else {
991
+ writes.push(mergeTomlConfig(filePath, activeEntries));
992
+ }
993
+ }
994
+ const results = await Promise.allSettled(writes);
995
+ const failures = results.filter((r) => r.status === 'rejected');
996
+ if (failures.length > 0) {
997
+ for (const f of failures) {
998
+ console.error('[MCP] Config write failed:', f.reason);
999
+ }
1000
+ }
1001
+ else if (pluginOptions.verbose) {
1002
+ const toolNames = tools.join(', ');
1003
+ console.log(`šŸ“ MCP: Generated config files for [${toolNames}] (port: ${actualPort})`);
1004
+ }
1005
+ };
1006
+ // Wait for server to start listening to get the actual port
1007
+ server.httpServer?.on('listening', () => {
1008
+ const address = server.httpServer?.address();
1009
+ const actualPort = typeof address === 'object' && address
1010
+ ? address.port
1011
+ : server.config.server.port || 5173;
1012
+ writeMcpConfigs(actualPort);
1013
+ // Report session start to hzdb telemetry (fire-and-forget via npx)
1014
+ reportSessionStart(sessionId, {
1015
+ iwsdkVersion,
1016
+ clientVersion: iwsdkVersion,
1017
+ port: actualPort,
1018
+ });
1019
+ // Warm up RAG MCP server (downloads embedding model if needed)
1020
+ // This ensures the model is cached before Claude Code tries to use it
1021
+ warmupRagMcp(ragMcpServerPath, pluginOptions.verbose);
1022
+ // Launch Playwright-managed browser
1023
+ const protocol = server.config.server.https ? 'https' : 'http';
1024
+ browserUrl = `${protocol}://localhost:${actualPort}`;
1025
+ launchBrowser();
1026
+ });
1027
+ // Clean up WebSocket server and browser when Vite server closes.
1028
+ // MCP config files (.mcp.json, .cursor/mcp.json, etc.) are intentionally
1029
+ // left in place — they are harmless when the dev server isn't running and
1030
+ // will be overwritten with fresh values on the next `npm run dev`.
1031
+ server.httpServer?.on('close', () => {
1032
+ serverShuttingDown = true;
1033
+ reportSessionEnd(sessionId, {
1034
+ durationMs: Date.now() - sessionStartTime,
1035
+ reason: 'user_closed',
1036
+ clientVersion: iwsdkVersion,
1037
+ });
1038
+ if (mcpWss) {
1039
+ for (const client of mcpClients || []) {
1040
+ client.close();
1041
+ }
1042
+ mcpClients?.clear();
1043
+ mcpWss.close();
1044
+ mcpWss = null;
1045
+ }
1046
+ if (managedBrowser) {
1047
+ managedBrowser.close().catch(() => { });
1048
+ managedBrowser = null;
1049
+ }
1050
+ });
1051
+ },
1052
+ resolveId(id) {
1053
+ if (id === VIRTUAL_ID) {
1054
+ return RESOLVED_VIRTUAL_ID;
1055
+ }
1056
+ },
1057
+ load(id) {
1058
+ if (id === RESOLVED_VIRTUAL_ID) {
1059
+ if (!injectionBundle) {
1060
+ return 'console.warn("[IWSDK Dev] Runtime not available - injection bundle not loaded");';
1061
+ }
1062
+ return injectionBundle.code;
1063
+ }
1064
+ },
1065
+ async buildStart() {
1066
+ // Determine if we should generate injection script
1067
+ const shouldInject = config.command === 'serve' ||
1068
+ (config.command === 'build' && pluginOptions.injectOnBuild);
1069
+ if (!shouldInject) {
1070
+ if (pluginOptions.verbose && config.command === 'build') {
1071
+ console.log('ā­ļø IWSDK Dev: Skipping build injection (injectOnBuild: false)');
1072
+ }
1073
+ return;
1074
+ }
1075
+ try {
1076
+ if (pluginOptions.verbose) {
1077
+ console.log('šŸš€ IWSDK Dev: Starting injection bundle generation...');
1078
+ }
1079
+ injectionBundle = await buildInjectionBundle(pluginOptions);
1080
+ if (pluginOptions.verbose) {
1081
+ console.log('āœ… IWSDK Dev: Injection bundle ready');
1082
+ }
1083
+ }
1084
+ catch (error) {
1085
+ console.error('āŒ IWSDK Dev: Failed to generate injection bundle:', error);
1086
+ // Continue without injection rather than failing the build
1087
+ }
1088
+ },
1089
+ transformIndexHtml: {
1090
+ order: 'pre', // Run before other HTML transformations
1091
+ handler(html) {
1092
+ // Check if we should inject
1093
+ const shouldInject = config.command === 'serve' ||
1094
+ (config.command === 'build' && pluginOptions.injectOnBuild);
1095
+ if (!shouldInject || !injectionBundle) {
1096
+ return html;
1097
+ }
1098
+ if (pluginOptions.verbose) {
1099
+ console.log('šŸ’‰ IWSDK Dev: Injecting runtime script into HTML');
1100
+ }
1101
+ // Inject the script using Vite's tag API for robustness
1102
+ return {
1103
+ tags: [
1104
+ {
1105
+ tag: 'script',
1106
+ attrs: { type: 'module', src: VIRTUAL_ID },
1107
+ injectTo: 'head',
1108
+ },
1109
+ ],
1110
+ };
1111
+ },
1112
+ },
1113
+ // Display summary at the end of build process
1114
+ closeBundle: {
1115
+ order: 'post',
1116
+ async handler() {
1117
+ // Only show summary when injection actually happened
1118
+ const shouldInject = config.command === 'serve' ||
1119
+ (config.command === 'build' && pluginOptions.injectOnBuild);
1120
+ if (shouldInject && injectionBundle) {
1121
+ const mode = config.command === 'serve' ? 'Development' : 'Build';
1122
+ console.log(`\n🄽 IWSDK Dev Summary (${mode}):`);
1123
+ console.log(` - Device: ${pluginOptions.device}`);
1124
+ console.log(` - Runtime injected: ${(injectionBundle.size / 1024).toFixed(1)}KB`);
1125
+ console.log(` - Activation mode: ${pluginOptions.activation}`);
1126
+ if (pluginOptions.sem) {
1127
+ console.log(` - SEM environment: ${pluginOptions.sem.defaultScene}`);
1128
+ }
1129
+ if (pluginOptions.ai) {
1130
+ console.log(` - AI: ${pluginOptions.ai.mode} mode (WebSocket at /__iwer_mcp)`);
1131
+ }
1132
+ if (pluginOptions.activation === 'localhost') {
1133
+ console.log(' - Note: Runtime only activates on localhost/local networks');
1134
+ }
1135
+ console.log(''); // Extra line for spacing
1136
+ }
1137
+ },
1138
+ },
1139
+ };
1140
+ }
1141
+ /** @deprecated Use `iwsdkDev` instead */
1142
+ const injectIWER = iwsdkDev;
1143
+
1144
+ export { injectIWER, iwsdkDev, mergeJsonConfig, mergeTomlConfig, unmergeJsonConfig, unmergeTomlConfig };
1145
+ //# sourceMappingURL=index.js.map