@luckylillia-dev/plugin-aiimgdetector 0.0.0-placeholder → 1.0.4

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.
Files changed (99) hide show
  1. package/README.md +2 -2
  2. package/assets/demo.png +0 -0
  3. package/assets/icon.svg +15 -0
  4. package/assets/synthid-login-check.jpg +0 -0
  5. package/docs/details.md +45 -0
  6. package/docs/publishing.md +66 -0
  7. package/docs/synthid.md +80 -0
  8. package/lib/image.js +90 -0
  9. package/lib/index.js +207 -0
  10. package/lib/provenance.js +21 -0
  11. package/lib/synthid-auth.js +100 -0
  12. package/lib/synthid-browser.js +451 -0
  13. package/lib/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
  14. package/lib/synthid-http-runtime/complete-protocol.mjs +88 -0
  15. package/lib/synthid-http-runtime/entry.d.mts +41 -0
  16. package/lib/synthid-http-runtime/entry.mjs +6 -0
  17. package/lib/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
  18. package/lib/synthid-http-runtime/independent-request-reference.mjs +49 -0
  19. package/lib/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
  20. package/lib/synthid-http-runtime/lifecycle-client.mjs +165 -0
  21. package/lib/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
  22. package/lib/synthid-http-runtime/lifecycle-worker.mjs +363 -0
  23. package/lib/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
  24. package/lib/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
  25. package/lib/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
  26. package/lib/synthid-http-runtime/realm-init.js +34 -0
  27. package/lib/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
  28. package/lib/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
  29. package/lib/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
  30. package/lib/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
  31. package/lib/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
  32. package/lib/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
  33. package/lib/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
  34. package/lib/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
  35. package/lib/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
  36. package/lib/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
  37. package/lib/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
  38. package/lib/synthid-http-runtime/runtime-web-compat.mjs +639 -0
  39. package/lib/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
  40. package/lib/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
  41. package/lib/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
  42. package/lib/synthid-http-runtime/scripting-parser.mjs +13 -0
  43. package/lib/synthid-http-runtime/web-session.mjs +64 -0
  44. package/lib/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
  45. package/lib/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
  46. package/lib/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
  47. package/lib/synthid-http.js +314 -0
  48. package/lib/synthid-manual.js +365 -0
  49. package/lib/synthid-page.js +101 -0
  50. package/lib/synthid-result.js +189 -0
  51. package/lib/synthid.js +540 -0
  52. package/lib/vision.js +41 -0
  53. package/package.json +77 -4
  54. package/src/image.ts +74 -0
  55. package/src/index.ts +203 -0
  56. package/src/provenance.ts +40 -0
  57. package/src/synthid-auth.ts +83 -0
  58. package/src/synthid-browser.ts +426 -0
  59. package/src/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
  60. package/src/synthid-http-runtime/complete-protocol.mjs +88 -0
  61. package/src/synthid-http-runtime/entry.d.mts +41 -0
  62. package/src/synthid-http-runtime/entry.mjs +6 -0
  63. package/src/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
  64. package/src/synthid-http-runtime/independent-request-reference.mjs +49 -0
  65. package/src/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
  66. package/src/synthid-http-runtime/lifecycle-client.mjs +165 -0
  67. package/src/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
  68. package/src/synthid-http-runtime/lifecycle-worker.mjs +363 -0
  69. package/src/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
  70. package/src/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
  71. package/src/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
  72. package/src/synthid-http-runtime/realm-init.js +34 -0
  73. package/src/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
  74. package/src/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
  75. package/src/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
  76. package/src/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
  77. package/src/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
  78. package/src/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
  79. package/src/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
  80. package/src/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
  81. package/src/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
  82. package/src/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
  83. package/src/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
  84. package/src/synthid-http-runtime/runtime-web-compat.mjs +639 -0
  85. package/src/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
  86. package/src/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
  87. package/src/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
  88. package/src/synthid-http-runtime/scripting-parser.mjs +13 -0
  89. package/src/synthid-http-runtime/web-session.mjs +64 -0
  90. package/src/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
  91. package/src/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
  92. package/src/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
  93. package/src/synthid-http.ts +290 -0
  94. package/src/synthid-manual.ts +388 -0
  95. package/src/synthid-page.ts +103 -0
  96. package/src/synthid-result.ts +177 -0
  97. package/src/synthid.ts +514 -0
  98. package/src/vision.ts +57 -0
  99. package/webui/index.js +279 -0
