ilml-plugin-linkedin 1.20.4 → 1.20.6

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,8 +1,8 @@
1
- var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Po(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 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 Qe=ce(()=>{});import{getPluginConfig as Yo}from"@ilivemylife/graph-sdk";var Ko,fe,te,pt,ht,gt=ce(async()=>{Ko=await Yo();for(let[e,t]of Object.entries(Ko))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"}),pt=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.NEEDS_REVIEW])),ht=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.REJECTED,te.NEEDS_REVIEW]))});import"dotenv/config";import*as O from"fs";import*as M from"path";import{fileURLToPath as zo}from"url";function mn(){Ce=null,Xo=null,ne=null,er=null,tr=null,nr=null}function Xe(){O.existsSync(oe)||O.mkdirSync(oe,{recursive:!0})}function bt(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 St(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: ${M.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 an(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=an(n),s=an(e[r].name);if(i&&s&&i===s)return r}return t}function sr(){O.existsSync(wt)||O.mkdirSync(wt,{recursive:!0})}function pn(e){let t=ye(e);return t?M.join(wt,`${t}.json`):null}function ir(e){let t=pn(e);return t?St(t,`profile-history/${ye(e)}.json`)||[]:[]}function lr(e,t){let n=pn(e);if(!n)return;sr();let o=ir(e);o.unshift(t);try{bt(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 un(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function ar(e,t){if(!e)return[];let n=[];for(let o of rr){let r=e[o],i=t[o];cn(r)||cn(i)||un(r)!==un(i)&&n.push(o)}return n}function cr(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=St(yt,"people.json")||{},Ce)}function et(e){Xe(),Ce=e;try{bt(yt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${M.resolve(yt)}`)}}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=ar(s,t);c.length>0&&(lr(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:cr(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 or)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 hn(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 gn(e){return e&&re()[e]?.connectionStatus||null}function yn(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 wn(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 bn(){return ne||(Xe(),ne=St(fn,"quota.json"),(!ne||!ne.connections)&&(ne={connections:[]}),ne)}function ur(e){Xe(),ne=e;try{bt(fn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Sn(e,t="unknown"){let n=bn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),ur(n)}function kn(){let e=bn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function kt(){let e=kn(),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 vt(){let e=kn(),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 Qo,Zo,oe,yt,bi,fn,Si,ki,vi,wt,dn,Ne,Oe,Ce,Xo,ne,er,tr,nr,or,rr,tt=ce(async()=>{await gt();Qo=zo(import.meta.url),Zo=M.dirname(M.dirname(Qo)),oe=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(Zo,"collected-profiles"),yt=M.join(oe,"people.json"),bi=M.join(oe,"jobs.json"),fn=M.join(oe,"quota.json"),Si=M.join(oe,"conversations.json"),ki=M.join(oe,"sync-state.json"),vi=M.join(oe,"application-questions.json"),wt=M.join(oe,"profile-history"),dn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ne=dn(process.env.CONNECT_MAX_DAILY,20),Oe=dn(process.env.CONNECT_MAX_WEEKLY,100),Ce=null,Xo=null,ne=null,er=null,tr=null,nr=null;or=["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"],rr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var vn={};ee(vn,{extractCertificationsFromDetails:()=>hr,extractEducationFromDetails:()=>mr,extractExperienceFromDetails:()=>fr,extractFeaturedFromDetails:()=>dr,extractRecommendationsFromDetails:()=>gr,extractSkillsFromDetails:()=>pr});async function fr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(y=>y.tagName==="DIV");if(m.length<3)continue;let g=m.filter(y=>(y.textContent||"").trim().length>50);g.length<3||(d.textContent||"").length<500||f.push({el:d,count:g.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let c=s(i);if(!c)return[];let l=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function a(u){let f=u[0]||null,d=null,m=null;if(u[1]){let k=u[1].split("\xB7").map(_=>_.trim());d=k[0]||null,k[1]&&(m=k[1])}let g=u.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),y=null,p=null;if(g>=0){let k=u[g].split("\xB7").map(_=>_.trim());y=k[0]||null,k[1]&&(p=k[1])}let h=null,v=-1;if(g>=0&&u[g+1]){let k=u[g+1],_=/^[>*\-•]|^&gt;/.test(k),X=/https?:\/\//.test(k),K=/\d{4}/.test(k),P=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!_&&!X&&!K&&k.length<100&&P&&(h=k,v=g+1)}let x=null,w=-1,$=u[u.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){w=u.length-1;let k=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(x={listed:k[1].split(",").map(_=>_.trim()),additional:parseInt(k[2],10)})}let R=new Set([0,1,g,v,w].filter(k=>k>=0)),D=u.filter((k,_)=>!R.has(_)),T=D.length>0?D.join(`
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(`
2
2
 
3
- `):null;return{title:f,company:d,employmentType:m,dates:y,duration:p,location:h,description:T,skills:x,_raw:u}}return l.map(u=>{let d=(u.innerText||"").trim().split(`
4
- `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return a(d)}).filter(u=>u.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 Me(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 dr(e,t){return Le(t,"featured","extractFeaturedFromDetails",async()=>(await Me(e,t,"featured"),await e.evaluate(`(() => {
5
- ${Pe}
3
+ `):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(`(() => {
5
+ ${Me}
6
6
 
7
7
  const main = document.querySelector('main');
8
8
  if (!main) return [];
@@ -42,8 +42,8 @@ var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
42
42
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
43
  return true;
44
44
  });
45
- })()`)))}async function mr(e,t){return Le(t,"education","extractEducationFromDetails",async()=>(await Me(e,t,"education"),await e.evaluate(`(() => {
46
- ${Pe}
45
+ })()`)))}async function wr(e,t){return Le(t,"education","extractEducationFromDetails",async()=>(await Pe(e,t,"education"),await e.evaluate(`(() => {
46
+ ${Me}
47
47
 
48
48
  const main = document.querySelector('main');
49
49
  if (!main) return [];
@@ -79,8 +79,8 @@ var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
79
79
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
80
  return true;
81
81
  });
82
- })()`)))}async function pr(e,t){return Le(t,"skills","extractSkillsFromDetails",async()=>(await Me(e,t,"skills"),await e.evaluate(`(() => {
83
- ${Pe}
82
+ })()`)))}async function br(e,t){return Le(t,"skills","extractSkillsFromDetails",async()=>(await Pe(e,t,"skills"),await e.evaluate(`(() => {
83
+ ${Me}
84
84
 
85
85
  const main = document.querySelector('main');
86
86
  if (!main) return [];
@@ -111,8 +111,8 @@ var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
111
111
  skills.push({ name, endorsements, _raw: lines });
112
112
  }
113
113
  return skills;
114
- })()`)))}async function hr(e,t){return Le(t,"certifications","extractCertificationsFromDetails",async()=>(await Me(e,t,"certifications"),await e.evaluate(`(() => {
115
- ${Pe}
114
+ })()`)))}async function Sr(e,t){return Le(t,"certifications","extractCertificationsFromDetails",async()=>(await Pe(e,t,"certifications"),await e.evaluate(`(() => {
115
+ ${Me}
116
116
 
117
117
  const main = document.querySelector('main');
118
118
  if (!main) return [];
@@ -136,8 +136,8 @@ var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
136
136
 
137
137
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
138
  }).filter(e => e.name);
139
- })()`)))}async function gr(e,t){return Le(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Me(e,t,"recommendations"),await e.evaluate(`(() => {
140
- ${Pe}
139
+ })()`)))}async function kr(e,t){return Le(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Pe(e,t,"recommendations"),await e.evaluate(`(() => {
140
+ ${Me}
141
141
 
142
142
  const main = document.querySelector('main');
143
143
  if (!main) return [];
@@ -172,7 +172,7 @@ var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
172
172
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
173
  return true;
174
174
  });
175
- })()`)))}var Pe,Cn=ce(()=>{Qe();Pe=`
175
+ })()`)))}var Me,$n=ce(()=>{Qe();Me=`
176
176
  function findEntryContainer(root) {
177
177
  const candidates = [];
178
178
  for (const div of root.querySelectorAll('div')) {
@@ -235,21 +235,21 @@ function findEntryContainer(root) {
235
235
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
236
  return candidates[0]?.el;
237
237
  }
238
- `});var En={};ee(En,{BLOCK_MARKERS:()=>xn,dedupeAndCap:()=>An,extractSidePanelProfiles:()=>yr,normalizeFundUrl:()=>nt,normalizeProfileUrl:()=>$e,scanRelatedBlocks:()=>$n});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 $n(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(([p])=>u.includes(p));if(!f)continue;let d=f[1],m=s(a);if(!m)continue;let g=0,y=new Set;for(let p of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let h=p.href||p.getAttribute("href")||"",v=r(h);if(!v)continue;let x=p.querySelector('span[aria-hidden="true"]'),w=o(x?x.textContent:p.getAttribute("aria-label")||p.textContent),$=i(w);if(!$||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 T=p.closest("li")||p.parentElement;T&&(R=Array.from(T.querySelectorAll("p, span")).map(_=>o(_.textContent)).filter(_=>_&&_!==$&&!/^view\b/i.test(_)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(_)&&/[a-z]/i.test(_)&&_.length>2)[0]||"")}c.push({href:h,name:$,headline:R,block:d,rank:g++})}}return c}function An(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 yr(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($n,xn)}catch{return[]}return An(n,t)}var xn,Ct=ce(()=>{xn=[["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 jn={};ee(jn,{getJobDecision:()=>Cr,getLastVisit:()=>Tr,getScoutStats:()=>Rr,loadCompanies:()=>It,loadDiscoveredPeople:()=>He,loadJobDecisions:()=>_t,loadScoutedJobs:()=>Et,loadVisitLog:()=>st,recordCompany:()=>_r,recordDiscoveredEdge:()=>Ar,recordDiscoveredEdges:()=>Er,recordVisit:()=>Dr,resetCaches:()=>At,saveCompany:()=>Ir,saveDiscoveredPerson:()=>xr,saveScoutedJob:()=>kr,setJobDecision:()=>vr});import"dotenv/config";import*as V from"fs";import*as B from"path";import{fileURLToPath as wr}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 At(){Ue=null,qe=null,Be=null,Je=null,we=null}function Et(){return Ue||(Ue=Ve(_n)||{},Ue)}function kr(e,t){if(!e)return;de();let n=Et(),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(_n,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function _t(){return qe||(qe=Ve(Dn)||{},qe)}function vr(e,t,n={}){if(!e||!t)return;de();let o=_t(),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(Dn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Cr(e){return _t()[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 Tn(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 xr(e,t){if(!e)return;de();let n=He(),o=new Date().toISOString().slice(0,10),r=Tn(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 $r(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 Rn(e,t,n={},o){if(!t)return;let r=Ae(t);t=Tn(e,t);let i=n.seedUrl?{...n,seedUrl:$e(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=$r(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=[]),xt(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&&xt(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 Ar(e,t={}){if(!e)return;de();let n=He();Rn(n,e,t,new Date().toISOString());try{me(rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Er(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||(Rn(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 _r(e={}){if(!e||!e.name)return;de();let t=e.key||nt(e.website)||nt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=It(),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($t,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function It(){return Je||(Je=Ve($t)||{},Je)}function Ir(e,t){if(!e)return;de();let n=It(),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($t,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function st(){return we||(we=Ve(In)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function Dr(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(In,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Tr(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 Rr(){let e=Et(),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 br,Sr,be,_n,rt,In,$t,Dn,Ue,qe,Be,xt,ot,Je,we,Dt=ce(()=>{Ct();br=wr(import.meta.url),Sr=B.dirname(B.dirname(br)),be=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join(Sr,"market-research"),_n=B.join(be,"scouted-jobs.json"),rt=B.join(be,"discovered-people.json"),In=B.join(be,"visit-log.json"),$t=B.join(be,"companies.json"),Dn=B.join(be,"job-decisions.json");Ue=null;qe=null;Be=null;xt=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},ot=(e,t)=>{if(Array.isArray(t))for(let n of t)xt(e,n)};Je=null;we=null});var Vn={};ee(Vn,{computeEngagement:()=>Rt,detectCategory:()=>Fn,detectCategoryFromTitle:()=>it,determineAction:()=>Bn,determineLastMessageBy:()=>Pn,determineSituation:()=>Mn,enrichConversation:()=>jr,enrichPerson:()=>Lr,enrichPersonContext:()=>Jn,extractAutoTags:()=>Un,generateSummary:()=>Ln,normPreview:()=>Tt});function jr(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!ht.has(l.status)),i=Or(t,e.profileUrl,n),s=Pn(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Fn(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Mn(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=Rt(r,t),e.personContext=Jn(i),e.summary=Ln(e,t,i),e.autoTags=Un(e,t,i);let c=Bn(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Nr(e),e}function Fn(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(On))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(On))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Mn(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 Nn.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 Nn.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Pn(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 Ln(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(`${jt(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=Fr(a),f=Mr(a),d=Pr(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 Un(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!ht.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=qn(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||Rt(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=>pt.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function qn(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 Bn(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Tt(e.lastMessagePreview)===Tt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(i=>pt.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:`${jt(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 Rt(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 Jn(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Nr(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 Or(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 Tt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function jt(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 Fr(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 Mr(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 Pr(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 Lr(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=it(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Ur(e),e.personSummary=qr(e),e.personAutoTags=Br(e);let n=Jr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Vr(e)),e}function Ur(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 qr(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 Br(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=qn("",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 Jr(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:`${jt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Vr(e){let t=e.category;if(!t)return null;let n=Hr(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 Hr(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 On,Nn,Hn=ce(async()=>{await gt();await tt();On={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]}};Nn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Gn={};ee(Gn,{DEFAULT_PROFILE_INTERESTS:()=>Wn,computeFit:()=>Yr,detectSectors:()=>Gr});function Gr(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(Wr))r.some(i=>i.test(t))&&n.push(o);return n}function Yr(e,t=Wn){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 Wr,Wn,Yn=ce(()=>{Wr={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/]};Wn={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Xs from"puppeteer";import"dotenv/config";import*as J from"fs";import*as ue from"path";import{fileURLToPath as Vo}from"url";import"dotenv/config";import{createGraphClient as Lo,resolveToken as Uo}from"@ilivemylife/graph-sdk";import{config as qo}from"dotenv";qo();var tn=Uo()||process.env.TOKEN;tn||(console.error(`
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(`
239
239
  [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
240
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
241
241
  `),console.error(` Or add ILML_TOKEN=... to .env
242
- `),process.exit(1));var nn=Lo({token:tn});function Bo(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 Jo({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?` ${Bo(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 on({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=`**${Jo({scriptName:e,mode:t,status:n,error:r,duration:i})}**
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})}**
243
243
 
244
244
  ${o.join(`
245
- `)}`;try{await nn.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Ho=Vo(import.meta.url),Wo=ue.dirname(ue.dirname(Ho)),ft=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(Wo,"collected-profiles"),dt=ue.join(ft,"run-log.json");function Go(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 rn(){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 sn(e){J.existsSync(ft)||J.mkdirSync(ft,{recursive:!0});try{Go(dt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ln(e,t="default"){let n=rn();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),sn(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=rn(),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)}sn(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";on({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 Kn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Kr(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 e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),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 $=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(T=>window.scrollTo(0,T),$*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"]),$=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 A=(C||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(A)},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:[]},T=document.querySelector("main");if(!T)return D;let k=[...Array.from(T.querySelectorAll("h1")),...Array.from(T.querySelectorAll("h2"))],_=Array.from(T.querySelectorAll("h2")),X=k.find(C=>{let A=C.textContent&&C.textContent.trim(),E=(A||"").replace(/\s*\(\d+\)$/,"").trim();return A&&A.length>1&&A.length<100&&!w.has(E)&&!$.has(E)}),K=X?X.textContent.trim():null,P=X?X.parentElement:null;for(;P&&P!==T&&!Array.from(P.children).filter(A=>A.tagName==="P").some(A=>{let E=A.textContent&&A.textContent.trim();return E&&E.length>5&&!R(E)});)P=P.parentElement;let le=null,De=null,Te=null,Re=null;if(P&&P!==T){let C=Array.from(P.children).filter(E=>E.tagName==="P").filter(E=>{let ae=E.textContent&&E.textContent.trim();return ae&&ae.length>5&&!R(ae)});if(C[0]&&(le=C[0].textContent.trim()),C[1]){let E=C[1].textContent.trim().split(/\s*[·•]\s*/);De=E[0]||null,E.length>1&&(Te=E.slice(1).join(" \xB7 "))}let A=Array.from(P.children).filter(E=>E.tagName==="DIV");for(let E=A.length-1;E>=0;E--){let ae=A[E].textContent&&A[E].textContent.trim();if(ae&&!(K&&ae.startsWith(K))&&(Re=ae.split(/[·•]/)[0].trim(),Re))break}}let Ke=null;if(P){let C=P.querySelectorAll("p, span, div");for(let A of C){let E=(A.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ke=E;break}}}let j=!!T.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),F=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),L=F&&F.src||null,N=T.textContent||"",z=null,Gt=N.match(/(\d+\+?)\s+connections\b/i);Gt&&(z=Gt[1]+" connections");let ze=null,Yt=N.match(/(\d+)\s+mutual connection/i),Kt=N.match(/and\s+(\d+)\s+other mutual/i),jo=N.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Yt?ze=parseInt(Yt[1],10):Kt?ze=2+parseInt(Kt[1],10):jo&&(ze=2);let zt=null,Qt=null,Zt=_.find(C=>C.textContent&&C.textContent.trim()==="About");if(Zt){let C=Zt.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let A=(C.textContent||"").trim();A=A.replace(/^About\s*/,"").trim();let E=A.match(/Top skills\s*(.+?)$/i);if(E){let ut=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Mo=>Mo.trim()).filter(Boolean);ut.length>0&&ut.length<10&&(Qt=ut)}A=A.split(/\n?…\s*more/i)[0].trim(),A=A.split(/\n?\.\.\.\s*more/i)[0].trim(),A=A.split(/\bTop skills\b/i)[0].trim(),A=A.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),zt=A||null}}let Xt=null,en=_.find(C=>C.textContent&&C.textContent.trim()==="Activity");if(en){let C=en.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let A=(C.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);A&&(Xt=parseInt(A[1].replace(/,/g,""),10))}}let No=[...new Set(_.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||"",Oo=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),Fo=/#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:Re,currentCompany:De,currentSchool:Te,connectionDegree:Ke,hasVerifiedBadge:j,photoUrl:L,connectionsLevel:z,mutualConnectionsCount:ze,followers:Xt,openToWork:Oo,hiring:Fo,about:zt,topSkills:Qt,availableSections:No}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,g=null,y=null,p=null,h=null,v=null;if(o||r||i||s||c||l){let w=await Promise.resolve().then(()=>(Cn(),vn));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&&(p=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),c&&(h=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${h.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},...p!==null&&{skillsFull:p},...h!==null&&{recommendations:h},...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 Nt(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 p=y.getBoundingClientRect();if(p.width===0||p.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(p=>{let h=p.getAttribute("aria-label")||"";return(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&m.test(h)}).map(p=>p.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 p of m){if(p.closest(g))continue;let h=p.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(h)&&(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&y.test(h))return p}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,p=(f.getAttribute("aria-label")||"").toLowerCase(),h=p.includes("invite"),v=d?p.includes(d):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:h,matchesName:v,ariaLabel:p}},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")||"",p=m.getBoundingClientRect();return p.top<100||p.top>600||p.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 p of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(p.innerText?.trim()==="Connect")return p}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 p=y.innerText?.trim();p&&p.length<40&&m.push(p)}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 zr(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 Qr(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 Nt(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 Zr(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=kt();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 Xr(e,t,n);return s.connectionSent&&!i&&Sn(t,o),s}async function Xr(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 h=re()[t]?.location;if(Kn(h,c))return console.log(` \u26A0 Excluded location (stored): ${h}`),l.reason="excluded_location",l.profileInfo={location:h},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),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:h,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(Ct(),En)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Dt(),jn)),{detectCategoryFromTitle:w}=await Hn().then(()=>Vn),{detectSectors:$}=await Promise.resolve().then(()=>(Yn(),Gn)),R=v(t)||t,D=await h(e,{seedUrl:R}),T=D.map(k=>{let _=k.headline?w(k.headline):null;return{url:k.url,seedUrl:R,block:k.block,rank:k.rank,name:k.name,headline:k.headline,categories:_?[_]:[],sectors:$(k.headline||"")}});x(T),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(h){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${h.message}`)}l.profileInfo=await e.evaluate(()=>{let h=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=j=>{let F=(j||"").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 $=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],R=Array.from(w.querySelectorAll("h2")),D=$.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!h.has(F)&&F!=="0 notifications"}),T=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==w&&!Array.from(k.children).filter(L=>L.tagName==="P").some(L=>{let N=L.textContent&&L.textContent.trim();return N&&N.length>5&&!v(N)});)k=k.parentElement;let _=null,X=null,K=null;if(k&&k!==w){let j=Array.from(k.children),F=j.filter(N=>N.tagName==="P").filter(N=>{let z=N.textContent&&N.textContent.trim();return z&&z.length>5&&!v(z)});F[0]&&(_=F[0].textContent.trim()),F[1]&&(X=F[1].textContent.trim());let L=j.filter(N=>N.tagName==="DIV");for(let N=L.length-1;N>=0;N--){let z=L[N].textContent&&L[N].textContent.trim();if(z&&!(T&&z.startsWith(T))&&(K=z.split(/[·•]/)[0].trim(),K))break}}let P=null;if(k){let j=k.querySelectorAll("p, span, div");for(let F of j){let L=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){P=L;break}}}let le=null,De=R.find(j=>j.textContent&&j.textContent.trim()==="About");if(De){let j=De.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(le=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,le&&(le=le.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Te=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Re=Te&&Te.src||null,Ke=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:T,title:_,location:K,about:le,company:X,connectionDegree:P,connectionsCount:null,mutualConnections:null,photoUrl:Re,hasVerifiedBadge:Ke}});try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(l.resolvedUrl=h.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let h=l.profileInfo?.location,v=re()[t]?.location,x=h||v;if(Kn(x,c))return console.log(` \u26A0 Excluded location (${h?"live":"stored"}): ${x}`),l.reason="excluded_location",l;!h&&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 Nt(e);if(d||await ge(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),d=await Nt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let h=await _e(e,{detail:!0});return s&&(h.status==="connected"||h.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 zr(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 h=await _e(e);if(h==="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: ${h} \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 h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of h){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 $=x.querySelector('button[aria-label="Send without a note"]');if($&&($.disabled||$.getAttribute("aria-disabled")==="true"||($.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let h=await e.$('button[aria-label="Dismiss"]');if(h)try{await h.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"]'),p=await e.$('button[aria-label="Send without a note"]');if(!y&&!p){let h=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(h.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(h.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));p=v?.asElement?.()||null,p||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 Qr(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 $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($)return await Ie(e,$)?(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(p)return console.log(" Sending without note..."),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(y&&!o){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h)return 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)}}else{console.log(" Sending without note (custom messages disabled)...");let h=p;if(h)return 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(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 $=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($.visible&&!$.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($=>$.scrollIntoView({behavior:"smooth",block:"center"}),x),await S(500),await x.click().catch(()=>e.evaluate($=>$.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(T=>T.click(),w),await S(3e3);let $=e.url();if($.includes("/premium/")||$.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 Qn(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=vt();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(`
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(`
248
248
  \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=gn(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 p=null;if(s){let h=await Kr(e,g.profileUrl);h?(Ze(g.profileUrl,{...h,source:u}),f.viewed++,p={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h,resolvedUrl:h.resolvedUrl}):(f.errors++,p={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let h=kt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(p=await Zr(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:u,skipQuotaGate:!0}),p.success)f.connectionsSent++;else switch(p.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(p?.fatal){console.log(`
250
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(p?.reason==="error"){if(d++,d>=3){console.log(`
251
- \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(p&&p.reason&&(yn(g.profileUrl,p.reason,{method:p.method,messageSent:p.messageSent,profileInfo:p.profileInfo}),p.resolvedUrl&&wn(g.profileUrl,p.resolvedUrl),hn(g.profileUrl,{source:u||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:p.reason})),l&&await l(g,f,p),m<t.length-1){let h=c+Math.random()*2e3;await S(h)}}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=vt();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 es}from"url";var ts=es(import.meta.url),ns=se.dirname(se.dirname(ts)),We=process.env.DATA_DIR?se.resolve(process.env.DATA_DIR,"collected-profiles"):se.join(ns,"collected-profiles");function Ot(){U.existsSync(We)||U.mkdirSync(We,{recursive:!0})}function os(){return new Date().toISOString().split("T")[0]}function Zn(e,t=null){let n=t||os();return se.join(We,`${e}-${n}.json`)}function Xn(e,t=null){Ot();let n=Zn(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 eo(e,t=null){return Xn(e,t).filter(o=>!o.processed)}function to(e,t,n,o=null){Ot();let r=Zn(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 no(e){let t=Xn(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 oo(){Ot();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 Jt from"os";import*as I from"path";import{fileURLToPath as Es}from"url";var Pt={};ee(Pt,{NAME:()=>ss,VERSION:()=>rs,up:()=>as});import*as H from"fs";import*as lt from"path";var rs=1,ss="normalize-jobs-and-questions",is=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ls=50;function Ft(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Mt(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 as(e,t){let n=lt.join(e,"jobs.json"),o=lt.join(t,"scouted-jobs.json"),r=lt.join(e,"application-questions.json"),i=Ft(n)||{},s=Ft(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 is)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),c++}c>0?(Mt(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Ft(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 p={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=ls?p.options=y.options:(p.optionsOmitted=!0,f++)),y.page&&(p.page=y.page),y.wasPreFilled&&(p.wasPreFilled=!0),y.wasRetry&&(p.wasRetry=!0),p});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})}Mt(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];Mt(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 Lt={};ee(Lt,{NAME:()=>us,VERSION:()=>cs,up:()=>ms});import*as W from"fs";import*as ro from"path";var cs=2,us="reset-unread-flags";function fs(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function ds(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 ms(e){let t=ro.join(e,"conversations.json"),n=fs(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}ds(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ut={};ee(Ut,{NAME:()=>hs,VERSION:()=>ps,up:()=>Ss});import*as G from"fs";import*as so from"path";var ps=3,hs="recompute-last-message-by",gs=new Set(["draft","confirmed","rejected","needs_review"]);function ys(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function ws(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 bs(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!gs.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 Ss(e){let t=so.join(e,"conversations.json"),n=ys(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=bs(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}ws(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 qt={};ee(qt,{NAME:()=>vs,VERSION:()=>ks,up:()=>As});import*as Y from"fs";import*as io from"path";var ks=4,vs="split-connection-timestamps",Cs=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function xs(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 $s(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 As(e){let t=io.join(e,"people.json"),n=xs(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++,Cs.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}$s(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();Dt();var _s=Es(import.meta.url),Is=I.dirname(_s),Ds=I.dirname(I.dirname(Is));function Ts(e){return e&&(e==="~"?Jt.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(Jt.homedir(),e.slice(2)):e)}var Q=process.env.DATA_DIR?I.resolve(Ts(process.env.DATA_DIR)):Ds,ke=I.join(Q,"collected-profiles"),ve=I.join(Q,"market-research"),q=I.join(Q,".schema-version"),lo=[I.join(ke,".schema-version"),I.join(ve,".schema-version")],pe=4,ie=[{version:1,module:Pt},{version:2,module:Lt},{version:3,module:Ut},{version:4,module:qt}];(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 fo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
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(`
250
+ \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
253
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
254
  `),process.exit(1));try{b.mkdirSync(Q,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
255
  [FATAL] Cannot create DATA_DIR (${Q}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -259,48 +259,48 @@ ${o.join(`
259
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.
260
260
  `),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
261
  [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 Rs(){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(`
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(`
263
263
  [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
264
  `),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 Vt(){try{if(JSON.parse(b.readFileSync(Se,"utf-8")).pid!==process.pid)return;b.unlinkSync(Se)}catch{}}var ao=!1;function js(){if(ao)return;ao=!0;let e=()=>{try{Vt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ns(){if(b.existsSync(q))return;let e=[],t=[];for(let i of lo)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(`
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(`
266
266
  [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
267
  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
268
  `),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
269
  [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 lo)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${q}`)}function Os(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 co(){if(Ns(),!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(`
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
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=Os(e);return t===null&&(console.error(`
272
+ `),process.exit(1)}let t=Us(e);return t===null&&(console.error(`
273
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 mo(e){try{b.chmodSync(e,384)}catch{}}function Fs(e){if(fo(),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)),mo(t),b.renameSync(t,q)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function uo(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{ho(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 Bt=!1;async function po(){if(Bt)return;fo(),qs();let t=co().version;if(t===pe){Bt=!0;return}js(),Rs(),process.on("exit",Vt),t>pe&&(console.error(`
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
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
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}.
277
277
  `),process.exit(1)),console.log(`
278
- \u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=Bs();if(!n.ok){console.error(`
278
+ \u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=Gs();if(!n.ok){console.error(`
279
279
  [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
280
  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
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{uo(ke,r.version),uo(ve,r.version)}catch(l){console.error(`
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
283
  [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
284
  `),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=Js(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.
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.
286
286
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
287
287
  `))}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=co();u.version=r.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Fs(u)}catch(l){console.error(`
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(`
289
289
  [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{mn()}catch{}try{At()}catch{}Bt=!0,Vt(),console.log(`
290
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{hn()}catch{}try{_t()}catch{}Vt=!0,Wt(),console.log(`
291
291
  \u2713 Schema is now at v${pe}
292
- `)}var Ms=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Ps(e){let t=e.toLowerCase();return Ms.some(n=>n.test(t))}var Ls=6e4;function Us(){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(!Ps(r))continue;let i=I.join(n,r);try{let s=b.statSync(i);if(!s.isFile()||e-s.mtimeMs<Ls)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function qs({verbose:e=!1}={}){let t=Us();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 Bs(){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 Js(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{ho(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 ho(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),mo(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 Vs="cookies.json";function go(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin","cookies.json"):Vs}function yo(){let e=go();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 wo(){return Z.existsSync(go())}function Hs(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin"):"."}function bo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ws(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?bo(t[1]):"default"}function So(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=bo(e||Ws()),o=he.join(Hs(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),he.resolve(o)}var ko=".ilml-seeded";function vo(e){return!Z.existsSync(he.join(e,ko))}function Co(e){try{Z.writeFileSync(he.join(e,ko),new Date().toISOString())}catch{}}function xo(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 Ht from"fs";import Gs from"path";var Ys={headless:!1,defaultViewport:null,protocolTimeout:3e5},Ye=new Set,$o=!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 Ks(){if($o)return;$o=!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 Wt(e){return Gs.join(e,".ilml-browser-session.json")}function Io(e,t={}){try{Ht.writeFileSync(Wt(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function zs(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Io(e,n?{wsEndpoint:n}:{})}catch{}}function Qs(e){let t=Do(e);t&&t.ownerPid===process.pid&&Ge(e)}function Ge(e){try{Ht.rmSync(Wt(e),{force:!0})}catch{}}function Do(e){try{return JSON.parse(Ht.readFileSync(Wt(e),"utf-8"))}catch{return null}}function Ao(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Eo(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 _o(e,t,{probeTimeoutMs:n=4e3}={}){let o=Do(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ao(o.ownerPid)?"live":(Ge(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Eo(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Ge(t),"free";if(Ao(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Eo(s.close().then(()=>!0).catch(()=>!1),n,!1))return Ge(t),"free";try{s.disconnect()}catch{}return"live"}function Zs(e,t){e&&(Ks(),Ye.add(e),e.on("disconnected",()=>{Ye.delete(e),t&&Ge(t)}))}async function To(e,t={}){let n=So(),o={...Ys,...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 _o(e,n)==="live")throw new Error(r);Io(n);let i;try{i=await e.launch(o)}catch{if(await _o(e,n)==="live")throw new Error(r);xo(n);try{i=await e.launch(o)}catch(c){throw Qs(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 Zs(i,n),zs(n,i),{browser:i,profileDir:n,needsSeed:vo(n)}}async function Ro(e,t){if(!t||!t.needsSeed)return!1;if(!wo())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(...yo()),Co(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await po();function ei(){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 ti(){let e=ei();if(e.list){console.log(`
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(`
293
293
  \u{1F4C2} Available profile files:
294
- `);let a=oo();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(`
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(`
295
295
  ========================================`),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=eo(e.source,e.date);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(`
297
297
  Profiles to process: ${t.length}`),t.length===0&&(console.log(`
298
298
  \u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
299
299
  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
300
  Press Enter to start, or Ctrl+C to cancel...`),await new Promise(a=>{process.stdin.once("data",()=>a())}),console.log(`
301
301
  \u{1F680} Starting browser...
302
- `);let n=await To(Xs,{devtools:!1}),o=n.browser,r=await o.newPage();await Ro(r,n),console.log(`\u2713 Browser ready (persistent profile)
303
- `);let i=e.viewOnly?"view-only":"connect",s=ln("funnel",i),c=await Qn(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)=>{to(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(`
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
304
  ========================================`),console.log("Funnel Complete!"),console.log(`========================================
305
- `);let l=no(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)}ti().catch(e=>{console.error("Funnel failed:",e);try{mt(null,"error",null,e.message)}catch{}process.exit(1)});
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)});