adaptar-vite-plugin 1.0.3 → 1.0.5

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.
@@ -7,6 +7,16 @@ export interface AdaptarErrorPayload {
7
7
  colno: number | undefined;
8
8
  source: string;
9
9
  plugin: string | undefined;
10
+ classification: "render-blocking" | "diagnostic";
11
+ category: "compile" | "resource";
12
+ severity: "error" | "advisory";
13
+ resourceKind: "module" | "stylesheet" | "image" | "font" | "media" | "unknown";
14
+ renderBlocking: boolean;
15
+ rootHealth: {
16
+ state: "unknown";
17
+ hasRootContent: undefined;
18
+ readyState: undefined;
19
+ };
10
20
  }
11
21
  /**
12
22
  * Intercepts Vite's internal WebSocket `send` to catch build/HMR errors
@@ -1,3 +1,22 @@
1
+ function classifyViteResource(filename, plugin) {
2
+ const signal = `${filename ?? ""} ${plugin ?? ""}`.toLowerCase();
3
+ if (/\.(?:css|less|sass|scss|styl)(?:$|[?#\s])/.test(signal) || /css|postcss|tailwind/.test(signal)) {
4
+ return "stylesheet";
5
+ }
6
+ if (/\.(?:avif|bmp|gif|ico|jpe?g|png|svg|webp)(?:$|[?#\s])/.test(signal)) {
7
+ return "image";
8
+ }
9
+ if (/\.(?:woff2?|ttf|otf|eot)(?:$|[?#\s])/.test(signal)) {
10
+ return "font";
11
+ }
12
+ if (/\.(?:aac|flac|m4a|m4v|mov|mp3|mp4|ogg|ogv|wav|webm|vtt)(?:$|[?#\s])/.test(signal)) {
13
+ return "media";
14
+ }
15
+ if (/\.(?:c|m)?(?:j|t)sx?(?:$|[?#\s])/.test(signal) || /react|swc|typescript|vite/.test(signal)) {
16
+ return "module";
17
+ }
18
+ return "unknown";
19
+ }
1
20
  // How long (ms) to suppress a full-reload after a fatal error so the
2
21
  // error overlay stays visible before the iframe clears it.
3
22
  const RELOAD_SUPPRESSION_MS = 5_000;
@@ -22,22 +41,42 @@ export function interceptHmrErrors(server) {
22
41
  // ── Fatal build / HMR error ──────────────────────────────────────────
23
42
  if (payload.type === "error") {
24
43
  const { err } = payload;
44
+ const filename = err.id ?? err.loc?.file;
45
+ const resourceKind = classifyViteResource(filename, err.plugin);
46
+ // A Vite failure in application/module compilation invalidates the
47
+ // candidate. Asset and stylesheet failures remain visible diagnostics
48
+ // because they do not prove that the application cannot render.
49
+ const renderBlocking = resourceKind === "module" || resourceKind === "unknown";
25
50
  const formatted = {
26
51
  message: `[vite] ${err.message || "Internal server error"}`,
27
52
  stack: [err.stack, err.frame].filter(Boolean).join("\n\n"),
28
- filename: err.id ?? err.loc?.file,
53
+ filename,
29
54
  lineno: err.loc?.line,
30
55
  colno: err.loc?.column,
31
56
  source: "vite-hmr",
32
57
  plugin: err.plugin,
58
+ classification: renderBlocking ? "render-blocking" : "diagnostic",
59
+ category: renderBlocking ? "compile" : "resource",
60
+ severity: renderBlocking ? "error" : "advisory",
61
+ resourceKind,
62
+ renderBlocking,
63
+ rootHealth: {
64
+ state: "unknown",
65
+ hasRootContent: undefined,
66
+ readyState: undefined,
67
+ },
33
68
  };
34
69
  originalSend({
35
70
  type: "custom",
36
71
  event: "adaptar:error",
37
72
  data: formatted,
38
73
  });
39
- // Start suppression window so the follow-up full-reload is blocked.
40
- suppressReloadUntil = Date.now() + RELOAD_SUPPRESSION_MS;
74
+ // Only render-blocking compilation errors should interrupt Vite's
75
+ // normal reload path. Diagnostic asset/style failures are reported but
76
+ // are allowed to recover normally.
77
+ if (renderBlocking) {
78
+ suppressReloadUntil = Date.now() + RELOAD_SUPPRESSION_MS;
79
+ }
41
80
  originalSend(payload);
42
81
  return;
43
82
  }
@@ -46,6 +85,18 @@ export function interceptHmrErrors(server) {
46
85
  suppressReloadUntil = 0; // reset — only suppress once
47
86
  return;
48
87
  }
88
+ // A Vite update has been compiled and sent to the preview client. The
89
+ // injected bridge associates this with the server-owned preview operation
90
+ // ID carried in the iframe URL.
91
+ if (payload.type === "update") {
92
+ originalSend(payload);
93
+ originalSend({
94
+ type: "custom",
95
+ event: "adaptar:compile-success",
96
+ data: { compiledAt: Date.now() },
97
+ });
98
+ return;
99
+ }
49
100
  }
50
101
  originalSend(payload);
51
102
  };
package/dist/html-tags.js CHANGED
@@ -4,14 +4,50 @@ import { SELECTION_BRIDGE_SCRIPT } from "./scripts/selection-bridge.js";
4
4
  * The inline module that subscribes to the `adaptar:error` custom HMR event
5
5
  * and forwards it to the parent window via postMessage.
6
6
  */