@@ -0,0 +1,363 @@
1
+ import { JSDOM, VirtualConsole, ResourceLoader, CookieJar } from 'jsdom';
2
+ import { Script } from 'node:vm';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { totalmem, platform, arch } from 'node:os';
5
+ import { enableScriptingParsingForOutsideOnly } from './scripting-parser.mjs';
6
+ import { createEventListenerDiagnostics } from './event-listener-diagnostics.mjs';
7
+ import { installEventClockCompatibility } from './jsdom-event-clock-compat.mjs';
8
+ import { createNodePlatformFailureDiagnostics } from './node-platform-failure-diagnostics.mjs';
9
+
10
+ // One isolated interpreter per image. The parent owns the HTTP connection,
11
+ // deadline and hard termination. No account credentials reach this process.
12
+ // Node filesystem permissions are not a network sandbox.
13
+ const VERSION = 1, MAX_INPUT_BYTES = 16 * 1024 * 1024, SYNC_TIMEOUT = 5000;
14
+ let dom, context, phase = 'empty', stopping = false, inputBuffer = '';
15
+ let initializedAt = 0, snapshotCount = 0, enablePointerDiagnostics = false;
16
+ let eventListenerProbe, eventClockCompatibility, clockPrecisionControl;
17
+ let runtimeWebCompatibility, runtimeNavigatorCompatibility, runtimeWindowStateCompatibility;
18
+ let runtimeChildWebCompatibility, runtimeDetachedFrameCompatibility, webidlBrandErrorAdapter;
19
+ let runtimeWebIdlRealmCompatibility, runtimeWebIdlCallableControl, javascriptBindings;
20
+ let runtimePermissionsControl, runtimeAnchorHrefTranslate, runtimeChromeCsi, runtimeCssProperties;
21
+ let platformFailureDiagnostics, restoreActivationState, activationDiagnostic;
22
+ let activationDiagnosticSource, activationTransientMs = 0, createActivationStateDiagnostic;
23
+ const diagnostics = { domErrors: 0, suppliedFrameRequests: 0, refusedResources: 0 };
24
+ class OperationError extends Error { constructor(code) { super(code); this.code = code; } }
25
+ const send = envelope => new Promise(resolve => process.stdout.write(JSON.stringify({ version: VERSION, ...envelope }) + '\n', resolve));
26
+ const bounded = async (promise, timeoutMs) => {
27
+ let timer;
28
+ try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new OperationError('OPERATION_TIMEOUT')), timeoutMs); })]); }
29
+ finally { clearTimeout(timer); }
30
+ };
31
+ const timeoutFor = (request, fallback) => Number.isInteger(request.timeoutMs) && request.timeoutMs >= 10 && request.timeoutMs <= 120000 ? request.timeoutMs : fallback;
32
+ const run = source => new Script(source, { filename: 'synthid-lifecycle-realm.js' }).runInContext(context, { timeout: SYNC_TIMEOUT });
33
+ const metrics = () => {
34
+ if (!context) return { errors: [] };
35
+ const encoded = run('JSON.stringify({experimentCount: __metrics.experimentCount, stateField5: __metrics.stateField5, errors: __metrics.errors.filter(Number.isSafeInteger).slice(0, 20)})');
36
+ return typeof encoded === 'string' && encoded.length < 4096 ? JSON.parse(encoded) : { errors: [] };
37
+ };
38
+ const inspect = () => ({
39
+ success: true, phase, snapshotCount, aliveMs: initializedAt ? Date.now() - initializedAt : 0,
40
+ diagnostics: { ...diagnostics }, metrics: metrics(),
41
+ javascriptBindings: javascriptBindings?.snapshot(), clockPrecisionControl: clockPrecisionControl?.snapshot(),
42
+ });
43
+ const closeDom = () => {
44
+ // Restore factory hooks in reverse installation order, including retained frames.
45
+ for (const control of [runtimeAnchorHrefTranslate, runtimePermissionsControl, javascriptBindings,
46
+ runtimeWebIdlCallableControl, runtimeWebIdlRealmCompatibility, runtimeCssProperties,
47
+ runtimeWindowStateCompatibility, runtimeNavigatorCompatibility]) try { control?.dispose(); } catch {}
48
+ if (clockPrecisionControl) try { runtimeDetachedFrameCompatibility?.dispose(); } catch {}
49
+ try { runtimeChildWebCompatibility?.dispose(); } catch {}
50
+ try { restoreActivationState?.(); } catch {}
51
+ try { runtimeWebCompatibility?.dispose(); } catch {}
52
+ if (!clockPrecisionControl) try { runtimeDetachedFrameCompatibility?.dispose(); } catch {}
53
+ try { eventListenerProbe?.dispose(); } catch {}
54
+ try { runtimeChromeCsi?.dispose(); } catch {}
55
+ try { dom?.window.close(); } catch {}
56
+ try { eventClockCompatibility?.dispose(); } catch {}
57
+ try { clockPrecisionControl?.dispose(); } catch {}
58
+ dom = undefined; context = undefined;
59
+ };
60
+ async function shutdown(timeoutMs) {
61
+ let shutdownInvoked = false, shutdownCompleted = false;
62
+ if (context) try {
63
+ shutdownInvoked = run('typeof globalThis.__shutdown === "function"');
64
+ if (shutdownInvoked) {
65
+ await bounded(Promise.resolve(run('(() => { const shutdown = globalThis.__shutdown; return shutdown(); })()')), timeoutMs);
66
+ shutdownCompleted = true;
67
+ }
68
+ } catch {}
69
+ closeDom(); phase = 'disposed';
70
+ return { success: true, phase, snapshotCount, shutdownInvoked, shutdownCompleted,
71
+ javascriptBindings: javascriptBindings?.snapshot(), clockPrecisionControl: clockPrecisionControl?.snapshot() };
72
+ }
73
+ function validateInput(input) {
74
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new OperationError('INVALID_INPUT');
75
+ const booleans = ['clockPrecision100us', 'eventClockCompatibility', 'enablePointerDiagnostics',
76
+ 'runtimeWebCompatibility', 'runtimeNetworkCompatibility', 'runtimeChildWebCompatibility',
77
+ 'runtimeNavigatorCompatibility', 'runtimeWindowStateCompatibility', 'runtimeDetachedFrameCompatibility',
78
+ 'runtimeWebIdlRealmCompatibility', 'runtimeWebIdlCallableControl', 'runtimePermissionsBinding',
79
+ 'runtimeAnchorHrefTranslate', 'runtimeMouseMediaCompatibility', 'runtimeChromeCsi', 'runtimeCssProperties',
80
+ 'javascriptBindings', 'activationStateControl', 'activationTimingControl', 'virtualFocusControl',
81
+ 'webidlBrandErrors', 'userActivationWebIdlCompatibility'];
82
+ for (const key of booleans) if (input[key] !== undefined && typeof input[key] !== 'boolean') throw new OperationError('INVALID_INPUT');
83
+ // The production worker has no native or interpreter-instrumentation modes.
84
+ const fields = new Set([...booleans, 'program', 'globalName', 'interpreter', 'interpreterSourceUrl',
85
+ 'pageUrl', 'pageHTML', 'frameUrl', 'frameHTML', 'experiments', 'rawExperiments', 'userAgent',
86
+ 'pageGlobals', 'referrer', 'cookieJar', 'performanceTimeOriginEpochMs', 'performanceEntries']);
87
+ if (Object.keys(input).some(key => !fields.has(key))) throw new OperationError('INVALID_INPUT');
88
+ if (input.clockPrecision100us && (!input.eventClockCompatibility || !input.runtimeWebCompatibility || !input.runtimeChildWebCompatibility)
89
+ || (input.runtimeWebIdlCallableControl || input.javascriptBindings) && !input.runtimeWebIdlRealmCompatibility
90
+ || input.activationTimingControl && !input.activationStateControl
91
+ || ['runtimeChildWebCompatibility', 'runtimeNetworkCompatibility', 'runtimeWindowStateCompatibility',
92
+ 'activationStateControl', 'virtualFocusControl', 'userActivationWebIdlCompatibility'].some(key => input[key] && !input.runtimeWebCompatibility)) throw new OperationError('INVALID_INPUT');
93
+ for (const name of ['program', 'globalName', 'interpreter']) {
94
+ if (typeof input[name] !== 'string' || !input[name] || input[name].length > 4 * 1024 * 1024) throw new OperationError('INVALID_INPUT');
95
+ }
96
+ if (input.globalName.length > 256) throw new OperationError('INVALID_INPUT');
97
+ if (input.pageGlobals !== undefined && (!input.pageGlobals || typeof input.pageGlobals !== 'object'
98
+ || Array.isArray(input.pageGlobals) || Object.keys(input.pageGlobals).some(key => key !== 'WIZ_global_data')
99
+ || !input.pageGlobals.WIZ_global_data || typeof input.pageGlobals.WIZ_global_data !== 'object'
100
+ || Array.isArray(input.pageGlobals.WIZ_global_data))) throw new OperationError('INVALID_INPUT');
101
+ for (const [name, limit] of [['pageHTML', 4 * 1024 * 1024], ['frameHTML', 1024 * 1024], ['experiments', 1024 * 1024], ['userAgent', 1024]]) {
102
+ if (input[name] !== undefined && (typeof input[name] !== 'string' || input[name].length > limit)) throw new OperationError('INVALID_INPUT');
103
+ }
104
+ const pageUrl = new URL(input.pageUrl || 'https://synthid.com/image-detection');
105
+ if (input.referrer !== undefined && typeof input.referrer !== 'string') throw new OperationError('INVALID_INPUT');
106
+ let referrer;
107
+ try { referrer = input.referrer === '' ? undefined : new URL(input.referrer ?? 'https://synthid.com/'); }
108
+ catch { throw new OperationError('INVALID_INPUT'); }
109
+ if (pageUrl.origin !== 'https://synthid.com' || pageUrl.username || pageUrl.password
110
+ || referrer && (referrer.origin !== 'https://synthid.com' || referrer.username || referrer.password)) throw new OperationError('INVALID_INPUT');
111
+ for (const name of ['frameUrl', 'interpreterSourceUrl']) if (input[name] !== undefined) {
112
+ const url = new URL(input[name]);
113
+ if (url.protocol !== 'https:' || !['synthid.com', 'www.google.com', 'www.gstatic.com'].includes(url.hostname)
114
+ || url.port || url.username || url.password || (name === 'frameUrl' ? typeof input.frameHTML !== 'string'
115
+ : url.hostname === 'synthid.com' || !url.pathname.startsWith('/js/'))) throw new OperationError('INVALID_INPUT');
116
+ }
117
+ return { pageUrl: pageUrl.href, referrer: referrer?.href ?? '' };
118
+ }
119
+ async function initialize(input, timeoutMs) {
120
+ if (phase !== 'empty') throw new OperationError('ALREADY_INITIALIZED');
121
+ const urls = validateInput(input);
122
+ platformFailureDiagnostics = createNodePlatformFailureDiagnostics(urls.pageUrl);
123
+ enablePointerDiagnostics = input.enablePointerDiagnostics === true;
124
+ phase = 'environment';
125
+ if (input.clockPrecision100us === true) clockPrecisionControl = (await import('./runtime-clock-precision-control.mjs')).installRuntimeClockPrecisionControl();
126
+ if (input.eventClockCompatibility === true) {
127
+ eventClockCompatibility = installEventClockCompatibility({ clockPrecision100us: input.clockPrecision100us === true });
128
+ diagnostics.eventClockCompatibility = true;
129
+ }
130
+ const virtualConsole = new VirtualConsole();
131
+ virtualConsole.on('jsdomError', error => { diagnostics.domErrors++; platformFailureDiagnostics.noteJsdomError(error); });
132
+ class SuppliedResources extends ResourceLoader {
133
+ constructor() { super(input.userAgent ? { userAgent: input.userAgent } : {}); }
134
+ fetch(url, options) {
135
+ eventListenerProbe?.noteFrame(options?.element);
136
+ if (url === input.frameUrl && typeof input.frameHTML === 'string') {
137
+ diagnostics.suppliedFrameRequests++;
138
+ return Promise.resolve(Buffer.from(input.frameHTML, 'utf8'));
139
+ }
140
+ diagnostics.refusedResources++;
141
+ platformFailureDiagnostics.noteRefusedResource(url, options);
142
+ return null;
143
+ }
144
+ }
145
+ let cookieJar;
146
+ if (input.cookieJar !== undefined) {
147
+ // JSDOM uses the same tough-cookie serialization as the parent HTTP jar.
148
+ // Cookie values are never placed in diagnostics or written to disk.
149
+ cookieJar = CookieJar.deserializeSync(input.cookieJar);
150
+ diagnostics.cookieJarProvided = true;
151
+ } else { cookieJar = new CookieJar(); diagnostics.cookieJarProvided = false; }
152
+ const pageHTML = input.pageHTML ?? '<!doctype html><html><head></head><body></body></html>';
153
+ diagnostics.pageHTMLProvided = input.pageHTML !== undefined;
154
+ diagnostics.pageHTMLBytes = Buffer.byteLength(pageHTML);
155
+ const chromeCsiModule = input.runtimeChromeCsi === true ? await import('./runtime-chrome-csi.mjs') : undefined;
156
+ dom = new JSDOM(pageHTML, {
157
+ url: urls.pageUrl, ...(urls.referrer === '' ? {} : { referrer: urls.referrer }), runScripts: 'outside-only', pretendToBeVisual: true,
158
+ virtualConsole, resources: new SuppliedResources(), cookieJar,
159
+ beforeParse(window) {
160
+ enableScriptingParsingForOutsideOnly(window);
161
+ if(chromeCsiModule) {
162
+ runtimeChromeCsi = chromeCsiModule.installRuntimeChromeCsi(window,{children:input.runtimeChildWebCompatibility===true});
163
+ diagnostics.runtimeChromeCsi = true;
164
+ }
165
+ },
166
+ });
167
+ diagnostics.documentReferrerEmpty = dom.window.document.referrer === '';
168
+ diagnostics.scriptingEnabledParsing = true;
169
+
170
+ if (enablePointerDiagnostics) eventListenerProbe = createEventListenerDiagnostics(dom.window);
171
+ context = dom.getInternalVMContext();
172
+ if (input.webidlBrandErrors === true) {
173
+ webidlBrandErrorAdapter = await import('./webidl-brand-errors-preload.mjs');
174
+ if (webidlBrandErrorAdapter.webidlBrandErrorSnapshot().changedMessages === 0) throw new OperationError('BRAND_ERROR_PRELOAD_MISSING');
175
+ }
176
+ if(input.runtimeDetachedFrameCompatibility===true && !input.clockPrecision100us) {
177
+ runtimeDetachedFrameCompatibility=(await import('./runtime-detached-frame-compat.mjs')).installRuntimeDetachedFrameCompat(dom.window);
178
+ diagnostics.runtimeDetachedFrameCompatibility=true;
179
+ }
180
+ if (input.runtimeWebCompatibility === true) {
181
+ const navigationTiming = input.performanceEntries?.find(entry => entry?.entryType === 'navigation');
182
+ const networkSample = input.runtimeNetworkCompatibility === true && navigationTiming
183
+ ? Object.fromEntries(['requestStart', 'responseStart', 'responseEnd', 'encodedBodySize', 'decodedBodySize']
184
+ .filter(key => navigationTiming[key] !== undefined).map(key => [key, navigationTiming[key]])) : undefined;
185
+ if (input.runtimeNetworkCompatibility === true && !(networkSample?.encodedBodySize > 0)) throw new OperationError('NETWORK_SAMPLE_UNAVAILABLE');
186
+ const compatibilityOptions = {
187
+ physicalMemoryBytes: totalmem(), platform: platform() === 'win32' ? 'Win32'
188
+ : platform() === 'darwin' ? 'MacIntel' : platform() === 'linux' ? (arch() === 'arm64' ? 'Linux aarch64' : 'Linux x86_64') : undefined, virtualScreen: true,
189
+ performanceTimeOriginEpochMs: input.performanceTimeOriginEpochMs, performanceEntries: input.performanceEntries,
190
+ deviceMemoryMaxGiB: 32,
191
+ virtualMouse: input.runtimeMouseMediaCompatibility === true,
192
+ clockPrecision100us: input.clockPrecision100us === true,
193
+ userActivationWebIdlCompatibility: input.userActivationWebIdlCompatibility === true,
194
+ networkSample,
195
+ };
196
+ const compatibilityModule = await import('./runtime-web-compat.mjs');
197
+ runtimeWebCompatibility = compatibilityModule.installRuntimeWebCompat(dom.window, compatibilityOptions);
198
+ if (input.userActivationWebIdlCompatibility === true) createActivationStateDiagnostic = compatibilityModule.createRuntimeUserActivationDiagnostic;
199
+ if (input.runtimeChildWebCompatibility === true) {
200
+ runtimeChildWebCompatibility = (await import('./runtime-child-web-compat.mjs')).installRuntimeChildWebCompat(compatibilityOptions);
201
+ diagnostics.runtimeChildWebCompatibility = true;
202
+ }
203
+ diagnostics.runtimeWebCompatibility = true;
204
+ diagnostics.userActivationWebIdlCompatibility = input.userActivationWebIdlCompatibility === true;
205
+ if (networkSample) diagnostics.runtimeNetworkCompatibility = 'http-sample-estimate';
206
+ diagnostics.runtimeWebApisInstalled = Array.from(runtimeWebCompatibility.installed);
207
+ }
208
+ // The retained-frame owner must capture the child's clock-adjusted rAF.
209
+ if(input.runtimeDetachedFrameCompatibility===true && input.clockPrecision100us) {
210
+ runtimeDetachedFrameCompatibility=(await import('./runtime-detached-frame-compat.mjs')).installRuntimeDetachedFrameCompat(dom.window);
211
+ diagnostics.runtimeDetachedFrameCompatibility=true;
212
+ }
213
+ if (input.runtimeNavigatorCompatibility === true) {
214
+ runtimeNavigatorCompatibility = (await import('./runtime-navigator-compat.mjs')).installRuntimeNavigatorCompat(dom.window, { children: input.runtimeChildWebCompatibility === true });
215
+ diagnostics.runtimeNavigatorCompatibility = true;
216
+ }
217
+ if (input.runtimeWindowStateCompatibility === true) {
218
+ runtimeWindowStateCompatibility = (await import('./runtime-window-state-compat.mjs')).installRuntimeWindowStateCompat(dom.window, { children: input.runtimeChildWebCompatibility === true });
219
+ diagnostics.runtimeWindowStateCompatibility = true;
220
+ }
221
+ // Capture the ordinary JSDOM interface prototypes before later compatibility
222
+ // layers replace constructor bindings with owned Proxy functions. Their
223
+ // createWindow hooks wrap this one and are disposed first.
224
+ if(input.runtimeCssProperties===true) {
225
+ runtimeCssProperties=(await import('./runtime-css-properties-compat.mjs')).installRuntimeCssPropertiesCompat(dom.window,{children:input.runtimeChildWebCompatibility===true});
226
+ diagnostics.runtimeCssProperties=true;
227
+ }
228
+ if (input.runtimeWebIdlRealmCompatibility === true) {
229
+ runtimeWebIdlRealmCompatibility = (await import('./runtime-webidl-realm-compat.mjs')).installWebIdlRealmCompat(dom.window, { children: input.runtimeChildWebCompatibility === true });
230
+ diagnostics.runtimeWebIdlRealmCompatibility = true;
231
+ }
232
+ if (input.activationStateControl === true) {
233
+ // Diagnostic state simulation, not a trusted event. Retain receiver-brand
234
+ // checks; the optional transient state uses a diagnostic five-second window.
235
+ activationTransientMs = input.activationTimingControl ? 5000 : 0;
236
+ if (createActivationStateDiagnostic) activationDiagnostic = createActivationStateDiagnostic(dom.window, activationTransientMs);
237
+ else {
238
+ activationDiagnosticSource = await readFile(new URL('./realm-activation-diagnostic.js', import.meta.url), 'utf8');
239
+ activationDiagnostic = run(activationDiagnosticSource + '(' + activationTransientMs + ')');
240
+ }
241
+ restoreActivationState = () => activationDiagnostic.dispose();
242
+ diagnostics.activationStateSimulation = true;
243
+ diagnostics.activationTimingSimulation = input.activationTimingControl === true;
244
+ }
245
+ if (input.runtimeWebIdlCallableControl === true) {
246
+ runtimeWebIdlCallableControl = (await import('./runtime-webidl-callable-control.mjs')).installWebIdlCallableControl(dom.window, { children: input.runtimeChildWebCompatibility === true });
247
+ diagnostics.runtimeWebIdlCallableControl = true;
248
+ }
249
+ if(input.javascriptBindings===true){javascriptBindings=(await import('./runtime-javascript-bindings.mjs')).installJavascriptBindings(dom.window,{children:input.runtimeChildWebCompatibility===true});diagnostics.javascriptBindings=true;}
250
+ if (input.runtimePermissionsBinding === true) {
251
+ runtimePermissionsControl = (await import('./runtime-permissions-control.mjs')).installRuntimePermissionsControl(dom.window, { children: input.runtimeChildWebCompatibility === true });
252
+ diagnostics.runtimePermissionsBinding = true;
253
+ }
254
+ if (input.runtimeAnchorHrefTranslate === true) {
255
+ runtimeAnchorHrefTranslate = (await import('./runtime-anchor-href-translate.mjs')).installRuntimeAnchorHrefTranslate(dom.window, { children: input.runtimeChildWebCompatibility === true });
256
+ diagnostics.runtimeAnchorHrefTranslate = true;
257
+ }
258
+ if (input.pageGlobals !== undefined) {
259
+ if(input.virtualFocusControl === true) {
260
+ const focusSource = await readFile(new URL('./realm-focus-diagnostic.js',import.meta.url),'utf8');
261
+ diagnostics.virtualFocusControl = JSON.parse(run('JSON.stringify('+focusSource+')'));
262
+ if(!diagnostics.virtualFocusControl.after || !diagnostics.virtualFocusControl.attributeRestored) throw new OperationError('VIRTUAL_FOCUS_FAILED');
263
+ }
264
+ run('globalThis.WIZ_global_data = JSON.parse(' + JSON.stringify(JSON.stringify(input.pageGlobals.WIZ_global_data)) + ')');
265
+ diagnostics.pageGlobalsProvided = true;
266
+ }
267
+ if (input.runtimePrivateBootstrapState !== true) run('globalThis.__input = ' + JSON.stringify({ program: input.program, globalName: input.globalName, experiments: input.experiments }));
268
+ phase = 'interpreter';
269
+ new Script(input.interpreter, { filename: input.interpreterSourceUrl ?? 'google-botguard-interpreter.js' }).runInContext(context, { timeout: SYNC_TIMEOUT });
270
+ phase = 'initialize';
271
+ const setup = await readFile(new URL('./realm-init.js', import.meta.url), 'utf8');
272
+ await bounded(run(setup), timeoutMs);
273
+ initializedAt = Date.now(); phase = 'ready';
274
+ return inspect();
275
+ }
276
+ async function snapshot(blobref, timeoutMs) {
277
+ if (phase !== 'ready') throw new OperationError('NOT_READY');
278
+ if (typeof blobref !== 'string' || !blobref.startsWith('/synthid-demo-drop-zone/ttl_1d/users/') || blobref.length > 2048 || /[\r\n\0]/.test(blobref)) throw new OperationError('INVALID_BLOBREF');
279
+ phase = 'snapshot';
280
+ // Preserve unbound callback invocation and the official four-element input.
281
+ const pendingToken = run('globalThis.__ready.then(() => new Promise(resolve => { const snapshot = globalThis.__snapshot; snapshot(resolve, [{blobref:' + JSON.stringify(blobref) + '}, undefined, undefined, undefined]); }))');
282
+ const token = await bounded(pendingToken, timeoutMs);
283
+ snapshotCount++; phase = 'ready';
284
+ if (typeof token !== 'string' || token.length > 512 * 1024 || !/^![\x21-\x7e]+$/.test(token)) return { ...inspect(), success: false, code: 'INVALID_TOKEN' };
285
+ return { ...inspect(), bgToken: token };
286
+ }
287
+ async function dispatchPointerDiagnostics(timeoutMs) {
288
+ if (phase !== 'ready') throw new OperationError('NOT_READY');
289
+ if (!enablePointerDiagnostics) throw new OperationError('POINTER_DIAGNOSTICS_DISABLED');
290
+ phase = 'pointerDiagnostics';
291
+ const deadline = Date.now() + timeoutMs;
292
+ const remaining = () => {
293
+ const milliseconds = deadline - Date.now();
294
+ if (milliseconds <= 0) throw new OperationError('OPERATION_TIMEOUT');
295
+ return milliseconds;
296
+ };
297
+ let installed = false, interval;
298
+ const eventListenersBefore = eventListenerProbe?.snapshot();
299
+ try {
300
+ const setup = await bounded(readFile(new URL('./realm-pointer-diagnostic.js', import.meta.url), 'utf8'), remaining());
301
+ run('if (Object.prototype.hasOwnProperty.call(globalThis, "__synthidPointerDiagnosticControl")) throw Error("POINTER_DIAGNOSTIC_COLLISION");' +
302
+ 'Object.defineProperty(globalThis, "__synthidPointerDiagnosticControl", { configurable: true, value: ' + setup + ' });');
303
+ installed = true;
304
+ for (let index = 0; index < 4; index++) {
305
+ if (index) await bounded(new Promise(resolve => { interval = setTimeout(resolve, 120); }), remaining());
306
+ remaining();
307
+ run('globalThis.__synthidPointerDiagnosticControl.step(' + index + ')');
308
+ remaining();
309
+ }
310
+ const encoded = run('JSON.stringify(globalThis.__synthidPointerDiagnosticControl.close())');
311
+ if (typeof encoded !== 'string' || encoded.length > 4096) throw new OperationError('POINTER_DIAGNOSTIC_FAILURE');
312
+ const raw = JSON.parse(encoded);
313
+ const booleans = ['diagnosticOnly', 'synthetic', 'mouseEventConstructorAvailable', 'listenerInstalled', 'listenerRemoved'];
314
+ const counters = ['requestedMoves', 'constructedEvents', 'constructedTrusted', 'constructedUntrusted', 'dispatchCalls',
315
+ 'dispatchedEvents', 'uncancelledDispatches', 'observedEvents', 'observedTrusted', 'observedUntrusted'];
316
+ if (booleans.some(key => typeof raw[key] !== 'boolean') || counters.some(key => !Number.isInteger(raw[key]) || raw[key] < 0 || raw[key] > 4)) throw new OperationError('POINTER_DIAGNOSTIC_FAILURE');
317
+ const pointerDiagnostics = Object.fromEntries([...booleans, ...counters].map(key => [key, raw[key]]));
318
+ phase = 'ready';
319
+ return { ...inspect(), eventListenersBefore, pointerDiagnostics };
320
+ } finally {
321
+ clearTimeout(interval);
322
+ if (installed && context) {
323
+ try { run('try { globalThis.__synthidPointerDiagnosticControl.close(); } finally { delete globalThis.__synthidPointerDiagnosticControl; }'); } catch {}
324
+ }
325
+ }
326
+ }
327
+ async function handle(request) {
328
+ if (!request || request.version !== VERSION || !Number.isSafeInteger(request.id) || request.id < 1
329
+ || !['init', 'snapshot', 'pointerDiagnostics', 'inspect', 'dispose'].includes(request.op)) throw new OperationError('INVALID_PROTOCOL');
330
+ let result;
331
+ if (request.op === 'init') result = await initialize(request.input, timeoutFor(request, 20000));
332
+ if (request.op === 'snapshot') result = await snapshot(request.blobref, timeoutFor(request, 15000));
333
+ if (request.op === 'pointerDiagnostics') result = await dispatchPointerDiagnostics(timeoutFor(request, 5000));
334
+ if (request.op === 'inspect') result = inspect();
335
+ if (request.op === 'dispose') { stopping = true; result = await shutdown(timeoutFor(request, 2000)); }
336
+ await send({ id: request.id, ok: true, result });
337
+ if (stopping) process.exit(0);
338
+ }
339
+ let queue = Promise.resolve();
340
+ process.stdin.setEncoding('utf8');
341
+ process.stdin.on('data', chunk => {
342
+ if (stopping) return;
343
+ inputBuffer += chunk;
344
+ if (Buffer.byteLength(inputBuffer) > MAX_INPUT_BYTES) { stopping = true; closeDom(); process.exit(1); }
345
+ let end;
346
+ while ((end = inputBuffer.indexOf('\n')) !== -1) {
347
+ const line = inputBuffer.slice(0, end); inputBuffer = inputBuffer.slice(end + 1);
348
+ queue = queue.then(async () => {
349
+ if (stopping) return;
350
+ let request;
351
+ try { request = JSON.parse(line); await handle(request); }
352
+ catch (error) {
353
+ const failedPhase = phase;
354
+ const fatal = !(error instanceof OperationError) || !['ALREADY_INITIALIZED', 'NOT_READY', 'INVALID_INPUT', 'INVALID_BLOBREF', 'POINTER_DIAGNOSTICS_DISABLED'].includes(error.code);
355
+ if (fatal) { stopping = true; closeDom(); }
356
+ await send({ id: Number.isSafeInteger(request?.id) ? request.id : 0, ok: false, error: { code: error instanceof OperationError ? error.code : 'INTERPRETER_FAILURE', phase: failedPhase, errorType: ['Error', 'TypeError', 'RangeError', 'SyntaxError'].includes(error?.name) ? error.name : 'unknown' } });
357
+ if (fatal) process.exit(1);
358
+ }
359
+ });
360
+ }
361
+ });
362
+ process.stdin.on('end', () => { queue.finally(async () => { if (!stopping) { stopping = true; await shutdown(500); process.exit(0); } }); });
363
+ process.stdin.on('error', () => { stopping = true; closeDom(); process.exit(1); });
@@ -0,0 +1,108 @@
1
+ import {types} from 'node:util';
2
+ import {URL as NativeURL} from 'node:url';
3
+ import ElementModule from 'jsdom/lib/jsdom/living/nodes/Element-impl.js';
4
+ import utils from 'jsdom/lib/jsdom/living/generated/utils.js';
5
+ import jsdomPackage from 'jsdom/package.json' with {type:'json'};
6
+
7
+ const get=Object.getOwnPropertyDescriptor,prototypeOf=Object.getPrototypeOf,own=Object.hasOwn,isProxy=types.isProxy;
8
+ const object=value=>value!==null&&(typeof value==='object'||typeof value==='function');
9
+ const data=(value,key)=>{
10
+ if(!object(value)||isProxy(value))return undefined;
11
+ const descriptor=get(value,key);return descriptor&&own(descriptor,'value')?descriptor.value:undefined;
12
+ };
13
+ const ERROR_CATEGORIES=Object.freeze(['navigation-not-implemented','canvas-not-implemented','other-not-implemented',
14
+ 'resource-loading','css-parsing','unhandled-exception','other']);
15
+ const SCHEMES=Object.freeze(['http','https','data','about','blob','file','javascript','other','invalid']);
16
+ const RELATIONS=Object.freeze(['same-origin','cross-origin','not-http','unknown']);
17
+ const ELEMENT_KINDS=Object.freeze(['iframe','frame','link','script','img','audio','video','source','object','embed','other','unknown']);
18
+ const ELEMENT_NAMES=new Set(ELEMENT_KINDS.slice(0,-2));
19
+ const LIMIT=1000000,MAX_URL_LENGTH=16384,MAX_MESSAGE_LENGTH=65536,MAX_PROTOTYPE_DEPTH=16;
20
+ const MAX_BUCKETS=SCHEMES.length*RELATIONS.length*ELEMENT_KINDS.length;
21
+ const HTML_NAMESPACE='http://www.w3.org/1999/xhtml';
22
+
23
+ function classifyElement(options){
24
+ const wrapper=data(options,'element'),impl=data(wrapper,utils.implSymbol);
25
+ if(!object(impl)||isProxy(impl)||data(impl,utils.wrapperSymbol)!==wrapper)return 'unknown';
26
+ let current=impl,matched=false;
27
+ for(let depth=0;object(current)&&depth<MAX_PROTOTYPE_DEPTH;depth++){
28
+ if(isProxy(current))return 'unknown';
29
+ if(current===ElementModule.implementation.prototype){matched=true;break;}
30
+ current=prototypeOf(current);
31
+ }
32
+ if(!matched)return 'unknown';
33
+ const name=data(impl,'_localName'),namespace=data(impl,'_namespaceURI');
34
+ if(typeof name!=='string'||typeof namespace!=='string')return 'unknown';
35
+ return namespace===HTML_NAMESPACE&&ELEMENT_NAMES.has(name)?name:'other';
36
+ }
37
+
38
+ /** Synchronous observations only: no listeners, requests, mutations or clocks.
39
+ * Root calls these inside its existing error handler/refused-resource branch.
40
+ * Aggregate buckets contain only fixed labels; no input object is retained. */
41
+ export function createNodePlatformFailureDiagnostics(pageUrl){
42
+ if(jsdomPackage.version!=='26.1.0')throw Error('PLATFORM_FAILURE_UNSUPPORTED_JSDOM');
43
+ let pageOrigin;
44
+ try{
45
+ if(typeof pageUrl!=='string'||pageUrl.length>MAX_URL_LENGTH)throw Error();
46
+ const parsed=new NativeURL(pageUrl);
47
+ if(parsed.protocol!=='http:'&&parsed.protocol!=='https:')throw Error();
48
+ pageOrigin=parsed.origin;
49
+ }catch{throw TypeError('PLATFORM_FAILURE_INVALID_PAGE_URL');}
50
+ const errors={total:0,byCategory:Object.fromEntries(ERROR_CATEGORIES.map(key=>[key,0])),
51
+ proxyInputsIgnored:0,typeUnavailable:0,messageUnavailable:0};
52
+ const resources={total:0,invalidUrlInputs:0,unknownElements:0};
53
+ const buckets=new Map();let limitReached=false;
54
+ const increment=(target,key)=>{if(target[key]<LIMIT)target[key]++;else limitReached=true;};
55
+ function noteJsdomError(error){
56
+ if(errors.total>=LIMIT){limitReached=true;return;}
57
+ increment(errors,'total');let category='other';
58
+ try{
59
+ if(object(error)&&isProxy(error))increment(errors,'proxyInputsIgnored');
60
+ const type=data(error,'type');
61
+ if(typeof type!=='string')increment(errors,'typeUnavailable');
62
+ else if(type==='not implemented'){
63
+ category='other-not-implemented';
64
+ const message=data(error,'message');
65
+ if(typeof message!=='string'||message.length>MAX_MESSAGE_LENGTH)increment(errors,'messageUnavailable');
66
+ else if(message.startsWith('Not implemented: navigation (except hash changes)'))category='navigation-not-implemented';
67
+ else if(message.startsWith('Not implemented: HTMLCanvasElement.prototype.'))category='canvas-not-implemented';
68
+ }else if(type==='resource loading')category='resource-loading';
69
+ else if(type==='css parsing'||type==='css @import URL parsing')category='css-parsing';
70
+ else if(type==='unhandled exception')category='unhandled-exception';
71
+ }catch{category='other';}
72
+ increment(errors.byCategory,category);
73
+ }
74
+ function noteRefusedResource(url,options){
75
+ if(resources.total>=LIMIT){limitReached=true;return;}
76
+ increment(resources,'total');
77
+ let scheme='invalid',httpOriginRelation='unknown',elementKind='unknown';
78
+ try{
79
+ if(typeof url!=='string'||url.length>MAX_URL_LENGTH)throw Error();
80
+ // JSDOM passes absolute resolved resource URLs. Relative or invalid inputs
81
+ // remain unknown; the diagnostic does not reinterpret the loader's target.
82
+ const parsed=new NativeURL(url),protocol=parsed.protocol.slice(0,-1);
83
+ scheme=SCHEMES.includes(protocol)&&protocol!=='invalid'?protocol:'other';
84
+ httpOriginRelation=scheme==='http'||scheme==='https'
85
+ ?(parsed.origin===pageOrigin?'same-origin':'cross-origin'):'not-http';
86
+ }catch{increment(resources,'invalidUrlInputs');}
87
+ try{elementKind=classifyElement(options);}catch{}
88
+ if(elementKind==='unknown')increment(resources,'unknownElements');
89
+ // This key is composed exclusively of three fixed enums, never URL text or
90
+ // an element name supplied by page code. Maximum cardinality is fixed.
91
+ const key=scheme+'|'+httpOriginRelation+'|'+elementKind;
92
+ let bucket=buckets.get(key);
93
+ if(!bucket){
94
+ if(buckets.size>=MAX_BUCKETS){limitReached=true;return;}
95
+ bucket={scheme,httpOriginRelation,elementKind,count:0};buckets.set(key,bucket);
96
+ }
97
+ increment(bucket,'count');
98
+ }
99
+ function snapshot(){
100
+ return{schemaVersion:1,diagnosticOnly:true,pinnedJsdomVersion:'26.1.0',
101
+ counterLimit:LIMIT,maximumResourceBuckets:MAX_BUCKETS,limitReached,
102
+ errorMessagesRecorded:false,errorStacksRecorded:false,urlsRecorded:false,inputObjectsRetained:false,
103
+ listenersInstalled:false,resourceDecisionsModified:false,
104
+ errors:{...errors,byCategory:{...errors.byCategory}},
105
+ refusedResources:{...resources,buckets:[...buckets.values()].map(bucket=>({...bucket}))}};
106
+ }
107
+ return Object.freeze({noteJsdomError,noteRefusedResource,snapshot});
108
+ }
@@ -0,0 +1,31 @@
1
+ (function installActivationDiagnostic(transientMs = 0, clock = () => performance.now()) {
2
+ if (![0, 5000].includes(transientMs) || typeof clock !== 'function') throw Error('INVALID_ACTIVATION_CONTROL');
3
+ const prototype = Object.getPrototypeOf(navigator.userActivation);
4
+ const previous = Object.fromEntries(['hasBeenActive','isActive'].map(key=>[key,Object.getOwnPropertyDescriptor(prototype,key)]));
5
+ if (Object.values(previous).some(value=>!value?.get || !value.configurable)) throw Error('ACTIVATION_STATE_UNAVAILABLE');
6
+ let startedAt = clock();
7
+ const apply = Reflect.apply;
8
+ let disposed = false;
9
+ const getters = {
10
+ get hasBeenActive() { apply(previous.hasBeenActive.get, this, []); return true; },
11
+ get isActive() { apply(previous.isActive.get, this, []); return transientMs > 0 && clock() - startedAt < transientMs; },
12
+ };
13
+ const installed = {};
14
+ for (const key of Object.keys(previous)) {
15
+ installed[key] = {...previous[key],get:Object.getOwnPropertyDescriptor(getters,key).get};
16
+ Object.defineProperty(prototype,key,installed[key]);
17
+ }
18
+ return {
19
+ // Explicit experiment control; this does not create a trusted DOM event.
20
+ activate() {
21
+ if (disposed) throw Error('ACTIVATION_CONTROL_DISPOSED');
22
+ startedAt = clock();
23
+ return { diagnosticOnly:true, sticky:true, transient:transientMs>0, transientMs, disposed:false };
24
+ },
25
+ snapshot() { return {diagnosticOnly:true,sticky:true,transient:transientMs>0 && clock()-startedAt<transientMs,transientMs,disposed}; },
26
+ dispose() {
27
+ if(disposed) return; disposed=true;
28
+ for(const key of Object.keys(previous)) if(Object.getOwnPropertyDescriptor(prototype,key)?.get===installed[key].get) Object.defineProperty(prototype,key,previous[key]);
29
+ },
30
+ };
31
+ })
@@ -0,0 +1,9 @@
1
+ (() => {
2
+ const body = document.body;
3
+ if (!body) throw Error('FOCUS_CONTROL_UNAVAILABLE');
4
+ const before = document.hasFocus();
5
+ const tabindex = body.getAttribute('tabindex');
6
+ try { body.setAttribute('tabindex','-1'); body.focus({preventScroll:true}); }
7
+ finally { if(tabindex===null) body.removeAttribute('tabindex'); else body.setAttribute('tabindex',tabindex); }
8
+ return {diagnosticOnly:true,virtualDocumentFocus:true,before,after:document.hasFocus(),bodyActive:document.activeElement===body,attributeRestored:body.getAttribute('tabindex')===tabindex};
9
+ })()
@@ -0,0 +1,34 @@
1
+ globalThis.__metrics = { errors: [] };
2
+ globalThis.__ready = new Promise((resolve, reject) => {
3
+ const input = globalThis.__input;
4
+ const vm = globalThis[input.globalName];
5
+ if (!vm || typeof vm.a !== 'function') throw new Error('interpreter unavailable');
6
+ const state = input.experiments ? JSON.parse(input.experiments) : [];
7
+ if (!Array.isArray(state)) throw new Error('experiment state');
8
+ const entries = state[5] || [];
9
+ if (!Array.isArray(entries) || entries.some(item => !Array.isArray(item))) throw new Error('experiment entries');
10
+ const int32 = value => {
11
+ if (typeof value !== 'number' && (typeof value !== 'string' || !value.trim())) return 0;
12
+ const number = Number(value);
13
+ return Number.isFinite(number) ? number | 0 : 0;
14
+ };
15
+ const first = entries.filter(item => int32(item[1]) <= 53).map(item => int32(item[0]));
16
+ const second = entries.filter(item => int32(item[1]) > 53).map(item => int32(item[0]));
17
+ const values = first.concat(second);
18
+ const kinds = first.map(() => 1).concat(second.map(() => 2));
19
+ __metrics.experimentCount = values.length;
20
+ __metrics.stateField5 = typeof state[4] === 'string';
21
+ const init = vm.a;
22
+ init(input.program, (snapshot, shutdown) => {
23
+ if (typeof snapshot !== 'function') { reject(new Error('snapshot unavailable')); return; }
24
+ Promise.resolve().then(() => {
25
+ globalThis.__snapshot = snapshot;
26
+ globalThis.__shutdown = shutdown;
27
+ resolve(true);
28
+ });
29
+ }, true, undefined, () => {}, [values, kinds], typeof state[4] === 'string' ? state[4] : '', false, [
30
+ () => {}, value => { if (__metrics.errors.length < 20 && typeof value === 'number') __metrics.errors.push(value); },
31
+ () => {}, () => {},
32
+ ], undefined);
33
+ });
34
+ __ready;
@@ -0,0 +1,49 @@
1
+ // Evaluated only by an explicitly enabled diagnostic operation. Standard DOM
2
+ // constructor/dispatch semantics are retained, including isTrusted === false.
3
+ (() => {
4
+ const Constructor = globalThis.__synthidPlatformMouseEventConstructor || globalThis.MouseEvent;
5
+ const target = document.body;
6
+ if (typeof Constructor !== 'function' || !target) throw Error('POINTER_DIAGNOSTIC_UNAVAILABLE');
7
+ const width = window.innerWidth, height = window.innerHeight;
8
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width < 2 || height < 2) throw Error('POINTER_DIAGNOSTIC_UNAVAILABLE');
9
+ const counts = { diagnosticOnly: true, synthetic: true, mouseEventConstructorAvailable: true,
10
+ requestedMoves: 4, constructedEvents: 0, constructedTrusted: 0, constructedUntrusted: 0,
11
+ dispatchCalls: 0, dispatchedEvents: 0, uncancelledDispatches: 0, observedEvents: 0,
12
+ observedTrusted: 0, observedUntrusted: 0, listenerInstalled: false, listenerRemoved: false };
13
+ const issued = new WeakSet();
14
+ let closed = false;
15
+ const listener = event => {
16
+ if (!issued.has(event)) return;
17
+ counts.observedEvents++;
18
+ if (event.isTrusted === true) counts.observedTrusted++;
19
+ else if (event.isTrusted === false) counts.observedUntrusted++;
20
+ };
21
+ target.addEventListener('mousemove', listener, { capture: true, passive: true });
22
+ counts.listenerInstalled = true;
23
+ return {
24
+ step(index) {
25
+ if (closed || !Number.isInteger(index) || index !== counts.constructedEvents || index > 3) throw Error('POINTER_DIAGNOSTIC_SEQUENCE');
26
+ // Four reproducible viewport-relative points; no coordinates leave realm.
27
+ const [x, y] = [[0.07, 0.53], [0.11, 0.61], [0.15, 0.69], [0.09, 0.76]][index];
28
+ const event = new Constructor('mousemove', { bubbles: true, cancelable: true, composed: true,
29
+ view: window, detail: 0, button: 0, buttons: 0, altKey: false, ctrlKey: false, metaKey: false, shiftKey: false,
30
+ clientX: Math.round(width * x), clientY: Math.round(height * y) });
31
+ issued.add(event);
32
+ counts.constructedEvents++;
33
+ if (event.isTrusted === true) counts.constructedTrusted++;
34
+ else if (event.isTrusted === false) counts.constructedUntrusted++;
35
+ counts.dispatchCalls++;
36
+ const platformDispatch = globalThis.__synthidPlatformDispatchEvent;
37
+ if (platformDispatch ? platformDispatch(target, event) : target.dispatchEvent(event)) counts.uncancelledDispatches++;
38
+ counts.dispatchedEvents++;
39
+ },
40
+ close() {
41
+ if (!closed) {
42
+ closed = true;
43
+ target.removeEventListener('mousemove', listener, { capture: true });
44
+ counts.listenerRemoved = true;
45
+ }
46
+ return { ...counts };
47
+ },
48
+ };
49
+ })()