@amaster.ai/vite-plugins 1.0.0-beta.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,866 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { createHash } from 'crypto';
4
+
5
+ // src/browser-logs.ts
6
+ function browserLogsPlugin() {
7
+ let logFilePath = "";
8
+ const injectedScript = `
9
+ <script>
10
+ (function() {
11
+ 'use strict';
12
+
13
+ // Log API path (provided by Vite dev server)
14
+ var LOG_API_PATH = '/__browser__';
15
+
16
+ // Write queue to ensure sequential writes
17
+ var writeQueue = [];
18
+ var isWriting = false;
19
+
20
+ // Process write queue to ensure sequential writes
21
+ function processWriteQueue() {
22
+ if (isWriting || writeQueue.length === 0) return;
23
+
24
+ isWriting = true;
25
+ var entry = writeQueue.shift();
26
+ var logText = JSON.stringify(entry);
27
+
28
+ fetch(LOG_API_PATH, {
29
+ method: 'POST',
30
+ headers: { 'Content-Type': 'application/json' },
31
+ body: logText
32
+ })
33
+ .then(function(response) {
34
+ isWriting = false;
35
+ if (!response.ok) {
36
+ console.warn('[BrowserLogs] Failed to write log:', response.status);
37
+ }
38
+ // Continue processing next item in queue
39
+ processWriteQueue();
40
+ })
41
+ .catch(function(error) {
42
+ console.warn('[BrowserLogs] Failed to write log:', error.message);
43
+ // On failure, put log back to queue head for retry
44
+ writeQueue.unshift(entry);
45
+ isWriting = false;
46
+ // Retry after delay
47
+ setTimeout(processWriteQueue, 1000);
48
+ });
49
+ }
50
+
51
+ // Limit headers object size
52
+ function truncateHeaders(headers) {
53
+ if (!headers) return headers;
54
+ var jsonStr = JSON.stringify(headers);
55
+ if (jsonStr.length <= MAX_HEADER_SIZE) return headers;
56
+ return '[Headers truncated, size: ' + jsonStr.length + ']';
57
+ }
58
+
59
+ // Truncate oversized log entries
60
+ function truncateLogEntry(entry) {
61
+ var jsonStr = JSON.stringify(entry);
62
+ if (jsonStr.length <= MAX_LOG_ENTRY_SIZE) {
63
+ return entry;
64
+ }
65
+
66
+ // If oversized, progressively truncate non-critical fields
67
+ var truncated = Object.assign({}, entry);
68
+
69
+ // 1. Truncate response body first
70
+ if (truncated.responseBody && typeof truncated.responseBody === 'string') {
71
+ truncated.responseBody = truncated.responseBody.substring(0, 500) + '... [truncated]';
72
+ }
73
+
74
+ // 2. Truncate request body
75
+ if (truncated.requestBody && typeof truncated.requestBody === 'string') {
76
+ truncated.requestBody = truncated.requestBody.substring(0, 500) + '... [truncated]';
77
+ }
78
+
79
+ // 3. Truncate message
80
+ if (truncated.message && typeof truncated.message === 'string' && truncated.message.length > 1000) {
81
+ truncated.message = truncated.message.substring(0, 1000) + '... [truncated]';
82
+ }
83
+
84
+ // 4. Truncate stack
85
+ if (truncated.stack && Array.isArray(truncated.stack) && truncated.stack.length > 3) {
86
+ truncated.stack = truncated.stack.slice(0, 3);
87
+ }
88
+
89
+ // Add truncation marker
90
+ truncated._truncated = true;
91
+ truncated._originalSize = jsonStr.length;
92
+
93
+ return truncated;
94
+ }
95
+
96
+ // Add log and send immediately (ensure order)
97
+ function addLog(entry) {
98
+ var truncatedEntry = truncateLogEntry(entry);
99
+ writeQueue.push(truncatedEntry);
100
+ processWriteQueue();
101
+ }
102
+
103
+ // ============================================
104
+ // Console log collection
105
+ // ============================================
106
+ var originalConsole = {
107
+ log: console.log,
108
+ info: console.info,
109
+ warn: console.warn,
110
+ error: console.error,
111
+ debug: console.debug
112
+ };
113
+
114
+ function getStackTrace() {
115
+ var stack = new Error().stack || '';
116
+ var lines = stack.split('\\n').slice(3);
117
+ // Limit stack lines
118
+ return lines.slice(0, MAX_STACK_LINES).map(function(line) { return line.trim(); });
119
+ }
120
+
121
+ function formatMessage(args) {
122
+ return Array.from(args).map(function(arg) {
123
+ if (arg === null) return 'null';
124
+ if (arg === undefined) return 'undefined';
125
+ if (typeof arg === 'object') {
126
+ try {
127
+ return JSON.stringify(arg);
128
+ } catch (e) {
129
+ return String(arg);
130
+ }
131
+ }
132
+ return String(arg);
133
+ }).join(' ');
134
+ }
135
+
136
+ function createLogEntry(level, args) {
137
+ return {
138
+ type: 'console',
139
+ timestamp: new Date().toISOString(),
140
+ level: level,
141
+ message: formatMessage(args),
142
+ stack: getStackTrace()
143
+ };
144
+ }
145
+
146
+ // Check if message should be filtered (contains [vite] text)
147
+ function shouldFilterConsoleLog(args) {
148
+ for (var i = 0; i < args.length; i++) {
149
+ var arg = args[i];
150
+ if (typeof arg === 'string' && arg.indexOf('[vite]') !== -1) {
151
+ return true;
152
+ }
153
+ }
154
+ return false;
155
+ }
156
+
157
+ function wrapConsoleMethod(method, level) {
158
+ return function() {
159
+ var args = arguments;
160
+ // Filter out logs containing [vite]
161
+ if (shouldFilterConsoleLog(args)) {
162
+ return originalConsole[method].apply(console, args);
163
+ }
164
+ var entry = createLogEntry(level, args);
165
+ addLog(entry);
166
+ return originalConsole[method].apply(console, args);
167
+ };
168
+ }
169
+
170
+ console.log = wrapConsoleMethod('log', 'log');
171
+ console.info = wrapConsoleMethod('info', 'info');
172
+ console.warn = wrapConsoleMethod('warn', 'warn');
173
+ console.error = wrapConsoleMethod('error', 'error');
174
+ console.debug = wrapConsoleMethod('debug', 'debug');
175
+
176
+ // ============================================
177
+ // Network request collection (exclude SSE and log API requests)
178
+ // ============================================
179
+
180
+ var MAX_BODY_SIZE = 2000;
181
+ var MAX_LOG_ENTRY_SIZE = 3000; // Max single log entry length
182
+ var MAX_HEADER_SIZE = 500; // Max single header object length
183
+ var MAX_STACK_LINES = 5; // Max stack lines to keep
184
+ const FILTERED_URLS = ['/__browser__', '/builtin']; // Filter out log API and Vite built-in requests
185
+
186
+ function isSSERequest(url, headers) {
187
+ var sseUrlPatterns = ['/events', '/sse', '/stream', 'text/event-stream'];
188
+ var urlStr = String(url).toLowerCase();
189
+ for (var i = 0; i < sseUrlPatterns.length; i++) {
190
+ if (urlStr.indexOf(sseUrlPatterns[i]) !== -1) {
191
+ return true;
192
+ }
193
+ }
194
+
195
+ if (headers) {
196
+ if (typeof headers.get === 'function') {
197
+ var accept = headers.get('Accept') || headers.get('accept');
198
+ if (accept && accept.indexOf('text/event-stream') !== -1) {
199
+ return true;
200
+ }
201
+ } else if (typeof headers === 'object') {
202
+ for (var key in headers) {
203
+ if (key.toLowerCase() === 'accept' && headers[key].indexOf('text/event-stream') !== -1) {
204
+ return true;
205
+ }
206
+ }
207
+ }
208
+ }
209
+
210
+ return false;
211
+ }
212
+
213
+ function shouldFilterRequest(url) {
214
+ return FILTERED_URLS.some(function(filteredUrl) {
215
+ return String(url).indexOf(filteredUrl) !== -1;
216
+ });
217
+ }
218
+
219
+ function formatRequestBody(body) {
220
+ if (!body) return null;
221
+
222
+ try {
223
+ if (typeof body === 'string') {
224
+ return body.substring(0, MAX_BODY_SIZE);
225
+ }
226
+ if (body instanceof FormData) {
227
+ var formDataObj = {};
228
+ body.forEach(function(value, key) {
229
+ if (value instanceof File) {
230
+ formDataObj[key] = '[File: ' + value.name + ', size: ' + value.size + ']';
231
+ } else {
232
+ formDataObj[key] = String(value).substring(0, 1000);
233
+ }
234
+ });
235
+ return JSON.stringify(formDataObj);
236
+ }
237
+ if (body instanceof Blob) {
238
+ return '[Blob: size=' + body.size + ', type=' + body.type + ']';
239
+ }
240
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
241
+ return '[Binary: size=' + body.byteLength + ']';
242
+ }
243
+ if (body instanceof URLSearchParams) {
244
+ return body.toString().substring(0, MAX_BODY_SIZE);
245
+ }
246
+ return String(body).substring(0, MAX_BODY_SIZE);
247
+ } catch (e) {
248
+ return '[Error reading body: ' + e.message + ']';
249
+ }
250
+ }
251
+
252
+ function formatResponseBody(response, responseType) {
253
+ if (!response) return null;
254
+
255
+ try {
256
+ if (responseType === '' || responseType === 'text') {
257
+ return String(response).substring(0, MAX_BODY_SIZE);
258
+ }
259
+ if (responseType === 'json') {
260
+ return JSON.stringify(response).substring(0, MAX_BODY_SIZE);
261
+ }
262
+ if (responseType === 'document') {
263
+ return '[Document]';
264
+ }
265
+ if (responseType === 'blob') {
266
+ return '[Blob: size=' + response.size + ']';
267
+ }
268
+ if (responseType === 'arraybuffer') {
269
+ return '[ArrayBuffer: size=' + response.byteLength + ']';
270
+ }
271
+ return String(response).substring(0, MAX_BODY_SIZE);
272
+ } catch (e) {
273
+ return '[Error reading response: ' + e.message + ']';
274
+ }
275
+ }
276
+
277
+ // Intercept XMLHttpRequest
278
+ var originalXHROpen = XMLHttpRequest.prototype.open;
279
+ var originalXHRSend = XMLHttpRequest.prototype.send;
280
+ var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
281
+
282
+ XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
283
+ this.__requestInfo__ = {
284
+ method: method,
285
+ url: url,
286
+ startTime: null,
287
+ headers: {}
288
+ };
289
+ return originalXHROpen.apply(this, arguments);
290
+ };
291
+
292
+ XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
293
+ if (this.__requestInfo__ && this.__requestInfo__.headers) {
294
+ this.__requestInfo__.headers[name] = value;
295
+ }
296
+ return originalXHRSetRequestHeader.apply(this, arguments);
297
+ };
298
+
299
+ XMLHttpRequest.prototype.send = function(body) {
300
+ var xhr = this;
301
+ var requestInfo = xhr.__requestInfo__;
302
+
303
+ if (requestInfo) {
304
+ // Skip SSE requests and filtered requests
305
+ if (isSSERequest(requestInfo.url, requestInfo.headers) || shouldFilterRequest(requestInfo.url)) {
306
+ return originalXHRSend.apply(this, arguments);
307
+ }
308
+
309
+ requestInfo.startTime = Date.now();
310
+ requestInfo.requestBody = formatRequestBody(body);
311
+
312
+ xhr.addEventListener('loadend', function() {
313
+ var contentType = xhr.getResponseHeader('Content-Type') || '';
314
+ if (contentType.indexOf('text/event-stream') !== -1) {
315
+ return;
316
+ }
317
+
318
+ var responseHeaders = {};
319
+ var allHeaders = xhr.getAllResponseHeaders();
320
+ if (allHeaders) {
321
+ allHeaders.split('\\r\\n').forEach(function(line) {
322
+ var parts = line.split(': ');
323
+ if (parts.length === 2) {
324
+ responseHeaders[parts[0]] = parts[1];
325
+ }
326
+ });
327
+ }
328
+
329
+ var entry = {
330
+ type: 'request',
331
+ timestamp: new Date().toISOString(),
332
+ requestType: 'xhr',
333
+ method: requestInfo.method,
334
+ url: requestInfo.url,
335
+ status: xhr.status,
336
+ statusText: xhr.statusText,
337
+ duration: Date.now() - requestInfo.startTime,
338
+ requestHeaders: truncateHeaders(requestInfo.headers),
339
+ requestBody: requestInfo.requestBody,
340
+ responseHeaders: truncateHeaders(responseHeaders),
341
+ responseType: xhr.responseType,
342
+ responseBody: formatResponseBody(xhr.response, xhr.responseType),
343
+ responseSize: xhr.response ? (typeof xhr.response === 'string' ? xhr.response.length : (xhr.response.byteLength || xhr.response.size || null)) : null
344
+ };
345
+
346
+ addLog(entry);
347
+ });
348
+ }
349
+
350
+ return originalXHRSend.apply(this, arguments);
351
+ };
352
+
353
+ // Intercept Fetch API
354
+ var originalFetch = window.fetch;
355
+
356
+ function headersToObject(headers) {
357
+ var obj = {};
358
+ if (!headers) return obj;
359
+
360
+ if (typeof headers.forEach === 'function') {
361
+ headers.forEach(function(value, key) {
362
+ obj[key] = value;
363
+ });
364
+ } else if (typeof headers === 'object') {
365
+ for (var key in headers) {
366
+ obj[key] = headers[key];
367
+ }
368
+ }
369
+ return obj;
370
+ }
371
+
372
+ window.fetch = function(input, init) {
373
+ var startTime = Date.now();
374
+ var method = (init && init.method) || 'GET';
375
+ var url = typeof input === 'string' ? input : input.url;
376
+ var headers = init && init.headers;
377
+
378
+ // Skip SSE requests and filtered requests
379
+ if (isSSERequest(url, headers) || shouldFilterRequest(url)) {
380
+ return originalFetch.apply(this, arguments);
381
+ }
382
+
383
+ var requestHeaders = headersToObject(headers);
384
+ var requestBody = formatRequestBody(init && init.body);
385
+
386
+ return originalFetch.apply(this, arguments)
387
+ .then(function(response) {
388
+ var contentType = response.headers.get('Content-Type') || '';
389
+ if (contentType.indexOf('text/event-stream') !== -1) {
390
+ return response;
391
+ }
392
+
393
+ var clonedResponse = response.clone();
394
+ var responseHeaders = headersToObject(response.headers);
395
+
396
+ clonedResponse.text().then(function(bodyText) {
397
+ var entry = {
398
+ type: 'request',
399
+ timestamp: new Date().toISOString(),
400
+ requestType: 'fetch',
401
+ method: method,
402
+ url: url,
403
+ status: response.status,
404
+ statusText: response.statusText,
405
+ duration: Date.now() - startTime,
406
+ requestHeaders: truncateHeaders(requestHeaders),
407
+ requestBody: requestBody,
408
+ responseHeaders: truncateHeaders(responseHeaders),
409
+ responseBody: bodyText ? bodyText.substring(0, MAX_BODY_SIZE) : null,
410
+ responseSize: bodyText ? bodyText.length : null,
411
+ ok: response.ok
412
+ };
413
+
414
+ addLog(entry);
415
+ }).catch(function(e) {
416
+ var entry = {
417
+ type: 'request',
418
+ timestamp: new Date().toISOString(),
419
+ requestType: 'fetch',
420
+ method: method,
421
+ url: url,
422
+ status: response.status,
423
+ statusText: response.statusText,
424
+ duration: Date.now() - startTime,
425
+ requestHeaders: truncateHeaders(requestHeaders),
426
+ requestBody: requestBody,
427
+ responseHeaders: truncateHeaders(responseHeaders),
428
+ responseBody: '[Unable to read: ' + e.message + ']',
429
+ responseSize: null,
430
+ ok: response.ok
431
+ };
432
+
433
+ addLog(entry);
434
+ });
435
+
436
+ return response;
437
+ })
438
+ .catch(function(error) {
439
+ var entry = {
440
+ type: 'request',
441
+ timestamp: new Date().toISOString(),
442
+ requestType: 'fetch',
443
+ method: method,
444
+ url: url,
445
+ status: 0,
446
+ statusText: 'Network Error',
447
+ duration: Date.now() - startTime,
448
+ requestHeaders: truncateHeaders(requestHeaders),
449
+ requestBody: requestBody,
450
+ responseHeaders: null,
451
+ responseBody: null,
452
+ error: error.message
453
+ };
454
+
455
+ addLog(entry);
456
+ throw error;
457
+ });
458
+ };
459
+
460
+ // ============================================
461
+ // Global error capture
462
+ // ============================================
463
+ window.addEventListener('error', function(event) {
464
+ var entry = {
465
+ type: 'error',
466
+ timestamp: new Date().toISOString(),
467
+ level: 'error',
468
+ message: event.message,
469
+ stack: event.error ? event.error.stack : 'at ' + event.filename + ':' + event.lineno + ':' + event.colno
470
+ };
471
+ addLog(entry);
472
+ });
473
+
474
+ window.addEventListener('unhandledrejection', function(event) {
475
+ var entry = {
476
+ type: 'error',
477
+ timestamp: new Date().toISOString(),
478
+ level: 'error',
479
+ message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),
480
+ stack: event.reason && event.reason.stack ? event.reason.stack : ''
481
+ };
482
+ addLog(entry);
483
+ });
484
+
485
+ // ============================================
486
+ // Send remaining logs on page unload
487
+ // ============================================
488
+ window.addEventListener('beforeunload', function() {
489
+ if (writeQueue.length > 0) {
490
+ // Use sendBeacon to ensure logs are sent
491
+ writeQueue.forEach(function(entry) {
492
+ navigator.sendBeacon(LOG_API_PATH, JSON.stringify(entry));
493
+ });
494
+ writeQueue = [];
495
+ }
496
+ });
497
+
498
+ // ============================================
499
+ // Provide manual flush method
500
+ // ============================================
501
+ window.__flushBrowserLogs__ = function() {
502
+ return new Promise(function(resolve) {
503
+ // Wait for queue to finish processing
504
+ function checkQueue() {
505
+ if (writeQueue.length === 0 && !isWriting) {
506
+ resolve();
507
+ } else {
508
+ setTimeout(checkQueue, 100);
509
+ }
510
+ }
511
+ checkQueue();
512
+ });
513
+ };
514
+
515
+ // Provide method to get queue status
516
+ window.__getBrowserLogsStatus__ = function() {
517
+ return {
518
+ queueLength: writeQueue.length,
519
+ isWriting: isWriting
520
+ };
521
+ };
522
+
523
+ originalConsole.log('[BrowserLogs] Log collection started');
524
+ })();
525
+ </script>`;
526
+ return {
527
+ name: "vite-plugin-browser-logs",
528
+ configResolved(config) {
529
+ const root = config.root || process.cwd();
530
+ logFilePath = path.join(root, "browser.log");
531
+ },
532
+ configureServer(devServer) {
533
+ devServer.middlewares.use((req, res, next) => {
534
+ if (req.url === "/__browser__" && req.method === "POST") {
535
+ const origin = req.headers.origin || "*";
536
+ let body = "";
537
+ req.on("data", (chunk) => {
538
+ body += chunk.toString();
539
+ });
540
+ req.on("end", () => {
541
+ try {
542
+ const logDir = path.dirname(logFilePath);
543
+ if (!fs.existsSync(logDir)) {
544
+ fs.mkdirSync(logDir, { recursive: true });
545
+ }
546
+ fs.appendFileSync(logFilePath, `${body}
547
+ `, "utf-8");
548
+ res.writeHead(200, {
549
+ "Content-Type": "application/json",
550
+ "Access-Control-Allow-Origin": origin,
551
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
552
+ "Access-Control-Allow-Headers": "Content-Type"
553
+ });
554
+ res.end(JSON.stringify({ success: true }));
555
+ } catch (error) {
556
+ console.error("[BrowserLogs] Write error:", error);
557
+ res.writeHead(500, {
558
+ "Content-Type": "application/json",
559
+ "Access-Control-Allow-Origin": origin,
560
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
561
+ "Access-Control-Allow-Headers": "Content-Type"
562
+ });
563
+ res.end(JSON.stringify({ success: false, error: String(error) }));
564
+ }
565
+ });
566
+ } else if (req.url === "/__browser__" && req.method === "OPTIONS") {
567
+ const origin = req.headers.origin || "*";
568
+ res.writeHead(204, {
569
+ "Access-Control-Allow-Origin": origin,
570
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
571
+ "Access-Control-Allow-Headers": "Content-Type",
572
+ "Access-Control-Max-Age": "86400"
573
+ });
574
+ res.end();
575
+ } else if (req.url === "/__browser__") {
576
+ const origin = req.headers.origin || "*";
577
+ res.writeHead(405, {
578
+ "Content-Type": "application/json",
579
+ "Access-Control-Allow-Origin": origin
580
+ });
581
+ res.end(JSON.stringify({ error: "Method not allowed" }));
582
+ } else {
583
+ next();
584
+ }
585
+ });
586
+ console.log("[BrowserLogs] Logs will be written to:", logFilePath);
587
+ },
588
+ transformIndexHtml(html) {
589
+ return html.replace(/<head([^>]*)>/i, `<head$1>${injectedScript}`);
590
+ }
591
+ };
592
+ }
593
+ function generateUniqueId(filePath, position) {
594
+ const key = `${filePath}:${position}`;
595
+ return createHash("md5").update(key).digest("hex").substring(0, 12);
596
+ }
597
+ var HTML_TAGS = /* @__PURE__ */ new Set([
598
+ "a",
599
+ "abbr",
600
+ "address",
601
+ "area",
602
+ "article",
603
+ "aside",
604
+ "audio",
605
+ "b",
606
+ "base",
607
+ "bdi",
608
+ "bdo",
609
+ "blockquote",
610
+ "body",
611
+ "br",
612
+ "button",
613
+ "canvas",
614
+ "caption",
615
+ "cite",
616
+ "code",
617
+ "col",
618
+ "colgroup",
619
+ "data",
620
+ "datalist",
621
+ "dd",
622
+ "del",
623
+ "details",
624
+ "dfn",
625
+ "dialog",
626
+ "div",
627
+ "dl",
628
+ "dt",
629
+ "em",
630
+ "embed",
631
+ "fieldset",
632
+ "figcaption",
633
+ "figure",
634
+ "footer",
635
+ "form",
636
+ "h1",
637
+ "h2",
638
+ "h3",
639
+ "h4",
640
+ "h5",
641
+ "h6",
642
+ "head",
643
+ "header",
644
+ "hgroup",
645
+ "hr",
646
+ "html",
647
+ "i",
648
+ "iframe",
649
+ "img",
650
+ "input",
651
+ "ins",
652
+ "kbd",
653
+ "label",
654
+ "legend",
655
+ "li",
656
+ "link",
657
+ "main",
658
+ "map",
659
+ "mark",
660
+ "meta",
661
+ "meter",
662
+ "nav",
663
+ "noscript",
664
+ "object",
665
+ "ol",
666
+ "optgroup",
667
+ "option",
668
+ "output",
669
+ "p",
670
+ "param",
671
+ "picture",
672
+ "pre",
673
+ "progress",
674
+ "q",
675
+ "rp",
676
+ "rt",
677
+ "ruby",
678
+ "s",
679
+ "samp",
680
+ "script",
681
+ "section",
682
+ "select",
683
+ "small",
684
+ "source",
685
+ "span",
686
+ "strong",
687
+ "style",
688
+ "sub",
689
+ "summary",
690
+ "sup",
691
+ "svg",
692
+ "table",
693
+ "tbody",
694
+ "td",
695
+ "template",
696
+ "textarea",
697
+ "tfoot",
698
+ "th",
699
+ "thead",
700
+ "time",
701
+ "title",
702
+ "tr",
703
+ "track",
704
+ "u",
705
+ "ul",
706
+ "var",
707
+ "video",
708
+ "wbr"
709
+ ]);
710
+ function componentIdPlugin() {
711
+ let isDev = false;
712
+ return {
713
+ name: "vite-plugin-component-id",
714
+ enforce: "pre",
715
+ configResolved(config) {
716
+ isDev = config.command === "serve";
717
+ },
718
+ transform(code, id) {
719
+ if (!isDev) {
720
+ return null;
721
+ }
722
+ if (!/\.(tsx|jsx)$/.test(id)) {
723
+ return null;
724
+ }
725
+ if (id.includes("node_modules")) {
726
+ return null;
727
+ }
728
+ if (!/<[a-z]/.test(code)) {
729
+ return null;
730
+ }
731
+ try {
732
+ let transformedCode = code;
733
+ const jsxOpenTagRegex = /<([a-z][\da-z]*)(?=[\s/>])/g;
734
+ let match;
735
+ const matches = [];
736
+ while ((match = jsxOpenTagRegex.exec(code)) !== null) {
737
+ const tag = match[1];
738
+ if (!tag) continue;
739
+ const tagStartIndex = match.index;
740
+ const tagEndIndex = match.index + match[0].length;
741
+ if (!HTML_TAGS.has(tag)) {
742
+ continue;
743
+ }
744
+ let checkIndex = tagEndIndex;
745
+ let foundClosing = false;
746
+ let hasComponentId = false;
747
+ while (checkIndex < code.length && !foundClosing) {
748
+ const char = code[checkIndex];
749
+ if (char === ">") {
750
+ foundClosing = true;
751
+ const tagContent = code.substring(tagStartIndex, checkIndex);
752
+ if (tagContent.includes("data-node-component-id")) {
753
+ hasComponentId = true;
754
+ }
755
+ }
756
+ checkIndex++;
757
+ }
758
+ if (hasComponentId) {
759
+ continue;
760
+ }
761
+ matches.push({
762
+ index: tagStartIndex,
763
+ tag,
764
+ tagEndIndex
765
+ });
766
+ }
767
+ let currentCode = code;
768
+ for (let i = matches.length - 1; i >= 0; i--) {
769
+ const item = matches[i];
770
+ if (!item) continue;
771
+ const { index, tagEndIndex } = item;
772
+ const uniqueId = generateUniqueId(id, index);
773
+ const before = currentCode.substring(0, tagEndIndex);
774
+ const after = currentCode.substring(tagEndIndex);
775
+ transformedCode = `${before} data-node-component-id="${uniqueId}"${after}`;
776
+ currentCode = transformedCode;
777
+ }
778
+ return {
779
+ code: transformedCode,
780
+ map: null
781
+ };
782
+ } catch {
783
+ return null;
784
+ }
785
+ }
786
+ };
787
+ }
788
+
789
+ // src/editor-bridge.ts
790
+ var clickHandlerScript = `<script>
791
+ document.addEventListener("click", (e) => {
792
+ const element = e.target;
793
+ const noJumpOut = document.body.classList.contains("forbid-jump-out")
794
+ if (element.hasAttribute("data-link-href") && !noJumpOut) {
795
+ const href = element.getAttribute("data-link-href");
796
+ const target = element.getAttribute("data-link-target");
797
+ if (href) {
798
+ if (target === "_blank") {
799
+ window.open(href, "_blank");
800
+ } else {
801
+ window.location.href = href;
802
+ }
803
+ }
804
+ } else if(noJumpOut && element.tagName === "A") {
805
+ e.preventDefault();
806
+ }
807
+ });
808
+ </script>`;
809
+ function editorBridgePlugin(options) {
810
+ let isDev = false;
811
+ const bridgePath = options?.bridgeScriptPath || "/scripts/bridge.js";
812
+ return {
813
+ name: "vite-plugin-editor-bridge",
814
+ configResolved(config) {
815
+ isDev = config.command === "serve";
816
+ },
817
+ transformIndexHtml(html) {
818
+ const devScript = isDev ? `<script type="module" src="${bridgePath}"></script>` : "";
819
+ const scriptsToInject = `${clickHandlerScript + devScript}</body>`;
820
+ return html.replace("</body>", scriptsToInject);
821
+ }
822
+ };
823
+ }
824
+
825
+ // src/routes-expose.ts
826
+ function routesExposePlugin(options) {
827
+ let isDev = false;
828
+ const routesPath = options?.routesFilePath || "src/routes.tsx";
829
+ return {
830
+ name: "vite-plugin-routes-expose",
831
+ enforce: "post",
832
+ configResolved(config) {
833
+ isDev = config.command === "serve";
834
+ },
835
+ transform(code, id) {
836
+ if (!isDev) {
837
+ return null;
838
+ }
839
+ if (!id.endsWith(routesPath)) {
840
+ return null;
841
+ }
842
+ try {
843
+ if (code.includes("window.__APP_ROUTES__")) {
844
+ return null;
845
+ }
846
+ const transformedCode = `${code}
847
+
848
+ // Development mode: Expose routes to window.__APP_ROUTES__
849
+ if (typeof window !== 'undefined') {
850
+ window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];
851
+ }
852
+ `;
853
+ return {
854
+ code: transformedCode,
855
+ map: null
856
+ };
857
+ } catch {
858
+ return null;
859
+ }
860
+ }
861
+ };
862
+ }
863
+
864
+ export { browserLogsPlugin, componentIdPlugin, editorBridgePlugin, routesExposePlugin };
865
+ //# sourceMappingURL=index.js.map
866
+ //# sourceMappingURL=index.js.map