7
- const HMR_LISTENER_SCRIPT = /* js */ `
8
- if (import.meta.hot) {
9
- import.meta.hot.on('adaptar:error', (data) => {
10
- try {
11
- window.parent.postMessage({ source: 'adaptar-preview', type: 'error', error: data }, '*');
12
- } catch (_) {}
13
- });
14
- }
7
+ const HMR_LISTENER_SCRIPT = /* js */ `
8
+ const adaptarOperationId = new URL(window.location.href).searchParams.get('__adaptarOperation') || undefined;
9
+ const readAdaptarRootHealth = () => {
10
+ const root = document.getElementById('root');
11
+ const hasRootContent = Boolean(root && (root.children.length || (root.textContent || '').trim()));
12
+ return {
13
+ state: !root ? 'missing' : (hasRootContent ? 'healthy' : 'empty'),
14
+ hasRootContent,
15
+ readyState: document.readyState,
16
+ };
17
+ };
18
+ const postToHost = (type, data) => {
19
+ try {
20
+ window.parent.postMessage({
21
+ source: 'adaptar-preview',
22
+ type,
23
+ operationId: adaptarOperationId,
24
+ ...data,
25
+ }, '*');
26
+ } catch (_) {}
27
+ };
28
+
29
+ if (import.meta.hot) {
30
+ import.meta.hot.on('adaptar:error', (data) => {
31
+ postToHost('error', {
32
+ error: {
33
+ ...data,
34
+ rootHealth: readAdaptarRootHealth(),
35
+ },
36
+ });
37
+ });
38
+ import.meta.hot.on('adaptar:compile-success', (data) => {
39
+ postToHost('compile-success', {
40
+ ...(data || {}),
41
+ rootHealth: readAdaptarRootHealth(),
42
+ });
43
+ });
44
+ }
45
+
46
+ postToHost('compile-success', {
47
+ compiledAt: Date.now(),
48
+ initial: true,
49
+ rootHealth: readAdaptarRootHealth(),
50
+ });
15
51
  `.trim();
16
52
  export function buildHtmlTags() {
17
53
  return [
@@ -1 +1 @@
1
- export declare const ERROR_BRIDGE_SCRIPT = "(function(){\n if (window.__ADAPTAR_ERROR_BRIDGE__) return;\n window.__ADAPTAR_ERROR_BRIDGE__ = true;\n\n function send(message, stack, filename, lineno, colno, source, plugin) {\n try {\n window.parent.postMessage({\n source: 'adaptar-preview',\n type: 'error',\n error: {\n message: message || 'Unknown error',\n stack: stack || '',\n filename: filename,\n lineno: lineno,\n colno: colno,\n source: source,\n plugin: plugin\n }\n }, '*');\n } catch (_) {}\n }\n\n // Resource load errors (scripts, stylesheets)\n window.addEventListener('error', function(e) {\n var target = e.target || e.srcElement;\n if (target && target !== window && target.tagName) {\n var tag = String(target.tagName).toLowerCase();\n var url = target.src || target.href;\n if (url && (tag === 'script' || tag === 'link')) {\n send(\n (tag === 'link' ? 'Failed to load stylesheet: ' : 'Failed to load module: ') + url,\n '', url, undefined, undefined, 'resource-load'\n );\n return;\n }\n }\n send(\n e.message || (e.error && e.error.message) || 'Runtime error occurred',\n e.error ? e.error.stack : '',\n e.filename, e.lineno, e.colno, 'runtime'\n );\n });\n\n // Unhandled promise rejections\n window.addEventListener('unhandledrejection', function(e) {\n var r = e.reason;\n send(\n r && r.message ? r.message : String(r || 'Unhandled Promise Rejection'),\n r && r.stack,\n r && r.fileName,\n r && r.lineNumber,\n r && r.columnNumber,\n 'unhandledrejection'\n );\n });\n\n // Console error interception for silent Vite/Syntax errors\n var nativeConsoleError = console.error;\n console.error = function() {\n var args = Array.prototype.slice.call(arguments);\n var msg = args.map(function(a) {\n return typeof a === 'string' ? a : (a && a.message ? a.message : String(a));\n }).join(' ');\n if (/Failed to load module|Internal Server Error|Syntax Error/i.test(msg)) {\n send(msg, '', undefined, undefined, undefined, 'console.error');\n }\n return nativeConsoleError.apply(console, args);\n };\n\n // Blank screen detector\n window.addEventListener('load', function() {\n setTimeout(function() {\n var root = document.getElementById('root');\n if (root && root.children.length === 0 && !(root.textContent || '').trim()) {\n send(\n 'Runtime error: Preview failed to render; a component or import may have failed silently.',\n '', location.href, undefined, undefined, 'blank-screen'\n );\n }\n }, 3000);\n });\n})();";
1
+ export declare const ERROR_BRIDGE_SCRIPT = "(function(){\n if (window.__ADAPTAR_ERROR_BRIDGE__) return;\n window.__ADAPTAR_ERROR_BRIDGE__ = true;\n\n var operationId = new URL(window.location.href).searchParams.get('__adaptarOperation') || undefined;\n\n function readRootHealth() {\n var root = document.getElementById('root');\n var hasRootContent = Boolean(\n root && (root.children.length || (root.textContent || '').trim())\n );\n\n return {\n state: !root ? 'missing' : (hasRootContent ? 'healthy' : 'empty'),\n hasRootContent: hasRootContent,\n readyState: document.readyState\n };\n }\n\n function sendRendered(heartbeat) {\n try {\n var rootHealth = readRootHealth();\n window.parent.postMessage({\n source: 'adaptar-preview',\n type: heartbeat ? 'render-heartbeat' : 'preview-rendered',\n operationId: operationId,\n renderedAt: Date.now(),\n hasRootContent: rootHealth.hasRootContent,\n rootHealth: rootHealth\n }, '*');\n } catch (_) {}\n }\n\n function classifyResource(target, url) {\n var tag = String((target && target.tagName) || '').toLowerCase();\n var rel = String((target && target.rel) || '').toLowerCase();\n var as = String((target && target.as) || '').toLowerCase();\n var type = String((target && target.type) || '').toLowerCase();\n var value = String(url || '').split(/[?#]/)[0].toLowerCase();\n\n if (\n as === 'font' ||\n type.indexOf('font/') === 0 ||\n /\\.(woff2?|ttf|otf|eot)$/.test(value)\n ) return 'font';\n if (\n tag === 'img' ||\n as === 'image' ||\n /\\.(avif|bmp|gif|ico|jpe?g|png|svg|webp)$/.test(value)\n ) return 'image';\n if (\n tag === 'audio' || tag === 'video' || tag === 'source' || tag === 'track' ||\n as === 'audio' || as === 'video' ||\n /\\.(aac|flac|m4a|m4v|mov|mp3|mp4|ogg|ogv|wav|webm|vtt)$/.test(value)\n ) return 'media';\n if (\n tag === 'script' ||\n as === 'script' ||\n rel === 'modulepreload' ||\n type === 'module' ||\n /\\.(c|m)?(j|t)sx?$/.test(value)\n ) return 'module';\n if (\n (tag === 'link' && rel === 'stylesheet') ||\n as === 'style' ||\n type === 'text/css' ||\n /\\.(css|less|sass|scss|styl)$/.test(value)\n ) return 'stylesheet';\n return 'unknown';\n }\n\n function resourceFailureMessage(resourceKind, url) {\n var labels = {\n font: 'Failed to load font: ',\n image: 'Failed to load image: ',\n media: 'Failed to load media: ',\n module: 'Failed to load module: ',\n stylesheet: 'Failed to load stylesheet: ',\n unknown: 'Failed to load resource: '\n };\n return (labels[resourceKind] || labels.unknown) + url;\n }\n\n function send(message, stack, filename, lineno, colno, source, plugin, metadata) {\n try {\n var details = metadata || {};\n var rootHealth = readRootHealth();\n var renderBlocking = details.renderBlocking === true || (\n details.blockWhenRootEmpty === true && !rootHealth.hasRootContent\n );\n\n window.parent.postMessage({\n source: 'adaptar-preview',\n type: 'error',\n operationId: operationId,\n error: {\n message: message || 'Unknown error',\n stack: stack || '',\n filename: filename,\n lineno: lineno,\n colno: colno,\n source: source,\n plugin: plugin,\n classification: renderBlocking ? 'render-blocking' : 'diagnostic',\n category: details.category || 'runtime',\n severity: renderBlocking ? 'error' : 'advisory',\n resourceKind: details.resourceKind || 'unknown',\n renderBlocking: renderBlocking,\n rootHealth: rootHealth\n }\n }, '*');\n } catch (_) {}\n }\n\n // Resource failures remain observable, but only a module required before\n // the application mounts can be classified as render-blocking. Images,\n // fonts, media, and stylesheets are quality diagnostics.\n window.addEventListener('error', function(e) {\n var target = e.target || e.srcElement;\n if (target && target !== window && target.tagName) {\n var url = target.src || target.href || target.currentSrc;\n var resourceKind = classifyResource(target, url);\n if (url || resourceKind !== 'unknown') {\n send(\n resourceFailureMessage(resourceKind, url || '(unknown resource URL)'),\n '', url, undefined, undefined, 'resource-load', undefined,\n {\n category: 'resource',\n resourceKind: resourceKind,\n blockWhenRootEmpty: resourceKind === 'module'\n }\n );\n return;\n }\n }\n\n send(\n e.message || (e.error && e.error.message) || 'Runtime error occurred',\n e.error ? e.error.stack : '',\n e.filename, e.lineno, e.colno, 'runtime', undefined,\n { category: 'runtime', resourceKind: 'module', blockWhenRootEmpty: true }\n );\n }, true);\n\n // An async failure is blocking only when the application has no rendered\n // root. Interaction failures in an otherwise-rendered page remain visible\n // diagnostics and never invalidate the candidate by themselves.\n window.addEventListener('unhandledrejection', function(e) {\n var r = e.reason;\n send(\n r && r.message ? r.message : String(r || 'Unhandled Promise Rejection'),\n r && r.stack,\n r && r.fileName,\n r && r.lineNumber,\n r && r.columnNumber,\n 'unhandledrejection', undefined,\n { category: 'runtime', resourceKind: 'module', blockWhenRootEmpty: true }\n );\n });\n\n // Intercept only errors that indicate a Vite/module compilation failure.\n // Their render-blocking status is still tied to an empty application root;\n // Vite HMR compile failures are classified separately by the server bridge.\n var nativeConsoleError = console.error;\n console.error = function() {\n var args = Array.prototype.slice.call(arguments);\n var msg = args.map(function(a) {\n return typeof a === 'string' ? a : (a && a.message ? a.message : String(a));\n }).join(' ');\n if (/Failed to load module|Internal Server Error|Syntax Error/i.test(msg)) {\n send(\n msg, '', undefined, undefined, undefined, 'console.error', undefined,\n { category: 'compile', resourceKind: 'module', blockWhenRootEmpty: true }\n );\n }\n return nativeConsoleError.apply(console, args);\n };\n\n // Blank root is a deterministic rendering failure. Quality checks are sent\n // separately as advisory diagnostics once a root is healthy.\n window.addEventListener('load', function() {\n requestAnimationFrame(function() {\n requestAnimationFrame(function() {\n sendRendered(false);\n });\n });\n\n setTimeout(function() {\n var rootHealth = readRootHealth();\n if (!rootHealth.hasRootContent) {\n send(\n 'Runtime error: Preview failed to render; a component or import may have failed silently.',\n '', location.href, undefined, undefined, 'blank-screen', undefined,\n { category: 'render', resourceKind: 'document', renderBlocking: true }\n );\n } else {\n var images = Array.prototype.slice.call(document.querySelectorAll('img'));\n var controls = Array.prototype.slice.call(\n document.querySelectorAll('button, a[href], input, select, textarea')\n );\n var checks = {\n viewportWidth: document.documentElement.clientWidth || window.innerWidth || 0,\n horizontalOverflow:\n document.documentElement.scrollWidth >\n (document.documentElement.clientWidth || window.innerWidth || 0) + 2,\n brokenImages: images.filter(function(img) {\n return img.complete && img.naturalWidth === 0;\n }).length,\n missingImageAlt: images.filter(function(img) {\n return !img.hasAttribute('alt');\n }).length,\n unlabeledControls: controls.filter(function(control) {\n var label = (\n control.getAttribute('aria-label') ||\n control.getAttribute('title') ||\n control.textContent ||\n control.value ||\n ''\n ).trim();\n return !label;\n }).length\n };\n var diagnostics = [];\n\n if (checks.horizontalOverflow) {\n diagnostics.push({\n code: 'horizontal-overflow',\n classification: 'diagnostic',\n category: 'layout',\n severity: 'advisory',\n resourceKind: 'quality',\n renderBlocking: false,\n message: 'The preview has horizontal overflow.'\n });\n }\n if (checks.brokenImages > 0) {\n diagnostics.push({\n code: 'broken-images',\n classification: 'diagnostic',\n category: 'asset',\n severity: 'advisory',\n resourceKind: 'image',\n renderBlocking: false,\n message: 'One or more images could not be displayed.',\n count: checks.brokenImages\n });\n }\n if (checks.missingImageAlt > 0) {\n diagnostics.push({\n code: 'missing-image-alt',\n classification: 'diagnostic',\n category: 'accessibility',\n severity: 'advisory',\n resourceKind: 'image',\n renderBlocking: false,\n message: 'One or more images are missing alternative text.',\n count: checks.missingImageAlt\n });\n }\n if (checks.unlabeledControls > 0) {\n diagnostics.push({\n code: 'unlabeled-controls',\n classification: 'diagnostic',\n category: 'accessibility',\n severity: 'advisory',\n resourceKind: 'control',\n renderBlocking: false,\n message: 'One or more controls do not have an accessible label.',\n count: checks.unlabeledControls\n });\n }\n\n window.parent.postMessage({\n source: 'adaptar-preview',\n type: 'preview-stable',\n operationId: operationId,\n stableAt: Date.now(),\n hasRootContent: rootHealth.hasRootContent,\n rootHealth: rootHealth,\n checks: checks,\n diagnostics: diagnostics\n }, '*');\n }\n }, 3000);\n });\n\n window.setInterval(function() { sendRendered(true); }, 20000);\n})();";
@@ -1,82 +1,288 @@
1
- export const ERROR_BRIDGE_SCRIPT = /* js */ `(function(){
2
- if (window.__ADAPTAR_ERROR_BRIDGE__) return;
3
- window.__ADAPTAR_ERROR_BRIDGE__ = true;
4
-
5
- function send(message, stack, filename, lineno, colno, source, plugin) {
6
- try {
7
- window.parent.postMessage({
8
- source: 'adaptar-preview',
9
- type: 'error',
10
- error: {
11
- message: message || 'Unknown error',
12
- stack: stack || '',
13
- filename: filename,
14
- lineno: lineno,
15
- colno: colno,
16
- source: source,
17
- plugin: plugin
18
- }
19
- }, '*');
20
- } catch (_) {}
21
- }
22
-
23
- // Resource load errors (scripts, stylesheets)
24
- window.addEventListener('error', function(e) {
25
- var target = e.target || e.srcElement;
26
- if (target && target !== window && target.tagName) {
27
- var tag = String(target.tagName).toLowerCase();
28
- var url = target.src || target.href;
29
- if (url && (tag === 'script' || tag === 'link')) {
30
- send(
31
- (tag === 'link' ? 'Failed to load stylesheet: ' : 'Failed to load module: ') + url,
32
- '', url, undefined, undefined, 'resource-load'
33
- );
34
- return;
35
- }
36
- }
37
- send(
38
- e.message || (e.error && e.error.message) || 'Runtime error occurred',
39
- e.error ? e.error.stack : '',
40
- e.filename, e.lineno, e.colno, 'runtime'
41
- );
42
- });
43
-
44
- // Unhandled promise rejections
45
- window.addEventListener('unhandledrejection', function(e) {
46
- var r = e.reason;
47
- send(
48
- r && r.message ? r.message : String(r || 'Unhandled Promise Rejection'),
49
- r && r.stack,
50
- r && r.fileName,
51
- r && r.lineNumber,
52
- r && r.columnNumber,
53
- 'unhandledrejection'
54
- );
55
- });
56
-
57
- // Console error interception for silent Vite/Syntax errors
58
- var nativeConsoleError = console.error;
59
- console.error = function() {
60
- var args = Array.prototype.slice.call(arguments);
61
- var msg = args.map(function(a) {
62
- return typeof a === 'string' ? a : (a && a.message ? a.message : String(a));
63
- }).join(' ');
64
- if (/Failed to load module|Internal Server Error|Syntax Error/i.test(msg)) {
65
- send(msg, '', undefined, undefined, undefined, 'console.error');
66
- }
67
- return nativeConsoleError.apply(console, args);
68
- };
69
-
70
- // Blank screen detector
71
- window.addEventListener('load', function() {
72
- setTimeout(function() {
73
- var root = document.getElementById('root');
74
- if (root && root.children.length === 0 && !(root.textContent || '').trim()) {
75
- send(
76
- 'Runtime error: Preview failed to render; a component or import may have failed silently.',
77
- '', location.href, undefined, undefined, 'blank-screen'
78
- );
79
- }
80
- }, 3000);
81
- });
1
+ export const ERROR_BRIDGE_SCRIPT = /* js */ `(function(){
2
+ if (window.__ADAPTAR_ERROR_BRIDGE__) return;
3
+ window.__ADAPTAR_ERROR_BRIDGE__ = true;
4
+
5
+ var operationId = new URL(window.location.href).searchParams.get('__adaptarOperation') || undefined;
6
+
7
+ function readRootHealth() {
8
+ var root = document.getElementById('root');
9
+ var hasRootContent = Boolean(
10
+ root && (root.children.length || (root.textContent || '').trim())
11
+ );
12
+
13
+ return {
14
+ state: !root ? 'missing' : (hasRootContent ? 'healthy' : 'empty'),
15
+ hasRootContent: hasRootContent,
16
+ readyState: document.readyState
17
+ };
18
+ }
19
+
20
+ function sendRendered(heartbeat) {
21
+ try {
22
+ var rootHealth = readRootHealth();
23
+ window.parent.postMessage({
24
+ source: 'adaptar-preview',
25
+ type: heartbeat ? 'render-heartbeat' : 'preview-rendered',
26
+ operationId: operationId,
27
+ renderedAt: Date.now(),
28
+ hasRootContent: rootHealth.hasRootContent,
29
+ rootHealth: rootHealth
30
+ }, '*');
31
+ } catch (_) {}
32
+ }
33
+
34
+ function classifyResource(target, url) {
35
+ var tag = String((target && target.tagName) || '').toLowerCase();
36
+ var rel = String((target && target.rel) || '').toLowerCase();
37
+ var as = String((target && target.as) || '').toLowerCase();
38
+ var type = String((target && target.type) || '').toLowerCase();
39
+ var value = String(url || '').split(/[?#]/)[0].toLowerCase();
40
+
41
+ if (
42
+ as === 'font' ||
43
+ type.indexOf('font/') === 0 ||
44
+ /\\.(woff2?|ttf|otf|eot)$/.test(value)
45
+ ) return 'font';
46
+ if (
47
+ tag === 'img' ||
48
+ as === 'image' ||
49
+ /\\.(avif|bmp|gif|ico|jpe?g|png|svg|webp)$/.test(value)
50
+ ) return 'image';
51
+ if (
52
+ tag === 'audio' || tag === 'video' || tag === 'source' || tag === 'track' ||
53
+ as === 'audio' || as === 'video' ||
54
+ /\\.(aac|flac|m4a|m4v|mov|mp3|mp4|ogg|ogv|wav|webm|vtt)$/.test(value)
55
+ ) return 'media';
56
+ if (
57
+ tag === 'script' ||
58
+ as === 'script' ||
59
+ rel === 'modulepreload' ||
60
+ type === 'module' ||
61
+ /\\.(c|m)?(j|t)sx?$/.test(value)
62
+ ) return 'module';
63
+ if (
64
+ (tag === 'link' && rel === 'stylesheet') ||
65
+ as === 'style' ||
66
+ type === 'text/css' ||
67
+ /\\.(css|less|sass|scss|styl)$/.test(value)
68
+ ) return 'stylesheet';
69
+ return 'unknown';
70
+ }
71
+
72
+ function resourceFailureMessage(resourceKind, url) {
73
+ var labels = {
74
+ font: 'Failed to load font: ',
75
+ image: 'Failed to load image: ',
76
+ media: 'Failed to load media: ',
77
+ module: 'Failed to load module: ',
78
+ stylesheet: 'Failed to load stylesheet: ',
79
+ unknown: 'Failed to load resource: '
80
+ };
81
+ return (labels[resourceKind] || labels.unknown) + url;
82
+ }
83
+
84
+ function send(message, stack, filename, lineno, colno, source, plugin, metadata) {
85
+ try {
86
+ var details = metadata || {};
87
+ var rootHealth = readRootHealth();
88
+ var renderBlocking = details.renderBlocking === true || (
89
+ details.blockWhenRootEmpty === true && !rootHealth.hasRootContent
90
+ );
91
+
92
+ window.parent.postMessage({
93
+ source: 'adaptar-preview',
94
+ type: 'error',
95
+ operationId: operationId,
96
+ error: {
97
+ message: message || 'Unknown error',
98
+ stack: stack || '',
99
+ filename: filename,
100
+ lineno: lineno,
101
+ colno: colno,
102
+ source: source,
103
+ plugin: plugin,
104
+ classification: renderBlocking ? 'render-blocking' : 'diagnostic',
105
+ category: details.category || 'runtime',
106
+ severity: renderBlocking ? 'error' : 'advisory',
107
+ resourceKind: details.resourceKind || 'unknown',
108
+ renderBlocking: renderBlocking,
109
+ rootHealth: rootHealth
110
+ }
111
+ }, '*');
112
+ } catch (_) {}
113
+ }
114
+
115
+ // Resource failures remain observable, but only a module required before
116
+ // the application mounts can be classified as render-blocking. Images,
117
+ // fonts, media, and stylesheets are quality diagnostics.
118
+ window.addEventListener('error', function(e) {
119
+ var target = e.target || e.srcElement;
120
+ if (target && target !== window && target.tagName) {
121
+ var url = target.src || target.href || target.currentSrc;
122
+ var resourceKind = classifyResource(target, url);
123
+ if (url || resourceKind !== 'unknown') {
124
+ send(
125
+ resourceFailureMessage(resourceKind, url || '(unknown resource URL)'),
126
+ '', url, undefined, undefined, 'resource-load', undefined,
127
+ {
128
+ category: 'resource',
129
+ resourceKind: resourceKind,
130
+ blockWhenRootEmpty: resourceKind === 'module'
131
+ }
132
+ );
133
+ return;
134
+ }
135
+ }
136
+
137
+ send(
138
+ e.message || (e.error && e.error.message) || 'Runtime error occurred',
139
+ e.error ? e.error.stack : '',
140
+ e.filename, e.lineno, e.colno, 'runtime', undefined,
141
+ { category: 'runtime', resourceKind: 'module', blockWhenRootEmpty: true }
142
+ );
143
+ }, true);
144
+
145
+ // An async failure is blocking only when the application has no rendered
146
+ // root. Interaction failures in an otherwise-rendered page remain visible
147
+ // diagnostics and never invalidate the candidate by themselves.
148
+ window.addEventListener('unhandledrejection', function(e) {
149
+ var r = e.reason;
150
+ send(
151
+ r && r.message ? r.message : String(r || 'Unhandled Promise Rejection'),
152
+ r && r.stack,
153
+ r && r.fileName,
154
+ r && r.lineNumber,
155
+ r && r.columnNumber,
156
+ 'unhandledrejection', undefined,
157
+ { category: 'runtime', resourceKind: 'module', blockWhenRootEmpty: true }
158
+ );
159
+ });
160
+
161
+ // Intercept only errors that indicate a Vite/module compilation failure.
162
+ // Their render-blocking status is still tied to an empty application root;
163
+ // Vite HMR compile failures are classified separately by the server bridge.
164
+ var nativeConsoleError = console.error;
165
+ console.error = function() {
166
+ var args = Array.prototype.slice.call(arguments);
167
+ var msg = args.map(function(a) {
168
+ return typeof a === 'string' ? a : (a && a.message ? a.message : String(a));
169
+ }).join(' ');
170
+ if (/Failed to load module|Internal Server Error|Syntax Error/i.test(msg)) {
171
+ send(
172
+ msg, '', undefined, undefined, undefined, 'console.error', undefined,
173
+ { category: 'compile', resourceKind: 'module', blockWhenRootEmpty: true }
174
+ );
175
+ }
176
+ return nativeConsoleError.apply(console, args);
177
+ };
178
+
179
+ // Blank root is a deterministic rendering failure. Quality checks are sent
180
+ // separately as advisory diagnostics once a root is healthy.
181
+ window.addEventListener('load', function() {
182
+ requestAnimationFrame(function() {
183
+ requestAnimationFrame(function() {
184
+ sendRendered(false);
185
+ });
186
+ });
187
+
188
+ setTimeout(function() {
189
+ var rootHealth = readRootHealth();
190
+ if (!rootHealth.hasRootContent) {
191
+ send(
192
+ 'Runtime error: Preview failed to render; a component or import may have failed silently.',
193
+ '', location.href, undefined, undefined, 'blank-screen', undefined,
194
+ { category: 'render', resourceKind: 'document', renderBlocking: true }
195
+ );
196
+ } else {
197
+ var images = Array.prototype.slice.call(document.querySelectorAll('img'));
198
+ var controls = Array.prototype.slice.call(
199
+ document.querySelectorAll('button, a[href], input, select, textarea')
200
+ );
201
+ var checks = {
202
+ viewportWidth: document.documentElement.clientWidth || window.innerWidth || 0,
203
+ horizontalOverflow:
204
+ document.documentElement.scrollWidth >
205
+ (document.documentElement.clientWidth || window.innerWidth || 0) + 2,
206
+ brokenImages: images.filter(function(img) {
207
+ return img.complete && img.naturalWidth === 0;
208
+ }).length,
209
+ missingImageAlt: images.filter(function(img) {
210
+ return !img.hasAttribute('alt');
211
+ }).length,
212
+ unlabeledControls: controls.filter(function(control) {
213
+ var label = (
214
+ control.getAttribute('aria-label') ||
215
+ control.getAttribute('title') ||
216
+ control.textContent ||
217
+ control.value ||
218
+ ''
219
+ ).trim();
220
+ return !label;
221
+ }).length
222
+ };
223
+ var diagnostics = [];
224
+
225
+ if (checks.horizontalOverflow) {
226
+ diagnostics.push({
227
+ code: 'horizontal-overflow',
228
+ classification: 'diagnostic',
229
+ category: 'layout',
230
+ severity: 'advisory',
231
+ resourceKind: 'quality',
232
+ renderBlocking: false,
233
+ message: 'The preview has horizontal overflow.'
234
+ });
235
+ }
236
+ if (checks.brokenImages > 0) {
237
+ diagnostics.push({
238
+ code: 'broken-images',
239
+ classification: 'diagnostic',
240
+ category: 'asset',
241
+ severity: 'advisory',
242
+ resourceKind: 'image',
243
+ renderBlocking: false,
244
+ message: 'One or more images could not be displayed.',
245
+ count: checks.brokenImages
246
+ });
247
+ }
248
+ if (checks.missingImageAlt > 0) {
249
+ diagnostics.push({
250
+ code: 'missing-image-alt',
251
+ classification: 'diagnostic',
252
+ category: 'accessibility',
253
+ severity: 'advisory',
254
+ resourceKind: 'image',
255
+ renderBlocking: false,
256
+ message: 'One or more images are missing alternative text.',
257
+ count: checks.missingImageAlt
258
+ });
259
+ }
260
+ if (checks.unlabeledControls > 0) {
261
+ diagnostics.push({
262
+ code: 'unlabeled-controls',
263
+ classification: 'diagnostic',
264
+ category: 'accessibility',
265
+ severity: 'advisory',
266
+ resourceKind: 'control',
267
+ renderBlocking: false,
268
+ message: 'One or more controls do not have an accessible label.',
269
+ count: checks.unlabeledControls
270
+ });
271
+ }
272
+
273
+ window.parent.postMessage({
274
+ source: 'adaptar-preview',
275
+ type: 'preview-stable',
276
+ operationId: operationId,
277
+ stableAt: Date.now(),
278
+ hasRootContent: rootHealth.hasRootContent,
279
+ rootHealth: rootHealth,
280
+ checks: checks,
281
+ diagnostics: diagnostics
282
+ }, '*');
283
+ }
284
+ }, 3000);
285
+ });
286
+
287
+ window.setInterval(function() { sendRendered(true); }, 20000);
82
288
  })();`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "adaptar-vite-plugin",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Vite plugin for Adaptar preview error and selection bridging",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,14 +1,54 @@
1
1
  import type { ViteDevServer, HMRPayload } from "vite";
2
2
 
3
- export interface AdaptarErrorPayload {
4
- message: string;
5
- stack: string;
6
- filename: string | undefined;
7
- lineno: number | undefined;
8
- colno: number | undefined;
9
- source: string;
10
- plugin: string | undefined;
11
- }
3
+ export interface AdaptarErrorPayload {
4
+ message: string;
5
+ stack: string;
6
+ filename: string | undefined;
7
+ lineno: number | undefined;
8
+ colno: number | undefined;
9
+ source: string;
10
+ plugin: string | undefined;
11
+ classification: "render-blocking" | "diagnostic";
12
+ category: "compile" | "resource";
13
+ severity: "error" | "advisory";
14
+ resourceKind:
15
+ | "module"
16
+ | "stylesheet"
17
+ | "image"
18
+ | "font"
19
+ | "media"
20
+ | "unknown";
21
+ renderBlocking: boolean;
22
+ rootHealth: {
23
+ state: "unknown";
24
+ hasRootContent: undefined;
25
+ readyState: undefined;
26
+ };
27
+ }
28
+
29
+ function classifyViteResource(
30
+ filename: string | undefined,
31
+ plugin: string | undefined,
32
+ ): AdaptarErrorPayload["resourceKind"] {
33
+ const signal = `${filename ?? ""} ${plugin ?? ""}`.toLowerCase();
34
+
35
+ if (/\.(?:css|less|sass|scss|styl)(?:$|[?#\s])/.test(signal) || /css|postcss|tailwind/.test(signal)) {
36
+ return "stylesheet";
37
+ }
38
+ if (/\.(?:avif|bmp|gif|ico|jpe?g|png|svg|webp)(?:$|[?#\s])/.test(signal)) {
39
+ return "image";
40
+ }
41
+ if (/\.(?:woff2?|ttf|otf|eot)(?:$|[?#\s])/.test(signal)) {
42
+ return "font";
43
+ }
44
+ if (/\.(?:aac|flac|m4a|m4v|mov|mp3|mp4|ogg|ogv|wav|webm|vtt)(?:$|[?#\s])/.test(signal)) {
45
+ return "media";
46
+ }
47
+ if (/\.(?:c|m)?(?:j|t)sx?(?:$|[?#\s])/.test(signal) || /react|swc|typescript|vite/.test(signal)) {
48
+ return "module";
49
+ }
50
+ return "unknown";
51
+ }
12
52
 
13
53
  // How long (ms) to suppress a full-reload after a fatal error so the
14
54
  // error overlay stays visible before the iframe clears it.
@@ -35,18 +75,34 @@ export function interceptHmrErrors(server: ViteDevServer): void {
35
75
  (server.ws as any).send = function (payload: HMRPayload): void {
36
76
  if (payload && typeof payload === "object") {
37
77
  // ── Fatal build / HMR error ──────────────────────────────────────────
38
- if (payload.type === "error") {
39
- const { err } = payload;
40
-
41
- const formatted: AdaptarErrorPayload = {
42
- message: `[vite] ${err.message || "Internal server error"}`,
43
- stack: [err.stack, err.frame].filter(Boolean).join("\n\n"),
44
- filename: err.id ?? err.loc?.file,
45
- lineno: err.loc?.line,
46
- colno: err.loc?.column,
47
- source: "vite-hmr",
48
- plugin: err.plugin,
49
- };
78
+ if (payload.type === "error") {
79
+ const { err } = payload;
80
+ const filename = err.id ?? err.loc?.file;
81
+ const resourceKind = classifyViteResource(filename, err.plugin);
82
+ // A Vite failure in application/module compilation invalidates the
83
+ // candidate. Asset and stylesheet failures remain visible diagnostics
84
+ // because they do not prove that the application cannot render.
85
+ const renderBlocking = resourceKind === "module" || resourceKind === "unknown";
86
+
87
+ const formatted: AdaptarErrorPayload = {
88
+ message: `[vite] ${err.message || "Internal server error"}`,
89
+ stack: [err.stack, err.frame].filter(Boolean).join("\n\n"),
90
+ filename,
91
+ lineno: err.loc?.line,
92
+ colno: err.loc?.column,
93
+ source: "vite-hmr",
94
+ plugin: err.plugin,
95
+ classification: renderBlocking ? "render-blocking" : "diagnostic",
96
+ category: renderBlocking ? "compile" : "resource",
97
+ severity: renderBlocking ? "error" : "advisory",
98
+ resourceKind,
99
+ renderBlocking,
100
+ rootHealth: {
101
+ state: "unknown",
102
+ hasRootContent: undefined,
103
+ readyState: undefined,
104
+ },
105
+ };
50
106
 
51
107
  originalSend({
52
108
  type: "custom",
@@ -54,18 +110,35 @@ export function interceptHmrErrors(server: ViteDevServer): void {
54
110
  data: formatted,
55
111
  });
56
112
 
57
- // Start suppression window so the follow-up full-reload is blocked.
58
- suppressReloadUntil = Date.now() + RELOAD_SUPPRESSION_MS;
113
+ // Only render-blocking compilation errors should interrupt Vite's
114
+ // normal reload path. Diagnostic asset/style failures are reported but
115
+ // are allowed to recover normally.
116
+ if (renderBlocking) {
117
+ suppressReloadUntil = Date.now() + RELOAD_SUPPRESSION_MS;
118
+ }
59
119
  originalSend(payload);
60
120
  return;
61
121
  }
62
122
 
63
123
  // ── Suppress full-reload that follows a fatal error ──────────────────
64
- if (payload.type === "full-reload" && Date.now() < suppressReloadUntil) {
124
+ if (payload.type === "full-reload" && Date.now() < suppressReloadUntil) {
65
125
  suppressReloadUntil = 0; // reset — only suppress once
66
126
  return;
67
- }
68
- }
127
+ }
128
+
129
+ // A Vite update has been compiled and sent to the preview client. The
130
+ // injected bridge associates this with the server-owned preview operation
131
+ // ID carried in the iframe URL.
132
+ if (payload.type === "update") {
133
+ originalSend(payload);
134
+ originalSend({
135
+ type: "custom",
136
+ event: "adaptar:compile-success",
137
+ data: { compiledAt: Date.now() },
138
+ });
139
+ return;
140
+ }
141
+ }
69
142
 
70
143
  originalSend(payload);
71
144
  };
package/src/html-tags.ts CHANGED
@@ -6,15 +6,51 @@ import { SELECTION_BRIDGE_SCRIPT } from "./scripts/selection-bridge.js";
6
6
  * The inline module that subscribes to the `adaptar:error` custom HMR event
7
7
  * and forwards it to the parent window via postMessage.
8
8
  */
9
- const HMR_LISTENER_SCRIPT = /* js */ `
10
- if (import.meta.hot) {
11
- import.meta.hot.on('adaptar:error', (data) => {
12
- try {
13
- window.parent.postMessage({ source: 'adaptar-preview', type: 'error', error: data }, '*');
14
- } catch (_) {}
15
- });
16
- }
17
- `.trim();
9
+ const HMR_LISTENER_SCRIPT = /* js */ `
10
+ const adaptarOperationId = new URL(window.location.href).searchParams.get('__adaptarOperation') || undefined;
11
+ const readAdaptarRootHealth = () => {
12
+ const root = document.getElementById('root');
13
+ const hasRootContent = Boolean(root && (root.children.length || (root.textContent || '').trim()));
14
+ return {
15
+ state: !root ? 'missing' : (hasRootContent ? 'healthy' : 'empty'),
16
+ hasRootContent,
17
+ readyState: document.readyState,
18
+ };
19
+ };
20
+ const postToHost = (type, data) => {
21
+ try {
22
+ window.parent.postMessage({
23
+ source: 'adaptar-preview',
24
+ type,
25
+ operationId: adaptarOperationId,
26
+ ...data,
27
+ }, '*');
28
+ } catch (_) {}
29
+ };
30
+
31
+ if (import.meta.hot) {
32
+ import.meta.hot.on('adaptar:error', (data) => {
33
+ postToHost('error', {
34
+ error: {
35
+ ...data,
36
+ rootHealth: readAdaptarRootHealth(),
37
+ },
38
+ });
39
+ });
40
+ import.meta.hot.on('adaptar:compile-success', (data) => {
41
+ postToHost('compile-success', {
42
+ ...(data || {}),
43
+ rootHealth: readAdaptarRootHealth(),
44
+ });
45
+ });
46
+ }
47
+
48
+ postToHost('compile-success', {
49
+ compiledAt: Date.now(),
50
+ initial: true,
51
+ rootHealth: readAdaptarRootHealth(),
52
+ });
53
+ `.trim();
18
54
 
19
55
  export function buildHtmlTags(): HtmlTagDescriptor[] {
20
56
  return [
@@ -1,82 +1,288 @@
1
- export const ERROR_BRIDGE_SCRIPT = /* js */ `(function(){
2
- if (window.__ADAPTAR_ERROR_BRIDGE__) return;
3
- window.__ADAPTAR_ERROR_BRIDGE__ = true;
4
-
5
- function send(message, stack, filename, lineno, colno, source, plugin) {
6
- try {
7
- window.parent.postMessage({
8
- source: 'adaptar-preview',
9
- type: 'error',
10
- error: {
11
- message: message || 'Unknown error',
12
- stack: stack || '',
13
- filename: filename,
14
- lineno: lineno,
15
- colno: colno,
16
- source: source,
17
- plugin: plugin
18
- }
19
- }, '*');
20
- } catch (_) {}
21
- }
22
-
23
- // Resource load errors (scripts, stylesheets)
24
- window.addEventListener('error', function(e) {
25
- var target = e.target || e.srcElement;
26
- if (target && target !== window && target.tagName) {
27
- var tag = String(target.tagName).toLowerCase();
28
- var url = target.src || target.href;
29
- if (url && (tag === 'script' || tag === 'link')) {
30
- send(
31
- (tag === 'link' ? 'Failed to load stylesheet: ' : 'Failed to load module: ') + url,
32
- '', url, undefined, undefined, 'resource-load'
33
- );
34
- return;
35
- }
36
- }
37
- send(
38
- e.message || (e.error && e.error.message) || 'Runtime error occurred',
39
- e.error ? e.error.stack : '',
40
- e.filename, e.lineno, e.colno, 'runtime'
41
- );
42
- });
43
-
44
- // Unhandled promise rejections
45
- window.addEventListener('unhandledrejection', function(e) {
46
- var r = e.reason;
47
- send(
48
- r && r.message ? r.message : String(r || 'Unhandled Promise Rejection'),
49
- r && r.stack,
50
- r && r.fileName,
51
- r && r.lineNumber,
52
- r && r.columnNumber,
53
- 'unhandledrejection'
54
- );
55
- });
56
-
57
- // Console error interception for silent Vite/Syntax errors
58
- var nativeConsoleError = console.error;
59
- console.error = function() {
60
- var args = Array.prototype.slice.call(arguments);
61
- var msg = args.map(function(a) {
62
- return typeof a === 'string' ? a : (a && a.message ? a.message : String(a));
63
- }).join(' ');
64
- if (/Failed to load module|Internal Server Error|Syntax Error/i.test(msg)) {
65
- send(msg, '', undefined, undefined, undefined, 'console.error');
66
- }
67
- return nativeConsoleError.apply(console, args);
68
- };
69
-
70
- // Blank screen detector
71
- window.addEventListener('load', function() {
72
- setTimeout(function() {
73
- var root = document.getElementById('root');
74
- if (root && root.children.length === 0 && !(root.textContent || '').trim()) {
75
- send(
76
- 'Runtime error: Preview failed to render; a component or import may have failed silently.',
77
- '', location.href, undefined, undefined, 'blank-screen'
78
- );
79
- }
80
- }, 3000);
81
- });
82
- })();`;
1
+ export const ERROR_BRIDGE_SCRIPT = /* js */ `(function(){
2
+ if (window.__ADAPTAR_ERROR_BRIDGE__) return;
3
+ window.__ADAPTAR_ERROR_BRIDGE__ = true;
4
+
5
+ var operationId = new URL(window.location.href).searchParams.get('__adaptarOperation') || undefined;
6
+
7
+ function readRootHealth() {
8
+ var root = document.getElementById('root');
9
+ var hasRootContent = Boolean(
10
+ root && (root.children.length || (root.textContent || '').trim())
11
+ );
12
+
13
+ return {
14
+ state: !root ? 'missing' : (hasRootContent ? 'healthy' : 'empty'),
15
+ hasRootContent: hasRootContent,
16
+ readyState: document.readyState
17
+ };
18
+ }
19
+
20
+ function sendRendered(heartbeat) {
21
+ try {
22
+ var rootHealth = readRootHealth();
23
+ window.parent.postMessage({
24
+ source: 'adaptar-preview',
25
+ type: heartbeat ? 'render-heartbeat' : 'preview-rendered',
26
+ operationId: operationId,
27
+ renderedAt: Date.now(),
28
+ hasRootContent: rootHealth.hasRootContent,
29
+ rootHealth: rootHealth
30
+ }, '*');
31
+ } catch (_) {}
32
+ }
33
+
34
+ function classifyResource(target, url) {
35
+ var tag = String((target && target.tagName) || '').toLowerCase();
36
+ var rel = String((target && target.rel) || '').toLowerCase();
37
+ var as = String((target && target.as) || '').toLowerCase();
38
+ var type = String((target && target.type) || '').toLowerCase();
39
+ var value = String(url || '').split(/[?#]/)[0].toLowerCase();
40
+
41
+ if (
42
+ as === 'font' ||
43
+ type.indexOf('font/') === 0 ||
44
+ /\\.(woff2?|ttf|otf|eot)$/.test(value)
45
+ ) return 'font';
46
+ if (
47
+ tag === 'img' ||
48
+ as === 'image' ||
49
+ /\\.(avif|bmp|gif|ico|jpe?g|png|svg|webp)$/.test(value)
50
+ ) return 'image';
51
+ if (
52
+ tag === 'audio' || tag === 'video' || tag === 'source' || tag === 'track' ||
53
+ as === 'audio' || as === 'video' ||
54
+ /\\.(aac|flac|m4a|m4v|mov|mp3|mp4|ogg|ogv|wav|webm|vtt)$/.test(value)
55
+ ) return 'media';
56
+ if (
57
+ tag === 'script' ||
58
+ as === 'script' ||
59
+ rel === 'modulepreload' ||
60
+ type === 'module' ||
61
+ /\\.(c|m)?(j|t)sx?$/.test(value)
62
+ ) return 'module';
63
+ if (
64
+ (tag === 'link' && rel === 'stylesheet') ||
65
+ as === 'style' ||
66
+ type === 'text/css' ||
67
+ /\\.(css|less|sass|scss|styl)$/.test(value)
68
+ ) return 'stylesheet';
69
+ return 'unknown';
70
+ }
71
+
72
+ function resourceFailureMessage(resourceKind, url) {
73
+ var labels = {
74
+ font: 'Failed to load font: ',
75
+ image: 'Failed to load image: ',
76
+ media: 'Failed to load media: ',
77
+ module: 'Failed to load module: ',
78
+ stylesheet: 'Failed to load stylesheet: ',
79
+ unknown: 'Failed to load resource: '
80
+ };
81
+ return (labels[resourceKind] || labels.unknown) + url;
82
+ }
83
+
84
+ function send(message, stack, filename, lineno, colno, source, plugin, metadata) {
85
+ try {
86
+ var details = metadata || {};
87
+ var rootHealth = readRootHealth();
88
+ var renderBlocking = details.renderBlocking === true || (
89
+ details.blockWhenRootEmpty === true && !rootHealth.hasRootContent
90
+ );
91
+
92
+ window.parent.postMessage({
93
+ source: 'adaptar-preview',
94
+ type: 'error',
95
+ operationId: operationId,
96
+ error: {
97
+ message: message || 'Unknown error',
98
+ stack: stack || '',
99
+ filename: filename,
100
+ lineno: lineno,
101
+ colno: colno,
102
+ source: source,
103
+ plugin: plugin,
104
+ classification: renderBlocking ? 'render-blocking' : 'diagnostic',
105
+ category: details.category || 'runtime',
106
+ severity: renderBlocking ? 'error' : 'advisory',
107
+ resourceKind: details.resourceKind || 'unknown',
108
+ renderBlocking: renderBlocking,
109
+ rootHealth: rootHealth
110
+ }
111
+ }, '*');
112
+ } catch (_) {}
113
+ }
114
+
115
+ // Resource failures remain observable, but only a module required before
116
+ // the application mounts can be classified as render-blocking. Images,
117
+ // fonts, media, and stylesheets are quality diagnostics.
118
+ window.addEventListener('error', function(e) {
119
+ var target = e.target || e.srcElement;
120
+ if (target && target !== window && target.tagName) {
121
+ var url = target.src || target.href || target.currentSrc;
122
+ var resourceKind = classifyResource(target, url);
123
+ if (url || resourceKind !== 'unknown') {
124
+ send(
125
+ resourceFailureMessage(resourceKind, url || '(unknown resource URL)'),
126
+ '', url, undefined, undefined, 'resource-load', undefined,
127
+ {
128
+ category: 'resource',
129
+ resourceKind: resourceKind,
130
+ blockWhenRootEmpty: resourceKind === 'module'
131
+ }
132
+ );
133
+ return;
134
+ }
135
+ }
136
+
137
+ send(
138
+ e.message || (e.error && e.error.message) || 'Runtime error occurred',
139
+ e.error ? e.error.stack : '',
140
+ e.filename, e.lineno, e.colno, 'runtime', undefined,
141
+ { category: 'runtime', resourceKind: 'module', blockWhenRootEmpty: true }
142
+ );
143
+ }, true);
144
+
145
+ // An async failure is blocking only when the application has no rendered
146
+ // root. Interaction failures in an otherwise-rendered page remain visible
147
+ // diagnostics and never invalidate the candidate by themselves.
148
+ window.addEventListener('unhandledrejection', function(e) {
149
+ var r = e.reason;
150
+ send(
151
+ r && r.message ? r.message : String(r || 'Unhandled Promise Rejection'),
152
+ r && r.stack,
153
+ r && r.fileName,
154
+ r && r.lineNumber,
155
+ r && r.columnNumber,
156
+ 'unhandledrejection', undefined,
157
+ { category: 'runtime', resourceKind: 'module', blockWhenRootEmpty: true }
158
+ );
159
+ });
160
+
161
+ // Intercept only errors that indicate a Vite/module compilation failure.
162
+ // Their render-blocking status is still tied to an empty application root;
163
+ // Vite HMR compile failures are classified separately by the server bridge.
164
+ var nativeConsoleError = console.error;
165
+ console.error = function() {
166
+ var args = Array.prototype.slice.call(arguments);
167
+ var msg = args.map(function(a) {
168
+ return typeof a === 'string' ? a : (a && a.message ? a.message : String(a));
169
+ }).join(' ');
170
+ if (/Failed to load module|Internal Server Error|Syntax Error/i.test(msg)) {
171
+ send(
172
+ msg, '', undefined, undefined, undefined, 'console.error', undefined,
173
+ { category: 'compile', resourceKind: 'module', blockWhenRootEmpty: true }
174
+ );
175
+ }
176
+ return nativeConsoleError.apply(console, args);
177
+ };
178
+
179
+ // Blank root is a deterministic rendering failure. Quality checks are sent
180
+ // separately as advisory diagnostics once a root is healthy.
181
+ window.addEventListener('load', function() {
182
+ requestAnimationFrame(function() {
183
+ requestAnimationFrame(function() {
184
+ sendRendered(false);
185
+ });
186
+ });
187
+
188
+ setTimeout(function() {
189
+ var rootHealth = readRootHealth();
190
+ if (!rootHealth.hasRootContent) {
191
+ send(
192
+ 'Runtime error: Preview failed to render; a component or import may have failed silently.',
193
+ '', location.href, undefined, undefined, 'blank-screen', undefined,
194
+ { category: 'render', resourceKind: 'document', renderBlocking: true }
195
+ );
196
+ } else {
197
+ var images = Array.prototype.slice.call(document.querySelectorAll('img'));
198
+ var controls = Array.prototype.slice.call(
199
+ document.querySelectorAll('button, a[href], input, select, textarea')
200
+ );
201
+ var checks = {
202
+ viewportWidth: document.documentElement.clientWidth || window.innerWidth || 0,
203
+ horizontalOverflow:
204
+ document.documentElement.scrollWidth >
205
+ (document.documentElement.clientWidth || window.innerWidth || 0) + 2,
206
+ brokenImages: images.filter(function(img) {
207
+ return img.complete && img.naturalWidth === 0;
208
+ }).length,
209
+ missingImageAlt: images.filter(function(img) {
210
+ return !img.hasAttribute('alt');
211
+ }).length,
212
+ unlabeledControls: controls.filter(function(control) {
213
+ var label = (
214
+ control.getAttribute('aria-label') ||
215
+ control.getAttribute('title') ||
216
+ control.textContent ||
217
+ control.value ||
218
+ ''
219
+ ).trim();
220
+ return !label;
221
+ }).length
222
+ };
223
+ var diagnostics = [];
224
+
225
+ if (checks.horizontalOverflow) {
226
+ diagnostics.push({
227
+ code: 'horizontal-overflow',
228
+ classification: 'diagnostic',
229
+ category: 'layout',
230
+ severity: 'advisory',
231
+ resourceKind: 'quality',
232
+ renderBlocking: false,
233
+ message: 'The preview has horizontal overflow.'
234
+ });
235
+ }
236
+ if (checks.brokenImages > 0) {
237
+ diagnostics.push({
238
+ code: 'broken-images',
239
+ classification: 'diagnostic',
240
+ category: 'asset',
241
+ severity: 'advisory',
242
+ resourceKind: 'image',
243
+ renderBlocking: false,
244
+ message: 'One or more images could not be displayed.',
245
+ count: checks.brokenImages
246
+ });
247
+ }
248
+ if (checks.missingImageAlt > 0) {
249
+ diagnostics.push({
250
+ code: 'missing-image-alt',
251
+ classification: 'diagnostic',
252
+ category: 'accessibility',
253
+ severity: 'advisory',
254
+ resourceKind: 'image',
255
+ renderBlocking: false,
256
+ message: 'One or more images are missing alternative text.',
257
+ count: checks.missingImageAlt
258
+ });
259
+ }
260
+ if (checks.unlabeledControls > 0) {
261
+ diagnostics.push({
262
+ code: 'unlabeled-controls',
263
+ classification: 'diagnostic',
264
+ category: 'accessibility',
265
+ severity: 'advisory',
266
+ resourceKind: 'control',
267
+ renderBlocking: false,
268
+ message: 'One or more controls do not have an accessible label.',
269
+ count: checks.unlabeledControls
270
+ });
271
+ }
272
+
273
+ window.parent.postMessage({
274
+ source: 'adaptar-preview',
275
+ type: 'preview-stable',
276
+ operationId: operationId,
277
+ stableAt: Date.now(),
278
+ hasRootContent: rootHealth.hasRootContent,
279
+ rootHealth: rootHealth,
280
+ checks: checks,
281
+ diagnostics: diagnostics
282
+ }, '*');
283
+ }
284
+ }, 3000);
285
+ });
286
+
287
+ window.setInterval(function() { sendRendered(true); }, 20000);
288
+ })();`;