ilml-plugin-linkedin 1.20.7 → 1.20.9

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.
@@ -1,7 +1,9 @@
1
- var Uo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Uo(e,n,{get:t[n],enumerable:!0})};async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function zo(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(s=>setTimeout(s,o))}return!1}function Zo(e){return Qo.test(e||"")}async function pt(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await zo(e,t,{timeout:o,label:n});if(!r&&Zo(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return r}async function ht(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:i=6e4}={}){return await e.goto(t,{waitUntil:"domcontentloaded",timeout:i}),pt(e,{readySelector:n,label:o,timeout:r})}async function ge(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),s=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||s||c){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let u of a){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Qo,Qe=ce(()=>{Qo=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as Xo}from"@ilivemylife/graph-sdk";var er,fe,te,gt,yt,wt=ce(async()=>{er=await Xo();for(let[e,t]of Object.entries(er))process.env[e]===void 0&&(process.env[e]=t);fe=process.env.LINKEDIN_NAME,te=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),gt=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.NEEDS_REVIEW])),yt=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.REJECTED,te.NEEDS_REVIEW]))});import"dotenv/config";import*as O from"fs";import*as P from"path";import{fileURLToPath as tr}from"url";function hn(){Ce=null,rr=null,ne=null,sr=null,ir=null,lr=null}function Xe(){O.existsSync(oe)||O.mkdirSync(oe,{recursive:!0})}function kt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function vt(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${P.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let r=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function Fe(){return new Date().toISOString().split("T")[0]}function ye(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function un(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,n=null){if(!t||e[t])return t;let o=ye(t);if(!o)return t;let r=null;for(let[i,s]of Object.entries(e)){if(ye(s.profileUrl||i)===o)return i;!r&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=i)}if(r){let i=un(n),s=un(e[r].name);if(i&&s&&i===s)return r}return t}function ur(){O.existsSync(St)||O.mkdirSync(St,{recursive:!0})}function gn(e){let t=ye(e);return t?P.join(St,`${t}.json`):null}function fr(e){let t=gn(e);return t?vt(t,`profile-history/${ye(e)}.json`)||[]:[]}function dr(e,t){let n=gn(e);if(!n)return;ur();let o=fr(e);o.unshift(t);try{kt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ye(e)}: ${r.message}`)}}function fn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function dn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function mr(e,t){if(!e)return[];let n=[];for(let o of cr){let r=e[o],i=t[o];fn(r)||fn(i)||dn(r)!==dn(i)&&n.push(o)}return n}function pr(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function re(){return Ce||(Xe(),Ce=vt(bt,"people.json")||{},Ce)}function et(e){Xe(),Ce=e;try{kt(bt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${P.resolve(bt)}`)}}function Ze(e,t={}){if(!e)return null;let n=re(),o=Fe(),r=new Date().toISOString(),i=xe(n,e,t.name),s=n[i];if(s){let c=mr(s,t);c.length>0&&(dr(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:pr(s)}),s.lastSnapshotAt=r),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=r,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of ar)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=r)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return et(n),n[i]}function yn(e,t){if(!e||!t)return;let n=re(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Fe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),et(n))}function wn(e){return e&&re()[e]?.connectionStatus||null}function bn(e,t,n={}){if(!e)return;if(n.profileInfo)Ze(e,n.profileInfo);else{let c=re(),l=xe(c,e,n.profileInfo?.name);c[l]||Ze(e,{})}let o=re(),r=xe(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let s=Fe();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),et(o)}function Sn(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ye(t);if(!o)return;let r=re(),i=xe(r,e),s=r[i];if(!s)return;let c=ye(s.profileUrl||i);o!==c&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(o)||(s.aliases.push(o),s.lastUpdated=new Date().toISOString(),et(r)))}function kn(){return ne||(Xe(),ne=vt(mn,"quota.json"),(!ne||!ne.connections)&&(ne={connections:[]}),ne)}function hr(e){Xe(),ne=e;try{kt(mn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function vn(e,t="unknown"){let n=kn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),hr(n)}function Cn(){let e=kn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ct(){let e=Cn(),t=Fe(),n=e.filter(l=>l.date===t).length,o=e.length,r=n>=Ne,i=o>=Oe,s=!r&&!i,c={allowed:s,daily:{sent:n,max:Ne},weekly:{sent:o,max:Oe}};return s||(c.reason=r?`Daily limit reached (${n}/${Ne})`:`Weekly limit reached (${o}/${Oe})`),c}function xt(){let e=Cn(),t=Fe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Ne,remaining:Ne-n},weekly:{sent:o,max:Oe,remaining:Oe-o}}}var nr,or,oe,bt,xi,mn,$i,Ai,Ei,St,pn,Ne,Oe,Ce,rr,ne,sr,ir,lr,ar,cr,tt=ce(async()=>{await wt();nr=tr(import.meta.url),or=P.dirname(P.dirname(nr)),oe=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(or,"collected-profiles"),bt=P.join(oe,"people.json"),xi=P.join(oe,"jobs.json"),mn=P.join(oe,"quota.json"),$i=P.join(oe,"conversations.json"),Ai=P.join(oe,"sync-state.json"),Ei=P.join(oe,"application-questions.json"),St=P.join(oe,"profile-history"),pn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ne=pn(process.env.CONNECT_MAX_DAILY,20),Oe=pn(process.env.CONNECT_MAX_WEEKLY,100),Ce=null,rr=null,ne=null,sr=null,ir=null,lr=null;ar=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],cr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var xn={};ee(xn,{extractCertificationsFromDetails:()=>Sr,extractEducationFromDetails:()=>wr,extractExperienceFromDetails:()=>gr,extractFeaturedFromDetails:()=>yr,extractRecommendationsFromDetails:()=>kr,extractSkillsFromDetails:()=>br});async function gr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await pt(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await S(1e3);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let o=0;for(;o<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)o++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function i(a){let u=[];for(let f of a.querySelectorAll("div")){let d=Array.from(f.children).filter(g=>g.tagName==="DIV");if(d.length<3)continue;let m=d.filter(g=>(g.textContent||"").trim().length>50);m.length<3||(f.textContent||"").length<500||u.push({el:f,count:m.length,totalText:(f.textContent||"").length})}return u.sort((f,d)=>d.count-f.count||f.totalText-d.totalText),u[0]?.el}let s=i(r);if(!s)return[];let c=Array.from(s.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function l(a){let u=a[0]||null,f=null,d=null;if(a[1]){let k=a[1].split("\xB7").map(E=>E.trim());f=k[0]||null,k[1]&&(d=k[1])}let m=a.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),g=null,y=null;if(m>=0){let k=a[m].split("\xB7").map(E=>E.trim());g=k[0]||null,k[1]&&(y=k[1])}let h=null,p=-1;if(m>=0&&a[m+1]){let k=a[m+1],E=/^[>*\-•]|^&gt;/.test(k),j=/https?:\/\//.test(k),X=/\d{4}/.test(k),K=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!E&&!j&&!X&&k.length<100&&K&&(h=k,p=m+1)}let v=null,x=-1,w=a[a.length-1];if(w&&/and\s+\+\d+\s+skills?$/i.test(w)){x=a.length-1;let k=w.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(v={listed:k[1].split(",").map(E=>E.trim()),additional:parseInt(k[2],10)})}let A=new Set([0,1,m,p,x].filter(k=>k>=0)),R=a.filter((k,E)=>!A.has(E)),D=R.length>0?R.join(`
1
+ var Jo=Object.defineProperty;var ee=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var n in t)Jo(e,n,{get:t[n],enumerable:!0})};import q from"fs";import ne from"path";function gt(){let e=process.env.ILML_SCOPE_DIR;return e?ne.join(e,"plugins-state","linkedin","cookies.json"):Zo}function er(){let e=gt(),t=ne.dirname(e);return t&&t!=="."&&!q.existsSync(t)&&q.mkdirSync(t,{recursive:!0}),e}function dn(e){let t=er();return q.writeFileSync(t,JSON.stringify(e)),t}function mn(){let e=gt();if(!q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=q.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function pn(){return q.existsSync(gt())}function tr(){let e=process.env.ILML_SCOPE_DIR;return e?ne.join(e,"plugins-state","linkedin"):"."}function hn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function nr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?hn(t[1]):"default"}function gn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return q.existsSync(t)||q.mkdirSync(t,{recursive:!0}),ne.resolve(t);let n=hn(e||nr()),o=ne.join(tr(),"chrome-profile",n);return q.existsSync(o)||q.mkdirSync(o,{recursive:!0}),ne.resolve(o)}function wn(e){return!q.existsSync(ne.join(e,yn))}function bn(e){try{q.writeFileSync(ne.join(e,yn),new Date().toISOString())}catch{}}function Sn(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{q.rmSync(ne.join(e,n),{force:!0}),t++}catch{}return t}var Zo,yn,Qe=ee(()=>{Zo="cookies.json";yn=".ilml-seeded"});async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function or(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(s=>setTimeout(s,o))}return!1}function rr(e){return kn.test(e||"")}async function sr(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),i=Date.now(),s=!1;for(;Date.now()-i<r;){let l="wait";try{l=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",kn.source)}catch{}if(l==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(f=>f.name==="li_at")){let f=dn(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(l==="creds"){if(!o){let a=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}s||(s=!0,console.log(`
2
+ \u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
3
+ `))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function Xe(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await or(e,t,{timeout:o,label:n});if(!r&&rr(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return r}async function yt(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:i=6e4,autoRecover:s=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await Xe(e,{readySelector:n,label:o,timeout:r})}catch(c){if(s&&c.code==="SESSION_EXPIRED"){await sr(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await Xe(e,{readySelector:n,label:o,timeout:r})}throw c}}async function ge(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),s=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||s||c){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let u of a){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var kn,Ze=ee(()=>{Qe();kn=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as ir}from"@ilivemylife/graph-sdk";var lr,de,oe,wt,bt,St=ee(async()=>{lr=await ir();for(let[e,t]of Object.entries(lr))process.env[e]===void 0&&(process.env[e]=t);de=process.env.LINKEDIN_NAME,oe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),wt=Object.freeze(new Set([oe.DRAFT,oe.CONFIRMED,oe.NEEDS_REVIEW])),bt=Object.freeze(new Set([oe.DRAFT,oe.CONFIRMED,oe.REJECTED,oe.NEEDS_REVIEW]))});import"dotenv/config";import*as O from"fs";import*as F from"path";import{fileURLToPath as ar}from"url";function En(){Ce=null,fr=null,re=null,dr=null,mr=null,pr=null}function tt(){O.existsSync(se)||O.mkdirSync(se,{recursive:!0})}function Ct(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function xt(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${F.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let r=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function Pe(){return new Date().toISOString().split("T")[0]}function ye(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function vn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,n=null){if(!t||e[t])return t;let o=ye(t);if(!o)return t;let r=null;for(let[i,s]of Object.entries(e)){if(ye(s.profileUrl||i)===o)return i;!r&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=i)}if(r){let i=vn(n),s=vn(e[r].name);if(i&&s&&i===s)return r}return t}function yr(){O.existsSync(vt)||O.mkdirSync(vt,{recursive:!0})}function _n(e){let t=ye(e);return t?F.join(vt,`${t}.json`):null}function wr(e){let t=_n(e);return t?xt(t,`profile-history/${ye(e)}.json`)||[]:[]}function br(e,t){let n=_n(e);if(!n)return;yr();let o=wr(e);o.unshift(t);try{Ct(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ye(e)}: ${r.message}`)}}function Cn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function xn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Sr(e,t){if(!e)return[];let n=[];for(let o of gr){let r=e[o],i=t[o];Cn(r)||Cn(i)||xn(r)!==xn(i)&&n.push(o)}return n}function kr(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function ie(){return Ce||(tt(),Ce=xt(kt,"people.json")||{},Ce)}function nt(e){tt(),Ce=e;try{Ct(kt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${F.resolve(kt)}`)}}function et(e,t={}){if(!e)return null;let n=ie(),o=Pe(),r=new Date().toISOString(),i=xe(n,e,t.name),s=n[i];if(s){let c=Sr(s,t);c.length>0&&(br(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:kr(s)}),s.lastSnapshotAt=r),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=r,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of hr)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=r)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return nt(n),n[i]}function In(e,t){if(!e||!t)return;let n=ie(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Pe(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),nt(n))}function Dn(e){return e&&ie()[e]?.connectionStatus||null}function Rn(e,t,n={}){if(!e)return;if(n.profileInfo)et(e,n.profileInfo);else{let c=ie(),l=xe(c,e,n.profileInfo?.name);c[l]||et(e,{})}let o=ie(),r=xe(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let s=Pe();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),nt(o)}function Tn(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ye(t);if(!o)return;let r=ie(),i=xe(r,e),s=r[i];if(!s)return;let c=ye(s.profileUrl||i);o!==c&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(o)||(s.aliases.push(o),s.lastUpdated=new Date().toISOString(),nt(r)))}function jn(){return re||(tt(),re=xt($n,"quota.json"),(!re||!re.connections)&&(re={connections:[]}),re)}function vr(e){tt(),re=e;try{Ct($n,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Nn(e,t="unknown"){let n=jn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),vr(n)}function On(){let e=jn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function $t(){let e=On(),t=Pe(),n=e.filter(l=>l.date===t).length,o=e.length,r=n>=Ne,i=o>=Oe,s=!r&&!i,c={allowed:s,daily:{sent:n,max:Ne},weekly:{sent:o,max:Oe}};return s||(c.reason=r?`Daily limit reached (${n}/${Ne})`:`Weekly limit reached (${o}/${Oe})`),c}function At(){let e=On(),t=Pe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Ne,remaining:Ne-n},weekly:{sent:o,max:Oe,remaining:Oe-o}}}var cr,ur,se,kt,Ti,$n,ji,Ni,Oi,vt,An,Ne,Oe,Ce,fr,re,dr,mr,pr,hr,gr,ot=ee(async()=>{await St();cr=ar(import.meta.url),ur=F.dirname(F.dirname(cr)),se=process.env.DATA_DIR?F.resolve(process.env.DATA_DIR,"collected-profiles"):F.join(ur,"collected-profiles"),kt=F.join(se,"people.json"),Ti=F.join(se,"jobs.json"),$n=F.join(se,"quota.json"),ji=F.join(se,"conversations.json"),Ni=F.join(se,"sync-state.json"),Oi=F.join(se,"application-questions.json"),vt=F.join(se,"profile-history"),An=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ne=An(process.env.CONNECT_MAX_DAILY,20),Oe=An(process.env.CONNECT_MAX_WEEKLY,100),Ce=null,fr=null,re=null,dr=null,mr=null,pr=null;hr=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],gr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Pn={};te(Pn,{extractCertificationsFromDetails:()=>Er,extractEducationFromDetails:()=>$r,extractExperienceFromDetails:()=>Cr,extractFeaturedFromDetails:()=>xr,extractRecommendationsFromDetails:()=>_r,extractSkillsFromDetails:()=>Ar});async function Cr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await Xe(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await S(1e3);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let o=0;for(;o<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)o++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function i(a){let u=[];for(let f of a.querySelectorAll("div")){let d=Array.from(f.children).filter(g=>g.tagName==="DIV");if(d.length<3)continue;let m=d.filter(g=>(g.textContent||"").trim().length>50);m.length<3||(f.textContent||"").length<500||u.push({el:f,count:m.length,totalText:(f.textContent||"").length})}return u.sort((f,d)=>d.count-f.count||f.totalText-d.totalText),u[0]?.el}let s=i(r);if(!s)return[];let c=Array.from(s.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function l(a){let u=a[0]||null,f=null,d=null;if(a[1]){let k=a[1].split("\xB7").map(E=>E.trim());f=k[0]||null,k[1]&&(d=k[1])}let m=a.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),g=null,y=null;if(m>=0){let k=a[m].split("\xB7").map(E=>E.trim());g=k[0]||null,k[1]&&(y=k[1])}let h=null,p=-1;if(m>=0&&a[m+1]){let k=a[m+1],E=/^[>*\-•]|^&gt;/.test(k),j=/https?:\/\//.test(k),Z=/\d{4}/.test(k),z=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!E&&!j&&!Z&&k.length<100&&z&&(h=k,p=m+1)}let v=null,x=-1,w=a[a.length-1];if(w&&/and\s+\+\d+\s+skills?$/i.test(w)){x=a.length-1;let k=w.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(v={listed:k[1].split(",").map(E=>E.trim()),additional:parseInt(k[2],10)})}let A=new Set([0,1,m,p,x].filter(k=>k>=0)),R=a.filter((k,E)=>!A.has(E)),D=R.length>0?R.join(`
2
4
 
3
5
  `):null;return{title:u,company:f,employmentType:d,dates:g,duration:y,location:h,description:D,skills:v,_raw:a}}return c.map(a=>{let f=(a.innerText||"").trim().split(`
4
- `).map(d=>d.trim()).filter(d=>d&&d.length<5e3);return l(f)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Pe(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function Le(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function yr(e,t){return Le(t,"featured","extractFeaturedFromDetails",async()=>(await Pe(e,t,"featured"),await e.evaluate(`(() => {
6
+ `).map(d=>d.trim()).filter(d=>d&&d.length<5e3);return l(f)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Fe(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function Le(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function xr(e,t){return Le(t,"featured","extractFeaturedFromDetails",async()=>(await Fe(e,t,"featured"),await e.evaluate(`(() => {
5
7
  ${Me}
6
8
 
7
9
  const main = document.querySelector('main');
@@ -42,7 +44,7 @@ var Uo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
42
44
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
45
  return true;
44
46
  });
45
- })()`)))}async function wr(e,t){return Le(t,"education","extractEducationFromDetails",async()=>(await Pe(e,t,"education"),await e.evaluate(`(() => {
47
+ })()`)))}async function $r(e,t){return Le(t,"education","extractEducationFromDetails",async()=>(await Fe(e,t,"education"),await e.evaluate(`(() => {
46
48
  ${Me}
47
49
 
48
50
  const main = document.querySelector('main');
@@ -79,7 +81,7 @@ var Uo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
79
81
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
82
  return true;
81
83
  });
82
- })()`)))}async function br(e,t){return Le(t,"skills","extractSkillsFromDetails",async()=>(await Pe(e,t,"skills"),await e.evaluate(`(() => {
84
+ })()`)))}async function Ar(e,t){return Le(t,"skills","extractSkillsFromDetails",async()=>(await Fe(e,t,"skills"),await e.evaluate(`(() => {
83
85
  ${Me}
84
86
 
85
87
  const main = document.querySelector('main');
@@ -111,7 +113,7 @@ var Uo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
111
113
  skills.push({ name, endorsements, _raw: lines });
112
114
  }
113
115
  return skills;
114
- })()`)))}async function Sr(e,t){return Le(t,"certifications","extractCertificationsFromDetails",async()=>(await Pe(e,t,"certifications"),await e.evaluate(`(() => {
116
+ })()`)))}async function Er(e,t){return Le(t,"certifications","extractCertificationsFromDetails",async()=>(await Fe(e,t,"certifications"),await e.evaluate(`(() => {
115
117
  ${Me}
116
118
 
117
119
  const main = document.querySelector('main');
@@ -136,7 +138,7 @@ var Uo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
136
138
 
137
139
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
140
  }).filter(e => e.name);
139
- })()`)))}async function kr(e,t){return Le(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Pe(e,t,"recommendations"),await e.evaluate(`(() => {
141
+ })()`)))}async function _r(e,t){return Le(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Fe(e,t,"recommendations"),await e.evaluate(`(() => {
140
142
  ${Me}
141
143
 
142
144
  const main = document.querySelector('main');
@@ -172,7 +174,7 @@ var Uo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
172
174
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
175
  return true;
174
176
  });
