speedhack.js modernization

AuthorKonata <konata@posteo.jp>
Date
Commit7428829ff96825231bad71aae56f0160a4e5387f
Parent93e4952
1 file changed, 579 insertions(+), 623 deletions(-)
▾Mspeedhack.js
@@ -1,6 +1,6 @@
// ==UserScript==
// @name Speedhack Panel
// @version 1.0.0
// @version 1.1.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
@@ -13,7 +13,7 @@
/* 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
@@ -31,7 +31,7 @@
* ------------------------------------------------------------------ */
const RealDate = pageWin.Date;
const origDateNow = RealDate.now.bind(RealDate);
const origPerfNow = (pageWin.performance && pageWin.performance.now)
const origPerfNow = pageWin.performance?.now
? pageWin.performance.now.bind(pageWin.performance)
: origDateNow;
const origSetTimeout = pageWin.setTimeout.bind(pageWin);
@@ -39,7 +39,7 @@
const origClearTimeout = pageWin.clearTimeout.bind(pageWin);
const origClearInterval= pageWin.clearInterval.bind(pageWin);
const origRAF = (pageWin.requestAnimationFrame ||
function (cb) { return origSetTimeout(function () { cb(origPerfNow()); }, 16); }
(cb => origSetTimeout(() => cb(origPerfNow()), 16))
).bind(pageWin);
/* ------------------------------------------------------------------ *
@@ -55,55 +55,38 @@
(function hookWasm() {
const W = pageWin.WebAssembly;
if (!W) return;
function record(m, label) {
const 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)) });
if (wasmMemories.some(e => e.memory === m)) return;
wasmMemories.push({ memory: m, label: label || ('mem#' + wasmMemories.length) });
} catch (e) {}
}
function scanExports(res) {
};
const 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;
const ex = (res?.instance ?? res)?.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;
};
const wrapInstantiate = (orig) => function () {
const p = orig.apply(this, arguments);
return (typeof p?.then === 'function') ? p.then(scanExports) : p;
};
if (typeof W.instantiate === 'function') W.instantiate = wrapInstantiate(W.instantiate);
if (typeof W.instantiateStreaming === 'function') W.instantiateStreaming = wrapInstantiate(W.instantiateStreaming);
const patchCtor = (Orig, onNew) => {
function Patched(...args) {
const obj = Reflect.construct(Orig, args, new.target || Patched);
onNew(obj);
return obj;
}
PatchedMemory.prototype = OrigMemory.prototype;
try { W.Memory = PatchedMemory; } catch (e) {}
}
Patched.prototype = Orig.prototype;
return Patched;
};
if (typeof W.Instance === 'function') { try { W.Instance = patchCtor(W.Instance, scanExports); } catch (e) {} }
if (typeof W.Memory === 'function') { try { W.Memory = patchCtor(W.Memory, m => record(m, 'Memory()')); } catch (e) {} }
})();
/* ------------------------------------------------------------------ *
@@ -116,24 +99,24 @@
* 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 SHIELD_TYPES = new Set(['keydown', 'keyup', 'keypress', 'pointerdown', 'pointerup',
'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu',
'wheel', 'touchstart', 'touchend']);
const shieldedTargets = new WeakSet();
function eventInPanel(ev) {
try { return !!(panelHost && ev && ev.composedPath && ev.composedPath().indexOf(panelHost) !== -1); } catch (e) { return false; }
try { return !!(panelHost && ev?.composedPath && ev.composedPath().includes(panelHost)); } 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 }
const captureOf = (opts) => (typeof opts === 'object' && opts) ? !!opts.capture : !!opts;
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);
if (!usable || !SHIELD_TYPES.has(type) || handler.__shxNoShield) return origAdd.call(this, type, handler, opts);
const key = type + '/' + (captureOf(opts) ? 1 : 0);
let per = wrappers.get(handler); if (!per) { per = Object.create(null); wrappers.set(handler, per); }
let wrapper = per[key];
if (!wrapper) {
@@ -143,16 +126,15 @@
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)];
if (!handler || !SHIELD_TYPES.has(type)) return origRemove.call(this, type, handler, opts);
const wrapper = wrappers.get(handler)?.[type + '/' + (captureOf(opts) ? 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) {}
try { shieldInputTarget(pageWin.document?.documentElement); } catch (e) {}
// <body> may not exist yet at document-start; it's shielded when the panel is built.
/* ------------------------------------------------------------------ *
@@ -162,11 +144,11 @@
* ------------------------------------------------------------------ */
const PAGE = location.href.split('#')[0]; // "exact" page URL, ignoring #hash
const store = {
get: function (k, d) {
get(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; }
try { const v = localStorage.getItem('shx_' + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; }
},
set: function (k, v) {
set(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) {}
}
@@ -185,10 +167,10 @@
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
now: () => aFake + (realFn() - aReal) * s,
setScale: (ns) => { const r = realFn(); aFake = aFake + (r - aReal) * s; aReal = r; s = ns; },
reanchor: () => { const r = realFn(); aReal = r; aFake = r; },
setTo: (v) => { aReal = realFn(); aFake = v; } // jump the fake timeline to absolute v
};
}
const dateClock = makeClock(origDateNow);
@@ -202,7 +184,7 @@
dateClock.setScale(ns);
perfClock.setScale(ns);
}
function perfRead() { return (turboNow !== null) ? turboNow : perfClock.now(); }
const perfRead = () => (turboNow !== null) ? turboNow : perfClock.now();
/* ------------------------------------------------------------------ *
* Pause (for the Scan tab). scale=0 is normally rejected by applyScale,
@@ -231,14 +213,13 @@
/* ------------------------------------------------------------------ *
* Fake Date
* ------------------------------------------------------------------ */
function FakeDate() {
const args = Array.prototype.slice.call(arguments);
function FakeDate(...args) {
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)))();
return new RealDate(...args);
}
FakeDate.prototype = RealDate.prototype;
FakeDate.now = function () { return Math.floor(dateClock.now()); };
FakeDate.now = () => Math.floor(dateClock.now());
FakeDate.parse = RealDate.parse.bind(RealDate);
FakeDate.UTC = RealDate.UTC.bind(RealDate);
try { Object.setPrototypeOf(FakeDate, RealDate); } catch (e) {}
@@ -264,8 +245,8 @@
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); };
pageWin.clearInterval = (id) => { if (clearFake(id)) return; return origClearInterval(id); };
pageWin.clearTimeout = (id) => { if (clearFake(id)) return; return origClearTimeout(id); };
}
/* ------------------------------------------------------------------ *
@@ -274,39 +255,37 @@
const hooks = {
date: {
label: 'Date (Date.now / new Date)',
install: function () { dateClock.reanchor(); pageWin.Date = FakeDate; },
uninstall: function () { pageWin.Date = RealDate; }
install: () => { dateClock.reanchor(); pageWin.Date = FakeDate; },
uninstall: () => { 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; }
install: () => { perfClock.reanchor(); if (pageWin.performance) pageWin.performance.now = () => perfRead(); },
uninstall: () => { 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);
install: () => {
pageWin.setTimeout = (fn, delay, ...rest) => {
if (typeof delay === 'number' && isFinite(delay)) delay = delay / scale;
return origSetTimeout.apply(null, [fn, delay].concat(rest));
return origSetTimeout(fn, delay, ...rest);
};
},
uninstall: function () { pageWin.setTimeout = origSetTimeout; }
uninstall: () => { pageWin.setTimeout = origSetTimeout; }
},
setInterval: {
label: 'setInterval',
install: function () {
install: () => {
installClearHooks();
pageWin.setInterval = function (fn, delay) {
const rest = Array.prototype.slice.call(arguments, 2);
pageWin.setInterval = (fn, delay, ...rest) => {
// 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);
return origSetInterval(fn, delay, ...rest);
}
const id = 'shx_int_' + (intervalSeq++);
const rec = { timer: 0, cancelled: false };
fakeIntervals.set(id, rec);
function tick() {
const 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
@@ -314,7 +293,7 @@
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;
@@ -322,44 +301,42 @@
},
// 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; }
uninstall: () => { 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
});
};
install: () => {
pageWin.requestAnimationFrame = (cb) => origRAF(() => {
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 = (next) => { if (typeof next === 'function') nextCbs.push(next); return 0; };
for (const c of currentCbs) { try { c(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 (const c of currentCbs) pageWin.requestAnimationFrame(c); // next REAL frame
});
},
uninstall: function () { pageWin.requestAnimationFrame = origRAF; }
uninstall: () => { pageWin.requestAnimationFrame = origRAF; }
}
};
@@ -369,7 +346,7 @@
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) {} } });
for (const n of Object.keys(hooks)) if (state[n]) { try { hooks[n].install(); } catch (e) {} }
/* ------------------------------------------------------------------ *
* Multi-frame coordination.
@@ -379,7 +356,7 @@
* 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; } })();
const isTop = (() => { 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
@@ -392,42 +369,35 @@
// 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 };
}
const settingsMsg = (type) => ({ type, scale, turbo, hooks: { ...state } });
function applySettings(s) {
if (s.hooks) Object.keys(s.hooks).forEach(function (n) {
if (s.hooks) for (const n of Object.keys(s.hooks)) {
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();
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.
// The one cross-origin-safe recursive walk over the live frame tree (root =
// window.top by default, i.e. every frame on the page except the root itself).
const topWin = () => { try { return window.top; } catch (e) { return window; } };
function forEachFrame(cb, root = topWin()) {
let list; try { list = root.frames; } catch (e) { return; }
for (let i = 0; i < list.length; i++) {
try { cb(list[i]); } catch (e) {}
forEachFrame(cb, list[i]);
}
}
// Deliver a scan message to EVERY frame in the tree (root + 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);
postTo(topWin(), msg);
forEachFrame(w => postTo(w, msg));
}
function pruneFrames() {
@@ -435,29 +405,20 @@
// 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);
forEachFrame(w => live.add(w));
let changed = false;
frames.forEach(function (f, src) { if (!live.has(src)) { frames.delete(src); changed = true; } });
frames.forEach((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')); });
frames.forEach((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);
forEachFrame(w => postTo(w, { type: 'rollcall' }));
}
function promoteToHost() {
if (isHost) return;
@@ -468,100 +429,90 @@
function detachFrame(src) {
const f = frames.get(src); if (!f) return;
f.attached = false; postTo(src, { type: 'detach' });
if (panelCtl) panelCtl.refreshFrames();
panelCtl?.refreshFrames();
}
function reattachFrame(src) {
const f = frames.get(src); if (!f) return;
f.attached = true; postTo(src, settingsMsg('attach'));
if (panelCtl) panelCtl.refreshFrames();
panelCtl?.refreshFrames();
}
window.addEventListener('message', function (e) {
// One named handler per message type; hostOnly/childOnly guards applied by the dispatcher.
const MSG = {
hello: { hostOnly: true, fn(m, e) { // host: a child announced itself
if (hostClosed) { postTo(e.source, { type: 'host-closing' }); return; } // late frame after close → go standalone
const f = frames.get(e.source);
if (f) { f.url = m.url; if (m.frameId) f.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 });
panelCtl?.refreshFrames();
} },
rollcall: { childOnly: true, fn(m, e) { // child: a host is probing for frames
gotHost = true; hostWin = e.source;
postTo(e.source, { type: 'hello', url: location.href, frameId: SELF_ID });
} },
settings: { childOnly: true, fn(m, e) { // child: host pushed settings
gotHost = true; hostWin = e.source;
if (attached) applySettings(m);
} },
detach: { childOnly: true, fn(m, e) { // child: host detached us → own panel
hostWin = e.source; attached = false;
ensurePanel('detached');
} },
'host-closing': { childOnly: true, fn() { // child: the host closed → become standalone
promoteToHost(); // host mode (no re-attach button), self-sufficient
} },
attach: { childOnly: true, fn(m) { // child: host folded us back in
attached = true; destroyPanel(); applySettings(m);
} },
reattach: { hostOnly: true, fn(m, e) { // host: a detached child asked to fold back
const f = frames.get(e.source);
if (f) { f.attached = true; postTo(e.source, settingsMsg('settings')); panelCtl?.refreshFrames(); }
} },
'clicker-config': { childOnly: true, fn(m) { // child: host pushed clicker settings
applyClickerConfig(m);
} },
'clicker-run': { fn(m) { // shared autoclicker running state
// host: a child toggled it → adopt + fan out to all; child: host pushed it down.
setClickerRunning(m.on, isHost);
} },
'scan-cmd': { fn(m, e) { // any frame: if addressed to me, run + reply
if (m.targetFrame && m.targetFrame !== SELF_ID) return; // broadcast not meant for this frame
const dkey = (m.from || '') + ':' + m.reqId;
if (scanHandled.has(dkey)) return; // 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)
let lastFrac = -2; // throttle determinate progress to ~2% steps (indeterminate always relayed)
runScanCommand(scmd, (frac) => {
if (frac >= 0 && frac !== 1 && frac - lastFrac < 0.02) return;
lastFrac = frac;
try { if (replyWin) postTo(replyWin, { type: 'scan-progress', reqId: m.reqId, targetFrame: m.from, frac }); } catch (e2) {}
}).then((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)
});
} },
'scan-progress': { fn(m) { // controller: forward incremental progress to the UI
if (m.targetFrame && m.targetFrame !== SELF_ID) return;
scanProgress.get(m.reqId)?.(m.frac);
} },
'scan-result': { fn(m) { // controller: resolve the matching pending request
if (m.targetFrame && m.targetFrame !== SELF_ID) return;
scanProgress.delete(m.reqId);
const resolve = scanPending.get(m.reqId);
if (resolve) { scanPending.delete(m.reqId); resolve(m); }
} }
};
window.addEventListener('message', (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)
let lastFrac = -2; // throttle determinate progress to ~2% steps (indeterminate always relayed)
runScanCommand(scmd, function (frac) {
if (frac >= 0 && frac !== 1 && frac - lastFrac < 0.02) return;
lastFrac = frac;
try { if (replyWin) postTo(replyWin, { type: 'scan-progress', reqId: m.reqId, targetFrame: m.from, frac: frac }); } catch (e2) {}
}).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-progress': { // controller: forward incremental progress to the UI
if (m.targetFrame && m.targetFrame !== SELF_ID) break;
const cb = scanProgress.get(m.reqId);
if (cb) cb(m.frac);
break;
}
case 'scan-result': { // controller: resolve the matching pending request
if (m.targetFrame && m.targetFrame !== SELF_ID) break;
scanProgress.delete(m.reqId);
const resolve = scanPending.get(m.reqId);
if (resolve) { scanPending.delete(m.reqId); resolve(m); }
break;
}
}
const h = MSG[m.type]; if (!h) return;
if ((h.hostOnly && !isHost) || (h.childOnly && isHost)) return;
h.fn(m, e);
});
/* ------------------------------------------------------------------ *
@@ -589,11 +540,11 @@
const MAX_CPS = 100;
const ctxDoc = pageWin.document || document;
function cursorInside() { return clicker.enteredDoc && !clicker.overChildFrame; }
const cursorInside = () => 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;
const tag = e.target?.tagName;
clicker.overChildFrame = (tag === 'IFRAME' || tag === 'FRAME');
}
try {
@@ -601,7 +552,7 @@
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);
ctxDoc.addEventListener('mouseout', (e) => { if (!e.relatedTarget) clicker.enteredDoc = false; }, true);
} catch (e) {}
function fireClick() {
@@ -610,16 +561,16 @@
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 });
const opts = { ...base, buttons };
let ev;
if (pointer && pageWin.PointerEvent) {
try { ev = new pageWin.PointerEvent(type, Object.assign(opts, { pointerId: 1, pointerType: 'mouse', isPrimary: true })); } catch (e) {}
try { ev = new pageWin.PointerEvent(type, { ...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 () {
const up = () => {
clicker.upTimer = 0;
dispatch('pointerup', 0, true); dispatch('mouseup', 0, false); dispatch('click', 0, false);
};
@@ -650,20 +601,20 @@
function setClickerRunning(on, propagate) {
on = !!on;
if (clicker.running !== on) { clicker.running = on; on ? startClickerLoop() : stopClickerLoop(); }
if (panelCtl) panelCtl.syncClicker();
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 });
if (isHost) frames.forEach((f, src) => postTo(src, { type: 'clicker-run', on }));
else if (hostWin) postTo(hostWin, { type: 'clicker-run', 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 };
const { mode, hotkey, swallowHotkey, cps, jitterMs, holdMs } = clicker;
return { type: 'clicker-config', mode, hotkey, swallowHotkey, cps, jitterMs, holdMs };
}
function broadcastClickerConfig() {
if (!isHost) return; // config flows host → all frames (not just attached)
pruneFrames();
frames.forEach(function (f, src) { postTo(src, clickerConfigMsg()); });
frames.forEach((f, src) => postTo(src, clickerConfigMsg()));
}
function applyClickerConfig(c) {
if (c.mode === 'toggle' || c.mode === 'hold') clicker.mode = c.mode;
@@ -672,7 +623,7 @@
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();
panelCtl?.syncClicker();
}
function hotkeyMatches(e, hk) {
@@ -680,15 +631,15 @@
!!e.shiftKey === !!hk.shift && !!e.metaKey === !!hk.meta;
}
function eventFromPanel(e) {
return panelHost && e.composedPath && e.composedPath().indexOf(panelHost) !== -1;
return panelHost && e.composedPath && e.composedPath().includes(panelHost);
}
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
if (['Control', 'Alt', 'Shift', 'Meta'].includes(e.key)) 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();
panelCtl?.syncClicker();
broadcastClickerConfig();
return;
}
@@ -714,7 +665,7 @@
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);
pageWin.addEventListener('blur', () => { if (clicker.mode === 'hold' && clicker.running) setClickerRunning(false, true); }, true);
} catch (e) {}
/* ================================================================== *
@@ -728,16 +679,18 @@
* The engine runs LOCALLY in each frame and owns its own candidate state;
* the panel drives it directly (this frame) or over postMessage (iframes).
* ================================================================== */
// `arr` is the TypedArray used for bulk scanning (platform-endian == little-endian
// on every supported browser, matching the explicit-LE DataView used for R/W).
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); } }
i8: { size: 1, arr: Int8Array, get: (d, o) => d.getInt8(o), set: (d, o, v) => d.setInt8(o, v) },
u8: { size: 1, arr: Uint8Array, get: (d, o) => d.getUint8(o), set: (d, o, v) => d.setUint8(o, v) },
i16: { size: 2, arr: Int16Array, get: (d, o) => d.getInt16(o, true), set: (d, o, v) => d.setInt16(o, v, true) },
u16: { size: 2, arr: Uint16Array, get: (d, o) => d.getUint16(o, true), set: (d, o, v) => d.setUint16(o, v, true) },
i32: { size: 4, arr: Int32Array, get: (d, o) => d.getInt32(o, true), set: (d, o, v) => d.setInt32(o, v, true) },
u32: { size: 4, arr: Uint32Array, get: (d, o) => d.getUint32(o, true), set: (d, o, v) => d.setUint32(o, v >>> 0, true) },
i64: { size: 8, arr: BigInt64Array, big: true, get: (d, o) => d.getBigInt64(o, true), set: (d, o, v) => d.setBigInt64(o, v, true) },
f32: { size: 4, arr: Float32Array, float: true, get: (d, o) => d.getFloat32(o, true), set: (d, o, v) => d.setFloat32(o, v, true) },
f64: { size: 8, arr: Float64Array, float: true, get: (d, o) => d.getFloat64(o, true), set: (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;
@@ -749,10 +702,8 @@
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'];
}
const expandTypes = (sel) =>
SCAN_TYPE_GROUPS[sel] ? SCAN_TYPE_GROUPS[sel].slice() : (SCAN_TYPES[sel] ? [sel] : ['i32']);
// Parse the user's typed value into the JS form the type compares with.
function parseScanValue(type, raw) {
@@ -786,12 +737,12 @@
// "-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; } }; }
if (t.big) { const target = parseScanValue(type, raw); if (target === null) return null; return { value: target, match: x => x === target }; }
const v = Number(raw); if (!isFinite(v)) return null;
if (!t.float) return { value: v, match: function (x) { return x === v; } };
if (!t.float) return { value: v, match: x => 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; } };
if (base < 0) { const lo = base - p, hi = base; return { value: v, match: x => x > lo && x <= hi }; }
const lo = base, hi = base + p; return { value: v, match: x => x >= lo && x < hi };
}
// Union matcher for a type group ('all'/'allint'/'allfloat'): matches if ANY expanded
// type's exact matcher does. Object-graph values are all f64, so this widens a whole
@@ -799,9 +750,9 @@
// already does per-type — otherwise a group would collapse to typeList[0]'s int matcher.
function makeGroupMatcher(typeList, raw) {
if (raw == null) return null;
const ms = typeList.map(function (t) { return makeExactMatcher(t, raw); }).filter(Boolean);
const ms = typeList.map(t => makeExactMatcher(t, raw)).filter(Boolean);
if (!ms.length) return null;
return { match: function (x) { for (let i = 0; i < ms.length; i++) if (ms[i].match(x)) return true; return false; } };
return { match: x => ms.some(m => m.match(x)) };
}
// refine criteria: 'exact' uses the typed-precision matcher; the rest compare a
// fresh read `cur` against the stored previous value `prev`.
@@ -815,19 +766,18 @@
default: return false;
}
}
function scanValueToWire(v) { return (typeof v === 'bigint') ? v.toString() : v; }
const scanValueToWire = (v) => (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() {
(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 -------------------------------------------------- *
@@ -838,7 +788,7 @@
* 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 () {
const wasmScan = (() => {
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
@@ -846,43 +796,51 @@
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]; }; }
const handle = () => wasmMemories[memIndex] || null;
const buffer = () => { const h = handle(); try { return h ? h.memory.buffer : null; } catch (e) { return null; } };
const view = () => { const b = buffer(); return b ? new DataView(b) : null; };
const matcherCache = (raw) => { const c = {}; return (t) => { if (!(t in c)) c[t] = (raw != null ? makeExactMatcher(t, raw) : null); return c[t]; }; };
function reset() { candidates = null; snapshot = null; }
const 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) {
// `accept(ty, cur, prev)` returns true (prev is the snapshot value at the same
// offset, or the same as cur for a fresh exact scan). One CHUNK of one type per
// slice. Bulk reads go through TypedArray views (recreated per slice, since
// memory.grow() detaches the buffer) — several× faster than per-call DataView
// getters, and every scanned offset is type-aligned because we step from 0 by size.
function scanAll(accept, prevBuf, 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 () {
chunkLoop(job, () => {
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 buf = buffer(); if (!buf) return false;
const t = types[ti], { size: sz, arr: Arr } = SCAN_TYPES[t];
const cap = prevBuf ? Math.min(len, buf.byteLength, prevLen) : Math.min(len, buf.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; }
const ta = new Arr(buf, 0, Math.floor(cap / sz)); // may throw on detach → chunkLoop finishes
const pa = prevBuf ? new Arr(prevBuf, 0, Math.floor(cap / sz)) : null;
const stop = Math.floor(end / sz);
for (let i = off / sz; i < stop; i++) {
const cur = ta[i], prev = pa ? pa[i] : cur;
if (accept(t, cur, prev)) { count++; if (out.length < SCAN_STORE_CAP) out.push({ off: i * sz, val: cur, ty: t }); else capped = true; }
}
off = stop * sz;
if (off + sz > cap) { ti++; off = 0; }
if (job.onProgress) job.onProgress(Math.min(1, (ti + (cap > 0 ? Math.min(1, off / cap) : 1)) / types.length));
job.onProgress?.(Math.min(1, (ti + (cap > 0 ? Math.min(1, off / cap) : 1)) / types.length));
return ti < types.length;
}, function (cancelled) {
}, (cancelled) => {
if (cancelled) { done({ cancelled: true }); return; }
candidates = out; done({ count: count, capped: capped, out: out });
candidates = out; done({ count, capped, 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);
if (types.every(t => !mfor(t))) { done({ error: 'bad value' }); return; }
scanAll((t, cur) => { const m = mfor(t); return m && m.match(cur); }, null, 0, job, done);
}
function firstUnknown(typeList, job, done) {
@@ -895,8 +853,8 @@
// 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) {
const mfor = matcherCache(raw);
scanAll((t, cur, prev) => passesCriteria(t, criteria, cur, prev, mfor(t)), snapshot.buffer, snapshot.byteLength, job, (r) => {
if (!r.cancelled && !r.error) { try { snapshot = new Uint8Array(handle().memory.buffer.slice(0)); } catch (e) {} } // re-baseline
done(r);
});
@@ -905,20 +863,19 @@
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; }
if (!view()) { done({ error: 'no WASM memory' }); return; }
const mfor = matcherCache(raw), src = candidates, kept = []; let i = 0;
chunkLoop(job, function () {
chunkLoop(job, () => {
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;
for (let n = 0; i < src.length && n < REFINE_BUDGET; i++, n++) {
const c = src[i], { size: sz, get } = SCAN_TYPES[c.ty];
if (c.off + sz > d.byteLength) continue;
let cur; try { cur = SCAN_TYPES[c.ty].get(d, c.off); } catch (e) { continue; }
let cur; try { cur = 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 });
}
if (job.onProgress) job.onProgress(src.length ? i / src.length : 1);
job.onProgress?.(src.length ? i / src.length : 1);
return i < src.length;
}, function (cancelled) {
}, (cancelled) => {
if (cancelled) { done({ cancelled: true }); return; }
candidates = kept; done({ count: kept.length, capped: false });
});
@@ -934,24 +891,23 @@
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; }
const [mi, off, aty] = String(address).split(':'); const ty = aty || 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 [mi, off, aty] = String(address).split(':'); const ty = aty || 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; }
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(); }
const memories = () => wasmMemories.map(m => {
let mb = 0; try { mb = m.memory.buffer.byteLength >> 20; } catch (e) {}
return { label: m.label + ' (' + mb + ' MB)' };
});
const 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
};
return { memories, setMem, reset, firstExact, firstUnknown, refine, rows, readAddress, writeAddress };
})();
/* ---- Object-graph backend ----------------------------------------- *
@@ -960,27 +916,35 @@
* 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 objectScan = (() => {
const NODE_CAP = 200000, DEPTH_CAP = 12, BUDGET = 15000; // nodes per event-loop slice
let type = 'f64'; // display / default-write type (typeList[0]); values are all f64
let types = ['f64']; // full expanded type list of the current scan (for group matchers)
let candidates = null; // [{ path:[...], val }]
let snapshot = null; // Map(pathKey -> { path, val }) for "unknown initial value"
function pathKey(path) { return path.join(' '); }
const pathKey = (path) => 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.
// Stack frames are parent-pointer nodes [obj, key, parentNode, depth]; the full path
// array is only materialized for leaves that actually match (path.concat per node
// used to allocate hundreds of thousands of throwaway arrays on a full walk).
function walkAsync(cb, match, job, done) {
const seen = new WeakSet(); let nodes = 0;
const stack = [[pageWin, [], 0]];
chunkLoop(job, function () {
const stack = [[pageWin, null, null, 0]];
const pathOf = (node, leafKey) => {
const p = [leafKey];
for (let n = node; n && n[1] !== null; n = n[2]) p.push(n[1]);
return p.reverse();
};
chunkLoop(job, () => {
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++;
const fr = stack.pop(); const obj = fr[0], depth = fr[3]; 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++) {
@@ -988,23 +952,22 @@
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); }
if (tv === 'number') { if (isFinite(v) && (!match || match(v))) cb(pathOf(fr, 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]);
stack.push([v, k, fr, depth + 1]);
}
}
}
if (job.onProgress) job.onProgress(-1); // total is unknown up front → indeterminate
job.onProgress?.(-1); // total is unknown up front → indeterminate
return stack.length > 0 && nodes < NODE_CAP;
}, done);
}
function reset() { candidates = null; snapshot = null; }
function setMem() {} // n/a for object graph
const reset = () => { candidates = null; snapshot = null; };
// 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.
@@ -1013,56 +976,50 @@
const matcher = makeGroupMatcher(types, 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) {
walkAsync((path, v) => { count++; if (out.length < SCAN_STORE_CAP) out.push({ path, val: v }); else capped = true; },
v => matcher.match(v), job, (cancelled) => {
if (cancelled) { done({ cancelled: true }); return; }
candidates = out; done({ count: count, capped: capped });
candidates = out; done({ count, capped });
});
}
function firstUnknown(typeList, job, done) {
types = typeList.slice(); 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) {
walkAsync((path, v) => snap.set(pathKey(path), { path, val: v }), null, job, (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; }
// Re-check `entries` ({ path, val }) against a fresh read, chunked so huge candidate
// sets never freeze the frame; used by both materialize (from snapshot, re-baselining)
// and refine (from candidates).
function recheck(entries, criteria, raw, rebaseline, job, done) {
const matcher = (raw != null) ? makeGroupMatcher(types, 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++) {
chunkLoop(job, () => {
for (let processed = 0; 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
if (rebaseline) entry.val = cur;
}
if (job.onProgress) job.onProgress(entries.length ? i / entries.length : 1);
job.onProgress?.(entries.length ? i / entries.length : 1);
return i < entries.length;
}, function (cancelled) {
}, (cancelled) => {
if (cancelled) { done({ cancelled: true }); return; }
candidates = out; done({ count: count, capped: capped });
candidates = out; done({ count, capped });
});
}
function refine(criteria, raw, job, done) {
if (candidates === null && snapshot !== null) { materialize(criteria, raw, job, done); return; }
if (candidates === null && snapshot !== null) { recheck(Array.from(snapshot.values()), criteria, raw, true, job, done); return; }
if (candidates === null) { done({ error: 'no scan in progress' }); return; }
const matcher = (raw != null) ? makeGroupMatcher(types, 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 });
recheck(candidates, criteria, raw, false, job, done);
}
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 });
out.push({ address: JSON.stringify(list[i].path), value: (typeof cur === 'number' ? cur : null), type });
}
return out;
}
@@ -1076,22 +1033,19 @@
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 []; }
const memories = () => [];
const setMem = () => {}; // n/a for object graph
return {
memories: memories, setMem: setMem, reset: reset,
firstExact: firstExact, firstUnknown: firstUnknown, refine: refine,
rows: rows, readAddress: readAddress, writeAddress: writeAddress
};
return { memories, setMem, reset, firstExact, firstUnknown, refine, rows, readAddress, writeAddress };
})();
function scanEngine(name) { return name === 'object' ? objectScan : wasmScan; }
const scanEngine = (name) => 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] + ')' : '');
const [mi, off, ty] = String(address).split(':');
return 'mem#' + mi + ' +0x' + (Number(off) || 0).toString(16) + (ty ? ' (' + ty + ')' : '');
}
// Execute one scan command against the LOCAL engines; resolves a wire-safe result.
@@ -1100,42 +1054,42 @@
const SCAN_ROW_LIMIT = 200; // most rows we ship/render at once
let scanJob = null;
function runScanCommand(cmd, onProgress) {
return new Promise(function (resolve) {
return new Promise((resolve) => {
try {
const eng = scanEngine(cmd.engine);
const cancelJob = () => { if (scanJob) scanJob.cancelled = true; };
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 'set-mem': cancelJob(); eng.setMem(cmd.mem | 0); resolve({ ok: true }); return;
case 'reset': cancelJob(); eng.reset(); resolve({ ok: true, count: 0, rows: [] }); return;
case 'cancel': cancelJob(); resolve({ ok: true, cancelled: true }); return;
case 'set-paused': setPaused(cmd.value); resolve({ ok: true, paused }); return;
case 'read':
resolve({ ok: true, values: (cmd.addresses || []).map(a => ({ address: a, value: scanValueToWire(eng.readAddress(a, cmd.type)) })) });
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;
resolve({ 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
cancelJob(); // supersede any prior scan
const job = { cancelled: false, onProgress: onProgress || null }; scanJob = job;
const done = function (r) {
const done = (r) => {
if (scanJob === job) scanJob = null;
if (!r || r.error) { resolve({ ok: false, error: (r && r.error) || 'scan failed' }); return; }
if (!r || r.error) { resolve({ ok: false, error: 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);
else eng.refine(cmd.criteria, 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) }); }
} catch (e) { resolve({ ok: false, error: String(e?.message || e) }); }
});
}
@@ -1155,7 +1109,7 @@
const scanHandledQ = []; // FIFO to bound scanHandled
function sendScan(targetId, targetWin, cmd, onProgress) {
if (!targetId) return runScanCommand(cmd, onProgress); // null → this frame (local engine, no messaging)
return new Promise(function (resolve) {
return new Promise((resolve) => {
const reqId = scanSeq++;
scanPending.set(reqId, resolve);
if (onProgress) scanProgress.set(reqId, onProgress);
@@ -1163,12 +1117,11 @@
// 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
const msg = { type: 'scan-cmd', reqId, targetFrame: targetId, from: SELF_ID, cmd };
if (targetWin) postTo(targetWin, msg); // proven channel (clicker/settings use it)
broadcastScanMsg(msg); // + frame-tree broadcast as backup
});
}
/* ------------------------------------------------------------------ *
* UI (Shadow DOM)
* ------------------------------------------------------------------ */
@@ -1447,104 +1400,105 @@
// 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');
for (const t of ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu',
'keydown', 'keyup', 'keypress', 'wheel', 'touchstart', 'touchend', 'pointermove', 'mousemove'])
host.addEventListener(t, e => e.stopPropagation(), false);
// Every [id] in the template, keyed by id: ui.panel, ui.scaleRange, ui.clkCps, …
const ui = {};
root.querySelectorAll('[id]').forEach(n => { ui[n.id] = n; });
const el = (tag, cls, text) => {
const n = document.createElement(tag);
if (cls) n.className = cls;
if (text != null) n.textContent = text;
return n;
};
const { panel, bar } = ui;
// 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.'; }
if (hasUnsafe) { ui.status.className = 'status ok'; ui.status.textContent = '✓ patching page context (unsafeWindow)'; }
else { ui.status.className = 'status warn'; ui.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 makeToggle = (text, checked, onChange) => {
const lab = el('label', 'tg');
lab.innerHTML = '<input type="checkbox"><span></span>';
const inp = lab.querySelector('input');
hookInputs[name] = inp;
inp.addEventListener('change', function (e) {
setHook(name, e.target.checked);
inp.checked = checked;
lab.querySelector('span').textContent = text;
inp.addEventListener('change', e => onChange(e.target.checked));
ui.toggles.appendChild(lab);
return { lab, inp };
};
const hookInputs = {};
for (const name of Object.keys(hooks)) {
hookInputs[name] = makeToggle(hooks[name].label, state[name], (on) => {
setHook(name, on);
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);
}).inp;
}
const turboTg = makeToggle('rAF turbo — multi-step (experimental)', turbo, (on) => { turbo = on; turboT = null; broadcastSettings(); });
const turboInput = turboTg.inp;
// turbo only does anything while the rAF hook is installed
function updateTurboEnabled() {
const on = !!state.raf;
turboInput.disabled = !on;
tlab.classList.toggle('disabled', !on);
turboTg.lab.classList.toggle('disabled', !on);
}
updateTurboEnabled();
// scale
function reflect(v) { out.textContent = v + '×'; badge.textContent = v + '×'; }
function reflect(v) { ui.scaleOut.textContent = v + '×'; ui.badge.textContent = v + '×'; }
const MAX_SCALE = 1000, SLIDER_MAX = 100, SLIDER_MIN = 0.1;
const clampSlider = (v) => Math.min(SLIDER_MAX, Math.max(SLIDER_MIN, v));
// 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;
ui.scaleRange.value = clampSlider(v);
if (writeNum !== false) ui.scaleNum.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); });
ui.scaleRange.addEventListener('input', e => onScale(e.target.value));
ui.scaleNum.addEventListener('input', e => onScale(e.target.value, false));
ui.scaleNum.addEventListener('change', e => onScale(e.target.value)); // normalize + cap on commit
root.querySelectorAll('.presets button').forEach(b => {
b.addEventListener('click', () => 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]; });
for (const n of Object.keys(hookInputs)) hookInputs[n].checked = !!state[n];
turboInput.checked = turbo;
updateTurboEnabled();
range.value = Math.min(SLIDER_MAX, Math.max(SLIDER_MIN, scale));
num.value = scale;
ui.scaleRange.value = clampSlider(scale);
ui.scaleNum.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; }
if (curMode !== 'host') { ui.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);
ui.frameList.textContent = '';
ui.framesBox.hidden = frames.size === 0;
frames.forEach((f, src) => {
const row = el('div', 'frow');
const label = el('span', 'furl', shortUrl(f.url)); label.title = f.url;
const btn = el('button', '', f.attached ? 'Detach' : 'Re-attach');
btn.addEventListener('click', () => { f.attached ? detachFrame(src) : reattachFrame(src); });
row.append(label, btn);
ui.frameList.appendChild(row);
});
}
reattachBtn.addEventListener('click', function () {
ui.reattach.addEventListener('click', () => {
if (hostWin) postTo(hostWin, { type: 'reattach' });
attached = true;
destroyPanel(); // back to headless; host will resend settings
@@ -1552,17 +1506,15 @@
// tabs
const panes = {};
root.querySelectorAll('.pane').forEach(function (p) { panes[p.dataset.pane] = p; });
root.querySelectorAll('.pane').forEach(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(b => b.classList.toggle('active', b.dataset.tab === name));
for (const n of Object.keys(panes)) panes[n].hidden = (n !== name);
}
tabBtns.forEach(function (b) { b.addEventListener('click', function () { setTab(b.dataset.tab); }); });
tabBtns.forEach(b => b.addEventListener('click', () => 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) {
@@ -1571,60 +1523,50 @@
(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;
clkModeBtns.forEach(b => b.classList.toggle('on', b.dataset.mode === clicker.mode));
ui.clkKey.textContent = clicker.listening ? 'press a key…' : keyLabel(clicker.hotkey);
ui.clkKey.classList.toggle('listening', clicker.listening);
ui.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
if (root.activeElement !== ui.clkCps) ui.clkCps.value = clicker.cps;
if (root.activeElement !== ui.clkJitter) ui.clkJitter.value = clicker.jitterMs;
if (root.activeElement !== ui.clkHold) ui.clkHold.value = clicker.holdMs;
ui.clkStatus.className = 'status ' + (clicker.running ? 'run' : 'idle');
ui.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 () {
clkModeBtns.forEach(b => {
b.addEventListener('click', () => {
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 () {
ui.clkSet.addEventListener('click', () => { clicker.listening = true; syncClicker(); });
ui.clkClear.addEventListener('click', () => {
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();
ui.clkSwallow.addEventListener('change', e => { clicker.swallowHotkey = e.target.checked; broadcastClickerConfig(); });
// Each numeric field commits live on input (clamped) and snaps back to the
// accepted value on change (blur/Enter).
for (const [input, key, min, max] of [[ui.clkCps, 'cps', 0.1, MAX_CPS], [ui.clkJitter, 'jitterMs', 0, 2000], [ui.clkHold, 'holdMs', 0, 2000]]) {
input.addEventListener('input', () => {
const v = Number(input.value);
if (!isFinite(v)) return;
clicker[key] = Math.min(max, Math.max(min, v));
broadcastClickerConfig();
});
input.addEventListener('change', () => { input.value = clicker[key]; });
}
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'), scCancel = $('#scCancel');
const scProgress = $('#scProgress'), scBar = $('#scBar');
const scModeInputs = root.querySelectorAll('#scMode input');
const scRefine = $('#scRefine'), scCount = $('#scCount'), scResults = $('#scResults'), scSaved = $('#scSaved');
function getScMode() {
for (let i = 0; i < scModeInputs.length; i++) if (scModeInputs[i].checked) return scModeInputs[i].value;
return 'exact';
}
const getScMode = () => [...scModeInputs].find(r => r.checked)?.value || 'exact';
const scEngineBtns = root.querySelectorAll('#scEngine button');
const scRefineBtns = root.querySelectorAll('#scRefine button');
@@ -1638,36 +1580,34 @@
let pausedLocalView = false;
function scCmd(extra, onProgress) {
const cmd = { engine: scEngineName, type: scType.value };
for (const k in extra) cmd[k] = extra[k];
return sendScan(scTargetId, scTargetWin, cmd, onProgress);
return sendScan(scTargetId, scTargetWin, { engine: scEngineName, type: ui.scType.value, ...extra }, onProgress);
}
// 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 setConn(kind, text) { ui.scStatus.className = 'status ' + kind; ui.scStatus.textContent = text; }
function setScan(text) { ui.scCount.textContent = text; }
function refreshScanTargets() {
const prev = scTarget.value;
const prev = ui.scTarget.value;
scTargetList.length = 0;
scTarget.textContent = '';
const self = document.createElement('option'); self.value = 'self'; self.textContent = 'This frame';
scTarget.appendChild(self);
ui.scTarget.textContent = '';
const self = el('option', '', 'This frame'); self.value = 'self';
ui.scTarget.appendChild(self);
// `frames` is only populated in host mode; a detached child just sees itself.
frames.forEach(function (f, src) {
frames.forEach((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);
const opt = el('option', '', shortUrl(f.url));
opt.value = 'f' + idx; opt.title = f.url;
ui.scTarget.appendChild(opt);
});
scTarget.value = Array.prototype.some.call(scTarget.options, function (o) { return o.value === prev; }) ? prev : 'self';
ui.scTarget.value = [...ui.scTarget.options].some(o => o.value === prev) ? prev : 'self';
applyTargetSelection();
}
function applyTargetSelection() {
const v = scTarget.value;
const v = ui.scTarget.value;
const ent = (v === 'self') ? null : scTargetList[+v.slice(1)];
scTargetId = ent ? ent.id : null;
scTargetWin = ent ? ent.win : null;
@@ -1675,27 +1615,27 @@
// Reflect scanActive / scanRunning onto the buttons.
function updateButtons() {
scFirst.textContent = scanActive ? 'New scan' : 'First scan';
scFirst.disabled = scanRunning;
ui.scFirst.textContent = scanActive ? 'New scan' : 'First scan';
ui.scFirst.disabled = scanRunning;
// Scan mode (Known value / Unknown initial) is locked once a scan exists — it only
// applies to starting a NEW scan. Start a new scan to change it.
scModeInputs.forEach(function (r) { r.disabled = scanRunning || scanActive; });
scCancel.hidden = !scanRunning;
scRefine.hidden = !scanActive;
scRefineBtns.forEach(function (b) { b.disabled = scanRunning || !scanActive; });
scType.disabled = scanRunning;
scModeInputs.forEach(r => { r.disabled = scanRunning || scanActive; });
ui.scCancel.hidden = !scanRunning;
ui.scRefine.hidden = !scanActive;
scRefineBtns.forEach(b => { b.disabled = scanRunning || !scanActive; });
ui.scType.disabled = scanRunning;
// The value box stays editable during refine (so "Exact" refine can take a new value);
// it's disabled only while a scan runs, or for a fresh "Unknown initial" scan (no value).
scValue.disabled = scanRunning || (!scanActive && getScMode() === 'unknown');
scMemDetect.disabled = scanRunning;
ui.scValue.disabled = scanRunning || (!scanActive && getScMode() === 'unknown');
ui.scMemDetect.disabled = scanRunning;
}
function setEngine(name) {
scEngineName = name;
scEngineBtns.forEach(function (b) { b.classList.toggle('on', b.dataset.engine === name); });
scEngineBtns.forEach(b => b.classList.toggle('on', b.dataset.engine === name));
const wasm = (name === 'wasm');
scMemDetect.hidden = !wasm;
scMem.hidden = true;
ui.scMemDetect.hidden = !wasm;
ui.scMem.hidden = true;
newScan();
if (wasm) { refreshMemList(); return; }
// object-graph engine: confirm a remote frame is reachable (same short
@@ -1703,13 +1643,13 @@
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 () {
origSetTimeout(() => {
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) {
scCmd({ op: 'ping' }).then((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.');
settled = true; setConn(res?.ok ? 'ok' : 'warn', res?.ok ? 'Frame connected — walking values reachable from its window.' : 'Frame not responding.');
});
}
@@ -1721,22 +1661,22 @@
if (scEngineName !== 'wasm') return;
const id = scTargetId; let settled = false;
setConn('idle', 'Detecting WASM memory…');
if (id) origSetTimeout(function () {
if (id) origSetTimeout(() => {
if (settled || scTargetId !== id || scEngineName !== 'wasm') return;
settled = true; scMem.hidden = true;
settled = true; ui.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) {
scCmd({ op: 'list-memories' }).then((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; }
if (!res || res.ok === false) { ui.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';
const prev = ui.scMem.value;
ui.scMem.textContent = '';
mems.forEach((m, i) => { const o = el('option', '', m.label); o.value = String(i); ui.scMem.appendChild(o); });
if (prev && mems[+prev]) ui.scMem.value = prev;
ui.scMem.hidden = mems.length === 0;
ui.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.');
});
@@ -1744,7 +1684,7 @@
function newScan() {
scanActive = false;
scResults.textContent = '';
ui.scResults.textContent = '';
setScan('No scan yet.');
showProgress(false);
updateButtons();
@@ -1755,7 +1695,7 @@
function onScanDone(res) {
setScanRunning(false);
if (!res || !res.ok) { setScan('Scan failed: ' + ((res && res.error) || 'unknown')); return; }
if (!res || !res.ok) { setScan('Scan failed: ' + (res?.error || 'unknown')); return; }
if (res.cancelled) { setScan('Scan cancelled.'); updateButtons(); return; }
scanActive = true;
updateButtons();
@@ -1774,51 +1714,51 @@
setScanRunning(true);
setScan(progress);
showProgress(true);
scCmd(cmd, onScanProgress).then(function (res) { showProgress(false); onScanDone(res); });
scCmd(cmd, onScanProgress).then((res) => { showProgress(false); onScanDone(res); });
}
// Progress bar: starts indeterminate (animated stripe); flips to a determinate fill the
// first time the engine reports a real fraction (frac >= 0). frac < 0 stays indeterminate
// (the object-graph walk, whose total isn't known up front).
function showProgress(on) {
scProgress.hidden = !on;
if (on) { scBar.classList.add('indet'); scBar.style.width = '0%'; }
ui.scProgress.hidden = !on;
if (on) { ui.scBar.classList.add('indet'); ui.scBar.style.width = '0%'; }
}
function onScanProgress(frac) {
if (typeof frac !== 'number' || frac < 0) return;
scBar.classList.remove('indet');
scBar.style.width = Math.max(0, Math.min(1, frac)) * 100 + '%';
ui.scBar.classList.remove('indet');
ui.scBar.style.width = Math.max(0, Math.min(1, frac)) * 100 + '%';
}
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);
});
ui.scResults.textContent = '';
for (const r of rows) {
const row = el('div', 'sc-row'); row.dataset.addr = r.address;
const addr = el('span', 'sc-addr', scanAddressLabel(scEngineName, r.address)); addr.title = addr.textContent;
const val = el('input', 'sc-val'); val.value = (r.value == null ? '?' : r.value);
val.addEventListener('change', () => scCmd({ op: 'write', address: r.address, value: val.value }));
const save = el('button', 'sc-mini', '★'); save.title = 'Save this result';
save.addEventListener('click', () => addSaved(r.address, r.type));
row.append(addr, val, save);
ui.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"]');
const scPane = panes.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; });
// Only poll while the Scan tab is actually visible (not tab-hidden, not minimized).
if ((scPane && scPane.hidden) || panel.classList.contains('min')) return;
const rowEls = [...ui.scResults.querySelectorAll('.sc-row')];
const addrs = rowEls.map(e2 => e2.dataset.addr);
if (addrs.length) {
scCmd({ op: 'read', addresses: addrs }).then(function (res) {
scCmd({ op: 'read', addresses: addrs }).then((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]);
});
const byAddr = new Map(res.values.map(v => [v.address, v.value]));
for (const rowEl of rowEls) {
const inp = rowEl.querySelector('.sc-val');
const v = byAddr.get(rowEl.dataset.addr);
if (inp && root.activeElement !== inp) inp.value = (v == null ? '?' : v);
}
});
}
pollSaved();
@@ -1827,70 +1767,81 @@
/* ----- 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 });
savedScans.push({ name: scanAddressLabel(scEngineName, address), engine: scEngineName, type: (ty || ui.scType.value), 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;
ui.scSaved.textContent = '';
savedScans.forEach((s, i) => {
const row = el('div', 'sc-srow'); row.dataset.idx = i;
const name = el('input', '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);
name.addEventListener('change', () => { s.name = name.value; persistSaved(); });
const val = el('input', 'sc-val'); val.value = '?';
val.addEventListener('change', () => sendScan(scTargetId, scTargetWin, { engine: s.engine, type: s.type, op: 'write', address: s.address, value: val.value }));
const del = el('button', 'sc-mini', '×'); del.title = 'Delete';
del.addEventListener('click', () => { savedScans.splice(i, 1); persistSaved(); renderSaved(); });
row.append(name, val, del);
ui.scSaved.appendChild(row);
});
}
// One batched `read` per (engine, type) group instead of a postMessage round-trip
// per saved row every poll tick.
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);
const groups = new Map(); // "engine type" -> { engine, type, addrs, els }
for (const rowEl of ui.scSaved.querySelectorAll('.sc-srow')) {
const s = savedScans[+rowEl.dataset.idx]; if (!s) continue;
const key = s.engine + ' ' + s.type;
let g = groups.get(key);
if (!g) { g = { engine: s.engine, type: s.type, addrs: [], els: [] }; groups.set(key, g); }
g.addrs.push(s.address); g.els.push(rowEl);
}
groups.forEach((g) => {
sendScan(scTargetId, scTargetWin, { engine: g.engine, type: g.type, op: 'read', addresses: g.addrs }).then((res) => {
const byAddr = new Map((res?.values || []).map(v => [v.address, v.value]));
g.els.forEach((rowEl, i) => {
const inp = rowEl.querySelector('.sc-val'); if (!inp || root.activeElement === inp) return;
const v = byAddr.get(g.addrs[i]);
inp.value = (v == null ? '∅' : v);
rowEl.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 : ''; });
scModeInputs.forEach(function (r) { r.addEventListener('change', updateButtons); });
scFirst.addEventListener('click', function () {
scEngineBtns.forEach(b => b.addEventListener('click', () => setEngine(b.dataset.engine)));
ui.scTarget.addEventListener('change', () => { applyTargetSelection(); setEngine(scEngineName); });
ui.scMem.addEventListener('change', () => { scCmd({ op: 'set-mem', mem: +ui.scMem.value }).then(newScan); });
ui.scMemDetect.addEventListener('click', refreshMemList);
ui.scType.addEventListener('change', () => { ui.scType.title = ui.scType.options[ui.scType.selectedIndex]?.title || ''; });
scModeInputs.forEach(r => r.addEventListener('change', updateButtons));
ui.scFirst.addEventListener('click', () => {
if (scanActive) { newScan(); return; } // acts as "New scan" once a scan exists
if (getScMode() === 'unknown') { startScan({ op: 'first-unknown' }, 'Snapshotting…'); return; }
const raw = scValue.value.trim();
const raw = ui.scValue.value.trim();
if (raw === '') { setScan('Enter a value, or choose “Unknown initial value”.'); return; }
startScan({ op: 'first-exact', value: raw }, 'Scanning…');
});
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();
ui.scCancel.addEventListener('click', () => { setScan('Cancelling…'); scCmd({ op: 'cancel' }); });
scRefineBtns.forEach(b => {
b.addEventListener('click', () => {
const crit = b.dataset.crit, raw = ui.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);
ui.scPause.addEventListener('click', () => {
scCmd({ op: 'set-paused', value: !pausedLocalView }).then((res) => {
pausedLocalView = !!res?.paused;
reflectPause();
});
});
function reflectPause() {
scPause.textContent = pausedLocalView ? '▶ Resume' : '⏸ Pause';
scPause.classList.toggle('on', pausedLocalView);
ui.scPause.textContent = pausedLocalView ? '▶ Resume' : '⏸ Pause';
ui.scPause.classList.toggle('on', pausedLocalView);
}
scType.title = scType.options[scType.selectedIndex] ? scType.options[scType.selectedIndex].title : '';
ui.scType.title = ui.scType.options[ui.scType.selectedIndex]?.title || '';
renderSaved();
setEngine('wasm');
reflectPause();
@@ -1899,66 +1850,71 @@
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; }
if (m === 'host') { ui.title.textContent = 'Speedhack'; ui.reattach.hidden = true; refreshFrames(); }
else { ui.title.textContent = 'Speedhack (frame)'; ui.framesBox.hidden = true; ui.reattach.hidden = false; }
}
setMode(mode || 'host');
// minimize (start minimized)
function setMin(m) { panel.classList.toggle('min', m); btnMin.textContent = m ? '▢' : '–'; }
function setMin(m) { panel.classList.toggle('min', m); ui.min.textContent = m ? '▢' : '–'; }
setMin(true);
btnMin.addEventListener('click', function (e) { e.stopPropagation(); setMin(!panel.classList.contains('min')); });
ui.min.addEventListener('click', (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); });
ui.close.addEventListener('click', (e) => { e.stopPropagation(); ui.dlgurl.textContent = PAGE; ui.dlg.hidden = false; });
ui.dlgCancel.addEventListener('click', () => { ui.dlg.hidden = true; });
ui.dlgNo.addEventListener('click', () => doClose(false));
ui.dlgYes.addEventListener('click', () => doClose(true));
function doClose(remember) {
if (remember) store.set(CLOSED_KEY, true);
Object.keys(hooks).forEach(function (n) { try { hooks[n].uninstall(); } catch (e) {} });
for (const n of Object.keys(hooks)) { 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' }); });
frames.forEach((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) {
bar.addEventListener('pointerdown', (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 (_) {}
try { bar.setPointerCapture(e.pointerId); } catch (e2) {}
});
bar.addEventListener('pointermove', function (e) {
bar.addEventListener('pointermove', (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) {
bar.addEventListener('pointerup', (e) => {
if (!dragging) return; dragging = false;
try { bar.releasePointerCapture(e.pointerId); } catch (_) {}
try { bar.releasePointerCapture(e.pointerId); } catch (e2) {}
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
removeNode() {
try { origClearInterval(scPoll); } catch (e) {}
try { host.remove(); } catch (e) {}
if (panelHost === host) panelHost = null;
clicker.listening = false;
},
refreshFrames,
refreshScan: refreshScanTargets,
setMode,
sync,
syncClicker
};
}
@@ -1970,14 +1926,14 @@
let pendingMode = 'host';
function whenBody(fn) {
if (document.body) { fn(); return; }
const obs = new MutationObserver(function () { if (document.body) { obs.disconnect(); fn(); } });
const obs = new MutationObserver(() => { 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 });
document.addEventListener('DOMContentLoaded', () => { try { obs.disconnect(); } catch (e) {} fn(); }, { once: true });
}
function ensurePanel(mode) {
pendingMode = mode;
if (panelCtl) { panelCtl.setMode(mode); return; }
whenBody(function () {
whenBody(() => {
if (panelCtl) { panelCtl.setMode(pendingMode); return; }
if (!(document.body || document.documentElement)) return;
panelCtl = buildUI(pendingMode);
@@ -1997,6 +1953,6 @@
} 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);
origSetTimeout(() => { if (!gotHost) promoteToHost(); }, 5000);
}
})();