/**
 * @license
 * Copyright 2025 ReverseCraft
 * SPDX-License-Identifier: Apache-2.0
 */
import{logger as e}from"./logger.js";export function findNearestBreakpointLocation(e,t){if(0===e.length)return null;let r=e[0],c=Math.abs(r.columnNumber-t);for(let n=1;n<e.length;n++){const o=e[n],u=Math.abs(o.columnNumber-t);(u<c||u===c&&o.columnNumber<r.columnNumber)&&(r=o,c=u)}return r}export async function queryPossibleBreakpoints(t,r,c,n,o,u,s){try{const e={start:{scriptId:r,lineNumber:c,columnNumber:n},end:{scriptId:r,lineNumber:o,columnNumber:u}},i=await t.send("Debugger.getPossibleBreakpoints",e);return(i.locations||[]).map(e=>({scriptId:e.scriptId,scriptUrl:s,lineNumber:e.lineNumber+1,columnNumber:e.columnNumber}))}catch(t){return e(`[debugger] Failed to get possible breakpoints: ${t}`),[]}}const t=new WeakMap;export function getScriptCache(e){let r=t.get(e);return r||(r=new Map,t.set(e,r)),r}export function cacheScript(e,t){getScriptCache(e).set(t.scriptId,t)}export function clearScriptCache(e){const r=t.get(e);r&&r.clear()}export async function findMatchingScripts(t,r){const c=getScriptCache(t),n=new RegExp(r),o=[];for(const e of c.values())n.test(e.url)&&o.push(e);return o.length>0?o:(e(`[debugger] No cached scripts matching pattern: ${r}`),[])}export async function getScriptSource(t,r){const c=getScriptCache(t).get(r);if(void 0!==c?.source)return c.source;try{const e=(await t.send("Debugger.getScriptSource",{scriptId:r})).scriptSource||null;return c&&null!==e&&(c.source=e),e}catch(t){return e(`[debugger] Failed to get script source for ${r}: ${t}`),null}}export async function getAllScriptsWithSource(e,t){const r=getScriptCache(e),c=new Map,n=t?new RegExp(t):null,o=[];for(const[e,t]of r)n&&!n.test(t.url)||t.url&&(void 0!==t.source?c.set(e,{url:t.url,source:t.source}):o.push({scriptId:e,url:t.url}));for(let t=0;t<o.length;t+=10){const r=o.slice(t,t+10),n=await Promise.all(r.map(({scriptId:t})=>getScriptSource(e,t)));for(let e=0;e<r.length;e++){const t=n[e];null!==t&&c.set(r[e].scriptId,{url:r[e].url,source:t})}}return c}