initial version
Akongregate_hide_anti-adblock_banner.js
@@ -0,0 +1,44 @@
// ==UserScript==
// @name Kongregate Hide Anti-Adblock Notice
// @version 1.0
// @description Hides the "ad or script blocking software is interfering" banner on Kongregate.
// @match *://*.kongregate.com/*
// @run-at document-start
// @grant none
// ==/UserScript==
(function () {
'use strict';
// The only stable marker is the text. Class names and the z-index are randomized.
const TEXT_NEEDLE = 'ad or script blocking software is interfering';
// Find the notice by its text, climb to the fixed-position bar, and remove it.
function sweep(root) {
const scope = (root && root.querySelectorAll) ? root : document;
scope.querySelectorAll('div').forEach(function (el) {
if (el.textContent && el.textContent.indexOf(TEXT_NEEDLE) !== -1) {
const bar = el.closest('div[style*="position: fixed"]') || el;
bar.remove();
}
});
}
// Catch insertions and re-insertions.
const observer = new MutationObserver(function (mutations) {
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.nodeType === 1 && (node.textContent || '').indexOf(TEXT_NEEDLE) !== -1) {
sweep(node.parentNode || document);
return;
}
}
}
});
observer.observe(document.documentElement, { childList: true, subtree: true });
// Initial pass + safety net on full load.
sweep(document);
window.addEventListener('load', function () { sweep(document); }, { once: true });
console.log("Anti-Adblock loaded")
})();
Aspeedhack.js
@@ -0,0 +1,1935 @@
// ==UserScript==
// @name Speedhack Panel
// @version 1.0.0
// @description Floating, movable, resizable, minimizable time-scaling panel with an autoclicker and a Cheat-Engine-style memory scanner. Scales the page's JS timing functions by a chosen factor. Runs inside iframes. By default only the TOP frame shows a panel and broadcasts settings to child frames; any frame can be detached for its own panel. The autoclicker clicks at the cursor and auto-targets whichever (i)frame the cursor is in. The Scan tab finds/edits values in a game's WebAssembly heap or JS object graph, and can target any (i)frame from the top panel. Only the per-URL "closed" state and saved scans are remembered.
// @match *://*/*
// @run-at document-start
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant unsafeWindow
// ==/UserScript==
/* eslint-disable no-empty */
/* eslint-disable no-unused-vars */
(function () {
'use strict';
if (window.__SPEEDHACK_PANEL__) return; // guard against double-injection in the same frame
window.__SPEEDHACK_PANEL__ = true;
/* ------------------------------------------------------------------ *
* The real page window. With @grant set we are sandboxed, so window
* !== unsafeWindow. Patch unsafeWindow so the game actually sees it.
* ------------------------------------------------------------------ */
const hasUnsafe = (typeof unsafeWindow !== 'undefined') && unsafeWindow && unsafeWindow !== window;
const pageWin = (typeof unsafeWindow !== 'undefined' && unsafeWindow) ? unsafeWindow : window;
/* ------------------------------------------------------------------ *
* Capture originals from the PAGE window, before patching.
* ------------------------------------------------------------------ */
const RealDate = pageWin.Date;
const origDateNow = RealDate.now.bind(RealDate);
const origPerfNow = (pageWin.performance && pageWin.performance.now)
? pageWin.performance.now.bind(pageWin.performance)
: origDateNow;
const origSetTimeout = pageWin.setTimeout.bind(pageWin);
const origSetInterval = pageWin.setInterval.bind(pageWin);
const origClearTimeout = pageWin.clearTimeout.bind(pageWin);
const origClearInterval= pageWin.clearInterval.bind(pageWin);
const origRAF = (pageWin.requestAnimationFrame ||
function (cb) { return origSetTimeout(function () { cb(origPerfNow()); }, 16); }
).bind(pageWin);
/* ------------------------------------------------------------------ *
* WebAssembly memory capture (for the Scan tab).
* Browser JS has no raw process memory, but WASM games (Unity, Emscripten,
* Godot, C/C++) keep their state in a WebAssembly.Memory linear buffer.
* We patch the page's WebAssembly constructors HERE — at document-start,
* before the game instantiates — so we capture every Memory it creates and
* can scan it like Cheat Engine. Each entry is a LIVE handle: memory.grow()
* detaches the old ArrayBuffer, so readers must always re-read memory.buffer.
* ------------------------------------------------------------------ */
const wasmMemories = []; // [{ memory, label }] — deduped, in creation order
(function hookWasm() {
const W = pageWin.WebAssembly;
if (!W) return;
function record(m, label) {
try {
if (!(m instanceof W.Memory)) return;
for (let i = 0; i < wasmMemories.length; i++) if (wasmMemories[i].memory === m) return;
wasmMemories.push({ memory: m, label: (label || ('mem#' + wasmMemories.length)) });
} catch (e) {}
}
function scanExports(res) {
// res is an instantiate result ({ module, instance }) or a bare Instance.
try {
const inst = (res && res.instance) ? res.instance : res;
const ex = inst && inst.exports;
if (ex) for (const k in ex) { try { if (ex[k] instanceof W.Memory) record(ex[k], k); } catch (e) {} }
} catch (e) {}
return res;
}
const origInstantiate = W.instantiate, origInstantiateStreaming = W.instantiateStreaming;
if (typeof origInstantiate === 'function') {
W.instantiate = function () {
const p = origInstantiate.apply(this, arguments);
return (p && typeof p.then === 'function') ? p.then(scanExports) : p;
};
}
if (typeof origInstantiateStreaming === 'function') {
W.instantiateStreaming = function () {
const p = origInstantiateStreaming.apply(this, arguments);
return (p && typeof p.then === 'function') ? p.then(scanExports) : p;
};
}
const OrigInstance = W.Instance;
if (typeof OrigInstance === 'function') {
function PatchedInstance() {
const inst = new (Function.prototype.bind.apply(OrigInstance, [null].concat(Array.prototype.slice.call(arguments))))();
scanExports(inst);
return inst;
}
PatchedInstance.prototype = OrigInstance.prototype;
try { W.Instance = PatchedInstance; } catch (e) {}
}
const OrigMemory = W.Memory;
if (typeof OrigMemory === 'function') {
function PatchedMemory() {
const mem = new (Function.prototype.bind.apply(OrigMemory, [null].concat(Array.prototype.slice.call(arguments))))();
record(mem, 'Memory()');
return mem;
}
PatchedMemory.prototype = OrigMemory.prototype;
try { W.Memory = PatchedMemory; } catch (e) {}
}
})();
/* ------------------------------------------------------------------ *
* Input isolation. So clicking/typing in the panel doesn't also drive the
* game, we wrap the page's input listeners on window/document/<html>/<body>
* (the only ancestors of the panel host) so an event whose composedPath
* includes the panel host is NOT delivered to the page's own handlers. This
* beats capture-phase listeners (which a per-element shield can't), while the
* panel's own handlers — attached to its shadow nodes, not these targets —
* are untouched. Installed at document-start so we wrap before the game does.
* `panelHost` is read at event time (set once the panel is built).
* ------------------------------------------------------------------ */
const SHIELD_TYPES = { keydown:1, keyup:1, keypress:1, pointerdown:1, pointerup:1,
mousedown:1, mouseup:1, click:1, dblclick:1, contextmenu:1,
wheel:1, touchstart:1, touchend:1 };
const shieldedTargets = new WeakSet();
function eventInPanel(ev) {
try { return !!(panelHost && ev && ev.composedPath && ev.composedPath().indexOf(panelHost) !== -1); } catch (e) { return false; }
}
function shieldInputTarget(target) {
if (!target || typeof target.addEventListener !== 'function' || shieldedTargets.has(target)) return;
shieldedTargets.add(target);
const origAdd = target.addEventListener, origRemove = target.removeEventListener;
const wrappers = new WeakMap(); // handler -> { typeKey -> wrapper }
try {
target.addEventListener = function (type, handler, opts) {
const usable = handler && (typeof handler === 'function' || typeof handler.handleEvent === 'function');
if (!usable || !SHIELD_TYPES[type] || handler.__shxNoShield) return origAdd.call(this, type, handler, opts);
const capture = (typeof opts === 'object' && opts) ? !!opts.capture : !!opts;
const key = type + '/' + (capture ? 1 : 0);
let per = wrappers.get(handler); if (!per) { per = Object.create(null); wrappers.set(handler, per); }
let wrapper = per[key];
if (!wrapper) {
wrapper = function (ev) { if (eventInPanel(ev)) return; return (typeof handler === 'function') ? handler.call(this, ev) : handler.handleEvent(ev); };
per[key] = wrapper;
}
return origAdd.call(this, type, wrapper, opts);
};
target.removeEventListener = function (type, handler, opts) {
if (!handler || !SHIELD_TYPES[type]) return origRemove.call(this, type, handler, opts);
const capture = (typeof opts === 'object' && opts) ? !!opts.capture : !!opts;
const per = wrappers.get(handler); const wrapper = per && per[type + '/' + (capture ? 1 : 0)];
return origRemove.call(this, type, wrapper || handler, opts);
};
} catch (e) {}
}
try { shieldInputTarget(pageWin); } catch (e) {}
try { shieldInputTarget(pageWin.document); } catch (e) {}
try { shieldInputTarget(pageWin.document && pageWin.document.documentElement); } catch (e) {}
// <body> may not exist yet at document-start; it's shielded when the panel is built.
/* ------------------------------------------------------------------ *
* Persistence — the "closed for this exact URL" flag and saved scans.
* Still per-frame: a child frame whose URL was remembered-closed stays
* out entirely (no hooks, no messaging), exactly as before.
* ------------------------------------------------------------------ */
const PAGE = location.href.split('#')[0]; // "exact" page URL, ignoring #hash
const store = {
get: function (k, d) {
try { if (typeof GM_getValue === 'function') return GM_getValue(k, d); } catch (e) {}
try { var v = localStorage.getItem('shx_' + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; }
},
set: function (k, v) {
try { if (typeof GM_setValue === 'function') { GM_setValue(k, v); return; } } catch (e) {}
try { localStorage.setItem('shx_' + k, JSON.stringify(v)); } catch (e) {}
}
};
const CLOSED_KEY = 'closed:' + PAGE;
if (store.get(CLOSED_KEY, false) === true) return; // remembered closed for this exact URL → do nothing
/* ------------------------------------------------------------------ *
* Scaled clocks. fake = anchorFake + (real - anchorReal) * scale
* ------------------------------------------------------------------ */
let scale = 1;
let turbo = false; // experimental multi-step rAF
let turboNow = null; // forced timestamp during turbo sub-steps
let turboT = null; // monotonic accumulator for turbo frames; reseeded when null
function makeClock(realFn) {
let aReal = realFn(), aFake = aReal, s = 1;
return {
now: function () { return aFake + (realFn() - aReal) * s; },
setScale: function (ns) { const r = realFn(); aFake = aFake + (r - aReal) * s; aReal = r; s = ns; },
reanchor: function () { const r = realFn(); aReal = r; aFake = r; },
setTo: function (v) { aReal = realFn(); aFake = v; } // jump the fake timeline to absolute v
};
}
const dateClock = makeClock(origDateNow);
const perfClock = makeClock(origPerfNow);
function applyScale(ns) {
ns = Number(ns);
if (!isFinite(ns) || ns <= 0) return;
paused = false;
scale = ns;
dateClock.setScale(ns);
perfClock.setScale(ns);
}
function perfRead() { return (turboNow !== null) ? turboNow : perfClock.now(); }
/* ------------------------------------------------------------------ *
* Pause (for the Scan tab). scale=0 is normally rejected by applyScale,
* so we freeze the clocks directly: patched setTimeout/setInterval delays
* go to Infinity and the Date/performance clocks stop advancing, halting
* time-driven game logic. (A game that advances purely by rAF frame-count
* rather than elapsed time won't fully stop — noted in the UI.) Pause is
* local to this frame and is NOT broadcast.
* ------------------------------------------------------------------ */
let paused = false;
let prevScale = 1;
function setPaused(on) {
on = !!on;
if (on === paused) return;
if (on) {
prevScale = scale || 1;
paused = true;
scale = 0;
dateClock.setScale(0);
perfClock.setScale(0);
} else {
applyScale(prevScale); // clears `paused`, restores clocks
}
}
/* ------------------------------------------------------------------ *
* Fake Date
* ------------------------------------------------------------------ */
function FakeDate() {
const args = Array.prototype.slice.call(arguments);
if (new.target === undefined) return new RealDate(dateClock.now()).toString();
if (args.length === 0) return new RealDate(dateClock.now());
return new (Function.prototype.bind.apply(RealDate, [null].concat(args)))();
}
FakeDate.prototype = RealDate.prototype;
FakeDate.now = function () { return Math.floor(dateClock.now()); };
FakeDate.parse = RealDate.parse.bind(RealDate);
FakeDate.UTC = RealDate.UTC.bind(RealDate);
try { Object.setPrototypeOf(FakeDate, RealDate); } catch (e) {}
/* ------------------------------------------------------------------ *
* setInterval re-arming. We drive intervals through a self-rescheduling
* setTimeout chain that re-reads `scale` every tick, so moving the slider
* rescales already-running intervals. clearInterval/clearTimeout are
* patched to recognise our handles (and pass native ids straight through).
* ------------------------------------------------------------------ */
let intervalSeq = 1;
const fakeIntervals = new Map(); // id -> { timer, cancelled }
function clearFake(id) {
const rec = fakeIntervals.get(id);
if (!rec) return false;
rec.cancelled = true;
origClearTimeout(rec.timer);
fakeIntervals.delete(id);
return true;
}
let clearHooksInstalled = false;
function installClearHooks() {
if (clearHooksInstalled) return;
clearHooksInstalled = true;
// Transparent: only our string handles are intercepted; native numeric ids fall through.
pageWin.clearInterval = function (id) { if (clearFake(id)) return; return origClearInterval(id); };
pageWin.clearTimeout = function (id) { if (clearFake(id)) return; return origClearTimeout(id); };
}
/* ------------------------------------------------------------------ *
* Hooks — installed onto the PAGE window
* ------------------------------------------------------------------ */
const hooks = {
date: {
label: 'Date (Date.now / new Date)',
install: function () { dateClock.reanchor(); pageWin.Date = FakeDate; },
uninstall: function () { pageWin.Date = RealDate; }
},
performance: {
label: 'performance.now',
install: function () { perfClock.reanchor(); if (pageWin.performance) pageWin.performance.now = function () { return perfRead(); }; },
uninstall: function () { if (pageWin.performance) pageWin.performance.now = origPerfNow; }
},
setTimeout: {
label: 'setTimeout',
install: function () {
pageWin.setTimeout = function (fn, delay) {
const rest = Array.prototype.slice.call(arguments, 2);
if (typeof delay === 'number' && isFinite(delay)) delay = delay / scale;
return origSetTimeout.apply(null, [fn, delay].concat(rest));
};
},
uninstall: function () { pageWin.setTimeout = origSetTimeout; }
},
setInterval: {
label: 'setInterval',
install: function () {
installClearHooks();
pageWin.setInterval = function (fn, delay) {
const rest = Array.prototype.slice.call(arguments, 2);
// Non-function callback or non-finite delay → defer to native semantics.
if (typeof fn !== 'function' || typeof delay !== 'number' || !isFinite(delay)) {
return origSetInterval.apply(null, arguments);
}
const id = 'shx_int_' + (intervalSeq++);
const rec = { timer: 0, cancelled: false };
fakeIntervals.set(id, rec);
function tick() {
if (rec.cancelled) return;
// Re-read scale every tick so slider changes take effect on a live interval.
// When the hook is toggled OFF, eff=1 → the interval keeps running at native
// cadence instead of freezing the page's loop.
const eff = state.setInterval ? scale : 1;
rec.timer = origSetTimeout(tick, delay / eff); // schedule next BEFORE the call,
try { fn.apply(pageWin, rest); } catch (e) {} // so a clear() inside fn cancels it
}
const eff0 = state.setInterval ? scale : 1;
rec.timer = origSetTimeout(tick, delay / eff0);
return id;
};
},
// Running fake intervals keep ticking after uninstall, but at scale 1 (see `eff`),
// so toggling the hook off unscales them rather than freezing the page.
uninstall: function () { pageWin.setInterval = origSetInterval; }
},
raf: {
label: 'requestAnimationFrame',
install: function () {
pageWin.requestAnimationFrame = function (cb) {
return origRAF(function (realT) {
if (!turbo) {
// Feed one scaled timestamp. If the callback throws, swallow it — do NOT
// re-invoke with a different time, which would double-run frame side effects.
try { cb(perfRead()); } catch (e) {}
return;
}
// turbo: run the frame callback k times per real frame on ONE monotonic
// timeline, ~1 normal frame apart, so engines that CLAMP delta-time still
// advance k frames. Fake time advances by exactly k*step here — it does not
// also track real elapsed time, which is what used to cause discontinuities.
const k = Math.max(1, Math.min(20, Math.round(scale))); // capped so the tab can't lock up
const step = 1000 / 60;
if (turboT === null) turboT = perfClock.now(); // seed once from current fake time
let currentCbs = [cb];
for (let i = 0; i < k && currentCbs.length; i++) {
turboT += step; // advance the single timeline
turboNow = turboT;
const nextCbs = []; // collect EVERY rAF re-registered this sub-step,
const prev = pageWin.requestAnimationFrame; // not just the last (a callback may schedule several)
pageWin.requestAnimationFrame = function (next) { if (typeof next === 'function') nextCbs.push(next); return 0; };
for (let j = 0; j < currentCbs.length; j++) { try { currentCbs[j](turboT); } catch (e) {} }
pageWin.requestAnimationFrame = prev; // restore our wrapper
currentCbs = nextCbs; // chain all re-registered callbacks
}
turboNow = null;
perfClock.setTo(turboT); // keep performance.now() continuous after the burst
for (let j = 0; j < currentCbs.length; j++) pageWin.requestAnimationFrame(currentCbs[j]); // next REAL frame
});
};
},
uninstall: function () { pageWin.requestAnimationFrame = origRAF; }
}
};
// Defaults: every hook ON, scale 1 (== no effect), turbo OFF. None of this is persisted.
const state = { date: true, performance: true, setTimeout: true, setInterval: true, raf: true };
function setHook(name, on) {
state[name] = on;
try { on ? hooks[name].install() : hooks[name].uninstall(); } catch (e) {}
}
Object.keys(hooks).forEach(function (n) { if (state[n]) { try { hooks[n].install(); } catch (e) {} } });
/* ------------------------------------------------------------------ *
* Multi-frame coordination.
* Default: only the TOP frame shows a panel; it broadcasts settings to
* child frames over postMessage and they apply them locally. A frame can
* be "detached" to run its own independent panel. A frame that never hears
* from a host within 5s promotes itself (covers a top frame the manager
* didn't inject into). Hooks are installed in every frame regardless.
* ------------------------------------------------------------------ */
const isTop = (function () { try { return window.top === window.self; } catch (e) { return true; } })();
let isHost = isTop; // top frame hosts by default; a stranded child may promote
let attached = !isTop; // children follow the host until detached
let hostWin = null; // a child's link back to its host window
let gotHost = false; // did we ever hear from a host?
let hostClosed = false; // this host's panel was closed → don't adopt frames anymore
const frames = new Map(); // host only: childWindow -> { url, attached }
// A stable, per-frame random id. Scan commands are addressed by this id and
// delivered by broadcasting across the live frame tree (see broadcastScanMsg),
// so targeting never depends on a stored cross-world `e.source` reference —
// which can be null/unpostable for cross-origin iframes in an isolated world.
const SELF_ID = 'shx-' + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
function currentSettings() {
return {
scale: scale,
turbo: turbo,
hooks: { date: state.date, performance: state.performance, setTimeout: state.setTimeout,
setInterval: state.setInterval, raf: state.raf }
};
}
function settingsMsg(type) {
const s = currentSettings();
return { type: type, scale: s.scale, turbo: s.turbo, hooks: s.hooks };
}
function applySettings(s) {
if (s.hooks) Object.keys(s.hooks).forEach(function (n) {
if (hooks[n] && state[n] !== s.hooks[n]) setHook(n, s.hooks[n]);
});
if (typeof s.turbo === 'boolean' && s.turbo !== turbo) { turbo = s.turbo; turboT = null; }
if (typeof s.scale === 'number') applyScale(s.scale);
if (panelCtl) panelCtl.sync();
}
function postTo(win, msg) { try { msg.__shx = 1; win.postMessage(msg, '*'); } catch (e) {} }
// Deliver a scan message to EVERY frame in the tree (root = window.top, plus all
// descendants), the same live-frame walk rollcall uses — which is proven to reach
// cross-origin children. Only the frame whose SELF_ID matches `targetFrame` acts on
// it; the rest ignore it. This sidesteps stored-`e.source` references entirely.
function broadcastScanMsg(msg) {
let root; try { root = window.top; } catch (e) { root = window; }
try { postTo(root, msg); } catch (e) {}
(function visit(win) {
let list; try { list = win.frames; } catch (e) { return; }
for (let i = 0; i < list.length; i++) {
try { postTo(list[i], msg); } catch (e) {}
try { visit(list[i]); } catch (e) {}
}
})(root);
}
function pruneFrames() {
// Registry keys are child window objects that are never otherwise cleaned up. Drop
// entries whose iframe has been removed from the tree, else they accumulate (phantom
// frame-list rows + dead postMessage targets) on long-lived / SPA pages.
const live = new Set();
(function visit(win) {
let list; try { list = win.frames; } catch (e) { return; }
for (let i = 0; i < list.length; i++) { try { live.add(list[i]); visit(list[i]); } catch (e) {} }
})(window.top);
let changed = false;
frames.forEach(function (f, src) { if (!live.has(src)) { frames.delete(src); changed = true; } });
return changed;
}
function broadcastSettings() {
if (!isHost) return; // only a host pushes settings out
pruneFrames();
frames.forEach(function (f, src) { if (f.attached) postTo(src, settingsMsg('settings')); });
}
function rollcall() {
// Ask every descendant frame to (re-)announce itself — covers a host that
// booted after its children. Reaching cross-origin frames via postMessage is fine.
(function visit(win) {
let list; try { list = win.frames; } catch (e) { return; }
for (let i = 0; i < list.length; i++) {
try { postTo(list[i], { type: 'rollcall' }); } catch (e) {}
try { visit(list[i]); } catch (e) {}
}
})(window.top);
}
function promoteToHost() {
if (isHost) return;
isHost = true; attached = false; hostWin = null;
rollcall();
ensurePanel('host');
}
function detachFrame(src) {
const f = frames.get(src); if (!f) return;
f.attached = false; postTo(src, { type: 'detach' });
if (panelCtl) panelCtl.refreshFrames();
}
function reattachFrame(src) {
const f = frames.get(src); if (!f) return;
f.attached = true; postTo(src, settingsMsg('attach'));
if (panelCtl) panelCtl.refreshFrames();
}
window.addEventListener('message', function (e) {
const m = e.data; if (!m || m.__shx !== 1) return;
switch (m.type) {
case 'hello': // host: a child announced itself
if (!isHost) break;
if (hostClosed) { postTo(e.source, { type: 'host-closing' }); break; } // late frame after close → go standalone
if (frames.has(e.source)) { frames.get(e.source).url = m.url; if (m.frameId) frames.get(e.source).id = m.frameId; }
else frames.set(e.source, { url: m.url, attached: true, id: m.frameId });
postTo(e.source, settingsMsg('settings')); // sync the newcomer immediately
postTo(e.source, clickerConfigMsg()); // ...including autoclicker config
postTo(e.source, { type: 'clicker-run', on: clicker.running });
if (panelCtl) panelCtl.refreshFrames();
break;
case 'rollcall': // child: a host is probing for frames
if (isHost) break;
gotHost = true; hostWin = e.source;
postTo(e.source, { type: 'hello', url: location.href, frameId: SELF_ID });
break;
case 'settings': // child: host pushed settings
if (isHost) break;
gotHost = true; hostWin = e.source;
if (attached) applySettings(m);
break;
case 'detach': // child: host detached us → own panel
if (isHost) break;
hostWin = e.source; attached = false;
ensurePanel('detached');
break;
case 'host-closing': // child: the host closed → become standalone
if (isHost) break;
promoteToHost(); // host mode (no re-attach button), self-sufficient
break;
case 'attach': // child: host folded us back in
if (isHost) break;
attached = true; destroyPanel(); applySettings(m);
break;
case 'reattach': // host: a detached child asked to fold back
if (!isHost) break;
{ const f = frames.get(e.source);
if (f) { f.attached = true; postTo(e.source, settingsMsg('settings')); if (panelCtl) panelCtl.refreshFrames(); } }
break;
case 'clicker-config': // child: host pushed clicker settings
if (isHost) break;
applyClickerConfig(m);
break;
case 'clicker-run': // shared autoclicker running state
if (isHost) { // a child toggled it → adopt + fan out to all
setClickerRunning(m.on, true);
} else { // host pushed the state down
setClickerRunning(m.on, false);
}
break;
case 'scan-cmd': { // any frame: if addressed to me, run + reply
if (m.targetFrame && m.targetFrame !== SELF_ID) break; // broadcast not meant for this frame
const dkey = (m.from || '') + ':' + m.reqId;
if (scanHandled.has(dkey)) break; // duplicate — arrived via both channels
scanHandled.add(dkey); scanHandledQ.push(dkey);
if (scanHandledQ.length > 400) scanHandled.delete(scanHandledQ.shift());
const replyWin = e.source;
const scmd = m.cmd || m; // command payload is nested under `cmd` (avoids type-field collision)
runScanCommand(scmd).then(function (res) {
res.type = 'scan-result'; res.reqId = m.reqId; res.targetFrame = m.from;
try { if (replyWin) postTo(replyWin, res); } catch (e2) {} // reply to the sender directly...
broadcastScanMsg(res); // ...and via window.top (reliable upward)
});
break;
}
case 'scan-result': { // controller: resolve the matching pending request
if (m.targetFrame && m.targetFrame !== SELF_ID) break;
const resolve = scanPending.get(m.reqId);
if (resolve) { scanPending.delete(m.reqId); resolve(m); }
break;
}
}
});
/* ------------------------------------------------------------------ *
* Autoclicker. The engine runs in EVERY frame; the panel frame owns
* the UI and broadcasts config + the shared running flag. A frame only
* dispatches while the cursor is directly inside it, so clicks follow
* the cursor across (i)frames with no detaching. Real-time timers keep
* the cadence independent of the speed scale.
* ------------------------------------------------------------------ */
const clicker = {
mode: 'toggle', // 'toggle' | 'hold'
hotkey: null, // { key, ctrl, alt, shift, meta } | null
swallowHotkey: false, // preventDefault/stopPropagation the hotkey so the page can't see it
cps: 10, // base clicks per second
jitterMs: 0, // random 0..jitterMs added to each gap
holdMs: 20, // mousedown→mouseup duration per click
running: false,
listening: false, // panel frame only: capturing the next key as the hotkey
lastX: 0, lastY: 0, // last cursor position in THIS frame (clientX/Y)
enteredDoc: false, // cursor currently within this frame's viewport
overChildFrame: false, // cursor currently over a nested <iframe>/<frame>
timer: 0, upTimer: 0
};
let panelHost = null; // the shadow-DOM host element of this frame's panel, if any
const MAX_CPS = 100;
const ctxDoc = pageWin.document || document;
function cursorInside() { return clicker.enteredDoc && !clicker.overChildFrame; }
function trackPointer(e) {
clicker.lastX = e.clientX; clicker.lastY = e.clientY;
clicker.enteredDoc = true;
const t = e.target, tag = t && t.tagName;
clicker.overChildFrame = (tag === 'IFRAME' || tag === 'FRAME');
}
try {
ctxDoc.addEventListener('pointermove', trackPointer, true);
ctxDoc.addEventListener('mousemove', trackPointer, true); // fallback where PointerEvents are absent
ctxDoc.addEventListener('mouseover', trackPointer, true); // updates overChildFrame even without movement
// relatedTarget == null on mouseout means the cursor left the window entirely.
ctxDoc.addEventListener('mouseout', function (e) { if (!e.relatedTarget) clicker.enteredDoc = false; }, true);
} catch (e) {}
function fireClick() {
const x = clicker.lastX, y = clicker.lastY;
const el = ctxDoc.elementFromPoint ? ctxDoc.elementFromPoint(x, y) : null;
if (!el) return;
const base = { bubbles: true, cancelable: true, composed: true, view: pageWin, clientX: x, clientY: y, button: 0 };
function dispatch(type, buttons, pointer) {
const opts = Object.assign({}, base, { buttons: buttons });
let ev;
if (pointer && pageWin.PointerEvent) {
try { ev = new pageWin.PointerEvent(type, Object.assign(opts, { pointerId: 1, pointerType: 'mouse', isPrimary: true })); } catch (e) {}
}
if (!ev) { try { ev = new pageWin.MouseEvent(type, opts); } catch (e) { return; } }
try { el.dispatchEvent(ev); } catch (e) {}
}
dispatch('pointerdown', 1, true); dispatch('mousedown', 1, false);
const up = function () {
clicker.upTimer = 0;
dispatch('pointerup', 0, true); dispatch('mouseup', 0, false); dispatch('click', 0, false);
};
const gap = 1000 / Math.max(0.1, clicker.cps);
const hold = Math.min(Math.max(0, clicker.holdMs), Math.max(0, gap - 5)); // keep hold < gap so clicks don't overlap
if (hold > 0) clicker.upTimer = origSetTimeout(up, hold); else up();
}
function startClickerLoop() {
if (clicker.timer) return;
(function tick() {
clicker.timer = 0;
if (!clicker.running) return;
if (cursorInside()) { try { fireClick(); } catch (e) {} }
// Re-read rate/jitter every cycle so slider-style changes apply live. Real-time
// timer (origSetTimeout) → cadence is unaffected by the speed scale.
const gap = Math.max(10, 1000 / Math.max(0.1, clicker.cps) + Math.random() * Math.max(0, clicker.jitterMs));
clicker.timer = origSetTimeout(tick, gap);
})();
}
function stopClickerLoop() {
if (clicker.timer) { origClearTimeout(clicker.timer); clicker.timer = 0; }
if (clicker.upTimer) { origClearTimeout(clicker.upTimer); clicker.upTimer = 0; }
}
// Set the shared running flag. propagate=true → tell the host (or, if we ARE the host,
// fan out to every frame) so all frames share one running state.
function setClickerRunning(on, propagate) {
on = !!on;
if (clicker.running !== on) { clicker.running = on; on ? startClickerLoop() : stopClickerLoop(); }
if (panelCtl) panelCtl.syncClicker();
if (!propagate) return;
if (isHost) frames.forEach(function (f, src) { postTo(src, { type: 'clicker-run', on: on }); });
else if (hostWin) postTo(hostWin, { type: 'clicker-run', on: on });
}
function clickerConfigMsg() {
return { type: 'clicker-config', mode: clicker.mode, hotkey: clicker.hotkey,
swallowHotkey: clicker.swallowHotkey, cps: clicker.cps, jitterMs: clicker.jitterMs, holdMs: clicker.holdMs };
}
function broadcastClickerConfig() {
if (!isHost) return; // config flows host → all frames (not just attached)
pruneFrames();
frames.forEach(function (f, src) { postTo(src, clickerConfigMsg()); });
}
function applyClickerConfig(c) {
if (c.mode === 'toggle' || c.mode === 'hold') clicker.mode = c.mode;
if ('hotkey' in c) clicker.hotkey = c.hotkey;
if (typeof c.swallowHotkey === 'boolean') clicker.swallowHotkey = c.swallowHotkey;
if (typeof c.cps === 'number') clicker.cps = Math.min(MAX_CPS, Math.max(0.1, c.cps));
if (typeof c.jitterMs === 'number') clicker.jitterMs = Math.max(0, c.jitterMs);
if (typeof c.holdMs === 'number') clicker.holdMs = Math.max(0, c.holdMs);
if (panelCtl) panelCtl.syncClicker();
}
function hotkeyMatches(e, hk) {
return hk && e.key === hk.key && !!e.ctrlKey === !!hk.ctrl && !!e.altKey === !!hk.alt &&
!!e.shiftKey === !!hk.shift && !!e.metaKey === !!hk.meta;
}
function eventFromPanel(e) {
return panelHost && e.composedPath && e.composedPath().indexOf(panelHost) !== -1;
}
function onClickerKeyDown(e) {
if (clicker.listening) { // capturing a new binding (panel frame)
if (e.key === 'Control' || e.key === 'Alt' || e.key === 'Shift' || e.key === 'Meta') return; // await a real key
e.preventDefault(); e.stopPropagation();
clicker.hotkey = { key: e.key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, meta: e.metaKey };
clicker.listening = false;
if (panelCtl) panelCtl.syncClicker();
broadcastClickerConfig();
return;
}
if (eventFromPanel(e)) return; // don't let typing in our own UI trigger the hotkey
if (!hotkeyMatches(e, clicker.hotkey)) return;
if (clicker.swallowHotkey) { e.preventDefault(); e.stopPropagation(); }
if (e.repeat) return;
if (clicker.mode === 'toggle') setClickerRunning(!clicker.running, true);
else setClickerRunning(true, true); // hold: down = on
}
function onClickerKeyUp(e) {
if (clicker.mode !== 'hold' || !clicker.hotkey || e.key !== clicker.hotkey.key) return;
if (eventFromPanel(e)) return;
if (clicker.swallowHotkey) { e.preventDefault(); e.stopPropagation(); }
setClickerRunning(false, true);
}
// These are OUR listeners and must see panel-originated keys (hotkey binding fires while
// the panel is focused), so exempt them from the input shield below.
onClickerKeyDown.__shxNoShield = true;
onClickerKeyUp.__shxNoShield = true;
try {
pageWin.addEventListener('keydown', onClickerKeyDown, true);
pageWin.addEventListener('keyup', onClickerKeyUp, true);
// Safeguard: in hold mode a keyup can land in a different frame than the keydown;
// losing focus then releasing would otherwise leave it stuck on.
pageWin.addEventListener('blur', function () { if (clicker.mode === 'hold' && clicker.running) setClickerRunning(false, true); }, true);
} catch (e) {}
/* ================================================================== *
* Scan engine (the "Memory Scan" tab). Browser JS has no raw process
* memory, so we offer two backends:
* - 'wasm' : scan a WebAssembly.Memory linear buffer as raw typed
* values at byte offsets (the truest Cheat Engine analog;
* works for Unity/Emscripten/Godot/C-C++ games).
* - 'object': walk the object graph reachable from the page window and
* track numeric properties by their path (for plain-JS games).
* The engine runs LOCALLY in each frame and owns its own candidate state;
* the panel drives it directly (this frame) or over postMessage (iframes).
* ================================================================== */
const SCAN_TYPES = {
i8: { size: 1, get: function (d, o) { return d.getInt8(o); }, set: function (d, o, v) { d.setInt8(o, v); } },
u8: { size: 1, get: function (d, o) { return d.getUint8(o); }, set: function (d, o, v) { d.setUint8(o, v); } },
i16: { size: 2, get: function (d, o) { return d.getInt16(o, true); }, set: function (d, o, v) { d.setInt16(o, v, true); } },
u16: { size: 2, get: function (d, o) { return d.getUint16(o, true); }, set: function (d, o, v) { d.setUint16(o, v, true); } },
i32: { size: 4, get: function (d, o) { return d.getInt32(o, true); }, set: function (d, o, v) { d.setInt32(o, v, true); } },
u32: { size: 4, get: function (d, o) { return d.getUint32(o, true); }, set: function (d, o, v) { d.setUint32(o, v >>> 0, true); } },
i64: { size: 8, big: true, get: function (d, o) { return d.getBigInt64(o, true); }, set: function (d, o, v) { d.setBigInt64(o, v, true); } },
f32: { size: 4, float: true, get: function (d, o) { return d.getFloat32(o, true); }, set: function (d, o, v) { d.setFloat32(o, v, true); } },
f64: { size: 8, float: true, get: function (d, o) { return d.getFloat64(o, true); }, set: function (d, o, v) { d.setFloat64(o, v, true); } }
};
const SCAN_STORE_CAP = 500000; // max candidates TRACKED locally (refine works on all of these)
const FLOAT_EPS = 1e-4;
// "Search multiple types": a type selection can be a single type or a group that
// expands to several. The engine scans every expanded type and tags each result
// with the type that matched, so refine/read/write stay correct per result.
const SCAN_TYPE_GROUPS = {
all: ['i8', 'u8', 'i16', 'u16', 'i32', 'u32', 'i64', 'f32', 'f64'],
allint: ['i8', 'u8', 'i16', 'u16', 'i32', 'u32', 'i64'],
allfloat: ['f32', 'f64']
};
function expandTypes(sel) {
if (SCAN_TYPE_GROUPS[sel]) return SCAN_TYPE_GROUPS[sel].slice();
return SCAN_TYPES[sel] ? [sel] : ['i32'];
}
// Parse the user's typed value into the JS form the type compares with.
function parseScanValue(type, raw) {
const t = SCAN_TYPES[type];
if (!t) return null;
if (t.big) { try { return BigInt(Math.trunc(Number(raw))); } catch (e) { try { return BigInt(raw); } catch (e2) { return null; } } }
const n = Number(raw);
return isFinite(n) ? n : null;
}
function valuesEqual(type, a, b) {
const t = SCAN_TYPES[type];
if (t.big) return a === b;
if (t.float) return Math.abs(a - b) <= FLOAT_EPS * (1 + Math.abs(b));
return a === b;
}
// The place value of the least-significant digit the user actually typed, so an
// "exact" search is only as precise as entered: "1e10" → 1e10, "1.5" → 0.1,
// "100" → 1, "1.50" → 0.01. Returns 1 if the string isn't a plain number.
function precisionFromString(raw) {
const m = String(raw).trim().toLowerCase().match(/^[+-]?(?:\d+)?(?:\.(\d+))?(?:e([+-]?\d+))?$/);
if (!m) return 1;
const decimals = m[1] ? m[1].length : 0;
const exp = m[2] ? parseInt(m[2], 10) : 0;
const p = Math.pow(10, exp - decimals);
return (isFinite(p) && p > 0) ? p : 1;
}
// Build the "exact"-match predicate from the raw typed string. Integers/i64 match
// exactly; floats match the precision cell implied by what was typed, always
// extending AWAY from zero (closed on the typed value, open at the far end):
// "1e10" → [1e10, 2e10), "1.5" → [1.5, 1.6), "-1e10" → (-2e10, -1e10],
// "-1.5" → (-1.6, -1.5]. So magnitude grows symmetrically for either sign.
function makeExactMatcher(type, raw) {
const t = SCAN_TYPES[type]; if (!t) return null;
if (t.big) { const target = parseScanValue(type, raw); if (target === null) return null; return { value: target, match: function (x) { return x === target; } }; }
const v = Number(raw); if (!isFinite(v)) return null;
if (!t.float) return { value: v, match: function (x) { return x === v; } };
const p = precisionFromString(raw), base = Math.round(v / p) * p; // snap to the precision grid
if (base < 0) { const lo = base - p, hi = base; return { value: v, match: function (x) { return x > lo && x <= hi; } }; }
const lo = base, hi = base + p; return { value: v, match: function (x) { return x >= lo && x < hi; } };
}
// refine criteria: 'exact' uses the typed-precision matcher; the rest compare a
// fresh read `cur` against the stored previous value `prev`.
function passesCriteria(type, criteria, cur, prev, matcher) {
switch (criteria) {
case 'exact': return !!matcher && matcher.match(cur);
case 'changed': return !valuesEqual(type, cur, prev);
case 'unchanged': return valuesEqual(type, cur, prev);
case 'increased': return cur > prev;
case 'decreased': return cur < prev;
default: return false;
}
}
function scanValueToWire(v) { return (typeof v === 'bigint') ? v.toString() : v; }
// Run `body()` in slices, yielding to the event loop between them so a scan
// never freezes the frame and can be cancelled mid-flight. body() returns true
// while more work remains; onFinish(cancelled) fires once at the end.
function chunkLoop(job, body, onFinish) {
function tick() {
if (job.cancelled) { onFinish(true); return; }
let more = false;
try { more = body(); } catch (e) { onFinish(false); return; }
if (more) origSetTimeout(tick, 0); else onFinish(false);
}
tick();
}
/* ---- WASM backend -------------------------------------------------- *
* Candidates are tagged with the type that matched ({ off, val, ty }) so a
* single scan can cover several value types at once and refine/read/write each
* one correctly. Scans run chunked (one CHUNK of one type per event-loop slice,
* cycling through the type list) so they never freeze the frame and stay
* cancellable. Up to SCAN_STORE_CAP matches are tracked, so refining a large
* first scan narrows the WHOLE set — not just the first rows shown.
* ------------------------------------------------------------------- */
const wasmScan = (function () {
let memIndex = 0; // which wasmMemories entry we're scanning
let types = ['i32']; // type list for the current scan
let candidates = null; // [{ off, val, ty }] or null
let snapshot = null; // Uint8Array copy for "unknown initial value" scans
const CHUNK = 8 * 1024 * 1024; // bytes scanned per event-loop slice
const REFINE_BUDGET = 200000; // candidates re-checked per slice during refine
function handle() { return wasmMemories[memIndex] || null; }
function view() { const h = handle(); try { return h ? new DataView(h.memory.buffer) : null; } catch (e) { return null; } }
function matcherCache(raw) { const c = {}; return function (t) { if (!(t in c)) c[t] = (raw != null ? makeExactMatcher(t, raw) : null); return c[t]; }; }
function reset() { candidates = null; snapshot = null; }
// Scan the whole buffer for each type in `types`, keeping matches for whichever
// `accept(ty, cur, prev)` returns true (prev is the snapshot byte value, or the
// same as cur for a fresh exact scan). One CHUNK of one type per slice.
function scanAll(accept, prevDv, prevLen, job, done) {
const h = handle(); if (!h) { done({ error: 'no WASM memory' }); return; }
let len = 0; try { len = h.memory.buffer.byteLength; } catch (e) {}
const out = []; let count = 0, capped = false, ti = 0, off = 0;
chunkLoop(job, function () {
if (ti >= types.length) return false;
const dv = view(); if (!dv) return false;
const t = types[ti], sz = SCAN_TYPES[t].size;
const cap = prevDv ? Math.min(len, dv.byteLength, prevLen) : Math.min(len, dv.byteLength);
const end = Math.min(cap, off + CHUNK);
for (; off + sz <= end; off += sz) {
let cur, prev; try { cur = SCAN_TYPES[t].get(dv, off); prev = prevDv ? SCAN_TYPES[t].get(prevDv, off) : cur; } catch (e) { continue; }
if (accept(t, cur, prev)) { count++; if (out.length < SCAN_STORE_CAP) out.push({ off: off, val: cur, ty: t }); else capped = true; }
}
if (off + sz > cap) { ti++; off = 0; }
return ti < types.length;
}, function (cancelled) {
if (cancelled) { done({ cancelled: true }); return; }
candidates = out; done({ count: count, capped: capped, out: out });
});
}
function firstExact(typeList, raw, job, done) {
types = typeList.slice(); snapshot = null; candidates = null;
const mfor = matcherCache(raw);
if (types.every(function (t) { return !mfor(t); })) { done({ error: 'bad value' }); return; }
scanAll(function (t, cur) { const m = mfor(t); return m && m.match(cur); }, null, 0, job, done);
}
function firstUnknown(typeList, job, done) {
types = typeList.slice(); candidates = null;
const h = handle(); if (!h) { done({ error: 'no WASM memory' }); return; }
try { snapshot = new Uint8Array(h.memory.buffer.slice(0)); } catch (e) { done({ error: 'snapshot failed' }); return; }
done({ count: -1, capped: true }); // -1 -> "unknown armed; refine to materialize"
}
// Build the first candidate list from the unknown-scan snapshot by diffing the buffer.
function materialize(criteria, raw, job, done) {
if (!snapshot) { done({ error: 'no snapshot' }); return; }
const mfor = matcherCache(raw), prevDv = new DataView(snapshot.buffer), snapLen = snapshot.byteLength;
scanAll(function (t, cur, prev) { return passesCriteria(t, criteria, cur, prev, mfor(t)); }, prevDv, snapLen, job, function (r) {
if (!r.cancelled && !r.error) { try { snapshot = new Uint8Array(handle().memory.buffer.slice(0)); } catch (e) {} } // re-baseline
done(r);
});
}
function refine(criteria, raw, job, done) {
if (candidates === null && snapshot !== null) { materialize(criteria, raw, job, done); return; }
if (candidates === null) { done({ error: 'no scan in progress' }); return; }
const dv = view(); if (!dv) { done({ error: 'no WASM memory' }); return; }
const mfor = matcherCache(raw), src = candidates, kept = []; let i = 0;
chunkLoop(job, function () {
const d = view(); if (!d) return false;
let n = 0;
for (; i < src.length && n < REFINE_BUDGET; i++, n++) {
const c = src[i], sz = SCAN_TYPES[c.ty].size;
if (c.off + sz > d.byteLength) continue;
let cur; try { cur = SCAN_TYPES[c.ty].get(d, c.off); } catch (e) { continue; }
if (passesCriteria(c.ty, criteria, cur, c.val, mfor(c.ty))) kept.push({ off: c.off, val: cur, ty: c.ty });
}
return i < src.length;
}, function (cancelled) {
if (cancelled) { done({ cancelled: true }); return; }
candidates = kept; done({ count: kept.length, capped: false });
});
}
// address used by the panel/saved list: "<memIndex>:<offset>:<type>"
function rows(limit) {
const dv = view(); const out = [], list = candidates || [];
for (let i = 0; i < list.length && i < limit; i++) {
const c = list[i]; let cur = null; if (dv) try { cur = SCAN_TYPES[c.ty].get(dv, c.off); } catch (e) {}
out.push({ address: memIndex + ':' + c.off + ':' + c.ty, value: scanValueToWire(cur), type: c.ty });
}
return out;
}
function readAddress(address, t) {
const p = String(address).split(':'); const mi = +p[0], off = +p[1], ty = p[2] || t;
const h = wasmMemories[mi]; if (!h || !SCAN_TYPES[ty]) return null;
try { return scanValueToWire(SCAN_TYPES[ty].get(new DataView(h.memory.buffer), off)); } catch (e) { return null; }
}
function writeAddress(address, t, raw) {
const p = String(address).split(':'); const mi = +p[0], off = +p[1], ty = p[2] || t;
const h = wasmMemories[mi]; if (!h || !SCAN_TYPES[ty]) return false;
const v = parseScanValue(ty, raw); if (v === null) return false;
try { SCAN_TYPES[ty].set(new DataView(h.memory.buffer), off, v); return true; } catch (e) { return false; }
}
function memories() { return wasmMemories.map(function (m) { let mb = 0; try { mb = m.memory.buffer.byteLength >> 20; } catch (e) {} return { label: m.label + ' (' + mb + ' MB)' }; }); }
function setMem(i) { memIndex = i | 0; reset(); }
return {
memories: memories, setMem: setMem, reset: reset,
firstExact: firstExact, firstUnknown: firstUnknown, refine: refine,
rows: rows, readAddress: readAddress, writeAddress: writeAddress
};
})();
/* ---- Object-graph backend ----------------------------------------- *
* Walks enumerable own properties reachable from the page window, capping
* node count and depth. Numeric leaves are tracked by their path (array of
* keys). JS numbers are all f64, so the int/float type only tunes equality
* (integer match vs. epsilon) here — noted in the UI.
* ------------------------------------------------------------------- */
const objectScan = (function () {
const NODE_CAP = 200000, DEPTH_CAP = 12, BUDGET = 15000; // nodes per event-loop slice
let type = 'f64';
let candidates = null; // [{ path:[...], val }]
let snapshot = null; // Map(pathKey -> { path, val }) for "unknown initial value"
function pathKey(path) { return path.join(' '); }
function resolve(path) {
let o = pageWin;
for (let i = 0; i < path.length; i++) { if (o == null) return undefined; o = o[path[i]]; }
return o;
}
// Iterative, chunked DFS over numeric leaves. cb(path, value); match(value) filters.
function walkAsync(cb, match, job, done) {
const seen = new WeakSet(); let nodes = 0;
const stack = [[pageWin, [], 0]];
chunkLoop(job, function () {
let processed = 0;
while (stack.length && processed < BUDGET && nodes < NODE_CAP) {
const fr = stack.pop(); const obj = fr[0], path = fr[1], depth = fr[2]; processed++;
if (obj == null || depth > DEPTH_CAP) continue;
let keys; try { keys = Object.keys(obj); } catch (e) { continue; }
for (let i = 0; i < keys.length; i++) {
if (nodes >= NODE_CAP) break;
const k = keys[i]; let v;
try { v = obj[k]; } catch (e) { continue; }
const tv = typeof v;
if (tv === 'number') { if (isFinite(v) && (!match || match(v))) cb(path.concat(k), v); }
else if (tv === 'object' || tv === 'function') {
if (v === null || seen.has(v) || v === pageWin || v === window) continue;
try { if (v.nodeType && v.nodeName) continue; } catch (e) {} // DOM nodes
try { if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) continue; } catch (e) {}
seen.add(v); nodes++;
stack.push([v, path.concat(k), depth + 1]);
}
}
}
return stack.length > 0 && nodes < NODE_CAP;
}, done);
}
function reset() { candidates = null; snapshot = null; }
function setMem() {} // n/a for object graph
// All JS numbers are f64, so the width only tunes equality (exact int vs. float
// cell); a multi-type selection just uses the first type's matcher here.
function firstExact(typeList, raw, job, done) {
type = typeList[0] || 'f64'; snapshot = null; candidates = null;
const matcher = makeExactMatcher(type, raw);
if (!matcher) { done({ error: 'bad value' }); return; }
const out = []; let count = 0, capped = false;
walkAsync(function (path, v) { count++; if (out.length < SCAN_STORE_CAP) out.push({ path: path, val: v }); else capped = true; },
function (v) { return matcher.match(v); }, job, function (cancelled) {
if (cancelled) { done({ cancelled: true }); return; }
candidates = out; done({ count: count, capped: capped });
});
}
function firstUnknown(typeList, job, done) {
type = typeList[0] || 'f64'; candidates = null;
const snap = new Map();
walkAsync(function (path, v) { snap.set(pathKey(path), { path: path, val: v }); }, null, job, function (cancelled) {
if (cancelled) { done({ cancelled: true }); return; }
snapshot = snap; done({ count: -1, capped: true });
});
}
function materialize(criteria, raw, job, done) {
if (!snapshot) { done({ error: 'no snapshot' }); return; }
const matcher = (raw != null) ? makeExactMatcher(type, raw) : null;
const entries = Array.from(snapshot.values());
const out = []; let count = 0, capped = false, i = 0;
chunkLoop(job, function () {
let processed = 0;
for (; i < entries.length && processed < BUDGET; i++, processed++) {
const entry = entries[i]; const cur = resolve(entry.path);
if (typeof cur !== 'number' || !isFinite(cur)) continue;
if (passesCriteria(type, criteria, cur, entry.val, matcher)) { count++; if (out.length < SCAN_STORE_CAP) out.push({ path: entry.path, val: cur }); else capped = true; }
entry.val = cur; // re-baseline
}
return i < entries.length;
}, function (cancelled) {
if (cancelled) { done({ cancelled: true }); return; }
candidates = out; done({ count: count, capped: capped });
});
}
function refine(criteria, raw, job, done) {
if (candidates === null && snapshot !== null) { materialize(criteria, raw, job, done); return; }
if (candidates === null) { done({ error: 'no scan in progress' }); return; }
const matcher = (raw != null) ? makeExactMatcher(type, raw) : null;
const kept = [];
for (let i = 0; i < candidates.length; i++) {
const c = candidates[i]; const cur = resolve(c.path);
if (typeof cur === 'number' && isFinite(cur) && passesCriteria(type, criteria, cur, c.val, matcher)) kept.push({ path: c.path, val: cur });
}
candidates = kept; done({ count: kept.length, capped: false });
}
function rows(limit) {
const out = [], list = candidates || [];
for (let i = 0; i < list.length && i < limit; i++) {
const cur = resolve(list[i].path);
out.push({ address: JSON.stringify(list[i].path), value: (typeof cur === 'number' ? cur : null), type: type });
}
return out;
}
function readAddress(address) {
try { const cur = resolve(JSON.parse(address)); return (typeof cur === 'number') ? cur : null; } catch (e) { return null; }
}
function writeAddress(address, t, raw) {
if (!SCAN_TYPES[t]) t = 'f64'; // a type group selection → object values are f64
let path; try { path = JSON.parse(address); } catch (e) { return false; }
const v = parseScanValue(t, raw); if (v === null) return false;
try { const parent = resolve(path.slice(0, -1)); if (parent == null) return false; parent[path[path.length - 1]] = (typeof v === 'bigint' ? Number(v) : v); return true; }
catch (e) { return false; }
}
function memories() { return []; }
return {
memories: memories, setMem: setMem, reset: reset,
firstExact: firstExact, firstUnknown: firstUnknown, refine: refine,
rows: rows, readAddress: readAddress, writeAddress: writeAddress
};
})();
function scanEngine(name) { return name === 'object' ? objectScan : wasmScan; }
// Address labels for display (wasm "mi:off:ty" → "mem#mi +0x.. (ty)"; object path → "window...").
function scanAddressLabel(engine, address) {
if (engine === 'object') { try { return 'window.' + JSON.parse(address).join('.'); } catch (e) { return String(address); } }
const p = String(address).split(':');
return 'mem#' + p[0] + ' +0x' + (Number(p[1]) || 0).toString(16) + (p[2] ? ' (' + p[2] + ')' : '');
}
// Execute one scan command against the LOCAL engines; resolves a wire-safe result.
// Long ops run asynchronously (chunked) and a single in-flight `scanJob` can be
// cancelled — there are no timeouts anywhere; callers wait until done or cancel.
const SCAN_ROW_LIMIT = 200; // most rows we ship/render at once
let scanJob = null;
function runScanCommand(cmd) {
return new Promise(function (resolve) {
try {
const eng = scanEngine(cmd.engine);
switch (cmd.op) {
case 'ping': resolve({ ok: true, pong: true }); return;
case 'list-memories': resolve({ ok: true, memories: wasmScan.memories() }); return;
case 'set-mem': if (scanJob) scanJob.cancelled = true; eng.setMem(cmd.mem | 0); resolve({ ok: true }); return;
case 'reset': if (scanJob) scanJob.cancelled = true; eng.reset(); resolve({ ok: true, count: 0, rows: [] }); return;
case 'cancel': if (scanJob) scanJob.cancelled = true; resolve({ ok: true, cancelled: true }); return;
case 'set-paused': setPaused(cmd.value); resolve({ ok: true, paused: paused }); return;
case 'read': {
const vals = (cmd.addresses || []).map(function (a) { return { address: a, value: scanValueToWire(eng.readAddress(a, cmd.type)) }; });
resolve({ ok: true, values: vals }); return;
}
case 'write': {
const ok = eng.writeAddress(cmd.address, cmd.type, cmd.value);
resolve({ ok: ok, value: scanValueToWire(eng.readAddress(cmd.address, cmd.type)) }); return;
}
case 'first-exact': case 'first-unknown': case 'refine': {
if (scanJob) scanJob.cancelled = true; // supersede any prior scan
const job = { cancelled: false }; scanJob = job;
const done = function (r) {
if (scanJob === job) scanJob = null;
if (!r || r.error) { resolve({ ok: false, error: (r && r.error) || 'scan failed' }); return; }
if (r.cancelled) { resolve({ ok: true, cancelled: true }); return; }
resolve({ ok: true, count: r.count, capped: r.capped, rows: eng.rows(SCAN_ROW_LIMIT) });
};
const types = expandTypes(cmd.type);
if (cmd.op === 'first-exact') eng.firstExact(types, cmd.value, job, done);
else if (cmd.op === 'first-unknown') eng.firstUnknown(types, job, done);
else eng.refine(cmd.criteria, (cmd.value != null ? cmd.value : null), job, done);
return;
}
default: resolve({ ok: false, error: 'unknown op' }); return;
}
} catch (e) { resolve({ ok: false, error: String(e && e.message || e) }); }
});
}
/* ------------------------------------------------------------------ *
* Scan controller — the panel drives a TARGET frame. For "this frame"
* it calls the local engine directly; for a child iframe it marshals the
* command over postMessage and resolves when the matching reply arrives.
* There is NO timeout — a request waits until the target replies or the
* user cancels (which sends a 'cancel' command that ends the scan).
* Candidate state stays in the target frame; only commands + small result
* batches cross the boundary (works cross-origin and for nested frames).
* ------------------------------------------------------------------ */
let scanSeq = 1;
const scanPending = new Map(); // reqId -> resolve (controller side)
const scanHandled = new Set(); // "from:reqId" of cmds already run (target side, dedup)
const scanHandledQ = []; // FIFO to bound scanHandled
function sendScan(targetId, targetWin, cmd) {
if (!targetId) return runScanCommand(cmd); // null → this frame (local engine, no messaging)
return new Promise(function (resolve) {
const reqId = scanSeq++;
scanPending.set(reqId, resolve);
// Nest the command under `cmd` rather than flattening it into the envelope:
// the scan value-type field is also called `type` and would otherwise overwrite
// the envelope's `type: 'scan-cmd'`, so the target saw an unknown message type
// and silently dropped every remote scan (v1.4.5 fix).
const msg = { type: 'scan-cmd', reqId: reqId, targetFrame: targetId, from: SELF_ID, cmd: cmd };
if (targetWin) { try { postTo(targetWin, msg); } catch (e) {} } // proven channel (clicker/settings use it)
broadcastScanMsg(msg); // + frame-tree broadcast as backup
});
}
/* ------------------------------------------------------------------ *
* UI (Shadow DOM)
* ------------------------------------------------------------------ */
const CSS = `
:host { all: initial; }
#panel {
position: fixed; right: 12px; bottom: 12px; z-index: 2147483647; box-sizing: border-box;
font: 12px/1.4 system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
color: #e8e8ea; background: #1b1d22; border: 1px solid #3a3d44; border-radius: 10px;
box-shadow: 0 10px 30px rgba(0,0,0,.5);
width: 256px; max-width: 92vw; max-height: 82vh;
display: flex; flex-direction: column; overflow: hidden; resize: both; user-select: none;
}
#panel.min { width: auto; height: auto !important; resize: none; }
#panel.min #bar { gap: 4px; padding: 5px 6px; cursor: pointer; }
#panel.min #title, #panel.min #badge, #panel.min .sp, #panel.min #close { display: none; }
#panel * { box-sizing: border-box; }
#bar { display: flex; align-items: center; gap: 6px; padding: 7px 8px; background: #23262d; cursor: grab; }
#bar:active { cursor: grabbing; }
#title { font-weight: 600; }
#badge { padding: 1px 7px; background: #2f6df6; border-radius: 999px; font-weight: 700; font-size: 11px; }
#panel:not(.min) #badge { display: none; }
.sp { flex: 1 1 auto; }
#bar button { all: unset; cursor: pointer; width: 20px; height: 20px; line-height: 20px; text-align: center; border-radius: 5px; color: #cfd2d8; font-size: 14px; }
#bar button:hover { background: #34384199; color: #fff; }
#body { padding: 11px; display: flex; flex-direction: column; gap: 11px; overflow: auto; }
#panel.min #body { display: none; }
.row { display: flex; flex-direction: column; gap: 6px; }
.row .lbl { display: flex; justify-content: space-between; align-items: baseline; color: #aeb2bb; }
.row output { color: #fff; font-weight: 700; }
input[type=range] { width: 100%; accent-color: #2f6df6; }
input[type=number] { all: unset; width: 100%; padding: 5px 8px; background: #14161a; border: 1px solid #3a3d44; border-radius: 6px; color: #fff; font: inherit; }
.presets { display: flex; flex-wrap: wrap; gap: 5px; }
.presets button { all: unset; cursor: pointer; padding: 3px 9px; background: #2a2e36; border: 1px solid #3a3d44; border-radius: 999px; color: #d6d9df; font-size: 11px; }
.presets button:hover { background: #353a44; color: #fff; }
.toggles { display: flex; flex-direction: column; gap: 6px; border-top: 1px solid #2c2f37; padding-top: 9px; }
.tg { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.tg input { accent-color: #2f6df6; cursor: pointer; }
.tg input:disabled { cursor: not-allowed; }
.tg.disabled { opacity: .45; cursor: not-allowed; }
.frames { display: flex; flex-direction: column; gap: 6px; border-top: 1px solid #2c2f37; padding-top: 9px; }
#framesBox[hidden] { display: none; } /* .frames display:flex above defeats the UA [hidden] rule otherwise */
.frames .lbl { color: #aeb2bb; }
#frameList { display: flex; flex-direction: column; gap: 5px; }
.frow { display: flex; align-items: center; gap: 6px; }
.furl { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #d6d9df; font-size: 10.5px; }
.frow button { all: unset; cursor: pointer; padding: 2px 8px; background: #2a2e36; border: 1px solid #3a3d44; border-radius: 999px; color: #d6d9df; font-size: 10.5px; }
.frow button:hover { background: #353a44; color: #fff; }
#reattach { all: unset; cursor: pointer; text-align: center; padding: 6px 8px; background: #2a2e36; border: 1px solid #3a3d44; border-radius: 6px; color: #d6d9df; font-size: 11px; }
#reattach:hover { background: #353a44; color: #fff; }
#reattach[hidden] { display: none; } /* all:unset above resets display to inline, defeating the UA [hidden] rule */
.tabs { display: flex; gap: 4px; padding: 6px 8px 0; background: #23262d; }
#panel.min .tabs { display: none; }
.tab { all: unset; cursor: pointer; padding: 5px 11px; border-radius: 6px 6px 0 0; color: #aeb2bb; font-size: 11.5px; font-weight: 600; }
.tab:hover { color: #fff; }
.tab.active { background: #1b1d22; color: #fff; }
.pane { display: flex; flex-direction: column; gap: 11px; }
.pane[hidden] { display: none; }
.clk-row { display: flex; align-items: center; gap: 8px; }
.clk-row > span.k { flex: 1 1 auto; color: #aeb2bb; }
.clk-grid { display: grid; grid-template-columns: auto 1fr; gap: 7px 8px; align-items: center; }
.clk-grid > span { color: #aeb2bb; }
.clk-grid input[type=number] { width: 100%; }
.clk-btn { all: unset; cursor: pointer; padding: 4px 10px; background: #2a2e36; border: 1px solid #3a3d44; border-radius: 6px; color: #d6d9df; font-size: 11px; }
.clk-btn:hover { background: #353a44; color: #fff; }
.clk-key { font-family: ui-monospace, Menlo, Consolas, monospace; color: #fff; background: #14161a; border: 1px solid #3a3d44; border-radius: 6px; padding: 4px 8px; flex: 1 1 auto; text-align: center; }
.clk-key.listening { color: #f0b07a; border-color: #5a4326; }
.seg { display: flex; gap: 0; border: 1px solid #3a3d44; border-radius: 6px; overflow: hidden; }
.seg button { all: unset; cursor: pointer; flex: 1 1 0; text-align: center; padding: 5px 0; color: #d6d9df; font-size: 11px; }
.seg button.on { background: #2f6df6; color: #fff; font-weight: 600; }
.sc-rowx { display: flex; align-items: center; gap: 6px; }
.sc-rowx > * { min-width: 0; }
.sc-sel { all: unset; cursor: pointer; box-sizing: border-box; display: block; width: 100%; min-width: 0; max-width: 100%; padding: 5px 8px; background: #14161a; border: 1px solid #3a3d44; border-radius: 6px; color: #fff; font: inherit; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.sc-sel[hidden] { display: none; }
.sc-type { flex: 0 0 auto; width: auto; }
#scValue { all: unset; box-sizing: border-box; flex: 1 1 auto; width: 100%; min-width: 0; padding: 5px 8px; background: #14161a; border: 1px solid #3a3d44; border-radius: 6px; color: #fff; font: inherit; }
.sc-pause { display: block; box-sizing: border-box; width: 100%; text-align: center; }
.sc-pause.on { background: #2f6df6; border-color: #2f6df6; color: #fff; }
.sc-btns { display: flex; flex-wrap: wrap; gap: 5px; }
.sc-btns .clk-btn { flex: 1 1 auto; text-align: center; }
.clk-btn[disabled] { opacity: .4; cursor: not-allowed; }
.sc-cancel { background: #3a2417; border-color: #5a4326; color: #f0b07a; }
.sc-cancel:hover { background: #4a2e1d; color: #ffcf9a; }
.sc-cancel[hidden], #scMemDetect[hidden] { display: none; }
#scRefine[hidden] { display: none; }
.sc-count { color: #aeb2bb; font-size: 10.5px; }
.sc-results { display: flex; flex-direction: column; gap: 4px; max-height: 180px; overflow: auto; }
.sc-results:empty { display: none; }
.sc-row { display: flex; align-items: center; gap: 6px; }
.sc-addr { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 10px; color: #9aa0ab; }
.sc-val { all: unset; box-sizing: border-box; width: 74px; padding: 3px 6px; background: #14161a; border: 1px solid #3a3d44; border-radius: 5px; color: #fff; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 10.5px; text-align: right; }
.sc-mini { all: unset; cursor: pointer; padding: 2px 7px; background: #2a2e36; border: 1px solid #3a3d44; border-radius: 999px; color: #d6d9df; font-size: 10px; }
.sc-mini:hover { background: #353a44; color: #fff; }
.sc-saved { display: flex; flex-direction: column; gap: 6px; border-top: 1px solid #2c2f37; padding-top: 9px; }
.sc-saved .lbl { color: #aeb2bb; }
#scSaved { display: flex; flex-direction: column; gap: 5px; }
#scSaved:empty::after { content: 'Nothing saved yet.'; color: #6f747f; font-size: 10.5px; }
.sc-srow { display: flex; align-items: center; gap: 6px; }
.sc-name { all: unset; box-sizing: border-box; flex: 1 1 auto; min-width: 0; padding: 4px 7px; background: #14161a; border: 1px solid #3a3d44; border-radius: 5px; color: #d6d9df; font: inherit; font-size: 11px; overflow: hidden; text-overflow: ellipsis; }
.sc-name:focus { border-color: #2f6df6; color: #fff; }
.sc-name.stale { color: #c77; border-color: #5a2c2c; }
.status { font-size: 10.5px; padding: 5px 7px; border-radius: 6px; }
.status.run { background: #16331f; color: #7fe0a0; }
.status.idle { background: #23262d; color: #aeb2bb; }
.status.ok { background: #16331f; color: #7fe0a0; }
.status.warn { background: #3a2417; color: #f0b07a; }
.note { color: #6f747f; font-size: 10.5px; border-top: 1px solid #2c2f37; padding-top: 8px; }
#dlg { position: fixed; inset: 0; z-index: 2147483647; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,.45); }
#dlg[hidden] { display: none; }
.dlgbox { background: #1b1d22; border: 1px solid #3a3d44; border-radius: 10px; padding: 16px; width: 300px; max-width: 88vw; box-shadow: 0 14px 40px rgba(0,0,0,.6); }
.dlgmsg { font-weight: 600; margin-bottom: 8px; }
.dlgurl { font-size: 10.5px; color: #8b909a; word-break: break-all; background: #14161a; border: 1px solid #2c2f37; border-radius: 6px; padding: 6px 8px; margin-bottom: 14px; }
.dlgbtns { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
.dlgbtns button { all: unset; cursor: pointer; padding: 6px 11px; border-radius: 6px; font-size: 11.5px; }
#dlgYes { background: #2f6df6; color: #fff; font-weight: 600; }
#dlgNo { background: #2a2e36; color: #e8e8ea; border: 1px solid #3a3d44; }
#dlgCancel { color: #aeb2bb; }
#dlgYes:hover { background: #3d79ff; }
`;
const HTML = `
<div id="panel" class="min">
<div id="bar">
<span id="grip">⚡</span>
<span id="title">Speedhack</span>
<span id="badge">1×</span>
<span class="sp"></span>
<button id="min" title="Minimize / expand">–</button>
<button id="close" title="Close">×</button>
</div>
<div class="tabs" id="tabs">
<button class="tab active" data-tab="speed">Speed</button>
<button class="tab" data-tab="clicker">Clicker</button>
<button class="tab" data-tab="scan">Scan</button>
</div>
<div id="body">
<div class="pane" data-pane="speed">
<div id="status" class="status"></div>
<div class="row">
<div class="lbl"><span>Scale factor</span><output id="scaleOut">1×</output></div>
<input id="scaleRange" type="range" min="0.1" max="100" step="0.1" value="1">
<input id="scaleNum" type="number" min="0.1" max="1000" step="0.1" value="1">
<div class="presets">
<button data-s="0.25">0.25×</button>
<button data-s="0.5">0.5×</button>
<button data-s="1">1×</button>
<button data-s="2">2×</button>
<button data-s="5">5×</button>
<button data-s="10">10×</button>
</div>
</div>
<div class="toggles" id="toggles"></div>
<div class="frames" id="framesBox" hidden>
<div class="lbl"><span>Frames on this page</span></div>
<div id="frameList"></div>
</div>
<button id="reattach" hidden>↩ Re-attach to main panel</button>
<div class="note">Settings reset on reload. Only the per-URL “closed” choice is saved.</div>
</div>
<div class="pane" data-pane="clicker" hidden>
<div id="clkStatus" class="status idle"></div>
<div class="seg" id="clkMode">
<button data-mode="toggle">Toggle</button>
<button data-mode="hold">Hold</button>
</div>
<div class="clk-row">
<span class="clk-key" id="clkKey">not set</span>
<button class="clk-btn" id="clkSet">Set</button>
<button class="clk-btn" id="clkClear">Clear</button>
</div>
<label class="tg"><input type="checkbox" id="clkSwallow"><span>Swallow hotkey (hide it from the page)</span></label>
<div class="clk-grid">
<span>Rate (clicks/s)</span><input id="clkCps" type="number" min="0.1" max="100" step="0.1" value="10">
<span>Random (± ms)</span><input id="clkJitter" type="number" min="0" max="2000" step="1" value="0">
<span>Hold (ms)</span><input id="clkHold" type="number" min="0" max="2000" step="1" value="20">
</div>
<div class="note">Clicks at the cursor in whichever (i)frame it is over. Synthetic clicks (isTrusted=false) — some anti-bot/anti-cheat won't accept them.</div>
</div>
<div class="pane" data-pane="scan" hidden>
<select id="scTarget" class="sc-sel" title="Frame to scan"></select>
<button class="clk-btn sc-pause" id="scPause">⏸ Pause</button>
<div id="scStatus" class="status idle"></div>
<div class="seg" id="scEngine">
<button data-engine="wasm" class="on">WASM</button>
<button data-engine="object">JS Objects</button>
</div>
<select id="scMem" class="sc-sel" hidden></select>
<button class="clk-btn sc-pause" id="scMemDetect" hidden>↻ Detect WASM memory</button>
<div class="sc-rowx">
<select id="scType" class="sc-sel sc-type">
<option value="i32" title="32-bit signed integer. The most common type — scores, counts, HP, currency in many games.">int32</option>
<option value="f32" title="32-bit float. Positions, health bars, speeds, timers — typical for Unity/C/C++ (WASM) games.">float32</option>
<option value="f64" title="64-bit float. JavaScript's native number type — the default for JS-object games.">float64</option>
<option value="i8" title="8-bit signed integer (-128..127). Small flags, levels, tiny counters.">int8</option>
<option value="u8" title="8-bit unsigned (0..255). Raw bytes, booleans, RGBA channels, small counters.">uint8</option>
<option value="i16" title="16-bit signed integer (-32768..32767). Medium counters and coordinates.">int16</option>
<option value="u16" title="16-bit unsigned (0..65535). Medium counters, tile/IDs, ammo.">uint16</option>
<option value="u32" title="32-bit unsigned (0..4.29e9). Large counts, currency, timestamps.">uint32</option>
<option value="i64" title="64-bit integer via BigInt. Very large currencies/IDs — WASM only.">int64</option>
<option value="allint" title="Scan every integer width (i8…i64) at once. Use when you know it's a whole number but not the size. WASM only.">all integers</option>
<option value="allfloat" title="Scan both float widths (f32 + f64) at once. Use when unsure which float precision the game uses.">all floats</option>
<option value="all" title="Scan ALL value types at once — slowest, but finds the value whatever its type. WASM only; refine to narrow.">all types</option>
</select>
<input id="scValue" type="text" inputmode="decimal" placeholder="value">
</div>
<div class="sc-btns">
<button class="clk-btn" id="scFirst">First scan</button>
<button class="clk-btn" id="scUnknown" title="Snapshot all values now, then narrow by how they change (Up/Down/Changed) — use when you don't know the value.">Unknown initial</button>
<button class="clk-btn sc-cancel" id="scCancel" hidden>Cancel</button>
</div>
<div class="sc-btns" id="scRefine" hidden>
<button class="clk-btn" data-crit="exact">Exact</button>
<button class="clk-btn" data-crit="changed">Changed</button>
<button class="clk-btn" data-crit="unchanged">Unchanged</button>
<button class="clk-btn" data-crit="increased">▲ Up</button>
<button class="clk-btn" data-crit="decreased">▼ Down</button>
</div>
<div id="scCount" class="sc-count">No scan yet.</div>
<div id="scResults" class="sc-results"></div>
<div class="sc-saved">
<div class="lbl"><span>Saved</span></div>
<div id="scSaved"></div>
</div>
<div class="note">No raw memory in a browser: WASM mode scans a game's WebAssembly heap; JS mode walks values reachable from <code>window</code>. Exact search is only as precise as typed (e.g. <code>1e10</code> matches 1e10–2e10). Pause is speed=0. Saved WASM offsets reset on reload.</div>
</div>
</div>
</div>
<div id="dlg" hidden>
<div class="dlgbox">
<div class="dlgmsg">Remember closing for this exact page?</div>
<div class="dlgurl" id="dlgurl"></div>
<div class="dlgbtns">
<button id="dlgCancel">Cancel</button>
<button id="dlgNo">Just close</button>
<button id="dlgYes">Don’t show here</button>
</div>
</div>
</div>
`;
function shortUrl(u) {
try { const p = new URL(u); return (p.pathname === '/' ? p.host : p.host + p.pathname); }
catch (e) { return String(u).replace(/^[a-z]+:\/\//, ''); }
}
// mode: 'host' (top / promoted — shows frame list) or 'detached' (child with re-attach)
function buildUI(mode) {
let host, root;
try {
host = document.createElement('div');
host.style.all = 'initial';
root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<style>' + CSS + '</style>' + HTML;
try { shieldInputTarget(document.body); } catch (e) {} // now that <body> exists
(document.body || document.documentElement).appendChild(host);
} catch (e) { return null; }
panelHost = host; // so the hotkey listener can ignore keys typed into our own UI
// Input shield: stop events that originate inside the panel from reaching the
// page's own listeners, so clicking/typing in the UI doesn't also drive the game.
// These fire in the BUBBLE phase, AFTER the panel's own handlers have run, then
// stopPropagation() keeps the event from bubbling out to document/window. (A page
// listener registered on window/document in the CAPTURE phase still sees the event —
// nothing in the same DOM can prevent that; detaching into the game's own frame, or
// an input-isolating iframe, would be the only full fix.)
['pointerdown','pointerup','mousedown','mouseup','click','dblclick','contextmenu',
'keydown','keyup','keypress','wheel','touchstart','touchend','pointermove','mousemove'
].forEach(function (t) { host.addEventListener(t, function (e) { e.stopPropagation(); }, false); });
const $ = function (s) { return root.querySelector(s); };
const panel = $('#panel'), bar = $('#bar'), badge = $('#badge'), title = $('#title');
const range = $('#scaleRange'), num = $('#scaleNum'), out = $('#scaleOut');
const btnMin = $('#min'), btnClose = $('#close'), dlg = $('#dlg'), status = $('#status');
const framesBox = $('#framesBox'), frameList = $('#frameList'), reattachBtn = $('#reattach');
// status line — confirms we reached the page's real context
if (hasUnsafe) { status.className = 'status ok'; status.textContent = '✓ patching page context (unsafeWindow)'; }
else { status.className = 'status warn'; status.textContent = '⚠ unsafeWindow not found — using this window. If nothing speeds up, the manager is sandboxing the script.'; }
// toggles (the 5 hooks + turbo)
const tg = $('#toggles');
const hookInputs = {};
Object.keys(hooks).forEach(function (name) {
const lab = document.createElement('label');
lab.className = 'tg';
lab.innerHTML = '<input type="checkbox" ' + (state[name] ? 'checked' : '') + '><span>' + hooks[name].label + '</span>';
const inp = lab.querySelector('input');
hookInputs[name] = inp;
inp.addEventListener('change', function (e) {
setHook(name, e.target.checked);
if (name === 'raf') updateTurboEnabled();
broadcastSettings();
});
tg.appendChild(lab);
});
const tlab = document.createElement('label');
tlab.className = 'tg';
tlab.innerHTML = '<input type="checkbox"><span>rAF turbo — multi-step (experimental)</span>';
const turboInput = tlab.querySelector('input');
turboInput.checked = turbo;
turboInput.addEventListener('change', function (e) { turbo = e.target.checked; turboT = null; broadcastSettings(); });
tg.appendChild(tlab);
// turbo only does anything while the rAF hook is installed
function updateTurboEnabled() {
const on = !!state.raf;
turboInput.disabled = !on;
tlab.classList.toggle('disabled', !on);
}
updateTurboEnabled();
// scale
function reflect(v) { out.textContent = v + '×'; badge.textContent = v + '×'; }
const MAX_SCALE = 1000, SLIDER_MAX = 100, SLIDER_MIN = 0.1;
// writeNum=false while the user is typing into the number field, so we don't
// clobber the caret / intermediate input — that field is normalized on commit.
function onScale(v, writeNum) {
v = Number(v); if (!isFinite(v) || v <= 0) return;
if (v > MAX_SCALE) v = MAX_SCALE; // hard cap, incl. typed-in numbers
applyScale(v);
range.value = Math.min(SLIDER_MAX, Math.max(SLIDER_MIN, v));
if (writeNum !== false) num.value = v;
reflect(v);
broadcastSettings();
}
range.addEventListener('input', function (e) { onScale(e.target.value); });
num.addEventListener('input', function (e) { onScale(e.target.value, false); });
num.addEventListener('change', function (e) { onScale(e.target.value); }); // normalize + cap on commit
root.querySelectorAll('.presets button').forEach(function (b) {
b.addEventListener('click', function () { onScale(b.dataset.s); });
});
// pull controls back in line with current state (used when settings arrive remotely)
function sync() {
Object.keys(hookInputs).forEach(function (n) { hookInputs[n].checked = !!state[n]; });
turboInput.checked = turbo;
updateTurboEnabled();
range.value = Math.min(SLIDER_MAX, Math.max(SLIDER_MIN, scale));
num.value = scale;
reflect(scale);
}
// frame list (host mode) — one row per child frame that has announced itself
function refreshFrames() {
refreshScanTargets();
if (curMode !== 'host') { framesBox.hidden = true; return; }
pruneFrames();
frameList.textContent = '';
if (frames.size === 0) { framesBox.hidden = true; return; }
framesBox.hidden = false;
frames.forEach(function (f, src) {
const row = document.createElement('div'); row.className = 'frow';
const label = document.createElement('span'); label.className = 'furl';
label.textContent = shortUrl(f.url); label.title = f.url;
const btn = document.createElement('button');
btn.textContent = f.attached ? 'Detach' : 'Re-attach';
btn.addEventListener('click', function () { f.attached ? detachFrame(src) : reattachFrame(src); });
row.appendChild(label); row.appendChild(btn);
frameList.appendChild(row);
});
}
reattachBtn.addEventListener('click', function () {
if (hostWin) postTo(hostWin, { type: 'reattach' });
attached = true;
destroyPanel(); // back to headless; host will resend settings
});
// tabs
const panes = {};
root.querySelectorAll('.pane').forEach(function (p) { panes[p.dataset.pane] = p; });
const tabBtns = root.querySelectorAll('.tab');
function setTab(name) {
tabBtns.forEach(function (b) { b.classList.toggle('active', b.dataset.tab === name); });
Object.keys(panes).forEach(function (n) { panes[n].hidden = (n !== name); });
}
tabBtns.forEach(function (b) { b.addEventListener('click', function () { setTab(b.dataset.tab); }); });
/* ----- clicker controls ----- */
const clkStatus = $('#clkStatus'), clkKey = $('#clkKey'), clkSet = $('#clkSet'), clkClear = $('#clkClear');
const clkSwallow = $('#clkSwallow'), clkCps = $('#clkCps'), clkJitter = $('#clkJitter'), clkHold = $('#clkHold');
const clkModeBtns = root.querySelectorAll('#clkMode button');
function keyLabel(hk) {
if (!hk) return 'not set';
return (hk.ctrl ? 'Ctrl+' : '') + (hk.alt ? 'Alt+' : '') + (hk.shift ? 'Shift+' : '') + (hk.meta ? 'Meta+' : '') +
(hk.key === ' ' ? 'Space' : hk.key);
}
function syncClicker() {
clkModeBtns.forEach(function (b) { b.classList.toggle('on', b.dataset.mode === clicker.mode); });
clkKey.textContent = clicker.listening ? 'press a key…' : keyLabel(clicker.hotkey);
clkKey.classList.toggle('listening', clicker.listening);
clkSwallow.checked = clicker.swallowHotkey;
// root.activeElement (not document.activeElement) sees focus *inside* the shadow root,
// so we don't overwrite a field the user is currently typing into.
if (root.activeElement !== clkCps) clkCps.value = clicker.cps;
if (root.activeElement !== clkJitter) clkJitter.value = clicker.jitterMs;
if (root.activeElement !== clkHold) clkHold.value = clicker.holdMs;
clkStatus.className = 'status ' + (clicker.running ? 'run' : 'idle');
clkStatus.textContent = clicker.running
? '● clicking — ' + Math.round(clicker.cps) + '/s at cursor'
: (clicker.hotkey ? '○ idle — press ' + keyLabel(clicker.hotkey) + ' to ' + (clicker.mode === 'hold' ? 'hold' : 'toggle')
: '○ idle — set a hotkey to start');
}
clkModeBtns.forEach(function (b) {
b.addEventListener('click', function () {
clicker.mode = b.dataset.mode;
if (clicker.running) setClickerRunning(false, true); // mode switch is a clean stop
syncClicker(); broadcastClickerConfig();
});
});
clkSet.addEventListener('click', function () { clicker.listening = true; syncClicker(); });
clkClear.addEventListener('click', function () {
if (clicker.running) setClickerRunning(false, true);
clicker.hotkey = null; clicker.listening = false; syncClicker(); broadcastClickerConfig();
});
clkSwallow.addEventListener('change', function (e) { clicker.swallowHotkey = e.target.checked; broadcastClickerConfig(); });
function commitNum(input, key, min, max) {
let v = Number(input.value);
if (!isFinite(v)) return;
v = Math.min(max, Math.max(min, v));
clicker[key] = v;
broadcastClickerConfig();
}
clkCps.addEventListener('input', function () { commitNum(clkCps, 'cps', 0.1, MAX_CPS); });
clkCps.addEventListener('change', function () { clkCps.value = clicker.cps; });
clkJitter.addEventListener('input', function () { commitNum(clkJitter, 'jitterMs', 0, 2000); });
clkJitter.addEventListener('change', function () { clkJitter.value = clicker.jitterMs; });
clkHold.addEventListener('input', function () { commitNum(clkHold, 'holdMs', 0, 2000); });
clkHold.addEventListener('change', function () { clkHold.value = clicker.holdMs; });
syncClicker();
/* ----- scan controls ----- */
const scTarget = $('#scTarget'), scPause = $('#scPause'), scStatus = $('#scStatus');
const scMem = $('#scMem'), scMemDetect = $('#scMemDetect'), scType = $('#scType'), scValue = $('#scValue');
const scFirst = $('#scFirst'), scUnknown = $('#scUnknown'), scCancel = $('#scCancel');
const scRefine = $('#scRefine'), scCount = $('#scCount'), scResults = $('#scResults'), scSaved = $('#scSaved');
const scEngineBtns = root.querySelectorAll('#scEngine button');
const scRefineBtns = root.querySelectorAll('#scRefine button');
let scEngineName = 'wasm';
let scTargetId = null; // null → this frame; else a remote frame's SELF_ID
let scTargetWin = null; // that frame's window (proven postMessage channel)
const scTargetList = []; // [{ id, win }] parallel to scTarget options (after the first)
let savedScans = store.get('scan:' + PAGE, []) || [];
let scanActive = false; // a candidate set exists (refine available)
let scanRunning = false; // a scan op is in flight
let pausedLocalView = false;
function scCmd(extra) {
const cmd = { engine: scEngineName, type: scType.value };
for (const k in extra) cmd[k] = extra[k];
return sendScan(scTargetId, scTargetWin, cmd);
}
// Two independent status lines so they never clobber each other:
// - setConn(): frame / WASM-memory / pause state (top, #scStatus)
// - setScan(): scan progress + result counts (#scCount)
function setConn(kind, text) { scStatus.className = 'status ' + kind; scStatus.textContent = text; }
function setScan(text) { scCount.textContent = text; }
function refreshScanTargets() {
const prev = scTarget.value;
scTargetList.length = 0;
scTarget.textContent = '';
const self = document.createElement('option'); self.value = 'self'; self.textContent = 'This frame';
scTarget.appendChild(self);
// `frames` is only populated in host mode; a detached child just sees itself.
frames.forEach(function (f, src) {
if (!f.id) return;
const idx = scTargetList.push({ id: f.id, win: src }) - 1;
const opt = document.createElement('option');
opt.value = 'f' + idx; opt.textContent = shortUrl(f.url); opt.title = f.url;
scTarget.appendChild(opt);
});
scTarget.value = Array.prototype.some.call(scTarget.options, function (o) { return o.value === prev; }) ? prev : 'self';
applyTargetSelection();
}
function applyTargetSelection() {
const v = scTarget.value;
const ent = (v === 'self') ? null : scTargetList[+v.slice(1)];
scTargetId = ent ? ent.id : null;
scTargetWin = ent ? ent.win : null;
}
// Reflect scanActive / scanRunning onto the buttons.
function updateButtons() {
scFirst.textContent = scanActive ? 'New scan' : 'First scan';
scFirst.disabled = scanRunning;
scUnknown.hidden = scanActive;
scUnknown.disabled = scanRunning;
scCancel.hidden = !scanRunning;
scRefine.hidden = !scanActive;
scRefineBtns.forEach(function (b) { b.disabled = scanRunning || !scanActive; });
scType.disabled = scanRunning; scValue.disabled = scanRunning;
scMemDetect.disabled = scanRunning;
}
function setEngine(name) {
scEngineName = name;
scEngineBtns.forEach(function (b) { b.classList.toggle('on', b.dataset.engine === name); });
const wasm = (name === 'wasm');
scMemDetect.hidden = !wasm;
scMem.hidden = true;
newScan();
if (wasm) { refreshMemList(); return; }
// object-graph engine: confirm a remote frame is reachable (same short
// connectivity timer as WASM detect; not a scan timeout).
if (!scTargetId) { setConn('idle', 'Walking values reachable from this frame’s window.'); return; }
const id = scTargetId; let settled = false;
setConn('idle', 'Connecting to frame…');
origSetTimeout(function () {
if (settled || scTargetId !== id || scEngineName !== 'object') return;
settled = true; setConn('warn', 'No response from that frame. If it just loaded, re-select it; otherwise open the frame’s own panel and scan there.');
}, 2500);
scCmd({ op: 'ping' }).then(function (res) {
if (settled || scTargetId !== id || scEngineName !== 'object') return;
settled = true; setConn(res && res.ok ? 'ok' : 'warn', res && res.ok ? 'Frame connected — walking values reachable from its window.' : 'Frame not responding.');
});
}
// Manual WASM-memory detection (no polling). Updates the memory dropdown + status.
// For a remote target this doubles as the connectivity check: a short real-time
// timer (NOT a scan timeout — scans still wait indefinitely) flips the status to
// "not responding" if the frame never answers, instead of hanging on "Detecting…".
function refreshMemList() {
if (scEngineName !== 'wasm') return;
const id = scTargetId; let settled = false;
setConn('idle', 'Detecting WASM memory…');
if (id) origSetTimeout(function () {
if (settled || scTargetId !== id || scEngineName !== 'wasm') return;
settled = true; scMem.hidden = true;
setConn('warn', 'No response from that frame. If the game is still loading, click “Detect” again; otherwise open the frame’s own panel and scan there.');
}, 2500);
scCmd({ op: 'list-memories' }).then(function (res) {
if (settled || scEngineName !== 'wasm' || scTargetId !== id) return; // stale/superseded
settled = true;
if (!res || res.ok === false) { scMem.hidden = true; setConn('warn', id ? 'Target frame not responding — try detaching its panel and scanning there.' : 'Frame not responding.'); return; }
const mems = res.memories || [];
const prev = scMem.value;
scMem.textContent = '';
mems.forEach(function (m, i) { const o = document.createElement('option'); o.value = String(i); o.textContent = m.label; scMem.appendChild(o); });
if (prev && mems[+prev]) scMem.value = prev;
scMem.hidden = mems.length === 0;
scMemDetect.textContent = mems.length ? '↻ Re-detect WASM memory' : '↻ Detect WASM memory';
if (mems.length === 0) setConn('warn', 'No WASM memory' + (id ? ' in that frame' : '') + ' yet. If the game is still loading, click “Detect” again.');
else setConn('ok', mems.length + ' WASM memor' + (mems.length === 1 ? 'y' : 'ies') + ' found.');
});
}
function newScan() {
scanActive = false;
scResults.textContent = '';
setScan('No scan yet.');
updateButtons();
scCmd({ op: 'reset' });
}
function setScanRunning(on) { scanRunning = on; updateButtons(); }
function onScanDone(res) {
setScanRunning(false);
if (!res || !res.ok) { setScan('Scan failed: ' + ((res && res.error) || 'unknown')); return; }
if (res.cancelled) { setScan('Scan cancelled.'); updateButtons(); return; }
scanActive = true;
updateButtons();
if (res.count === -1) {
setScan('Unknown scan armed — change the value in-game, then refine (Up / Down / Changed).');
} else if (res.capped) {
setScan(res.count.toLocaleString() + ' matches — too many to list; refine to narrow.');
} else {
setScan(res.count.toLocaleString() + ' match' + (res.count === 1 ? '' : 'es') + (res.count > 200 ? ' (showing first 200)' : ''));
}
renderRows(res.rows || []);
}
function startScan(cmd, progress) {
if (scanRunning) return;
setScanRunning(true);
setScan(progress);
scCmd(cmd).then(onScanDone);
}
function renderRows(rows) {
scResults.textContent = '';
rows.forEach(function (r) {
const row = document.createElement('div'); row.className = 'sc-row'; row.dataset.addr = r.address;
const addr = document.createElement('span'); addr.className = 'sc-addr';
addr.textContent = scanAddressLabel(scEngineName, r.address); addr.title = addr.textContent;
const val = document.createElement('input'); val.className = 'sc-val'; val.value = (r.value == null ? '?' : r.value);
val.addEventListener('change', function () { scCmd({ op: 'write', address: r.address, value: val.value }); });
const save = document.createElement('button'); save.className = 'sc-mini'; save.textContent = '★';
save.title = 'Save this result';
save.addEventListener('click', function () { addSaved(r.address, r.type); });
row.appendChild(addr); row.appendChild(val); row.appendChild(save);
scResults.appendChild(row);
});
}
// live re-read of shown result rows + saved rows (real-time; unaffected by pause)
const scPane = root.querySelector('.pane[data-pane="scan"]');
function pollValues() {
if (scPane && scPane.hidden) return; // only poll while the Scan tab is open
const rowEls = Array.prototype.slice.call(scResults.querySelectorAll('.sc-row'));
const addrs = rowEls.map(function (el) { return el.dataset.addr; });
if (addrs.length) {
scCmd({ op: 'read', addresses: addrs }).then(function (res) {
if (!res || !res.values) return;
const byAddr = {}; res.values.forEach(function (v) { byAddr[v.address] = v.value; });
rowEls.forEach(function (el) {
const inp = el.querySelector('.sc-val');
if (inp && root.activeElement !== inp) inp.value = (byAddr[el.dataset.addr] == null ? '?' : byAddr[el.dataset.addr]);
});
});
}
pollSaved();
}
/* ----- saved list ----- */
function persistSaved() { store.set('scan:' + PAGE, savedScans); }
function addSaved(address, ty) {
savedScans.push({ name: scanAddressLabel(scEngineName, address), engine: scEngineName, type: (ty || scType.value), address: address });
persistSaved(); renderSaved();
}
function renderSaved() {
scSaved.textContent = '';
savedScans.forEach(function (s, i) {
const row = document.createElement('div'); row.className = 'sc-srow'; row.dataset.idx = i;
const name = document.createElement('input'); name.className = 'sc-name'; name.value = s.name;
name.title = scanAddressLabel(s.engine, s.address) + ' (' + s.type + ')';
name.addEventListener('change', function () { s.name = name.value; persistSaved(); });
const val = document.createElement('input'); val.className = 'sc-val'; val.value = '?';
val.addEventListener('change', function () { sendScan(scTargetId, scTargetWin, { engine: s.engine, type: s.type, op: 'write', address: s.address, value: val.value }); });
const del = document.createElement('button'); del.className = 'sc-mini'; del.textContent = '×'; del.title = 'Delete';
del.addEventListener('click', function () { savedScans.splice(i, 1); persistSaved(); renderSaved(); });
row.appendChild(name); row.appendChild(val); row.appendChild(del);
scSaved.appendChild(row);
});
}
function pollSaved() {
const rowEls = Array.prototype.slice.call(scSaved.querySelectorAll('.sc-srow'));
rowEls.forEach(function (el) {
const s = savedScans[+el.dataset.idx]; if (!s) return;
sendScan(scTargetId, scTargetWin, { engine: s.engine, type: s.type, op: 'read', addresses: [s.address] }).then(function (res) {
const inp = el.querySelector('.sc-val'); if (!inp || root.activeElement === inp) return;
const v = res && res.values && res.values[0] ? res.values[0].value : null;
inp.value = (v == null ? '∅' : v);
el.querySelector('.sc-name').classList.toggle('stale', v == null);
});
});
}
// wire scan controls
scEngineBtns.forEach(function (b) { b.addEventListener('click', function () { setEngine(b.dataset.engine); }); });
scTarget.addEventListener('change', function () { applyTargetSelection(); setEngine(scEngineName); });
scMem.addEventListener('change', function () { scCmd({ op: 'set-mem', mem: +scMem.value }).then(newScan); });
scMemDetect.addEventListener('click', function () { refreshMemList(); });
scType.addEventListener('change', function () { const o = scType.options[scType.selectedIndex]; scType.title = o ? o.title : ''; });
scFirst.addEventListener('click', function () {
if (scanActive) { newScan(); return; } // acts as "New scan" once a scan exists
const raw = scValue.value.trim();
if (raw === '') { setScan('Enter a value, or use “Unknown initial”.'); return; }
startScan({ op: 'first-exact', value: raw }, 'Scanning…');
});
scUnknown.addEventListener('click', function () { startScan({ op: 'first-unknown' }, 'Snapshotting…'); });
scCancel.addEventListener('click', function () { setScan('Cancelling…'); scCmd({ op: 'cancel' }); });
scRefineBtns.forEach(function (b) {
b.addEventListener('click', function () {
const crit = b.dataset.crit, raw = scValue.value.trim();
startScan({ op: 'refine', criteria: crit, value: (crit === 'exact' && raw !== '') ? raw : undefined }, 'Refining…');
});
});
scPause.addEventListener('click', function () {
scCmd({ op: 'set-paused', value: !pausedLocalView }).then(function (res) {
pausedLocalView = !!(res && res.paused);
reflectPause();
});
});
function reflectPause() {
scPause.textContent = pausedLocalView ? '▶ Resume' : '⏸ Pause';
scPause.classList.toggle('on', pausedLocalView);
}
scType.title = scType.options[scType.selectedIndex] ? scType.options[scType.selectedIndex].title : '';
renderSaved();
setEngine('wasm');
reflectPause();
const scPoll = origSetInterval(pollValues, 600); // real-time; unaffected by speed/pause
let curMode;
function setMode(m) {
curMode = m;
if (m === 'host') { title.textContent = 'Speedhack'; reattachBtn.hidden = true; refreshFrames(); }
else { title.textContent = 'Speedhack (frame)'; framesBox.hidden = true; reattachBtn.hidden = false; }
}
setMode(mode || 'host');
// minimize (start minimized)
function setMin(m) { panel.classList.toggle('min', m); btnMin.textContent = m ? '▢' : '–'; }
setMin(true);
btnMin.addEventListener('click', function (e) { e.stopPropagation(); setMin(!panel.classList.contains('min')); });
// close + remember dialog
btnClose.addEventListener('click', function (e) { e.stopPropagation(); $('#dlgurl').textContent = PAGE; dlg.hidden = false; });
$('#dlgCancel').addEventListener('click', function () { dlg.hidden = true; });
$('#dlgNo').addEventListener('click', function () { doClose(false); });
$('#dlgYes').addEventListener('click', function () { doClose(true); });
function doClose(remember) {
if (remember) store.set(CLOSED_KEY, true);
Object.keys(hooks).forEach(function (n) { try { hooks[n].uninstall(); } catch (e) {} });
// The host is going away, so there's nothing left to re-attach to. Tell EVERY
// frame (attached or already-detached) to become its own standalone main panel
// rather than a detached one with a dead "re-attach" button. `hostClosed` also
// makes us hand off any iframe that announces itself AFTER this point.
if (isHost) {
hostClosed = true;
frames.forEach(function (f, src) { f.attached = false; postTo(src, { type: 'host-closing' }); });
}
destroyPanel();
}
// drag (and tap-to-expand when minimized)
let dragging = false, moved = false, sx, sy, ox, oy;
bar.addEventListener('pointerdown', function (e) {
if (e.target.closest('button')) return;
dragging = true; moved = false;
const r = panel.getBoundingClientRect();
panel.style.left = r.left + 'px'; panel.style.top = r.top + 'px';
panel.style.right = 'auto'; panel.style.bottom = 'auto';
sx = e.clientX; sy = e.clientY; ox = r.left; oy = r.top;
try { bar.setPointerCapture(e.pointerId); } catch (_) {}
});
bar.addEventListener('pointermove', function (e) {
if (!dragging) return;
const dx = e.clientX - sx, dy = e.clientY - sy;
if (Math.abs(dx) > 4 || Math.abs(dy) > 4) moved = true;
panel.style.left = Math.max(0, Math.min(window.innerWidth - 30, ox + dx)) + 'px';
panel.style.top = Math.max(0, Math.min(window.innerHeight - 20, oy + dy)) + 'px';
});
bar.addEventListener('pointerup', function (e) {
if (!dragging) return; dragging = false;
try { bar.releasePointerCapture(e.pointerId); } catch (_) {}
if (!moved && panel.classList.contains('min')) setMin(false);
});
return {
removeNode: function () { try { origClearInterval(scPoll); } catch (e) {} try { host.remove(); } catch (e) {} if (panelHost === host) panelHost = null; clicker.listening = false; },
refreshFrames: refreshFrames,
refreshScan: refreshScanTargets,
setMode: setMode,
sync: sync,
syncClicker: syncClicker
};
}
/* ------------------------------------------------------------------ *
* Panel lifecycle — build lazily once a host node exists; rebuildable
* (a child may gain/lose a panel as it detaches / re-attaches).
* ------------------------------------------------------------------ */
let panelCtl = null;
let pendingMode = 'host';
function whenBody(fn) {
if (document.body) { fn(); return; }
const obs = new MutationObserver(function () { if (document.body) { obs.disconnect(); fn(); } });
try { obs.observe(document.documentElement, { childList: true, subtree: true }); } catch (e) {}
document.addEventListener('DOMContentLoaded', function () { try { obs.disconnect(); } catch (e) {} fn(); }, { once: true });
}
function ensurePanel(mode) {
pendingMode = mode;
if (panelCtl) { panelCtl.setMode(mode); return; }
whenBody(function () {
if (panelCtl) { panelCtl.setMode(pendingMode); return; }
if (!(document.body || document.documentElement)) return;
panelCtl = buildUI(pendingMode);
});
}
function destroyPanel() {
if (panelCtl) { panelCtl.removeNode(); panelCtl = null; }
}
/* ------------------------------------------------------------------ *
* Boot. Top frame hosts and rolls call; a child announces itself and
* arms a real-time 5s fallback to promote if no host ever answers.
* ------------------------------------------------------------------ */
if (isTop) {
ensurePanel('host');
rollcall();
} else {
postTo(window.top, { type: 'hello', url: location.href, frameId: SELF_ID });
// origSetTimeout (real time) so scaling can't distort the 5s fallback window.
origSetTimeout(function () { if (!gotHost) promoteToHost(); }, 5000);
}
})();