glidercli 0.3.21 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/glider.js +1147 -11
  2. package/package.json +1 -1
package/bin/glider.js CHANGED
@@ -1939,14 +1939,18 @@ async function cmdExplore(url, opts = []) {
1939
1939
  let outputDir = '/tmp/glider-explore';
1940
1940
  let harFile = null;
1941
1941
  let sessionId = null;
1942
+ let freshTab = false;
1943
+ let closeOnDone = false;
1942
1944
 
1943
1945
  for (let i = 0; i < opts.length; i++) {
1944
1946
  if (opts[i] === '--depth' || opts[i] === '-d') depth = parseInt(opts[++i], 10);
1945
1947
  else if (opts[i] === '--output' || opts[i] === '-o') outputDir = opts[++i];
1946
1948
  else if (opts[i] === '--har') harFile = opts[++i];
1947
1949
  else if (opts[i] === '--session-id' || opts[i] === '--session') sessionId = opts[++i];
1950
+ else if (opts[i] === '--fresh-tab') freshTab = true;
1951
+ else if (opts[i] === '--close-on-done') closeOnDone = true;
1948
1952
  }
1949
- if (!sessionId && activeSessionId) sessionId = activeSessionId;
1953
+ if (!sessionId && !freshTab && activeSessionId) sessionId = activeSessionId;
1950
1954
 
1951
1955
  try {
1952
1956
  assertUrlAllowed(url, allowedDomainList, 'explore');
@@ -1956,6 +1960,29 @@ async function cmdExplore(url, opts = []) {
1956
1960
  process.exit(1);
1957
1961
  }
1958
1962
 
1963
+ // v0.4.2: --fresh-tab sidesteps H4 (CSS.enable forwardCDPCommand timeout
1964
+ // on long-lived session reuse). Opens a new tab, waits for target attach,
1965
+ // uses the new session-id, and optionally closes on done.
1966
+ let freshTargetId = null;
1967
+ if (freshTab) {
1968
+ const { WindowManager } = require(path.join(LIB_DIR, 'bwindow.js'));
1969
+ const wm = new WindowManager();
1970
+ await wm.connect();
1971
+ await wm.init();
1972
+ log.info(`[explore] Opening fresh tab for capture...`);
1973
+ const result = await wm.createTab(url);
1974
+ freshTargetId = result.targetId;
1975
+ await new Promise(r => setTimeout(r, 2500));
1976
+ try {
1977
+ const targetsRes = await httpGet('/targets');
1978
+ const targets = (targetsRes && targetsRes.targets) || targetsRes || [];
1979
+ const t = (Array.isArray(targets) ? targets : []).find(x => x.targetId === freshTargetId);
1980
+ if (t && t.sessionId) sessionId = t.sessionId;
1981
+ } catch {}
1982
+ if (!sessionId) log.info('[explore] fresh-tab created but sessionId not resolved (bexplore will auto-pin)');
1983
+ else log.ok(`[explore] fresh-tab session: ${sessionId}`);
1984
+ }
1985
+
1959
1986
  log.info(`Exploring: ${url} (depth: ${depth})`);
1960
1987
 
1961
1988
  // Use the bexplore.js library
@@ -1969,9 +1996,24 @@ async function cmdExplore(url, opts = []) {
1969
1996
  const child = spawn('node', spawnArgs, {
1970
1997
  stdio: 'inherit'
1971
1998
  });
1972
- await new Promise((resolve, reject) => {
1973
- child.on('close', code => code === 0 ? resolve() : reject(new Error(`Exit code: ${code}`)));
1974
- });
1999
+ try {
2000
+ await new Promise((resolve, reject) => {
2001
+ child.on('close', code => code === 0 ? resolve() : reject(new Error(`Exit code: ${code}`)));
2002
+ });
2003
+ } finally {
2004
+ if (freshTab && closeOnDone && freshTargetId) {
2005
+ try {
2006
+ const { WindowManager } = require(path.join(LIB_DIR, 'bwindow.js'));
2007
+ const wm = new WindowManager();
2008
+ await wm.connect();
2009
+ await wm.init();
2010
+ await wm.closeTarget(freshTargetId);
2011
+ log.ok(`[explore] fresh-tab closed: ${freshTargetId}`);
2012
+ } catch (e) {
2013
+ log.info(`[explore] fresh-tab close failed: ${e.message}`);
2014
+ }
2015
+ }
2016
+ }
1975
2017
  } else {
1976
2018
  // Fallback: simple exploration
1977
2019
  await cmdGoto(url);
@@ -2412,6 +2454,37 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
2412
2454
  }
2413
2455
  console.log('');
2414
2456
  }
2457
+ console.log(`${YELLOW}DOM-SCORCH (waves 1-5):${NC}`);
2458
+ console.log(` ${GREEN}${'read'.padEnd(16)}${NC} ${DIM}read attr/prop/text/html/value; --all --count --exists --visible --enabled${NC}`);
2459
+ console.log(` ${GREEN}${'click'.padEnd(16)}${NC} ${DIM}--text --contains --regex --nth --role --inside --wait --double --right --hold${NC}`);
2460
+ console.log(` ${GREEN}${'type'.padEnd(16)}${NC} ${DIM}--editor auto|ckeditor|tinymce|prosemirror|monaco|slate|contentEditable ; --file --clear-first --commit${NC}`);
2461
+ console.log(` ${GREEN}${'wait'.padEnd(16)}${NC} ${DIM}--selector --text --gone --matches --stable --url-matches --timeout${NC}`);
2462
+ console.log(` ${GREEN}${'hover'.padEnd(16)}${NC} ${DIM}hover a target${NC}`);
2463
+ console.log(` ${GREEN}${'focus/blur'.padEnd(16)}${NC} ${DIM}focus/blur an element${NC}`);
2464
+ console.log(` ${GREEN}${'scroll'.padEnd(16)}${NC} ${DIM}scroll to <sel> | by <dx> <dy> | until <sel>${NC}`);
2465
+ console.log(` ${GREEN}${'key'.padEnd(16)}${NC} ${DIM}"Ctrl+Enter" | "ArrowDown x5" | "Escape" | --text "literal"${NC}`);
2466
+ console.log(` ${GREEN}${'right-click'.padEnd(16)}${NC} ${DIM}right-click (same flags as click)${NC}`);
2467
+ console.log(` ${GREEN}${'double-click'.padEnd(16)}${NC} ${DIM}double-click (same flags as click)${NC}`);
2468
+ console.log(` ${GREEN}${'drag'.padEnd(16)}${NC} ${DIM}drag <src> --to <dst>${NC}`);
2469
+ console.log(` ${GREEN}${'click-at'.padEnd(16)}${NC} ${DIM}click-at x,y${NC}`);
2470
+ console.log(` ${GREEN}${'select'.padEnd(16)}${NC} ${DIM}<sel> --by-text | --by-value | --nth${NC}`);
2471
+ console.log(` ${GREEN}${'eval'.padEnd(16)}${NC} ${DIM}--arg K=V --arg-file K=@path --json --await${NC}`);
2472
+ console.log(` ${GREEN}${'screenshot'.padEnd(16)}${NC} ${DIM}--selector --clip --full-page --format webp|jpg|png${NC}`);
2473
+ console.log(` ${GREEN}${'frames'.padEnd(16)}${NC} ${DIM}list all frames in the page${NC}`);
2474
+ console.log(` ${GREEN}${'frame-eval'.padEnd(16)}${NC} ${DIM}<frameId> <js> - eval inside iframe${NC}`);
2475
+ console.log(` ${GREEN}${'upload'.padEnd(16)}${NC} ${DIM}<input-sel> <file-path> via DOM.setFileInputFiles${NC}`);
2476
+ console.log(` ${GREEN}${'har'.padEnd(16)}${NC} ${DIM}har start | stop | dump [PATH]${NC}`);
2477
+ console.log(` ${GREEN}${'emulate'.padEnd(16)}${NC} ${DIM}tz | geo | viewport | offline | ua | color-scheme${NC}`);
2478
+ console.log(` ${GREEN}${'storage'.padEnd(16)}${NC} ${DIM}get | set | delete | keys | jar (localStorage)${NC}`);
2479
+ console.log(` ${GREEN}${'cookies'.padEnd(16)}${NC} ${DIM}(read: no flags) | --set NAME=VAL --host H | --delete NAME --host H${NC}`);
2480
+ console.log(` ${GREEN}${'history'.padEnd(16)}${NC} ${DIM}back | forward | reload${NC}`);
2481
+ console.log(` ${GREEN}${'dialog'.padEnd(16)}${NC} ${DIM}dialog auto accept|dismiss${NC}`);
2482
+ console.log(` ${GREEN}${'console'.padEnd(16)}${NC} ${DIM}console tail | dump${NC}`);
2483
+ console.log(` ${GREEN}${'pdf'.padEnd(16)}${NC} ${DIM}[PATH] [--landscape] [--margin N] [--scale F]${NC}`);
2484
+ console.log(` ${GREEN}${'mock'.padEnd(16)}${NC} ${DIM}<url-glob> --status N --body FILE | mock clear${NC}`);
2485
+ console.log(` ${GREEN}${'a11y'.padEnd(16)}${NC} ${DIM}Accessibility.getFullAXTree (snapshot --a11y flag equivalent)${NC}`);
2486
+ console.log(` ${GREEN}${'frozen'.padEnd(16)}${NC} ${DIM}freeze/restore page state${NC}`);
2487
+ console.log('');
2415
2488
  }
2416
2489
 
2417
2490
  // Version check - non-blocking, runs in background
@@ -2669,6 +2742,982 @@ function parseJsonPluginArgs(argv, schema) {
2669
2742
  return out;
2670
2743
  }
2671
2744
 
