-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
590 lines (505 loc) · 24 KB
/
app.js
File metadata and controls
590 lines (505 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// app.js
import { DEFAULT_BLOCKLIST, EXTRA_EXCLUDE_KEYWORDS } from './diffalgorithm/degdiff.js';
const inclusionSel = document.querySelector('#inclusion');
const fileSel = document.querySelector('#filetype');
const diffSel = document.querySelector('#difference');
const runBtn = document.querySelector('#run');
const dl0 = document.querySelector('#dl0');
const dl1 = document.querySelector('#dl1');
const downloads = document.querySelector('#downloads');
const diffPreview = document.querySelector('#diffPreview');
const autoClose = document.querySelector('#autoclose');
const bust = document.querySelector('#bust');
const applyBlocklist = document.querySelector('#applyBlocklist');
const windowMode = document.querySelector('#windowMode');
//sandbox controls
const sandboxOpenBtn = document.querySelector('#sandbox-open');
const sandboxStatus = document.querySelector('#sandbox-status');
const sandboxS0Vendor = document.querySelector('#sandbox-s0-vendor');
const sandboxS1Vendor = document.querySelector('#sandbox-s1-vendor');
const sandboxCopy0Vendor = document.querySelector('#sandbox-copy0-vendor');
const sandboxCopy1Vendor = document.querySelector('#sandbox-copy1-vendor');
const sandboxPaste0 = document.querySelector('#sandbox-paste0');
const sandboxPaste1 = document.querySelector('#sandbox-paste1');
const tabsEl = document.querySelector('#tabs');
const panelsEl = document.querySelector('#panels');
const TESTCONFIG_FILES = [
'config.json','csv-export.json','default.json','top200-500.json',
'top200.json','veryhax_test.json','wpt-header.json',
];
let diffMap = new Map();
const LaunchMeta = new Map();
const Jobs = new Map();
async function registerSW() {
if (!('serviceWorker' in navigator)) return;
const reg = await navigator.serviceWorker.register('./sw.js', { scope: './' });
await navigator.serviceWorker.ready;
if (!navigator.serviceWorker.controller) {
await new Promise(r => navigator.serviceWorker.addEventListener('controllerchange', () => r(), { once: true }));
}
return reg;
}
function setDiffWithAck(diffObj) {
return new Promise((resolve) => {
const mc = new MessageChannel();
mc.port1.onmessage = (ev) => {
if (ev.data && ev.data.type === 'DIFF_SET') resolve();
};
navigator.serviceWorker.controller?.postMessage({ type: 'SET_DIFF', diff: diffObj }, [mc.port2]);
setTimeout(resolve, 400);
});
}
async function loadDifferences() {
const all = [];
for (const f of TESTCONFIG_FILES) {
try {
const res = await fetch(`./testconfigs/${f}`, { cache: 'no-store' });
if (!res.ok) continue;
const j = await res.json();
if (Array.isArray(j.differences)) all.push(...j.differences);
} catch {}
}
diffMap = new Map(all.map(d => [d.name, d]));
const names = [...diffMap.keys()].sort((a,b)=>a.localeCompare(b));
diffSel.innerHTML = names.map(n => `<option>${n}</option>`).join('');
if (names.length) diffPreview.textContent = JSON.stringify(diffMap.get(names[0]), null, 2);
}
//INPUT SANITIZATION
function sanitizeGraph(raw) {
if (!raw || typeof raw !== 'object') return raw;
//use JSON clone for very large graphs (safer memory profile)
let out;
try { out = structuredClone(raw); } catch { out = JSON.parse(JSON.stringify(raw)); }
let nodes = Array.isArray(out.nodes) ? out.nodes
: (Array.isArray(out.graph?.nodes) ? out.graph.nodes : []);
let edges = Array.isArray(out.edges) ? out.edges
: (Array.isArray(out.graph?.edges) ? out.graph.edges : []);
if (!Array.isArray(nodes)) nodes = [];
if (!Array.isArray(edges)) edges = [];
const isVenNode = (n) => {
const nt = String(n?.nodetype ?? '').toUpperCase();
const isVenFlag = (n?.isVEN === true) || (String(n?.isVEN).toLowerCase() === 'true');
const typeIsVEN = String(n?.type) === 'Virtual Entry Node';
return nt === 'VEN' || isVenFlag || typeIsVEN;
};
let venIdxs = [];
for (let i = 0; i < nodes.length; i++) if (isVenNode(nodes[i])) venIdxs.push(i);
if (venIdxs.length === 0) {
let idx = nodes.findIndex(n => String(n?.nodeid) === '0' || n?.traversalLevel === -1);
if (idx < 0) idx = nodes.length ? 0 : -1;
if (idx >= 0) {
nodes[idx].nodetype = 'VEN';
nodes[idx].isVEN = true;
nodes[idx].type = 'Virtual Entry Node';
venIdxs = [idx];
} else {
nodes = [{ nodeid: '0', nodetype: 'VEN', nodevalue: 'VEN', isVEN: true, traversalLevel: -1, name: '0', type: 'Virtual Entry Node' }];
venIdxs = [0];
}
} else if (venIdxs.length > 1) {
for (let j = 1; j < venIdxs.length; j++) {
const n = nodes[venIdxs[j]];
if (!n) continue;
n.isVEN = false;
if (String(n.nodetype).toUpperCase() === 'VEN') n.nodetype = 'object';
if (n.type === 'Virtual Entry Node') n.type = 'Object';
}
} else {
const n = nodes[venIdxs[0]];
n.nodetype = 'VEN';
n.isVEN = true;
n.type = 'Virtual Entry Node';
}
out.nodes = nodes;
out.edges = edges;
if (!out.graph) out.graph = {};
out.graph.nodes = nodes;
out.graph.edges = edges;
return out;
}
function normalizeIncoming(data) {
if (!data) return null;
const validType = ['CRAWL_RESULT','GRAPH','RESULT','CRAWLER_RESULT'].includes(data.type);
if (!validType) {
//accept bare graph via manual paste
const guess = { sid: null, state: null, graph: data };
if (guess.graph && (Array.isArray(guess.graph.nodes) || Array.isArray(guess.graph.graph?.nodes))) return guess;
return null;
}
const sid = data.sid || data.sessionId || data.channel || data.jobId || null;
let stateRaw = data.state ?? data.runState ?? data.which ?? data.index;
if (stateRaw === 'state0') stateRaw = 0;
if (stateRaw === 'state1') stateRaw = 1;
const state = Number(stateRaw);
const normState = Number.isFinite(state) && (state === 0 || state === 1) ? state : null;
let graph = data.graph ?? data.graphJson ?? data.json ?? data.payload?.graph;
if (!graph) return null;
if (typeof graph === 'string') {
try { graph = JSON.parse(graph); } catch {}
}
if (typeof graph !== 'object') return null;
return { sid, state: normState, graph };
}
function updateTabReadiness(sid) {
const job = Jobs.get(sid);
const btn = document.getElementById(job?.tabId || '');
if (!btn) return;
const small = btn.querySelector('.small');
if (!small) return;
const s0 = job?.state0 ? '✓' : '…';
const s1 = job?.state1 ? '✓' : '…';
small.textContent = ` • s0 ${s0} s1 ${s1}`;
}
function handleResult(raw) {
const norm = normalizeIncoming(raw);
if (!norm) return;
let { sid, state, graph } = norm;
//when pasting a bare graph, ask which run and state to attach to
if (!sid || state === null) {
const sandboxSids = [...Jobs.keys()].filter(k => k.startsWith('sandbox_'));
if (!sid) {
if (sandboxSids.length === 1) sid = sandboxSids[0];
else {
const pick = prompt(`Multiple sandbox runs detected.\nAvailable: \n${sandboxSids.join('\n')}\n\nEnter SID to attach this graph to:`);
if (!pick) return;
sid = pick.trim();
}
}
if (state === null) {
const s = prompt('Enter state to attach to (0 or 1):', '0');
if (s !== '0' && s !== '1') return;
state = Number(s);
}
}
graph = sanitizeGraph(graph);
let job = Jobs.get(sid);
if (!job) { job = {}; Jobs.set(sid, job); }
if (!job.tabId || !job.panelId) {
const meta = LaunchMeta.get(sid) || { inc: '(?)', file: '(?)', diffName: '(?)' };
const title = `${meta.inc} | ${meta.file} | ${meta.diffName}`;
ensureTabAndPanelForSid(sid, title, job);
}
job[`state${state}`] = graph;
updateTabReadiness(sid);
const blob = new Blob([JSON.stringify(graph, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const fileName = `${sid}-state${state}.json`;
if (state === 0) { dl0.href = url; dl0.download = fileName; dl0.classList.remove('disabled'); }
else { dl1.href = url; dl1.download = fileName; dl1.classList.remove('disabled'); }
downloads.classList.remove('hidden');
const panel = document.getElementById(job.panelId);
if (panel) {
if (state === 0) panel.querySelector(`#pdl0-${sid}`).href = url;
else panel.querySelector(`#pdl1-${sid}`).href = url;
}
if (job.state0 && job.state1 && !job.worker) {
computeDiffInWorker(sid, job);
}
}
window.addEventListener('message', (ev) => handleResult(ev.data));
async function run() {
const inc = inclusionSel.value.trim();
const file = fileSel.value.trim();
const diffName = diffSel.value.trim();
if (!inc || !file || !diffName) return alert('Please select inclusion method, file type, and difference.');
const asWindow = windowMode && windowMode.checked;
const features = 'width=620,height=520,menubar=0,toolbar=0,location=0,status=0,resizable=1,scrollbars=1';
let w0, w1;
if (asWindow) {
//open as regular browser windows/tabs
w0 = window.open('about:blank', '_domdiff_state0');
w1 = window.open('about:blank', '_domdiff_state1');
} else {
//og small popup behavior
w0 = window.open('about:blank', '_domdiff_state0', features);
w1 = window.open('about:blank', '_domdiff_state1', features);
}
if (!w0 || !w1) { alert('Popups were blocked. Allow popups for this page and click Run again.'); return; }
const sid = `domdiff_${Date.now()}_${Math.random().toString(36).slice(2)}`;
LaunchMeta.set(sid, { inc, file, diffName });
const bc = new BroadcastChannel(sid);
bc.onmessage = (ev) => handleResult(ev.data);
const cb = bust.checked ? `&cb=${Date.now()}` : '';
const ac = autoClose.checked ? '&autoclose=1' : '&autoclose=0';
const base = `./popup/runner.html?inc=${encodeURIComponent(inc)}&file=${encodeURIComponent(file)}&diff=${encodeURIComponent(diffName)}&sid=${encodeURIComponent(sid)}${cb}${ac}`;
const diffObj = diffMap.get(diffName);
await setDiffWithAck(diffObj);
try { w0.location.href = base + '&state=0'; } catch {}
try { w1.location.href = base + '&state=1'; } catch {}
}
runBtn.addEventListener('click', run);
function ensureTabAndPanelForSid(sid, title, job) {
if (job.tabId && job.panelId) return;
const tabId = `tab-${sid}`;
const panelId = `panel-${sid}`;
const btn = document.createElement('button');
btn.className = 'tab';
btn.id = tabId;
btn.textContent = title;
const small = document.createElement('span');
small.className = 'small';
small.textContent = ' • s0 … s1 …';
btn.appendChild(small);
btn.addEventListener('click', () => activateTab(sid));
tabsEl.appendChild(btn);
const panel = document.createElement('div');
panel.className = 'tabpanel';
panel.id = panelId;
panel.innerHTML = `
<div class="panel-tools">
<a class="btn" id="exp-${sid}" download="diff_paths.csv">Export CSV</a>
<span class="sep">|</span>
<a class="btn" id="pdl0-${sid}" download="state0.json">Download State 0</a>
<a class="btn" id="pdl1-${sid}" download="state1.json">Download State 1</a>
<span id="stats-${sid}" class="meta">Waiting for both graphs…</span>
</div>
<div id="tags-${sid}" class="config-tags-inline hidden"></div>
<div id="table-${sid}" class="table"><div class="meta">Waiting for both graphs…</div></div>
`;
panelsEl.appendChild(panel);
job.tabId = tabId;
job.panelId = panelId;
activateTab(sid);
}
function activateTab(sid) {
const job = Jobs.get(sid);
if (!job) return;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tabpanel').forEach(p => p.classList.remove('active'));
document.getElementById(job.tabId)?.classList.add('active');
document.getElementById(job.panelId)?.classList.add('active');
//show tab's tags in the global bar, might change later
const tags = Array.isArray(job.configTags) ? job.configTags : [];
window.dispatchEvent(new CustomEvent('show-config-tags', { detail: { sid, tags } }));
}
//PROGRESSIVE DIFF RENDERING
function buildExcludeKeywords() {
if (applyBlocklist && applyBlocklist.checked) {
return [...DEFAULT_BLOCKLIST, ...EXTRA_EXCLUDE_KEYWORDS];
}
return [];
}
function appendRowsToTable(sid, newRows) {
const panel = document.getElementById(Jobs.get(sid).panelId);
let table = panel.querySelector('table');
if (!table) {
panel.querySelector(`#table-${sid}`).innerHTML = '<table><thead><tr><th>Path</th><th>State 0</th><th>State 1</th></tr></thead><tbody></tbody></table>';
table = panel.querySelector('table');
}
const tbody = table.querySelector('tbody');
const frag = document.createDocumentFragment();
for (const r of newRows) {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${escapeHtml(r.path)}</td><td>${escapeHtml(r.s0)}</td><td>${escapeHtml(r.s1)}</td>`;
frag.appendChild(tr);
}
tbody.appendChild(frag);
}
function progressiveRenderFinalRows(sid, rows, stats, configTags) {
const CHUNK = 250;
let i = 0;
const updateStats = () => {
const tbody = document.querySelector(`#panel-${sid} tbody`);
const count = tbody ? tbody.children.length : rows.length;
document.getElementById(`stats-${sid}`)?.replaceChildren(document.createTextNode(
`Paths with diffs: ${count} • Roots of change: ${stats.roots}`
));
};
const step = () => {
if (i >= rows.length) { updateStats(); return; }
const slice = rows.slice(i, i + CHUNK);
appendRowsToTable(sid, slice);
i += CHUNK;
updateStats();
setTimeout(step, 0);
};
const jobRef = Jobs.get(sid);
if (jobRef) jobRef.configTags = configTags || jobRef.configTags || [];
const tagHost = document.querySelector(`#panel-${sid} #tags-${sid}`);
if (tagHost && configTags?.length) {
tagHost.innerHTML = configTags.map(t => `<span class="tag-chip">${escapeHtml(t)}</span>`).join('');
tagHost.classList.remove('hidden');
}
document.getElementById(`table-${sid}`).innerHTML = '<table><thead><tr><th>Path</th><th>State 0</th><th>State 1</th></tr></thead><tbody></tbody></table>';
step();
}
function renderDiffTable(sid, rows, stats, configTags = []) {
if (rows && rows.length > 500) {
progressiveRenderFinalRows(sid, rows, stats, configTags);
return;
}
const panel = document.getElementById(Jobs.get(sid).panelId);
const tbl = [
'<table><thead><tr><th>Path</th><th>State 0</th><th>State 1</th></tr></thead><tbody>',
...rows.map(r => `<tr><td>${escapeHtml(r.path)}</td><td>${escapeHtml(r.s0)}</td><td>${escapeHtml(r.s1)}</td></tr>`),
'</tbody></table>'
].join('');
panel.querySelector(`#table-${sid}`).innerHTML = tbl;
panel.querySelector(`#stats-${sid}`).textContent = `Paths with diffs: ${rows.length} • Roots of change: ${stats.roots}`;
//render per-panel tags
const tagHost = panel.querySelector(`#tags-${sid}`);
if (tagHost) {
if (configTags.length) {
tagHost.innerHTML = configTags.map(t => `<span class="tag-chip">${escapeHtml(t)}</span>`).join('');
tagHost.classList.remove('hidden');
} else {
tagHost.innerHTML = '';
tagHost.classList.add('hidden');
}
}
//alsoo tell index.html's global bar to show these tags
window.dispatchEvent(new CustomEvent('show-config-tags', {
detail: { sid, tags: configTags }
}));
const csv = toCSV([['Path','State 0','State 1'], ...rows.map(r => [r.path, r.s0, r.s1])]);
const blob = new Blob([csv], { type: 'text/csv' });
const exp = panel.querySelector(`#exp-${sid}`);
exp.href = URL.createObjectURL(blob);
}
function computeDiffInWorker(sid, job) {
const worker = new Worker('./diffalgorithm/diff.worker.js', { type: 'module' });
job.worker = worker;
const tabBtn = document.getElementById(job.tabId);
const statusSpan = tabBtn?.querySelector('.small');
if (statusSpan) statusSpan.textContent = ' • computing… s0 ✓ s1 ✓';
worker.onmessage = (ev) => {
const { type, rows, stats, message, configTags, appendRows, partialStats } = ev.data || {};
if (type === 'diff-progress' && Array.isArray(appendRows) && appendRows.length) {
appendRowsToTable(sid, appendRows);
const roots = partialStats?.roots ?? 0;
const tbodyCount = document.querySelector(`#panel-${sid} tbody`)?.children.length || 0;
document.getElementById(`stats-${sid}`).textContent = `Paths with diffs: ${tbodyCount} • Roots of change: ${roots}`;
return;
}
if (type === 'diff-result') {
const jobRef = Jobs.get(sid);
if (jobRef) jobRef.configTags = Array.isArray(configTags) ? configTags : [];
renderDiffTable(sid, rows, stats, Array.isArray(configTags) ? configTags : []);
if (statusSpan) statusSpan.textContent = ' * done';
worker.terminate();
job.worker = null;
return;
}
if (type === 'diff-error') {
const panel = document.getElementById(job.panelId);
panel.querySelector(`#table-${sid}`).innerHTML = `<div class="meta" style="color:#b00">Error: ${escapeHtml(message)}</div>`;
if (statusSpan) statusSpan.textContent = ' • error';
worker.terminate();
job.worker = null;
return;
}
};
//build exclude list to send to the worker
let excludeKeywords = [];
if (applyBlocklist && applyBlocklist.checked) {
excludeKeywords = [...DEFAULT_BLOCKLIST, ...EXTRA_EXCLUDE_KEYWORDS];
} else {
excludeKeywords = []; //show everything
}
document.getElementById(`table-${sid}`).innerHTML = '<table><thead><tr><th>Path</th><th>State 0</th><th>State 1</th></tr></thead><tbody></tbody></table>';
document.getElementById(`stats-${sid}`).textContent = `Paths with diffs: 0 • Roots of change: 0`;
worker.postMessage({ type: 'diff', sid, jsonA: job.state0, jsonB: job.state1, excludeKeywords });
}
function toCSV(rows) { return rows.map(r => r.map(v => `"${String(v ?? '').replace(/"/g,'""')}"`).join(',')).join('\n'); }
function escapeHtml(s){ return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'"',"'":'''}[c])); }
//SANDBOX: VENDOR SNIPPETS ONLY
function mkVendorSnippet({ sid, state, analysisOrigin }) {
//copy the full message (with sid/state/type) to clipboard
return `(function(){
const sid=${JSON.stringify(sid)}, state=${JSON.stringify(state)}, analysisOrigin=${JSON.stringify(analysisOrigin)};
function deliver(graph){
const msg={type:'CRAWL_RESULT', state, sid, graph};
try{ if(window.opener && typeof window.opener.postMessage==='function'){ window.opener.postMessage(msg, analysisOrigin); } }catch(e){ console.error('[sandbox] postMessage failed', e); }
try{ const j=JSON.stringify(msg); console.log('[graphdiff sandbox][vendor] State', state, 'graph (wrapped item):', graph); navigator.clipboard&&navigator.clipboard.writeText(j).catch(()=>{});}catch(_){}
return '[graphdiff] If opener available: sent via postMessage. Also logged and copied to clipboard.';
}
(function(){ const X=window.XMLHttpRequest; if(!X||X.__xslPatched) return;
function Wrapped(){ const xhr=new X(); let _url=''; const origOpen=xhr.open, origSend=xhr.send;
xhr.open=function(m,u){ _url=u||''; return origOpen.apply(this, arguments); };
xhr.send=function(body){
try{
if(typeof _url==='string' && _url.indexOf('/capture')!==-1){
const chunk=JSON.parse(typeof body==='string'? body : '{}');
if(chunk && chunk.chunk_type==='completegraph' && chunk.wrapped_items && chunk.wrapped_items[0]){
deliver(chunk.wrapped_items[0]);
return;
}
}
}catch(_){}
return origSend.apply(this, arguments);
};
return xhr;
}
Wrapped.__xslPatched=true; window.XMLHttpRequest=Wrapped;
})();
try { currentScript = { src: analysisOrigin + '/vendor/crawler-standalone.js' }; } catch(_) { try { window.currentScript = { src: analysisOrigin + '/vendor/crawler-standalone.js' }; } catch(_){} }
window.CRAWLER_CONFIG={ entrypoint:'window', mode:'async', serverURL: location.origin + '/capture', logURL:'', beaconURL:'',
localLogLevel:1, serverLogLevel:0, alertLogLevel:0, domLogLevel:0, maximumTraversalDepth:5, stopCrawlingUponEmptyQueue:true, traversePrototypes:false,
discoveryMethodForIn:false, discoveryMethodOwnPropertyNames:true, discoveryMethodReflectOwnKeys:false,
discoveryMethodOwnPropertyDescriptors:false, discoveryMethodOwnPropertySymbols:false, discoveryMethodKeys:false,
discoveryMethodEntries:false, discoveryMethodLengthProperty:false, discoveryMethodHistoricals:false,
discoveryMethodClassGetMethods:false, discoveryMethodClassGetFields:false, discoveryMethodIndexChar:false,
discoveryMethodSymbolUnscopables:false, discoveryMethodNewEnumerator:false, discoveryMethodGetPrototypeOf:false,
asyncMaxObjectsPerStep:120, asyncMaxDurationPerStep:500, skipUnreadables:true, skipUndefined:true,
skipNonDeterministics:true, skipHtmlAndTextProperties:true, skipAboutBlankDOMs:true
};
var s=document.createElement('script'); s.src=analysisOrigin + '/vendor/crawler-standalone.js'; s.async=true; document.head.appendChild(s);
})();`;
}
function startSandbox() {
const asWindow = windowMode && windowMode.checked;
const features = 'width=880,height=720,menubar=1,toolbar=1,location=1,status=1,resizable=1,scrollbars=1';
let w0, w1;
if (asWindow) {
w0 = window.open('about:blank', '_sandbox_state0');
w1 = window.open('about:blank', '_sandbox_state1');
} else {
w0 = window.open('about:blank', '_sandbox_state0', features);
w1 = window.open('about:blank', '_sandbox_state1', features);
}
if (!w0 || !w1) { alert('Popups were blocked. Allow popups for this page and click again.'); return; }
const sid = `sandbox_${Date.now()}_${Math.random().toString(36).slice(2)}`;
LaunchMeta.set(sid, { inc: 'sandbox', file: 'websites', diffName: 'manual' });
const job = {};
Jobs.set(sid, job);
ensureTabAndPanelForSid(sid, 'sandbox | websites | manual', job);
updateTabReadiness(sid);
const origin = location.origin;
sandboxS0Vendor.value = mkVendorSnippet({ sid, state: 0, analysisOrigin: origin });
sandboxS1Vendor.value = mkVendorSnippet({ sid, state: 1, analysisOrigin: origin });
if (sandboxStatus) {
sandboxStatus.textContent = 'Navigate each window to the target page, open DevTools → Console, paste the Vendor snippet (State 0 / State 1). If postMessage is blocked, the full message is also copied to the clipboard; use the “Paste JSON → State …” buttons here.';
}
}
sandboxOpenBtn?.addEventListener('click', startSandbox);
async function copyTxt(el){ try{ await navigator.clipboard.writeText(el.value||''); }catch{} }
sandboxCopy0Vendor?.addEventListener('click', () => copyTxt(sandboxS0Vendor));
sandboxCopy1Vendor?.addEventListener('click', () => copyTxt(sandboxS1Vendor));
function pickSandboxSidInteractively(defaultSid = null) {
const sandboxSids = [...Jobs.keys()].filter(k => k.startsWith('sandbox_'));
if (!sandboxSids.length) return null;
if (defaultSid && sandboxSids.includes(defaultSid)) return defaultSid;
if (sandboxSids.length === 1) return sandboxSids[0];
const pick = prompt(`Select sandbox SID:\n${sandboxSids.join('\n')}`);
return pick ? pick.trim() : null;
}
function pasteIntoState(which) {
const txt = prompt(`Paste JSON for State ${which}.\nTip: the vendor snippet copies the FULL message object ({type:'CRAWL_RESULT', sid, state, graph}).`);
if (!txt) return;
let obj;
try { obj = JSON.parse(txt); } catch (e) { alert('Invalid JSON'); return; }
//if it's already a full message, just route it. otherwise wrap as message
if (obj && obj.type && obj.graph) {
handleResult(obj);
} else {
const sid = pickSandboxSidInteractively();
if (!sid) return;
handleResult({ type: 'CRAWL_RESULT', sid, state: which, graph: obj });
}
}
sandboxPaste0?.addEventListener('click', () => pasteIntoState(0));
sandboxPaste1?.addEventListener('click', () => pasteIntoState(1));
(async () => {
await registerSW();
await loadDifferences();
})();