ilml-plugin-linkedin 1.13.0 → 1.13.1

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.
package/dist/syncAll.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ao=Object.defineProperty;var Fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ue=(e,t)=>{for(var n in t)Ao(e,n,{get:t[n],enumerable:!0})};function qe(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function St(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=qe(n),r=new Date(t);return l?r.setHours(l.hours,l.minutes,0,0):r.setHours(0,0,0,0),r.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=To[o[1].toLowerCase()],r=qe(o[2]||""),c=new Date(t),f=c.getDay()-l;return f<=0&&(f+=7),c.setDate(c.getDate()-f),r?c.setHours(r.hours,r.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=bt[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(s[2],10),c=parseInt(s[3],10),u=qe(s[4]||"");return new Date(c,l,r,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let l=bt[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(i[2],10),c=qe(i[3]||""),u=t.getFullYear(),f=new Date(u,l,r,c?.hours||0,c?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let l=bt[a[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(a[2],10),c=qe(a[3]||""),u=t.getFullYear(),f=new Date(u,l,r,c?.hours||0,c?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function $(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function dn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function he(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),a=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||a||l){let r=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(r)return r.click(),{dismissed:!0,matched:s.substring(0,80)};let c=o.querySelectorAll("button");for(let u of c){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:s.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})}function fn(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function mn(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var bt,To,Ae=Fe(()=>{bt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},To={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Ro}from"@ilivemylife/graph-sdk";var Do,z,V,Be,Te,He=Fe(async()=>{Do=await Ro();for(let[e,t]of Object.entries(Do))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Be=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Te=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as U from"fs";import*as B from"path";import{fileURLToPath as Io}from"url";import{execSync as vt}from"child_process";function bn(){Re=null,No=null,ae=null,we=null,De=null,ye=null}function le(){U.existsSync(Z)||U.mkdirSync(Z,{recursive:!0})}function Ie(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";U.writeFileSync(o,n);for(let s=0;s<3;s++)try{U.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function We(e,t){if(!U.existsSync(e))return null;try{let n=JSON.parse(U.readFileSync(e,"utf-8"));try{U.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(U.existsSync(o))try{let s=JSON.parse(U.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{U.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function Ct(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Lo(){U.existsSync(kt)||U.mkdirSync(kt,{recursive:!0})}function Sn(e){let t=Ct(e);return t?B.join(kt,`${t}.json`):null}function Fo(e){let t=Sn(e);return t?We(t,`profile-history/${Ct(e)}.json`)||[]:[]}function Uo(e,t){let n=Sn(e);if(!n)return;Lo();let o=Fo(e);o.unshift(t);try{Ie(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Ct(e)}: ${s.message}`)}}function gn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function hn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function qo(e,t){if(!e)return[];let n=[];for(let o of Po){let s=e[o],i=t[o];gn(s)||gn(i)||hn(s)!==hn(i)&&n.push(o)}return n}function Bo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Re||(le(),Re=We($t,"people.json")||{},Re)}function Me(e){le(),Re=e;try{Ie($t,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve($t)}`)}}function Ge(){return we||(le(),we=We(lt,"conversations.json")||{},Ho(we),we)}function Ho(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Ie(lt,e)}catch{}}}function fe(e){le(),we=e;try{Ie(lt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(lt)}`)}}function be(e,t={}){if(!e)return null;let n=J(),o=Ye(),s=new Date().toISOString(),i=n[e];if(i){let a=qo(i,t);a.length>0&&(Uo(e,{capturedAt:s,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:Bo(i)}),i.lastSnapshotAt=s),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=s,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of jo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=s)}else n[e]={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,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Me(n),n[e]}function vn(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Ye(),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(l=>l.date===i.date&&l.source===i.source&&l.action===i.action&&(l.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Me(n))}function $n(e){return e&&J()[e]?.connectionStatus||null}function kn(e,t,n={}){if(!e)return;n.profileInfo?be(e,n.profileInfo):J()[e]||be(e,{});let o=J(),s=o[e];s&&(s.connectionStatus=t,s.connectionDate=Ye(),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),Me(o))}function Cn(){return ae||(le(),ae=We(yn,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function Jo(e){le(),ae=e;try{Ie(yn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function xn(e,t="unknown"){let n=Cn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Jo(n)}function _n(){let e=Cn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function En(){let e=_n(),t=Ye(),n=e.filter(r=>r.date===t).length,o=e.length,s=n>=Je,i=o>=Ve,a=!s&&!i,l={allowed:a,daily:{sent:n,max:Je},weekly:{sent:o,max:Ve}};return a||(l.reason=s?`Daily limit reached (${n}/${Je})`:`Weekly limit reached (${o}/${Ve})`),l}function ze(){let e=_n(),t=Ye(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:Je,remaining:Je-n},weekly:{sent:o,max:Ve,remaining:Ve-o}}}function xt(){return De||(le(),De=We(wn,"sync-state.json")||{},De)}function An(e){le(),De=e;try{Ie(wn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Vo(){if(ye)return ye;le();try{U.existsSync(pn)&&(ye=JSON.parse(U.readFileSync(pn,"utf-8")))}catch{}return ye||(ye={}),ye}function Wo(e){return Array.isArray(e.applications)}function Yo(){let e=Vo();if(Wo(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function Tn(){let e=Yo(),t=new Map;for(let i of e)for(let a of i.questions||[]){let l=a.question.toLowerCase().trim();if(!l)continue;t.has(l)||t.set(l,{question:a.question,count:0,answers:new Map});let r=t.get(l);r.count++;let c=(a.answer||"").trim();r.answers.set(c,(r.answers.get(c)||0)+1)}let n=[...t.values()].sort((i,a)=>a.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((a,l)=>l[1]-a[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((a,l)=>l[1]-a[1]).map(([a,l])=>`${a} (${l}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function _t(e){if(U.existsSync(B.join(Z,".git")))try{let t={cwd:Z,stdio:"pipe",timeout:1e4};vt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{vt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');vt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Mo,Oo,Z,$t,di,yn,lt,wn,pn,kt,Je,Ve,Re,No,ae,we,De,ye,jo,Po,Ke=Fe(async()=>{await He();Mo=Io(import.meta.url),Oo=B.dirname(B.dirname(Mo)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Oo,"collected-profiles"),$t=B.join(Z,"people.json"),di=B.join(Z,"jobs.json"),yn=B.join(Z,"quota.json"),lt=B.join(Z,"conversations.json"),wn=B.join(Z,"sync-state.json"),pn=B.join(Z,"application-questions.json"),kt=B.join(Z,"profile-history"),Je=20,Ve=100,Re=null,No=null,ae=null,we=null,De=null,ye=null;jo=["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"],Po=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var co={};Ue(co,{extractCertificationsFromDetails:()=>Ir,extractEducationFromDetails:()=>Rr,extractExperienceFromDetails:()=>Ar,extractFeaturedFromDetails:()=>Tr,extractRecommendationsFromDetails:()=>Mr,extractSkillsFromDetails:()=>Dr});async function Ar(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await $(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 $(900);await $(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await $(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(p=>p.tagName==="DIV");if(m.length<3)continue;let y=m.filter(p=>(p.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let l=a(i);if(!l)return[];let r=Array.from(l.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function c(u){let f=u[0]||null,d=null,m=null;if(u[1]){let T=u[1].split("\xB7").map(L=>L.trim());d=T[0]||null,T[1]&&(m=T[1])}let y=u.findIndex(T=>/(\d{4}|present)/i.test(T)&&/(-|–|—)/i.test(T)&&T.length<80),p=null,b=null;if(y>=0){let T=u[y].split("\xB7").map(L=>L.trim());p=T[0]||null,T[1]&&(b=T[1])}let w=null,S=-1;if(y>=0&&u[y+1]){let T=u[y+1],L=/^[>*\-•]|^&gt;/.test(T),G=/https?:\/\//.test(T),v=/\d{4}/.test(T),_=/,/.test(T)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(T);!L&&!G&&!v&&T.length<100&&_&&(w=T,S=y+1)}let g=null,h=-1,k=u[u.length-1];if(k&&/and\s+\+\d+\s+skills?$/i.test(k)){h=u.length-1;let T=k.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);T&&(g={listed:T[1].split(",").map(L=>L.trim()),additional:parseInt(T[2],10)})}let C=new Set([0,1,y,S,h].filter(T=>T>=0)),E=u.filter((T,L)=>!C.has(L)),I=E.length>0?E.join(`
1
+ var Ao=Object.defineProperty;var Fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ue=(e,t)=>{for(var n in t)Ao(e,n,{get:t[n],enumerable:!0})};function qe(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function St(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=qe(n),r=new Date(t);return l?r.setHours(l.hours,l.minutes,0,0):r.setHours(0,0,0,0),r.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=To[o[1].toLowerCase()],r=qe(o[2]||""),c=new Date(t),f=c.getDay()-l;return f<=0&&(f+=7),c.setDate(c.getDate()-f),r?c.setHours(r.hours,r.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=bt[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(s[2],10),c=parseInt(s[3],10),u=qe(s[4]||"");return new Date(c,l,r,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let l=bt[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(i[2],10),c=qe(i[3]||""),u=t.getFullYear(),f=new Date(u,l,r,c?.hours||0,c?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let l=bt[a[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let r=parseInt(a[2],10),c=qe(a[3]||""),u=t.getFullYear(),f=new Date(u,l,r,c?.hours||0,c?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function $(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function dn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function he(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),a=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||a||l){let r=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(r)return r.click(),{dismissed:!0,matched:s.substring(0,80)};let c=o.querySelectorAll("button");for(let u of c){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:s.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})}function fn(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function mn(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var bt,To,Ae=Fe(()=>{bt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},To={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Ro}from"@ilivemylife/graph-sdk";var Do,z,V,Be,Te,He=Fe(async()=>{Do=await Ro();for(let[e,t]of Object.entries(Do))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Be=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Te=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as U from"fs";import*as B from"path";import{fileURLToPath as Io}from"url";import{execSync as vt}from"child_process";function bn(){Re=null,No=null,ae=null,we=null,De=null,ye=null}function le(){U.existsSync(Z)||U.mkdirSync(Z,{recursive:!0})}function Ie(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";U.writeFileSync(o,n);for(let s=0;s<3;s++)try{U.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function We(e,t){if(!U.existsSync(e))return null;try{let n=JSON.parse(U.readFileSync(e,"utf-8"));try{U.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(U.existsSync(o))try{let s=JSON.parse(U.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{U.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{U.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ye(){return new Date().toISOString().split("T")[0]}function Ct(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Lo(){U.existsSync(kt)||U.mkdirSync(kt,{recursive:!0})}function Sn(e){let t=Ct(e);return t?B.join(kt,`${t}.json`):null}function Fo(e){let t=Sn(e);return t?We(t,`profile-history/${Ct(e)}.json`)||[]:[]}function Uo(e,t){let n=Sn(e);if(!n)return;Lo();let o=Fo(e);o.unshift(t);try{Ie(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Ct(e)}: ${s.message}`)}}function gn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function hn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function qo(e,t){if(!e)return[];let n=[];for(let o of Po){let s=e[o],i=t[o];gn(s)||gn(i)||hn(s)!==hn(i)&&n.push(o)}return n}function Bo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Re||(le(),Re=We($t,"people.json")||{},Re)}function Me(e){le(),Re=e;try{Ie($t,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve($t)}`)}}function Ge(){return we||(le(),we=We(lt,"conversations.json")||{},Ho(we),we)}function Ho(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Ie(lt,e)}catch{}}}function fe(e){le(),we=e;try{Ie(lt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(lt)}`)}}function be(e,t={}){if(!e)return null;let n=J(),o=Ye(),s=new Date().toISOString(),i=n[e];if(i){let a=qo(i,t);a.length>0&&(Uo(e,{capturedAt:s,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:Bo(i)}),i.lastSnapshotAt=s),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=s,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of jo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=s)}else n[e]={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,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Me(n),n[e]}function vn(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Ye(),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(l=>l.date===i.date&&l.source===i.source&&l.action===i.action&&(l.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Me(n))}function $n(e){return e&&J()[e]?.connectionStatus||null}function kn(e,t,n={}){if(!e)return;n.profileInfo?be(e,n.profileInfo):J()[e]||be(e,{});let o=J(),s=o[e];s&&(s.connectionStatus=t,s.connectionDate=Ye(),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),Me(o))}function Cn(){return ae||(le(),ae=We(yn,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function Jo(e){le(),ae=e;try{Ie(yn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function xn(e,t="unknown"){let n=Cn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Jo(n)}function En(){let e=Cn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function _n(){let e=En(),t=Ye(),n=e.filter(r=>r.date===t).length,o=e.length,s=n>=Je,i=o>=Ve,a=!s&&!i,l={allowed:a,daily:{sent:n,max:Je},weekly:{sent:o,max:Ve}};return a||(l.reason=s?`Daily limit reached (${n}/${Je})`:`Weekly limit reached (${o}/${Ve})`),l}function ze(){let e=En(),t=Ye(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:Je,remaining:Je-n},weekly:{sent:o,max:Ve,remaining:Ve-o}}}function xt(){return De||(le(),De=We(wn,"sync-state.json")||{},De)}function An(e){le(),De=e;try{Ie(wn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Vo(){if(ye)return ye;le();try{U.existsSync(pn)&&(ye=JSON.parse(U.readFileSync(pn,"utf-8")))}catch{}return ye||(ye={}),ye}function Wo(e){return Array.isArray(e.applications)}function Yo(){let e=Vo();if(Wo(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function Tn(){let e=Yo(),t=new Map;for(let i of e)for(let a of i.questions||[]){let l=a.question.toLowerCase().trim();if(!l)continue;t.has(l)||t.set(l,{question:a.question,count:0,answers:new Map});let r=t.get(l);r.count++;let c=(a.answer||"").trim();r.answers.set(c,(r.answers.get(c)||0)+1)}let n=[...t.values()].sort((i,a)=>a.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((a,l)=>l[1]-a[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((a,l)=>l[1]-a[1]).map(([a,l])=>`${a} (${l}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function Et(e){if(U.existsSync(B.join(Z,".git")))try{let t={cwd:Z,stdio:"pipe",timeout:1e4};vt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{vt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');vt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Mo,Oo,Z,$t,di,yn,lt,wn,pn,kt,Je,Ve,Re,No,ae,we,De,ye,jo,Po,Ke=Fe(async()=>{await He();Mo=Io(import.meta.url),Oo=B.dirname(B.dirname(Mo)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Oo,"collected-profiles"),$t=B.join(Z,"people.json"),di=B.join(Z,"jobs.json"),yn=B.join(Z,"quota.json"),lt=B.join(Z,"conversations.json"),wn=B.join(Z,"sync-state.json"),pn=B.join(Z,"application-questions.json"),kt=B.join(Z,"profile-history"),Je=20,Ve=100,Re=null,No=null,ae=null,we=null,De=null,ye=null;jo=["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"],Po=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var co={};Ue(co,{extractCertificationsFromDetails:()=>Ir,extractEducationFromDetails:()=>Rr,extractExperienceFromDetails:()=>Ar,extractFeaturedFromDetails:()=>Tr,extractRecommendationsFromDetails:()=>Mr,extractSkillsFromDetails:()=>Dr});async function Ar(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await $(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 $(900);await $(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await $(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(p=>p.tagName==="DIV");if(m.length<3)continue;let y=m.filter(p=>(p.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let l=a(i);if(!l)return[];let r=Array.from(l.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function c(u){let f=u[0]||null,d=null,m=null;if(u[1]){let T=u[1].split("\xB7").map(L=>L.trim());d=T[0]||null,T[1]&&(m=T[1])}let y=u.findIndex(T=>/(\d{4}|present)/i.test(T)&&/(-|–|—)/i.test(T)&&T.length<80),p=null,b=null;if(y>=0){let T=u[y].split("\xB7").map(L=>L.trim());p=T[0]||null,T[1]&&(b=T[1])}let w=null,S=-1;if(y>=0&&u[y+1]){let T=u[y+1],L=/^[>*\-•]|^&gt;/.test(T),G=/https?:\/\//.test(T),v=/\d{4}/.test(T),E=/,/.test(T)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(T);!L&&!G&&!v&&T.length<100&&E&&(w=T,S=y+1)}let g=null,h=-1,k=u[u.length-1];if(k&&/and\s+\+\d+\s+skills?$/i.test(k)){h=u.length-1;let T=k.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);T&&(g={listed:T[1].split(",").map(L=>L.trim()),additional:parseInt(T[2],10)})}let C=new Set([0,1,y,S,h].filter(T=>T>=0)),_=u.filter((T,L)=>!C.has(L)),I=_.length>0?_.join(`
2
2
 
3
3
  `):null;return{title:f,company:d,employmentType:m,dates:p,duration:b,location:w,description:I,skills:g,_raw:u}}return r.map(u=>{let d=(u.innerText||"").trim().split(`
4
4
  `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return c(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 nt(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let a=0;a<4;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);await $(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)i++,await $(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(600)}async function st(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;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 Tr(e,t){return st(t,"featured","extractFeaturedFromDetails",async()=>(await nt(e,t,"featured"),await e.evaluate(`(() => {
@@ -37,6 +37,9 @@ var Ao=Object.defineProperty;var Fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ue=(e,t)=>{
37
37
  // Reject "People You May Know" sidebar cards: signature is
38
38
  // exactly [title, "View"] with no url/caption beyond "View".
39
39
  if (e._raw.length === 2 && e._raw[1] === 'View') return false;
40
+ // Reject "Other profiles you may know" widget cards: caption is
41
+ // just a connection-degree marker (e.g. "\xB7 3rd", "\xB7 2nd").
42
+ if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
40
43
  return true;
41
44
  });
42
45
  })()`)))}async function Rr(e,t){return st(t,"education","extractEducationFromDetails",async()=>(await nt(e,t,"education"),await e.evaluate(`(() => {
@@ -71,6 +74,9 @@ var Ao=Object.defineProperty;var Fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ue=(e,t)=>{
71
74
  if (!e.school) return false;
72
75
  // Reject "People You May Know" sidebar cards: [title, "View"].
73
76
  if (e._raw.length === 2 && e._raw[1] === 'View') return false;
77
+ // Reject related-profile widget: "degree" parsed as the
78
+ // connection-degree marker ("\xB7 3rd") instead of a real degree.
79
+ if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
74
80
  return true;
75
81
  });
76
82
  })()`)))}async function Dr(e,t){return st(t,"skills","extractSkillsFromDetails",async()=>(await nt(e,t,"skills"),await e.evaluate(`(() => {
@@ -161,6 +167,9 @@ var Ao=Object.defineProperty;var Fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ue=(e,t)=>{
161
167
  if (!e.recommender || !e.text) return false;
162
168
  // Reject "People You May Know" sidebar cards: [title, "View"].
163
169
  if (e._raw.length === 2 && e._raw[1] === 'View') return false;
170
+ // Reject related-profile widget: recommenderTitle is the
171
+ // connection-degree marker, not a real job title.
172
+ if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
164
173
  return true;
165
174
  });
166
175
  })()`)))}var ot,uo=Fe(()=>{Ae();ot=`
@@ -183,6 +192,20 @@ function findEntryContainer(root) {
183
192
  });
184
193
  if (allLookLikePYMK) continue;
185
194
 
195
+ // Reject "Other profiles you may know" / related-profile widget:
196
+ // LinkedIn shows this when /details/<section>/ has no real data
197
+ // (e.g. profile has no Featured at all). Every entry is a short
198
+ // [name, "\xB7 Nth"] card with a connection-degree marker as the only
199
+ // metadata. Real Featured / Education / Recommendations entries
200
+ // NEVER consist solely of name + degree.
201
+ const DEGREE_RE = /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i;
202
+ const allLookLikeRelatedProfiles = substantial.every(c => {
203
+ const lines = (c.innerText || '').trim().split('\\n').map(l => l.trim()).filter(Boolean);
204
+ if (lines.length > 4) return false;
205
+ return lines.some(l => DEGREE_RE.test(l));
206
+ });
207
+ if (allLookLikeRelatedProfiles) continue;
208
+
186
209
  // Reject LinkedIn footer/legal blocks: when a /details/<section>/ page
187
210
  // renders empty, LinkedIn falls back to "Questions? Visit our Help
188
211
  // Center", "Select language" (35+ languages), "Recommendation
@@ -198,6 +221,8 @@ function findEntryContainer(root) {
198
221
  'Who your viewers also viewed', // "Private to you" PYMK block on empty pages
199
222
  'People also viewed',
200
223
  'People you may know',
224
+ 'More profiles for you', // LinkedIn related-profiles widget shown
225
+ 'Other profiles you may know', // when /details/<section>/ is empty
201
226
  ];
202
227
  if (FOOTER_MARKERS.some(m => containerText.includes(m))) continue;
203
228
 
@@ -210,17 +235,17 @@ function findEntryContainer(root) {
210
235
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
211
236
  return candidates[0]?.el;
212
237
  }
213
- `});var po={};Ue(po,{clickConnectButton:()=>Kt,default:()=>Nr,detectConnectionStatus:()=>_e,findConnectButton:()=>rt,runFunnel:()=>mo,sendConnectionRequest:()=>Qt,shouldExcludeLocation:()=>ht,viewProfile:()=>zt});async function fo(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: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function ht(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function zt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:r=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await he(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await fo(e,t));let u=0;for(let g=0;g<2;g++){let h=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(E=>window.scrollTo(0,E),h*C/6),await $(900);let k=await e.evaluate(()=>document.body.scrollHeight);if(k===u)break;u=k}await $(800);let f=await e.evaluate(()=>{let g=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"]),h=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"]),k=R=>{let D=(R||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},C={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:[]},E=document.querySelector("main");if(!E)return C;let I=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],T=Array.from(E.querySelectorAll("h2")),L=I.find(R=>{let D=R.textContent&&R.textContent.trim(),O=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!g.has(O)&&!h.has(O)}),G=L?L.textContent.trim():null,v=L?L.parentElement:null;for(;v&&v!==E&&!Array.from(v.children).filter(D=>D.tagName==="P").some(D=>{let O=D.textContent&&D.textContent.trim();return O&&O.length>5&&!k(O)});)v=v.parentElement;let _=null,A=null,M=null,q=null;if(v&&v!==E){let R=Array.from(v.children).filter(O=>O.tagName==="P").filter(O=>{let de=O.textContent&&O.textContent.trim();return de&&de.length>5&&!k(de)});if(R[0]&&(_=R[0].textContent.trim()),R[1]){let O=R[1].textContent.trim().split(/\s*[·•]\s*/);A=O[0]||null,O.length>1&&(M=O.slice(1).join(" \xB7 "))}let D=Array.from(v.children).filter(O=>O.tagName==="DIV");for(let O=D.length-1;O>=0;O--){let de=D[O].textContent&&D[O].textContent.trim();if(de&&!(G&&de.startsWith(G))&&(q=de.split(/[·•]/)[0].trim(),q))break}}let re=null;if(v){let R=v.querySelectorAll("p, span, div");for(let D of R){let O=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){re=O;break}}}let ie=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),F=j&&j.src||null,P=E.textContent||"",H=null,oe=P.match(/(\d+\+?)\s+connections\b/i);oe&&(H=oe[1]+" connections");let at=null,on=P.match(/(\d+)\s+mutual connection/i),sn=P.match(/and\s+(\d+)\s+other mutual/i),ko=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);on?at=parseInt(on[1],10):sn?at=2+parseInt(sn[1],10):ko&&(at=2);let rn=null,an=null,ln=T.find(R=>R.textContent&&R.textContent.trim()==="About");if(ln){let R=ln.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let O=D.match(/Top skills\s*(.+?)$/i);if(O){let wt=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Eo=>Eo.trim()).filter(Boolean);wt.length>0&&wt.length<10&&(an=wt)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),rn=D||null}}let cn=null,un=T.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(un){let R=un.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(cn=parseInt(D[1].replace(/,/g,""),10))}}let Co=[...new Set(T.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==G).filter(R=>g.has(R)))],Le=document.body.textContent||"",xo=/#OpenToWork\b/i.test(Le)||/\bOpen to work\b/.test(Le),_o=/#Hiring\b/i.test(Le)||/\bI'?m hiring\b/i.test(Le)||/\bWe are hiring\b/i.test(Le);return{name:G,title:_,location:q,currentCompany:A,currentSchool:M,connectionDegree:re,hasVerifiedBadge:ie,photoUrl:F,connectionsLevel:H,mutualConnectionsCount:at,followers:cn,openToWork:xo,hiring:_o,about:rn,topSkills:an,availableSections:Co}});console.log(`Viewed: ${f.name} - ${f.title}`);let d=null,m=null,y=null,p=null,b=null,w=null;if(o||s||i||a||l||r){let g=await Promise.resolve().then(()=>(uo(),co));o&&(d=await g.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(m=await g.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(y=await g.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),a&&(p=await g.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),l&&(b=await g.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${b.length} entries`)),r&&(w=await g.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...f,profileUrl:t,...d!==null&&{experience:d},...m!==null&&{featured:m},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...b!==null&&{recommendations:b},...w!==null&&{certifications:w}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function _e(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(r=>r.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),a={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!s,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:a}:s&&!i?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function rt(e){let t=null,n=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim();if(r&&!r.includes("notification"))return r;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(r=c.textContent?.trim(),r&&!r.includes("notification")))return r;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let r=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});r.count>0&&console.log(` S0: ${r.count} custom-invite links: ${JSON.stringify(r.labels)}`),t=await e.evaluateHandle(u=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=u.toLowerCase().split(" ")[0],m=null,y=null;for(let p of f){let b=p.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(d)){m=p;break}y||(y=p)}return m||y||null},n);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(n){let r=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${r}"`);let c=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let b=p.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&d.test(b)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},r);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of d){let p=y.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return y}return null},r);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,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 r=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(c)&&(console.log(` Skipping primary button: wrong person (${r})`),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 s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let r of o){let c=await e.evaluate((u,f)=>{let d=u.className.includes("muted"),m=u.className.includes("sticky-header")||u.className.includes("sticky"),y=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(u.getAttribute("aria-label")||"").toLowerCase(),b=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:y,hasInvite:b,matchesName:w,ariaLabel:p}},r,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=r;break}}for(let r of o)r!==i&&await r.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 a=null,l=await e.$$('button[id*="profile-overflow-action"]');for(let r of l){let c=await e.evaluate(u=>{let f=u.getBoundingClientRect(),d=f.width>0&&f.height>0,m=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},r);if(c.isVisible&&!c.isInStickyHeader){a=r,console.log(" Found More button by ID pattern (main)");break}}for(let r of l)r!==a&&await r.dispose().catch(()=>{});if(!a&&l.length>0&&(a=l[l.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let r=await e.evaluateHandle(()=>{let u=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),y=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!u)return null;let f=u.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==u)return m;f=f.parentElement}return null});a=r?.asElement?.()||null,a||await r?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),a),await $(500),await e.evaluate(u=>u.click(),a),await $(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let u=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let y of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});c=u?.asElement?.()||null,c||await u?.dispose?.().catch(()=>{})}if(!c){let u=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let y of m.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(r){console.log(" More dropdown click failed:",r.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let r=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(c)&&(console.log(` Skipping generic button: wrong person (${r})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Kt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),t)]),await $(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await $(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await $(3e3)):(await e.evaluate(c=>c.click(),t),await $(3e3));let a=e.url();if(a.includes("/premium/")||a.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')),r=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${r}`:` \u26A0 No modal after connect click \u2014 ${r}`),"success"}async function Or(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 $(1500);let n=await rt(e);if(n){await e.evaluate(s=>s.click(),n),await $(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Qt(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,r={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
214
- --- Connecting: ${c} ---`),l.length>0){let w=J()[t]?.location;if(ht(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),r.reason="excluded_location",r.profileInfo={location:w},r}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await he(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await fo(e,t),await $(2e3)),r.profileInfo=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","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},h=document.querySelector("main");if(!h)return g;let k=[...Array.from(h.querySelectorAll("h1")),...Array.from(h.querySelectorAll("h2"))],C=Array.from(h.querySelectorAll("h2")),E=k.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!w.has(F)&&F!=="0 notifications"}),I=E?E.textContent.trim():null,T=E?E.parentElement:null;for(;T&&T!==h&&!Array.from(T.children).filter(P=>P.tagName==="P").some(P=>{let H=P.textContent&&P.textContent.trim();return H&&H.length>5&&!S(H)});)T=T.parentElement;let L=null,G=null,v=null;if(T&&T!==h){let j=Array.from(T.children),F=j.filter(H=>H.tagName==="P").filter(H=>{let oe=H.textContent&&H.textContent.trim();return oe&&oe.length>5&&!S(oe)});F[0]&&(L=F[0].textContent.trim()),F[1]&&(G=F[1].textContent.trim());let P=j.filter(H=>H.tagName==="DIV");for(let H=P.length-1;H>=0;H--){let oe=P[H].textContent&&P[H].textContent.trim();if(oe&&!(I&&oe.startsWith(I))&&(v=oe.split(/[·•]/)[0].trim(),v))break}}let _=null;if(T){let j=T.querySelectorAll("p, span, div");for(let F of j){let P=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){_=P;break}}}let A=null,M=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(M){let j=M.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(A=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,A&&(A=A.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let q=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),re=q&&q.src||null,ie=!!h.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:I,title:L,location:v,about:A,company:G,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:re,hasVerifiedBadge:ie}}),l.length>0){let w=r.profileInfo?.location,S=J()[t]?.location,g=w||S;if(ht(g,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),r.reason="excluded_location",r;!w&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await _e(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),r.reason="pending",r;if(f==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),r.reason="connected",r;await he(e);let d=await rt(e);if(!d&&(await he(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),d=await rt(e)),!d))return console.log(" \u2717 Connect not found"),r.reason="button_not_found",r;if(r.method=d.method,await Kt(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let w=await _e(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await he(e),await $(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(h=>h.scrollIntoView({behavior:"smooth",block:"center"}),S),await $(500),await S.click().catch(()=>e.evaluate(h=>h.click(),S)),await $(2e3);let g=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await $(3e3);let h=e.url();if(h.includes("/premium/")||h.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),r.reason="premium_required",r;if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.method="more_dropdown",r.withCustomMessage=!1,r;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await $(500),r.reason="premium_required",r}catch(g){return console.log(" More dropdown failed:",g.message),await e.keyboard.press("Escape").catch(()=>{}),r.reason="premium_required",r}else return console.log(" \u2717 No More button found \u2014 Premium required"),r.reason="premium_required",r}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await $(500),r.reason="email_required",r}let p=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!p&&!b){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let g=S.querySelector('button[aria-label="Add a note"]'),h=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!h}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=S?.asElement?.()||null,p||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await $(1500),await e.$("div.modal-upsell")){let g=await Or(e);return r.success=g,r.connectionSent=g,r.reason=g?"sent_without_note_upsell":"upsell_failed",r.withCustomMessage=!1,r}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),h=o.replace("{name}",g);await S.type(h,{delay:20}),await $(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k){try{await k.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (with note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_with_note",r.withCustomMessage=!0,r.messageSent=h,r}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}else if(p&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}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 $(4e3)),await he(e),await $(500);let S=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let h of S){let k=await e.evaluate(C=>{let E=C.getBoundingClientRect();return{visible:E.width>0&&E.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},h);if(k.visible&&!k.inSticky){g=h;break}}!g&&S.length>0&&(g=S[S.length-1]);for(let h of S)h!==g&&await h.dispose().catch(()=>{});if(g)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),g),await $(500),await g.click().catch(()=>e.evaluate(k=>k.click(),g)),await $(2e3);let h=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(h){console.log(" Found Connect in More dropdown, clicking..."),r.method="more_dropdown",await e.evaluate(I=>I.click(),h),await $(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await _e(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r):(r.reason="premium_required",r);if(await _e(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;let E=await e.$('button[aria-label="Send without a note"]');if(E){console.log(" Modal appeared via More dropdown, sending without note...");try{await E.evaluate(I=>I.click())}catch{}return await $(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(h){console.log(" More dropdown fallback failed:",h.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),r.reason="modal_failed",r}catch(c){console.error(` \u2717 Error: ${c.message}`),r.reason="error",r.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return r.fatal=!0,r;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{r.fatal=!0}return r}}async function mo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:r=null,excludeLocations:c=[],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(`
238
+ `});var po={};Ue(po,{clickConnectButton:()=>Kt,default:()=>Nr,detectConnectionStatus:()=>Ee,findConnectButton:()=>rt,runFunnel:()=>mo,sendConnectionRequest:()=>Qt,shouldExcludeLocation:()=>ht,viewProfile:()=>zt});async function fo(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: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function ht(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function zt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:r=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await he(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await fo(e,t));let u=0;for(let g=0;g<2;g++){let h=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(_=>window.scrollTo(0,_),h*C/6),await $(900);let k=await e.evaluate(()=>document.body.scrollHeight);if(k===u)break;u=k}await $(800);let f=await e.evaluate(()=>{let g=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"]),h=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"]),k=R=>{let D=(R||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},C={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:[]},_=document.querySelector("main");if(!_)return C;let I=[...Array.from(_.querySelectorAll("h1")),...Array.from(_.querySelectorAll("h2"))],T=Array.from(_.querySelectorAll("h2")),L=I.find(R=>{let D=R.textContent&&R.textContent.trim(),O=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!g.has(O)&&!h.has(O)}),G=L?L.textContent.trim():null,v=L?L.parentElement:null;for(;v&&v!==_&&!Array.from(v.children).filter(D=>D.tagName==="P").some(D=>{let O=D.textContent&&D.textContent.trim();return O&&O.length>5&&!k(O)});)v=v.parentElement;let E=null,A=null,M=null,q=null;if(v&&v!==_){let R=Array.from(v.children).filter(O=>O.tagName==="P").filter(O=>{let de=O.textContent&&O.textContent.trim();return de&&de.length>5&&!k(de)});if(R[0]&&(E=R[0].textContent.trim()),R[1]){let O=R[1].textContent.trim().split(/\s*[·•]\s*/);A=O[0]||null,O.length>1&&(M=O.slice(1).join(" \xB7 "))}let D=Array.from(v.children).filter(O=>O.tagName==="DIV");for(let O=D.length-1;O>=0;O--){let de=D[O].textContent&&D[O].textContent.trim();if(de&&!(G&&de.startsWith(G))&&(q=de.split(/[·•]/)[0].trim(),q))break}}let re=null;if(v){let R=v.querySelectorAll("p, span, div");for(let D of R){let O=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){re=O;break}}}let ie=!!_.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),F=j&&j.src||null,P=_.textContent||"",H=null,oe=P.match(/(\d+\+?)\s+connections\b/i);oe&&(H=oe[1]+" connections");let at=null,on=P.match(/(\d+)\s+mutual connection/i),sn=P.match(/and\s+(\d+)\s+other mutual/i),ko=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);on?at=parseInt(on[1],10):sn?at=2+parseInt(sn[1],10):ko&&(at=2);let rn=null,an=null,ln=T.find(R=>R.textContent&&R.textContent.trim()==="About");if(ln){let R=ln.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let O=D.match(/Top skills\s*(.+?)$/i);if(O){let wt=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(_o=>_o.trim()).filter(Boolean);wt.length>0&&wt.length<10&&(an=wt)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),rn=D||null}}let cn=null,un=T.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(un){let R=un.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(cn=parseInt(D[1].replace(/,/g,""),10))}}let Co=[...new Set(T.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==G).filter(R=>g.has(R)))],Le=document.body.textContent||"",xo=/#OpenToWork\b/i.test(Le)||/\bOpen to work\b/.test(Le),Eo=/#Hiring\b/i.test(Le)||/\bI'?m hiring\b/i.test(Le)||/\bWe are hiring\b/i.test(Le);return{name:G,title:E,location:q,currentCompany:A,currentSchool:M,connectionDegree:re,hasVerifiedBadge:ie,photoUrl:F,connectionsLevel:H,mutualConnectionsCount:at,followers:cn,openToWork:xo,hiring:Eo,about:rn,topSkills:an,availableSections:Co}});console.log(`Viewed: ${f.name} - ${f.title}`);let d=null,m=null,y=null,p=null,b=null,w=null;if(o||s||i||a||l||r){let g=await Promise.resolve().then(()=>(uo(),co));o&&(d=await g.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(m=await g.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),i&&(y=await g.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),a&&(p=await g.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),l&&(b=await g.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${b.length} entries`)),r&&(w=await g.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...f,profileUrl:t,...d!==null&&{experience:d},...m!==null&&{featured:m},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...b!==null&&{recommendations:b},...w!==null&&{certifications:w}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function Ee(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(r=>r.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),a={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!s,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:a}:s&&!i?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function rt(e){let t=null,n=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim();if(r&&!r.includes("notification"))return r;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(r=c.textContent?.trim(),r&&!r.includes("notification")))return r;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let r=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});r.count>0&&console.log(` S0: ${r.count} custom-invite links: ${JSON.stringify(r.labels)}`),t=await e.evaluateHandle(u=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=u.toLowerCase().split(" ")[0],m=null,y=null;for(let p of f){let b=p.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(d)){m=p;break}y||(y=p)}return m||y||null},n);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(n){let r=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${r}"`);let c=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let b=p.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&d.test(b)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},r);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of d){let p=y.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return y}return null},r);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,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 r=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(c)&&(console.log(` Skipping primary button: wrong person (${r})`),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 s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let r of o){let c=await e.evaluate((u,f)=>{let d=u.className.includes("muted"),m=u.className.includes("sticky-header")||u.className.includes("sticky"),y=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(u.getAttribute("aria-label")||"").toLowerCase(),b=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:y,hasInvite:b,matchesName:w,ariaLabel:p}},r,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=r;break}}for(let r of o)r!==i&&await r.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 a=null,l=await e.$$('button[id*="profile-overflow-action"]');for(let r of l){let c=await e.evaluate(u=>{let f=u.getBoundingClientRect(),d=f.width>0&&f.height>0,m=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},r);if(c.isVisible&&!c.isInStickyHeader){a=r,console.log(" Found More button by ID pattern (main)");break}}for(let r of l)r!==a&&await r.dispose().catch(()=>{});if(!a&&l.length>0&&(a=l[l.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let r=await e.evaluateHandle(()=>{let u=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),y=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!u)return null;let f=u.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==u)return m;f=f.parentElement}return null});a=r?.asElement?.()||null,a||await r?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),a),await $(500),await e.evaluate(u=>u.click(),a),await $(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let u=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let y of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});c=u?.asElement?.()||null,c||await u?.dispose?.().catch(()=>{})}if(!c){let u=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let y of m.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(r){console.log(" More dropdown click failed:",r.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let r=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(c)&&(console.log(` Skipping generic button: wrong person (${r})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Kt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),t)]),await $(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await $(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await $(3e3)):(await e.evaluate(c=>c.click(),t),await $(3e3));let a=e.url();if(a.includes("/premium/")||a.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')),r=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${r}`:` \u26A0 No modal after connect click \u2014 ${r}`),"success"}async function Or(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 $(1500);let n=await rt(e);if(n){await e.evaluate(s=>s.click(),n),await $(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Qt(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,r={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
+ --- Connecting: ${c} ---`),l.length>0){let w=J()[t]?.location;if(ht(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),r.reason="excluded_location",r.profileInfo={location:w},r}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await he(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await fo(e,t),await $(2e3)),r.profileInfo=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","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},h=document.querySelector("main");if(!h)return g;let k=[...Array.from(h.querySelectorAll("h1")),...Array.from(h.querySelectorAll("h2"))],C=Array.from(h.querySelectorAll("h2")),_=k.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!w.has(F)&&F!=="0 notifications"}),I=_?_.textContent.trim():null,T=_?_.parentElement:null;for(;T&&T!==h&&!Array.from(T.children).filter(P=>P.tagName==="P").some(P=>{let H=P.textContent&&P.textContent.trim();return H&&H.length>5&&!S(H)});)T=T.parentElement;let L=null,G=null,v=null;if(T&&T!==h){let j=Array.from(T.children),F=j.filter(H=>H.tagName==="P").filter(H=>{let oe=H.textContent&&H.textContent.trim();return oe&&oe.length>5&&!S(oe)});F[0]&&(L=F[0].textContent.trim()),F[1]&&(G=F[1].textContent.trim());let P=j.filter(H=>H.tagName==="DIV");for(let H=P.length-1;H>=0;H--){let oe=P[H].textContent&&P[H].textContent.trim();if(oe&&!(I&&oe.startsWith(I))&&(v=oe.split(/[·•]/)[0].trim(),v))break}}let E=null;if(T){let j=T.querySelectorAll("p, span, div");for(let F of j){let P=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){E=P;break}}}let A=null,M=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(M){let j=M.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(A=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,A&&(A=A.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let q=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),re=q&&q.src||null,ie=!!h.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:I,title:L,location:v,about:A,company:G,connectionDegree:E,connectionsCount:null,mutualConnections:null,photoUrl:re,hasVerifiedBadge:ie}}),l.length>0){let w=r.profileInfo?.location,S=J()[t]?.location,g=w||S;if(ht(g,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),r.reason="excluded_location",r;!w&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await Ee(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),r.reason="pending",r;if(f==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),r.reason="connected",r;await he(e);let d=await rt(e);if(!d&&(await he(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),d=await rt(e)),!d))return console.log(" \u2717 Connect not found"),r.reason="button_not_found",r;if(r.method=d.method,await Kt(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let w=await Ee(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await he(e),await $(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(h=>h.scrollIntoView({behavior:"smooth",block:"center"}),S),await $(500),await S.click().catch(()=>e.evaluate(h=>h.click(),S)),await $(2e3);let g=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await $(3e3);let h=e.url();if(h.includes("/premium/")||h.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),r.reason="premium_required",r;if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.method="more_dropdown",r.withCustomMessage=!1,r;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await $(500),r.reason="premium_required",r}catch(g){return console.log(" More dropdown failed:",g.message),await e.keyboard.press("Escape").catch(()=>{}),r.reason="premium_required",r}else return console.log(" \u2717 No More button found \u2014 Premium required"),r.reason="premium_required",r}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await $(500),r.reason="email_required",r}let p=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!p&&!b){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let g=S.querySelector('button[aria-label="Add a note"]'),h=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!h}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=S?.asElement?.()||null,p||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await $(1500),await e.$("div.modal-upsell")){let g=await Or(e);return r.success=g,r.connectionSent=g,r.reason=g?"sent_without_note_upsell":"upsell_failed",r.withCustomMessage=!1,r}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),h=o.replace("{name}",g);await S.type(h,{delay:20}),await $(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k){try{await k.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (with note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_with_note",r.withCustomMessage=!0,r.messageSent=h,r}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}else if(p&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}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 $(4e3)),await he(e),await $(500);let S=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let h of S){let k=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},h);if(k.visible&&!k.inSticky){g=h;break}}!g&&S.length>0&&(g=S[S.length-1]);for(let h of S)h!==g&&await h.dispose().catch(()=>{});if(g)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),g),await $(500),await g.click().catch(()=>e.evaluate(k=>k.click(),g)),await $(2e3);let h=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(h){console.log(" Found Connect in More dropdown, clicking..."),r.method="more_dropdown",await e.evaluate(I=>I.click(),h),await $(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await Ee(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r):(r.reason="premium_required",r);if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;let _=await e.$('button[aria-label="Send without a note"]');if(_){console.log(" Modal appeared via More dropdown, sending without note...");try{await _.evaluate(I=>I.click())}catch{}return await $(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(h){console.log(" More dropdown fallback failed:",h.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),r.reason="modal_failed",r}catch(c){console.error(` \u2717 Error: ${c.message}`),r.reason="error",r.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return r.fatal=!0,r;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{r.fatal=!0}return r}}async function mo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:r=null,excludeLocations:c=[],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(`
215
240
  === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${a?"View Only":`Connect (max ${i})`}`),a||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!a){let m=ze();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 y=t[m];try{if(e.isClosed()){console.log(`
216
241
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
217
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let p=$n(y.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,r&&await r(y,f,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let b=null;if(a){let w=await zt(e,y.profileUrl);w?(be(y.profileUrl,{...w,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=En();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await Qt(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:c}),b.success)f.connectionsSent++,b.connectionSent&&xn(y.profileUrl,u);else switch(b.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(b?.fatal){console.log(`
242
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let p=$n(y.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,r&&await r(y,f,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let b=null;if(a){let w=await zt(e,y.profileUrl);w?(be(y.profileUrl,{...w,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=_n();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await Qt(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:c}),b.success)f.connectionsSent++,b.connectionSent&&xn(y.profileUrl,u);else switch(b.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(b?.fatal){console.log(`
218
243
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(b?.reason==="error"){if(d++,d>=3){console.log(`
219
244
  \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(b&&b.reason&&(kn(y.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),vn(y.profileUrl,{source:u||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:b.reason})),r&&await r(y,f,b),m<t.length-1){let w=l+Math.random()*2e3;await $(w)}}if(console.log(`
220
- === 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}`),!a){let m=ze();console.log(` Quota remaining: today ${m.daily.remaining}/${m.daily.max} | week ${m.weekly.remaining}/${m.weekly.max}`)}return f}var Nr,go=Fe(async()=>{Ae();await Ke();Nr={viewProfile:zt,detectConnectionStatus:_e,findConnectButton:rt,clickConnectButton:Kt,sendConnectionRequest:Qt,runFunnel:mo,shouldExcludeLocation:ht}});Ae();await Ke();import"dotenv/config";import*as ve from"fs";import*as K from"path";import{fileURLToPath as Go}from"url";var zo=Go(import.meta.url),Ko=K.dirname(K.dirname(zo)),et=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(Ko,"market-research"),Qo=K.join(et,"scouted-jobs.json"),Zo=K.join(et,"discovered-people.json"),Xo=K.join(et,"visit-log.json"),gi=K.join(et,"companies.json"),es=K.join(et,"job-decisions.json");function ct(e){try{if(ve.existsSync(e))return JSON.parse(ve.readFileSync(e,"utf-8"))}catch{}return null}function Rn(){Qe=null,Ze=null,Xe=null,ns=null,Se=null}var Qe=null;function Et(){return Qe||(Qe=ct(Qo)||{},Qe)}var Ze=null;function Dn(){return Ze||(Ze=ct(es)||{},Ze)}var Xe=null;function ts(){return Xe||(Xe=ct(Zo)||{},Xe)}var ns=null;var Se=null;function os(){return Se||(Se=ct(Xo)||{visits:[]},Array.isArray(Se.visits)||(Se.visits=[]),Se)}function In(){let e=Et(),t=ts(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),a={};for(let d of n)for(let m of d.techStack||[])a[m]=(a[m]||0)+1;let l=Object.entries(a).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),r=os(),c=new Date().toISOString().slice(0,10),u=r.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(r.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:l,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}await Ke();var ss=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),rs=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Mn=["vancouver","british columbia"],is=["canada","montreal","quebec","alberta","calgary","ottawa"],as=["toronto","ontario"],ls=["india","pakistan","nigeria","philippines"];function cs(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)ss.has(u)&&s++,rs.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=us(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let a=(e.location||"").toLowerCase(),l=/remote/i.test(a)||e.workplaceType==="remote";ls.some(u=>a.includes(u))?n-=30:l&&/united states|usa|\bus\b/i.test(a)?n+=25:l&&Mn.some(u=>a.includes(u))?n+=22:l?n+=20:Mn.some(u=>a.includes(u))?n+=18:is.some(u=>a.includes(u))?n+=10:as.some(u=>a.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let r=(e.seniority||"").toLowerCase();r.includes("senior")||r.includes("lead")||r.includes("staff")?n+=10:r.includes("mid")?n+=5:(r.includes("entry")||r.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let c=new Set(e.jobTags||[]);return c.has("managerial")?n+=8:c.has("senior-ic")&&(n+=5),c.has("junior")&&(n-=15),c.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function On(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=Et(),s=J(),i=new Set,a=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let l={connectedRecruiters:i,conversationRecruiters:a},r=Dn(),c=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=r[f];return!(m&&c.has(m.status))}).map(([f,d])=>({jobId:f,score:cs(d,l),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function us(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await He();import ps from"puppeteer";import{addExtra as gs}from"puppeteer-extra";import hs from"puppeteer-extra-plugin-stealth";Ae();await He();import Nn from"fs";import ds from"path";var fs="cookies.json";function ms(){let e=process.env.ILML_SCOPE_DIR;return e?ds.join(e,"plugins-state","linkedin","cookies.json"):fs}function ut(){let e=ms();if(!Nn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Nn.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}var Ln=gs(ps);Ln.use(hs());async function Fn(){let e=await Ln.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
245
+ === 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}`),!a){let m=ze();console.log(` Quota remaining: today ${m.daily.remaining}/${m.daily.max} | week ${m.weekly.remaining}/${m.weekly.max}`)}return f}var Nr,go=Fe(async()=>{Ae();await Ke();Nr={viewProfile:zt,detectConnectionStatus:Ee,findConnectButton:rt,clickConnectButton:Kt,sendConnectionRequest:Qt,runFunnel:mo,shouldExcludeLocation:ht}});Ae();await Ke();import"dotenv/config";import*as ve from"fs";import*as K from"path";import{fileURLToPath as Go}from"url";var zo=Go(import.meta.url),Ko=K.dirname(K.dirname(zo)),et=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(Ko,"market-research"),Qo=K.join(et,"scouted-jobs.json"),Zo=K.join(et,"discovered-people.json"),Xo=K.join(et,"visit-log.json"),gi=K.join(et,"companies.json"),es=K.join(et,"job-decisions.json");function ct(e){try{if(ve.existsSync(e))return JSON.parse(ve.readFileSync(e,"utf-8"))}catch{}return null}function Rn(){Qe=null,Ze=null,Xe=null,ns=null,Se=null}var Qe=null;function _t(){return Qe||(Qe=ct(Qo)||{},Qe)}var Ze=null;function Dn(){return Ze||(Ze=ct(es)||{},Ze)}var Xe=null;function ts(){return Xe||(Xe=ct(Zo)||{},Xe)}var ns=null;var Se=null;function os(){return Se||(Se=ct(Xo)||{visits:[]},Array.isArray(Se.visits)||(Se.visits=[]),Se)}function In(){let e=_t(),t=ts(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),a={};for(let d of n)for(let m of d.techStack||[])a[m]=(a[m]||0)+1;let l=Object.entries(a).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),r=os(),c=new Date().toISOString().slice(0,10),u=r.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(r.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:l,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}await Ke();var ss=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),rs=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Mn=["vancouver","british columbia"],is=["canada","montreal","quebec","alberta","calgary","ottawa"],as=["toronto","ontario"],ls=["india","pakistan","nigeria","philippines"];function cs(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)ss.has(u)&&s++,rs.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=us(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let a=(e.location||"").toLowerCase(),l=/remote/i.test(a)||e.workplaceType==="remote";ls.some(u=>a.includes(u))?n-=30:l&&/united states|usa|\bus\b/i.test(a)?n+=25:l&&Mn.some(u=>a.includes(u))?n+=22:l?n+=20:Mn.some(u=>a.includes(u))?n+=18:is.some(u=>a.includes(u))?n+=10:as.some(u=>a.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let r=(e.seniority||"").toLowerCase();r.includes("senior")||r.includes("lead")||r.includes("staff")?n+=10:r.includes("mid")?n+=5:(r.includes("entry")||r.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let c=new Set(e.jobTags||[]);return c.has("managerial")?n+=8:c.has("senior-ic")&&(n+=5),c.has("junior")&&(n-=15),c.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function On(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=_t(),s=J(),i=new Set,a=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let l={connectedRecruiters:i,conversationRecruiters:a},r=Dn(),c=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=r[f];return!(m&&c.has(m.status))}).map(([f,d])=>({jobId:f,score:cs(d,l),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function us(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await He();import ps from"puppeteer";import{addExtra as gs}from"puppeteer-extra";import hs from"puppeteer-extra-plugin-stealth";Ae();await He();import Nn from"fs";import ds from"path";var fs="cookies.json";function ms(){let e=process.env.ILML_SCOPE_DIR;return e?ds.join(e,"plugins-state","linkedin","cookies.json"):fs}function ut(){let e=ms();if(!Nn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Nn.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}var Ln=gs(ps);Ln.use(hs());async function Fn(){let e=await Ln.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
221
246
  Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=ut();await n.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
222
247
  [!] ${o.message}
223
- `),await e.close(),process.exit(1)}return{browser:e,page:n}}async function At(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await $(3e3)}console.log(" Inbox loaded.")}async function Un(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let a=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!a)continue;let r=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(r)||/^\s*Promoted\b/i.test(r))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(r.startsWith("You:"))d="me",m=r.slice(4).trim();else{let p=a.split(" ")[0];if(r.startsWith(a+":")||r.startsWith(p+":")){d="them";let b=r.indexOf(":");m=r.slice(b+1).trim()}else d="them",m=r}let y=s.getBoundingClientRect();o.push({name:a,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=St(n.lastMessageTime)||n.lastMessageTime;return t}async function Tt(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function ys(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let a=i.textContent?.trim()?.replace(/\s+/g," ");if(a&&a.length>1&&a.length<100&&!t.test(a))return a}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function Rt(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function jn(e,t){let n=await ys(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(l=>i.includes(l)),headerName:n}}async function dt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:r,headerName:c}=await jn(e,t);if(r)return await $(500),{verified:!0,headerName:c};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await $(300),{verified:!0,headerName:n};await $(s),i+=s}let{match:a,headerName:l}=await jn(e,t);return a?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function ws(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let a=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!a){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(a=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!a)return{found:!1};let l=a.querySelectorAll("li.msg-s-message-list__event").length;return a.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(a.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!i.found||i.atTop)break;if(await $(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function Dt(e,{scrollUp:t=!0}={}){t&&await ws(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let a=i.querySelectorAll("li.msg-s-message-list__event");if(a.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(a=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let p=Number(y[1]);if(p>14200704e5&&p<20512224e5)return p}catch{}return null}let r="";function c(u,f,d){let m=l(u),p=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let w=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let S=m?new Date(m).toISOString():d?`${d} ${p}`.trim():p;return{sender:f,text:w,time:S}}for(let u of a){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(r=f.textContent?.trim()||r);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let p=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=c(w,p,r);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let y of m){let p=y.querySelector(".msg-s-message-group__name");p&&(s=p.textContent?.trim()||s);let w=c(y,s||"Unknown",r);w&&o.push(w)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=St(o.time)||o.time);return n}function It(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=[...new Set(e.map(c=>c.sender).filter(c=>c&&c!=="Unknown"))],a=i.some(c=>{let u=c.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),l=z.toLowerCase().split(/\s+/),r=i.every(c=>{let u=c.toLowerCase();return l.some(f=>u.includes(f))});if(a)return!0;if(r){for(let c of e){let f=(c.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(y=>y===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let c=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return c.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Oe(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Mt(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Oe(d.sender)+"||"+Oe(d.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Te.has(d.status)?!1:!o.has(n(d))),a=t.filter(d=>!s.has(n(d))),l=t.filter(d=>s.has(n(d))),r=e.filter(d=>Te.has(d.status)),c=[...i,...l,...a],u=[];for(let d of c){let m=Oe(d.text),y=Oe(d.sender),p=!1;for(let b=0;b<u.length;b++){let w=u[b];if(Oe(w.sender)!==y)continue;let S=Oe(w.text);if(m.length>S.length&&m.endsWith(S)){p=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=d,p=!0;break}}p||u.push(d)}return[...u,...r]}async function qn(e,t){await At(e),await $(2500),await e.evaluate(()=>{let l=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let r of l){let c=document.querySelector(r);if(c){c.scrollTop=0;return}}}),await $(500);async function n(){return e.evaluate(l=>{let r=document.querySelectorAll(".msg-conversation-listitem");for(let c of r)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===l){let d=c.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,a=0;for(let l=0;l<s&&!o;l++){let r=await Tt(e);if(!r)break;if(r.scrollTop===i){if(a++,a>=2)break}else a=0,i=r.scrollTop;await $(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await $(3e3),dt(e,t)):{verified:!1,headerName:null}}async function Ot(e,t){let n=await e.evaluate(a=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let r of l)if(r.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===a){let f=r.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await $(3e3);let a=await dt(e,t);if(a.verified)return a}let o=fn(t),s=o!==t?[t,o]:[t];for(let a of s)if(await Pn(e,a,t)){let r=await dt(e,t);if(r.verified)return r}let i=mn(o);if(i!==o&&i.length>0&&await Pn(e,i,t,{requireUnique:!0})){let l=await dt(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Pn(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await $(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await $(300),await i.type(t,{delay:30}),await $(500),await e.keyboard.press("Enter"),await $(3500);let a=await e.evaluate((l,r)=>{let c=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let p of f){let w=p.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(c)){let g=p.getBoundingClientRect();if(g.height>0){let h=w.includes(",")||/\d+ other/.test(w),k=S===u?3:S.includes(u)?2:1,C={text:w,isGroup:h,score:k,x:g.x+g.width/2,y:g.y+g.height/2};h?m.push(C):d.push(C)}}}d.sort((p,b)=>b.score-p.score);let y=[...d,...m];return r&&y.length!==1?null:d[0]||m[0]||null},n,s);return a?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(a.x,a.y),!0):!1}async function me(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await $(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await $(1e3))}await He();function jt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(r=>!Te.has(r.status)),i=_s(t,e.profileUrl,n),a=Pt(s,t);if(e.lastMessageBy=a,e.conversationStatus=a==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let r=bs(s,t,i);r&&(e.category=r,e.categorySource=e.categorySource||"message_content")}if(e.situation=Ss(s,a,t),s.length>0){let r=s[s.length-1];e.lastMessageTime=r.time}if(s.length>0&&!e.initiatedBy){let r=s[0];r.sender===z?e.initiatedBy="us":r.sender!=="Unknown"&&r.sender!==""&&(e.initiatedBy="them")}e.engagement=Vn(s,t),e.personContext=Cs(i),e.summary=vs(e,t,i),e.autoTags=$s(e,t,i);let l=ks(e);return e.actionNeeded=l.action,e.actionDetail=l.detail,e.suggestedPriority=xs(e),e}var Hn={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]}};function bs(e,t,n){if(!e||e.length===0)return n?.title?Nt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(Hn))if(i.theirMessages){for(let a of i.theirMessages)if(a.test(o))return s}if(n?.title){let s=Nt(n.title);if(s)return s}return null}function Nt(e){if(!e)return null;for(let[t,n]of Object.entries(Hn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}var Bn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i;function Ss(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 Bn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return Bn.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Pt(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function vs(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,a=n?.title,l=n?.company,r=n?.location;i==="recruiter"&&l?s.push(`Recruiter from ${l}`):i==="hiring_manager"&&l?s.push(`Hiring manager at ${l}`):i==="founder"&&l?s.push(`Founder of ${l}`):i&&a?s.push(`${Lt(i)}: ${Ne(a,40)}`):a?s.push(Ne(a,50)):s.push(t.split(" ")[0]);let c=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),u=Es(c),f=As(c),d=Ts(c),m=[];return u&&m.push(u),d&&d!==r&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function $s(e,t,n){let o=[],s=(e.messages||[]).filter(c=>!Te.has(c.status)),i=s.map(c=>c.text).join(" "),a=s.filter(c=>c.sender!==z&&c.sender!=="Unknown").map(c=>c.text).join(" "),l=Jn(a,n?.location);o.push(...l),/\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 r=e.engagement||Vn(s,t);return r.messageCount>=6&&o.push("active-thread"),r.theirCount===0&&r.ourCount>0&&o.push("no-response"),r.ourCount===0&&r.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(c=>Be.has(c.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"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let a of o)i.includes(a)&&n.push(a.replace(/\s+/g,"-"));for(let[a,l]of s)i.includes(a)&&n.push(l);return n}function ks(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 s=(e.messages||[]).find(i=>Be.has(i.status));return s?s.status===V.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:`${Lt(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 Vn(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,s=0,i=!1,a=!1,l=e.map(r=>r.text).join(" ");for(let r of e)r.sender===z?n++:r.sender==="Unknown"||r.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(l),a=/\$[\d,]+|\d+k|\d+\/hr/i.test(l),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:a}}function Cs(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function xs(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 _s(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function tt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Lt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ne(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Es(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 As(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 Ts(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 Wn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Nt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Rs(e),e.personSummary=Ds(e),e.personAutoTags=Is(e);let n=Ms(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Os(e)),e}function Rs(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 Ds(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ne(o,40)} at ${Ne(s,30)}`):o?t.push(Ne(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let a=new Date(e.connectionDate);if(!isNaN(a)){let l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${l[a.getMonth()]} ${a.getDate()}`)}}if(e.jobCount>0){let a=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(a+=` (last: ${Ne(e.lastJobTitle,30)}`,e.lastJobDate){let l=new Date(e.lastJobDate);isNaN(l)||(a+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][l.getMonth()]} ${l.getDate()}`)}a+=")"}t.push(a)}return t.join(". ").replace(/\.\./g,".")||null}function Is(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 Ms(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:`${Lt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Os(e){let t=e.category;if(!t)return null;let n=Ns(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 Ns(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}import"dotenv/config";import*as X from"fs";import*as pe from"path";import{fileURLToPath as qs}from"url";import"dotenv/config";import{createGraphClient as js,resolveToken as Ps}from"@ilivemylife/graph-sdk";import{config as Ls}from"dotenv";Ls();var Yn=Ps()||process.env.TOKEN;Yn||(console.error(`
248
+ `),await e.close(),process.exit(1)}return{browser:e,page:n}}async function At(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await $(3e3)}console.log(" Inbox loaded.")}async function Un(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let a=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!a)continue;let r=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(r)||/^\s*Promoted\b/i.test(r))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(r.startsWith("You:"))d="me",m=r.slice(4).trim();else{let p=a.split(" ")[0];if(r.startsWith(a+":")||r.startsWith(p+":")){d="them";let b=r.indexOf(":");m=r.slice(b+1).trim()}else d="them",m=r}let y=s.getBoundingClientRect();o.push({name:a,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=St(n.lastMessageTime)||n.lastMessageTime;return t}async function Tt(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function ys(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let a=i.textContent?.trim()?.replace(/\s+/g," ");if(a&&a.length>1&&a.length<100&&!t.test(a))return a}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function Rt(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function jn(e,t){let n=await ys(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(l=>i.includes(l)),headerName:n}}async function dt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:r,headerName:c}=await jn(e,t);if(r)return await $(500),{verified:!0,headerName:c};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await $(300),{verified:!0,headerName:n};await $(s),i+=s}let{match:a,headerName:l}=await jn(e,t);return a?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function ws(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let a=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!a){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(a=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!a)return{found:!1};let l=a.querySelectorAll("li.msg-s-message-list__event").length;return a.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(a.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!i.found||i.atTop)break;if(await $(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function Dt(e,{scrollUp:t=!0}={}){t&&await ws(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let a=i.querySelectorAll("li.msg-s-message-list__event");if(a.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(a=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let p=Number(y[1]);if(p>14200704e5&&p<20512224e5)return p}catch{}return null}let r="";function c(u,f,d){let m=l(u),p=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let w=b.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let S=m?new Date(m).toISOString():d?`${d} ${p}`.trim():p;return{sender:f,text:w,time:S}}for(let u of a){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(r=f.textContent?.trim()||r);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let p=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=c(w,p,r);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let y of m){let p=y.querySelector(".msg-s-message-group__name");p&&(s=p.textContent?.trim()||s);let w=c(y,s||"Unknown",r);w&&o.push(w)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=St(o.time)||o.time);return n}function It(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=[...new Set(e.map(c=>c.sender).filter(c=>c&&c!=="Unknown"))],a=i.some(c=>{let u=c.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),l=z.toLowerCase().split(/\s+/),r=i.every(c=>{let u=c.toLowerCase();return l.some(f=>u.includes(f))});if(a)return!0;if(r){for(let c of e){let f=(c.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(y=>y===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let c=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return c.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Oe(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Mt(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Oe(d.sender)+"||"+Oe(d.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Te.has(d.status)?!1:!o.has(n(d))),a=t.filter(d=>!s.has(n(d))),l=t.filter(d=>s.has(n(d))),r=e.filter(d=>Te.has(d.status)),c=[...i,...l,...a],u=[];for(let d of c){let m=Oe(d.text),y=Oe(d.sender),p=!1;for(let b=0;b<u.length;b++){let w=u[b];if(Oe(w.sender)!==y)continue;let S=Oe(w.text);if(m.length>S.length&&m.endsWith(S)){p=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=d,p=!0;break}}p||u.push(d)}return[...u,...r]}async function qn(e,t){await At(e),await $(2500),await e.evaluate(()=>{let l=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let r of l){let c=document.querySelector(r);if(c){c.scrollTop=0;return}}}),await $(500);async function n(){return e.evaluate(l=>{let r=document.querySelectorAll(".msg-conversation-listitem");for(let c of r)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===l){let d=c.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,a=0;for(let l=0;l<s&&!o;l++){let r=await Tt(e);if(!r)break;if(r.scrollTop===i){if(a++,a>=2)break}else a=0,i=r.scrollTop;await $(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await $(3e3),dt(e,t)):{verified:!1,headerName:null}}async function Ot(e,t){let n=await e.evaluate(a=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let r of l)if(r.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===a){let f=r.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await $(3e3);let a=await dt(e,t);if(a.verified)return a}let o=fn(t),s=o!==t?[t,o]:[t];for(let a of s)if(await Pn(e,a,t)){let r=await dt(e,t);if(r.verified)return r}let i=mn(o);if(i!==o&&i.length>0&&await Pn(e,i,t,{requireUnique:!0})){let l=await dt(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Pn(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await $(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await $(300),await i.type(t,{delay:30}),await $(500),await e.keyboard.press("Enter"),await $(3500);let a=await e.evaluate((l,r)=>{let c=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let p of f){let w=p.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(c)){let g=p.getBoundingClientRect();if(g.height>0){let h=w.includes(",")||/\d+ other/.test(w),k=S===u?3:S.includes(u)?2:1,C={text:w,isGroup:h,score:k,x:g.x+g.width/2,y:g.y+g.height/2};h?m.push(C):d.push(C)}}}d.sort((p,b)=>b.score-p.score);let y=[...d,...m];return r&&y.length!==1?null:d[0]||m[0]||null},n,s);return a?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(a.x,a.y),!0):!1}async function me(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await $(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await $(1e3))}await He();function jt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(r=>!Te.has(r.status)),i=Es(t,e.profileUrl,n),a=Pt(s,t);if(e.lastMessageBy=a,e.conversationStatus=a==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let r=bs(s,t,i);r&&(e.category=r,e.categorySource=e.categorySource||"message_content")}if(e.situation=Ss(s,a,t),s.length>0){let r=s[s.length-1];e.lastMessageTime=r.time}if(s.length>0&&!e.initiatedBy){let r=s[0];r.sender===z?e.initiatedBy="us":r.sender!=="Unknown"&&r.sender!==""&&(e.initiatedBy="them")}e.engagement=Vn(s,t),e.personContext=Cs(i),e.summary=vs(e,t,i),e.autoTags=$s(e,t,i);let l=ks(e);return e.actionNeeded=l.action,e.actionDetail=l.detail,e.suggestedPriority=xs(e),e}var Hn={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]}};function bs(e,t,n){if(!e||e.length===0)return n?.title?Nt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(Hn))if(i.theirMessages){for(let a of i.theirMessages)if(a.test(o))return s}if(n?.title){let s=Nt(n.title);if(s)return s}return null}function Nt(e){if(!e)return null;for(let[t,n]of Object.entries(Hn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}var Bn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i;function Ss(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 Bn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return Bn.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Pt(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function vs(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,a=n?.title,l=n?.company,r=n?.location;i==="recruiter"&&l?s.push(`Recruiter from ${l}`):i==="hiring_manager"&&l?s.push(`Hiring manager at ${l}`):i==="founder"&&l?s.push(`Founder of ${l}`):i&&a?s.push(`${Lt(i)}: ${Ne(a,40)}`):a?s.push(Ne(a,50)):s.push(t.split(" ")[0]);let c=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),u=_s(c),f=As(c),d=Ts(c),m=[];return u&&m.push(u),d&&d!==r&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function $s(e,t,n){let o=[],s=(e.messages||[]).filter(c=>!Te.has(c.status)),i=s.map(c=>c.text).join(" "),a=s.filter(c=>c.sender!==z&&c.sender!=="Unknown").map(c=>c.text).join(" "),l=Jn(a,n?.location);o.push(...l),/\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 r=e.engagement||Vn(s,t);return r.messageCount>=6&&o.push("active-thread"),r.theirCount===0&&r.ourCount>0&&o.push("no-response"),r.ourCount===0&&r.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(c=>Be.has(c.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"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let a of o)i.includes(a)&&n.push(a.replace(/\s+/g,"-"));for(let[a,l]of s)i.includes(a)&&n.push(l);return n}function ks(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 s=(e.messages||[]).find(i=>Be.has(i.status));return s?s.status===V.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:`${Lt(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 Vn(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,s=0,i=!1,a=!1,l=e.map(r=>r.text).join(" ");for(let r of e)r.sender===z?n++:r.sender==="Unknown"||r.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(l),a=/\$[\d,]+|\d+k|\d+\/hr/i.test(l),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:a}}function Cs(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function xs(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 Es(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function tt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Lt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ne(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function _s(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 As(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 Ts(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 Wn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Nt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Rs(e),e.personSummary=Ds(e),e.personAutoTags=Is(e);let n=Ms(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Os(e)),e}function Rs(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 Ds(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ne(o,40)} at ${Ne(s,30)}`):o?t.push(Ne(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let a=new Date(e.connectionDate);if(!isNaN(a)){let l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${l[a.getMonth()]} ${a.getDate()}`)}}if(e.jobCount>0){let a=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(a+=` (last: ${Ne(e.lastJobTitle,30)}`,e.lastJobDate){let l=new Date(e.lastJobDate);isNaN(l)||(a+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][l.getMonth()]} ${l.getDate()}`)}a+=")"}t.push(a)}return t.join(". ").replace(/\.\./g,".")||null}function Is(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 Ms(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:`${Lt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Os(e){let t=e.category;if(!t)return null;let n=Ns(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 Ns(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}import"dotenv/config";import*as X from"fs";import*as pe from"path";import{fileURLToPath as qs}from"url";import"dotenv/config";import{createGraphClient as js,resolveToken as Ps}from"@ilivemylife/graph-sdk";import{config as Ls}from"dotenv";Ls();var Yn=Ps()||process.env.TOKEN;Yn||(console.error(`
224
249
  [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.
225
250
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
226
251
  `),console.error(` Or add ILML_TOKEN=... to .env
@@ -261,15 +286,15 @@ ${o.join(`
261
286
  Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,a=`.pre-${i}.backup`;try{oo(ke,s.version),oo(Ce,s.version)}catch(r){console.error(`
262
287
  [FATAL] Pre-migration backup failed for ${i}: ${r.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
263
288
  `),process.exit(1)}let l=s.module;try{await l.up(ke,Ce)}catch(r){console.error(`
264
- [FATAL] Migration ${i} failed: ${r.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let c=_r(a);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
289
+ [FATAL] Migration ${i} failed: ${r.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let c=Er(a);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
265
290
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${a} files back over the originals.
266
291
  `))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${a} files back over the originals.
267
292
  `)}process.exit(1)}try{let r=new Date().toISOString(),c={version:s.version,name:l.NAME||i,appliedAt:r},u=no();u.version=s.version,u.migratedAt=r,u.migrations=u.migrations||[],u.migrations.push(c),br(u)}catch(r){console.error(`
268
293
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${r.message}`),console.error(` Your data is in the v${s.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.
269
294
  `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{bn()}catch{}try{Rn()}catch{}Wt=!0,Gt(),console.log(`
270
295
  \u2713 Schema is now at v${ge}
271
- `)}var Sr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function vr(e){let t=e.toLowerCase();return Sr.some(n=>n.test(t))}var $r=6e4;function kr(){let e=Date.now(),t=[];for(let n of[se,ke,Ce]){if(!x.existsSync(n))continue;let o;try{o=x.readdirSync(n)}catch{continue}for(let s of o){if(!vr(s))continue;let i=N.join(n,s);try{let a=x.statSync(i);if(!a.isFile()||e-a.mtimeMs<$r)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Cr({verbose:e=!1}={}){let t=kr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{x.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${N.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function xr(){let e=[];for(let t of[ke,Ce]){if(!x.existsSync(t))continue;let n=x.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=N.join(t,o);try{gt(s)}catch(i){e.push({dir:N.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function _r(e){let t=[],n=[];for(let i of[ke,Ce]){if(!x.existsSync(i))continue;let a=x.readdirSync(i).filter(l=>l.endsWith(e));for(let l of a){let r=N.join(i,l),c=l.slice(0,-e.length),u=N.join(i,c);try{c.toLowerCase().endsWith(".json")?gt(r):x.accessSync(r,x.constants.R_OK),t.push({backupPath:r,originalPath:u,fileName:l,dir:i})}catch(f){n.push(`${N.basename(i)}/${l}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:a,fileName:l,dir:r}of t)try{ao(i,a),o++}catch(c){s.push(`${N.basename(r)}/${l}: ${c.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function ao(e,t){let n=t+".tmp";try{x.copyFileSync(e,n),ro(n)}catch(o){try{x.unlinkSync(n)}catch{}throw o}try{x.renameSync(n,t)}catch(o){try{x.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=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 s.code=o.code,s}throw o}}Ae();async function Er(e,t,n="op"){let o,s=new Promise((i,a)=>{o=setTimeout(()=>a(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function xe(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function lo(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await Er(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let a=await e.newPage();if(i)try{await i(a)}catch{}if(s)try{let l=s();Array.isArray(l)&&l.length>0&&await a.setCookie(...l)}catch{}if(n){await a.goto(n,{waitUntil:"domcontentloaded",timeout:o});let l=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(l))throw new Error(`Session expired after recovery \u2014 landed on ${l}. Run: ilml linkedin login`)}return a}await io();var vo="https://www.linkedin.com/messaging/",jr=10,Zt=3,Pr=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},Lr=()=>ut(),Ee={pageRecoveries:0};async function yt(e,t){if(Ee.pageRecoveries>=jr)throw new Error(`CDP unrecoverable: ${Ee.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
272
- \u{1F504} CDP dead \u2014 recovering page (#${Ee.pageRecoveries+1}). Reason: ${t}`),e.page=await lo(e.browser,e.page,{returnUrl:vo,cookiesProvider:Lr,setupPage:Pr}),Ee.pageRecoveries++,await $(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Ee.pageRecoveries}).
296
+ `)}var Sr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function vr(e){let t=e.toLowerCase();return Sr.some(n=>n.test(t))}var $r=6e4;function kr(){let e=Date.now(),t=[];for(let n of[se,ke,Ce]){if(!x.existsSync(n))continue;let o;try{o=x.readdirSync(n)}catch{continue}for(let s of o){if(!vr(s))continue;let i=N.join(n,s);try{let a=x.statSync(i);if(!a.isFile()||e-a.mtimeMs<$r)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Cr({verbose:e=!1}={}){let t=kr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{x.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${N.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function xr(){let e=[];for(let t of[ke,Ce]){if(!x.existsSync(t))continue;let n=x.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=N.join(t,o);try{gt(s)}catch(i){e.push({dir:N.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Er(e){let t=[],n=[];for(let i of[ke,Ce]){if(!x.existsSync(i))continue;let a=x.readdirSync(i).filter(l=>l.endsWith(e));for(let l of a){let r=N.join(i,l),c=l.slice(0,-e.length),u=N.join(i,c);try{c.toLowerCase().endsWith(".json")?gt(r):x.accessSync(r,x.constants.R_OK),t.push({backupPath:r,originalPath:u,fileName:l,dir:i})}catch(f){n.push(`${N.basename(i)}/${l}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:a,fileName:l,dir:r}of t)try{ao(i,a),o++}catch(c){s.push(`${N.basename(r)}/${l}: ${c.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function ao(e,t){let n=t+".tmp";try{x.copyFileSync(e,n),ro(n)}catch(o){try{x.unlinkSync(n)}catch{}throw o}try{x.renameSync(n,t)}catch(o){try{x.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=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 s.code=o.code,s}throw o}}Ae();async function _r(e,t,n="op"){let o,s=new Promise((i,a)=>{o=setTimeout(()=>a(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function xe(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function lo(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await _r(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let a=await e.newPage();if(i)try{await i(a)}catch{}if(s)try{let l=s();Array.isArray(l)&&l.length>0&&await a.setCookie(...l)}catch{}if(n){await a.goto(n,{waitUntil:"domcontentloaded",timeout:o});let l=a.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(l))throw new Error(`Session expired after recovery \u2014 landed on ${l}. Run: ilml linkedin login`)}return a}await io();var vo="https://www.linkedin.com/messaging/",jr=10,Zt=3,Pr=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},Lr=()=>ut(),_e={pageRecoveries:0};async function yt(e,t){if(_e.pageRecoveries>=jr)throw new Error(`CDP unrecoverable: ${_e.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
297
+ \u{1F504} CDP dead \u2014 recovering page (#${_e.pageRecoveries+1}). Reason: ${t}`),e.page=await lo(e.browser,e.page,{returnUrl:vo,cookiesProvider:Lr,setupPage:Pr}),_e.pageRecoveries++,await $(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${_e.pageRecoveries}).
273
298
  `)}function Pe(e){return(e.messages||[]).find(t=>Be.has(t.status))?.status}var Q=process.argv.slice(2),Xt=Q.includes("--full"),W=Q.includes("--dry-run"),ho=Q.includes("--report"),en=Q.includes("--verbose"),yo=Q.includes("--backfill"),wo=Q.includes("--enrich"),bo=Q.includes("--today"),tn=Q.includes("--read-unread"),it=parseInt(Q.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),Fr=Q.includes("--auto-enrich-replies"),So=parseInt(Q.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),Ur=parseInt(Q.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function qr(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function Br(e,t){console.log(`
274
299
  \u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
275
300
  `);let n=xt(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,a=new Map,l=0,r=0,c=0,u=0,f=0,d=-1,m=0;for(;;){r++;let w=await Un(e),S=0;for(let h of w){if(!h.name||s.has(h.name))continue;s.set(h.name,h),S++,h.unread&&a.set(h.name,h);let k=t[h.name],C=qr(h,k);C&&(!tn&&h.unread?l++:i.set(h.name,{card:h,reason:C})),k&&(C||(k.lastMessageBy=h.lastMessageBy,k.lastMessagePreview=h.lastMessagePreview||k.lastMessagePreview,k.lastMessageTime=h.lastMessageTime||k.lastMessageTime),k.unread=h.unread,h.lastMessageBy==="them"&&h.unread&&(k.conversationStatus="unanswered_by_us"))}if(en?console.log(` Round #${r}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${r}, ${i.size} need reading)`),S===0){if(f++,f>=3){console.log(`
@@ -280,7 +305,7 @@ ${o.join(`
280
305
  Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${p}`),console.log(` Need reading/re-reading: ${i.size}`),!tn&&l>0&&console.log(` Preserved unread (default): ${l} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),b>0&&console.log(` New unread stubs: ${b} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let w={};for(let{reason:S}of i.values())w[S]=(w[S]||0)+1;for(let[S,g]of Object.entries(w))console.log(` ${S}: ${g}`)}if(!W){let w=xt();w.lastIncrementalSync=new Date().toISOString(),Xt&&(w.lastFullSync=w.lastIncrementalSync),An(w),fe(t)}return{allCards:s,toReRead:i,unreadCards:a}}async function Hr(e,t,n,o){console.log(`
281
306
  \u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
282
307
  `);let s=Array.from(t.entries()),i=Math.min(s.length,it);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(vo,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!xe(f))throw f;await yt(e,"Phase 2 inbox reset")}await $(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let a={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(a[f[1].reason]??5)-(a[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${it})
283
- `);let l=[],r=[],c=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);let p=e.page;try{let b={verified:!1,headerName:null};try{b=await Ot(p,d)}catch(S){if(xe(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!b.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{b=await qn(e.page,d)}catch(S){if(xe(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),c++;try{await me(e.page)}catch{}continue}let w=await Dt(p);if(w&&w.length>0){if(!It(w,d,r)){console.log(" Skipped \u2014 stale data."),c++,await me(p);continue}let g=await Rt(p),h=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},k=h.messages?.length||0;h.messages=Mt(h.messages,w),h.lastSynced=new Date().toISOString(),g&&!h.profileUrl&&(h.profileUrl=g);let C=h.messages.filter(I=>!["draft","confirmed","rejected","needs_review"].includes(I.status));h.lastMessageBy=Pt(C,d),h.lastMessagePreview=m.lastMessagePreview||h.lastMessagePreview,h.lastMessageTime=m.lastMessageTime||h.lastMessageTime,h.unread=!1,n[d]=h,W||fe(n);let E=h.messages.length-k;console.log(` ${h.messages.length} msgs (${E>=0?"+"+E:E} new)${g&&!h.profileUrl?" +url":""}`),l.push({name:d}),r=[...new Set(w.map(I=>I.sender).filter(I=>I&&I!=="Unknown"))]}else console.log(" No messages extracted."),c++;await me(p),await $(500)}catch(b){if(!xe(b))throw b;u++,o&&o.add(d),await yt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
308
+ `);let l=[],r=[],c=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);let p=e.page;try{let b={verified:!1,headerName:null};try{b=await Ot(p,d)}catch(S){if(xe(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!b.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{b=await qn(e.page,d)}catch(S){if(xe(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),c++;try{await me(e.page)}catch{}continue}let w=await Dt(p);if(w&&w.length>0){if(!It(w,d,r)){console.log(" Skipped \u2014 stale data."),c++,await me(p);continue}let g=await Rt(p),h=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},k=h.messages?.length||0;h.messages=Mt(h.messages,w),h.lastSynced=new Date().toISOString(),g&&!h.profileUrl&&(h.profileUrl=g);let C=h.messages.filter(I=>!["draft","confirmed","rejected","needs_review"].includes(I.status));h.lastMessageBy=Pt(C,d),h.lastMessagePreview=m.lastMessagePreview||h.lastMessagePreview,h.lastMessageTime=m.lastMessageTime||h.lastMessageTime,h.unread=!1,n[d]=h,W||fe(n);let _=h.messages.length-k;console.log(` ${h.messages.length} msgs (${_>=0?"+"+_:_} new)${g&&!h.profileUrl?" +url":""}`),l.push({name:d}),r=[...new Set(w.map(I=>I.sender).filter(I=>I&&I!=="Unknown"))]}else console.log(" No messages extracted."),c++;await me(p),await $(500)}catch(b){if(!xe(b))throw b;u++,o&&o.add(d),await yt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
284
309
  Phase 2 complete: ${l.length} read, ${c} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),l}async function Jr(e,t,n){if(!Fr)return null;console.log(`
285
310
  \u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
286
311
  `);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),a=Ur*24*60*60*1e3,l=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let p=y.profileUrl;if(!p)continue;let w=s[p]?._lastEnrichedAt;if(w){let S=i-new Date(w).getTime();if(Number.isFinite(S)&&S<a)continue}l.push({name:m,profileUrl:p,lastMessageTime:y.lastMessageTime||null})}if(l.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
@@ -295,23 +320,23 @@ ${o.join(`
295
320
  People enriched: ${c}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${r.length}`),nn(e,null,null)}function nn(e,t,n,o={}){let s=Object.entries(e),i=J(),{unreadCards:a=null,readUnread:l=!1}=o;console.log(`
296
321
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" SYNC REPORT"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
297
322
  `),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let r=s.length,c=s.filter(([,v])=>v.messages?.length>0).length,u=s.filter(([,v])=>!v.messages||v.messages.length===0).length,f=s.filter(([,v])=>v.profileUrl).length,d=s.filter(([,v])=>!v.profileUrl).length;console.log(`
298
- Database:`),console.log(` Total conversations: ${r}`),console.log(` With messages: ${c}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,y=0;for(let[,v]of s)for(let _ of v.messages||[])m++,(!_.sender||_.sender==="Unknown")&&y++;console.log(`
299
- Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let p={};for(let[,v]of s){let _=v.conversationStatus||"null";p[_]=(p[_]||0)+1}console.log(`
300
- Statuses:`);for(let[v,_]of Object.entries(p).sort((A,M)=>M[1]-A[1]))console.log(` ${v}: ${_}`);let b={};for(let[,v]of s){let _=v.category||"(none)";b[_]=(b[_]||0)+1}console.log(`
301
- Categories:`);for(let[v,_]of Object.entries(b).sort((A,M)=>M[1]-A[1]))console.log(` ${v}: ${_}`);let w={};for(let[,v]of s){let _=v.actionNeeded||"(none)";w[_]=(w[_]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
302
- Actions Needed:`);for(let[v,_]of Object.entries(w).sort((A,M)=>M[1]-A[1]))console.log(` ${v}: ${_}`)}let S=new Map;for(let[v,_]of s){if(!_.profileUrl)continue;let A=_.profileUrl.toLowerCase().replace(/\/$/,"");S.has(A)||S.set(A,[]),S.get(A).push(v)}let g=[...S.entries()].filter(([,v])=>v.length>1);if(g.length>0){console.log(`
303
- Duplicates (${g.length}):`);for(let[v,_]of g)console.log(` ${_.join(" | ")} \u2192 ${v}`)}let h=s.filter(([,v])=>v.conversationStatus==="unanswered_by_us").sort((v,_)=>(_[1].lastSynced||"").localeCompare(v[1].lastSynced||"")),k=s.filter(([,v])=>Pe(v));if(console.log(`
323
+ Database:`),console.log(` Total conversations: ${r}`),console.log(` With messages: ${c}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,y=0;for(let[,v]of s)for(let E of v.messages||[])m++,(!E.sender||E.sender==="Unknown")&&y++;console.log(`
324
+ Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let p={};for(let[,v]of s){let E=v.conversationStatus||"null";p[E]=(p[E]||0)+1}console.log(`
325
+ Statuses:`);for(let[v,E]of Object.entries(p).sort((A,M)=>M[1]-A[1]))console.log(` ${v}: ${E}`);let b={};for(let[,v]of s){let E=v.category||"(none)";b[E]=(b[E]||0)+1}console.log(`
326
+ Categories:`);for(let[v,E]of Object.entries(b).sort((A,M)=>M[1]-A[1]))console.log(` ${v}: ${E}`);let w={};for(let[,v]of s){let E=v.actionNeeded||"(none)";w[E]=(w[E]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
327
+ Actions Needed:`);for(let[v,E]of Object.entries(w).sort((A,M)=>M[1]-A[1]))console.log(` ${v}: ${E}`)}let S=new Map;for(let[v,E]of s){if(!E.profileUrl)continue;let A=E.profileUrl.toLowerCase().replace(/\/$/,"");S.has(A)||S.set(A,[]),S.get(A).push(v)}let g=[...S.entries()].filter(([,v])=>v.length>1);if(g.length>0){console.log(`
328
+ Duplicates (${g.length}):`);for(let[v,E]of g)console.log(` ${E.join(" | ")} \u2192 ${v}`)}let h=s.filter(([,v])=>v.conversationStatus==="unanswered_by_us").sort((v,E)=>(E[1].lastSynced||"").localeCompare(v[1].lastSynced||"")),k=s.filter(([,v])=>Pe(v));if(console.log(`
304
329
  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(" ACTION NEEDED"),console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
305
330
  `),a&&!l&&a.size>0){let v=[...a.entries()];console.log(` STILL UNREAD ON LINKEDIN (${v.length}) \u2014 kept bold; read them in the LinkedIn UI:
306
- `);let _=30;for(let[A,M]of v.slice(0,_)){let q=e[A],re=q?.category?` [${q.category}]`:"",ie=M.lastMessageTime||q?.lastMessageTime||"",j=(M.lastMessagePreview||"").slice(0,80),F=q?.summary,P=q?.personContext?.title?`${q.personContext.title}${q.personContext.company?` at ${q.personContext.company}`:""}`:null;console.log(` ${A}${re}${ie?` \u2014 ${ie}`:""}`),j&&console.log(` "${j}"`),F?console.log(` ${F}`):P&&console.log(` ${P}`)}v.length>_&&console.log(`
307
- ... and ${v.length-_} more`),console.log(`
331
+ `);let E=30;for(let[A,M]of v.slice(0,E)){let q=e[A],re=q?.category?` [${q.category}]`:"",ie=M.lastMessageTime||q?.lastMessageTime||"",j=(M.lastMessagePreview||"").slice(0,80),F=q?.summary,P=q?.personContext?.title?`${q.personContext.title}${q.personContext.company?` at ${q.personContext.company}`:""}`:null;console.log(` ${A}${re}${ie?` \u2014 ${ie}`:""}`),j&&console.log(` "${j}"`),F?console.log(` ${F}`):P&&console.log(` ${P}`)}v.length>E&&console.log(`
332
+ ... and ${v.length-E} more`),console.log(`
308
333
  To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
309
- `)}if(k.length>0){let v=k.filter(([,A])=>Pe(A)===V.CONFIRMED),_=k.filter(([,A])=>{let M=Pe(A);return M===V.DRAFT||M===V.NEEDS_REVIEW});console.log(` Drafts: ${k.length} total (${v.length} confirmed, ${_.length} pending)`),_.length>0&&console.log(" Review: npm run messages -- --review-drafts"),v.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=h.filter(([,v])=>v.actionNeeded==="schedule_call"),E=h.filter(([,v])=>v.actionNeeded!=="schedule_call");if(E.sort((v,_)=>{let A={high:0,medium:1,low:2}[v[1].suggestedPriority]??3,M={high:0,medium:1,low:2}[_[1].suggestedPriority]??3;return A-M}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
310
- `);for(let[v,_]of C){let A=_.category||"",M=_.summary||"";console.log(` ${v}${A?` [${A}]`:""} \u2192 schedule_call`),M&&console.log(` ${M}`)}console.log()}if(E.length>0){console.log(` REPLY NEEDED (${E.length}):
311
- `);let v=20;for(let[_,A]of E.slice(0,v)){let M=A.category||"",q=A.suggestedPriority?`[${A.suggestedPriority}]`:"",re=(A.autoTags||[]).slice(0,4).join(", "),ie=A.summary||"",F=[...A.messages||[]].reverse().find(P=>P.sender!==z&&P.sender!=="Unknown")?.text?.slice(0,80)||A.lastMessagePreview?.slice(0,80)||"";console.log(` ${q} ${_}${M?` [${M}]`:""}`),console.log(ie?` ${ie}`:` "${F}"`),re&&console.log(` #${re.replace(/, /g," #")}`)}E.length>v&&console.log(`
312
- ... and ${E.length-v} more`)}h.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let I=new Set(Object.keys(e)),T=new Set(Object.values(e).map(v=>v.profileUrl).filter(Boolean)),L=Object.entries(i).filter(([v,_])=>_.connectionStatus==="connected"&&_.personActionNeeded==="initiate_contact"&&!T.has(v)&&!(_.name&&I.has(_.name))).sort((v,_)=>{let A={high:0,medium:1,low:2}[v[1].personPriority]??3,M={high:0,medium:1,low:2}[_[1].personPriority]??3;return A!==M?A-M:(_[1].connectionDate||"").localeCompare(v[1].connectionDate||"")});if(L.length>0){console.log(`
334
+ `)}if(k.length>0){let v=k.filter(([,A])=>Pe(A)===V.CONFIRMED),E=k.filter(([,A])=>{let M=Pe(A);return M===V.DRAFT||M===V.NEEDS_REVIEW});console.log(` Drafts: ${k.length} total (${v.length} confirmed, ${E.length} pending)`),E.length>0&&console.log(" Review: npm run messages -- --review-drafts"),v.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=h.filter(([,v])=>v.actionNeeded==="schedule_call"),_=h.filter(([,v])=>v.actionNeeded!=="schedule_call");if(_.sort((v,E)=>{let A={high:0,medium:1,low:2}[v[1].suggestedPriority]??3,M={high:0,medium:1,low:2}[E[1].suggestedPriority]??3;return A-M}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
335
+ `);for(let[v,E]of C){let A=E.category||"",M=E.summary||"";console.log(` ${v}${A?` [${A}]`:""} \u2192 schedule_call`),M&&console.log(` ${M}`)}console.log()}if(_.length>0){console.log(` REPLY NEEDED (${_.length}):
336
+ `);let v=20;for(let[E,A]of _.slice(0,v)){let M=A.category||"",q=A.suggestedPriority?`[${A.suggestedPriority}]`:"",re=(A.autoTags||[]).slice(0,4).join(", "),ie=A.summary||"",F=[...A.messages||[]].reverse().find(P=>P.sender!==z&&P.sender!=="Unknown")?.text?.slice(0,80)||A.lastMessagePreview?.slice(0,80)||"";console.log(` ${q} ${E}${M?` [${M}]`:""}`),console.log(ie?` ${ie}`:` "${F}"`),re&&console.log(` #${re.replace(/, /g," #")}`)}_.length>v&&console.log(`
337
+ ... and ${_.length-v} more`)}h.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let I=new Set(Object.keys(e)),T=new Set(Object.values(e).map(v=>v.profileUrl).filter(Boolean)),L=Object.entries(i).filter(([v,E])=>E.connectionStatus==="connected"&&E.personActionNeeded==="initiate_contact"&&!T.has(v)&&!(E.name&&I.has(E.name))).sort((v,E)=>{let A={high:0,medium:1,low:2}[v[1].personPriority]??3,M={high:0,medium:1,low:2}[E[1].personPriority]??3;return A!==M?A-M:(E[1].connectionDate||"").localeCompare(v[1].connectionDate||"")});if(L.length>0){console.log(`
313
338
  INITIATE CONTACT (${L.length}):
314
- `);let v=20;for(let[_,A]of L.slice(0,v)){let M=A.personPriority?`[${A.personPriority.toUpperCase()}]`:"",q=A.personSummary||A.title||"";console.log(` ${M} ${A.name||"Unknown"} \u2014 ${q}`)}L.length>v&&console.log(`
339
+ `);let v=20;for(let[E,A]of L.slice(0,v)){let M=A.personPriority?`[${A.personPriority.toUpperCase()}]`:"",q=A.personSummary||A.title||"";console.log(` ${M} ${A.name||"Unknown"} \u2014 ${q}`)}L.length>v&&console.log(`
315
340
  ... and ${L.length-v} more`)}let G=s.filter(([,v])=>v.conversationStatus==="awaiting_reply");G.length>0&&console.log(`
316
341
  BALL IN THEIR COURT: ${G.length} conversations`),W&&console.log(`
317
342
  [DRY RUN \u2014 no changes written]`),console.log(`
@@ -323,19 +348,19 @@ ${o.join(`
323
348
  Backfill complete: ${s.length} read, ${i} failed${a?`, ${a} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function Gr(e){let t=ze(),n=Object.values(e),o=n.filter(r=>r.sources?.includes("recruiters-from-jobs")&&!r.connectionStatus).length,s=n.filter(r=>r.connectionStatus==="modal_failed").length,i=o+s,a=n.filter(r=>r.connectionStatus==="connected"&&r.connectionMethod).length,l=n.filter(r=>r.connectionStatus==="pending"||r.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${a} accepted, ${l} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}function zr(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?ue(o.lastJobTitle,25):"",a=o.lastJobDate||"",l=i?` (last: ${i}${a?", "+a:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ue(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${l}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Kr(){let e=On(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=ue(o.title||"?",30),i=ue(o.company||"?",15),a=o.salary?` \u2014 ${ue(o.salary,12)}`:"",l=o.location?` \u2014 ${ue(o.location,15)}`:"",r=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${a}${l}${r}`)}console.log(" Apply: npm run apply-queue"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function Qr(){let e=In();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"))}function Zr(){let e=Tn();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=ue(t.topAnswer,30);console.log(` "${ue(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${ue(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}}function ue(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Xr(){let e=Ge(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(g=>g.profileUrl).filter(Boolean));console.log(`
324
349
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" TODAY'S PRIORITIES"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
325
350
  `),console.log(Qn()),console.log(""),Gr(t),console.log(""),zr(t),console.log(""),Qr(),console.log(""),Kr(),console.log(""),Zr(),console.log("");let s=Object.entries(e),i=s.filter(([,g])=>g.unread===!0).sort((g,h)=>(h[1].lastMessageTime||"").localeCompare(g[1].lastMessageTime||""));if(i.length>0){let g=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
326
- `);for(let h=0;h<g.length;h++){let[k,C]=g[h],E=C.category?` [${C.category}]`:"",I=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${h+1}. ${k}${E}${I?` \u2014 ${I}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let a=new Date().toISOString().slice(0,10),l=s.filter(([,g])=>g.followUpNote),r=l.filter(([,g])=>!g.followUpDate||g.followUpDate<=a),c=l.filter(([,g])=>g.followUpDate&&g.followUpDate>a);if(l.length>0){console.log(` FOLLOW-UPS (${r.length} due, ${c.length} scheduled):
351
+ `);for(let h=0;h<g.length;h++){let[k,C]=g[h],_=C.category?` [${C.category}]`:"",I=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${h+1}. ${k}${_}${I?` \u2014 ${I}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let a=new Date().toISOString().slice(0,10),l=s.filter(([,g])=>g.followUpNote),r=l.filter(([,g])=>!g.followUpDate||g.followUpDate<=a),c=l.filter(([,g])=>g.followUpDate&&g.followUpDate>a);if(l.length>0){console.log(` FOLLOW-UPS (${r.length} due, ${c.length} scheduled):
327
352
  `);for(let[g,h]of r){let k=h.followUpDate?` [due ${h.followUpDate}]`:" [no date]";console.log(` \u26A1 ${g}${k} \u2014 ${h.followUpNote}`)}for(let[g,h]of c.slice(0,5))console.log(` \u{1F4C5} ${g} [${h.followUpDate}] \u2014 ${h.followUpNote}`);c.length>5&&console.log(` ... +${c.length-5} more scheduled`),console.log()}let u=g=>g.actionNeeded&&g.actionNeeded!=="none"&&(!g.reviewedAtPreview||tt(g.lastMessagePreview)!==tt(g.reviewedAtPreview)),f=s.filter(([,g])=>u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(f.length>0){let g=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
328
- `);for(let h=0;h<g.length;h++){let[k,C]=g[h],E=C.priority||C.suggestedPriority||"",I=C.category?` [${C.category}]`:"",T=C.summary||"";console.log(` ${h+1}. ${E?`[${E}] `:""}${k}${I} \u2014 ${T}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,g])=>g.actionNeeded==="schedule_call").sort((g,h)=>{let k={high:0,medium:1,low:2}[g[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[h[1].suggestedPriority]??3;return k-C});if(d.length>0){let g=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
329
- `);for(let h=0;h<g.length;h++){let[k,C]=g[h],E=C.summary||C.personContext?.title||"";console.log(` ${h+1}. ${k} \u2014 ${E}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&(g.suggestedPriority==="high"||g.priority==="high")&&!u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(m.length>0){let g=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
330
- `);for(let h=0;h<g.length;h++){let[k,C]=g[h],E=C.category?` [${C.category}]`:"",I=C.summary||"";console.log(` ${h+1}. ${k}${E} \u2014 ${I}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&g.suggestedPriority==="medium"&&g.priority!=="high"&&!u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(y.length>0){let g=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
331
- `);for(let h=0;h<g.length;h++){let[k,C]=g[h],E=C.category?` [${C.category}]`:"",I=C.summary||"";console.log(` ${h+1}. ${k}${E} \u2014 ${I}`)}y.length>5&&console.log(` ... +${y.length-5} more`),console.log()}let p=Object.entries(t).filter(([g,h])=>h.connectionStatus==="connected"&&h.personActionNeeded==="initiate_contact"&&!o.has(g)&&!(h.name&&n.has(h.name))).sort((g,h)=>{let k={high:0,medium:1,low:2}[g[1].personPriority]??3,C={high:0,medium:1,low:2}[h[1].personPriority]??3;return k!==C?k-C:(h[1].connectionDate||"").localeCompare(g[1].connectionDate||"")});if(p.length>0){let g=p.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${p.length}):
332
- `);for(let h=0;h<g.length;h++){let[,k]=g[h],C=k.personPriority?`[${k.personPriority.toUpperCase()}]`:"",E=k.connectionDate?ei(k.connectionDate):"",I=k.title?`${k.title}${k.company?` at ${k.company}`:""}`:k.company||"";console.log(` ${h+1}. ${C} ${k.name||"Unknown"} \u2014 ${I}${E?` (${E})`:""}`)}p.length>10&&console.log(` ... +${p.length-10} more`),console.log()}let b=s.filter(([,g])=>Pe(g));if(b.length>0){let g=b.filter(([,k])=>Pe(k)===V.CONFIRMED).length,h=b.filter(([,k])=>{let C=Pe(k);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${g} confirmed, ${h} pending)`),g>0&&console.log(" Send: npm run messages -- --push-drafts"),h>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let w=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us").length,S=s.filter(([,g])=>g.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${w} need reply, ${p.length} new connections, ${S} ball in their court`),console.log(`
353
+ `);for(let h=0;h<g.length;h++){let[k,C]=g[h],_=C.priority||C.suggestedPriority||"",I=C.category?` [${C.category}]`:"",T=C.summary||"";console.log(` ${h+1}. ${_?`[${_}] `:""}${k}${I} \u2014 ${T}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,g])=>g.actionNeeded==="schedule_call").sort((g,h)=>{let k={high:0,medium:1,low:2}[g[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[h[1].suggestedPriority]??3;return k-C});if(d.length>0){let g=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
354
+ `);for(let h=0;h<g.length;h++){let[k,C]=g[h],_=C.summary||C.personContext?.title||"";console.log(` ${h+1}. ${k} \u2014 ${_}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&(g.suggestedPriority==="high"||g.priority==="high")&&!u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(m.length>0){let g=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
355
+ `);for(let h=0;h<g.length;h++){let[k,C]=g[h],_=C.category?` [${C.category}]`:"",I=C.summary||"";console.log(` ${h+1}. ${k}${_} \u2014 ${I}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&g.suggestedPriority==="medium"&&g.priority!=="high"&&!u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(y.length>0){let g=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
356
+ `);for(let h=0;h<g.length;h++){let[k,C]=g[h],_=C.category?` [${C.category}]`:"",I=C.summary||"";console.log(` ${h+1}. ${k}${_} \u2014 ${I}`)}y.length>5&&console.log(` ... +${y.length-5} more`),console.log()}let p=Object.entries(t).filter(([g,h])=>h.connectionStatus==="connected"&&h.personActionNeeded==="initiate_contact"&&!o.has(g)&&!(h.name&&n.has(h.name))).sort((g,h)=>{let k={high:0,medium:1,low:2}[g[1].personPriority]??3,C={high:0,medium:1,low:2}[h[1].personPriority]??3;return k!==C?k-C:(h[1].connectionDate||"").localeCompare(g[1].connectionDate||"")});if(p.length>0){let g=p.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${p.length}):
357
+ `);for(let h=0;h<g.length;h++){let[,k]=g[h],C=k.personPriority?`[${k.personPriority.toUpperCase()}]`:"",_=k.connectionDate?ei(k.connectionDate):"",I=k.title?`${k.title}${k.company?` at ${k.company}`:""}`:k.company||"";console.log(` ${h+1}. ${C} ${k.name||"Unknown"} \u2014 ${I}${_?` (${_})`:""}`)}p.length>10&&console.log(` ... +${p.length-10} more`),console.log()}let b=s.filter(([,g])=>Pe(g));if(b.length>0){let g=b.filter(([,k])=>Pe(k)===V.CONFIRMED).length,h=b.filter(([,k])=>{let C=Pe(k);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${g} confirmed, ${h} pending)`),g>0&&console.log(" Send: npm run messages -- --push-drafts"),h>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let w=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us").length,S=s.filter(([,g])=>g.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${w} need reply, ${p.length} new connections, ${S} ball in their court`),console.log(`
333
358
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
334
359
  `)}function ei(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function ti(){let e=Ge();nn(e,null,null)}async function ni(){if(console.log(`
335
360
  LinkedIn Sync-All
336
361
  `),bo){Xr();return}if(ho){let a=mt("sync-all","report");ti(),je(a,"success");return}if(wo){let a=mt("sync-all","enrich");try{Wr(),je(a,"success")}catch(l){throw je(a,"error",null,l.message),l}return}let e=yo?"backfill":Xt?"full":"incremental",t=mt("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${it}`);let o=Ge(),s=await Fn(),i={browser:s.browser,page:s.page};try{await At(i.page);let a=null,l=[];if(yo)l=await Yr(i,o);else{let r=0;for(;;)try{a=await Br(i.page,o);break}catch(d){if(!xe(d))throw d;if(r++,r>=Zt)throw new Error(`Phase 1 failed ${Zt} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
337
362
  \u26A0 Phase 1 CDP dead (attempt ${r}/${Zt}). Recovering and restarting Phase 1...`),await yt(i,`Phase 1 attempt ${r}`)}let c=new Set;l=await Hr(i,a.toReRead,o,c),n.scanned=a.totalCards||0,n.toReRead=a.toReRead?.size||0;let u=new Set(l.map(d=>d.name)),f=0;for(let[d,{card:m}]of a.toReRead){if(u.has(d)||c.has(d))continue;let y=o[d];y&&(y.lastMessageBy=m.lastMessageBy,y.lastMessageTime=m.lastMessageTime||y.lastMessageTime,y.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),W||fe(o))}n.threadsRead=l.length,n.newMessages=l.reduce((r,c)=>r+(c.newMessages||0),0);try{let r=await Jr(i,o,l);r&&(n.autoEnriched=r.enriched,r.authWall&&(n.autoEnrichAuthWall=!0))}catch(r){console.log(`
338
363
  \u26A0 Auto-enrich phase crashed: ${r.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
339
- `)}l.length>0&&Vr(o,l),nn(o,a,l,{unreadCards:a?.unreadCards,readUnread:tn}),Ee.pageRecoveries>0&&console.log(`
340
- CDP page recoveries this run: ${Ee.pageRecoveries}`),W||_t(),je(t,"success",n)}catch(a){console.error(`
341
- Error:`,a.message),en&&console.error(a.stack),je(t,"error",n,a.message)}finally{if(!W&&!ho&&!wo&&!bo)try{_t()}catch{}await i.browser.close()}}ni();
364
+ `)}l.length>0&&Vr(o,l),nn(o,a,l,{unreadCards:a?.unreadCards,readUnread:tn}),_e.pageRecoveries>0&&console.log(`
365
+ CDP page recoveries this run: ${_e.pageRecoveries}`),W||Et(),je(t,"success",n)}catch(a){console.error(`
366
+ Error:`,a.message),en&&console.error(a.stack),je(t,"error",n,a.message)}finally{if(!W&&!ho&&!wo&&!bo)try{Et()}catch{}await i.browser.close()}}ni();