2745
+ // ═══════════════════════════════════════════════════════════════════
2746
+ // WAVES 1-5 (dom-scorch) - AGNOSTIC DOM PRIMITIVES
2747
+ // ═══════════════════════════════════════════════════════════════════
2748
+
2749
+ // --- flag parser used by dom-scorch verbs ---------------------------
2750
+ function parseFlags(argv, specs) {
2751
+ // specs: { longName: {short?, type: 'boolean'|'string'|'int'|'float', default?} }
2752
+ const out = { _: [] };
2753
+ for (const k of Object.keys(specs)) if ('default' in specs[k]) out[k] = specs[k].default;
2754
+ const shortMap = {};
2755
+ for (const [k, s] of Object.entries(specs)) if (s.short) shortMap['-' + s.short] = k;
2756
+ for (let i = 0; i < argv.length; i++) {
2757
+ const a = argv[i];
2758
+ let key = null;
2759
+ if (a.startsWith('--')) key = a.slice(2);
2760
+ else if (shortMap[a]) key = shortMap[a];
2761
+ if (key && specs[key]) {
2762
+ const s = specs[key];
2763
+ if (s.type === 'boolean') out[key] = true;
2764
+ else {
2765
+ const v = argv[++i];
2766
+ out[key] = s.type === 'int' ? parseInt(v, 10)
2767
+ : s.type === 'float' ? parseFloat(v)
2768
+ : v;
2769
+ }
2770
+ } else {
2771
+ out._.push(a);
2772
+ }
2773
+ }
2774
+ return out;
2775
+ }
2776
+
2777
+ // --- guard: allow-list check + auto-connect --------------------------
2778
+ async function _guardAndConnect(action) {
2779
+ if (!await ensureConnected()) process.exit(1);
2780
+ try { await assertCurrentUrlAllowed(action); }
2781
+ catch (e) { if (jsonOutput) emitJson(false, null, e.message); log.fail(e.message); process.exit(1); }
2782
+ }
2783
+
2784
+ // --- shared runtime helper: eval JS, unwrap value -------------------
2785
+ async function _rtEval(expression, opts = {}) {
2786
+ const result = await httpPost('/cdp', {
2787
+ method: 'Runtime.evaluate',
2788
+ params: {
2789
+ expression,
2790
+ returnByValue: true,
2791
+ awaitPromise: opts.awaitPromise !== false,
2792
+ ...(opts.contextId !== undefined ? { contextId: opts.contextId } : {}),
2793
+ ...(opts.uniqueContextId ? { uniqueContextId: opts.uniqueContextId } : {}),
2794
+ }
2795
+ });
2796
+ if (result?.exceptionDetails) {
2797
+ throw new Error(result.exceptionDetails.text || result.exceptionDetails.exception?.description || 'eval threw');
2798
+ }
2799
+ return result;
2800
+ }
2801
+
2802
+ // --- WAVE 1: cmdRead ------------------------------------------------
2803
+ // glider read <sel> [--attr X | --prop Y | --text | --html | --value | --all | --count | --exists | --visible | --enabled]
2804
+ async function cmdRead(argv) {
2805
+ const opts = parseFlags(argv, {
2806
+ attr: { type: 'string' },
2807
+ prop: { type: 'string' },
2808
+ text: { type: 'boolean' },
2809
+ html: { type: 'boolean' },
2810
+ value: { type: 'boolean' },
2811
+ all: { type: 'boolean' },
2812
+ count: { type: 'boolean' },
2813
+ exists: { type: 'boolean' },
2814
+ visible: { type: 'boolean' },
2815
+ enabled: { type: 'boolean' },
2816
+ });
2817
+ const sel = opts._[0];
2818
+ if (!sel) { log.fail('Usage: glider read <selector> [--attr X | --prop Y | --text | --html | --value | --all | --count | --exists | --visible | --enabled]'); process.exit(1); }
2819
+ await _guardAndConnect('read');
2820
+ const selJ = JSON.stringify(sel);
2821
+ const attrJ = opts.attr ? JSON.stringify(opts.attr) : 'null';
2822
+ const propJ = opts.prop ? JSON.stringify(opts.prop) : 'null';
2823
+ const mode = opts.count ? 'count'
2824
+ : opts.exists ? 'exists'
2825
+ : opts.visible ? 'visible'
2826
+ : opts.enabled ? 'enabled'
2827
+ : opts.attr ? 'attr'
2828
+ : opts.prop ? 'prop'
2829
+ : opts.value ? 'value'
2830
+ : opts.html ? 'html'
2831
+ : opts.text ? 'text'
2832
+ : 'text';
2833
+ const modeJ = JSON.stringify(mode);
2834
+ const allJ = opts.all ? 'true' : 'false';
2835
+ const js = `(() => {
2836
+ const sel=${selJ}, mode=${modeJ}, attr=${attrJ}, prop=${propJ}, all=${allJ};
2837
+ const els=[...document.querySelectorAll(sel)];
2838
+ if (mode==='count') return els.length;
2839
+ if (mode==='exists') return els.length>0;
2840
+ if (els.length===0) return null;
2841
+ const one=e=>{
2842
+ if (mode==='visible'){const r=e.getBoundingClientRect(); const s=getComputedStyle(e); return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}
2843
+ if (mode==='enabled') return !e.disabled && e.getAttribute('aria-disabled')!=='true';
2844
+ if (mode==='attr') return e.getAttribute(attr);
2845
+ if (mode==='prop') return e[prop];
2846
+ if (mode==='value') return e.value;
2847
+ if (mode==='html') return e.outerHTML;
2848
+ return e.innerText;
2849
+ };
2850
+ return all ? els.map(one) : one(els[0]);
2851
+ })()`;
2852
+ try {
2853
+ const r = await _rtEval(js);
2854
+ const v = r.result?.value;
2855
+ if (jsonOutput) emitJson(true, v);
2856
+ else if (v === null || v === undefined) { /* nothing */ }
2857
+ else if (typeof v === 'string') console.log(v);
2858
+ else console.log(JSON.stringify(v));
2859
+ } catch (e) {
2860
+ if (jsonOutput) emitJson(false, null, e.message);
2861
+ log.fail(`Read failed: ${e.message}`); process.exit(1);
2862
+ }
2863
+ }
2864
+
2865
+ // --- WAVE 1: cmdHover -----------------------------------------------
2866
+ async function cmdHover(argv) {
2867
+ const opts = parseFlags(argv, {
2868
+ text: { type: 'string' },
2869
+ contains: { type: 'string' },
2870
+ nth: { type: 'int' },
2871
+ });
2872
+ const sel = opts._[0];
2873
+ if (!sel && !opts.text && !opts.contains) { log.fail('Usage: glider hover <selector> [--text S | --contains S | --nth N]'); process.exit(1); }
2874
+ await _guardAndConnect('hover');
2875
+ const findExpr = _buildFindElExpr(sel, opts);
2876
+ const js = `(() => {
2877
+ const el = ${findExpr};
2878
+ if (!el) return { error: 'Element not found' };
2879
+ const r = el.getBoundingClientRect();
2880
+ return { x: Math.round(r.left + r.width/2), y: Math.round(r.top + r.height/2) };
2881
+ })()`;
2882
+ try {
2883
+ const r = await _rtEval(js);
2884
+ const v = r.result?.value;
2885
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
2886
+ // dispatch a real mousemove via CDP
2887
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseMoved', x: v.x, y: v.y, button: 'none', clickCount: 0 } });
2888
+ if (jsonOutput) emitJson(true, { hovered: true, at: v });
2889
+ else log.ok(`Hovered at ${v.x},${v.y}`);
2890
+ } catch (e) {
2891
+ if (jsonOutput) emitJson(false, null, e.message);
2892
+ log.fail(`Hover failed: ${e.message}`); process.exit(1);
2893
+ }
2894
+ }
2895
+
2896
+ // --- WAVE 1: cmdFocus / cmdBlur -------------------------------------
2897
+ async function cmdFocusVerb(argv) {
2898
+ const sel = argv[0];
2899
+ if (!sel) { log.fail('Usage: glider focus <selector>'); process.exit(1); }
2900
+ await _guardAndConnect('focus');
2901
+ const js = `(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return { error: 'not found' }; el.focus(); return { focused: true }; })()`;
2902
+ const r = await _rtEval(js);
2903
+ const v = r.result?.value;
2904
+ if (v?.error) { log.fail(v.error); process.exit(1); }
2905
+ if (jsonOutput) emitJson(true, { selector: sel, focused: true });
2906
+ else log.ok(`Focused: ${sel}`);
2907
+ }
2908
+ async function cmdBlurVerb(argv) {
2909
+ const sel = argv[0];
2910
+ await _guardAndConnect('blur');
2911
+ const js = sel
2912
+ ? `(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return { error: 'not found' }; el.blur(); return { blurred: true }; })()`
2913
+ : `(() => { if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); return { blurred: true }; })()`;
2914
+ const r = await _rtEval(js);
2915
+ const v = r.result?.value;
2916
+ if (v?.error) { log.fail(v.error); process.exit(1); }
2917
+ if (jsonOutput) emitJson(true, { blurred: true });
2918
+ else log.ok(`Blurred${sel ? ': ' + sel : ''}`);
2919
+ }
2920
+
2921
+ // --- WAVE 1: cmdScroll -----------------------------------------------
2922
+ // scroll-to <sel> | scroll-by dx dy | scroll-until <sel>
2923
+ async function cmdScroll(argv) {
2924
+ const sub = argv[0];
2925
+ await _guardAndConnect('scroll');
2926
+ if (sub === 'to' && argv[1]) {
2927
+ const sel = argv[1];
2928
+ const js = `(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return { error: 'not found' }; el.scrollIntoView({behavior:'auto',block:'center'}); return { scrolled: true }; })()`;
2929
+ const r = await _rtEval(js);
2930
+ const v = r.result?.value;
2931
+ if (v?.error) { log.fail(v.error); process.exit(1); }
2932
+ if (jsonOutput) emitJson(true, { scrolledTo: sel }); else log.ok(`Scrolled to: ${sel}`);
2933
+ } else if (sub === 'by' && argv[1] && argv[2]) {
2934
+ const dx = parseFloat(argv[1]); const dy = parseFloat(argv[2]);
2935
+ const js = `(() => { window.scrollBy(${dx}, ${dy}); return { x: window.scrollX, y: window.scrollY }; })()`;
2936
+ const r = await _rtEval(js);
2937
+ if (jsonOutput) emitJson(true, r.result?.value); else log.ok(`Scrolled by ${dx},${dy}`);
2938
+ } else if (sub === 'until' && argv[1]) {
2939
+ const sel = argv[1];
2940
+ const timeoutMs = 10000; const start = Date.now();
2941
+ while (Date.now() - start < timeoutMs) {
2942
+ const r = await _rtEval(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; const r=el.getBoundingClientRect(); return r.top >= 0 && r.bottom <= window.innerHeight; })()`);
2943
+ if (r.result?.value === true) { if (jsonOutput) emitJson(true, { found: sel }); else log.ok(`Reached: ${sel}`); return; }
2944
+ await _rtEval(`window.scrollBy(0, window.innerHeight * 0.8); void 0;`);
2945
+ await new Promise(r => setTimeout(r, 300));
2946
+ }
2947
+ if (jsonOutput) emitJson(false, null, 'scroll-until timeout');
2948
+ log.fail(`scroll-until timeout: ${sel}`); process.exit(1);
2949
+ } else {
2950
+ log.fail('Usage: glider scroll to <sel> | scroll by <dx> <dy> | scroll until <sel>'); process.exit(1);
2951
+ }
2952
+ }
2953
+
2954
+ // --- WAVE 1: cmdClick (upgraded) -------------------------------------
2955
+ // Backward-compat: glider click <selector>
2956
+ // New: glider click [<sel>] [--text S] [--contains S] [--regex R] [--nth N] [--role R] [--inside S] [--wait MS] [--scroll-into-view] [--double] [--right] [--hold MS] [--modifier ctrl|shift|alt|meta]
2957
+ function _buildFindElExpr(sel, opts) {
2958
+ // returns a JS expression evaluating to element or null; expects `document`
2959
+ const selJ = sel ? JSON.stringify(sel) : 'null';
2960
+ const textJ = opts.text ? JSON.stringify(opts.text) : 'null';
2961
+ const contJ = opts.contains ? JSON.stringify(opts.contains) : 'null';
2962
+ const rxJ = opts.regex ? JSON.stringify(opts.regex) : 'null';
2963
+ const roleJ = opts.role ? JSON.stringify(opts.role) : 'null';
2964
+ const insJ = opts.inside ? JSON.stringify(opts.inside) : 'null';
2965
+ const nthN = Number.isInteger(opts.nth) ? opts.nth : 0;
2966
+ return `(() => {
2967
+ const sel=${selJ}, text=${textJ}, cont=${contJ}, rxs=${rxJ}, role=${roleJ}, inside=${insJ}, nth=${nthN};
2968
+ const root = inside ? document.querySelector(inside) : document;
2969
+ if (!root) return null;
2970
+ let els;
2971
+ if (sel) els = [...root.querySelectorAll(sel)];
2972
+ else if (role) els = [...root.querySelectorAll('[role="'+role+'"]')];
2973
+ else els = [...root.querySelectorAll('button, [role=button], a, [role=link], [role=menuitem], [role=option], [role=listitem], li')];
2974
+ if (text) { const t=text.toLowerCase(); els = els.filter(e => (e.innerText||'').toLowerCase().includes(t)); }
2975
+ if (cont) { const t=cont.toLowerCase(); els = els.filter(e => (e.innerText||'').toLowerCase().includes(t)); }
2976
+ if (rxs) { const rx=new RegExp(rxs, 'i'); els = els.filter(e => rx.test(e.innerText||'')); }
2977
+ return els[nth] || null;
2978
+ })()`;
2979
+ }
2980
+ async function cmdClickV2(argv) {
2981
+ const opts = parseFlags(argv, {
2982
+ text: { type: 'string' }, contains: { type: 'string' }, regex: { type: 'string' },
2983
+ nth: { type: 'int' }, role: { type: 'string' }, inside: { type: 'string' },
2984
+ wait: { type: 'int' }, 'scroll-into-view': { type: 'boolean' },
2985
+ double: { type: 'boolean' }, right: { type: 'boolean' },
2986
+ hold: { type: 'int' }, modifier: { type: 'string' },
2987
+ });
2988
+ const sel = opts._[0];
2989
+ if (!sel && !opts.text && !opts.contains && !opts.regex && !opts.role) {
2990
+ log.fail('Usage: glider click <selector> [--text S | --contains S | --regex R | --nth N | --role R | --inside S | --scroll-into-view | --double | --right | --wait MS]'); process.exit(1);
2991
+ }
2992
+ await _guardAndConnect('click');
2993
+ const findExpr = _buildFindElExpr(sel, opts);
2994
+ const modifiers = { ctrl: 2, shift: 8, alt: 1, meta: 4 };
2995
+ const modBits = opts.modifier ? (modifiers[opts.modifier] || 0) : 0;
2996
+ // Wait for existence if --wait
2997
+ if (opts.wait) {
2998
+ const deadline = Date.now() + opts.wait;
2999
+ while (Date.now() < deadline) {
3000
+ const r = await _rtEval(`(() => { return !!${findExpr}; })()`);
3001
+ if (r.result?.value === true) break;
3002
+ await new Promise(r => setTimeout(r, 100));
3003
+ }
3004
+ }
3005
+ if (opts['scroll-into-view']) {
3006
+ await _rtEval(`(() => { const el=${findExpr}; if (el) el.scrollIntoView({behavior:'auto',block:'center'}); void 0; })()`);
3007
+ await new Promise(r => setTimeout(r, 100));
3008
+ }
3009
+ // For pointer-input path (right/double/hold), we need coords; simple .click() covers left-single
3010
+ if (opts.right || opts.double || opts.hold) {
3011
+ const cr = await _rtEval(`(() => { const el=${findExpr}; if (!el) return {error:'not found'}; const r=el.getBoundingClientRect(); return { x: Math.round(r.left+r.width/2), y: Math.round(r.top+r.height/2) }; })()`);
3012
+ const v = cr.result?.value;
3013
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
3014
+ const button = opts.right ? 'right' : 'left';
3015
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.x, y: v.y, button, clickCount: opts.double ? 2 : 1, modifiers: modBits } });
3016
+ if (opts.hold) await new Promise(r => setTimeout(r, opts.hold));
3017
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.x, y: v.y, button, clickCount: opts.double ? 2 : 1, modifiers: modBits } });
3018
+ if (opts.double) {
3019
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.x, y: v.y, button, clickCount: 2, modifiers: modBits } });
3020
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.x, y: v.y, button, clickCount: 2, modifiers: modBits } });
3021
+ }
3022
+ if (jsonOutput) emitJson(true, { clicked: true, button, at: v });
3023
+ else log.ok(`Clicked (${button}${opts.double ? ',double' : ''}) at ${v.x},${v.y}`);
3024
+ return;
3025
+ }
3026
+ // Left-single path via el.click()
3027
+ const js = `(() => { const el=${findExpr}; if (!el) return {error:'Element not found'}; el.click(); return { clicked: true }; })()`;
3028
+ try {
3029
+ const r = await _rtEval(js);
3030
+ if (r.result?.value?.error) { if (jsonOutput) emitJson(false, null, r.result.value.error); log.fail(r.result.value.error); process.exit(1); }
3031
+ if (jsonOutput) emitJson(true, { clicked: true });
3032
+ else log.ok(`Clicked${sel ? ': '+sel : ''}${opts.text ? ' text='+opts.text : ''}`);
3033
+ } catch (e) {
3034
+ if (jsonOutput) emitJson(false, null, e.message);
3035
+ log.fail(`Click failed: ${e.message}`); process.exit(1);
3036
+ }
3037
+ }
3038
+
3039
+ // --- WAVE 1: cmdType (upgraded, --editor auto) ----------------------
3040
+ async function cmdTypeV2(argv) {
3041
+ const opts = parseFlags(argv, {
3042
+ editor: { type: 'string' }, // auto|ckeditor|tinymce|prosemirror|monaco|slate|contentEditable|textarea|input
3043
+ file: { type: 'string' },
3044
+ 'clear-first': { type: 'boolean' },
3045
+ commit: { type: 'string' }, // enter|tab|blur|none
3046
+ code: { type: 'boolean' },
3047
+ lang: { type: 'string' },
3048
+ intro: { type: 'string' },
3049
+ raw: { type: 'boolean' },
3050
+ 'delay-ms': { type: 'int' },
3051
+ });
3052
+ const sel = opts._[0];
3053
+ let text = opts._.slice(1).join(' ');
3054
+ if (opts.file) {
3055
+ try { text = fs.readFileSync(opts.file, 'utf8'); } catch (e) { log.fail(`Cannot read --file: ${e.message}`); process.exit(1); }
3056
+ }
3057
+ if (!sel || (text === undefined || text === null)) {
3058
+ log.fail('Usage: glider type <selector> <text> [--editor auto|...] [--file PATH] [--clear-first] [--commit enter|tab|blur|none] [--code --lang X --intro TXT]'); process.exit(1);
3059
+ }
3060
+ await _guardAndConnect('type');
3061
+ const editor = opts.editor || 'auto';
3062
+ const clear = !!opts['clear-first'];
3063
+ const codeBlock = !!opts.code;
3064
+ const b64 = Buffer.from(text, 'utf8').toString('base64');
3065
+ const langJ = JSON.stringify(opts.lang || 'plaintext');
3066
+ const introB64 = Buffer.from(opts.intro || '', 'utf8').toString('base64');
3067
+ const selJ = JSON.stringify(sel);
3068
+ const edJ = JSON.stringify(editor);
3069
+ // The heart: editor-agnostic write
3070
+ const js = `(() => {
3071
+ const dec = b => new TextDecoder().decode(Uint8Array.from(atob(b), c => c.charCodeAt(0)));
3072
+ const body = dec('${b64}');
3073
+ const intro = dec('${introB64}');
3074
+ const el = document.querySelector(${selJ});
3075
+ if (!el) return { error: 'Element not found', selector: ${selJ} };
3076
+ const codeBlock = ${codeBlock ? 'true' : 'false'};
3077
+ const langHint = ${langJ};
3078
+ const clearFirst = ${clear ? 'true' : 'false'};
3079
+ let editor = ${edJ};
3080
+ // auto-detect
3081
+ if (editor === 'auto') {
3082
+ if (el.ckeditorInstance) editor = 'ckeditor';
3083
+ else if (window.tinymce && window.tinymce.get && window.tinymce.get(el.id)) editor = 'tinymce';
3084
+ else if (el.pmView || el.classList.contains('ProseMirror') || el.closest('.ProseMirror')) editor = 'prosemirror';
3085
+ else if (el.classList.contains('monaco-editor') || el.closest('.monaco-editor')) editor = 'monaco';
3086
+ else if (el.hasAttribute('data-slate-editor')) editor = 'slate';
3087
+ else if (el.CodeMirror || el.classList.contains('CodeMirror')) editor = 'codemirror';
3088
+ else if (el.isContentEditable) editor = 'contentEditable';
3089
+ else if (el.tagName === 'TEXTAREA') editor = 'textarea';
3090
+ else editor = 'input';
3091
+ }
3092
+ try {
3093
+ if (editor === 'ckeditor') {
3094
+ const inst = el.ckeditorInstance;
3095
+ if (!inst) return { error: 'ckeditor instance missing' };
3096
+ if (clearFirst) inst.setData('');
3097
+ if (codeBlock) {
3098
+ const pre = document.createElement('pre'), code = document.createElement('code');
3099
+ if (langHint) code.className = 'language-' + langHint;
3100
+ code.textContent = body;
3101
+ pre.appendChild(code);
3102
+ const introHtml = intro ? ('<p>' + intro.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</p>') : '';
3103
+ el.focus(); inst.setData(introHtml + pre.outerHTML);
3104
+ } else {
3105
+ el.focus(); inst.setData(body);
3106
+ }
3107
+ return { editor: 'ckeditor', wrote: inst.getData().length };
3108
+ }
3109
+ if (editor === 'tinymce') {
3110
+ const inst = window.tinymce.get(el.id);
3111
+ if (clearFirst) inst.setContent('');
3112
+ if (codeBlock) inst.setContent('<pre><code class="language-'+langHint+'">'+body.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</code></pre>');
3113
+ else inst.setContent(body);
3114
+ return { editor: 'tinymce' };
3115
+ }
3116
+ if (editor === 'monaco') {
3117
+ const mEl = el.classList.contains('monaco-editor') ? el : el.closest('.monaco-editor');
3118
+ // Search Monaco global registry for editor bound to this DOM node
3119
+ if (window.monaco && window.monaco.editor) {
3120
+ const eds = window.monaco.editor.getEditors ? window.monaco.editor.getEditors() : [];
3121
+ const me = eds.find(m => m.getContainerDomNode && m.getContainerDomNode() === mEl);
3122
+ if (me) { if (clearFirst) me.setValue(''); me.setValue(body); return { editor: 'monaco' }; }
3123
+ }
3124
+ return { error: 'monaco editor not resolvable' };
3125
+ }
3126
+ if (editor === 'prosemirror' || editor === 'slate' || editor === 'contentEditable') {
3127
+ // Best-effort: focus, select-all, insertText (execCommand path)
3128
+ const target = el.isContentEditable ? el : (el.querySelector('[contenteditable=true]') || el);
3129
+ target.focus();
3130
+ if (clearFirst) {
3131
+ const s = window.getSelection(); const r = document.createRange();
3132
+ r.selectNodeContents(target); s.removeAllRanges(); s.addRange(r);
3133
+ document.execCommand('delete', false, null);
3134
+ }
3135
+ // Insert as either code block or plain
3136
+ if (codeBlock) {
3137
+ document.execCommand('insertHTML', false, '<pre><code>' + body.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</code></pre>');
3138
+ } else {
3139
+ document.execCommand('insertText', false, body);
3140
+ }
3141
+ return { editor };
3142
+ }
3143
+ if (editor === 'textarea' || editor === 'input') {
3144
+ const nativeSetter = Object.getOwnPropertyDescriptor(el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype, 'value').set;
3145
+ if (clearFirst) { nativeSetter.call(el, ''); el.dispatchEvent(new Event('input', { bubbles: true })); }
3146
+ nativeSetter.call(el, (clearFirst || !el.value ? '' : el.value) + body);
3147
+ el.dispatchEvent(new Event('input', { bubbles: true }));
3148
+ el.dispatchEvent(new Event('change', { bubbles: true }));
3149
+ return { editor };
3150
+ }
3151
+ return { error: 'unknown editor: ' + editor };
3152
+ } catch (e) { return { error: 'editor write threw: ' + e.message }; }
3153
+ })()`;
3154
+ try {
3155
+ const r = await _rtEval(js);
3156
+ const v = r.result?.value;
3157
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
3158
+ if (opts.commit && opts.commit !== 'none') {
3159
+ // fire commit key via keyboard input layer
3160
+ const keyMap = { enter: 'Enter', tab: 'Tab' };
3161
+ if (opts.commit === 'blur') {
3162
+ await _rtEval(`(() => { const el = document.querySelector(${selJ}); if (el && el.blur) el.blur(); void 0; })()`);
3163
+ } else if (keyMap[opts.commit]) {
3164
+ await _dispatchKey(keyMap[opts.commit]);
3165
+ }
3166
+ }
3167
+ if (jsonOutput) emitJson(true, v);
3168
+ else log.ok(`Typed via ${v.editor || 'unknown'}${v.wrote ? ' (' + v.wrote + ' chars)' : ''}`);
3169
+ } catch (e) {
3170
+ if (jsonOutput) emitJson(false, null, e.message);
3171
+ log.fail(`Type failed: ${e.message}`); process.exit(1);
3172
+ }
3173
+ }
3174
+
3175
+ // --- WAVE 1: cmdWait (upgraded) --------------------------------------
3176
+ async function cmdWait(argv) {
3177
+ const opts = parseFlags(argv, {
3178
+ selector: { type: 'string' }, text: { type: 'string' }, gone: { type: 'string' },
3179
+ matches: { type: 'string' }, stable: { type: 'int' },
3180
+ 'network-idle': { type: 'int' }, 'url-matches': { type: 'string' },
3181
+ 'url-changes-from': { type: 'string' },
3182
+ timeout: { type: 'int', default: 10000 }, poll: { type: 'int', default: 200 },
3183
+ });
3184
+ const positional = opts._[0];
3185
+ // Back-compat: bare number = sleep in seconds
3186
+ if (positional && /^\d+(\.\d+)?$/.test(positional) && !opts.selector && !opts.matches && !opts.text && !opts.gone && !opts['url-matches']) {
3187
+ await new Promise(r => setTimeout(r, parseFloat(positional) * 1000));
3188
+ if (jsonOutput) emitJson(true, { slept_ms: parseFloat(positional) * 1000 });
3189
+ return;
3190
+ }
3191
+ await _guardAndConnect('wait');
3192
+ const deadline = Date.now() + opts.timeout;
3193
+ const buildProbe = () => {
3194
+ if (opts.selector) {
3195
+ const t = opts.text ? JSON.stringify(opts.text.toLowerCase()) : 'null';
3196
+ return `(() => { const e = document.querySelector(${JSON.stringify(opts.selector)}); if (!e) return false; const t=${t}; return t ? (e.innerText||'').toLowerCase().includes(t) : true; })()`;
3197
+ }
3198
+ if (opts.gone) return `!document.querySelector(${JSON.stringify(opts.gone)})`;
3199
+ if (opts.matches) return `!!(${opts.matches})`;
3200
+ if (opts['url-matches']) return `new RegExp(${JSON.stringify(opts['url-matches'])}).test(location.href)`;
3201
+ if (opts['url-changes-from']) return `location.href !== ${JSON.stringify(opts['url-changes-from'])}`;
3202
+ return 'true';
3203
+ };
3204
+ const probe = buildProbe();
3205
+ let lastRect = null; let stableStart = null;
3206
+ while (Date.now() < deadline) {
3207
+ try {
3208
+ const r = await _rtEval(probe, { awaitPromise: false });
3209
+ const v = r.result?.value;
3210
+ if (opts.stable && opts.selector) {
3211
+ const rr = await _rtEval(`(() => { const e = document.querySelector(${JSON.stringify(opts.selector)}); if (!e) return null; const r=e.getBoundingClientRect(); return [r.x,r.y,r.width,r.height]; })()`);
3212
+ const rect = rr.result?.value;
3213
+ if (rect && lastRect && rect.every((n,i)=>n===lastRect[i])) {
3214
+ if (!stableStart) stableStart = Date.now();
3215
+ if (Date.now() - stableStart >= opts.stable) { if (jsonOutput) emitJson(true, { stable_ms: opts.stable }); else log.ok(`stable for ${opts.stable}ms`); return; }
3216
+ } else { stableStart = null; }
3217
+ lastRect = rect;
3218
+ } else if (v === true) {
3219
+ if (jsonOutput) emitJson(true, { matched: true });
3220
+ else log.ok('condition met');
3221
+ return;
3222
+ }
3223
+ } catch (_) { /* ignore transient */ }
3224
+ await new Promise(r => setTimeout(r, opts.poll));
3225
+ }
3226
+ if (jsonOutput) emitJson(false, null, 'wait timeout');
3227
+ log.fail(`wait timeout after ${opts.timeout}ms`); process.exit(1);
3228
+ }
3229
+
3230
+ // --- WAVE 2: cmdKey / cmdRightClick / cmdDoubleClick / cmdDrag --------
3231
+ function _keyEventTemplate(keyName) {
3232
+ const specials = {
3233
+ Enter: { code: 'Enter', keyCode: 13, key: 'Enter', text: '\r' },
3234
+ Tab: { code: 'Tab', keyCode: 9, key: 'Tab' },
3235
+ Escape: { code: 'Escape', keyCode: 27, key: 'Escape' },
3236
+ Backspace: { code: 'Backspace', keyCode: 8, key: 'Backspace' },
3237
+ Delete: { code: 'Delete', keyCode: 46, key: 'Delete' },
3238
+ ArrowUp: { code: 'ArrowUp', keyCode: 38, key: 'ArrowUp' },
3239
+ ArrowDown: { code: 'ArrowDown', keyCode: 40, key: 'ArrowDown' },
3240
+ ArrowLeft: { code: 'ArrowLeft', keyCode: 37, key: 'ArrowLeft' },
3241
+ ArrowRight: { code: 'ArrowRight', keyCode: 39, key: 'ArrowRight' },
3242
+ Home: { code: 'Home', keyCode: 36, key: 'Home' },
3243
+ End: { code: 'End', keyCode: 35, key: 'End' },
3244
+ PageUp: { code: 'PageUp', keyCode: 33, key: 'PageUp' },
3245
+ PageDown: { code: 'PageDown', keyCode: 34, key: 'PageDown' },
3246
+ Space: { code: 'Space', keyCode: 32, key: ' ', text: ' ' },
3247
+ };
3248
+ return specials[keyName] || null;
3249
+ }
3250
+ async function _dispatchKey(keyName, mods = 0) {
3251
+ const tpl = _keyEventTemplate(keyName);
3252
+ if (!tpl) throw new Error('unknown key: ' + keyName);
3253
+ await httpPost('/cdp', { method: 'Input.dispatchKeyEvent', params: { type: 'keyDown', modifiers: mods, ...tpl } });
3254
+ await httpPost('/cdp', { method: 'Input.dispatchKeyEvent', params: { type: 'keyUp', modifiers: mods, ...tpl } });
3255
+ }
3256
+ async function _insertText(text) {
3257
+ await httpPost('/cdp', { method: 'Input.insertText', params: { text } });
3258
+ }
3259
+ async function cmdKey(argv) {
3260
+ await _guardAndConnect('key');
3261
+ // Grammar: `Ctrl+Enter`, `ArrowDown x5`, `Escape`, or `"literal text"`
3262
+ const raw = argv.join(' ');
3263
+ if (!raw) { log.fail('Usage: glider key "<Chord|Sequence>" e.g. "Ctrl+Enter" | "ArrowDown x5" | "Escape" | --text "insert this"'); process.exit(1); }
3264
+ const opts = parseFlags(argv, { text: { type: 'string' } });
3265
+ if (opts.text) { await _insertText(opts.text); if (jsonOutput) emitJson(true, { inserted: opts.text.length }); else log.ok(`Inserted ${opts.text.length} chars`); return; }
3266
+ // parse repeat count: "ArrowDown x5"
3267
+ const m = raw.match(/^([\w+]+)(?:\s+x(\d+))?$/i);
3268
+ if (m) {
3269
+ const chord = m[1]; const times = m[2] ? parseInt(m[2], 10) : 1;
3270
+ const parts = chord.split('+');
3271
+ const key = parts[parts.length - 1];
3272
+ const modMap = { ctrl: 2, control: 2, shift: 8, alt: 1, meta: 4, cmd: 4 };
3273
+ let mods = 0;
3274
+ for (const p of parts.slice(0, -1)) mods |= (modMap[p.toLowerCase()] || 0);
3275
+ for (let i = 0; i < times; i++) await _dispatchKey(key, mods);
3276
+ if (jsonOutput) emitJson(true, { key: chord, times });
3277
+ else log.ok(`Sent ${chord}${times>1 ? ' x'+times : ''}`);
3278
+ return;
3279
+ }
3280
+ log.fail('Could not parse key expression: ' + raw); process.exit(1);
3281
+ }
3282
+ async function cmdRightClick(argv) { await cmdClickV2(['--right', ...argv]); }
3283
+ async function cmdDoubleClick(argv) { await cmdClickV2(['--double', ...argv]); }
3284
+ async function cmdClickAt(argv) {
3285
+ const parts = (argv[0] || '').split(',');
3286
+ if (parts.length !== 2) { log.fail('Usage: glider click-at x,y'); process.exit(1); }
3287
+ const x = parseInt(parts[0], 10); const y = parseInt(parts[1], 10);
3288
+ await _guardAndConnect('click-at');
3289
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x, y, button: 'left', clickCount: 1 } });
3290
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 } });
3291
+ if (jsonOutput) emitJson(true, { clicked: {x, y} });
3292
+ else log.ok(`Clicked at ${x},${y}`);
3293
+ }
3294
+ async function cmdDrag(argv) {
3295
+ const opts = parseFlags(argv, { to: { type: 'string' }, steps: { type: 'int', default: 10 } });
3296
+ const src = opts._[0]; const dst = opts.to;
3297
+ if (!src || !dst) { log.fail('Usage: glider drag <src-sel> --to <dst-sel> [--steps N]'); process.exit(1); }
3298
+ await _guardAndConnect('drag');
3299
+ const r = await _rtEval(`(() => {
3300
+ const a = document.querySelector(${JSON.stringify(src)}); const b = document.querySelector(${JSON.stringify(dst)});
3301
+ if (!a || !b) return { error: 'src or dst not found' };
3302
+ const ra=a.getBoundingClientRect(), rb=b.getBoundingClientRect();
3303
+ return { sx: Math.round(ra.left+ra.width/2), sy: Math.round(ra.top+ra.height/2), dx: Math.round(rb.left+rb.width/2), dy: Math.round(rb.top+rb.height/2) };
3304
+ })()`);
3305
+ const v = r.result?.value;
3306
+ if (v?.error) { log.fail(v.error); process.exit(1); }
3307
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.sx, y: v.sy, button: 'left', clickCount: 1 } });
3308
+ for (let i = 1; i <= opts.steps; i++) {
3309
+ const x = v.sx + Math.round((v.dx - v.sx) * i / opts.steps);
3310
+ const y = v.sy + Math.round((v.dy - v.sy) * i / opts.steps);
3311
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseMoved', x, y, button: 'left' } });
3312
+ }
3313
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.dx, y: v.dy, button: 'left', clickCount: 1 } });
3314
+ if (jsonOutput) emitJson(true, { dragged: {from: [v.sx,v.sy], to: [v.dx,v.dy]} });
3315
+ else log.ok(`Dragged ${v.sx},${v.sy} -> ${v.dx},${v.dy}`);
3316
+ }
3317
+
3318
+ // --- WAVE 2: cmdSelect ----------------------------------------------
3319
+ async function cmdSelect(argv) {
3320
+ const opts = parseFlags(argv, { 'by-text': { type: 'string' }, 'by-value': { type: 'string' }, nth: { type: 'int', default: 0 } });
3321
+ const sel = opts._[0];
3322
+ if (!sel || (!opts['by-text'] && !opts['by-value'] && opts.nth === undefined)) {
3323
+ log.fail('Usage: glider select <selector> --by-text S | --by-value V | --nth N'); process.exit(1);
3324
+ }
3325
+ await _guardAndConnect('select');
3326
+ const wantJ = JSON.stringify(opts['by-text'] || opts['by-value'] || '');
3327
+ const mode = opts['by-text'] ? 'text' : opts['by-value'] ? 'value' : 'nth';
3328
+ const nth = opts.nth || 0;
3329
+ const js = `(() => {
3330
+ const el = document.querySelector(${JSON.stringify(sel)});
3331
+ if (!el) return { error: 'select not found' };
3332
+ const want = ${wantJ}; const mode = ${JSON.stringify(mode)}; const nth = ${nth};
3333
+ if (el.tagName === 'SELECT') {
3334
+ const opts = [...el.options];
3335
+ let target;
3336
+ if (mode === 'text') target = opts.find(o => (o.textContent||'').trim().toLowerCase().includes(want.toLowerCase()));
3337
+ else if (mode === 'value') target = opts.find(o => o.value === want);
3338
+ else target = opts[nth];
3339
+ if (!target) return { error: 'option not found' };
3340
+ el.value = target.value;
3341
+ el.dispatchEvent(new Event('change', { bubbles: true }));
3342
+ return { selected: target.value };
3343
+ }
3344
+ // aria-listbox / aria-combobox path
3345
+ const listbox = el.getAttribute('role') === 'listbox' ? el : el.querySelector('[role=listbox]');
3346
+ if (listbox) {
3347
+ const options = [...listbox.querySelectorAll('[role=option]')];
3348
+ let target;
3349
+ if (mode === 'text') target = options.find(o => (o.textContent||'').toLowerCase().includes(want.toLowerCase()));
3350
+ else if (mode === 'value') target = options.find(o => o.getAttribute('data-value') === want || o.textContent.trim() === want);
3351
+ else target = options[nth];
3352
+ if (!target) return { error: 'aria option not found' };
3353
+ target.click();
3354
+ return { selected: target.textContent.trim() };
3355
+ }
3356
+ return { error: 'not a select or listbox' };
3357
+ })()`;
3358
+ const r = await _rtEval(js);
3359
+ const v = r.result?.value;
3360
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
3361
+ if (jsonOutput) emitJson(true, v);
3362
+ else log.ok(`Selected: ${v.selected}`);
3363
+ }
3364
+
3365
+ // --- WAVE 2: cmdEval upgrade (--arg, --arg-file, --json, --await, --context) ---
3366
+ async function cmdEvalV2(argv) {
3367
+ const opts = parseFlags(argv, {
3368
+ arg: { type: 'string' }, 'arg-file': { type: 'string' },
3369
+ json: { type: 'boolean' }, await: { type: 'boolean', default: true },
3370
+ context: { type: 'string' }, // main|iframe|sw|worker (advisory only for now)
3371
+ });
3372
+ const js = opts._.join(' ');
3373
+ if (!js) { log.fail('Usage: glider eval <js> [--arg K=V ...] [--arg-file K=@path ...] [--await] [--context main|iframe|sw|worker]'); process.exit(1); }
3374
+ if (!await ensureConnected()) process.exit(1);
3375
+ // Build ${K} substitutions safely
3376
+ // Multiple --arg parses: user may pass --arg foo=bar --arg baz=qux ; parseFlags only kept the last one.
3377
+ // So we re-walk argv for all --arg / --arg-file occurrences.
3378
+ const args = {};
3379
+ for (let i = 0; i < argv.length; i++) {
3380
+ if (argv[i] === '--arg' && argv[i+1]) { const [k, ...rest] = argv[++i].split('='); args[k] = rest.join('='); }
3381
+ else if (argv[i] === '--arg-file' && argv[i+1]) {
3382
+ const spec = argv[++i]; const [k, ...rest] = spec.split('='); const path = rest.join('=');
3383
+ const p = path.replace(/^@/, '');
3384
+ args[k] = fs.readFileSync(p, 'utf8');
3385
+ }
3386
+ }
3387
+ // Substitute ${K} with JSON.stringified value so it's injection-safe
3388
+ let expr = js.replace(/\$\{(\w+)\}/g, (m, k) => k in args ? JSON.stringify(args[k]) : m);
3389
+ try {
3390
+ const r = await _rtEval(expr, { awaitPromise: opts.await !== false });
3391
+ const v = r.result?.value;
3392
+ if (opts.json || jsonOutput) emitJson(true, v !== undefined ? v : r.result);
3393
+ else if (v !== undefined) console.log(typeof v === 'string' ? v : JSON.stringify(v));
3394
+ else console.log(JSON.stringify(r));
3395
+ } catch (e) {
3396
+ if (jsonOutput || opts.json) emitJson(false, null, e.message);
3397
+ log.fail(`Eval failed: ${e.message}`); process.exit(1);
3398
+ }
3399
+ }
3400
+
3401
+ // --- WAVE 2: cmdScreenshot upgrade (--selector, --clip, --full-page, --format) ---
3402
+ async function cmdScreenshotV2(argv) {
3403
+ const opts = parseFlags(argv, {
3404
+ selector: { type: 'string' }, clip: { type: 'string' },
3405
+ 'full-page': { type: 'boolean' }, format: { type: 'string', default: 'png' },
3406
+ pad: { type: 'int', default: 0 },
3407
+ });
3408
+ const outPath = opts._[0] || `/tmp/glider-screenshot-${Date.now()}.${opts.format}`;
3409
+ if (!await ensureConnected()) process.exit(1);
3410
+ const params = { format: opts.format };
3411
+ if (opts.selector) {
3412
+ const r = await _rtEval(`(() => { const el = document.querySelector(${JSON.stringify(opts.selector)}); if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.left, y: r.top, width: r.width, height: r.height, dpr: window.devicePixelRatio || 1 }; })()`);
3413
+ const v = r.result?.value;
3414
+ if (!v) { log.fail('selector not found'); process.exit(1); }
3415
+ params.clip = { x: v.x - opts.pad, y: v.y - opts.pad, width: v.width + opts.pad*2, height: v.height + opts.pad*2, scale: 1 };
3416
+ } else if (opts.clip) {
3417
+ const [x, y, w, h] = opts.clip.split(',').map(Number);
3418
+ params.clip = { x, y, width: w, height: h, scale: 1 };
3419
+ }
3420
+ if (opts['full-page']) params.captureBeyondViewport = true;
3421
+ try {
3422
+ const result = await httpPost('/cdp', { method: 'Page.captureScreenshot', params });
3423
+ if (result.data) {
3424
+ fs.writeFileSync(outPath, Buffer.from(result.data, 'base64'));
3425
+ if (jsonOutput) emitJson(true, { path: outPath, bytes: Buffer.byteLength(result.data, 'base64') });
3426
+ else log.ok(`Screenshot: ${outPath}`);
3427
+ } else { log.fail('no screenshot data'); process.exit(1); }
3428
+ } catch (e) { log.fail(`Screenshot failed: ${e.message}`); process.exit(1); }
3429
+ }
3430
+
3431
+ // --- WAVE 2: session_liveness_probe (upgrade cmdUseSession) ---
3432
+ async function cmdUseSessionV2(arg, opts = []) {
3433
+ // Try normal path first
3434
+ try {
3435
+ await cmdUseSession(arg, opts);
3436
+ return;
3437
+ } catch (_) { /* fall through to re-probe */ }
3438
+ // Re-probe: connect + fetch targets, re-match on --url if provided
3439
+ const urlIdx = opts.indexOf('--url');
3440
+ if (urlIdx >= 0 && opts[urlIdx+1]) {
3441
+ log.warn('use-session failed - re-probing');
3442
+ try {
3443
+ const result = await httpPost('/list-targets', {});
3444
+ const targets = result.targets || [];
3445
+ const want = opts[urlIdx+1].toLowerCase();
3446
+ const hit = targets.find(t => (t.url||'').toLowerCase().includes(want));
3447
+ if (hit) { await cmdUseSession(hit.sessionId, opts); return; }
3448
+ } catch (e) { log.fail(`re-probe failed: ${e.message}`); }
3449
+ }
3450
+ log.fail(`use-session: session not live and no --url to re-probe`); process.exit(1);
3451
+ }
3452
+
3453
+ // --- WAVE 3: frames + iframe-scope-eval + upload-file ---
3454
+ async function cmdFrames(argv) {
3455
+ await _guardAndConnect('frames');
3456
+ try {
3457
+ const r = await httpPost('/cdp', { method: 'Page.getFrameTree', params: {} });
3458
+ if (jsonOutput) emitJson(true, r.frameTree);
3459
+ else console.log(JSON.stringify(r.frameTree, null, 2));
3460
+ } catch (e) { log.fail(`frames failed: ${e.message}`); process.exit(1); }
3461
+ }
3462
+ async function cmdFrameEval(argv) {
3463
+ const frameId = argv[0]; const js = argv.slice(1).join(' ');
3464
+ if (!frameId || !js) { log.fail('Usage: glider frame-eval <frameId> <js>'); process.exit(1); }
3465
+ await _guardAndConnect('frame-eval');
3466
+ // Create isolated world in frame, eval there
3467
+ try {
3468
+ const iw = await httpPost('/cdp', { method: 'Page.createIsolatedWorld', params: { frameId, worldName: 'glider' } });
3469
+ const r = await _rtEval(js, { contextId: iw.executionContextId });
3470
+ const v = r.result?.value;
3471
+ if (jsonOutput) emitJson(true, v);
3472
+ else console.log(typeof v === 'string' ? v : JSON.stringify(v));
3473
+ } catch (e) { log.fail(`frame-eval failed: ${e.message}`); process.exit(1); }
3474
+ }
3475
+ async function cmdUpload(argv) {
3476
+ const sel = argv[0]; const filePath = argv[1];
3477
+ if (!sel || !filePath) { log.fail('Usage: glider upload <input-selector> <file-path>'); process.exit(1); }
3478
+ await _guardAndConnect('upload');
3479
+ try {
3480
+ const nodeR = await _rtEval(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return null; return true; })()`);
3481
+ if (!nodeR.result?.value) { log.fail('input not found'); process.exit(1); }
3482
+ // Need backendNodeId via DOM.getDocument -> DOM.querySelector
3483
+ const doc = await httpPost('/cdp', { method: 'DOM.getDocument', params: { depth: -1 } });
3484
+ const q = await httpPost('/cdp', { method: 'DOM.querySelector', params: { nodeId: doc.root.nodeId, selector: sel } });
3485
+ if (!q.nodeId) { log.fail('nodeId lookup failed'); process.exit(1); }
3486
+ await httpPost('/cdp', { method: 'DOM.setFileInputFiles', params: { files: [filePath], nodeId: q.nodeId } });
3487
+ if (jsonOutput) emitJson(true, { uploaded: filePath, to: sel });
3488
+ else log.ok(`Attached ${filePath} to ${sel}`);
3489
+ } catch (e) { log.fail(`upload failed: ${e.message}`); process.exit(1); }
3490
+ }
3491
+
3492
+ // --- WAVE 3: cmdHar (start/stop/dump/status) ---
3493
+ // v0.4.1: rewired to bexplore subprocess (was Potemkin stub - help advertised
3494
+ // the verb but dump always returned 0 entries; "server-side subscription
3495
+ // not implemented"). Now delegates to the same code path `explore --har` uses.
3496
+ async function cmdHar(argv) {
3497
+ const sub = argv[0];
3498
+ const STATE_PATH = path.join(os.homedir(), '.glider', 'har-state.json');
3499
+ const BUF_HAR = path.join(os.homedir(), '.glider', 'har-buffer.har');
3500
+ const BUF_OUT = path.join(os.homedir(), '.glider', 'har-buffer-out');
3501
+ const readState = () => { try { return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')); } catch { return null; } };
3502
+ const writeState = (st) => { try { fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true }); } catch {} fs.writeFileSync(STATE_PATH, JSON.stringify(st, null, 2)); };
3503
+ const pidAlive = (pid) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } };
3504
+
3505
+ if (sub === 'start') {
3506
+ const url = argv[1];
3507
+ if (!url) { log.fail('Usage: glider har start <url> [--session-id id]'); process.exit(1); }
3508
+ const existing = readState();
3509
+ if (existing && pidAlive(existing.pid)) {
3510
+ log.fail(`HAR capture already running (pid=${existing.pid}, url=${existing.url}). Run 'glider har stop' first.`);
3511
+ process.exit(1);
3512
+ }
3513
+ let sessionId = null;
3514
+ for (let i = 2; i < argv.length; i++) {
3515
+ if (argv[i] === '--session-id' || argv[i] === '--session') sessionId = argv[++i];
3516
+ }
3517
+ if (!sessionId && activeSessionId) sessionId = activeSessionId;
3518
+ await _guardAndConnect('har');
3519
+ try { fs.mkdirSync(BUF_OUT, { recursive: true }); } catch {}
3520
+ try { fs.unlinkSync(BUF_HAR); } catch {}
3521
+ const bexplorePath = path.join(LIB_DIR, 'bexplore.js');
3522
+ const spawnArgs = [bexplorePath, url, '--depth', '0', '--output', BUF_OUT, '--har', BUF_HAR];
3523
+ if (sessionId) spawnArgs.push('--session-id', sessionId);
3524
+ const child = spawn('node', spawnArgs, { detached: true, stdio: ['ignore', 'ignore', 'ignore'] });
3525
+ child.unref();
3526
+ const state = { pid: child.pid, har: BUF_HAR, url, session_id: sessionId, started_at: new Date().toISOString() };
3527
+ writeState(state);
3528
+ if (jsonOutput) emitJson(true, state);
3529
+ else log.ok(`HAR capture started (pid=${child.pid}, url=${url}); dump with 'glider har dump [path]'`);
3530
+ } else if (sub === 'stop') {
3531
+ const st = readState();
3532
+ if (!st) { log.fail('No HAR capture in progress'); process.exit(1); }
3533
+ if (pidAlive(st.pid)) { try { process.kill(st.pid, 'SIGTERM'); } catch {} }
3534
+ try { fs.unlinkSync(STATE_PATH); } catch {}
3535
+ if (jsonOutput) emitJson(true, { stopped: true, pid: st.pid });
3536
+ else log.ok(`HAR capture stopped (pid=${st.pid})`);
3537
+ } else if (sub === 'dump') {
3538
+ const p = argv[1] || `/tmp/glider-${Date.now()}.har`;
3539
+ const st = readState();
3540
+ if (!st) { log.fail('No HAR capture in progress. Run: glider har start <url>'); process.exit(1); }
3541
+ const timeoutMs = 60000;
3542
+ const started = Date.now();
3543
+ while (pidAlive(st.pid) && (Date.now() - started) < timeoutMs) {
3544
+ await new Promise(r => setTimeout(r, 500));
3545
+ }
3546
+ if (pidAlive(st.pid)) {
3547
+ log.fail(`HAR child still running after ${timeoutMs}ms; run 'glider har stop' or wait`);
3548
+ process.exit(1);
3549
+ }
3550
+ if (!fs.existsSync(st.har)) {
3551
+ log.fail(`HAR buffer not found at ${st.har} (capture may have failed)`);
3552
+ process.exit(1);
3553
+ }
3554
+ fs.copyFileSync(st.har, p);
3555
+ let entryCount = 0;
3556
+ try { entryCount = JSON.parse(fs.readFileSync(p, 'utf8')).log.entries.length; } catch {}
3557
+ try { fs.unlinkSync(STATE_PATH); } catch {}
3558
+ if (jsonOutput) emitJson(true, { path: p, entries: entryCount });
3559
+ else log.ok(`HAR dumped to ${p} (${entryCount} entries)`);
3560
+ } else if (sub === 'status') {
3561
+ const st = readState();
3562
+ if (!st) { if (jsonOutput) emitJson(true, { running: false }); else console.log('idle'); return; }
3563
+ const alive = pidAlive(st.pid);
3564
+ if (jsonOutput) emitJson(true, { running: alive, ...st });
3565
+ else console.log(`${alive ? 'RUNNING' : 'DONE'} pid=${st.pid} url=${st.url} started=${st.started_at}`);
3566
+ } else {
3567
+ log.fail('Usage: glider har start <url> [--session-id id] | stop | dump [PATH] | status'); process.exit(1);
3568
+ }
3569
+ }
3570
+
3571
+ // --- WAVE 4: cmdEmulate ---
3572
+ async function cmdEmulate(argv) {
3573
+ const what = argv[0]; const val = argv.slice(1).join(' ');
3574
+ if (!what) { log.fail('Usage: glider emulate <tz|geo|viewport|offline|ua|color-scheme> <value>'); process.exit(1); }
3575
+ await _guardAndConnect('emulate');
3576
+ try {
3577
+ if (what === 'tz') {
3578
+ await httpPost('/cdp', { method: 'Emulation.setTimezoneOverride', params: { timezoneId: val } });
3579
+ } else if (what === 'geo') {
3580
+ const [lat, lng, acc] = val.split(',').map(Number);
3581
+ await httpPost('/cdp', { method: 'Emulation.setGeolocationOverride', params: { latitude: lat, longitude: lng, accuracy: acc || 100 } });
3582
+ } else if (what === 'viewport') {
3583
+ const m = val.match(/^(\d+)x(\d+)(?:,(\d+(?:\.\d+)?))?(?:,(true|false))?$/);
3584
+ if (!m) { log.fail('viewport format: WxH[,dpr[,mobile]]'); process.exit(1); }
3585
+ await httpPost('/cdp', { method: 'Emulation.setDeviceMetricsOverride', params: { width: parseInt(m[1]), height: parseInt(m[2]), deviceScaleFactor: m[3] ? parseFloat(m[3]) : 1, mobile: m[4] === 'true' } });
3586
+ } else if (what === 'offline') {
3587
+ const presets = { true: { offline: true, latency: 0, downloadThroughput: 0, uploadThroughput: 0 }, 'slow-3g': { offline: false, latency: 400, downloadThroughput: 51200, uploadThroughput: 51200 }, 'fast-4g': { offline: false, latency: 20, downloadThroughput: 4*1024*1024/8, uploadThroughput: 3*1024*1024/8 }, false: { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 } };
3588
+ const p = presets[val]; if (!p) { log.fail('offline: true|slow-3g|fast-4g|false'); process.exit(1); }
3589
+ await httpPost('/cdp', { method: 'Network.emulateNetworkConditions', params: p });
3590
+ } else if (what === 'ua') {
3591
+ await httpPost('/cdp', { method: 'Emulation.setUserAgentOverride', params: { userAgent: val } });
3592
+ } else if (what === 'color-scheme') {
3593
+ await httpPost('/cdp', { method: 'Emulation.setEmulatedMedia', params: { features: [{ name: 'prefers-color-scheme', value: val }] } });
3594
+ } else { log.fail(`unknown emulate target: ${what}`); process.exit(1); }
3595
+ if (jsonOutput) emitJson(true, { emulate: what, value: val });
3596
+ else log.ok(`Emulated ${what}=${val}`);
3597
+ } catch (e) { log.fail(`emulate failed: ${e.message}`); process.exit(1); }
3598
+ }
3599
+
3600
+ // --- WAVE 4: cmdStorage ---
3601
+ async function cmdStorage(argv) {
3602
+ const sub = argv[0];
3603
+ await _guardAndConnect('storage');
3604
+ if (sub === 'get') {
3605
+ const k = argv[1]; if (!k) { log.fail('storage get <key>'); process.exit(1); }
3606
+ const r = await _rtEval(`localStorage.getItem(${JSON.stringify(k)})`);
3607
+ if (jsonOutput) emitJson(true, r.result?.value); else console.log(r.result?.value || '');
3608
+ } else if (sub === 'set') {
3609
+ const k = argv[1]; const v = argv.slice(2).join(' ');
3610
+ await _rtEval(`localStorage.setItem(${JSON.stringify(k)}, ${JSON.stringify(v)}); void 0;`);
3611
+ if (jsonOutput) emitJson(true, { set: k }); else log.ok(`storage set: ${k}`);
3612
+ } else if (sub === 'delete') {
3613
+ const k = argv[1];
3614
+ await _rtEval(`localStorage.removeItem(${JSON.stringify(k)}); void 0;`);
3615
+ if (jsonOutput) emitJson(true, { deleted: k }); else log.ok(`storage deleted: ${k}`);
3616
+ } else if (sub === 'keys') {
3617
+ const r = await _rtEval(`Object.keys(localStorage)`);
3618
+ if (jsonOutput) emitJson(true, r.result?.value);
3619
+ else (r.result?.value || []).forEach(k => console.log(k));
3620
+ } else if (sub === 'jar') {
3621
+ const r = await _rtEval(`(() => { const o={}; for (let i=0;i<localStorage.length;i++){const k=localStorage.key(i); o[k]=localStorage.getItem(k);} return o; })()`);
3622
+ if (jsonOutput) emitJson(true, r.result?.value);
3623
+ else console.log(JSON.stringify(r.result?.value || {}, null, 2));
3624
+ } else {
3625
+ log.fail('Usage: glider storage get <k> | set <k> <v> | delete <k> | keys | jar'); process.exit(1);
3626
+ }
3627
+ }
3628
+
3629
+ // --- WAVE 4: cmdHistory + cmdDialog + cmdConsole + cmdPdf ---
3630
+ async function cmdHistory(argv) {
3631
+ const sub = argv[0]; await _guardAndConnect('history');
3632
+ if (sub === 'back') await _rtEval('history.back(); void 0;');
3633
+ else if (sub === 'forward') await _rtEval('history.forward(); void 0;');
3634
+ else if (sub === 'reload') await httpPost('/cdp', { method: 'Page.reload', params: {} });
3635
+ else { log.fail('Usage: glider history back | forward | reload'); process.exit(1); }
3636
+ if (jsonOutput) emitJson(true, { history: sub }); else log.ok(`history ${sub}`);
3637
+ }
3638
+ async function cmdDialog(argv) {
3639
+ const sub = argv[0]; const action = argv[1];
3640
+ if (sub !== 'auto' || !['accept','dismiss'].includes(action)) { log.fail('Usage: glider dialog auto accept|dismiss'); process.exit(1); }
3641
+ await _guardAndConnect('dialog');
3642
+ // NOTE: needs bg WS subscription to Page.javascriptDialogOpening for full solution.
3643
+ // Here: inject a page-side beforeunload/confirm/alert stub.
3644
+ await _rtEval(`(() => {
3645
+ window.alert = () => ${action === 'accept' ? 'true' : 'undefined'};
3646
+ window.confirm = () => ${action === 'accept' ? 'true' : 'false'};
3647
+ window.prompt = () => ${action === 'accept' ? "''" : 'null'};
3648
+ window.onbeforeunload = null;
3649
+ return { installed: true };
3650
+ })()`);
3651
+ if (jsonOutput) emitJson(true, { dialog: 'auto-' + action });
3652
+ else log.ok(`Dialog auto-${action} installed`);
3653
+ }
3654
+ async function cmdConsole(argv) {
3655
+ const sub = argv[0]; if (sub !== 'tail' && sub !== 'dump') { log.fail('Usage: glider console tail | dump [PATH]'); process.exit(1); }
3656
+ await _guardAndConnect('console');
3657
+ await httpPost('/cdp', { method: 'Runtime.enable', params: {} });
3658
+ // Persistent tail requires bg WS; here we do a one-shot poll: enable console + report installed
3659
+ log.warn('console tail is stub - needs bg WS subscription to Runtime.consoleAPICalled');
3660
+ if (jsonOutput) emitJson(true, { installed: true, note: 'stub - bg subscription required' });
3661
+ }
3662
+ async function cmdPdf(argv) {
3663
+ const opts = parseFlags(argv, { landscape: { type: 'boolean' }, margin: { type: 'float' }, scale: { type: 'float', default: 1.0 } });
3664
+ const outPath = opts._[0] || `/tmp/glider-${Date.now()}.pdf`;
3665
+ await _guardAndConnect('pdf');
3666
+ try {
3667
+ const params = { landscape: !!opts.landscape, scale: opts.scale, printBackground: true };
3668
+ if (opts.margin !== undefined) { params.marginTop = params.marginBottom = params.marginLeft = params.marginRight = opts.margin; }
3669
+ const r = await httpPost('/cdp', { method: 'Page.printToPDF', params });
3670
+ if (r.data) { fs.writeFileSync(outPath, Buffer.from(r.data, 'base64')); if (jsonOutput) emitJson(true, { path: outPath }); else log.ok(`PDF: ${outPath}`); }
3671
+ else { log.fail('no pdf data'); process.exit(1); }
3672
+ } catch (e) { log.fail(`pdf failed: ${e.message}`); process.exit(1); }
3673
+ }
3674
+ async function cmdCookieWrite(argv) {
3675
+ const opts = parseFlags(argv, { set: { type: 'string' }, delete: { type: 'string' }, host: { type: 'string' } });
3676
+ if (!opts.host) { log.fail('Usage: glider cookies --set NAME=VAL --host H | --delete NAME --host H'); process.exit(1); }
3677
+ await _guardAndConnect('cookies-write');
3678
+ try {
3679
+ if (opts.set) {
3680
+ const [name, ...rest] = opts.set.split('='); const value = rest.join('=');
3681
+ const r = await httpPost('/extension', { method: 'setCookie', params: { url: 'https://' + opts.host, name, value } });
3682
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie set: ${name}@${opts.host}`);
3683
+ } else if (opts.delete) {
3684
+ const r = await httpPost('/extension', { method: 'removeCookie', params: { url: 'https://' + opts.host, name: opts.delete } });
3685
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${opts.host}`);
3686
+ }
3687
+ } catch (e) { log.fail(`cookie write failed: ${e.message}`); process.exit(1); }
3688
+ }
3689
+
3690
+ // --- WAVE 5: cmdMock + cmdA11ySnapshot + cmdRecord/Replay ---
3691
+ async function cmdMock(argv) {
3692
+ const sub = argv[0];
3693
+ await _guardAndConnect('mock');
3694
+ if (sub === 'clear') {
3695
+ await httpPost('/cdp', { method: 'Fetch.disable', params: {} });
3696
+ if (jsonOutput) emitJson(true, { cleared: true }); else log.ok('mocks cleared');
3697
+ return;
3698
+ }
3699
+ const opts = parseFlags(argv.slice(1), { status: { type: 'int', default: 200 }, body: { type: 'string' } });
3700
+ const glob = argv[0];
3701
+ if (!glob || !opts.body) { log.fail('Usage: glider mock <url-glob> --status N --body FILE | glider mock clear'); process.exit(1); }
3702
+ try {
3703
+ await httpPost('/cdp', { method: 'Fetch.enable', params: { patterns: [{ urlPattern: glob }] } });
3704
+ log.warn('mock is stub - needs bg WS subscription to Fetch.requestPaused + Fetch.fulfillRequest');
3705
+ if (jsonOutput) emitJson(true, { registered: glob, note: 'stub' });
3706
+ } catch (e) { log.fail(`mock failed: ${e.message}`); process.exit(1); }
3707
+ }
3708
+ async function cmdA11y(argv) {
3709
+ await _guardAndConnect('a11y');
3710
+ try {
3711
+ await httpPost('/cdp', { method: 'Accessibility.enable', params: {} });
3712
+ const r = await httpPost('/cdp', { method: 'Accessibility.getFullAXTree', params: {} });
3713
+ if (jsonOutput) emitJson(true, r.nodes);
3714
+ else console.log(JSON.stringify(r.nodes, null, 2));
3715
+ } catch (e) { log.fail(`a11y failed: ${e.message}`); process.exit(1); }
3716
+ }
3717
+
3718
+ // End of dom-scorch verb block. Total ≈ 30 verbs / verb-upgrades.
3719
+
3720
+
2672
3721
  // Main