175
- })()`)))}var Me,$n=ce(()=>{Qe();Me=`
177
+ })()`)))}var Me,Fn=ee(()=>{Ze();Me=`
176
178
  function findEntryContainer(root) {
177
179
  const candidates = [];
178
180
  for (const div of root.querySelectorAll('div')) {
@@ -235,72 +237,72 @@ function findEntryContainer(root) {
235
237
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
238
  return candidates[0]?.el;
237
239
  }
238
- `});var In={};ee(In,{BLOCK_MARKERS:()=>An,dedupeAndCap:()=>_n,extractSidePanelProfiles:()=>vr,normalizeFundUrl:()=>nt,normalizeProfileUrl:()=>$e,scanRelatedBlocks:()=>En});function $e(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function nt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function En(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=a=>(a||"").replace(/\s+/g," ").trim(),r=a=>{let u=String(a||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=a=>o(a).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=a=>{let u=a,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||a.parentElement},c=[],l=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let a of l){let u=o(a.textContent).toLowerCase();if(!u)continue;let f=e.find(([h])=>u.includes(h));if(!f)continue;let d=f[1],m=s(a);if(!m)continue;let g=0,y=new Set;for(let h of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let p=h.href||h.getAttribute("href")||"",v=r(p);if(!v)continue;let x=h.querySelector('span[aria-hidden="true"]'),w=o(x?x.textContent:h.getAttribute("aria-label")||h.textContent),A=i(w);if(!A||y.has(v))continue;y.add(v);let R="",D=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(D&&(R=o(D[1])),!R){let k=h.closest("li")||h.parentElement;k&&(R=Array.from(k.querySelectorAll("p, span")).map(j=>o(j.textContent)).filter(j=>j&&j!==A&&!/^view\b/i.test(j)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(j)&&/[a-z]/i.test(j)&&j.length>2)[0]||"")}c.push({href:p,name:A,headline:R,block:d,rank:g++})}}return c}function _n(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=$e(t.seedUrl||""),r=new Map,i={};for(let s of e||[]){let c=$e(s.href);c&&(o&&c===o||(i[s.block]=i[s.block]||0,!(i[s.block]>=n)&&(r.has(c)||(i[s.block]++,r.set(c,{url:c,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(r.values())}async function vr(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(En,An)}catch{return[]}return _n(n,t)}var An,$t=ce(()=>{An=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var On={};ee(On,{getJobDecision:()=>_r,getLastVisit:()=>Fr,getScoutStats:()=>Pr,loadCompanies:()=>Rt,loadDiscoveredPeople:()=>He,loadJobDecisions:()=>Dt,loadScoutedJobs:()=>It,loadVisitLog:()=>st,recordCompany:()=>jr,recordDiscoveredEdge:()=>Rr,recordDiscoveredEdges:()=>Tr,recordVisit:()=>Or,resetCaches:()=>_t,saveCompany:()=>Nr,saveDiscoveredPerson:()=>Ir,saveScoutedJob:()=>Ar,setJobDecision:()=>Er});import"dotenv/config";import*as V from"fs";import*as B from"path";import{fileURLToPath as Cr}from"url";function de(){V.existsSync(be)||V.mkdirSync(be,{recursive:!0})}function me(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";V.writeFileSync(o,n);for(let r=0;r<3;r++)try{V.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ve(e){try{if(V.existsSync(e))return JSON.parse(V.readFileSync(e,"utf-8"))}catch{}return null}function _t(){Ue=null,qe=null,Be=null,Je=null,we=null}function It(){return Ue||(Ue=Ve(Dn)||{},Ue)}function Ar(e,t){if(!e)return;de();let n=It(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,i]of Object.entries(t))i!=null&&(n[e][r]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{me(Dn,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function Dt(){return qe||(qe=Ve(Tn)||{},qe)}function Er(e,t,n={}){if(!e||!t)return;de();let o=Dt(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{me(Tn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function _r(e){return Dt()[e]||null}function He(){return Be||(Be=Ve(rt)||{},Be)}function Ae(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function jn(e,t){let n=$e(t)||t;if(e[n])return n;let o=Ae(t);if(!o)return n;let r=null;for(let[i,s]of Object.entries(e)){if(Ae(s&&(s.canonicalUrl||s.profileUrl)||i)===o)return i;!r&&s&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=i)}return r||n}function Ir(e,t){if(!e)return;de();let n=He(),o=new Date().toISOString().slice(0,10),r=jn(n,e),i=Ae(e);if(n[r]){let s=n[r];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&Ae(s.canonicalUrl||s.profileUrl||r)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=o,s.seenCount=(s.seenCount||1)+1}else n[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{me(rt,n)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Dr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function Nn(e,t,n={},o){if(!t)return;let r=Ae(t);t=jn(e,t);let i=n.seedUrl?{...n,seedUrl:$e(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=Dr(i,o),a=e[t];a||(a=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),n.name&&(a.name=n.name),n.headline&&(!a.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(a.headline))&&(a.headline=n.headline),n.location&&(a.location=a.location||n.location),n.company&&(a.company=n.company),n.companyUrl&&(a.companyUrl=a.companyUrl||n.companyUrl),n.isConnected!=null&&(a.isConnected=n.isConnected),n.connectionsCount!=null&&(a.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(a.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(a.connectGate=n.connectGate),n.note&&!a.note&&(a.note=n.note),n.whyUseful&&!a.whyUseful&&(a.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(a.extra={...a.extra||{},...n.extra}),Array.isArray(a.sources)||(a.sources=[]);let u=a.sources.find(l);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):a.sources.push(c),Array.isArray(a.categories)||(a.categories=[]),Array.isArray(a.sectors)||(a.sectors=[]),Array.isArray(a.aliases)||(a.aliases=[]),Array.isArray(a.graphRefs)||(a.graphRefs=[]),At(a.categories,n.category),ot(a.categories,n.categories),ot(a.sectors,n.sectors),ot(a.aliases,n.aliases),r&&Ae(a.canonicalUrl||t)!==r&&At(a.aliases,r),ot(a.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(a.affiliations)||(a.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||a.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||a.affiliations.push(f)}a.lastSeen=s,a.seenCount=(a.seenCount||0)+1}function Rr(e,t={}){if(!e)return;de();let n=He();Nn(n,e,t,new Date().toISOString());try{me(rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Tr(e){if(!Array.isArray(e)||e.length===0)return;de();let t=He(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(Nn(t,r.url,r,n),o++);if(o)try{me(rt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function jr(e={}){if(!e||!e.name)return;de();let t=e.key||nt(e.website)||nt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=Rt(),o=new Date().toISOString().slice(0,10),r=(l,a)=>{a&&Array.isArray(l)&&!l.includes(a)&&l.push(a)},i=(l,a)=>{if(Array.isArray(a))for(let u of a)r(l,u)},s=n[t];s||(s=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let c=l=>{if(!l||!l.url)return;let a=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));a?l.current!=null&&(a.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(l=>c({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let a=l&&(l.key||l.name);a&&!s.portfolio.some(u=>(u.key||u.name)===a)&&s.portfolio.push(l)}s.lastSeen=o,s.seenCount=(s.seenCount||0)+1;try{me(Et,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function Rt(){return Je||(Je=Ve(Et)||{},Je)}function Nr(e,t){if(!e)return;de();let n=Rt(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{me(Et,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function st(){return we||(we=Ve(Rn)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function Or(e,t={}){if(!e)return;de();let n=st();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{me(Rn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Fr(e){let t=st();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function Pr(){let e=It(),t=He(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let i=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),s={};for(let d of n)for(let m of d.techStack||[])s[m]=(s[m]||0)+1;let c=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),l=st(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(a)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var xr,$r,be,Dn,rt,Rn,Et,Tn,Ue,qe,Be,At,ot,Je,we,Tt=ce(()=>{$t();xr=Cr(import.meta.url),$r=B.dirname(B.dirname(xr)),be=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join($r,"market-research"),Dn=B.join(be,"scouted-jobs.json"),rt=B.join(be,"discovered-people.json"),Rn=B.join(be,"visit-log.json"),Et=B.join(be,"companies.json"),Tn=B.join(be,"job-decisions.json");Ue=null;qe=null;Be=null;At=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},ot=(e,t)=>{if(Array.isArray(t))for(let n of t)At(e,n)};Je=null;we=null});var Wn={};ee(Wn,{computeEngagement:()=>Nt,detectCategory:()=>Mn,detectCategoryFromTitle:()=>it,determineAction:()=>Vn,determineLastMessageBy:()=>Un,determineSituation:()=>Ln,enrichConversation:()=>Mr,enrichPerson:()=>Vr,enrichPersonContext:()=>Hn,extractAutoTags:()=>Bn,generateSummary:()=>qn,normPreview:()=>jt});function Mr(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!yt.has(l.status)),i=Ur(t,e.profileUrl,n),s=Un(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Mn(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Ln(r,s,t),r.length>0){let l=r[r.length-1];e.lastMessageTime=l.time}if(r.length>0&&!e.initiatedBy){let l=r[0];l.sender===fe?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=Nt(r,t),e.personContext=Hn(i),e.summary=qn(e,t,i),e.autoTags=Bn(e,t,i);let c=Vn(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Lr(e),e}function Mn(e,t,n){if(!e||e.length===0)return n?.title?it(n.title):null;let o=e.filter(r=>r.sender!==fe&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,i]of Object.entries(Pn))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(o))return r}if(n?.title){let r=it(n.title);if(r)return r}return null}function it(e){if(!e)return null;for(let[t,n]of Object.entries(Pn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Ln(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Fn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(i=>i.sender!==fe&&i.sender!=="Unknown");return Fn.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Un(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let i=r.sender;if(i===fe)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function qn(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],i=e.category,s=n?.title,c=n?.company,l=n?.location;i==="recruiter"&&c?r.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):i==="founder"&&c?r.push(`Founder of ${c}`):i&&s?r.push(`${Ot(i)}: ${Ee(s,40)}`):s?r.push(Ee(s,50)):r.push(t.split(" ")[0]);let a=o.filter(g=>g.sender!==fe&&g.sender!=="Unknown").map(g=>g.text).join(" "),u=qr(a),f=Br(a),d=Jr(a),m=[];return u&&m.push(u),d&&d!==l&&m.push(d),f&&m.push(f),m.length>0&&r.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function Bn(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!yt.has(a.status)),i=r.map(a=>a.text).join(" "),s=r.filter(a=>a.sender!==fe&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=Jn(s,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let l=e.engagement||Nt(r,t);return l.messageCount>=6&&o.push("active-thread"),l.theirCount===0&&l.ourCount>0&&o.push("no-response"),l.ourCount===0&&l.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(a=>gt.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function Jn(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of o)i.includes(s)&&n.push(s.replace(/\s+/g,"-"));for(let[s,c]of r)i.includes(s)&&n.push(c);return n}function Vn(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&jt(e.lastMessagePreview)===jt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(i=>gt.has(i.status));return r?r.status===te.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Ot(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Nt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,i=!1,s=!1,c=e.map(l=>l.text).join(" ");for(let l of e)l.sender===fe?n++:l.sender==="Unknown"||l.sender===""?r++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:i,hasSalary:s}}function Hn(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Lr(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function Ur(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=xe(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function jt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Ot(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ee(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function qr(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function Br(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function Jr(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function Vr(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=it(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Hr(e),e.personSummary=Wr(e),e.personAutoTags=Gr(e);let n=Yr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Kr(e)),e}function Hr(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function Wr(e){let t=[],n=e.category,o=e.title,r=e.company,i=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${Ee(o,40)} at ${Ee(r,30)}`):o?t.push(Ee(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${Ee(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function Gr(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=Jn("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function Yr(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Ot(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Kr(e){let t=e.category;if(!t)return null;let n=zr(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function zr(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var Pn,Fn,Gn=ce(async()=>{await wt();await tt();Pn={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};Fn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Kn={};ee(Kn,{DEFAULT_PROFILE_INTERESTS:()=>Yn,computeFit:()=>Xr,detectSectors:()=>Zr});function Zr(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(Qr))r.some(i=>i.test(t))&&n.push(o);return n}function Xr(e,t=Yn){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let i of e){let s=n(t&&t[i]);s>r&&(r=s)}return Math.min(1,r/o)}var Qr,Yn,zn=ce(()=>{Qr={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};Yn={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import ri from"puppeteer";import"dotenv/config";import*as J from"fs";import*as ue from"path";import{fileURLToPath as Wo}from"url";import"dotenv/config";import{createGraphClient as qo,resolveToken as Bo}from"@ilivemylife/graph-sdk";import{config as Jo}from"dotenv";Jo();var on=Bo()||process.env.TOKEN;on||(console.error(`
240
+ `});var qn={};te(qn,{BLOCK_MARKERS:()=>Mn,dedupeAndCap:()=>Un,extractSidePanelProfiles:()=>Ir,normalizeFundUrl:()=>rt,normalizeProfileUrl:()=>$e,scanRelatedBlocks:()=>Ln});function $e(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function rt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Ln(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=a=>(a||"").replace(/\s+/g," ").trim(),r=a=>{let u=String(a||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=a=>o(a).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=a=>{let u=a,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||a.parentElement},c=[],l=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let a of l){let u=o(a.textContent).toLowerCase();if(!u)continue;let f=e.find(([h])=>u.includes(h));if(!f)continue;let d=f[1],m=s(a);if(!m)continue;let g=0,y=new Set;for(let h of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let p=h.href||h.getAttribute("href")||"",v=r(p);if(!v)continue;let x=h.querySelector('span[aria-hidden="true"]'),w=o(x?x.textContent:h.getAttribute("aria-label")||h.textContent),A=i(w);if(!A||y.has(v))continue;y.add(v);let R="",D=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(D&&(R=o(D[1])),!R){let k=h.closest("li")||h.parentElement;k&&(R=Array.from(k.querySelectorAll("p, span")).map(j=>o(j.textContent)).filter(j=>j&&j!==A&&!/^view\b/i.test(j)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(j)&&/[a-z]/i.test(j)&&j.length>2)[0]||"")}c.push({href:p,name:A,headline:R,block:d,rank:g++})}}return c}function Un(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=$e(t.seedUrl||""),r=new Map,i={};for(let s of e||[]){let c=$e(s.href);c&&(o&&c===o||(i[s.block]=i[s.block]||0,!(i[s.block]>=n)&&(r.has(c)||(i[s.block]++,r.set(c,{url:c,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(r.values())}async function Ir(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Ln,Mn)}catch{return[]}return Un(n,t)}var Mn,Et=ee(()=>{Mn=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var Gn={};te(Gn,{getJobDecision:()=>Or,getLastVisit:()=>Jr,getScoutStats:()=>Vr,loadCompanies:()=>jt,loadDiscoveredPeople:()=>He,loadJobDecisions:()=>Tt,loadScoutedJobs:()=>Rt,loadVisitLog:()=>lt,recordCompany:()=>Ur,recordDiscoveredEdge:()=>Mr,recordDiscoveredEdges:()=>Lr,recordVisit:()=>Br,resetCaches:()=>Dt,saveCompany:()=>qr,saveDiscoveredPerson:()=>Pr,saveScoutedJob:()=>jr,setJobDecision:()=>Nr});import"dotenv/config";import*as H from"fs";import*as J from"path";import{fileURLToPath as Dr}from"url";function me(){H.existsSync(be)||H.mkdirSync(be,{recursive:!0})}function pe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";H.writeFileSync(o,n);for(let r=0;r<3;r++)try{H.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ve(e){try{if(H.existsSync(e))return JSON.parse(H.readFileSync(e,"utf-8"))}catch{}return null}function Dt(){Ue=null,qe=null,Be=null,Je=null,we=null}function Rt(){return Ue||(Ue=Ve(Bn)||{},Ue)}function jr(e,t){if(!e)return;me();let n=Rt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,i]of Object.entries(t))i!=null&&(n[e][r]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{pe(Bn,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function Tt(){return qe||(qe=Ve(Vn)||{},qe)}function Nr(e,t,n={}){if(!e||!t)return;me();let o=Tt(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{pe(Vn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Or(e){return Tt()[e]||null}function He(){return Be||(Be=Ve(it)||{},Be)}function Ae(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Hn(e,t){let n=$e(t)||t;if(e[n])return n;let o=Ae(t);if(!o)return n;let r=null;for(let[i,s]of Object.entries(e)){if(Ae(s&&(s.canonicalUrl||s.profileUrl)||i)===o)return i;!r&&s&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=i)}return r||n}function Pr(e,t){if(!e)return;me();let n=He(),o=new Date().toISOString().slice(0,10),r=Hn(n,e),i=Ae(e);if(n[r]){let s=n[r];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&Ae(s.canonicalUrl||s.profileUrl||r)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=o,s.seenCount=(s.seenCount||1)+1}else n[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{pe(it,n)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Fr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function Wn(e,t,n={},o){if(!t)return;let r=Ae(t);t=Hn(e,t);let i=n.seedUrl?{...n,seedUrl:$e(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=Fr(i,o),a=e[t];a||(a=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),n.name&&(a.name=n.name),n.headline&&(!a.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(a.headline))&&(a.headline=n.headline),n.location&&(a.location=a.location||n.location),n.company&&(a.company=n.company),n.companyUrl&&(a.companyUrl=a.companyUrl||n.companyUrl),n.isConnected!=null&&(a.isConnected=n.isConnected),n.connectionsCount!=null&&(a.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(a.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(a.connectGate=n.connectGate),n.note&&!a.note&&(a.note=n.note),n.whyUseful&&!a.whyUseful&&(a.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(a.extra={...a.extra||{},...n.extra}),Array.isArray(a.sources)||(a.sources=[]);let u=a.sources.find(l);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):a.sources.push(c),Array.isArray(a.categories)||(a.categories=[]),Array.isArray(a.sectors)||(a.sectors=[]),Array.isArray(a.aliases)||(a.aliases=[]),Array.isArray(a.graphRefs)||(a.graphRefs=[]),_t(a.categories,n.category),st(a.categories,n.categories),st(a.sectors,n.sectors),st(a.aliases,n.aliases),r&&Ae(a.canonicalUrl||t)!==r&&_t(a.aliases,r),st(a.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(a.affiliations)||(a.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||a.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||a.affiliations.push(f)}a.lastSeen=s,a.seenCount=(a.seenCount||0)+1}function Mr(e,t={}){if(!e)return;me();let n=He();Wn(n,e,t,new Date().toISOString());try{pe(it,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Lr(e){if(!Array.isArray(e)||e.length===0)return;me();let t=He(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(Wn(t,r.url,r,n),o++);if(o)try{pe(it,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Ur(e={}){if(!e||!e.name)return;me();let t=e.key||rt(e.website)||rt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=jt(),o=new Date().toISOString().slice(0,10),r=(l,a)=>{a&&Array.isArray(l)&&!l.includes(a)&&l.push(a)},i=(l,a)=>{if(Array.isArray(a))for(let u of a)r(l,u)},s=n[t];s||(s=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let c=l=>{if(!l||!l.url)return;let a=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));a?l.current!=null&&(a.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(l=>c({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let a=l&&(l.key||l.name);a&&!s.portfolio.some(u=>(u.key||u.name)===a)&&s.portfolio.push(l)}s.lastSeen=o,s.seenCount=(s.seenCount||0)+1;try{pe(It,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function jt(){return Je||(Je=Ve(It)||{},Je)}function qr(e,t){if(!e)return;me();let n=jt(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{pe(It,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function lt(){return we||(we=Ve(Jn)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function Br(e,t={}){if(!e)return;me();let n=lt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{pe(Jn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Jr(e){let t=lt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function Vr(){let e=Rt(),t=He(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let i=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),s={};for(let d of n)for(let m of d.techStack||[])s[m]=(s[m]||0)+1;let c=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),l=lt(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(a)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Rr,Tr,be,Bn,it,Jn,It,Vn,Ue,qe,Be,_t,st,Je,we,Nt=ee(()=>{Et();Rr=Dr(import.meta.url),Tr=J.dirname(J.dirname(Rr)),be=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"market-research"):J.join(Tr,"market-research"),Bn=J.join(be,"scouted-jobs.json"),it=J.join(be,"discovered-people.json"),Jn=J.join(be,"visit-log.json"),It=J.join(be,"companies.json"),Vn=J.join(be,"job-decisions.json");Ue=null;qe=null;Be=null;_t=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},st=(e,t)=>{if(Array.isArray(t))for(let n of t)_t(e,n)};Je=null;we=null});var ro={};te(ro,{computeEngagement:()=>Pt,detectCategory:()=>zn,detectCategoryFromTitle:()=>at,determineAction:()=>no,determineLastMessageBy:()=>Xn,determineSituation:()=>Qn,enrichConversation:()=>Hr,enrichPerson:()=>Qr,enrichPersonContext:()=>oo,extractAutoTags:()=>eo,generateSummary:()=>Zn,normPreview:()=>Ot});function Hr(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!bt.has(l.status)),i=Gr(t,e.profileUrl,n),s=Xn(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=zn(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Qn(r,s,t),r.length>0){let l=r[r.length-1];e.lastMessageTime=l.time}if(r.length>0&&!e.initiatedBy){let l=r[0];l.sender===de?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=Pt(r,t),e.personContext=oo(i),e.summary=Zn(e,t,i),e.autoTags=eo(e,t,i);let c=no(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Wr(e),e}function zn(e,t,n){if(!e||e.length===0)return n?.title?at(n.title):null;let o=e.filter(r=>r.sender!==de&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,i]of Object.entries(Kn))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(o))return r}if(n?.title){let r=at(n.title);if(r)return r}return null}function at(e){if(!e)return null;for(let[t,n]of Object.entries(Kn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Qn(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Yn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(i=>i.sender!==de&&i.sender!=="Unknown");return Yn.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Xn(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let i=r.sender;if(i===de)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Zn(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],i=e.category,s=n?.title,c=n?.company,l=n?.location;i==="recruiter"&&c?r.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):i==="founder"&&c?r.push(`Founder of ${c}`):i&&s?r.push(`${Ft(i)}: ${Ee(s,40)}`):s?r.push(Ee(s,50)):r.push(t.split(" ")[0]);let a=o.filter(g=>g.sender!==de&&g.sender!=="Unknown").map(g=>g.text).join(" "),u=Yr(a),f=Kr(a),d=zr(a),m=[];return u&&m.push(u),d&&d!==l&&m.push(d),f&&m.push(f),m.length>0&&r.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function eo(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!bt.has(a.status)),i=r.map(a=>a.text).join(" "),s=r.filter(a=>a.sender!==de&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=to(s,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let l=e.engagement||Pt(r,t);return l.messageCount>=6&&o.push("active-thread"),l.theirCount===0&&l.ourCount>0&&o.push("no-response"),l.ourCount===0&&l.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(a=>wt.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function to(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of o)i.includes(s)&&n.push(s.replace(/\s+/g,"-"));for(let[s,c]of r)i.includes(s)&&n.push(c);return n}function no(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Ot(e.lastMessagePreview)===Ot(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(i=>wt.has(i.status));return r?r.status===oe.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Ft(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Pt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,i=!1,s=!1,c=e.map(l=>l.text).join(" ");for(let l of e)l.sender===de?n++:l.sender==="Unknown"||l.sender===""?r++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:i,hasSalary:s}}function oo(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Wr(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function Gr(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=xe(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Ot(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Ft(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ee(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Yr(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function Kr(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function zr(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function Qr(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=at(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Xr(e),e.personSummary=Zr(e),e.personAutoTags=es(e);let n=ts(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=ns(e)),e}function Xr(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function Zr(e){let t=[],n=e.category,o=e.title,r=e.company,i=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${Ee(o,40)} at ${Ee(r,30)}`):o?t.push(Ee(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${Ee(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function es(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=to("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function ts(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Ft(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function ns(e){let t=e.category;if(!t)return null;let n=os(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function os(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var Kn,Yn,so=ee(async()=>{await St();await ot();Kn={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};Yn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var lo={};te(lo,{DEFAULT_PROFILE_INTERESTS:()=>io,computeFit:()=>is,detectSectors:()=>ss});function ss(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(rs))r.some(i=>i.test(t))&&n.push(o);return n}function is(e,t=io){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let i of e){let s=n(t&&t[i]);s>r&&(r=s)}return Math.min(1,r/o)}var rs,io,ao=ee(()=>{rs={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};io={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import ai from"puppeteer";import"dotenv/config";import*as V from"fs";import*as fe from"path";import{fileURLToPath as Ko}from"url";import"dotenv/config";import{createGraphClient as Vo,resolveToken as Ho}from"@ilivemylife/graph-sdk";import{config as Wo}from"dotenv";Wo();var sn=Ho()||process.env.TOKEN;sn||(console.error(`
239
241
  [FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
240
242
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
241
243
  `),console.error(` Or add ILML_TOKEN=... to .env
242
- `),process.exit(1));var rn=qo({token:on});function Vo(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Ho({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Vo(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${l} \u2014 ${s}${c}`}async function sn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(o)||o.length===0)return;let l=`**${Ho({scriptName:e,mode:t,status:n,error:r,duration:i})}**
244
+ `),process.exit(1));var ln=Vo({token:sn});function Go(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Yo({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Go(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${l} \u2014 ${s}${c}`}async function an({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(o)||o.length===0)return;let l=`**${Yo({scriptName:e,mode:t,status:n,error:r,duration:i})}**
243
245
 
244
246
  ${o.join(`
245
- `)}`;try{await rn.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Go=Wo(import.meta.url),Yo=ue.dirname(ue.dirname(Go)),ft=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(Yo,"collected-profiles"),dt=ue.join(ft,"run-log.json");function Ko(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let r=0;r<3;r++)try{J.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function ln(){try{if(!J.existsSync(dt))return{runs:[]};let e=JSON.parse(J.readFileSync(dt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function an(e){J.existsSync(ft)||J.mkdirSync(ft,{recursive:!0});try{Ko(dt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function cn(e,t="default"){let n=ln();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),an(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function mt(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=ln(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}an(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";sn({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Qe();Qe();await tt();async function Zn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Qn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function es(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=n;try{await ht(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await S(1500),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await Zn(e,t));let u=0;for(let w=0;w<2;w++){let A=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(k=>window.scrollTo(0,k),A*D/6),await S(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await S(800);let f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),A=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=C=>{let $=(C||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},D={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},k=document.querySelector("main");if(!k)return D;let E=[...Array.from(k.querySelectorAll("h1")),...Array.from(k.querySelectorAll("h2"))],j=Array.from(k.querySelectorAll("h2")),X=E.find(C=>{let $=C.textContent&&C.textContent.trim(),_=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!w.has(_)&&!A.has(_)}),K=X?X.textContent.trim():null,L=X?X.parentElement:null;for(;L&&L!==k&&!Array.from(L.children).filter($=>$.tagName==="P").some($=>{let _=$.textContent&&$.textContent.trim();return _&&_.length>5&&!R(_)});)L=L.parentElement;let le=null,De=null,Re=null,Te=null;if(L&&L!==k){let C=Array.from(L.children).filter(_=>_.tagName==="P").filter(_=>{let ae=_.textContent&&_.textContent.trim();return ae&&ae.length>5&&!R(ae)});if(C[0]&&(le=C[0].textContent.trim()),C[1]){let _=C[1].textContent.trim().split(/\s*[·•]\s*/);De=_[0]||null,_.length>1&&(Re=_.slice(1).join(" \xB7 "))}let $=Array.from(L.children).filter(_=>_.tagName==="DIV");for(let _=$.length-1;_>=0;_--){let ae=$[_].textContent&&$[_].textContent.trim();if(ae&&!(K&&ae.startsWith(K))&&(Te=ae.split(/[·•]/)[0].trim(),Te))break}}let Ke=null;if(L){let C=L.querySelectorAll("p, span, div");for(let $ of C){let _=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(_==="1st"||_==="2nd"||_==="3rd"){Ke=_;break}}}let T=!!k.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),F=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=F&&F.src||null,N=k.textContent||"",z=null,Kt=N.match(/(\d+\+?)\s+connections\b/i);Kt&&(z=Kt[1]+" connections");let ze=null,zt=N.match(/(\d+)\s+mutual connection/i),Qt=N.match(/and\s+(\d+)\s+other mutual/i),Oo=N.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);zt?ze=parseInt(zt[1],10):Qt?ze=2+parseInt(Qt[1],10):Oo&&(ze=2);let Zt=null,Xt=null,en=j.find(C=>C.textContent&&C.textContent.trim()==="About");if(en){let C=en.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let $=(C.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let _=$.match(/Top skills\s*(.+?)$/i);if(_){let ut=_[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Lo=>Lo.trim()).filter(Boolean);ut.length>0&&ut.length<10&&(Xt=ut)}$=$.split(/\n?…\s*more/i)[0].trim(),$=$.split(/\n?\.\.\.\s*more/i)[0].trim(),$=$.split(/\bTop skills\b/i)[0].trim(),$=$.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Zt=$||null}}let tn=null,nn=j.find(C=>C.textContent&&C.textContent.trim()==="Activity");if(nn){let C=nn.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let $=(C.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(tn=parseInt($[1].replace(/,/g,""),10))}}let Fo=[...new Set(j.map(C=>(C.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(C=>C&&C.length>1&&C.length<60&&C!==K).filter(C=>w.has(C)))],je=document.body.textContent||"",Po=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),Mo=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:K,title:le,location:Te,currentCompany:De,currentSchool:Re,connectionDegree:Ke,hasVerifiedBadge:T,photoUrl:M,connectionsLevel:z,mutualConnectionsCount:ze,followers:tn,openToWork:Po,hiring:Mo,about:Zt,topSkills:Xt,availableSections:Fo}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,g=null,y=null,h=null,p=null,v=null;if(o||r||i||s||c||l){let w=await Promise.resolve().then(()=>($n(),xn));o&&(m=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(g=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),i&&(y=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),s&&(h=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(p=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${p.length} entries`)),l&&(v=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...g!==null&&{featured:g},...y!==null&&{education:y},...h!==null&&{skillsFull:h},...p!==null&&{recommendations:p},...v!==null&&{certifications:v}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function _e(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(r),s=f=>Array.from(document.querySelectorAll(f)).filter(i),c=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,a=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!a};return c.length>0?{status:"pending",debug:u}:l&&!a?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await S(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function Ft(e){let t=null,n=await e.evaluate(()=>{let a=document.querySelector("h1")?.textContent?.trim();if(a&&!a.includes("notification"))return a;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(a=u.textContent?.trim(),a&&!a.includes("notification")))return a;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let a=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});a.count>0&&console.log(` S0: ${a.count} custom-invite links: ${JSON.stringify(a.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of d){let h=y.getBoundingClientRect();if(h.width===0||h.height===0||y.closest(g))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(m))return y}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let a=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${a}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(h=>{let p=h.getAttribute("aria-label")||"";return(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of m){if(h.closest(g))continue;let p=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(p)&&(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&y.test(p))return h}return null},a);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let a=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),g=f.className.includes("sticky-header")||f.className.includes("sticky"),y=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(f.getAttribute("aria-label")||"").toLowerCase(),p=h.includes("invite"),v=d?h.includes(d):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:p,matchesName:v,ariaLabel:h}},a,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=a;break}}for(let a of o)a!==i&&await a.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,g=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:g,top:d.top}},a);if(u.isVisible&&!u.isInStickyHeader){s=a,console.log(" Found More button by ID pattern (main)");break}}for(let a of c)a!==s&&await a.dispose().catch(()=>{});if(!s&&c.length>0&&(s=c[c.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let a=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let g=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",h=m.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let g of d.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==f)return g;d=d.parentElement}return null});s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await S(500),await e.evaluate(d=>d.click(),s),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let g of m){let y=g.querySelector('a[href*="custom-invite"]');if(y)return y;for(let h of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let g of d)for(let y of g.querySelectorAll('[role="menuitem"], a, div')){let h=y.innerText?.trim();h&&h.length<40&&m.push(h)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(a){console.log(" More dropdown click failed:",a.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(a=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(a||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let g=d.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ts(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",s=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await S(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await S(3e3)):(await e.evaluate(u=>u.click(),t),await S(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function ns(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await Ft(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Ie(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ie(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(s=>{let c=l=>!!(l&&l.querySelector(s));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let c=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,n);return s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(c=>c.click())}catch{}if(await S(3e3),await r())return!1;if(await o())return!0;if(s===0){let c=await i();if(!c)return await o();t=c,await S(600)}}return await o()}async function os(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=Ct();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let s=await rs(e,t,n);return s.connectionSent&&!i&&vn(t,o),s}async function rs(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:c=[]}=n,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
- --- Connecting: ${a} ---`),c.length>0){let p=re()[t]?.location;if(Qn(p,c))return console.log(` \u26A0 Excluded location (stored): ${p}`),l.reason="excluded_location",l.profileInfo={location:p},l}try{await ht(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(p){if(p.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;throw p}if(await S(2e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await Zn(e,t),await S(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:p,normalizeProfileUrl:v}=await Promise.resolve().then(()=>($t(),In)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Tt(),On)),{detectCategoryFromTitle:w}=await Gn().then(()=>Wn),{detectSectors:A}=await Promise.resolve().then(()=>(zn(),Kn)),R=v(t)||t,D=await p(e,{seedUrl:R}),k=D.map(E=>{let j=E.headline?w(E.headline):null;return{url:E.url,seedUrl:R,block:E.block,rank:E.rank,name:E.name,headline:E.headline,categories:j?[j]:[],sectors:A(E.headline||"")}});x(k),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(p){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${p.message}`)}l.profileInfo=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),v=T=>{let F=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return x;let A=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],R=Array.from(w.querySelectorAll("h2")),D=A.find(T=>{let F=T.textContent&&T.textContent.trim();return F&&F.length>1&&F.length<100&&!p.has(F)&&F!=="0 notifications"}),k=D?D.textContent.trim():null,E=D?D.parentElement:null;for(;E&&E!==w&&!Array.from(E.children).filter(M=>M.tagName==="P").some(M=>{let N=M.textContent&&M.textContent.trim();return N&&N.length>5&&!v(N)});)E=E.parentElement;let j=null,X=null,K=null;if(E&&E!==w){let T=Array.from(E.children),F=T.filter(N=>N.tagName==="P").filter(N=>{let z=N.textContent&&N.textContent.trim();return z&&z.length>5&&!v(z)});F[0]&&(j=F[0].textContent.trim()),F[1]&&(X=F[1].textContent.trim());let M=T.filter(N=>N.tagName==="DIV");for(let N=M.length-1;N>=0;N--){let z=M[N].textContent&&M[N].textContent.trim();if(z&&!(k&&z.startsWith(k))&&(K=z.split(/[·•]/)[0].trim(),K))break}}let L=null;if(E){let T=E.querySelectorAll("p, span, div");for(let F of T){let M=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){L=M;break}}}let le=null,De=R.find(T=>T.textContent&&T.textContent.trim()==="About");if(De){let T=De.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(le=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,le&&(le=le.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Re=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Te=Re&&Re.src||null,Ke=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:k,title:j,location:K,about:le,company:X,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:Te,hasVerifiedBadge:Ke}});try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(l.resolvedUrl=p.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let p=l.profileInfo?.location,v=re()[t]?.location,x=p||v;if(Qn(x,c))return console.log(` \u26A0 Excluded location (${p?"live":"stored"}): ${x}`),l.reason="excluded_location",l;!p&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await _e(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await ge(e);let d=await Ft(e);if(d||await ge(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),d=await Ft(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let p=await _e(e,{detail:!0});return s&&(p.status==="connected"||p.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let m=await ts(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let p=await _e(e);if(p==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${p} \u2014 trying More dropdown...`),await ge(e),await S(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await S(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await S(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),x),await S(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),l.reason="premium_required",l;if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),l.reason="premium_required",l}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of p){let x=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let w=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let A=x.querySelector('button[aria-label="Send without a note"]');if(A&&(A.disabled||A.getAttribute("aria-disabled")==="true"||(A.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let p=await e.$('button[aria-label="Dismiss"]');if(p)try{await p.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await S(500),l.reason="email_required",l}let y=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!y&&!h){let p=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let x=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!w}});if(p.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=v?.asElement?.()||null,y||await v.dispose().catch(()=>{})}if(p.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));h=v?.asElement?.()||null,h||await v.dispose().catch(()=>{})}}if(r)if(y&&o){if(console.log(" Adding personalized note..."),await y.click(),await S(1500),await e.$("div.modal-upsell")){let x=await ns(e);return l.success=x,l.connectionSent=x,l.reason=x?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",x);await v.type(w,{delay:20}),await S(500);let A=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(A)return await Ie(e,A)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=w,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(h)return console.log(" Sending without note..."),await Ie(e,h)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(y&&!o){console.log(" No message provided, sending without note...");let p=await e.$('button[aria-label="Send without a note"]');if(p)return await Ie(e,p)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let p=h;if(p)return await Ie(e,p)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3)),await ge(e),await S(500);let v=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let w of v){let A=await e.evaluate(R=>{let D=R.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},w);if(A.visible&&!A.inSticky){x=w;break}}!x&&v.length>0&&(x=v[v.length-1]);for(let w of v)w!==x&&await w.dispose().catch(()=>{});if(x)try{await e.evaluate(A=>A.scrollIntoView({behavior:"smooth",block:"center"}),x),await S(500),await x.click().catch(()=>e.evaluate(A=>A.click(),x)),await S(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(w){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(k=>k.click(),w),await S(3e3);let A=e.url();if(A.includes("/premium/")||A.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await _e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let D=await e.$('button[aria-label="Send without a note"]');if(D)return console.log(" Modal appeared via More dropdown, sending without note..."),await Ie(e,D)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(a){console.error(` \u2717 Error: ${a.message}`),l.reason="error",l.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{l.fatal=!0}return l}}async function Xn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:l=null,excludeLocations:a=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!s){let m=xt();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let g=t[m];try{if(e.isClosed()){console.log(`
247
+ `)}`;try{await ln.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var zo=Ko(import.meta.url),Qo=fe.dirname(fe.dirname(zo)),mt=process.env.DATA_DIR?fe.resolve(process.env.DATA_DIR,"collected-profiles"):fe.join(Qo,"collected-profiles"),pt=fe.join(mt,"run-log.json");function Xo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";V.writeFileSync(o,n);for(let r=0;r<3;r++)try{V.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function cn(){try{if(!V.existsSync(pt))return{runs:[]};let e=JSON.parse(V.readFileSync(pt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function un(e){V.existsSync(mt)||V.mkdirSync(mt,{recursive:!0});try{Xo(pt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function fn(e,t="default"){let n=cn();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),un(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ht(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=cn(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}un(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";an({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Ze();Ze();await ot();async function uo(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function co(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function ls(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=n;try{await yt(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await S(1500),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await uo(e,t));let u=0;for(let w=0;w<2;w++){let A=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(k=>window.scrollTo(0,k),A*D/6),await S(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await S(800);let f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),A=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),R=C=>{let $=(C||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},D={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},k=document.querySelector("main");if(!k)return D;let E=[...Array.from(k.querySelectorAll("h1")),...Array.from(k.querySelectorAll("h2"))],j=Array.from(k.querySelectorAll("h2")),Z=E.find(C=>{let $=C.textContent&&C.textContent.trim(),_=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!w.has(_)&&!A.has(_)}),z=Z?Z.textContent.trim():null,L=Z?Z.parentElement:null;for(;L&&L!==k&&!Array.from(L.children).filter($=>$.tagName==="P").some($=>{let _=$.textContent&&$.textContent.trim();return _&&_.length>5&&!R(_)});)L=L.parentElement;let ce=null,De=null,Re=null,Te=null;if(L&&L!==k){let C=Array.from(L.children).filter(_=>_.tagName==="P").filter(_=>{let ue=_.textContent&&_.textContent.trim();return ue&&ue.length>5&&!R(ue)});if(C[0]&&(ce=C[0].textContent.trim()),C[1]){let _=C[1].textContent.trim().split(/\s*[·•]\s*/);De=_[0]||null,_.length>1&&(Re=_.slice(1).join(" \xB7 "))}let $=Array.from(L.children).filter(_=>_.tagName==="DIV");for(let _=$.length-1;_>=0;_--){let ue=$[_].textContent&&$[_].textContent.trim();if(ue&&!(z&&ue.startsWith(z))&&(Te=ue.split(/[·•]/)[0].trim(),Te))break}}let Ke=null;if(L){let C=L.querySelectorAll("p, span, div");for(let $ of C){let _=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(_==="1st"||_==="2nd"||_==="3rd"){Ke=_;break}}}let T=!!k.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),P=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=P&&P.src||null,N=k.textContent||"",Q=null,Qt=N.match(/(\d+\+?)\s+connections\b/i);Qt&&(Q=Qt[1]+" connections");let ze=null,Xt=N.match(/(\d+)\s+mutual connection/i),Zt=N.match(/and\s+(\d+)\s+other mutual/i),Mo=N.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Xt?ze=parseInt(Xt[1],10):Zt?ze=2+parseInt(Zt[1],10):Mo&&(ze=2);let en=null,tn=null,nn=j.find(C=>C.textContent&&C.textContent.trim()==="About");if(nn){let C=nn.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let $=(C.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let _=$.match(/Top skills\s*(.+?)$/i);if(_){let dt=_[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Bo=>Bo.trim()).filter(Boolean);dt.length>0&&dt.length<10&&(tn=dt)}$=$.split(/\n?…\s*more/i)[0].trim(),$=$.split(/\n?\.\.\.\s*more/i)[0].trim(),$=$.split(/\bTop skills\b/i)[0].trim(),$=$.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),en=$||null}}let on=null,rn=j.find(C=>C.textContent&&C.textContent.trim()==="Activity");if(rn){let C=rn.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let $=(C.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(on=parseInt($[1].replace(/,/g,""),10))}}let Lo=[...new Set(j.map(C=>(C.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(C=>C&&C.length>1&&C.length<60&&C!==z).filter(C=>w.has(C)))],je=document.body.textContent||"",Uo=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),qo=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:z,title:ce,location:Te,currentCompany:De,currentSchool:Re,connectionDegree:Ke,hasVerifiedBadge:T,photoUrl:M,connectionsLevel:Q,mutualConnectionsCount:ze,followers:on,openToWork:Uo,hiring:qo,about:en,topSkills:tn,availableSections:Lo}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,g=null,y=null,h=null,p=null,v=null;if(o||r||i||s||c||l){let w=await Promise.resolve().then(()=>(Fn(),Pn));o&&(m=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(g=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),i&&(y=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),s&&(h=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),c&&(p=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${p.length} entries`)),l&&(v=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...g!==null&&{featured:g},...y!==null&&{education:y},...h!==null&&{skillsFull:h},...p!==null&&{recommendations:p},...v!==null&&{certifications:v}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function _e(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(r),s=f=>Array.from(document.querySelectorAll(f)).filter(i),c=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,a=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!a};return c.length>0?{status:"pending",debug:u}:l&&!a?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await S(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function Mt(e){let t=null,n=await e.evaluate(()=>{let a=document.querySelector("h1")?.textContent?.trim();if(a&&!a.includes("notification"))return a;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(a=u.textContent?.trim(),a&&!a.includes("notification")))return a;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let a=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});a.count>0&&console.log(` S0: ${a.count} custom-invite links: ${JSON.stringify(a.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of d){let h=y.getBoundingClientRect();if(h.width===0||h.height===0||y.closest(g))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(m))return y}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let a=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${a}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(h=>{let p=h.getAttribute("aria-label")||"";return(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p)}).map(h=>h.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of m){if(h.closest(g))continue;let p=h.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(p)&&(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&y.test(p))return h}return null},a);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let a=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),g=f.className.includes("sticky-header")||f.className.includes("sticky"),y=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(f.getAttribute("aria-label")||"").toLowerCase(),p=h.includes("invite"),v=d?h.includes(d):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:p,matchesName:v,ariaLabel:h}},a,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=a;break}}for(let a of o)a!==i&&await a.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,g=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:g,top:d.top}},a);if(u.isVisible&&!u.isInStickyHeader){s=a,console.log(" Found More button by ID pattern (main)");break}}for(let a of c)a!==s&&await a.dispose().catch(()=>{});if(!s&&c.length>0&&(s=c[c.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let a=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let g=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",h=m.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let g of d.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==f)return g;d=d.parentElement}return null});s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await S(500),await e.evaluate(d=>d.click(),s),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let g of m){let y=g.querySelector('a[href*="custom-invite"]');if(y)return y;for(let h of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let g of d)for(let y of g.querySelectorAll('[role="menuitem"], a, div')){let h=y.innerText?.trim();h&&h.length<40&&m.push(h)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(a){console.log(" More dropdown click failed:",a.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(a=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(a||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let g=d.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function as(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",s=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await S(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await S(3e3)):(await e.evaluate(u=>u.click(),t),await S(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function cs(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await Mt(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Ie(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ie(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(s=>{let c=l=>!!(l&&l.querySelector(s));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let c=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,n);return s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(c=>c.click())}catch{}if(await S(3e3),await r())return!1;if(await o())return!0;if(s===0){let c=await i();if(!c)return await o();t=c,await S(600)}}return await o()}async function us(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=$t();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let s=await fs(e,t,n);return s.connectionSent&&!i&&Nn(t,o),s}async function fs(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:c=[]}=n,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
248
+ --- Connecting: ${a} ---`),c.length>0){let p=ie()[t]?.location;if(co(p,c))return console.log(` \u26A0 Excluded location (stored): ${p}`),l.reason="excluded_location",l.profileInfo={location:p},l}try{await yt(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(p){if(p.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;throw p}if(await S(2e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await uo(e,t),await S(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:p,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(Et(),qn)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Nt(),Gn)),{detectCategoryFromTitle:w}=await so().then(()=>ro),{detectSectors:A}=await Promise.resolve().then(()=>(ao(),lo)),R=v(t)||t,D=await p(e,{seedUrl:R}),k=D.map(E=>{let j=E.headline?w(E.headline):null;return{url:E.url,seedUrl:R,block:E.block,rank:E.rank,name:E.name,headline:E.headline,categories:j?[j]:[],sectors:A(E.headline||"")}});x(k),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(p){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${p.message}`)}l.profileInfo=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),v=T=>{let P=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return x;let A=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],R=Array.from(w.querySelectorAll("h2")),D=A.find(T=>{let P=T.textContent&&T.textContent.trim();return P&&P.length>1&&P.length<100&&!p.has(P)&&P!=="0 notifications"}),k=D?D.textContent.trim():null,E=D?D.parentElement:null;for(;E&&E!==w&&!Array.from(E.children).filter(M=>M.tagName==="P").some(M=>{let N=M.textContent&&M.textContent.trim();return N&&N.length>5&&!v(N)});)E=E.parentElement;let j=null,Z=null,z=null;if(E&&E!==w){let T=Array.from(E.children),P=T.filter(N=>N.tagName==="P").filter(N=>{let Q=N.textContent&&N.textContent.trim();return Q&&Q.length>5&&!v(Q)});P[0]&&(j=P[0].textContent.trim()),P[1]&&(Z=P[1].textContent.trim());let M=T.filter(N=>N.tagName==="DIV");for(let N=M.length-1;N>=0;N--){let Q=M[N].textContent&&M[N].textContent.trim();if(Q&&!(k&&Q.startsWith(k))&&(z=Q.split(/[·•]/)[0].trim(),z))break}}let L=null;if(E){let T=E.querySelectorAll("p, span, div");for(let P of T){let M=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){L=M;break}}}let ce=null,De=R.find(T=>T.textContent&&T.textContent.trim()==="About");if(De){let T=De.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(ce=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,ce&&(ce=ce.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Re=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Te=Re&&Re.src||null,Ke=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:k,title:j,location:z,about:ce,company:Z,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:Te,hasVerifiedBadge:Ke}});try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(l.resolvedUrl=p.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let p=l.profileInfo?.location,v=ie()[t]?.location,x=p||v;if(co(x,c))return console.log(` \u26A0 Excluded location (${p?"live":"stored"}): ${x}`),l.reason="excluded_location",l;!p&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await _e(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await ge(e);let d=await Mt(e);if(d||await ge(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),d=await Mt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let p=await _e(e,{detail:!0});return s&&(p.status==="connected"||p.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let m=await as(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let p=await _e(e);if(p==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${p} \u2014 trying More dropdown...`),await ge(e),await S(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await S(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await S(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),x),await S(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),l.reason="premium_required",l;if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),l.reason="premium_required",l}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of p){let x=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let w=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let A=x.querySelector('button[aria-label="Send without a note"]');if(A&&(A.disabled||A.getAttribute("aria-disabled")==="true"||(A.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let p=await e.$('button[aria-label="Dismiss"]');if(p)try{await p.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await S(500),l.reason="email_required",l}let y=await e.$('button[aria-label="Add a note"]'),h=await e.$('button[aria-label="Send without a note"]');if(!y&&!h){let p=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let x=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!w}});if(p.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=v?.asElement?.()||null,y||await v.dispose().catch(()=>{})}if(p.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));h=v?.asElement?.()||null,h||await v.dispose().catch(()=>{})}}if(r)if(y&&o){if(console.log(" Adding personalized note..."),await y.click(),await S(1500),await e.$("div.modal-upsell")){let x=await cs(e);return l.success=x,l.connectionSent=x,l.reason=x?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",x);await v.type(w,{delay:20}),await S(500);let A=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(A)return await Ie(e,A)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=w,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(h)return console.log(" Sending without note..."),await Ie(e,h)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(y&&!o){console.log(" No message provided, sending without note...");let p=await e.$('button[aria-label="Send without a note"]');if(p)return await Ie(e,p)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let p=h;if(p)return await Ie(e,p)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3)),await ge(e),await S(500);let v=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let w of v){let A=await e.evaluate(R=>{let D=R.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},w);if(A.visible&&!A.inSticky){x=w;break}}!x&&v.length>0&&(x=v[v.length-1]);for(let w of v)w!==x&&await w.dispose().catch(()=>{});if(x)try{await e.evaluate(A=>A.scrollIntoView({behavior:"smooth",block:"center"}),x),await S(500),await x.click().catch(()=>e.evaluate(A=>A.click(),x)),await S(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(w){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(k=>k.click(),w),await S(3e3);let A=e.url();if(A.includes("/premium/")||A.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await _e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let D=await e.$('button[aria-label="Send without a note"]');if(D)return console.log(" Modal appeared via More dropdown, sending without note..."),await Ie(e,D)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(a){console.error(` \u2717 Error: ${a.message}`),l.reason="error",l.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{l.fatal=!0}return l}}async function fo(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:l=null,excludeLocations:a=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
249
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!s){let m=At();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let g=t[m];try{if(e.isClosed()){console.log(`
248
250
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
249
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=wn(g.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(g,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl}`);let h=null;if(s){let p=await es(e,g.profileUrl);p?(Ze(g.profileUrl,{...p,source:u}),f.viewed++,h={success:!0,reason:"viewed",connectionSent:!1,profileInfo:p,resolvedUrl:p.resolvedUrl}):(f.errors++,h={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let p=Ct();if(!p.allowed){console.log(` \u26A0 Global quota exhausted: ${p.reason}`);break}if(h=await os(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:u,skipQuotaGate:!0}),h.success)f.connectionsSent++;else switch(h.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(h?.fatal){console.log(`
251
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=Dn(g.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(g,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl}`);let h=null;if(s){let p=await ls(e,g.profileUrl);p?(et(g.profileUrl,{...p,source:u}),f.viewed++,h={success:!0,reason:"viewed",connectionSent:!1,profileInfo:p,resolvedUrl:p.resolvedUrl}):(f.errors++,h={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let p=$t();if(!p.allowed){console.log(` \u26A0 Global quota exhausted: ${p.reason}`);break}if(h=await us(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:u,skipQuotaGate:!0}),h.success)f.connectionsSent++;else switch(h.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(h?.fatal){console.log(`
250
252
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(h?.reason==="error"){if(d++,d>=3){console.log(`
251
- \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(h&&h.reason&&(bn(g.profileUrl,h.reason,{method:h.method,messageSent:h.messageSent,profileInfo:h.profileInfo}),h.resolvedUrl&&Sn(g.profileUrl,h.resolvedUrl),yn(g.profileUrl,{source:u||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:h.reason})),l&&await l(g,f,h),m<t.length-1){let p=c+Math.random()*2e3;await S(p)}}if(console.log(`
252
- === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let m=xt();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}import"dotenv/config";import*as U from"fs";import*as se from"path";import{fileURLToPath as ss}from"url";var is=ss(import.meta.url),ls=se.dirname(se.dirname(is)),We=process.env.DATA_DIR?se.resolve(process.env.DATA_DIR,"collected-profiles"):se.join(ls,"collected-profiles");function Pt(){U.existsSync(We)||U.mkdirSync(We,{recursive:!0})}function as(){return new Date().toISOString().split("T")[0]}function eo(e,t=null){let n=t||as();return se.join(We,`${e}-${n}.json`)}function to(e,t=null){Pt();let n=eo(e,t);try{if(U.existsSync(n)){let o=U.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function no(e,t=null){return to(e,t).filter(o=>!o.processed)}function oo(e,t,n,o=null){Pt();let r=eo(e,o);try{if(!U.existsSync(r))return;let i=JSON.parse(U.readFileSync(r,"utf-8")),s=i.profiles.find(c=>c.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof n=="string")s.status=n;else if(typeof n=="object"){if(s.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(s.name=c.name),c.title&&(s.title=c.title),c.location&&(s.location=c.location),c.company&&(s.company=c.company),c.connectionDegree&&(s.connectionDegree=c.connectionDegree),c.connectionsCount&&(s.connectionsCount=c.connectionsCount),c.mutualConnections&&(s.mutualConnections=c.mutualConnections),c.photoUrl&&(s.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=c.hasVerifiedBadge)}s.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),U.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function ro(e){let t=to(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function so(){Pt();try{return U.readdirSync(We).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(U.readFileSync(se.join(We,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as b from"fs";import*as Ht from"os";import*as I from"path";import{fileURLToPath as Ts}from"url";var Ut={};ee(Ut,{NAME:()=>us,VERSION:()=>cs,up:()=>ms});import*as H from"fs";import*as lt from"path";var cs=1,us="normalize-jobs-and-questions",fs=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ds=50;function Mt(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Lt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function ms(e,t){let n=lt.join(e,"jobs.json"),o=lt.join(t,"scouted-jobs.json"),r=lt.join(e,"application-questions.json"),i=Mt(n)||{},s=Mt(o)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let m of fs)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),c++}c>0?(Lt(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Mt(r);if(a&&Array.isArray(a.applications)){let u={},f=0;for(let d of a.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let g=(d.questions||[]).map(y=>{let h={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=ds?h.options=y.options:(h.optionsOmitted=!0,f++)),y.page&&(h.page=y.page),y.wasPreFilled&&(h.wasPreFilled=!0),y.wasRetry&&(h.wasRetry=!0),h});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||g.length,questions:g})}Lt(r,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];Lt(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var qt={};ee(qt,{NAME:()=>hs,VERSION:()=>ps,up:()=>ws});import*as W from"fs";import*as io from"path";var ps=2,hs="reset-unread-flags";function gs(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function ys(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function ws(e){let t=io.join(e,"conversations.json"),n=gs(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}ys(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Bt={};ee(Bt,{NAME:()=>Ss,VERSION:()=>bs,up:()=>$s});import*as G from"fs";import*as lo from"path";var bs=3,Ss="recompute-last-message-by",ks=new Set(["draft","confirmed","rejected","needs_review"]);function vs(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function Cs(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{G.writeFileSync(o,n)}catch(r){try{G.unlinkSync(o)}catch{}throw r}try{G.renameSync(o,e)}catch(r){try{G.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function xs(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!ks.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function $s(e){let t=lo.join(e,"conversations.json"),n=vs(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=xs(a,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Cs(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Jt={};ee(Jt,{NAME:()=>Es,VERSION:()=>As,up:()=>Rs});import*as Y from"fs";import*as ao from"path";var As=4,Es="split-connection-timestamps",_s=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Is(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ds(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Rs(e){let t=ao.join(e,"people.json"),n=Is(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,_s.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ds(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await tt();Tt();var js=Ts(import.meta.url),Ns=I.dirname(js),Os=I.dirname(I.dirname(Ns));function Fs(e){return e&&(e==="~"?Ht.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(Ht.homedir(),e.slice(2)):e)}var Q=process.env.DATA_DIR?I.resolve(Fs(process.env.DATA_DIR)):Os,ke=I.join(Q,"collected-profiles"),ve=I.join(Q,"market-research"),q=I.join(Q,".schema-version"),co=[I.join(ke,".schema-version"),I.join(ve,".schema-version")],pe=4,ie=[{version:1,module:Ut},{version:2,module:qt},{version:3,module:Bt},{version:4,module:Jt}];(function(){ie.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ie){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ie.length?ie[ie.length-1].version:0;if(n!==pe)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${pe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ie.length;o++){let r=o+1;if(ie[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ie[o].version}`)}})();function po(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
+ \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(h&&h.reason&&(Rn(g.profileUrl,h.reason,{method:h.method,messageSent:h.messageSent,profileInfo:h.profileInfo}),h.resolvedUrl&&Tn(g.profileUrl,h.resolvedUrl),In(g.profileUrl,{source:u||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:h.reason})),l&&await l(g,f,h),m<t.length-1){let p=c+Math.random()*2e3;await S(p)}}if(console.log(`
254
+ === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let m=At();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}import"dotenv/config";import*as U from"fs";import*as le from"path";import{fileURLToPath as ds}from"url";var ms=ds(import.meta.url),ps=le.dirname(le.dirname(ms)),We=process.env.DATA_DIR?le.resolve(process.env.DATA_DIR,"collected-profiles"):le.join(ps,"collected-profiles");function Lt(){U.existsSync(We)||U.mkdirSync(We,{recursive:!0})}function hs(){return new Date().toISOString().split("T")[0]}function mo(e,t=null){let n=t||hs();return le.join(We,`${e}-${n}.json`)}function po(e,t=null){Lt();let n=mo(e,t);try{if(U.existsSync(n)){let o=U.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function ho(e,t=null){return po(e,t).filter(o=>!o.processed)}function go(e,t,n,o=null){Lt();let r=mo(e,o);try{if(!U.existsSync(r))return;let i=JSON.parse(U.readFileSync(r,"utf-8")),s=i.profiles.find(c=>c.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof n=="string")s.status=n;else if(typeof n=="object"){if(s.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(s.name=c.name),c.title&&(s.title=c.title),c.location&&(s.location=c.location),c.company&&(s.company=c.company),c.connectionDegree&&(s.connectionDegree=c.connectionDegree),c.connectionsCount&&(s.connectionsCount=c.connectionsCount),c.mutualConnections&&(s.mutualConnections=c.mutualConnections),c.photoUrl&&(s.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=c.hasVerifiedBadge)}s.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),U.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function yo(e){let t=po(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function wo(){Lt();try{return U.readdirSync(We).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(U.readFileSync(le.join(We,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as b from"fs";import*as Gt from"os";import*as I from"path";import{fileURLToPath as Ls}from"url";var Bt={};te(Bt,{NAME:()=>ys,VERSION:()=>gs,up:()=>Ss});import*as W from"fs";import*as ct from"path";var gs=1,ys="normalize-jobs-and-questions",ws=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],bs=50;function Ut(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function qt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ss(e,t){let n=ct.join(e,"jobs.json"),o=ct.join(t,"scouted-jobs.json"),r=ct.join(e,"application-questions.json"),i=Ut(n)||{},s=Ut(o)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let m of ws)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),c++}c>0?(qt(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Ut(r);if(a&&Array.isArray(a.applications)){let u={},f=0;for(let d of a.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let g=(d.questions||[]).map(y=>{let h={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=bs?h.options=y.options:(h.optionsOmitted=!0,f++)),y.page&&(h.page=y.page),y.wasPreFilled&&(h.wasPreFilled=!0),y.wasRetry&&(h.wasRetry=!0),h});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||g.length,questions:g})}qt(r,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete s[u];qt(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Jt={};te(Jt,{NAME:()=>vs,VERSION:()=>ks,up:()=>$s});import*as G from"fs";import*as bo from"path";var ks=2,vs="reset-unread-flags";function Cs(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function xs(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{G.writeFileSync(o,n)}catch(r){try{G.unlinkSync(o)}catch{}throw r}try{G.renameSync(o,e)}catch(r){try{G.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function $s(e){let t=bo.join(e,"conversations.json"),n=Cs(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}xs(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Vt={};te(Vt,{NAME:()=>Es,VERSION:()=>As,up:()=>Ts});import*as Y from"fs";import*as So from"path";var As=3,Es="recompute-last-message-by",_s=new Set(["draft","confirmed","rejected","needs_review"]);function Is(e){return Y.existsSync(e)?JSON.parse(Y.readFileSync(e,"utf-8")):null}function Ds(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Rs(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!_s.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Ts(e){let t=So.join(e,"conversations.json"),n=Is(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=Rs(a,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Ds(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ht={};te(Ht,{NAME:()=>Ns,VERSION:()=>js,up:()=>Ms});import*as K from"fs";import*as ko from"path";var js=4,Ns="split-connection-timestamps",Os=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ps(e){if(!K.existsSync(e))return null;let t=K.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Fs(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{K.writeFileSync(o,n)}catch(r){try{K.unlinkSync(o)}catch{}throw r}try{K.renameSync(o,e)}catch(r){try{K.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ms(e){let t=ko.join(e,"people.json"),n=Ps(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,Os.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Fs(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await ot();Nt();var Us=Ls(import.meta.url),qs=I.dirname(Us),Bs=I.dirname(I.dirname(qs));function Js(e){return e&&(e==="~"?Gt.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(Gt.homedir(),e.slice(2)):e)}var X=process.env.DATA_DIR?I.resolve(Js(process.env.DATA_DIR)):Bs,ke=I.join(X,"collected-profiles"),ve=I.join(X,"market-research"),B=I.join(X,".schema-version"),vo=[I.join(ke,".schema-version"),I.join(ve,".schema-version")],he=4,ae=[{version:1,module:Bt},{version:2,module:Jt},{version:3,module:Vt},{version:4,module:Ht}];(function(){ae.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ae){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ae.length?ae[ae.length-1].version:0;if(n!==he)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${he}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ae.length;o++){let r=o+1;if(ae[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ae[o].version}`)}})();function Ao(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
255
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
- `),process.exit(1));try{b.mkdirSync(Q,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
- [FATAL] Cannot create DATA_DIR (${Q}): ${t.message}`),console.error(` Fix the path or permissions and try again.
256
- `),process.exit(1))}let e;try{e=b.statSync(Q)}catch(t){console.error(`
257
- [FATAL] DATA_DIR (${Q}) is not accessible: ${t.message}
256
+ `),process.exit(1));try{b.mkdirSync(X,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
+ [FATAL] Cannot create DATA_DIR (${X}): ${t.message}`),console.error(` Fix the path or permissions and try again.
258
+ `),process.exit(1))}let e;try{e=b.statSync(X)}catch(t){console.error(`
259
+ [FATAL] DATA_DIR (${X}) is not accessible: ${t.message}
258
260
  `),process.exit(1)}e.isDirectory()||(console.error(`
259
- [FATAL] DATA_DIR (${Q}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
261
+ [FATAL] DATA_DIR (${X}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
260
262
  `),process.exit(1));for(let t of[ke,ve]){let n;try{n=b.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
261
263
  [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
262
- `),process.exit(1))}}var Se=I.join(Q,".migration-lock");function Ps(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync(Se,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync(Se,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(s){s.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}o&&i<r&&(console.error(`
264
+ `),process.exit(1))}}var Se=I.join(X,".migration-lock");function Vs(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync(Se,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync(Se,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(s){s.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}o&&i<r&&(console.error(`
263
265
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Se}
264
266
  `),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
265
- `),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Se+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,Se),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Wt(){try{if(JSON.parse(b.readFileSync(Se,"utf-8")).pid!==process.pid)return;b.unlinkSync(Se)}catch{}}var uo=!1;function Ms(){if(uo)return;uo=!0;let e=()=>{try{Wt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ls(){if(b.existsSync(q))return;let e=[],t=[];for(let i of co)if(b.existsSync(i))try{e.push({file:i,schema:at(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
267
+ `),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Se+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,Se),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Yt(){try{if(JSON.parse(b.readFileSync(Se,"utf-8")).pid!==process.pid)return;b.unlinkSync(Se)}catch{}}var Co=!1;function Hs(){if(Co)return;Co=!0;let e=()=>{try{Yt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ws(){if(b.existsSync(B))return;let e=[],t=[];for(let i of vo)if(b.existsSync(i))try{e.push({file:i,schema:ut(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
266
268
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
267
269
  Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
268
270
  `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
269
271
  [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
270
- `),process.exit(1)}let o=e[0].schema,r=q+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,q)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of co)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${q}`)}function Us(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function at(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function fo(){if(Ls(),!b.existsSync(q))return{version:0,migrations:[]};let e;try{e=at(q)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
271
- [FATAL] ${q} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
272
- `),process.exit(1)}let t=Us(e);return t===null&&(console.error(`
273
- [FATAL] ${q} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
274
- `),process.exit(1)),t}function ho(e){try{b.chmodSync(e,384)}catch{}}function qs(e){if(po(),b.existsSync(q))try{if(b.lstatSync(q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${q}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=q+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),ho(t),b.renameSync(t,q)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function mo(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return b.statSync(I.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=I.join(e,c),a=I.join(e,c+n);if(b.existsSync(a)){i++;continue}try{yo(l,a),r++}catch(u){s.push({file:c,err:u.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${I.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${I.basename(e)}/ (${n})${c}`)}}var Vt=!1;async function go(){if(Vt)return;po(),Ws();let t=fo().version;if(t===pe){Vt=!0;return}Ms(),Ps(),process.on("exit",Wt),t>pe&&(console.error(`
275
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${pe}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
276
- `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${pe}.
272
+ `),process.exit(1)}let o=e[0].schema,r=B+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,B)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of vo)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${B}`)}function Gs(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function ut(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function xo(){if(Ws(),!b.existsSync(B))return{version:0,migrations:[]};let e;try{e=ut(B)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
273
+ [FATAL] ${B} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
274
+ `),process.exit(1)}let t=Gs(e);return t===null&&(console.error(`
275
+ [FATAL] ${B} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
276
+ `),process.exit(1)),t}function Eo(e){try{b.chmodSync(e,384)}catch{}}function Ys(e){if(Ao(),b.existsSync(B))try{if(b.lstatSync(B).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${B}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=B+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),Eo(t),b.renameSync(t,B)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function $o(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return b.statSync(I.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=I.join(e,c),a=I.join(e,c+n);if(b.existsSync(a)){i++;continue}try{Io(l,a),r++}catch(u){s.push({file:c,err:u.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${I.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${I.basename(e)}/ (${n})${c}`)}}var Wt=!1;async function _o(){if(Wt)return;Ao(),Zs();let t=xo().version;if(t===he){Wt=!0;return}Hs(),Vs(),process.on("exit",Yt),t>he&&(console.error(`
277
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${he}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
278
+ `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${he}.
277
279
  `),process.exit(1)),console.log(`
278
- \u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=Gs();if(!n.ok){console.error(`
280
+ \u{1F4E6} Schema migration: v${t} \u2192 v${he}`);let n=ei();if(!n.ok){console.error(`
279
281
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
280
282
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
281
- `),process.exit(1)}let o=ie.filter(r=>r.version>t);for(let r of o){console.log(`
282
- Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{mo(ke,r.version),mo(ve,r.version)}catch(l){console.error(`
283
+ `),process.exit(1)}let o=ae.filter(r=>r.version>t);for(let r of o){console.log(`
284
+ Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{$o(ke,r.version),$o(ve,r.version)}catch(l){console.error(`
283
285
  [FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
284
286
  `),process.exit(1)}let c=r.module;try{await c.up(ke,ve)}catch(l){console.error(`
285
- [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=Ys(s);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
287
+ [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=ti(s);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
286
288
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
287
289
  `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
288
- `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:l},u=fo();u.version=r.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),qs(u)}catch(l){console.error(`
290
+ `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:l},u=xo();u.version=r.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Ys(u)}catch(l){console.error(`
289
291
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
290
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{hn()}catch{}try{_t()}catch{}Vt=!0,Wt(),console.log(`
291
- \u2713 Schema is now at v${pe}
292
- `)}var Bs=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Js(e){let t=e.toLowerCase();return Bs.some(n=>n.test(t))}var Vs=6e4;function Hs(){let e=Date.now(),t=[];for(let n of[Q,ke,ve]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!Js(r))continue;let i=I.join(n,r);try{let s=b.statSync(i);if(!s.isFile()||e-s.mtimeMs<Vs)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function Ws({verbose:e=!1}={}){let t=Hs();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${I.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Gs(){let e=[];for(let t of[ke,ve]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=I.join(t,o);try{at(r)}catch(i){e.push({dir:I.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ys(e){let t=[],n=[];for(let i of[ke,ve]){if(!b.existsSync(i))continue;let s=b.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=I.join(i,c),a=c.slice(0,-e.length),u=I.join(i,a);try{a.toLowerCase().endsWith(".json")?at(l):b.accessSync(l,b.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${I.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{yo(i,s),o++}catch(a){r.push(`${I.basename(l)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function yo(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),ho(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}import Z from"fs";import he from"path";var Ks="cookies.json";function wo(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin","cookies.json"):Ks}function bo(){let e=wo();if(!Z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Z.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function So(){return Z.existsSync(wo())}function zs(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin"):"."}function ko(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Qs(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?ko(t[1]):"default"}function vo(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Z.existsSync(t)||Z.mkdirSync(t,{recursive:!0}),he.resolve(t);let n=ko(e||Qs()),o=he.join(zs(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),he.resolve(o)}var Co=".ilml-seeded";function xo(e){return!Z.existsSync(he.join(e,Co))}function $o(e){try{Z.writeFileSync(he.join(e,Co),new Date().toISOString())}catch{}}function Ao(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Z.rmSync(he.join(e,n),{force:!0}),t++}catch{}return t}import Gt from"fs";import Zs from"path";var Xs={headless:!1,defaultViewport:null,protocolTimeout:3e5},Ye=new Set,Eo=!1;async function ct(){let e=[...Ye].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});Ye.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function ei(){if(Eo)return;Eo=!0;let e=t=>async()=>{await ct(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ct(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ct(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ct(),process.exit(0))}),process.on("exit",()=>{for(let t of Ye)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Yt(e){return Zs.join(e,".ilml-browser-session.json")}function Ro(e,t={}){try{Gt.writeFileSync(Yt(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function ti(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Ro(e,n?{wsEndpoint:n}:{})}catch{}}function ni(e){let t=To(e);t&&t.ownerPid===process.pid&&Ge(e)}function Ge(e){try{Gt.rmSync(Yt(e),{force:!0})}catch{}}function To(e){try{return JSON.parse(Gt.readFileSync(Yt(e),"utf-8"))}catch{return null}}function _o(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Io(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function Do(e,t,{probeTimeoutMs:n=4e3}={}){let o=To(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&_o(o.ownerPid)?"live":(Ge(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Io(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Ge(t),"free";if(_o(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Io(s.close().then(()=>!0).catch(()=>!1),n,!1))return Ge(t),"free";try{s.disconnect()}catch{}return"live"}function oi(e,t){e&&(ei(),Ye.add(e),e.on("disconnected",()=>{Ye.delete(e),t&&Ge(t)}))}async function jo(e,t={}){let n=vo(),o={...Xs,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Do(e,n)==="live")throw new Error(r);Ro(n);let i;try{i=await e.launch(o)}catch{if(await Do(e,n)==="live")throw new Error(r);Ao(n);try{i=await e.launch(o)}catch(c){throw ni(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return oi(i,n),ti(n,i),{browser:i,profileDir:n,needsSeed:xo(n)}}async function No(e,t){if(!t||!t.needsSeed)return!1;if(!So())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...bo()),$o(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await go();function si(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function ii(){let e=si();if(e.list){console.log(`
292
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{En()}catch{}try{Dt()}catch{}Wt=!0,Yt(),console.log(`
293
+ \u2713 Schema is now at v${he}
294
+ `)}var Ks=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function zs(e){let t=e.toLowerCase();return Ks.some(n=>n.test(t))}var Qs=6e4;function Xs(){let e=Date.now(),t=[];for(let n of[X,ke,ve]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!zs(r))continue;let i=I.join(n,r);try{let s=b.statSync(i);if(!s.isFile()||e-s.mtimeMs<Qs)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function Zs({verbose:e=!1}={}){let t=Xs();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${I.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ei(){let e=[];for(let t of[ke,ve]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=I.join(t,o);try{ut(r)}catch(i){e.push({dir:I.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ti(e){let t=[],n=[];for(let i of[ke,ve]){if(!b.existsSync(i))continue;let s=b.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=I.join(i,c),a=c.slice(0,-e.length),u=I.join(i,a);try{a.toLowerCase().endsWith(".json")?ut(l):b.accessSync(l,b.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${I.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{Io(i,s),o++}catch(a){r.push(`${I.basename(l)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Io(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),Eo(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}Qe();Qe();import Kt from"fs";import ni from"path";var oi={headless:!1,defaultViewport:null,protocolTimeout:3e5},Ye=new Set,Do=!1;async function ft(){let e=[...Ye].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});Ye.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function ri(){if(Do)return;Do=!0;let e=t=>async()=>{await ft(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ft(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ft(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ft(),process.exit(0))}),process.on("exit",()=>{for(let t of Ye)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function zt(e){return ni.join(e,".ilml-browser-session.json")}function No(e,t={}){try{Kt.writeFileSync(zt(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function si(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();No(e,n?{wsEndpoint:n}:{})}catch{}}function ii(e){let t=Oo(e);t&&t.ownerPid===process.pid&&Ge(e)}function Ge(e){try{Kt.rmSync(zt(e),{force:!0})}catch{}}function Oo(e){try{return JSON.parse(Kt.readFileSync(zt(e),"utf-8"))}catch{return null}}function Ro(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function To(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function jo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Oo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ro(o.ownerPid)?"live":(Ge(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await To(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Ge(t),"free";if(Ro(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await To(s.close().then(()=>!0).catch(()=>!1),n,!1))return Ge(t),"free";try{s.disconnect()}catch{}return"live"}function li(e,t){e&&(ri(),Ye.add(e),e.on("disconnected",()=>{Ye.delete(e),t&&Ge(t)}))}async function Po(e,t={}){let n=gn(),o={...oi,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await jo(e,n)==="live")throw new Error(r);No(n);let i;try{i=await e.launch(o)}catch{if(await jo(e,n)==="live")throw new Error(r);Sn(n);try{i=await e.launch(o)}catch(c){throw ii(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return li(i,n),si(n,i),{browser:i,profileDir:n,needsSeed:wn(n)}}async function Fo(e,t){if(!t||!t.needsSeed)return!1;if(!pn())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...mn()),bn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await _o();function ci(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function ui(){let e=ci();if(e.list){console.log(`
293
295
  \u{1F4C2} Available profile files:
294
- `);let a=so();if(a.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of a)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
296
+ `);let a=wo();if(a.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of a)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
295
297
  ========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
296
- `),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=no(e.source,e.date);console.log(`
298
+ `),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=ho(e.source,e.date);console.log(`
297
299
  Profiles to process: ${t.length}`),t.length===0&&(console.log(`
298
300
  \u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
299
301
  Profiles:`),t.slice(0,10).forEach((a,u)=>{console.log(` ${u+1}. ${a.name||"Unknown"} - ${a.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
300
302
  Press Enter to start, or Ctrl+C to cancel...`),await new Promise(a=>{process.stdin.once("data",()=>a())}),console.log(`
301
303
  \u{1F680} Starting browser...
302
- `);let n=await jo(ri,{devtools:!1}),o=n.browser,r=await o.newPage();await No(r,n),console.log(`\u2713 Browser ready (persistent profile)
303
- `);let i=e.viewOnly?"view-only":"connect",s=cn("funnel",i),c=await Xn(r,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(a,u,f)=>{oo(e.source,a.profileUrl,{status:f.reason,connectionSent:f.connectionSent,withCustomMessage:f.withCustomMessage,message:f.messageSent,method:f.method,reason:f.reason,error:f.error,profileInfo:f.profileInfo})}});console.log(`
304
+ `);let n=await Po(ai,{devtools:!1}),o=n.browser,r=await o.newPage();await Fo(r,n),console.log(`\u2713 Browser ready (persistent profile)
305
+ `);let i=e.viewOnly?"view-only":"connect",s=fn("funnel",i),c=await fo(r,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(a,u,f)=>{go(e.source,a.profileUrl,{status:f.reason,connectionSent:f.connectionSent,withCustomMessage:f.withCustomMessage,message:f.messageSent,method:f.method,reason:f.reason,error:f.error,profileInfo:f.profileInfo})}});console.log(`
304
306
  ========================================`),console.log("Funnel Complete!"),console.log(`========================================
305
- `);let l=ro(e.source);if(console.log(`Processed: ${l.processed}/${l.total}`),console.log(`Remaining: ${l.unprocessed}`),Object.keys(l.statuses).length>0){console.log(`
306
- Status breakdown:`);for(let[a,u]of Object.entries(l.statuses))console.log(` ${a}: ${u}`)}mt(s,"success",{sent:c.connectionsSent,viewed:c.viewed,errors:c.errors,skippedPending:c.skipped?.pending||0,skippedConnected:c.skipped?.connected||0}),await o.close(),process.exit(0)}ii().catch(e=>{console.error("Funnel failed:",e);try{mt(null,"error",null,e.message)}catch{}process.exit(1)});
307
+ `);let l=yo(e.source);if(console.log(`Processed: ${l.processed}/${l.total}`),console.log(`Remaining: ${l.unprocessed}`),Object.keys(l.statuses).length>0){console.log(`
308
+ Status breakdown:`);for(let[a,u]of Object.entries(l.statuses))console.log(` ${a}: ${u}`)}ht(s,"success",{sent:c.connectionsSent,viewed:c.viewed,errors:c.errors,skippedPending:c.skipped?.pending||0,skippedConnected:c.skipped?.connected||0}),await o.close(),process.exit(0)}ui().catch(e=>{console.error("Funnel failed:",e);try{ht(null,"error",null,e.message)}catch{}process.exit(1)});