2673
3722
  async function main() {
2674
3723
  const args = parseGlobalFlags(process.argv.slice(2));
@@ -2774,7 +3823,7 @@ async function main() {
2774
3823
  await cmdTargets();
2775
3824
  break;
2776
3825
  case 'use-session':
2777
- await cmdUseSession(args[1], args.slice(2));
3826
+ await cmdUseSessionV2(args[1], args.slice(2));
2778
3827
  break;
2779
3828
  case 'snapshot':
2780
3829
  await cmdSnapshot(args.slice(1));
@@ -2798,17 +3847,98 @@ async function main() {
2798
3847
  break;
2799
3848
  case 'eval':
2800
3849
  case 'js':
2801
- await cmdEval(args.slice(1).join(' '));
3850
+ await cmdEvalV2(args.slice(1));
2802
3851
  break;
2803
3852
  case 'click':
2804
- await cmdClick(args[1]);
3853
+ await cmdClickV2(args.slice(1));
2805
3854
  break;
2806
3855
  case 'type':
2807
- await cmdType(args[1], args.slice(2).join(' '));
3856
+ await cmdTypeV2(args.slice(1));
2808
3857
  break;
2809
3858
  case 'screenshot':
2810
- await cmdScreenshot(args[1]);
3859
+ await cmdScreenshotV2(args.slice(1));
3860
+ break;
3861
+ // ── dom-scorch waves 1-5 ──
3862
+ case 'read':
3863
+ await cmdRead(args.slice(1));
3864
+ break;
3865
+ case 'hover':
3866
+ await cmdHover(args.slice(1));
3867
+ break;
3868
+ case 'focus':
3869
+ await cmdFocusVerb(args.slice(1));
3870
+ break;
3871
+ case 'blur':
3872
+ await cmdBlurVerb(args.slice(1));
3873
+ break;
3874
+ case 'scroll':
3875
+ case 'scroll-to':
3876
+ case 'scroll-by':
3877
+ case 'scroll-until':
3878
+ if (cmd === 'scroll') await cmdScroll(args.slice(1));
3879
+ else await cmdScroll([cmd.replace('scroll-',''), ...args.slice(1)]);
3880
+ break;
3881
+ case 'wait':
3882
+ await cmdWait(args.slice(1));
3883
+ break;
3884
+ case 'key':
3885
+ await cmdKey(args.slice(1));
2811
3886
  break;
3887
+ case 'right-click':
3888
+ await cmdRightClick(args.slice(1));
3889
+ break;
3890
+ case 'double-click':
3891
+ await cmdDoubleClick(args.slice(1));
3892
+ break;
3893
+ case 'click-at':
3894
+ await cmdClickAt(args.slice(1));
3895
+ break;
3896
+ case 'drag':
3897
+ await cmdDrag(args.slice(1));
3898
+ break;
3899
+ case 'select':
3900
+ await cmdSelect(args.slice(1));
3901
+ break;
3902
+ case 'frames':
3903
+ await cmdFrames(args.slice(1));
3904
+ break;
3905
+ case 'frame-eval':
3906
+ await cmdFrameEval(args.slice(1));
3907
+ break;
3908
+ case 'upload':
3909
+ await cmdUpload(args.slice(1));
3910
+ break;
3911
+ case 'har':
3912
+ await cmdHar(args.slice(1));
3913
+ break;
3914
+ case 'emulate':
3915
+ await cmdEmulate(args.slice(1));
3916
+ break;
3917
+ case 'storage':
3918
+ await cmdStorage(args.slice(1));
3919
+ break;
3920
+ case 'history':
3921
+ await cmdHistory(args.slice(1));
3922
+ break;
3923
+ case 'dialog':
3924
+ await cmdDialog(args.slice(1));
3925
+ break;
3926
+ case 'console':
3927
+ await cmdConsole(args.slice(1));
3928
+ break;
3929
+ case 'pdf':
3930
+ await cmdPdf(args.slice(1));
3931
+ break;
3932
+ case 'mock':
3933
+ await cmdMock(args.slice(1));
3934
+ break;
3935
+ case 'a11y':
3936
+ await cmdA11y(args.slice(1));
3937
+ break;
3938
+ case 'cookies-write':
3939
+ await cmdCookieWrite(args.slice(1));
3940
+ break;
3941
+ // ── /dom-scorch ──
2812
3942
  case 'text':
2813
3943
  await cmdText();
2814
3944
  break;
@@ -2834,7 +3964,11 @@ async function main() {
2834
3964
  await cmdFrozen(args.slice(1));
2835
3965
  break;
2836
3966
  case 'cookies':
2837
- await cmdCookies(args.slice(1));
3967
+ if (args.slice(1).some(a => a === '--set' || a === '--delete')) {
3968
+ await cmdCookieWrite(args.slice(1));
3969
+ } else {
3970
+ await cmdCookies(args.slice(1));
3971
+ }
2838
3972
  break;
2839
3973
  case 'spawn':
2840
3974
  await cmdSpawn(args.slice(1));
@@ -2909,7 +4043,9 @@ async function main() {
2909
4043
  const KNOWN_CMDS = ['status','start','stop','restart','reload-ext','attach-all','install','uninstall',
2910
4044
  'update','version','connect','browser','use','test','domains','resolve','goto','eval','click','type',
2911
4045
  'screenshot','snapshot','text','html','title','url','tabs','targets','use-session','fetch','spawn',
2912
- 'extract','explore','favicon','window','reg','run','loop','ralph'];
4046
+ 'extract','explore','favicon','window','reg','run','loop','ralph',
4047
+ 'read','hover','focus','blur','scroll','wait','key','right-click','double-click','click-at','drag','select',
4048
+ 'frames','frame-eval','upload','har','emulate','storage','history','dialog','console','pdf','mock','a11y','cookies'];
2913
4049
  function lev(a, b) {
2914
4050
  if (Math.abs(a.length - b.length) > 2) return 3;
2915
4051
  const m = Array.from({length: a.length+1}, () => new Array(b.length+1).fill(0));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.3.21",
3
+ "version": "0.4.2",
4
4
  "description": "Browser automation CLI. Control Chrome from terminal via CDP, run YAML task files, autonomous loops until completion.",
5
5
  "main": "index.js",
6
6
  "bin": {