ilml-plugin-linkedin 1.19.2 → 1.20.0

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,8 +1,8 @@
1
- var Go=Object.defineProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var Me=(e,t)=>{for(var n in t)Go(e,n,{get:t[n],enumerable:!0})};function Ge(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 _t(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=Ge(n),i=new Date(t);return l?i.setHours(l.hours,l.minutes,0,0):i.setHours(0,0,0,0),i.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=zo[o[1].toLowerCase()],i=Ge(o[2]||""),d=new Date(t),f=d.getDay()-l;return f<=0&&(f+=7),d.setDate(d.getDate()-f),i?d.setHours(i.hours,i.minutes,0,0):d.setHours(0,0,0,0),d.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=xt[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let i=parseInt(s[2],10),d=parseInt(s[3],10),c=Ge(s[4]||"");return new Date(d,l,i,c?.hours||0,c?.minutes||0,0,0).toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=xt[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let i=parseInt(r[2],10),d=Ge(r[3]||""),c=t.getFullYear(),f=new Date(c,l,i,d?.hours||0,d?.minutes||0,0,0);return f>t&&f.setFullYear(c-1),f.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let l=xt[a[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let i=parseInt(a[2],10),d=Ge(a[3]||""),c=t.getFullYear(),f=new Date(c,l,i,d?.hours||0,d?.minutes||0,0,0);return f>t&&f.setFullYear(c-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 Sn(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 Se(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",r=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(r||a||l){let i=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:s.substring(0,80)};let d=o.querySelectorAll("button");for(let c of d){let f=c.innerText?.trim().toLowerCase()||"",u=c.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||u.includes("dismiss"))return c.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 vn(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 $n(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 xt,zo,Oe=Ye(()=>{xt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},zo={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Ko}from"@ilivemylife/graph-sdk";var Qo,z,V,ze,Ne,Ke=Ye(async()=>{Qo=await Ko();for(let[e,t]of Object.entries(Qo))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"}),ze=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Ne=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as L from"fs";import*as B from"path";import{fileURLToPath as Zo}from"url";import{execSync as At}from"child_process";function Rn(){je=null,ts=null,ce=null,$e=null,Pe=null,ve=null}function ue(){L.existsSync(Z)||L.mkdirSync(Z,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";L.writeFileSync(o,n);for(let s=0;s<3;s++)try{L.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw r}}function Xe(e,t){if(!L.existsSync(e))return null;try{let n=JSON.parse(L.readFileSync(e,"utf-8"));try{L.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(L.existsSync(o))try{let s=JSON.parse(L.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{L.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{L.copyFileSync(e,e+".corrupted")}catch{}return null}}function et(){return new Date().toISOString().split("T")[0]}function ke(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Cn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Le(e,t,n=null){if(!t||e[t])return t;let o=ke(t);if(!o)return t;let s=null;for(let[r,a]of Object.entries(e)){if(ke(a.profileUrl||r)===o)return r;!s&&Array.isArray(a.aliases)&&a.aliases.includes(o)&&(s=r)}if(s){let r=Cn(n),a=Cn(e[s].name);if(r&&a&&r===a)return s}return t}function ss(){L.existsSync(Rt)||L.mkdirSync(Rt,{recursive:!0})}function Dn(e){let t=ke(e);return t?B.join(Rt,`${t}.json`):null}function rs(e){let t=Dn(e);return t?Xe(t,`profile-history/${ke(e)}.json`)||[]:[]}function is(e,t){let n=Dn(e);if(!n)return;ss();let o=rs(e);o.unshift(t);try{Fe(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${ke(e)}: ${s.message}`)}}function En(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function xn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function as(e,t){if(!e)return[];let n=[];for(let o of os){let s=e[o],r=t[o];En(s)||En(r)||xn(s)!==xn(r)&&n.push(o)}return n}function ls(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 je||(ue(),je=Xe(Tt,"people.json")||{},je)}function Ee(e){ue(),je=e;try{Fe(Tt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Tt)}`)}}function tt(){return $e||(ue(),$e=Xe(pt,"conversations.json")||{},cs($e),$e)}function cs(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(r=>r.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{Fe(pt,e)}catch{}}}function pe(e){ue(),$e=e;try{Fe(pt,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(pt)}`)}}function Ce(e,t={}){if(!e)return null;let n=J(),o=et(),s=new Date().toISOString(),r=Le(n,e,t.name),a=n[r];if(a){let l=as(a,t);l.length>0&&(is(r,{capturedAt:s,previousLastUpdated:a.lastUpdated||null,changedFields:l,snapshot:ls(a)}),a.lastSnapshotAt=s),a.seenCount=(a.seenCount||1)+1,a.lastSeen=o,a.lastUpdated=s,t.source&&!a.sources?.includes(t.source)&&(a.sources=a.sources||[],a.sources.push(t.source));for(let i of ns)if(t[i]!=null){if(Array.isArray(t[i])&&t[i].length===0&&Array.isArray(a[i])&&a[i].length>0)continue;a[i]=t[i]}Array.isArray(t.availableSections)&&(a.lastFullVisitAt=s)}else n[r]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Ee(n),n[r]}function In(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let r={date:et(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(r.jobId=String(t.jobId)),t.jobTitle&&(r.jobTitle=t.jobTitle),t.jobCompany&&(r.jobCompany=t.jobCompany),!o.encounters.some(l=>l.date===r.date&&l.source===r.source&&l.action===r.action&&(l.jobId||"")===(r.jobId||""))&&(o.encounters.push(r),o.lastUpdated=new Date().toISOString(),Ee(n))}function Mn(e){return e&&J()[e]?.connectionStatus||null}function On(e,t,n={}){if(!e)return;if(n.profileInfo)Ce(e,n.profileInfo);else{let l=J(),i=Le(l,e,n.profileInfo?.name);l[i]||Ce(e,{})}let o=J(),s=Le(o,e,n.profileInfo?.name),r=o[s];if(!r)return;let a=et();r.connectionStatus=t,t==="connected"?r.connectionDate=a:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(r.requestedConnectionAt||(r.requestedConnectionAt=a)),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),Ee(o)}function gt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ke(t);if(!o)return;let s=J(),r=Le(s,e),a=s[r];if(!a)return;let l=ke(a.profileUrl||r);o!==l&&(Array.isArray(a.aliases)||(a.aliases=[]),a.aliases.includes(o)||(a.aliases.push(o),a.lastUpdated=new Date().toISOString(),Ee(s)))}function Nn(){return ce||(ue(),ce=Xe(_n,"quota.json"),(!ce||!ce.connections)&&(ce={connections:[]}),ce)}function us(e){ue(),ce=e;try{Fe(_n,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function jn(e,t="unknown"){let n=Nn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),us(n)}function Pn(){let e=Nn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Dt(){let e=Pn(),t=et(),n=e.filter(i=>i.date===t).length,o=e.length,s=n>=Qe,r=o>=Ze,a=!s&&!r,l={allowed:a,daily:{sent:n,max:Qe},weekly:{sent:o,max:Ze}};return a||(l.reason=s?`Daily limit reached (${n}/${Qe})`:`Weekly limit reached (${o}/${Ze})`),l}function nt(){let e=Pn(),t=et(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:Qe,remaining:Qe-n},weekly:{sent:o,max:Ze,remaining:Ze-o}}}function It(){return Pe||(ue(),Pe=Xe(An,"sync-state.json")||{},Pe)}function Ln(e){ue(),Pe=e;try{Fe(An,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function ds(){if(ve)return ve;ue();try{L.existsSync(kn)&&(ve=JSON.parse(L.readFileSync(kn,"utf-8")))}catch{}return ve||(ve={}),ve}function fs(e){return Array.isArray(e.applications)}function ms(){let e=ds();if(fs(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function Fn(){let e=ms(),t=new Map;for(let r of e)for(let a of r.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 i=t.get(l);i.count++;let d=(a.answer||"").trim();i.answers.set(d,(i.answers.get(d)||0)+1)}let n=[...t.values()].sort((r,a)=>a.count-r.count),o=n.slice(0,15).map(r=>({question:r.question,count:r.count,topAnswer:[...r.answers.entries()].sort((a,l)=>l[1]-a[1])[0]?.[0]||""})),s=n.filter(r=>r.answers.size>1&&r.count>=3).map(r=>({question:r.question,count:r.count,answers:[...r.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 Mt(e){if(L.existsSync(B.join(Z,".git")))try{let t={cwd:Z,stdio:"pipe",timeout:1e4};At("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{At("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');At(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Xo,es,Z,Tt,Fi,_n,pt,An,kn,Rt,Tn,Qe,Ze,je,ts,ce,$e,Pe,ve,ns,os,Ue=Ye(async()=>{await Ke();Xo=Zo(import.meta.url),es=B.dirname(B.dirname(Xo)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(es,"collected-profiles"),Tt=B.join(Z,"people.json"),Fi=B.join(Z,"jobs.json"),_n=B.join(Z,"quota.json"),pt=B.join(Z,"conversations.json"),An=B.join(Z,"sync-state.json"),kn=B.join(Z,"application-questions.json"),Rt=B.join(Z,"profile-history"),Tn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Qe=Tn(process.env.CONNECT_MAX_DAILY,20),Ze=Tn(process.env.CONNECT_MAX_WEEKLY,100),je=null,ts=null,ce=null,$e=null,Pe=null,ve=null;ns=["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"],os=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Ro={};Me(Ro,{extractCertificationsFromDetails:()=>ri,extractEducationFromDetails:()=>oi,extractExperienceFromDetails:()=>ti,extractFeaturedFromDetails:()=>ni,extractRecommendationsFromDetails:()=>ii,extractSkillsFromDetails:()=>si});async function ti(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 r=0;r<5;r++)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 r=document.querySelector("main");if(!r)return[];function a(c){let f=[];for(let u of c.querySelectorAll("div")){let m=Array.from(u.children).filter(g=>g.tagName==="DIV");if(m.length<3)continue;let y=m.filter(g=>(g.textContent||"").trim().length>50);y.length<3||(u.textContent||"").length<500||f.push({el:u,count:y.length,totalText:(u.textContent||"").length})}return f.sort((u,m)=>m.count-u.count||u.totalText-m.totalText),f[0]?.el}let l=a(r);if(!l)return[];let i=Array.from(l.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function d(c){let f=c[0]||null,u=null,m=null;if(c[1]){let T=c[1].split("\xB7").map(F=>F.trim());u=T[0]||null,T[1]&&(m=T[1])}let y=c.findIndex(T=>/(\d{4}|present)/i.test(T)&&/(-|–|—)/i.test(T)&&T.length<80),g=null,b=null;if(y>=0){let T=c[y].split("\xB7").map(F=>F.trim());g=T[0]||null,T[1]&&(b=T[1])}let w=null,S=-1;if(y>=0&&c[y+1]){let T=c[y+1],F=/^[>*\-•]|^&gt;/.test(T),G=/https?:\/\//.test(T),k=/\d{4}/.test(T),E=/,/.test(T)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(T);!F&&!G&&!k&&T.length<100&&E&&(w=T,S=y+1)}let h=null,p=-1,v=c[c.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){p=c.length-1;let T=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);T&&(h={listed:T[1].split(",").map(F=>F.trim()),additional:parseInt(T[2],10)})}let C=new Set([0,1,y,S,p].filter(T=>T>=0)),A=c.filter((T,F)=>!C.has(F)),D=A.length>0?A.join(`
1
+ var Es=Object.defineProperty;var fe=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{for(var n in t)Es(e,n,{get:t[n],enumerable:!0})};function et(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 Ht(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 a=et(n),l=new Date(t);return a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let a=_s[o[1].toLowerCase()],l=et(o[2]||""),c=new Date(t),d=c.getDay()-a;return d<=0&&(d+=7),c.setDate(c.getDate()-d),l?c.setHours(l.hours,l.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 a=Bt[s[1].toLowerCase().slice(0,3)];if(a===void 0)return null;let l=parseInt(s[2],10),c=parseInt(s[3],10),u=et(s[4]||"");return new Date(c,a,l,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 a=Bt[i[1].toLowerCase().slice(0,3)];if(a===void 0)return null;let l=parseInt(i[2],10),c=et(i[3]||""),u=t.getFullYear(),d=new Date(u,a,l,c?.hours||0,c?.minutes||0,0,0);return d>t&&d.setFullYear(u-1),d.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let a=Bt[r[1].toLowerCase().slice(0,3)];if(a===void 0)return null;let l=parseInt(r[2],10),c=et(r[3]||""),u=t.getFullYear(),d=new Date(u,a,l,c?.hours||0,c?.minutes||0,0,0);return d>t&&d.setFullYear(u-1),d.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 qn(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 Ae(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"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),a=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||a){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:s.substring(0,80)};let c=o.querySelectorAll("button");for(let u of c){let d=u.innerText?.trim().toLowerCase()||"",f=u.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.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 Bn(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 Hn(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,_s,Le=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},_s={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Ts}from"@ilivemylife/graph-sdk";var Rs,z,V,tt,Fe,nt=fe(async()=>{Rs=await Ts();for(let[e,t]of Object.entries(Rs))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"}),tt=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Fe=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as B from"path";import{fileURLToPath as Ds}from"url";import{execSync as Jt}from"child_process";function Qn(){Ue=null,Os=null,de=null,Ee=null,qe=null,xe=null}function me(){F.existsSync(Z)||F.mkdirSync(Z,{recursive:!0})}function He(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function rt(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.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(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.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{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function it(){return new Date().toISOString().split("T")[0]}function _e(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Vn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Be(e,t,n=null){if(!t||e[t])return t;let o=_e(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(_e(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=Vn(n),r=Vn(e[s].name);if(i&&r&&i===r)return s}return t}function Ps(){F.existsSync(Wt)||F.mkdirSync(Wt,{recursive:!0})}function Zn(e){let t=_e(e);return t?B.join(Wt,`${t}.json`):null}function Ls(e){let t=Zn(e);return t?rt(t,`profile-history/${_e(e)}.json`)||[]:[]}function Fs(e,t){let n=Zn(e);if(!n)return;Ps();let o=Ls(e);o.unshift(t);try{He(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${_e(e)}: ${s.message}`)}}function Wn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Yn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Us(e,t){if(!e)return[];let n=[];for(let o of js){let s=e[o],i=t[o];Wn(s)||Wn(i)||Yn(s)!==Yn(i)&&n.push(o)}return n}function qs(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 Ue||(me(),Ue=rt(Vt,"people.json")||{},Ue)}function Re(e){me(),Ue=e;try{He(Vt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Vt)}`)}}function lt(){return Ee||(me(),Ee=rt(Ct,"conversations.json")||{},Bs(Ee),Ee)}function Bs(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{He(Ct,e)}catch{}}}function ye(e){me(),Ee=e;try{He(Ct,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(Ct)}`)}}function Te(e,t={}){if(!e)return null;let n=J(),o=it(),s=new Date().toISOString(),i=Be(n,e,t.name),r=n[i];if(r){let a=Us(r,t);a.length>0&&(Fs(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:a,snapshot:qs(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let l of Ms)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(r[l])&&r[l].length>0)continue;r[l]=t[l]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Re(n),n[i]}function Xn(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:it(),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(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Re(n))}function eo(e){return e&&J()[e]?.connectionStatus||null}function to(e,t,n={}){if(!e)return;if(n.profileInfo)Te(e,n.profileInfo);else{let a=J(),l=Be(a,e,n.profileInfo?.name);a[l]||Te(e,{})}let o=J(),s=Be(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=it();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Re(o)}function At(e,t,n={}){if(n.dryRun||!e||!t)return;let o=_e(t);if(!o)return;let s=J(),i=Be(s,e),r=s[i];if(!r)return;let a=_e(r.profileUrl||i);o!==a&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),Re(s)))}function no(){return de||(me(),de=rt(Gn,"quota.json"),(!de||!de.connections)&&(de={connections:[]}),de)}function Hs(e){me(),de=e;try{He(Gn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function oo(e,t="unknown"){let n=no(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Hs(n)}function so(){let e=no(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Yt(){let e=so(),t=it(),n=e.filter(l=>l.date===t).length,o=e.length,s=n>=ot,i=o>=st,r=!s&&!i,a={allowed:r,daily:{sent:n,max:ot},weekly:{sent:o,max:st}};return r||(a.reason=s?`Daily limit reached (${n}/${ot})`:`Weekly limit reached (${o}/${st})`),a}function at(){let e=so(),t=it(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:ot,remaining:ot-n},weekly:{sent:o,max:st,remaining:st-o}}}function Gt(){return qe||(me(),qe=rt(zn,"sync-state.json")||{},qe)}function ro(e){me(),qe=e;try{He(zn,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Js(){if(xe)return xe;me();try{F.existsSync(Jn)&&(xe=JSON.parse(F.readFileSync(Jn,"utf-8")))}catch{}return xe||(xe={}),xe}function Vs(e){return Array.isArray(e.applications)}function Ws(){let e=Js();if(Vs(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function io(){let e=Ws(),t=new Map;for(let i of e)for(let r of i.questions||[]){let a=r.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:r.question,count:0,answers:new Map});let l=t.get(a);l.count++;let c=(r.answer||"").trim();l.answers.set(c,(l.answers.get(c)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,a)=>a[1]-r[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((r,a)=>a[1]-r[1]).map(([r,a])=>`${r} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function zt(e){if(F.existsSync(B.join(Z,".git")))try{let t={cwd:Z,stdio:"pipe",timeout:1e4};Jt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Jt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Jt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Is,Ns,Z,Vt,vl,Gn,Ct,zn,Jn,Wt,Kn,ot,st,Ue,Os,de,Ee,qe,xe,Ms,js,Je=fe(async()=>{await nt();Is=Ds(import.meta.url),Ns=B.dirname(B.dirname(Is)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Ns,"collected-profiles"),Vt=B.join(Z,"people.json"),vl=B.join(Z,"jobs.json"),Gn=B.join(Z,"quota.json"),Ct=B.join(Z,"conversations.json"),zn=B.join(Z,"sync-state.json"),Jn=B.join(Z,"application-questions.json"),Wt=B.join(Z,"profile-history"),Kn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ot=Kn(process.env.CONNECT_MAX_DAILY,20),st=Kn(process.env.CONNECT_MAX_WEEKLY,100),Ue=null,Os=null,de=null,Ee=null,qe=null,xe=null;Ms=["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"],js=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var lo={};ae(lo,{extractSidePanelProfiles:()=>Gs,normalizeFundUrl:()=>xt,normalizeProfileUrl:()=>Ve});function Ve(e){if(!e||typeof e!="string"||/custom-invite|\/search\/|miniProfile/.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function xt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}async function Gs(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10;try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(a=>setTimeout(a,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(a=>setTimeout(a,1200))}catch{}let o;try{o=await e.evaluate(a=>{let l=m=>(m||"").replace(/\s+/g," ").trim(),c=m=>l(m).replace(/^View\s+/i,"").split(/\s*[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\b(1st|2nd|3rd)\b.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),u=m=>{let h=m;for(let g=0;g<6&&h.parentElement;g++)if(h=h.parentElement,h.querySelectorAll('a[href*="/in/"]').length>=2)return h;return m.parentElement},d=[],f=Array.from(document.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let m of f){let h=l(m.textContent).toLowerCase();if(!h)continue;let g=a.find(([v])=>h.includes(v));if(!g)continue;let[,b]=g,w=u(m);if(!w)continue;let S=Array.from(w.querySelectorAll('a[href*="/in/"]')),y=0,p=new Set;for(let v of S){let C=v.href||v.getAttribute("href")||"";if(!/\/in\//.test(C))continue;let _=v.querySelector('span[aria-hidden="true"]'),R=c(_?_.textContent:v.getAttribute("aria-label")||v.textContent);if(!R||p.has(C))continue;p.add(C);let E=v.closest("li")||v.parentElement,M="";E&&(M=Array.from(E.querySelectorAll("p, span")).map(k=>l(k.textContent)).filter(k=>k&&k!==R&&!/^view\b/i.test(k)&&k.length>2)[0]||""),d.push({href:C,name:R,headline:M,block:b,rank:y++})}}return d},Ys)}catch{return[]}let s=Ve(t.seedUrl||""),i=new Map,r={};for(let a of o){let l=Ve(a.href);l&&(s&&l===s||(r[a.block]=r[a.block]||0,!(r[a.block]>=n)&&(i.has(l)||(r[a.block]++,i.set(l,{url:l,name:a.name,headline:a.headline||null,block:a.block,rank:a.rank})))))}return Array.from(i.values())}var Ys,Kt=fe(()=>{Ys=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var po={};ae(po,{getJobDecision:()=>er,getLastVisit:()=>ar,getScoutStats:()=>tn,loadCompanies:()=>en,loadDiscoveredPeople:()=>ht,loadJobDecisions:()=>gt,loadScoutedJobs:()=>pt,loadVisitLog:()=>Tt,recordCompany:()=>rr,recordDiscoveredEdge:()=>or,recordDiscoveredEdges:()=>sr,recordVisit:()=>lr,resetCaches:()=>Xt,saveCompany:()=>ir,saveDiscoveredPerson:()=>tr,saveScoutedJob:()=>Zs,setJobDecision:()=>Xs});import"dotenv/config";import*as X from"fs";import*as K from"path";import{fileURLToPath as zs}from"url";function we(){X.existsSync(Ie)||X.mkdirSync(Ie,{recursive:!0})}function be(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";X.writeFileSync(o,n);for(let s=0;s<3;s++)try{X.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function mt(e){try{if(X.existsSync(e))return JSON.parse(X.readFileSync(e,"utf-8"))}catch{}return null}function Xt(){ct=null,ut=null,ft=null,dt=null,De=null}function pt(){return ct||(ct=mt(ao)||{},ct)}function Zs(e,t){if(!e)return;we();let n=pt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{be(ao,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function gt(){return ut||(ut=mt(uo)||{},ut)}function Xs(e,t,n={}){if(!e||!t)return;we();let o=gt(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{be(uo,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function er(e){return gt()[e]||null}function ht(){return ft||(ft=mt(_t)||{},ft)}function We(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function fo(e,t){let n=Ve(t)||t;if(e[n])return n;let o=We(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(We(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function tr(e,t){if(!e)return;we();let n=ht(),o=new Date().toISOString().slice(0,10),s=fo(n,e),i=We(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&We(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{be(_t,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function nr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function mo(e,t,n={},o){if(!t)return;let s=We(t);t=fo(e,t);let i=n.seedUrl?{...n,seedUrl:Ve(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:a,match:l}=nr(i,o),c=e[t];c||(c=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:a.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:a.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:r,firstSeen:r,lastSeen:r}),n.name&&(c.name=n.name),n.headline&&(c.headline=c.headline||n.headline),n.location&&(c.location=c.location||n.location),n.company&&(c.company=n.company),n.companyUrl&&(c.companyUrl=c.companyUrl||n.companyUrl),n.isConnected!=null&&(c.isConnected=n.isConnected),n.connectionsCount!=null&&(c.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(c.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(c.connectGate=n.connectGate),n.note&&!c.note&&(c.note=n.note),n.whyUseful&&!c.whyUseful&&(c.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(c.extra={...c.extra||{},...n.extra}),Array.isArray(c.sources)||(c.sources=[]);let u=c.sources.find(l);if(u?(a.rank!=null&&(u.rank==null||a.rank<u.rank)&&(u.rank=a.rank),u.at=a.at):c.sources.push(a),Array.isArray(c.categories)||(c.categories=[]),Array.isArray(c.sectors)||(c.sectors=[]),Array.isArray(c.aliases)||(c.aliases=[]),Array.isArray(c.graphRefs)||(c.graphRefs=[]),Qt(c.categories,n.category),Et(c.categories,n.categories),Et(c.sectors,n.sectors),Et(c.aliases,n.aliases),s&&We(c.canonicalUrl||t)!==s&&Qt(c.aliases,s),Et(c.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(c.affiliations)||(c.affiliations=[]);for(let d of n.affiliations)!d||!d.companyKey||c.affiliations.some(f=>f.companyKey===d.companyKey&&f.role===d.role)||c.affiliations.push(d)}c.lastSeen=r,c.seenCount=(c.seenCount||0)+1}function or(e,t={}){if(!e)return;we();let n=ht();mo(n,e,t,new Date().toISOString());try{be(_t,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function sr(e){if(!Array.isArray(e)||e.length===0)return;we();let t=ht(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||(mo(t,s.url,s,n),o++);if(o)try{be(_t,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function rr(e={}){if(!e||!e.name)return;we();let t=e.key||xt(e.website)||xt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=en(),o=new Date().toISOString().slice(0,10),s=(l,c)=>{c&&Array.isArray(l)&&!l.includes(c)&&l.push(c)},i=(l,c)=>{if(Array.isArray(c))for(let u of c)s(l,u)},r=n[t];r||(r=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!r[l]&&(r[l]=e[l]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[l])||(r[l]=[]),i(r[l],e[l]);Array.isArray(r.people)||(r.people=[]);let a=l=>{if(!l||!l.url)return;let c=r.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));c?l.current!=null&&(c.current=l.current):r.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(a),(e.partners||[]).forEach(l=>a({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(r.portfolio)||(r.portfolio=[]);for(let l of e.portfolio||[]){let c=l&&(l.key||l.name);c&&!r.portfolio.some(u=>(u.key||u.name)===c)&&r.portfolio.push(l)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{be(Zt,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function en(){return dt||(dt=mt(Zt)||{},dt)}function ir(e,t){if(!e)return;we();let n=en(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{be(Zt,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function Tt(){return De||(De=mt(co)||{visits:[]},Array.isArray(De.visits)||(De.visits=[]),De)}function lr(e,t={}){if(!e)return;we();let n=Tt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{be(co,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function ar(e){let t=Tt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function tn(){let e=pt(),t=ht(),n=Object.values(e),o=Object.values(t),s={};for(let f of n)f.company&&(s[f.company]=(s[f.company]||0)+1);let i=Object.entries(s).sort((f,m)=>m[1]-f[1]).slice(0,5).map(([f,m])=>`${f} (${m})`),r={};for(let f of n)for(let m of f.techStack||[])r[m]=(r[m]||0)+1;let a=Object.entries(r).sort((f,m)=>m[1]-f[1]).slice(0,8).map(([f,m])=>`${f} (${m})`),l=Tt(),c=new Date().toISOString().slice(0,10),u=l.visits.filter(f=>f.date.startsWith(c)).length,d=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:a,totalVisited:d,todayVisited:u,lastScoutDate:n.length>0?n.sort((f,m)=>(m.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}var Ks,Qs,Ie,ao,_t,co,Zt,uo,ct,ut,ft,Qt,Et,dt,De,yt=fe(()=>{Kt();Ks=zs(import.meta.url),Qs=K.dirname(K.dirname(Ks)),Ie=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(Qs,"market-research"),ao=K.join(Ie,"scouted-jobs.json"),_t=K.join(Ie,"discovered-people.json"),co=K.join(Ie,"visit-log.json"),Zt=K.join(Ie,"companies.json"),uo=K.join(Ie,"job-decisions.json");ct=null;ut=null;ft=null;Qt=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Et=(e,t)=>{if(Array.isArray(t))for(let n of t)Qt(e,n)};dt=null;De=null});var Bo={};ae(Bo,{computeEngagement:()=>un,detectCategory:()=>Mo,detectCategoryFromTitle:()=>It,determineAction:()=>Uo,determineLastMessageBy:()=>Ot,determineSituation:()=>jo,enrichConversation:()=>Nt,enrichPerson:()=>dn,enrichPersonContext:()=>qo,extractAutoTags:()=>Lo,generateSummary:()=>Po,normPreview:()=>ze});function Nt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(l=>!Fe.has(l.status)),i=xr(t,e.profileUrl,n),r=Ot(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Mo(s,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=jo(s,r,t),s.length>0){let l=s[s.length-1];e.lastMessageTime=l.time}if(s.length>0&&!e.initiatedBy){let l=s[0];l.sender===z?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=un(s,t),e.personContext=qo(i),e.summary=Po(e,t,i),e.autoTags=Lo(e,t,i);let a=Uo(e);return e.actionNeeded=a.action,e.actionDetail=a.detail,e.suggestedPriority=Ar(e),e}function Mo(e,t,n){if(!e||e.length===0)return n?.title?It(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(Oo))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=It(n.title);if(s)return s}return null}function It(e){if(!e)return null;for(let[t,n]of Object.entries(Oo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function jo(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 No.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 No.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Ot(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 Po(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,a=n?.company,l=n?.location;i==="recruiter"&&a?s.push(`Recruiter from ${a}`):i==="hiring_manager"&&a?s.push(`Hiring manager at ${a}`):i==="founder"&&a?s.push(`Founder of ${a}`):i&&r?s.push(`${fn(i)}: ${Ge(r,40)}`):r?s.push(Ge(r,50)):s.push(t.split(" ")[0]);let c=o.filter(h=>h.sender!==z&&h.sender!=="Unknown").map(h=>h.text).join(" "),u=Er(c),d=_r(c),f=Tr(c),m=[];return u&&m.push(u),f&&f!==l&&m.push(f),d&&m.push(d),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 Lo(e,t,n){let o=[],s=(e.messages||[]).filter(c=>!Fe.has(c.status)),i=s.map(c=>c.text).join(" "),r=s.filter(c=>c.sender!==z&&c.sender!=="Unknown").map(c=>c.text).join(" "),a=Fo(r,n?.location);o.push(...a),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let l=e.engagement||un(s,t);return l.messageCount>=6&&o.push("active-thread"),l.theirCount===0&&l.ourCount>0&&o.push("no-response"),l.ourCount===0&&l.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(c=>tt.has(c.status))&&o.push("has-draft"),[...new Set(o)]}function Fo(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 r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,a]of s)i.includes(r)&&n.push(a);return n}function Uo(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&ze(e.lastMessagePreview)===ze(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>tt.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:`${fn(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 un(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,r=!1,a=e.map(l=>l.text).join(" ");for(let l of e)l.sender===z?n++:l.sender==="Unknown"||l.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(a),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(a),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function qo(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Ar(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 xr(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=Be(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function ze(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function fn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Er(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 _r(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 Tr(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 dn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=It(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Rr(e),e.personSummary=Dr(e),e.personAutoTags=Ir(e);let n=Nr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Or(e)),e}function Rr(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 Dr(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(`${Ge(o,40)} at ${Ge(s,30)}`):o?t.push(Ge(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${a[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${Ge(e.lastJobTitle,30)}`,e.lastJobDate){let a=new Date(e.lastJobDate);isNaN(a)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]} ${a.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function Ir(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=Fo("",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 Nr(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:`${fn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Or(e){let t=e.category;if(!t)return null;let n=Mr(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 Mr(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var Oo,No,mn=fe(async()=>{await nt();await Je();Oo={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]}};No=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var is={};ae(is,{extractCertificationsFromDetails:()=>Li,extractEducationFromDetails:()=>ji,extractExperienceFromDetails:()=>Oi,extractFeaturedFromDetails:()=>Mi,extractRecommendationsFromDetails:()=>Fi,extractSkillsFromDetails:()=>Pi});async function Oi(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 r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.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 r(u){let d=[];for(let f of u.querySelectorAll("div")){let m=Array.from(f.children).filter(g=>g.tagName==="DIV");if(m.length<3)continue;let h=m.filter(g=>(g.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,m)=>m.count-f.count||f.totalText-m.totalText),d[0]?.el}let a=r(i);if(!a)return[];let l=Array.from(a.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function c(u){let d=u[0]||null,f=null,m=null;if(u[1]){let E=u[1].split("\xB7").map(M=>M.trim());f=E[0]||null,E[1]&&(m=E[1])}let h=u.findIndex(E=>/(\d{4}|present)/i.test(E)&&/(-|–|—)/i.test(E)&&E.length<80),g=null,b=null;if(h>=0){let E=u[h].split("\xB7").map(M=>M.trim());g=E[0]||null,E[1]&&(b=E[1])}let w=null,S=-1;if(h>=0&&u[h+1]){let E=u[h+1],M=/^[>*\-•]|^&gt;/.test(E),Y=/https?:\/\//.test(E),k=/\d{4}/.test(E),A=/,/.test(E)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(E);!M&&!Y&&!k&&E.length<100&&A&&(w=E,S=h+1)}let y=null,p=-1,v=u[u.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){p=u.length-1;let E=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);E&&(y={listed:E[1].split(",").map(M=>M.trim()),additional:parseInt(E[2],10)})}let C=new Set([0,1,h,S,p].filter(E=>E>=0)),_=u.filter((E,M)=>!C.has(M)),R=_.length>0?_.join(`
2
2
 
3
- `):null;return{title:f,company:u,employmentType:m,dates:g,duration:b,location:w,description:D,skills:h,_raw:c}}return i.map(c=>{let u=(c.innerText||"").trim().split(`
4
- `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return d(u)}).filter(c=>c.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 lt(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 r=0;for(;r<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});)r++,await $(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(600)}async function ut(e,t,n,o){try{return await o()}catch(s){let r=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(r))throw s;return/not available on profile/i.test(r)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${r.slice(0,120)}`),[])}}async function ni(e,t){return ut(t,"featured","extractFeaturedFromDetails",async()=>(await lt(e,t,"featured"),await e.evaluate(`(() => {
5
- ${ct}
3
+ `):null;return{title:d,company:f,employmentType:m,dates:g,duration:b,location:w,description:R,skills:y,_raw:u}}return l.map(u=>{let f=(u.innerText||"").trim().split(`
4
+ `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return c(f)}).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 wt(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 r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);await $(800);let i=0;for(;i<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});)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 Mi(e,t){return St(t,"featured","extractFeaturedFromDetails",async()=>(await wt(e,t,"featured"),await e.evaluate(`(() => {
5
+ ${bt}
6
6
 
7
7
  const main = document.querySelector('main');
8
8
  if (!main) return [];
@@ -42,8 +42,8 @@ var Go=Object.defineProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var Me=(e,t)=>{
42
42
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
43
  return true;
44
44
  });
45
- })()`)))}async function oi(e,t){return ut(t,"education","extractEducationFromDetails",async()=>(await lt(e,t,"education"),await e.evaluate(`(() => {
46
- ${ct}
45
+ })()`)))}async function ji(e,t){return St(t,"education","extractEducationFromDetails",async()=>(await wt(e,t,"education"),await e.evaluate(`(() => {
46
+ ${bt}
47
47
 
48
48
  const main = document.querySelector('main');
49
49
  if (!main) return [];
@@ -79,8 +79,8 @@ var Go=Object.defineProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var Me=(e,t)=>{
79
79
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
80
  return true;
81
81
  });
82
- })()`)))}async function si(e,t){return ut(t,"skills","extractSkillsFromDetails",async()=>(await lt(e,t,"skills"),await e.evaluate(`(() => {
83
- ${ct}
82
+ })()`)))}async function Pi(e,t){return St(t,"skills","extractSkillsFromDetails",async()=>(await wt(e,t,"skills"),await e.evaluate(`(() => {
83
+ ${bt}
84
84
 
85
85
  const main = document.querySelector('main');
86
86
  if (!main) return [];
@@ -111,8 +111,8 @@ var Go=Object.defineProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var Me=(e,t)=>{
111
111
  skills.push({ name, endorsements, _raw: lines });
112
112
  }
113
113
  return skills;
114
- })()`)))}async function ri(e,t){return ut(t,"certifications","extractCertificationsFromDetails",async()=>(await lt(e,t,"certifications"),await e.evaluate(`(() => {
115
- ${ct}
114
+ })()`)))}async function Li(e,t){return St(t,"certifications","extractCertificationsFromDetails",async()=>(await wt(e,t,"certifications"),await e.evaluate(`(() => {
115
+ ${bt}
116
116
 
117
117
  const main = document.querySelector('main');
118
118
  if (!main) return [];
@@ -136,8 +136,8 @@ var Go=Object.defineProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var Me=(e,t)=>{
136
136
 
137
137
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
138
  }).filter(e => e.name);
139
- })()`)))}async function ii(e,t){return ut(t,"recommendations","extractRecommendationsFromDetails",async()=>(await lt(e,t,"recommendations"),await e.evaluate(`(() => {
140
- ${ct}
139
+ })()`)))}async function Fi(e,t){return St(t,"recommendations","extractRecommendationsFromDetails",async()=>(await wt(e,t,"recommendations"),await e.evaluate(`(() => {
140
+ ${bt}
141
141
 
142
142
  const main = document.querySelector('main');
143
143
  if (!main) return [];
@@ -172,7 +172,7 @@ var Go=Object.defineProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var Me=(e,t)=>{
172
172
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
173
  return true;
174
174
  });
175
- })()`)))}var ct,Do=Ye(()=>{Oe();ct=`
175
+ })()`)))}var bt,ls=fe(()=>{Le();bt=`
176
176
  function findEntryContainer(root) {
177
177
  const candidates = [];
178
178
  for (const div of root.querySelectorAll('div')) {
@@ -235,130 +235,130 @@ function findEntryContainer(root) {
235
235
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
236
  return candidates[0]?.el;
237
237
  }
238
- `});var Oo={};Me(Oo,{clickConnectButton:()=>sn,default:()=>ci,detectConnectionStatus:()=>be,findConnectButton:()=>dt,runFunnel:()=>Mo,sendConnectionRequest:()=>rn,shouldExcludeLocation:()=>kt,viewProfile:()=>on});async function Io(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function kt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function on(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:r=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:i=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await Se(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await Io(e,t));let c=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let A=1;A<=6;A++)await e.evaluate(D=>window.scrollTo(0,D),v*A/6),await $(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===c)break;c=C}await $(800);let f=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(f=p.split("?")[0].replace(/\/+$/,""))}catch{}let u=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),v=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"]),C=R=>{let I=(R||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},A={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:[]},D=document.querySelector("main");if(!D)return A;let T=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],F=Array.from(D.querySelectorAll("h2")),G=T.find(R=>{let I=R.textContent&&R.textContent.trim(),O=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!p.has(O)&&!v.has(O)}),k=G?G.textContent.trim():null,E=G?G.parentElement:null;for(;E&&E!==D&&!Array.from(E.children).filter(I=>I.tagName==="P").some(I=>{let O=I.textContent&&I.textContent.trim();return O&&O.length>5&&!C(O)});)E=E.parentElement;let _=null,M=null,H=null,se=null;if(E&&E!==D){let R=Array.from(E.children).filter(O=>O.tagName==="P").filter(O=>{let me=O.textContent&&O.textContent.trim();return me&&me.length>5&&!C(me)});if(R[0]&&(_=R[0].textContent.trim()),R[1]){let O=R[1].textContent.trim().split(/\s*[·•]\s*/);M=O[0]||null,O.length>1&&(H=O.slice(1).join(" \xB7 "))}let I=Array.from(E.children).filter(O=>O.tagName==="DIV");for(let O=I.length-1;O>=0;O--){let me=I[O].textContent&&I[O].textContent.trim();if(me&&!(k&&me.startsWith(k))&&(se=me.split(/[·•]/)[0].trim(),se))break}}let re=null;if(E){let R=E.querySelectorAll("p, span, div");for(let I of R){let O=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){re=O;break}}}let j=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),P=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=P&&P.src||null,q=D.textContent||"",ie=null,fn=q.match(/(\d+\+?)\s+connections\b/i);fn&&(ie=fn[1]+" connections");let mt=null,mn=q.match(/(\d+)\s+mutual connection/i),pn=q.match(/and\s+(\d+)\s+other mutual/i),Ho=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);mn?mt=parseInt(mn[1],10):pn?mt=2+parseInt(pn[1],10):Ho&&(mt=2);let gn=null,hn=null,yn=F.find(R=>R.textContent&&R.textContent.trim()==="About");if(yn){let R=yn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let I=(R.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let O=I.match(/Top skills\s*(.+?)$/i);if(O){let Et=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Yo=>Yo.trim()).filter(Boolean);Et.length>0&&Et.length<10&&(hn=Et)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),gn=I||null}}let wn=null,bn=F.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(bn){let R=bn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let I=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(wn=parseInt(I[1].replace(/,/g,""),10))}}let Jo=[...new Set(F.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==k).filter(R=>p.has(R)))],We=document.body.textContent||"",Vo=/#OpenToWork\b/i.test(We)||/\bOpen to work\b/.test(We),Wo=/#Hiring\b/i.test(We)||/\bI'?m hiring\b/i.test(We)||/\bWe are hiring\b/i.test(We);return{name:k,title:_,location:se,currentCompany:M,currentSchool:H,connectionDegree:re,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:ie,mutualConnectionsCount:mt,followers:wn,openToWork:Vo,hiring:Wo,about:gn,topSkills:hn,availableSections:Jo}});console.log(`Viewed: ${u.name} - ${u.title}`);let m=null,y=null,g=null,b=null,w=null,S=null;if(o||s||r||a||l||i){let p=await Promise.resolve().then(()=>(Do(),Ro));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(y=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${y.length} entries`)),r&&(g=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),a&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),l&&(w=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),i&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...u,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...y!==null&&{featured:y},...g!==null&&{education:g},...b!==null&&{skillsFull:b},...w!==null&&{recommendations:w},...S!==null&&{certifications:S}}}catch(d){console.error(`Error viewing profile ${t}:`,d.message);try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(d.message||""))throw d;return null}}async function be(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',r=f=>f&&!f.closest(s),a=f=>Array.from(document.querySelectorAll(f)).filter(r),l=a('button[aria-label*="Pending"], a[aria-label*="Pending"]'),i=a('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,d=a('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,c={pendingCount:l.length,pendingLabels:l.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!i,hasConnectBtn:!!d};return l.length>0?{status:"pending",debug:c}:i&&!d?{status:"connected",debug:c}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:c}:{status:"not_connected",debug:c}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await $(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function dt(e){let t=null,n=await e.evaluate(()=>{let d=document.querySelector("h1")?.textContent?.trim();if(d&&!d.includes("notification"))return d;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(d=c.textContent?.trim(),d&&!d.includes("notification")))return d;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let u=document.title;return u&&u.includes("|")?u.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let d=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(u=>u.getAttribute("aria-label")?.slice(0,50))}});d.count>0&&console.log(` S0: ${d.count} custom-invite links: ${JSON.stringify(d.labels)}`),t=await e.evaluateHandle(f=>{let u=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],y='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of u){let b=g.getBoundingClientRect();if(b.width===0||b.height===0||g.closest(y))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(m))return g}return 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 d=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${d}"`);let c=await e.evaluate(u=>{let m=new RegExp("\\b"+u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),y=document.querySelectorAll("button[aria-label]");return Array.from(y).filter(b=>{let w=b.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&m.test(w)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},d);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(u=>{let m=document.querySelectorAll("button[aria-label]"),y='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(y))continue;let w=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(w)&&(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&g.test(w))return b}return null},d);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let d=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),c=n.split(" ")[0].toLowerCase();d.includes("invite")&&!d.includes(c)&&(console.log(` Skipping primary button: wrong person (${d})`),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():"",r=null;for(let d of o){let c=await e.evaluate((f,u)=>{let m=f.className.includes("muted"),y=f.className.includes("sticky-header")||f.className.includes("sticky"),g=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(f.getAttribute("aria-label")||"").toLowerCase(),w=b.includes("invite"),S=u?b.includes(u):!0;return{isMuted:m,isStickyHeader:y,inRecommendations:g,hasInvite:w,matchesName:S,ariaLabel:b}},d,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}r=d;break}}for(let d of o)d!==r&&await d.dispose().catch(()=>{});if(r)return console.log(" Found: secondary button"),{button:r,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 d of l){let c=await e.evaluate(f=>{let u=f.getBoundingClientRect(),m=u.width>0&&u.height>0,y=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:y,top:u.top}},d);if(c.isVisible&&!c.isInStickyHeader){a=d,console.log(" Found More button by ID pattern (main)");break}}for(let d of l)d!==a&&await d.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 d=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let y=m.innerText?.trim(),g=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:y==="Follow"||y==="Message"||y==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!f)return null;let u=f.parentElement;for(let m=0;m<8&&u;m++){for(let y of u.querySelectorAll("button"))if(y.innerText?.trim()==="More"&&y!==f)return y;u=u.parentElement}return null});a=d?.asElement?.()||null,a||await d?.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" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!c){let u=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let y of m){let g=y.querySelector('a[href*="custom-invite"]');if(g)return g;for(let b of y.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}return null});c=u?.asElement?.()||null,c||await u?.dispose?.().catch(()=>{})}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};let f=await e.evaluate(()=>{let u=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let y of u)for(let g of y.querySelectorAll('[role="menuitem"], a, div')){let b=g.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(u=>/remove (your )?connection/i.test(u)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(d){console.log(" More dropdown click failed:",d.message),await e.keyboard.press("Escape")}let i=await e.evaluateHandle(d=>{let c='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(d||"").split(" ")[0].toLowerCase();for(let u of document.querySelectorAll("button[aria-label]")){if(u.closest(c))continue;let m=(u.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let y=u.getBoundingClientRect();if(!(y.width===0||y.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return u;continue}if(m==="connect")return u}}return null},n||"");return t=i?.asElement?.()||null,t||await i?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function sn(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"),r=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(a))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(a.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!a.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await $(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 r?(await e.evaluate(c=>c.click(),t),await $(3e3)):(await e.evaluate(c=>c.click(),t),await $(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let i=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),d=e.url();return console.log(i?` \u2713 Connect sent \u2014 ${d}`:` \u26A0 No modal after connect click \u2014 ${d}`),"success"}async function ai(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 dt(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)return await Je(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Je(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(a=>{let l=i=>!!(i&&i.querySelector(a));return!(l(document)||l(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let a of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(a.innerText||""))return!0;return!1}),r=async()=>{let a=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(a)return a;let l=await e.evaluateHandle(i=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(i)||null,n);return a=l?.asElement?.()||null,a||await l?.dispose?.().catch(()=>{}),a};for(let a=0;a<2;a++){try{await t.evaluate(l=>l.click())}catch{}if(await $(3e3),await s())return!1;if(await o())return!0;if(a===0){let l=await r();if(!l)return await o();t=l,await $(600)}}return await o()}async function rn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:r=!1}=n;if(!s){let l=Dt();if(!l.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${l.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:l.reason,profileInfo:null}}let a=await li(e,t,n);return a.connectionSent&&!r&&jn(t,o),a}async function li(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:r=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let d=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
- --- Connecting: ${d} ---`),l.length>0){let w=J()[t]?.location;if(kt(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),i.reason="excluded_location",i.profileInfo={location:w},i}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await Se(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await Io(e,t),await $(2e3)),i.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 P=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},h={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return h;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),A=v.find(j=>{let P=j.textContent&&j.textContent.trim();return P&&P.length>1&&P.length<100&&!w.has(P)&&P!=="0 notifications"}),D=A?A.textContent.trim():null,T=A?A.parentElement:null;for(;T&&T!==p&&!Array.from(T.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)T=T.parentElement;let F=null,G=null,k=null;if(T&&T!==p){let j=Array.from(T.children),P=j.filter(q=>q.tagName==="P").filter(q=>{let ie=q.textContent&&q.textContent.trim();return ie&&ie.length>5&&!S(ie)});P[0]&&(F=P[0].textContent.trim()),P[1]&&(G=P[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let ie=U[q].textContent&&U[q].textContent.trim();if(ie&&!(D&&ie.startsWith(D))&&(k=ie.split(/[·•]/)[0].trim(),k))break}}let E=null;if(T){let j=T.querySelectorAll("p, span, div");for(let P of j){let U=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){E=U;break}}}let _=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&&(_=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,_&&(_=_.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),se=H&&H.src||null,re=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:D,title:F,location:k,about:_,company:G,connectionDegree:E,connectionsCount:null,mutualConnections:null,photoUrl:se,hasVerifiedBadge:re}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(i.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(l.length>0){let w=i.profileInfo?.location,S=J()[t]?.location,h=w||S;if(kt(h,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${h}`),i.reason="excluded_location",i;!w&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await be(e,{detail:!0})).status==="pending"&&r)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;await Se(e);let u=await dt(e);if(u||await Se(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),u=await dt(e)),u&&u.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),i.reason="connected",i;if(!u){let w=await be(e,{detail:!0});return a&&(w.status==="connected"||w.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),i.reason="connected",i):(console.log(" \u2717 Connect not found"),i.reason="button_not_found",i)}i.method=u.method;let m=await sn(e,u.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),i.reason="wrong_target",i;if(m==="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 be(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await Se(e),await $(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await $(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await $(2e3);let h=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(h){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),h),await $(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),i.reason="premium_required",i;if(await be(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;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),i.reason="premium_required",i}catch(h){return console.log(" More dropdown failed:",h.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.evaluate(()=>{let w=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of w){let h=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!h)continue;let p=(h.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||h.querySelector('input[type="email"], input[name="email"]'))return!0;let v=h.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let w=await e.$('button[aria-label="Dismiss"]');if(w)try{await w.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await $(500),i.reason="email_required",i}let g=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!g&&!b){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let h=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!h,sendWithout:!!p}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=S?.asElement?.()||null,g||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(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await $(1500),await e.$("div.modal-upsell")){let h=await ai(e);return i.success=h,i.connectionSent=h,i.reason=h?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let h=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",h);await S.type(p,{delay:20}),await $(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Je(e,v)?(console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=p,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i)}}else{if(b)return console.log(" Sending without note..."),await Je(e,b)?(console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i);if(g&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w)return await Je(e,w)?(console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i)}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w)return await Je(e,w)?(console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i)}if(u.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 Se(e),await $(500);let S=await e.$$('button[id*="profile-overflow-action"]'),h=null;for(let p of S){let v=await e.evaluate(C=>{let A=C.getBoundingClientRect();return{visible:A.width>0&&A.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){h=p;break}}!h&&S.length>0&&(h=S[S.length-1]);for(let p of S)p!==h&&await p.dispose().catch(()=>{});if(h)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),h),await $(500),await h.click().catch(()=>e.evaluate(v=>v.click(),h)),await $(2e3);let p=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(p){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(D=>D.click(),p),await $(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await be(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await be(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let A=await e.$('button[aria-label="Send without a note"]');if(A)return console.log(" Modal appeared via More dropdown, sending without note..."),await Je(e,A)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),i.reason="modal_failed",i);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(p){console.log(" More dropdown fallback failed:",p.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(d){console.error(` \u2717 Error: ${d.message}`),i.reason="error",i.error=d.message;let c=d.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{i.fatal=!0}return i}}async function Mo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:r=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:i=null,excludeLocations:d=[],source:c="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
240
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${a?"View Only":`Connect (max ${r})`}`),a||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),d.length>0&&console.log(`Excluding locations: ${d.join(", ")}`),!a){let m=nt();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let u=0;for(let m=0;m<t.length;m++){let y=t[m];try{if(e.isClosed()){console.log(`
238
+ `});var cs={};ae(cs,{DEFAULT_PROFILE_INTERESTS:()=>as,computeFit:()=>Bi,detectSectors:()=>qi});function qi(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(Ui))s.some(i=>i.test(t))&&n.push(o);return n}function Bi(e,t=as){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var Ui,as,us=fe(()=>{Ui={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};as={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var ms={};ae(ms,{clickConnectButton:()=>xn,default:()=>Vi,detectConnectionStatus:()=>Ce,findConnectButton:()=>vt,runFunnel:()=>ds,sendConnectionRequest:()=>En,shouldExcludeLocation:()=>Ft,viewProfile:()=>An});async function fs(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Ft(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function An(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await fs(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(R=>window.scrollTo(0,R),v*_/6),await $(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await $(800);let d=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(d=p.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),v=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"]),C=D=>{let I=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},_={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:[]},R=document.querySelector("main");if(!R)return _;let E=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],M=Array.from(R.querySelectorAll("h2")),Y=E.find(D=>{let I=D.textContent&&D.textContent.trim(),O=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!p.has(O)&&!v.has(O)}),k=Y?Y.textContent.trim():null,A=Y?Y.parentElement:null;for(;A&&A!==R&&!Array.from(A.children).filter(I=>I.tagName==="P").some(I=>{let O=I.textContent&&I.textContent.trim();return O&&O.length>5&&!C(O)});)A=A.parentElement;let T=null,N=null,H=null,re=null;if(A&&A!==R){let D=Array.from(A.children).filter(O=>O.tagName==="P").filter(O=>{let he=O.textContent&&O.textContent.trim();return he&&he.length>5&&!C(he)});if(D[0]&&(T=D[0].textContent.trim()),D[1]){let O=D[1].textContent.trim().split(/\s*[·•]\s*/);N=O[0]||null,O.length>1&&(H=O.slice(1).join(" \xB7 "))}let I=Array.from(A.children).filter(O=>O.tagName==="DIV");for(let O=I.length-1;O>=0;O--){let he=I[O].textContent&&I[O].textContent.trim();if(he&&!(k&&he.startsWith(k))&&(re=he.split(/[·•]/)[0].trim(),re))break}}let ie=null;if(A){let D=A.querySelectorAll("p, span, div");for(let I of D){let O=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){ie=O;break}}}let P=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=L&&L.src||null,q=R.textContent||"",le=null,Nn=q.match(/(\d+\+?)\s+connections\b/i);Nn&&(le=Nn[1]+" connections");let $t=null,On=q.match(/(\d+)\s+mutual connection/i),Mn=q.match(/and\s+(\d+)\s+other mutual/i),ks=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);On?$t=parseInt(On[1],10):Mn?$t=2+parseInt(Mn[1],10):ks&&($t=2);let jn=null,Pn=null,Ln=M.find(D=>D.textContent&&D.textContent.trim()==="About");if(Ln){let D=Ln.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;if(D){let I=(D.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let O=I.match(/Top skills\s*(.+?)$/i);if(O){let qt=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(xs=>xs.trim()).filter(Boolean);qt.length>0&&qt.length<10&&(Pn=qt)}I=I.split(/\n?…\s*more/i)[0].trim(),I=I.split(/\n?\.\.\.\s*more/i)[0].trim(),I=I.split(/\bTop skills\b/i)[0].trim(),I=I.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),jn=I||null}}let Fn=null,Un=M.find(D=>D.textContent&&D.textContent.trim()==="Activity");if(Un){let D=Un.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;if(D){let I=(D.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(Fn=parseInt(I[1].replace(/,/g,""),10))}}let $s=[...new Set(M.map(D=>(D.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(D=>D&&D.length>1&&D.length<60&&D!==k).filter(D=>p.has(D)))],Xe=document.body.textContent||"",Cs=/#OpenToWork\b/i.test(Xe)||/\bOpen to work\b/.test(Xe),As=/#Hiring\b/i.test(Xe)||/\bI'?m hiring\b/i.test(Xe)||/\bWe are hiring\b/i.test(Xe);return{name:k,title:T,location:re,currentCompany:N,currentSchool:H,connectionDegree:ie,hasVerifiedBadge:P,photoUrl:U,connectionsLevel:le,mutualConnectionsCount:$t,followers:Fn,openToWork:Cs,hiring:As,about:jn,topSkills:Pn,availableSections:$s}});console.log(`Viewed: ${f.name} - ${f.title}`);let m=null,h=null,g=null,b=null,w=null,S=null;if(o||s||i||r||a||l){let p=await Promise.resolve().then(()=>(ls(),is));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(h=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),i&&(g=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),r&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),a&&(w=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),l&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...m!==null&&{experience:m},...h!==null&&{featured:h},...g!==null&&{education:g},...b!==null&&{skillsFull:b},...w!==null&&{recommendations:w},...S!==null&&{certifications:S}}}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 Ce(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=d=>d&&!d.closest(s),r=d=>Array.from(document.querySelectorAll(d)).filter(i),a=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:a.length,pendingLabels:a.map(d=>d.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await $(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function vt(e){let t=null,n=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let c=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),m=d.toLowerCase().split(" ")[0],h='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of f){let b=g.getBoundingClientRect();if(b.width===0||b.height===0||g.closest(h))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(m))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let c=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(f=>{let m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),h=document.querySelectorAll("button[aria-label]");return Array.from(h).filter(b=>{let w=b.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&m.test(w)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let m=document.querySelectorAll("button[aria-label]"),h='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(h))continue;let w=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(w)&&(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&g.test(w))return b}return null},c);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,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 c=await e.evaluate(d=>(d.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),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 c of o){let u=await e.evaluate((d,f)=>{let m=d.className.includes("muted"),h=d.className.includes("sticky-header")||d.className.includes("sticky"),g=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(d.getAttribute("aria-label")||"").toLowerCase(),w=b.includes("invite"),S=f?b.includes(f):!0;return{isMuted:m,isStickyHeader:h,inRecommendations:g,hasInvite:w,matchesName:S,ariaLabel:b}},c,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of o)c!==i&&await c.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 r=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(d=>{let f=d.getBoundingClientRect(),m=f.width>0&&f.height>0,h=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:h,top:f.top}},c);if(u.isVisible&&!u.isInStickyHeader){r=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==r&&await c.dispose().catch(()=>{});if(!r&&a.length>0&&(r=a[a.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let c=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(m=>{let h=m.innerText?.trim(),g=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:h==="Follow"||h==="Message"||h==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!d)return null;let f=d.parentElement;for(let m=0;m<8&&f;m++){for(let h of f.querySelectorAll("button"))if(h.innerText?.trim()==="More"&&h!==d)return h;f=f.parentElement}return null});r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),r),await $(500),await e.evaluate(f=>f.click(),r),await $(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let f=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let h of m){let g=h.querySelector('a[href*="custom-invite"]');if(g)return g;for(let b of h.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}return null});u=f?.asElement?.()||null,u||await f?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let d=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let h of f)for(let g of h.querySelectorAll('[role="menuitem"], a, div')){let b=g.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(f=>/remove (your )?connection/i.test(f)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',d=(c||"").split(" ")[0].toLowerCase();for(let f of document.querySelectorAll("button[aria-label]")){if(f.closest(u))continue;let m=(f.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let h=f.getBoundingClientRect();if(!(h.width===0||h.height===0)){if(m.includes("invite")){if(d&&m.includes(d))return f;continue}if(m==="connect")return f}}return null},n||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function xn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await $(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await $(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await $(3e3)):(await e.evaluate(u=>u.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')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function Hi(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 vt(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)return await Qe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Qe(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let a=l=>!!(l&&l.querySelector(r));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,n);return r=a?.asElement?.()||null,r||await a?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(a=>a.click())}catch{}if(await $(3e3),await s())return!1;if(await o())return!0;if(r===0){let a=await i();if(!a)return await o();t=a,await $(600)}}return await o()}async function En(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let a=Yt();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let r=await Ji(e,t,n);return r.connectionSent&&!i&&oo(t,o),r}async function Ji(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!0,excludeLocations:a=[]}=n,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
+ --- Connecting: ${c} ---`),a.length>0){let w=J()[t]?.location;if(Ft(w,a))return console.log(` \u26A0 Excluded location (stored): ${w}`),l.reason="excluded_location",l.profileInfo={location:w},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await fs(e,t),await $(2e3)),process.env.LINKEDIN_DISCOVERY==="1")try{let{extractSidePanelProfiles:w,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(Kt(),lo)),{recordDiscoveredEdges:y}=await Promise.resolve().then(()=>(yt(),po)),{detectCategoryFromTitle:p}=await mn().then(()=>Bo),{detectSectors:v}=await Promise.resolve().then(()=>(us(),cs)),C=S(t)||t,_=await w(e,{seedUrl:C}),R=_.map(E=>{let M=E.headline?p(E.headline):null;return{url:E.url,seedUrl:C,block:E.block,rank:E.rank,name:E.name,headline:E.headline,categories:M?[M]:[],sectors:v(E.headline||"")}});y(R),_.length&&console.log(` \xB7 discovery: harvested ${_.length} related profiles`)}catch(w){process.env.LINKEDIN_DISCOVERY_DEBUG==="1"&&console.log(` \xB7 discovery harvest skipped: ${w.message}`)}l.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=P=>{let L=(P||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},y={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return y;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),_=v.find(P=>{let L=P.textContent&&P.textContent.trim();return L&&L.length>1&&L.length<100&&!w.has(L)&&L!=="0 notifications"}),R=_?_.textContent.trim():null,E=_?_.parentElement:null;for(;E&&E!==p&&!Array.from(E.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)E=E.parentElement;let M=null,Y=null,k=null;if(E&&E!==p){let P=Array.from(E.children),L=P.filter(q=>q.tagName==="P").filter(q=>{let le=q.textContent&&q.textContent.trim();return le&&le.length>5&&!S(le)});L[0]&&(M=L[0].textContent.trim()),L[1]&&(Y=L[1].textContent.trim());let U=P.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let le=U[q].textContent&&U[q].textContent.trim();if(le&&!(R&&le.startsWith(R))&&(k=le.split(/[·•]/)[0].trim(),k))break}}let A=null;if(E){let P=E.querySelectorAll("p, span, div");for(let L of P){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){A=U;break}}}let T=null,N=C.find(P=>P.textContent&&P.textContent.trim()==="About");if(N){let P=N.parentElement;for(;P&&P.tagName!=="SECTION";)P=P.parentElement;P&&(T=(P.textContent||"").trim().replace(/^About\s*/,"").trim()||null,T&&(T=T.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),re=H&&H.src||null,ie=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:M,location:k,about:T,company:Y,connectionDegree:A,connectionsCount:null,mutualConnections:null,photoUrl:re,hasVerifiedBadge:ie}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(l.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let w=l.profileInfo?.location,S=J()[t]?.location,y=w||S;if(Ft(y,a))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${y}`),l.reason="excluded_location",l;!w&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ce(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await Ae(e);let f=await vt(e);if(f||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),f=await vt(e)),f&&f.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!f){let w=await Ce(e,{detail:!0});return r&&(w.status==="connected"||w.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=f.method;let m=await xn(e,f.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let w=await Ce(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await Ae(e),await $(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await $(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await $(2e3);let y=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(y){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),y),await $(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),l.reason="premium_required",l;if(await Ce(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await $(500),l.reason="premium_required",l}catch(y){return console.log(" More dropdown failed:",y.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let w=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of w){let y=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!y)continue;let p=(y.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||y.querySelector('input[type="email"], input[name="email"]'))return!0;let v=y.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let w=await e.$('button[aria-label="Dismiss"]');if(w)try{await w.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await $(500),l.reason="email_required",l}let g=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!g&&!b){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let y=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!y,sendWithout:!!p}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=S?.asElement?.()||null,g||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(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await $(1500),await e.$("div.modal-upsell")){let y=await Hi(e);return l.success=y,l.connectionSent=y,l.reason=y?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let y=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",y);await S.type(p,{delay:20}),await $(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Qe(e,v)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=p,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(b)return console.log(" Sending without note..."),await Qe(e,b)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(g&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w)return await Qe(e,w)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w)return await Qe(e,w)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(f.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 Ae(e),await $(500);let S=await e.$$('button[id*="profile-overflow-action"]'),y=null;for(let p of S){let v=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){y=p;break}}!y&&S.length>0&&(y=S[S.length-1]);for(let p of S)p!==y&&await p.dispose().catch(()=>{});if(y)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),y),await $(500),await y.click().catch(()=>e.evaluate(v=>v.click(),y)),await $(2e3);let p=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(p){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(R=>R.click(),p),await $(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await Ce(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await Ce(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let _=await e.$('button[aria-label="Send without a note"]');if(_)return console.log(" Modal appeared via More dropdown, sending without note..."),await Qe(e,_)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(p){console.log(" More dropdown fallback failed:",p.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.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 l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{l.fatal=!0}return l}}async function ds(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
240
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!r){let m=at();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let f=0;for(let m=0;m<t.length;m++){let h=t[m];try{if(e.isClosed()){console.log(`
241
241
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
242
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let g=Mn(y.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,i&&await i(y,f,{success:!1,reason:g,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 on(e,y.profileUrl);w?(Ce(y.profileUrl,{...w,source:c}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w,resolvedUrl:w.resolvedUrl}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=r){console.log(` Max connections per session (${r}) reached`);break}let w=Dt();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await rn(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:d,source:c,skipQuotaGate:!0}),b.success)f.connectionsSent++;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(`
243
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(b?.reason==="error"){if(u++,u>=3){console.log(`
244
- \u26A0 ${u} consecutive errors \u2014 aborting funnel`);break}}else u=0;if(b&&b.reason&&(On(y.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&gt(y.profileUrl,b.resolvedUrl),In(y.profileUrl,{source:c||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:b.reason})),i&&await i(y,f,b),m<t.length-1){let w=l+Math.random()*2e3;await $(w)}}if(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=nt();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var ci,No=Ye(async()=>{Oe();await Ue();ci={viewProfile:on,detectConnectionStatus:be,findConnectButton:dt,clickConnectButton:sn,sendConnectionRequest:rn,runFunnel:Mo,shouldExcludeLocation:kt}});Oe();await Ue();import"dotenv/config";import*as _e from"fs";import*as K from"path";import{fileURLToPath as ps}from"url";var gs=ps(import.meta.url),hs=K.dirname(K.dirname(gs)),it=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(hs,"market-research"),ys=K.join(it,"scouted-jobs.json"),ws=K.join(it,"discovered-people.json"),bs=K.join(it,"visit-log.json"),Hi=K.join(it,"companies.json"),Ss=K.join(it,"job-decisions.json");function ht(e){try{if(_e.existsSync(e))return JSON.parse(_e.readFileSync(e,"utf-8"))}catch{}return null}function Un(){ot=null,st=null,rt=null,$s=null,xe=null}var ot=null;function Ot(){return ot||(ot=ht(ys)||{},ot)}var st=null;function qn(){return st||(st=ht(Ss)||{},st)}var rt=null;function vs(){return rt||(rt=ht(ws)||{},rt)}var $s=null;var xe=null;function ks(){return xe||(xe=ht(bs)||{visits:[]},Array.isArray(xe.visits)||(xe.visits=[]),xe)}function Bn(){let e=Ot(),t=vs(),n=Object.values(e),o=Object.values(t),s={};for(let u of n)u.company&&(s[u.company]=(s[u.company]||0)+1);let r=Object.entries(s).sort((u,m)=>m[1]-u[1]).slice(0,5).map(([u,m])=>`${u} (${m})`),a={};for(let u of n)for(let m of u.techStack||[])a[m]=(a[m]||0)+1;let l=Object.entries(a).sort((u,m)=>m[1]-u[1]).slice(0,8).map(([u,m])=>`${u} (${m})`),i=ks(),d=new Date().toISOString().slice(0,10),c=i.visits.filter(u=>u.date.startsWith(d)).length,f=new Set(i.visits.map(u=>u.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:r,topTech:l,totalVisited:f,todayVisited:c,lastScoutDate:n.length>0?n.sort((u,m)=>(m.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}await Ue();var Cs=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"]),Es=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Hn=["vancouver","british columbia"],xs=["canada","montreal","quebec","alberta","calgary","ottawa"],_s=["toronto","ontario"],As=["india","pakistan","nigeria","philippines"];function Ts(e,t={}){let n=0,o=(e.techStack||[]).map(c=>c.toLowerCase()),s=0,r=0;for(let c of o)Cs.has(c)&&s++,Es.has(c)&&r++;if(n+=Math.min(s*6,24),n+=Math.min(r*3,6),e.salary){let c=Rs(e.salary);c&&(c>=15e4?n+=20:c>=12e4?n+=15:c>=1e5?n+=10:c>=8e4?n+=5:c>=100&&c<1e3?n+=15:c>=70&&c<1e3&&(n+=10))}let a=(e.location||"").toLowerCase(),l=/remote/i.test(a)||e.workplaceType==="remote";As.some(c=>a.includes(c))?n-=30:l&&/united states|usa|\bus\b/i.test(a)?n+=25:l&&Hn.some(c=>a.includes(c))?n+=22:l?n+=20:Hn.some(c=>a.includes(c))?n+=18:xs.some(c=>a.includes(c))?n+=10:_s.some(c=>a.includes(c))&&(n+=5),e.isEasyApply&&(n+=5);let i=(e.seniority||"").toLowerCase();i.includes("senior")||i.includes("lead")||i.includes("staff")?n+=10:i.includes("mid")?n+=5:(i.includes("entry")||i.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let d=new Set(e.jobTags||[]);return d.has("managerial")?n+=8:d.has("senior-ic")&&(n+=5),d.has("junior")&&(n-=15),d.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function Jn(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=Ot(),s=J(),r=new Set,a=new Set;for(let[f,u]of Object.entries(s))u.connectionStatus==="connected"&&r.add(f);let l={connectedRecruiters:r,conversationRecruiters:a},i=qn(),d=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,u])=>{if(typeof u!="object"||n&&!u.isEasyApply||u.applied)return!1;let m=i[f];return!(m&&d.has(m.status))}).map(([f,u])=>({jobId:f,score:Ts(u,l),job:u})).sort((f,u)=>{if(u.score!==f.score)return u.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(u.job.scoutedAt||u.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Rs(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 Ke();import Ns from"puppeteer";import{addExtra as js}from"puppeteer-extra";import Ps from"puppeteer-extra-plugin-stealth";Oe();await Ke();import ae from"fs";import ge from"path";var Ds="cookies.json";function Vn(){let e=process.env.ILML_SCOPE_DIR;return e?ge.join(e,"plugins-state","linkedin","cookies.json"):Ds}function yt(){let e=Vn();if(!ae.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ae.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function Wn(){return ae.existsSync(Vn())}function Is(){let e=process.env.ILML_SCOPE_DIR;return e?ge.join(e,"plugins-state","linkedin"):"."}function Yn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ms(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Yn(t[1]):"default"}function Gn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ae.existsSync(t)||ae.mkdirSync(t,{recursive:!0}),ge.resolve(t);let n=Yn(e||Ms()),o=ge.join(Is(),"chrome-profile",n);return ae.existsSync(o)||ae.mkdirSync(o,{recursive:!0}),ge.resolve(o)}var zn=".ilml-seeded";function Kn(e){return!ae.existsSync(ge.join(e,zn))}function Qn(e){try{ae.writeFileSync(ge.join(e,zn),new Date().toISOString())}catch{}}function Zn(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ae.rmSync(ge.join(e,n),{force:!0}),t++}catch{}return t}var Os={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function Xn(e,t={}){let n=Gn(),o={...Os,...t,userDataDir:n},s;try{s=await e.launch(o)}catch{Zn(n);try{s=await e.launch(o)}catch(a){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return{browser:s,profileDir:n,needsSeed:Kn(n)}}async function eo(e,t){if(!t||!t.needsSeed)return!1;if(!Wn())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...yt()),Qn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var oo=js(Ns);oo.use(Ps());async function so(){let{browser:e,profileDir:t,needsSeed:n}=await Xn(oo),o=async()=>{console.log(`
246
- Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let s=await e.newPage();return await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await eo(s,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:s}}async function Nt(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 (not logged in, or session expired). Run: ilml linkedin 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 ro(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 i=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(i)||/^\s*Promoted\b/i.test(i))continue;let c=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,u,m;if(i.startsWith("You:"))u="me",m=i.slice(4).trim();else{let g=a.split(" ")[0];if(i.startsWith(a+":")||i.startsWith(g+":")){u="them";let b=i.indexOf(":");m=i.slice(b+1).trim()}else u="them",m=i}let y=s.getBoundingClientRect();o.push({name:a,lastMessagePreview:m,lastMessageTime:c,unread:f,lastMessageBy:u,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=_t(n.lastMessageTime)||n.lastMessageTime;return t}async function jt(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 Ls(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 r=document.querySelector(s);if(r){let a=r.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 r=s.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function Pt(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 to(e,t){let n=await Ls(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=n.toLowerCase();return{match:r.includes(o)||s.some(l=>r.includes(l)),headerName:n}}async function wt(e,t){let n=t.split(" ")[0],o=8e3,s=500,r=0;for(;r<o;){let{match:i,headerName:d}=await to(e,t);if(i)return await $(500),{verified:!0,headerName:d};let c=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),u=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:u,msgCount:m}});if(c.msgCount>0&&c.allSenders.some(u=>u.toLowerCase().includes(n.toLowerCase())))return await $(300),{verified:!0,headerName:n};await $(s),r+=s}let{match:a,headerName:l}=await to(e,t);return a?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function Fs(e){let n=0,o=0;for(let s=0;s<50;s++){let r=await e.evaluate(()=>{let a=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!a){let d=document.querySelector(".msg-overlay-conversation-bubble");d&&(a=d.querySelector(".msg-s-message-list-container")||d.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(!r.found||r.atTop)break;if(await $(800),r.msgCount===n){if(o++,o>=3)break}else o=0;n=r.msgCount}}async function Lt(e,{scrollUp:t=!0}={}){t&&await Fs(e);let n=await e.evaluate(()=>{let o=[],s="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(r=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!r)return o;let a=r.querySelectorAll("li.msg-s-message-list__event");if(a.length===0){let c=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");c&&(a=c.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(c){let f=c.getAttribute("data-event-urn");if(!f)return null;let u=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!u)return null;try{let y=atob(u[1]).match(/^(\d{13})/);if(!y)return null;let g=Number(y[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let i="";function d(c,f,u){let m=l(c),g=c.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=c.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():u?`${u} ${g}`.trim():g;return{sender:f,text:w,time:S}}for(let c of a){let f=c.querySelector("time.msg-s-message-list__time-heading");f&&(i=f.textContent?.trim()||i);let u=c.querySelectorAll(".msg-s-message-group");if(u.length>0)for(let m of u){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=d(w,g,i);S&&o.push(S)}}else{let m=c.querySelectorAll(".msg-s-event-listitem");for(let y of m){let g=y.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let w=d(y,s||"Unknown",i);w&&o.push(w)}}}if(o.length===0){let c=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of c){let u=f.textContent?.trim();u&&o.push({sender:"",text:u,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=_t(o.time)||o.time);return n}function Ft(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(d=>d.length>1),r=[...new Set(e.map(d=>d.sender).filter(d=>d&&d!=="Unknown"))],a=r.some(d=>{let c=d.toLowerCase();return c.includes(o)||s.some(f=>c.includes(f))}),l=z.toLowerCase().split(/\s+/),i=r.every(d=>{let c=d.toLowerCase();return l.some(f=>c.includes(f))});if(a)return!0;if(i){for(let d of e){let f=(d.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let u=f[1].toLowerCase();if(u!=="there"&&u!=="all"&&!(s.some(y=>y===u)||u===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let d=n.map(f=>f.toLowerCase());if(r.some(f=>{let u=f.toLowerCase();return d.some(m=>u.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${r.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${r.join(", ")})`),!1}function qe(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Ut(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=u=>qe(u.sender)+"||"+qe(u.text),o=new Set(t.map(n)),s=new Set(e.map(n)),r=e.filter(u=>Ne.has(u.status)?!1:!o.has(n(u))),a=t.filter(u=>!s.has(n(u))),l=t.filter(u=>s.has(n(u))),i=e.filter(u=>Ne.has(u.status)),d=[...r,...l,...a],c=[];for(let u of d){let m=qe(u.text),y=qe(u.sender),g=!1;for(let b=0;b<c.length;b++){let w=c[b];if(qe(w.sender)!==y)continue;let S=qe(w.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){c[b]=u,g=!0;break}}g||c.push(u)}return[...c,...i]}async function io(e,t){await Nt(e),await $(2500),await e.evaluate(()=>{let l=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let i of l){let d=document.querySelector(i);if(d){d.scrollTop=0;return}}}),await $(500);async function n(){return e.evaluate(l=>{let i=document.querySelectorAll(".msg-conversation-listitem");for(let d of i)if(d.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===l){let u=d.getBoundingClientRect();if(u.height>0)return{x:u.x+u.width/2,y:u.y+u.height/2}}return null},t)}let o=await n(),s=50,r=-1,a=0;for(let l=0;l<s&&!o;l++){let i=await jt(e);if(!i)break;if(i.scrollTop===r){if(a++,a>=2)break}else a=0,r=i.scrollTop;await $(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await $(3e3),wt(e,t)):{verified:!1,headerName:null}}async function qt(e,t){let n=await e.evaluate(a=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let i of l)if(i.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===a){let f=i.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 wt(e,t);if(a.verified)return a}let o=vn(t),s=o!==t?[t,o]:[t];for(let a of s)if(await no(e,a,t)){let i=await wt(e,t);if(i.verified)return i}let r=$n(o);if(r!==o&&r.length>0&&await no(e,r,t,{requireUnique:!0})){let l=await wt(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function no(e,t,n,o={}){let{requireUnique:s=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.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 r.type(t,{delay:30}),await $(500),await e.keyboard.press("Enter"),await $(3500);let a=await e.evaluate((l,i)=>{let d=l.split(" ")[0].toLowerCase(),c=l.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),u=[],m=[];for(let g of f){let w=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(d)){let h=g.getBoundingClientRect();if(h.height>0){let p=w.includes(",")||/\d+ other/.test(w),v=S===c?3:S.includes(c)?2:1,C={text:w,isGroup:p,score:v,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):u.push(C)}}}u.sort((g,b)=>b.score-g.score);let y=[...u,...m];return i&&y.length!==1?null:u[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 he(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 Ke();await Ue();function Ht(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(i=>!Ne.has(i.status)),r=Ys(t,e.profileUrl,n),a=Jt(s,t);if(e.lastMessageBy=a,e.conversationStatus=a==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let i=Us(s,t,r);i&&(e.category=i,e.categorySource=e.categorySource||"message_content")}if(e.situation=qs(s,a,t),s.length>0){let i=s[s.length-1];e.lastMessageTime=i.time}if(s.length>0&&!e.initiatedBy){let i=s[0];i.sender===z?e.initiatedBy="us":i.sender!=="Unknown"&&i.sender!==""&&(e.initiatedBy="them")}e.engagement=uo(s,t),e.personContext=Vs(r),e.summary=Bs(e,t,r),e.autoTags=Hs(e,t,r);let l=Js(e);return e.actionNeeded=l.action,e.actionDetail=l.detail,e.suggestedPriority=Ws(e),e}var lo={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 Us(e,t,n){if(!e||e.length===0)return n?.title?Bt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,r]of Object.entries(lo))if(r.theirMessages){for(let a of r.theirMessages)if(a.test(o))return s}if(n?.title){let s=Bt(n.title);if(s)return s}return null}function Bt(e){if(!e)return null;for(let[t,n]of Object.entries(lo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}var ao=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i;function qs(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 ao.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(r=>r.sender!==z&&r.sender!=="Unknown");return ao.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Jt(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,r)=>r.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let r=s.sender;if(r===z)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}function Bs(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],r=e.category,a=n?.title,l=n?.company,i=n?.location;r==="recruiter"&&l?s.push(`Recruiter from ${l}`):r==="hiring_manager"&&l?s.push(`Hiring manager at ${l}`):r==="founder"&&l?s.push(`Founder of ${l}`):r&&a?s.push(`${Vt(r)}: ${Be(a,40)}`):a?s.push(Be(a,50)):s.push(t.split(" ")[0]);let d=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),c=Gs(d),f=zs(d),u=Ks(d),m=[];return c&&m.push(c),u&&u!==i&&m.push(u),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 Hs(e,t,n){let o=[],s=(e.messages||[]).filter(d=>!Ne.has(d.status)),r=s.map(d=>d.text).join(" "),a=s.filter(d=>d.sender!==z&&d.sender!=="Unknown").map(d=>d.text).join(" "),l=co(a,n?.location);o.push(...l),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(r)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(r)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(r)&&o.push("remote"),/\b(hybrid)\b/i.test(r)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(r)&&o.push("onsite"),/\b(java)\b/i.test(r)&&!/javascript/i.test(r)&&o.push("java"),/\b(python)\b/i.test(r)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(r)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(r)&&o.push("backend"),/\b(full.?stack)\b/i.test(r)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(r)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(r)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(r)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(r)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(r)&&o.push("has-salary");let i=e.engagement||uo(s,t);return i.messageCount>=6&&o.push("active-thread"),i.theirCount===0&&i.ourCount>0&&o.push("no-response"),i.ourCount===0&&i.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(d=>ze.has(d.status))&&o.push("has-draft"),[...new Set(o)]}function co(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"]],r=(e+" "+(t||"")).toLowerCase();for(let a of o)r.includes(a)&&n.push(a.replace(/\s+/g,"-"));for(let[a,l]of s)r.includes(a)&&n.push(l);return n}function Js(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&at(e.lastMessagePreview)===at(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(r=>ze.has(r.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:`${Vt(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 uo(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,r=!1,a=!1,l=e.map(i=>i.text).join(" ");for(let i of e)i.sender===z?n++:i.sender==="Unknown"||i.sender===""?s++:o++;return r=/\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:r,hasSalary:a}}function Vs(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Ws(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 Ys(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=Le(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function at(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Vt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Be(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Gs(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 zs(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 Ks(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 fo(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Bt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Qs(e),e.personSummary=Zs(e),e.personAutoTags=Xs(e);let n=er(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=tr(e)),e}function Qs(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 Zs(e){let t=[],n=e.category,o=e.title,s=e.company,r=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(`${Be(o,40)} at ${Be(s,30)}`):o?t.push(Be(o,50)):e.name&&t.push(e.name.split(" ")[0]),r&&t.push(r),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: ${Be(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 Xs(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=co("",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 er(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:`${Vt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function tr(e){let t=e.category;if(!t)return null;let n=nr(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 nr(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 ye from"path";import{fileURLToPath as lr}from"url";import"dotenv/config";import{createGraphClient as or,resolveToken as sr}from"@ilivemylife/graph-sdk";import{config as rr}from"dotenv";rr();var mo=sr()||process.env.TOKEN;mo||(console.error(`
242
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let g=eo(h.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,l&&await l(h,d,{success:!1,reason:g,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(r){let w=await An(e,h.profileUrl);w?(Te(h.profileUrl,{...w,source:u}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w,resolvedUrl:w.resolvedUrl}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=Yt();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await En(e,h.profileUrl,{message:o,useCustomMessage:s,excludeLocations:c,source:u,skipQuotaGate:!0}),b.success)d.connectionsSent++;else switch(b.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(b?.fatal){console.log(`
243
+ \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(b?.reason==="error"){if(f++,f>=3){console.log(`
244
+ \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(b&&b.reason&&(to(h.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&At(h.profileUrl,b.resolvedUrl),Xn(h.profileUrl,{source:u||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:b.reason})),l&&await l(h,d,b),m<t.length-1){let w=a+Math.random()*2e3;await $(w)}}if(console.log(`
245
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!r){let m=at();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}var Vi,ps=fe(async()=>{Le();await Je();Vi={viewProfile:An,detectConnectionStatus:Ce,findConnectButton:vt,clickConnectButton:xn,sendConnectionRequest:En,runFunnel:ds,shouldExcludeLocation:Ft}});Le();await Je();yt();await Je();yt();var cr=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"]),ur=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),go=["vancouver","british columbia"],fr=["canada","montreal","quebec","alberta","calgary","ottawa"],dr=["toronto","ontario"],mr=["india","pakistan","nigeria","philippines"];function pr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)cr.has(u)&&s++,ur.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=gr(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 r=(e.location||"").toLowerCase(),a=/remote/i.test(r)||e.workplaceType==="remote";mr.some(u=>r.includes(u))?n-=30:a&&/united states|usa|\bus\b/i.test(r)?n+=25:a&&go.some(u=>r.includes(u))?n+=22:a?n+=20:go.some(u=>r.includes(u))?n+=18:fr.some(u=>r.includes(u))?n+=10:dr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let l=(e.seniority||"").toLowerCase();l.includes("senior")||l.includes("lead")||l.includes("staff")?n+=10:l.includes("mid")?n+=5:(l.includes("entry")||l.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 ho(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=pt(),s=J(),i=new Set,r=new Set;for(let[d,f]of Object.entries(s))f.connectionStatus==="connected"&&i.add(d);let a={connectedRecruiters:i,conversationRecruiters:r},l=gt(),c=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([d,f])=>{if(typeof f!="object"||n&&!f.isEasyApply||f.applied)return!1;let m=l[d];return!(m&&c.has(m.status))}).map(([d,f])=>({jobId:d,score:pr(f,a),job:f})).sort((d,f)=>{if(f.score!==d.score)return f.score-d.score;let m=d.job.scoutedAt||d.job.postedTime||"";return(f.job.scoutedAt||f.job.postedTime||"").localeCompare(m)}).slice(0,e)}function gr(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 nt();import Sr from"puppeteer";import{addExtra as vr}from"puppeteer-extra";import kr from"puppeteer-extra-plugin-stealth";Le();await nt();import ce from"fs";import Se from"path";var hr="cookies.json";function yo(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin","cookies.json"):hr}function Rt(){let e=yo();if(!ce.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ce.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function wo(){return ce.existsSync(yo())}function yr(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin"):"."}function bo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function wr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?bo(t[1]):"default"}function So(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),Se.resolve(t);let n=bo(e||wr()),o=Se.join(yr(),"chrome-profile",n);return ce.existsSync(o)||ce.mkdirSync(o,{recursive:!0}),Se.resolve(o)}var vo=".ilml-seeded";function ko(e){return!ce.existsSync(Se.join(e,vo))}function $o(e){try{ce.writeFileSync(Se.join(e,vo),new Date().toISOString())}catch{}}function Co(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ce.rmSync(Se.join(e,n),{force:!0}),t++}catch{}return t}var br={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function Ao(e,t={}){let n=So(),o={...br,...t,userDataDir:n},s;try{s=await e.launch(o)}catch{Co(n);try{s=await e.launch(o)}catch(r){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${r.message})`)}}return{browser:s,profileDir:n,needsSeed:ko(n)}}async function xo(e,t){if(!t||!t.needsSeed)return!1;if(!wo())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Rt()),$o(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var To=vr(Sr);To.use(kr());async function Ro(){let{browser:e,profileDir:t,needsSeed:n}=await Ao(To),o=async()=>{console.log(`
246
+ Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let s=await e.newPage();return await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await xo(s,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:s}}async function nn(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 (not logged in, or session expired). Run: ilml linkedin 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 Do(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let l=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(l)||/^\s*Promoted\b/i.test(l))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",d=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,f,m;if(l.startsWith("You:"))f="me",m=l.slice(4).trim();else{let g=r.split(" ")[0];if(l.startsWith(r+":")||l.startsWith(g+":")){f="them";let b=l.indexOf(":");m=l.slice(b+1).trim()}else f="them",m=l}let h=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:d,lastMessageBy:f,x:h.x+h.width/2,y:h.y+h.height/2})}return o});for(let n of t)n.lastMessageTime=Ht(n.lastMessageTime)||n.lastMessageTime;return t}async function on(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 $r(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 r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}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 sn(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 Eo(e,t){let n=await $r(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(a=>a.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(a=>i.includes(a)),headerName:n}}async function Dt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:l,headerName:c}=await Eo(e,t);if(l)return await $(500),{verified:!0,headerName:c};let u=await e.evaluate(()=>{let d=document.querySelectorAll(".msg-s-message-group__name"),f=Array.from(d).map(h=>h.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:f,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(f=>f.toLowerCase().includes(n.toLowerCase())))return await $(300),{verified:!0,headerName:n};await $(s),i+=s}let{match:r,headerName:a}=await Eo(e,t);return r?{verified:!0,headerName:a}:{verified:!1,headerName:a}}async function Cr(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(r=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let a=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:a}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:a})});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 rn(e,{scrollUp:t=!0}={}){t&&await Cr(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 r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function a(u){let d=u.getAttribute("data-event-urn");if(!d)return null;let f=d.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!f)return null;try{let h=atob(f[1]).match(/^(\d{13})/);if(!h)return null;let g=Number(h[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let l="";function c(u,d,f){let m=a(u),g=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():f?`${f} ${g}`.trim():g;return{sender:d,text:w,time:S}}for(let u of r){let d=u.querySelector("time.msg-s-message-list__time-heading");d&&(l=d.textContent?.trim()||l);let f=u.querySelectorAll(".msg-s-message-group");if(f.length>0)for(let m of f){let h=m.querySelector(".msg-s-message-group__name");h&&(s=h.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=c(w,g,l);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let h of m){let g=h.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let w=c(h,s||"Unknown",l);w&&o.push(w)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let d of u){let f=d.textContent?.trim();f&&o.push({sender:"",text:f,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Ht(o.time)||o.time);return n}function ln(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"))],r=i.some(c=>{let u=c.toLowerCase();return u.includes(o)||s.some(d=>u.includes(d))}),a=z.toLowerCase().split(/\s+/),l=i.every(c=>{let u=c.toLowerCase();return a.some(d=>u.includes(d))});if(r)return!0;if(l){for(let c of e){let d=(c.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(d){let f=d[1].toLowerCase();if(f!=="there"&&f!=="all"&&!(s.some(h=>h===f)||f===o))return console.log(` STALE DATA: message says "Hi ${d[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let c=n.map(d=>d.toLowerCase());if(i.some(d=>{let f=d.toLowerCase();return c.some(m=>f.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 Ye(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function an(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=f=>Ye(f.sender)+"||"+Ye(f.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(f=>Fe.has(f.status)?!1:!o.has(n(f))),r=t.filter(f=>!s.has(n(f))),a=t.filter(f=>s.has(n(f))),l=e.filter(f=>Fe.has(f.status)),c=[...i,...a,...r],u=[];for(let f of c){let m=Ye(f.text),h=Ye(f.sender),g=!1;for(let b=0;b<u.length;b++){let w=u[b];if(Ye(w.sender)!==h)continue;let S=Ye(w.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=f,g=!0;break}}g||u.push(f)}return[...u,...l]}async function Io(e,t){await nn(e),await $(2500),await e.evaluate(()=>{let a=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let l of a){let c=document.querySelector(l);if(c){c.scrollTop=0;return}}}),await $(500);async function n(){return e.evaluate(a=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let c of l)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===a){let f=c.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let a=0;a<s&&!o;a++){let l=await on(e);if(!l)break;if(l.scrollTop===i){if(r++,r>=2)break}else r=0,i=l.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 cn(e,t){let n=await e.evaluate(r=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let d=l.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await $(3e3);let r=await Dt(e,t);if(r.verified)return r}let o=Bn(t),s=o!==t?[t,o]:[t];for(let r of s)if(await _o(e,r,t)){let l=await Dt(e,t);if(l.verified)return l}let i=Hn(o);if(i!==o&&i.length>0&&await _o(e,i,t,{requireUnique:!0})){let a=await Dt(e,t);if(a.verified)return a}return{verified:!1,headerName:null}}async function _o(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 r=await e.evaluate((a,l)=>{let c=a.split(" ")[0].toLowerCase(),u=a.toLowerCase(),d=document.querySelectorAll(".msg-conversation-listitem"),f=[],m=[];for(let g of d){let w=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(c)){let y=g.getBoundingClientRect();if(y.height>0){let p=w.includes(",")||/\d+ other/.test(w),v=S===u?3:S.includes(u)?2:1,C={text:w,isGroup:p,score:v,x:y.x+y.width/2,y:y.y+y.height/2};p?m.push(C):f.push(C)}}}f.sort((g,b)=>b.score-g.score);let h=[...f,...m];return l&&h.length!==1?null:f[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ve(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 mn();import"dotenv/config";import*as ee from"fs";import*as ke from"path";import{fileURLToPath as qr}from"url";import"dotenv/config";import{createGraphClient as jr,resolveToken as Pr}from"@ilivemylife/graph-sdk";import{config as Lr}from"dotenv";Lr();var Ho=Pr()||process.env.TOKEN;Ho||(console.error(`
247
247
  [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.
248
248
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
249
249
  `),console.error(` Or add ILML_TOKEN=... to .env
250
- `),process.exit(1));var po=or({token:mo});function ir(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function ar({scriptName:e,mode:t,status:n,error:o,duration:s}){let r=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",a=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${ir(s)}`:"",i=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",d=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${d} \u2014 ${i} \u2014 ${a}${l}`}async function go({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:r}){let a=process.env.NODE_RUN_REPORTS;if(!a||!Array.isArray(o)||o.length===0)return;let i=`**${ar({scriptName:e,mode:t,status:n,error:s,duration:r})}**
250
+ `),process.exit(1));var Jo=jr({token:Ho});function Fr(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Ur({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),a=s?` ${Fr(s)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${l} \u2014 ${r}${a}`}async function Vo({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(o)||o.length===0)return;let l=`**${Ur({scriptName:e,mode:t,status:n,error:s,duration:i})}**
251
251
 
252
252
  ${o.join(`
253
- `)}`;try{await po.addMessage(a,i)}catch(d){console.error(`[runReport] Failed to post end-of-session message: ${d.message}`)}}var cr=lr(import.meta.url),ur=ye.dirname(ye.dirname(cr)),Wt=process.env.DATA_DIR?ye.resolve(process.env.DATA_DIR,"collected-profiles"):ye.join(ur,"collected-profiles"),Yt=ye.join(Wt,"run-log.json");function dr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";X.writeFileSync(o,n);for(let s=0;s<3;s++)try{X.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw r}}function bt(){try{if(!X.existsSync(Yt))return{runs:[]};let e=JSON.parse(X.readFileSync(Yt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ho(e){X.existsSync(Wt)||X.mkdirSync(Wt,{recursive:!0});try{dr(Yt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function St(e,t="default"){let n=bt();for(let a of n.runs)a.status==="running"&&(a.status="interrupted",a.result="interrupted",a.timestamp&&(a.duration=Date.now()-new Date(a.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(a=>new Date(a.timestamp).getTime()>r),ho(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function He(e,t,n=null,o=null){if(!e)return;let s=null;try{let a=bt(),l=a.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration;else{let i=a.runs.find(d=>d.script===e.script&&d.status==="running"&&d.timestamp===new Date(e.startTime).toISOString());i&&(i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=o,s=i.duration)}ho(a)}catch(a){console.error(`[runLog] Failed to end run: ${a.message}`)}let r=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let a=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";go({scriptName:e.script,mode:e.mode,status:a,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}function fr(){let e=new Date().toISOString().slice(0,10),t=bt(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function mr(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function yo(){let e=["sync-all","messages","funnel","sync","apply"],t=bt(),n=fr(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let r of e){let a=t.runs.filter(g=>g.script===r),l=[...a].reverse().find(g=>g.status==="success"),i=a[a.length-1],d=l||i,c=d?mr(d.timestamp):"never",u=(d?Math.floor((Date.now()-new Date(d.timestamp).getTime())/864e5):1/0)>1?" \u26A0":d?.status==="error"?" \u2717":" \u2713",m="";if(d?.stats){let g=d.stats,b=Object.entries(g).filter(([,w])=>typeof w=="number"&&w>0).slice(0,3).map(([w,S])=>`${S} ${w}`);b.length&&(m=` (${b.join(", ")})`)}let y=d?.duration?` ${Math.round(d.duration/1e3)}s`:"";o.push(` ${r.padEnd(14)} ${c.padEnd(16)}${y}${m}${u}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[r,a]of s){let l=[];a.success&&l.push(`${a.success} success`),a.error&&l.push(`${a.error} error`),a.interrupted&&l.push(`${a.interrupted} interrupted`),a.running&&l.push(`${a.running} running`),o.push(` Today: ${r} \xD7${a.total} (${l.join(", ")})`)}}return o.push("\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"),o.join(`
254
- `)}import"dotenv/config";import*as x from"fs";import*as tn from"os";import*as N from"path";import{fileURLToPath as Pr}from"url";var Kt={};Me(Kt,{NAME:()=>gr,VERSION:()=>pr,up:()=>wr});import*as ee from"fs";import*as vt from"path";var pr=1,gr="normalize-jobs-and-questions",hr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],yr=50;function Gt(e){return ee.existsSync(e)?JSON.parse(ee.readFileSync(e,"utf-8")):null}function zt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ee.writeFileSync(o,n)}catch(s){try{ee.unlinkSync(o)}catch{}throw s}try{ee.renameSync(o,e)}catch(s){try{ee.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function wr(e,t){let n=vt.join(e,"jobs.json"),o=vt.join(t,"scouted-jobs.json"),s=vt.join(e,"application-questions.json"),r=Gt(n)||{},a=Gt(o)||{},l=0,i=[];for(let c of Object.keys(r)){if(!a[c])continue;let f=a[c],u=r[c];for(let m of hr)f[m]!=null&&u[m]==null&&(u[m]=f[m]);i.push(c),l++}l>0?(zt(n,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let d=Gt(s);if(d&&Array.isArray(d.applications)){let c={},f=0;for(let u of d.applications){let m=u.jobId||"unknown";c[m]||(c[m]={applications:[]});let y=(u.questions||[]).map(g=>{let b={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=yr?b.options=g.options:(b.optionsOmitted=!0,f++)),g.page&&(b.page=g.page),g.wasPreFilled&&(b.wasPreFilled=!0),g.wasRetry&&(b.wasRetry=!0),b});c[m].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||y.length,questions:y})}zt(s,c),console.log(` Phase 2: Rekeyed ${d.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else d&&!d.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let c of i)delete a[c];zt(o,a),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(a).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Qt={};Me(Qt,{NAME:()=>Sr,VERSION:()=>br,up:()=>kr});import*as te from"fs";import*as wo from"path";var br=2,Sr="reset-unread-flags";function vr(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function $r(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{te.writeFileSync(o,n)}catch(s){try{te.unlinkSync(o)}catch{}throw s}try{te.renameSync(o,e)}catch(s){try{te.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function kr(e){let t=wo.join(e,"conversations.json"),n=vr(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}$r(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Zt={};Me(Zt,{NAME:()=>Er,VERSION:()=>Cr,up:()=>Rr});import*as ne from"fs";import*as bo from"path";var Cr=3,Er="recompute-last-message-by",xr=new Set(["draft","confirmed","rejected","needs_review"]);function _r(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function Ar(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Tr(e,t){if(!e||e.length===0)return"them";let n=e.filter(r=>!xr.has(r.status));if(n.length===0)return"them";let o=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,a)=>a.t-r.t).map(r=>r.m),s=o.length>0?o:[...n].reverse();for(let r of s){let a=r.sender;if(a===t)return"me";if(a!=="Unknown"&&a!=="")return"them"}return"them"}async function Rr(e){let t=bo.join(e,"conversations.json"),n=_r(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,a=0;for(let l of Object.keys(n)){let i=n[l];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,r++);let d=Array.isArray(i.messages)?i.messages:[],c=Tr(d,o),f=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&a++,i.lastMessageBy=c,i.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}Ar(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${a} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Xt={};Me(Xt,{NAME:()=>Ir,VERSION:()=>Dr,up:()=>jr});import*as oe from"fs";import*as So from"path";var Dr=4,Ir="split-connection-timestamps",Mr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Or(e){if(!oe.existsSync(e))return null;let t=oe.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Nr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function jr(e){let t=So.join(e,"people.json"),n=Or(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let r of Object.keys(n)){let a=n[r];!a||typeof a!="object"||(s++,Mr.has(a.connectionStatus)&&a.connectionDate&&!a.requestedConnectionAt&&(a.requestedConnectionAt=a.connectionDate,a.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Nr(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Ue();var Lr=Pr(import.meta.url),Fr=N.dirname(Lr),Ur=N.dirname(N.dirname(Fr));function qr(e){return e&&(e==="~"?tn.homedir():e.startsWith("~/")||e.startsWith("~\\")?N.join(tn.homedir(),e.slice(2)):e)}var le=process.env.DATA_DIR?N.resolve(qr(process.env.DATA_DIR)):Ur,Te=N.join(le,"collected-profiles"),Re=N.join(le,"market-research"),Y=N.join(le,".schema-version"),vo=[N.join(Te,".schema-version"),N.join(Re,".schema-version")],we=4,de=[{version:1,module:Kt},{version:2,module:Qt},{version:3,module:Zt},{version:4,module:Xt}];(function(){de.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of de){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=de.length?de[de.length-1].version:0;if(n!==we)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${we}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<de.length;o++){let s=o+1;if(de[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${de[o].version}`)}})();function Eo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
+ `)}`;try{await Jo.addMessage(r,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Br=qr(import.meta.url),Hr=ke.dirname(ke.dirname(Br)),pn=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(Hr,"collected-profiles"),gn=ke.join(pn,"run-log.json");function Jr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let s=0;s<3;s++)try{ee.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function Mt(){try{if(!ee.existsSync(gn))return{runs:[]};let e=JSON.parse(ee.readFileSync(gn,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Wo(e){ee.existsSync(pn)||ee.mkdirSync(pn,{recursive:!0});try{Jr(gn,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function jt(e,t="default"){let n=Mt();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),Wo(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Ke(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=Mt(),a=r.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration;else{let l=r.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration)}Wo(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Vo({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}function Vr(){let e=new Date().toISOString().slice(0,10),t=Mt(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function Wr(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function Yo(){let e=["sync-all","messages","funnel","sync","apply"],t=Mt(),n=Vr(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let r=t.runs.filter(g=>g.script===i),a=[...r].reverse().find(g=>g.status==="success"),l=r[r.length-1],c=a||l,u=c?Wr(c.timestamp):"never",f=(c?Math.floor((Date.now()-new Date(c.timestamp).getTime())/864e5):1/0)>1?" \u26A0":c?.status==="error"?" \u2717":" \u2713",m="";if(c?.stats){let g=c.stats,b=Object.entries(g).filter(([,w])=>typeof w=="number"&&w>0).slice(0,3).map(([w,S])=>`${S} ${w}`);b.length&&(m=` (${b.join(", ")})`)}let h=c?.duration?` ${Math.round(c.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${h}${m}${f}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,r]of s){let a=[];r.success&&a.push(`${r.success} success`),r.error&&a.push(`${r.error} error`),r.interrupted&&a.push(`${r.interrupted} interrupted`),r.running&&a.push(`${r.running} running`),o.push(` Today: ${i} \xD7${r.total} (${a.join(", ")})`)}}return o.push("\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"),o.join(`
254
+ `)}import"dotenv/config";import*as x from"fs";import*as $n from"os";import*as j from"path";import{fileURLToPath as hi}from"url";var wn={};ae(wn,{NAME:()=>Gr,VERSION:()=>Yr,up:()=>Qr});import*as te from"fs";import*as Pt from"path";var Yr=1,Gr="normalize-jobs-and-questions",zr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Kr=50;function hn(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function yn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{te.writeFileSync(o,n)}catch(s){try{te.unlinkSync(o)}catch{}throw s}try{te.renameSync(o,e)}catch(s){try{te.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Qr(e,t){let n=Pt.join(e,"jobs.json"),o=Pt.join(t,"scouted-jobs.json"),s=Pt.join(e,"application-questions.json"),i=hn(n)||{},r=hn(o)||{},a=0,l=[];for(let u of Object.keys(i)){if(!r[u])continue;let d=r[u],f=i[u];for(let m of zr)d[m]!=null&&f[m]==null&&(f[m]=d[m]);l.push(u),a++}a>0?(yn(n,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=hn(s);if(c&&Array.isArray(c.applications)){let u={},d=0;for(let f of c.applications){let m=f.jobId||"unknown";u[m]||(u[m]={applications:[]});let h=(f.questions||[]).map(g=>{let b={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=Kr?b.options=g.options:(b.optionsOmitted=!0,d++)),g.page&&(b.page=g.page),g.wasPreFilled&&(b.wasPreFilled=!0),g.wasRetry&&(b.wasRetry=!0),b});u[m].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}yn(s,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete r[u];yn(o,r),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var bn={};ae(bn,{NAME:()=>Xr,VERSION:()=>Zr,up:()=>ni});import*as ne from"fs";import*as Go from"path";var Zr=2,Xr="reset-unread-flags";function ei(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function ti(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function ni(e){let t=Go.join(e,"conversations.json"),n=ei(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}ti(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Sn={};ae(Sn,{NAME:()=>si,VERSION:()=>oi,up:()=>ci});import*as oe from"fs";import*as zo from"path";var oi=3,si="recompute-last-message-by",ri=new Set(["draft","confirmed","rejected","needs_review"]);function ii(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function li(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function ai(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!ri.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let r=i.sender;if(r===t)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function ci(e){let t=zo.join(e,"conversations.json"),n=ii(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,r=0;for(let a of Object.keys(n)){let l=n[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=ai(c,o),d=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&r++,l.lastMessageBy=u,l.conversationStatus=d,s++}if(s===0){console.log(" No conversations to recompute.");return}li(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var vn={};ae(vn,{NAME:()=>fi,VERSION:()=>ui,up:()=>gi});import*as se from"fs";import*as Ko from"path";var ui=4,fi="split-connection-timestamps",di=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function mi(e){if(!se.existsSync(e))return null;let t=se.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function pi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{se.writeFileSync(o,n)}catch(s){try{se.unlinkSync(o)}catch{}throw s}try{se.renameSync(o,e)}catch(s){try{se.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function gi(e){let t=Ko.join(e,"people.json"),n=mi(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,di.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}pi(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Je();yt();var yi=hi(import.meta.url),wi=j.dirname(yi),bi=j.dirname(j.dirname(wi));function Si(e){return e&&(e==="~"?$n.homedir():e.startsWith("~/")||e.startsWith("~\\")?j.join($n.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?j.resolve(Si(process.env.DATA_DIR)):bi,Oe=j.join(ue,"collected-profiles"),Me=j.join(ue,"market-research"),G=j.join(ue,".schema-version"),Qo=[j.join(Oe,".schema-version"),j.join(Me,".schema-version")],$e=4,pe=[{version:1,module:wn},{version:2,module:bn},{version:3,module:Sn},{version:4,module:vn}];(function(){pe.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of pe){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=pe.length?pe[pe.length-1].version:0;if(n!==$e)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${$e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<pe.length;o++){let s=o+1;if(pe[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${pe[o].version}`)}})();function ts(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
255
255
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
256
- `),process.exit(1));try{x.mkdirSync(le,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
- [FATAL] Cannot create DATA_DIR (${le}): ${t.message}`),console.error(` Fix the path or permissions and try again.
258
- `),process.exit(1))}let e;try{e=x.statSync(le)}catch(t){console.error(`
259
- [FATAL] DATA_DIR (${le}) is not accessible: ${t.message}
256
+ `),process.exit(1));try{x.mkdirSync(ue,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
257
+ [FATAL] Cannot create DATA_DIR (${ue}): ${t.message}`),console.error(` Fix the path or permissions and try again.
258
+ `),process.exit(1))}let e;try{e=x.statSync(ue)}catch(t){console.error(`
259
+ [FATAL] DATA_DIR (${ue}) is not accessible: ${t.message}
260
260
  `),process.exit(1)}e.isDirectory()||(console.error(`
261
- [FATAL] DATA_DIR (${le}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
262
- `),process.exit(1));for(let t of[Te,Re]){let n;try{n=x.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
261
+ [FATAL] DATA_DIR (${ue}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
262
+ `),process.exit(1));for(let t of[Oe,Me]){let n;try{n=x.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
263
263
  [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
264
- `),process.exit(1))}}var Ae=N.join(le,".migration-lock");function Br(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return x.writeFileSync(Ae,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(x.readFileSync(Ae,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(a){a.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let a=Date.parse(t.startedAt);Number.isNaN(a)||(r=Date.now()-a)}o&&r<s&&(console.error(`
265
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ae}
264
+ `),process.exit(1))}}var Ne=j.join(ue,".migration-lock");function vi(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return x.writeFileSync(Ne,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(x.readFileSync(Ne,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
265
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ne}
266
266
  `),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
267
- `),process.exit(1)),o&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ae+".tmp";try{return x.writeFileSync(n,e),x.renameSync(n,Ae),!0}catch(o){try{x.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function nn(){try{if(JSON.parse(x.readFileSync(Ae,"utf-8")).pid!==process.pid)return;x.unlinkSync(Ae)}catch{}}var $o=!1;function Hr(){if($o)return;$o=!0;let e=()=>{try{nn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Jr(){if(x.existsSync(Y))return;let e=[],t=[];for(let r of vo)if(x.existsSync(r))try{e.push({file:r,schema:$t(r)})}catch(a){t.push({file:r,err:a.message})}if(t.length>0){console.error(`
268
- [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
267
+ `),process.exit(1)),o&&i>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ne+".tmp";try{return x.writeFileSync(n,e),x.renameSync(n,Ne),!0}catch(o){try{x.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Cn(){try{if(JSON.parse(x.readFileSync(Ne,"utf-8")).pid!==process.pid)return;x.unlinkSync(Ne)}catch{}}var Zo=!1;function ki(){if(Zo)return;Zo=!0;let e=()=>{try{Cn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function $i(){if(x.existsSync(G))return;let e=[],t=[];for(let i of Qo)if(x.existsSync(i))try{e.push({file:i,schema:Lt(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
268
+ [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
269
269
  Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
270
- `),process.exit(1)}if(e.length===0)return;let n=e.map(r=>r.schema.version);if(new Set(n).size>1){console.error(`
271
- [FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
272
- `),process.exit(1)}let o=e[0].schema,s=Y+".tmp";try{x.writeFileSync(s,JSON.stringify(o,null,2)),x.renameSync(s,Y)}catch(r){try{x.unlinkSync(s)}catch{}throw r}for(let r of vo)if(x.existsSync(r))try{x.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Y}`)}function Vr(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function $t(e){let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ko(){if(Jr(),!x.existsSync(Y))return{version:0,migrations:[]};let e;try{e=$t(Y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
273
- [FATAL] ${Y} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
274
- `),process.exit(1)}let t=Vr(e);return t===null&&(console.error(`
275
- [FATAL] ${Y} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
276
- `),process.exit(1)),t}function xo(e){try{x.chmodSync(e,384)}catch{}}function Wr(e){if(Eo(),x.existsSync(Y))try{if(x.lstatSync(Y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=Y+".tmp";try{x.writeFileSync(t,JSON.stringify(e,null,2)),xo(t),x.renameSync(t,Y)}catch(n){try{x.unlinkSync(t)}catch{}throw n}}function Co(e,t){if(!x.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=x.readdirSync(e).filter(l=>{let i=l.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return x.statSync(N.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,a=[];for(let l of o){let i=N.join(e,l),d=N.join(e,l+n);if(x.existsSync(d)){r++;continue}try{Ao(i,d),s++}catch(c){a.push({file:l,err:c.message})}}if(a.length>0){let l=new Error(`Failed to back up ${a.length} file(s) in ${N.basename(e)}/: `+a.map(i=>`${i.file} (${i.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${N.basename(e)}/ (${n})${l}`)}}var en=!1;async function _o(){if(en)return;Eo(),Qr();let t=ko().version;if(t===we){en=!0;return}Hr(),Br(),process.on("exit",nn),t>we&&(console.error(`
277
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${we}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
278
- `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${we}.
270
+ `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
271
+ [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
272
+ `),process.exit(1)}let o=e[0].schema,s=G+".tmp";try{x.writeFileSync(s,JSON.stringify(o,null,2)),x.renameSync(s,G)}catch(i){try{x.unlinkSync(s)}catch{}throw i}for(let i of Qo)if(x.existsSync(i))try{x.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function Ci(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function Lt(e){let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Xo(){if($i(),!x.existsSync(G))return{version:0,migrations:[]};let e;try{e=Lt(G)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
273
+ [FATAL] ${G} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
274
+ `),process.exit(1)}let t=Ci(e);return t===null&&(console.error(`
275
+ [FATAL] ${G} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
276
+ `),process.exit(1)),t}function ns(e){try{x.chmodSync(e,384)}catch{}}function Ai(e){if(ts(),x.existsSync(G))try{if(x.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=G+".tmp";try{x.writeFileSync(t,JSON.stringify(e,null,2)),ns(t),x.renameSync(t,G)}catch(n){try{x.unlinkSync(t)}catch{}throw n}}function es(e,t){if(!x.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=x.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return x.statSync(j.join(e,a)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let a of o){let l=j.join(e,a),c=j.join(e,a+n);if(x.existsSync(c)){i++;continue}try{ss(l,c),s++}catch(u){r.push({file:a,err:u.message})}}if(r.length>0){let a=new Error(`Failed to back up ${r.length} file(s) in ${j.basename(e)}/: `+r.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(s>0||i>0){let a=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${j.basename(e)}/ (${n})${a}`)}}var kn=!1;async function os(){if(kn)return;ts(),Ri();let t=Xo().version;if(t===$e){kn=!0;return}ki(),vi(),process.on("exit",Cn),t>$e&&(console.error(`
277
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${$e}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
278
+ `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${$e}.
279
279
  `),process.exit(1)),console.log(`
280
- \u{1F4E6} Schema migration: v${t} \u2192 v${we}`);let n=Zr();if(!n.ok){console.error(`
280
+ \u{1F4E6} Schema migration: v${t} \u2192 v${$e}`);let n=Di();if(!n.ok){console.error(`
281
281
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
282
282
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
283
- `),process.exit(1)}let o=de.filter(s=>s.version>t);for(let s of o){console.log(`
284
- Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,a=`.pre-${r}.backup`;try{Co(Te,s.version),Co(Re,s.version)}catch(i){console.error(`
285
- [FATAL] Pre-migration backup failed for ${r}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
286
- `),process.exit(1)}let l=s.module;try{await l.up(Te,Re)}catch(i){console.error(`
287
- [FATAL] Migration ${r} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let d=Xr(a);d.ok?(console.error(` \u2713 Auto-rollback restored ${d.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
288
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${d.error}`),console.error(` Manual recovery: copy *${a} files back over the originals.
289
- `))}catch(d){console.error(` [!] Auto-rollback CRASHED while restoring: ${d.message}`),console.error(` Manual recovery: copy *${a} files back over the originals.
290
- `)}process.exit(1)}try{let i=new Date().toISOString(),d={version:s.version,name:l.NAME||r,appliedAt:i},c=ko();c.version=s.version,c.migratedAt=i,c.migrations=c.migrations||[],c.migrations.push(d),Wr(c)}catch(i){console.error(`
291
- [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${i.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 ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
292
- `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{Rn()}catch{}try{Un()}catch{}en=!0,nn(),console.log(`
293
- \u2713 Schema is now at v${we}
294
- `)}var Yr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Gr(e){let t=e.toLowerCase();return Yr.some(n=>n.test(t))}var zr=6e4;function Kr(){let e=Date.now(),t=[];for(let n of[le,Te,Re]){if(!x.existsSync(n))continue;let o;try{o=x.readdirSync(n)}catch{continue}for(let s of o){if(!Gr(s))continue;let r=N.join(n,s);try{let a=x.statSync(r);if(!a.isFile()||e-a.mtimeMs<zr)continue;t.push({dir:n,file:s,fullPath:r})}catch{}}}return t}function Qr({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 Zr(){let e=[];for(let t of[Te,Re]){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{$t(s)}catch(r){e.push({dir:N.basename(t),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Xr(e){let t=[],n=[];for(let r of[Te,Re]){if(!x.existsSync(r))continue;let a=x.readdirSync(r).filter(l=>l.endsWith(e));for(let l of a){let i=N.join(r,l),d=l.slice(0,-e.length),c=N.join(r,d);try{d.toLowerCase().endsWith(".json")?$t(i):x.accessSync(i,x.constants.R_OK),t.push({backupPath:i,originalPath:c,fileName:l,dir:r})}catch(f){n.push(`${N.basename(r)}/${l}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:a,fileName:l,dir:i}of t)try{Ao(r,a),o++}catch(d){s.push(`${N.basename(i)}/${l}: ${d.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),xo(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}}Oe();async function ei(e,t,n="op"){let o,s=new Promise((r,a)=>{o=setTimeout(()=>a(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function De(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 To(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:r=null}={}){try{await ei(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let a=await e.newPage();if(r)try{await r(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 _o();var qo="https://www.linkedin.com/messaging/",ui=10,an=3,di=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},fi=()=>yt(),Ie={pageRecoveries:0};async function Ct(e,t){if(Ie.pageRecoveries>=ui)throw new Error(`CDP unrecoverable: ${Ie.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
295
- \u{1F504} CDP dead \u2014 recovering page (#${Ie.pageRecoveries+1}). Reason: ${t}`),e.page=await To(e.browser,e.page,{returnUrl:qo,cookiesProvider:fi,setupPage:di}),Ie.pageRecoveries++,await $(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Ie.pageRecoveries}).
296
- `)}function Ve(e){return(e.messages||[]).find(t=>ze.has(t.status))?.status}var Q=process.argv.slice(2),ln=Q.includes("--full"),W=Q.includes("--dry-run"),jo=Q.includes("--report"),cn=Q.includes("--verbose"),Po=Q.includes("--backfill"),Lo=Q.includes("--enrich"),Fo=Q.includes("--today"),un=Q.includes("--read-unread"),ft=parseInt(Q.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),mi=Q.includes("--auto-enrich-replies"),Uo=parseInt(Q.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),pi=parseInt(Q.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function gi(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(),r=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(r)&&s>r)return"activity_after_last_read"}return null}async function hi(e,t){console.log(`
283
+ `),process.exit(1)}let o=pe.filter(s=>s.version>t);for(let s of o){console.log(`
284
+ Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{es(Oe,s.version),es(Me,s.version)}catch(l){console.error(`
285
+ [FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
286
+ `),process.exit(1)}let a=s.module;try{await a.up(Oe,Me)}catch(l){console.error(`
287
+ [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let c=Ii(r);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.
288
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
289
+ `))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
290
+ `)}process.exit(1)}try{let l=new Date().toISOString(),c={version:s.version,name:a.NAME||i,appliedAt:l},u=Xo();u.version=s.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(c),Ai(u)}catch(l){console.error(`
291
+ [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.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.
292
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Qn()}catch{}try{Xt()}catch{}kn=!0,Cn(),console.log(`
293
+ \u2713 Schema is now at v${$e}
294
+ `)}var xi=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Ei(e){let t=e.toLowerCase();return xi.some(n=>n.test(t))}var _i=6e4;function Ti(){let e=Date.now(),t=[];for(let n of[ue,Oe,Me]){if(!x.existsSync(n))continue;let o;try{o=x.readdirSync(n)}catch{continue}for(let s of o){if(!Ei(s))continue;let i=j.join(n,s);try{let r=x.statSync(i);if(!r.isFile()||e-r.mtimeMs<_i)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Ri({verbose:e=!1}={}){let t=Ti();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: ${j.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 Di(){let e=[];for(let t of[Oe,Me]){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=j.join(t,o);try{Lt(s)}catch(i){e.push({dir:j.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ii(e){let t=[],n=[];for(let i of[Oe,Me]){if(!x.existsSync(i))continue;let r=x.readdirSync(i).filter(a=>a.endsWith(e));for(let a of r){let l=j.join(i,a),c=a.slice(0,-e.length),u=j.join(i,c);try{c.toLowerCase().endsWith(".json")?Lt(l):x.accessSync(l,x.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:a,dir:i})}catch(d){n.push(`${j.basename(i)}/${a}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:a,dir:l}of t)try{ss(i,r),o++}catch(c){s.push(`${j.basename(l)}/${a}: ${c.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function ss(e,t){let n=t+".tmp";try{x.copyFileSync(e,n),ns(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}}Le();async function Ni(e,t,n="op"){let o,s=new Promise((i,r)=>{o=setTimeout(()=>r(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function je(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 rs(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await Ni(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let r=await e.newPage();if(i)try{await i(r)}catch{}if(s)try{let a=s();Array.isArray(a)&&a.length>0&&await r.setCookie(...a)}catch{}if(n){await r.goto(n,{waitUntil:"domcontentloaded",timeout:o});let a=r.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return r}await os();var Ss="https://www.linkedin.com/messaging/",Wi=10,_n=3,Yi=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},Gi=()=>Rt(),Pe={pageRecoveries:0};async function Ut(e,t){if(Pe.pageRecoveries>=Wi)throw new Error(`CDP unrecoverable: ${Pe.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
295
+ \u{1F504} CDP dead \u2014 recovering page (#${Pe.pageRecoveries+1}). Reason: ${t}`),e.page=await rs(e.browser,e.page,{returnUrl:Ss,cookiesProvider:Gi,setupPage:Yi}),Pe.pageRecoveries++,await $(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Pe.pageRecoveries}).
296
+ `)}function Ze(e){return(e.messages||[]).find(t=>tt.has(t.status))?.status}var Q=process.argv.slice(2),Tn=Q.includes("--full"),W=Q.includes("--dry-run"),gs=Q.includes("--report"),Rn=Q.includes("--verbose"),hs=Q.includes("--backfill"),ys=Q.includes("--enrich"),ws=Q.includes("--today"),Dn=Q.includes("--read-unread"),kt=parseInt(Q.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),zi=Q.includes("--auto-enrich-replies"),bs=parseInt(Q.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),Ki=parseInt(Q.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function Qi(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 Zi(e,t){console.log(`
297
297
  \u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
298
- `);let n=It(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,r=new Map,a=new Map,l=0,i=0,d=0,c=0,f=0,u=-1,m=0;for(;;){i++;let w=await ro(e),S=0;for(let p of w){if(!p.name||s.has(p.name))continue;s.set(p.name,p),S++,p.unread&&a.set(p.name,p);let v=t[p.name],C=gi(p,v);C&&(!un&&p.unread?l++:r.set(p.name,{card:p,reason:C})),v&&(C||(v.lastMessageBy=p.lastMessageBy,v.lastMessagePreview=p.lastMessagePreview||v.lastMessagePreview,v.lastMessageTime=p.lastMessageTime||v.lastMessageTime),v.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&(v.conversationStatus="unanswered_by_us"))}if(cn?console.log(` Round #${i}: +${S} new | Total: ${s.size} | Need reading: ${r.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${i}, ${r.size} need reading)`),S===0){if(f++,f>=3){console.log(`
299
- 3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!ln){if(r.size===c){if(d++,d>=3){console.log(`
300
- Caught up \u2014 3 screens with no new threads to read.`);break}}else d=0;c=r.size}let h=await jt(e);if(h){if(h.scrollTop===u){if(m++,m>=3){console.log(`
301
- Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;u=h.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let v=await p.boundingBox();v&&(await e.mouse.move(v.x+v.width/2,v.y+v.height/2),await e.mouse.wheel({deltaY:600}))}}await $(2e3)}cn||process.stdout.write(`
302
- `);let y=new Date().toISOString(),g=0;for(let[w,{card:S}]of r)t[w]||(t[w]={profileUrl:null,lastSynced:y,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},g++);let b=0;for(let[w,S]of a)t[w]||(t[w]={profileUrl:null,lastSynced:y,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},b++);if(console.log(`
303
- Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${g}`),console.log(` Need reading/re-reading: ${r.size}`),!un&&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`),r.size>0){let w={};for(let{reason:S}of r.values())w[S]=(w[S]||0)+1;for(let[S,h]of Object.entries(w))console.log(` ${S}: ${h}`)}if(!W){let w=It();w.lastIncrementalSync=new Date().toISOString(),ln&&(w.lastFullSync=w.lastIncrementalSync),Ln(w),pe(t)}return{allCards:s,toReRead:r,unreadCards:a}}async function yi(e,t,n,o){console.log(`
298
+ `);let n=Gt(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,r=new Map,a=0,l=0,c=0,u=0,d=0,f=-1,m=0;for(;;){l++;let w=await Do(e),S=0;for(let p of w){if(!p.name||s.has(p.name))continue;s.set(p.name,p),S++,p.unread&&r.set(p.name,p);let v=t[p.name],C=Qi(p,v);C&&(!Dn&&p.unread?a++:i.set(p.name,{card:p,reason:C})),v&&(C||(v.lastMessageBy=p.lastMessageBy,v.lastMessagePreview=p.lastMessagePreview||v.lastMessagePreview,v.lastMessageTime=p.lastMessageTime||v.lastMessageTime),v.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&(v.conversationStatus="unanswered_by_us"))}if(Rn?console.log(` Round #${l}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${l}, ${i.size} need reading)`),S===0){if(d++,d>=3){console.log(`
299
+ 3 rounds with no new items \u2014 end of visible list.`);break}}else d=0;if(!Tn){if(i.size===u){if(c++,c>=3){console.log(`
300
+ Caught up \u2014 3 screens with no new threads to read.`);break}}else c=0;u=i.size}let y=await on(e);if(y){if(y.scrollTop===f){if(m++,m>=3){console.log(`
301
+ Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;f=y.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let v=await p.boundingBox();v&&(await e.mouse.move(v.x+v.width/2,v.y+v.height/2),await e.mouse.wheel({deltaY:600}))}}await $(2e3)}Rn||process.stdout.write(`
302
+ `);let h=new Date().toISOString(),g=0;for(let[w,{card:S}]of i)t[w]||(t[w]={profileUrl:null,lastSynced:h,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},g++);let b=0;for(let[w,S]of r)t[w]||(t[w]={profileUrl:null,lastSynced:h,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},b++);if(console.log(`
303
+ Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${g}`),console.log(` Need reading/re-reading: ${i.size}`),!Dn&&a>0&&console.log(` Preserved unread (default): ${a} \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,y]of Object.entries(w))console.log(` ${S}: ${y}`)}if(!W){let w=Gt();w.lastIncrementalSync=new Date().toISOString(),Tn&&(w.lastFullSync=w.lastIncrementalSync),ro(w),ye(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function Xi(e,t,n,o){console.log(`
304
304
  \u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
305
- `);let s=Array.from(t.entries()),r=Math.min(s.length,ft);if(r===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(qo,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!De(f))throw f;await Ct(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,u)=>(a[f[1].reason]??5)-(a[u[1].reason]??5)),console.log(` Reading ${r} of ${s.length} threads (--max=${ft})
306
- `);let l=[],i=[],d=0,c=0;for(let f=0;f<r;f++){let[u,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${r}] ${u} (${y})`);let g=e.page;try{let b={verified:!1,headerName:null};try{b=await qt(g,u)}catch(S){if(De(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 io(e.page,u)}catch(S){if(De(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),d++;try{await he(e.page)}catch{}continue}let w=await Lt(g);if(w&&w.length>0){if(!Ft(w,u,i)){console.log(" Skipped \u2014 stale data."),d++,await he(g);continue}let h=await Pt(g),p=n[u]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},v=p.messages?.length||0;p.messages=Ut(p.messages,w),p.lastSynced=new Date().toISOString(),h&&!p.profileUrl&&(p.profileUrl=h);let C=p.messages.filter(D=>!["draft","confirmed","rejected","needs_review"].includes(D.status));p.lastMessageBy=Jt(C,u),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[u]=p,W||pe(n);let A=p.messages.length-v;console.log(` ${p.messages.length} msgs (${A>=0?"+"+A:A} new)${h&&!p.profileUrl?" +url":""}`),l.push({name:u}),i=[...new Set(w.map(D=>D.sender).filter(D=>D&&D!=="Unknown"))]}else console.log(" No messages extracted."),d++;await he(g),await $(500)}catch(b){if(!De(b))throw b;c++,o&&o.add(u),await Ct(e,`Phase 2 thread ${f+1}/${r} (${u})`)}}return console.log(`
307
- Phase 2 complete: ${l.length} read, ${d} failed${c?`, ${c} skipped on CDP recovery`:""}`),s.length>r&&console.log(` ${s.length-r} more threads pending (run again or increase --max)`),l}async function wi(e,t,n){if(!mi)return null;console.log(`
305
+ `);let s=Array.from(t.entries()),i=Math.min(s.length,kt);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(Ss,{waitUntil:"domcontentloaded",timeout:6e4})}catch(d){if(!je(d))throw d;await Ut(e,"Phase 2 inbox reset")}await $(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let r={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((d,f)=>(r[d[1].reason]??5)-(r[f[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${kt})
306
+ `);let a=[],l=[],c=0,u=0;for(let d=0;d<i;d++){let[f,{card:m,reason:h}]=s[d];console.log(` [${d+1}/${i}] ${f} (${h})`);let g=e.page;try{let b={verified:!1,headerName:null};try{b=await cn(g,f)}catch(S){if(je(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 Io(e.page,f)}catch(S){if(je(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),c++;try{await ve(e.page)}catch{}continue}let w=await rn(g);if(w&&w.length>0){if(!ln(w,f,l)){console.log(" Skipped \u2014 stale data."),c++,await ve(g);continue}let y=await sn(g),p=n[f]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},v=p.messages?.length||0;p.messages=an(p.messages,w),p.lastSynced=new Date().toISOString(),y&&!p.profileUrl&&(p.profileUrl=y);let C=p.messages.filter(R=>!["draft","confirmed","rejected","needs_review"].includes(R.status));p.lastMessageBy=Ot(C,f),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[f]=p,W||ye(n);let _=p.messages.length-v;console.log(` ${p.messages.length} msgs (${_>=0?"+"+_:_} new)${y&&!p.profileUrl?" +url":""}`),a.push({name:f}),l=[...new Set(w.map(R=>R.sender).filter(R=>R&&R!=="Unknown"))]}else console.log(" No messages extracted."),c++;await ve(g),await $(500)}catch(b){if(!je(b))throw b;u++,o&&o.add(f),await Ut(e,`Phase 2 thread ${d+1}/${i} (${f})`)}}return console.log(`
307
+ Phase 2 complete: ${a.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)`),a}async function el(e,t,n){if(!zi)return null;console.log(`
308
308
  \u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
309
- `);let o=new Set(n.map(m=>m.name)),s=J(),r=Date.now(),a=pi*24*60*60*1e3,l=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let g=y.profileUrl;if(!g)continue;let w=s[g]?._lastEnrichedAt;if(w){let S=r-new Date(w).getTime();if(Number.isFinite(S)&&S<a)continue}l.push({name:m,profileUrl:g,lastMessageTime:y.lastMessageTime||null})}if(l.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
310
- `),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};l.sort((m,y)=>{let g=new Date(m.lastMessageTime||0).getTime();return new Date(y.lastMessageTime||0).getTime()-g});let i=l.slice(0,Uo),d=l.length-i.length;if(console.log(` Candidates: ${l.length} | picking ${i.length} (cap ${Uo}) | skipping ${d}`),d>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),W){console.log(" [DRY RUN] Would enrich:");for(let m of i)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:i.length,enriched:0,skipped:d,errors:0,dryRun:!0}}let{viewProfile:c}=await No().then(()=>Oo),f=0,u=0;for(let m=0;m<i.length;m++){let y=i[m];console.log(`
311
- [${m+1}/${i.length}] Enriching ${y.name} ${y.profileUrl}`);try{let g=await c(e.page,y.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!g||!g.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),u++;continue}let b={name:g.name,title:g.title,location:g.location,about:g.about,currentCompany:g.currentCompany,currentSchool:g.currentSchool,topSkills:g.topSkills,availableSections:g.availableSections,connectionsLevel:g.connectionsLevel,mutualConnectionsCount:g.mutualConnectionsCount,followers:g.followers,openToWork:g.openToWork,hiring:g.hiring,hasVerifiedBadge:g.hasVerifiedBadge,photoUrl:g.photoUrl,source:"auto-enrich-replies"},w=!1;for(let[S,h]of[["experience",g.experience],["featured",g.featured],["education",g.education],["skillsFull",g.skillsFull],["recommendations",g.recommendations],["certifications",g.certifications]])Array.isArray(h)&&h.length>0&&(b[S]=h,w=!0);w&&(b._lastEnrichedAt=new Date().toISOString()),Ce(y.profileUrl,b),g.resolvedUrl&&gt(y.profileUrl,g.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${w?"yes":"no \u2014 basic only"})`)}catch(g){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(g.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:i.length,enriched:f,skipped:d,errors:u,authWall:!0};console.log(` \u2717 ${g.message?.slice(0,200)}`),u++}m+1<i.length&&await $(8e3)}return console.log(`
312
- Auto-enrich done: ${f} enriched, ${u} errors, ${d} skipped (over cap)
313
- `),{picked:i.length,enriched:f,skipped:d,errors:u}}function bi(e,t){console.log(`
309
+ `);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r=Ki*24*60*60*1e3,a=[];for(let m of o){let h=t[m];if(!h||h.lastMessageBy!=="them")continue;let g=h.profileUrl;if(!g)continue;let w=s[g]?._lastEnrichedAt;if(w){let S=i-new Date(w).getTime();if(Number.isFinite(S)&&S<r)continue}a.push({name:m,profileUrl:g,lastMessageTime:h.lastMessageTime||null})}if(a.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
310
+ `),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};a.sort((m,h)=>{let g=new Date(m.lastMessageTime||0).getTime();return new Date(h.lastMessageTime||0).getTime()-g});let l=a.slice(0,bs),c=a.length-l.length;if(console.log(` Candidates: ${a.length} | picking ${l.length} (cap ${bs}) | skipping ${c}`),c>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),W){console.log(" [DRY RUN] Would enrich:");for(let m of l)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:l.length,enriched:0,skipped:c,errors:0,dryRun:!0}}let{viewProfile:u}=await ps().then(()=>ms),d=0,f=0;for(let m=0;m<l.length;m++){let h=l[m];console.log(`
311
+ [${m+1}/${l.length}] Enriching ${h.name} ${h.profileUrl}`);try{let g=await u(e.page,h.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!g||!g.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),f++;continue}let b={name:g.name,title:g.title,location:g.location,about:g.about,currentCompany:g.currentCompany,currentSchool:g.currentSchool,topSkills:g.topSkills,availableSections:g.availableSections,connectionsLevel:g.connectionsLevel,mutualConnectionsCount:g.mutualConnectionsCount,followers:g.followers,openToWork:g.openToWork,hiring:g.hiring,hasVerifiedBadge:g.hasVerifiedBadge,photoUrl:g.photoUrl,source:"auto-enrich-replies"},w=!1;for(let[S,y]of[["experience",g.experience],["featured",g.featured],["education",g.education],["skillsFull",g.skillsFull],["recommendations",g.recommendations],["certifications",g.certifications]])Array.isArray(y)&&y.length>0&&(b[S]=y,w=!0);w&&(b._lastEnrichedAt=new Date().toISOString()),Te(h.profileUrl,b),g.resolvedUrl&&At(h.profileUrl,g.resolvedUrl),d++,console.log(` \u2713 saved (rich sections: ${w?"yes":"no \u2014 basic only"})`)}catch(g){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(g.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:l.length,enriched:d,skipped:c,errors:f,authWall:!0};console.log(` \u2717 ${g.message?.slice(0,200)}`),f++}m+1<l.length&&await $(8e3)}return console.log(`
312
+ Auto-enrich done: ${d} enriched, ${f} errors, ${c} skipped (over cap)
313
+ `),{picked:l.length,enriched:d,skipped:c,errors:f}}function tl(e,t){console.log(`
314
314
  \u2550\u2550 PHASE 3: Post-processing & Enrichment \u2550\u2550
315
- `);let n=J();for(let o of t){let{name:s}=o,r=e[s];if(!r?.messages?.length)continue;try{Ht(r,s,n)}catch(i){console.warn(` [!] Enrichment failed for ${s}: ${i.message}`)}r._cardSynced&&delete r._cardSynced;let a=r.profileUrl,l=null;if(a&&(l=n[a]||null),!l){let i=Object.entries(n).filter(([,d])=>d.name===s);i.length===1&&(a||(a=i[0][0],r.profileUrl=a),l=i[0][1])}!l&&a&&(l=Ce(a,{name:s,source:"sync-all"})),l&&(r.category&&!l.category&&(l.category=r.category),l.conversationStatus=r.conversationStatus,l.lastUpdated=new Date().toISOString()),a&&l&&(r.isConnection=l.connectionStatus==="connected")}W||(Ee(n),pe(e)),console.log(` Enriched ${t.length} conversations.`),Bo(e)}function Bo(e){let t=new Map;for(let[s,r]of Object.entries(e)){if(!r.profileUrl)continue;let a=r.profileUrl.toLowerCase().replace(/\/$/,"");t.has(a)||t.set(a,[]),t.get(a).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[r,a]=s.map(c=>({name:c,conv:e[c]})),l=(r.conv.messages?.length||0)>=(a.conv.messages?.length||0)?r:a,i=l===r?a:r,d=new Set((l.conv.messages||[]).map(c=>`${c.text?.slice(0,80)}|${c.time}`));for(let c of i.conv.messages||[]){let f=`${c.text?.slice(0,80)}|${c.time}`;d.has(f)||(l.conv.messages.push(c),d.add(f))}l.conv.messages.sort((c,f)=>(c.time||"").localeCompare(f.time||"")),i.conv.notes&&!l.conv.notes&&(l.conv.notes=i.conv.notes),i.conv.priority&&!l.conv.priority&&(l.conv.priority=i.conv.priority),i.conv.categorySource==="manual"&&l.conv.categorySource!=="manual"&&(l.conv.category=i.conv.category,l.conv.categorySource="manual"),(i.conv.lastSynced||"")>(l.conv.lastSynced||"")&&(l.conv.lastSynced=i.conv.lastSynced),delete e[i.name],console.log(` Merged: "${i.name}" \u2192 "${l.name}"`),o++}o>0&&(W||pe(e),console.log(` ${o} duplicates merged.`))}function Si(){let e=tt(),t=J(),n=Object.entries(e);console.log(`
315
+ `);let n=J();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Nt(i,s,n)}catch(l){console.warn(` [!] Enrichment failed for ${s}: ${l.message}`)}i._cardSynced&&delete i._cardSynced;let r=i.profileUrl,a=null;if(r&&(a=n[r]||null),!a){let l=Object.entries(n).filter(([,c])=>c.name===s);l.length===1&&(r||(r=l[0][0],i.profileUrl=r),a=l[0][1])}!a&&r&&(a=Te(r,{name:s,source:"sync-all"})),a&&(i.category&&!a.category&&(a.category=i.category),a.conversationStatus=i.conversationStatus,a.lastUpdated=new Date().toISOString()),r&&a&&(i.isConnection=a.connectionStatus==="connected")}W||(Re(n),ye(e)),console.log(` Enriched ${t.length} conversations.`),vs(e)}function vs(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let r=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(r)||t.set(r,[]),t.get(r).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,r]=s.map(u=>({name:u,conv:e[u]})),a=(i.conv.messages?.length||0)>=(r.conv.messages?.length||0)?i:r,l=a===i?r:i,c=new Set((a.conv.messages||[]).map(u=>`${u.text?.slice(0,80)}|${u.time}`));for(let u of l.conv.messages||[]){let d=`${u.text?.slice(0,80)}|${u.time}`;c.has(d)||(a.conv.messages.push(u),c.add(d))}a.conv.messages.sort((u,d)=>(u.time||"").localeCompare(d.time||"")),l.conv.notes&&!a.conv.notes&&(a.conv.notes=l.conv.notes),l.conv.priority&&!a.conv.priority&&(a.conv.priority=l.conv.priority),l.conv.categorySource==="manual"&&a.conv.categorySource!=="manual"&&(a.conv.category=l.conv.category,a.conv.categorySource="manual"),(l.conv.lastSynced||"")>(a.conv.lastSynced||"")&&(a.conv.lastSynced=l.conv.lastSynced),delete e[l.name],console.log(` Merged: "${l.name}" \u2192 "${a.name}"`),o++}o>0&&(W||ye(e),console.log(` ${o} duplicates merged.`))}function nl(){let e=lt(),t=J(),n=Object.entries(e);console.log(`
316
316
  \u2550\u2550 ENRICHMENT: Re-processing all conversations \u2550\u2550
317
- `);let o=0,s=0,r=0;for(let[f,u]of n){if(!u.profileUrl){let m=Object.entries(t).filter(([,y])=>y.name===f);m.length===1&&(u.profileUrl=m[0][0],r++)}if(!u.messages||u.messages.length===0){s++;continue}try{Ht(u,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}Bo(e),W||pe(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),r>0&&console.log(` Linked profileUrl from people.json: ${r}`),console.log(` Total: ${n.length}`);let a=new Set(Object.keys(e)),l=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),i=Object.entries(t),d=0,c=0;for(let[f,u]of i){if(l.has(f)){c++;continue}if(u.name&&a.has(u.name)){c++;continue}if(u.connectionStatus!=="connected"){c++;continue}fo(u,f),d++}W||Ee(t),console.log(`
318
- People enriched: ${d}`),console.log(` People skipped (have conversation or not connected): ${c}`),console.log(` People total: ${i.length}`),dn(e,null,null)}function dn(e,t,n,o={}){let s=Object.entries(e),r=J(),{unreadCards:a=null,readUnread:l=!1}=o;console.log(`
317
+ `);let o=0,s=0,i=0;for(let[d,f]of n){if(!f.profileUrl){let m=Object.entries(t).filter(([,h])=>h.name===d);m.length===1&&(f.profileUrl=m[0][0],i++)}if(!f.messages||f.messages.length===0){s++;continue}try{Nt(f,d,t)}catch(m){console.warn(` [!] Enrichment failed for ${d}: ${m.message}`)}o++}vs(e),W||ye(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let r=new Set(Object.keys(e)),a=new Set(Object.values(e).map(d=>d.profileUrl).filter(Boolean)),l=Object.entries(t),c=0,u=0;for(let[d,f]of l){if(a.has(d)){u++;continue}if(f.name&&r.has(f.name)){u++;continue}if(f.connectionStatus!=="connected"){u++;continue}dn(f,d),c++}W||Re(t),console.log(`
318
+ People enriched: ${c}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${l.length}`),In(e,null,null)}function In(e,t,n,o={}){let s=Object.entries(e),i=J(),{unreadCards:r=null,readUnread:a=!1}=o;console.log(`
319
319
  \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
320
- `),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 i=s.length,d=s.filter(([,k])=>k.messages?.length>0).length,c=s.filter(([,k])=>!k.messages||k.messages.length===0).length,f=s.filter(([,k])=>k.profileUrl).length,u=s.filter(([,k])=>!k.profileUrl).length;console.log(`
321
- Database:`),console.log(` Total conversations: ${i}`),console.log(` With messages: ${d}`),console.log(` Without messages: ${c}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${u}`);let m=0,y=0;for(let[,k]of s)for(let E of k.messages||[])m++,(!E.sender||E.sender==="Unknown")&&y++;console.log(`
322
- Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let g={};for(let[,k]of s){let E=k.conversationStatus||"null";g[E]=(g[E]||0)+1}console.log(`
323
- Statuses:`);for(let[k,E]of Object.entries(g).sort((_,M)=>M[1]-_[1]))console.log(` ${k}: ${E}`);let b={};for(let[,k]of s){let E=k.category||"(none)";b[E]=(b[E]||0)+1}console.log(`
324
- Categories:`);for(let[k,E]of Object.entries(b).sort((_,M)=>M[1]-_[1]))console.log(` ${k}: ${E}`);let w={};for(let[,k]of s){let E=k.actionNeeded||"(none)";w[E]=(w[E]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
325
- Actions Needed:`);for(let[k,E]of Object.entries(w).sort((_,M)=>M[1]-_[1]))console.log(` ${k}: ${E}`)}let S=new Map;for(let[k,E]of s){if(!E.profileUrl)continue;let _=E.profileUrl.toLowerCase().replace(/\/$/,"");S.has(_)||S.set(_,[]),S.get(_).push(k)}let h=[...S.entries()].filter(([,k])=>k.length>1);if(h.length>0){console.log(`
326
- Duplicates (${h.length}):`);for(let[k,E]of h)console.log(` ${E.join(" | ")} \u2192 ${k}`)}let p=s.filter(([,k])=>k.conversationStatus==="unanswered_by_us").sort((k,E)=>(E[1].lastSynced||"").localeCompare(k[1].lastSynced||"")),v=s.filter(([,k])=>Ve(k));if(console.log(`
320
+ `),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 l=s.length,c=s.filter(([,k])=>k.messages?.length>0).length,u=s.filter(([,k])=>!k.messages||k.messages.length===0).length,d=s.filter(([,k])=>k.profileUrl).length,f=s.filter(([,k])=>!k.profileUrl).length;console.log(`
321
+ Database:`),console.log(` Total conversations: ${l}`),console.log(` With messages: ${c}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${d}`),console.log(` Without profileUrl: ${f}`);let m=0,h=0;for(let[,k]of s)for(let A of k.messages||[])m++,(!A.sender||A.sender==="Unknown")&&h++;console.log(`
322
+ Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${h} (${m>0?(h/m*100).toFixed(1):0}%)`);let g={};for(let[,k]of s){let A=k.conversationStatus||"null";g[A]=(g[A]||0)+1}console.log(`
323
+ Statuses:`);for(let[k,A]of Object.entries(g).sort((T,N)=>N[1]-T[1]))console.log(` ${k}: ${A}`);let b={};for(let[,k]of s){let A=k.category||"(none)";b[A]=(b[A]||0)+1}console.log(`
324
+ Categories:`);for(let[k,A]of Object.entries(b).sort((T,N)=>N[1]-T[1]))console.log(` ${k}: ${A}`);let w={};for(let[,k]of s){let A=k.actionNeeded||"(none)";w[A]=(w[A]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
325
+ Actions Needed:`);for(let[k,A]of Object.entries(w).sort((T,N)=>N[1]-T[1]))console.log(` ${k}: ${A}`)}let S=new Map;for(let[k,A]of s){if(!A.profileUrl)continue;let T=A.profileUrl.toLowerCase().replace(/\/$/,"");S.has(T)||S.set(T,[]),S.get(T).push(k)}let y=[...S.entries()].filter(([,k])=>k.length>1);if(y.length>0){console.log(`
326
+ Duplicates (${y.length}):`);for(let[k,A]of y)console.log(` ${A.join(" | ")} \u2192 ${k}`)}let p=s.filter(([,k])=>k.conversationStatus==="unanswered_by_us").sort((k,A)=>(A[1].lastSynced||"").localeCompare(k[1].lastSynced||"")),v=s.filter(([,k])=>Ze(k));if(console.log(`
327
327
  \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
328
- `),a&&!l&&a.size>0){let k=[...a.entries()];console.log(` STILL UNREAD ON LINKEDIN (${k.length}) \u2014 kept bold; read them in the LinkedIn UI:
329
- `);let E=30;for(let[_,M]of k.slice(0,E)){let H=e[_],se=H?.category?` [${H.category}]`:"",re=M.lastMessageTime||H?.lastMessageTime||"",j=(M.lastMessagePreview||"").slice(0,80),P=H?.summary,U=H?.personContext?.title?`${H.personContext.title}${H.personContext.company?` at ${H.personContext.company}`:""}`:null;console.log(` ${_}${se}${re?` \u2014 ${re}`:""}`),j&&console.log(` "${j}"`),P?console.log(` ${P}`):U&&console.log(` ${U}`)}k.length>E&&console.log(`
330
- ... and ${k.length-E} more`),console.log(`
328
+ `),r&&!a&&r.size>0){let k=[...r.entries()];console.log(` STILL UNREAD ON LINKEDIN (${k.length}) \u2014 kept bold; read them in the LinkedIn UI:
329
+ `);let A=30;for(let[T,N]of k.slice(0,A)){let H=e[T],re=H?.category?` [${H.category}]`:"",ie=N.lastMessageTime||H?.lastMessageTime||"",P=(N.lastMessagePreview||"").slice(0,80),L=H?.summary,U=H?.personContext?.title?`${H.personContext.title}${H.personContext.company?` at ${H.personContext.company}`:""}`:null;console.log(` ${T}${re}${ie?` \u2014 ${ie}`:""}`),P&&console.log(` "${P}"`),L?console.log(` ${L}`):U&&console.log(` ${U}`)}k.length>A&&console.log(`
330
+ ... and ${k.length-A} more`),console.log(`
331
331
  To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
332
- `)}if(v.length>0){let k=v.filter(([,_])=>Ve(_)===V.CONFIRMED),E=v.filter(([,_])=>{let M=Ve(_);return M===V.DRAFT||M===V.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${k.length} confirmed, ${E.length} pending)`),E.length>0&&console.log(" Review: npm run messages -- --review-drafts"),k.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,k])=>k.actionNeeded==="schedule_call"),A=p.filter(([,k])=>k.actionNeeded!=="schedule_call");if(A.sort((k,E)=>{let _={high:0,medium:1,low:2}[k[1].suggestedPriority]??3,M={high:0,medium:1,low:2}[E[1].suggestedPriority]??3;return _-M}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
333
- `);for(let[k,E]of C){let _=E.category||"",M=E.summary||"";console.log(` ${k}${_?` [${_}]`:""} \u2192 schedule_call`),M&&console.log(` ${M}`)}console.log()}if(A.length>0){console.log(` REPLY NEEDED (${A.length}):
334
- `);let k=20;for(let[E,_]of A.slice(0,k)){let M=_.category||"",H=_.suggestedPriority?`[${_.suggestedPriority}]`:"",se=(_.autoTags||[]).slice(0,4).join(", "),re=_.summary||"",P=[..._.messages||[]].reverse().find(U=>U.sender!==z&&U.sender!=="Unknown")?.text?.slice(0,80)||_.lastMessagePreview?.slice(0,80)||"";console.log(` ${H} ${E}${M?` [${M}]`:""}`),console.log(re?` ${re}`:` "${P}"`),se&&console.log(` #${se.replace(/, /g," #")}`)}A.length>k&&console.log(`
335
- ... and ${A.length-k} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let D=new Set(Object.keys(e)),T=new Set(Object.values(e).map(k=>k.profileUrl).filter(Boolean)),F=Object.entries(r).filter(([k,E])=>E.connectionStatus==="connected"&&E.personActionNeeded==="initiate_contact"&&!T.has(k)&&!(E.name&&D.has(E.name))).sort((k,E)=>{let _={high:0,medium:1,low:2}[k[1].personPriority]??3,M={high:0,medium:1,low:2}[E[1].personPriority]??3;return _!==M?_-M:(E[1].connectionDate||"").localeCompare(k[1].connectionDate||"")});if(F.length>0){console.log(`
336
- INITIATE CONTACT (${F.length}):
337
- `);let k=20;for(let[E,_]of F.slice(0,k)){let M=_.personPriority?`[${_.personPriority.toUpperCase()}]`:"",H=_.personSummary||_.title||"";console.log(` ${M} ${_.name||"Unknown"} \u2014 ${H}`)}F.length>k&&console.log(`
338
- ... and ${F.length-k} more`)}let G=s.filter(([,k])=>k.conversationStatus==="awaiting_reply");G.length>0&&console.log(`
339
- BALL IN THEIR COURT: ${G.length} conversations`),W&&console.log(`
332
+ `)}if(v.length>0){let k=v.filter(([,T])=>Ze(T)===V.CONFIRMED),A=v.filter(([,T])=>{let N=Ze(T);return N===V.DRAFT||N===V.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${k.length} confirmed, ${A.length} pending)`),A.length>0&&console.log(" Review: npm run messages -- --review-drafts"),k.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,k])=>k.actionNeeded==="schedule_call"),_=p.filter(([,k])=>k.actionNeeded!=="schedule_call");if(_.sort((k,A)=>{let T={high:0,medium:1,low:2}[k[1].suggestedPriority]??3,N={high:0,medium:1,low:2}[A[1].suggestedPriority]??3;return T-N}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
333
+ `);for(let[k,A]of C){let T=A.category||"",N=A.summary||"";console.log(` ${k}${T?` [${T}]`:""} \u2192 schedule_call`),N&&console.log(` ${N}`)}console.log()}if(_.length>0){console.log(` REPLY NEEDED (${_.length}):
334
+ `);let k=20;for(let[A,T]of _.slice(0,k)){let N=T.category||"",H=T.suggestedPriority?`[${T.suggestedPriority}]`:"",re=(T.autoTags||[]).slice(0,4).join(", "),ie=T.summary||"",L=[...T.messages||[]].reverse().find(U=>U.sender!==z&&U.sender!=="Unknown")?.text?.slice(0,80)||T.lastMessagePreview?.slice(0,80)||"";console.log(` ${H} ${A}${N?` [${N}]`:""}`),console.log(ie?` ${ie}`:` "${L}"`),re&&console.log(` #${re.replace(/, /g," #")}`)}_.length>k&&console.log(`
335
+ ... and ${_.length-k} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let R=new Set(Object.keys(e)),E=new Set(Object.values(e).map(k=>k.profileUrl).filter(Boolean)),M=Object.entries(i).filter(([k,A])=>A.connectionStatus==="connected"&&A.personActionNeeded==="initiate_contact"&&!E.has(k)&&!(A.name&&R.has(A.name))).sort((k,A)=>{let T={high:0,medium:1,low:2}[k[1].personPriority]??3,N={high:0,medium:1,low:2}[A[1].personPriority]??3;return T!==N?T-N:(A[1].connectionDate||"").localeCompare(k[1].connectionDate||"")});if(M.length>0){console.log(`
336
+ INITIATE CONTACT (${M.length}):
337
+ `);let k=20;for(let[A,T]of M.slice(0,k)){let N=T.personPriority?`[${T.personPriority.toUpperCase()}]`:"",H=T.personSummary||T.title||"";console.log(` ${N} ${T.name||"Unknown"} \u2014 ${H}`)}M.length>k&&console.log(`
338
+ ... and ${M.length-k} more`)}let Y=s.filter(([,k])=>k.conversationStatus==="awaiting_reply");Y.length>0&&console.log(`
339
+ BALL IN THEIR COURT: ${Y.length} conversations`),W&&console.log(`
340
340
  [DRY RUN \u2014 no changes written]`),console.log(`
341
341
  \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
342
- `)}async function vi(e,t){console.log(`
342
+ `)}async function ol(e,t){console.log(`
343
343
  \u2550\u2550 BACKFILL: Reading conversations with 0 messages \u2550\u2550
344
- `);let n=Object.entries(t).filter(([,i])=>!i.messages||i.messages.length===0).map(([i,d])=>({name:i,preview:d.lastMessagePreview||"",lastBy:d.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((i,d)=>i.lastBy==="them"&&d.lastBy!=="them"?-1:i.lastBy!=="them"&&d.lastBy==="them"?1:0);let o=Math.min(n.length,ft);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${ft})
345
- `);let s=[],r=0,a=0,l=[];for(let i=0;i<o;i++){let{name:d}=n[i];console.log(` [${i+1}/${o}] ${d}`);let c=e.page;try{if(await Sn(c),!(await qt(c,d)).verified){console.log(" Not found or thread didn't load."),r++,await he(c),await $(500);continue}let u=await Lt(c);if(!u||u.length===0){console.log(" No messages extracted."),r++,await he(c),await $(500);continue}if(!Ft(u,d,l)){console.log(" Skipped \u2014 stale data."),r++,await he(c),await $(500);continue}let y=await Pt(c),g=t[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};g.messages=Ut(g.messages,u),g.lastSynced=new Date().toISOString(),y&&(g.profileUrl=y),t[d]=g,W||pe(t),console.log(` \u2713 ${g.messages.length} msgs${y?" +url":""}`),s.push({name:d}),l=[...new Set(u.map(b=>b.sender).filter(b=>b&&b!=="Unknown"))],await he(c),await $(500)}catch(f){if(!De(f))throw f;a++,await Ct(e,`Backfill thread ${i+1}/${o} (${d})`)}}return console.log(`
346
- Backfill complete: ${s.length} read, ${r} failed${a?`, ${a} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function $i(e){let t=nt(),n=Object.values(e),o=n.filter(i=>i.sources?.includes("recruiters-from-jobs")&&!i.connectionStatus).length,s=n.filter(i=>i.connectionStatus==="modal_failed").length,r=o+s,a=n.filter(i=>i.connectionStatus==="connected"&&i.connectionMethod).length,l=n.filter(i=>i.connectionStatus==="pending"||i.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: ${r} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${a} accepted, ${l} pending`),r===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 ki(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",r=o.lastJobTitle?fe(o.lastJobTitle,25):"",a=o.lastJobDate||"",l=r?` (last: ${r}${a?", "+a:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${fe(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 Ci(){let e=Jn(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=fe(o.title||"?",30),r=fe(o.company||"?",15),a=o.salary?` \u2014 ${fe(o.salary,12)}`:"",l=o.location?` \u2014 ${fe(o.location,15)}`:"",i=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${r}${a}${l}${i}`)}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 Ei(){let e=Bn();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 xi(){let e=Fn();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=fe(t.topAnswer,30);console.log(` "${fe(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(` "${fe(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 fe(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function _i(){let e=tt(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(h=>h.profileUrl).filter(Boolean));console.log(`
344
+ `);let n=Object.entries(t).filter(([,l])=>!l.messages||l.messages.length===0).map(([l,c])=>({name:l,preview:c.lastMessagePreview||"",lastBy:c.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((l,c)=>l.lastBy==="them"&&c.lastBy!=="them"?-1:l.lastBy!=="them"&&c.lastBy==="them"?1:0);let o=Math.min(n.length,kt);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${kt})
345
+ `);let s=[],i=0,r=0,a=[];for(let l=0;l<o;l++){let{name:c}=n[l];console.log(` [${l+1}/${o}] ${c}`);let u=e.page;try{if(await qn(u),!(await cn(u,c)).verified){console.log(" Not found or thread didn't load."),i++,await ve(u),await $(500);continue}let f=await rn(u);if(!f||f.length===0){console.log(" No messages extracted."),i++,await ve(u),await $(500);continue}if(!ln(f,c,a)){console.log(" Skipped \u2014 stale data."),i++,await ve(u),await $(500);continue}let h=await sn(u),g=t[c]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};g.messages=an(g.messages,f),g.lastSynced=new Date().toISOString(),h&&(g.profileUrl=h),t[c]=g,W||ye(t),console.log(` \u2713 ${g.messages.length} msgs${h?" +url":""}`),s.push({name:c}),a=[...new Set(f.map(b=>b.sender).filter(b=>b&&b!=="Unknown"))],await ve(u),await $(500)}catch(d){if(!je(d))throw d;r++,await Ut(e,`Backfill thread ${l+1}/${o} (${c})`)}}return console.log(`
346
+ Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function sl(e){let t=at(),n=Object.values(e),o=n.filter(l=>l.sources?.includes("recruiters-from-jobs")&&!l.connectionStatus).length,s=n.filter(l=>l.connectionStatus==="modal_failed").length,i=o+s,r=n.filter(l=>l.connectionStatus==="connected"&&l.connectionMethod).length,a=n.filter(l=>l.connectionStatus==="pending"||l.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: ${r} accepted, ${a} 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 rl(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?ge(o.lastJobTitle,25):"",r=o.lastJobDate||"",a=i?` (last: ${i}${r?", "+r:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ge(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${a}`)}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 il(){let e=ho(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=ge(o.title||"?",30),i=ge(o.company||"?",15),r=o.salary?` \u2014 ${ge(o.salary,12)}`:"",a=o.location?` \u2014 ${ge(o.location,15)}`:"",l=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${r}${a}${l}`)}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 ll(){let e=tn();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 al(){let e=io();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=ge(t.topAnswer,30);console.log(` "${ge(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(` "${ge(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 ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function cl(){let e=lt(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(y=>y.profileUrl).filter(Boolean));console.log(`
347
347
  \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
348
- `),console.log(yo()),console.log(""),$i(t),console.log(""),ki(t),console.log(""),Ei(),console.log(""),Ci(),console.log(""),xi(),console.log("");let s=Object.entries(e),r=s.filter(([,h])=>h.unread===!0).sort((h,p)=>(p[1].lastMessageTime||"").localeCompare(h[1].lastMessageTime||""));if(r.length>0){let h=r.slice(0,10);console.log(` UNREAD ON LINKEDIN (${r.length}) \u2014 bold in LinkedIn UI, not yet opened:
349
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],A=C.category?` [${C.category}]`:"",D=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${v}${A}${D?` \u2014 ${D}`:""}`)}r.length>10&&console.log(` ... +${r.length-10} more`),console.log()}let a=new Date().toISOString().slice(0,10),l=s.filter(([,h])=>h.followUpNote),i=l.filter(([,h])=>!h.followUpDate||h.followUpDate<=a),d=l.filter(([,h])=>h.followUpDate&&h.followUpDate>a);if(l.length>0){console.log(` FOLLOW-UPS (${i.length} due, ${d.length} scheduled):
350
- `);for(let[h,p]of i){let v=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${h}${v} \u2014 ${p.followUpNote}`)}for(let[h,p]of d.slice(0,5))console.log(` \u{1F4C5} ${h} [${p.followUpDate}] \u2014 ${p.followUpNote}`);d.length>5&&console.log(` ... +${d.length-5} more scheduled`),console.log()}let c=h=>h.actionNeeded&&h.actionNeeded!=="none"&&(!h.reviewedAtPreview||at(h.lastMessagePreview)!==at(h.reviewedAtPreview)),f=s.filter(([,h])=>c(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(f.length>0){let h=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
351
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],A=C.priority||C.suggestedPriority||"",D=C.category?` [${C.category}]`:"",T=C.summary||"";console.log(` ${p+1}. ${A?`[${A}] `:""}${v}${D} \u2014 ${T}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let u=s.filter(([,h])=>h.actionNeeded==="schedule_call").sort((h,p)=>{let v={high:0,medium:1,low:2}[h[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return v-C});if(u.length>0){let h=u.slice(0,5);console.log(` CALLS TO SCHEDULE (${u.length}):
352
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],A=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${A}`)}u.length>5&&console.log(` ... +${u.length-5} more`),console.log()}let m=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&(h.suggestedPriority==="high"||h.priority==="high")&&!c(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(m.length>0){let h=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
353
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],A=C.category?` [${C.category}]`:"",D=C.summary||"";console.log(` ${p+1}. ${v}${A} \u2014 ${D}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&h.suggestedPriority==="medium"&&h.priority!=="high"&&!c(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(y.length>0){let h=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
354
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],A=C.category?` [${C.category}]`:"",D=C.summary||"";console.log(` ${p+1}. ${v}${A} \u2014 ${D}`)}y.length>5&&console.log(` ... +${y.length-5} more`),console.log()}let g=Object.entries(t).filter(([h,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(h)&&!(p.name&&n.has(p.name))).sort((h,p)=>{let v={high:0,medium:1,low:2}[h[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return v!==C?v-C:(p[1].connectionDate||"").localeCompare(h[1].connectionDate||"")});if(g.length>0){let h=g.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${g.length}):
355
- `);for(let p=0;p<h.length;p++){let[,v]=h[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",A=v.connectionDate?Ai(v.connectionDate):"",D=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${D}${A?` (${A})`:""}`)}g.length>10&&console.log(` ... +${g.length-10} more`),console.log()}let b=s.filter(([,h])=>Ve(h));if(b.length>0){let h=b.filter(([,v])=>Ve(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Ve(v);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${h} confirmed, ${p} pending)`),h>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let w=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us").length,S=s.filter(([,h])=>h.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${r.length} unread on LinkedIn, ${f.length} unreviewed, ${w} need reply, ${g.length} new connections, ${S} ball in their court`),console.log(`
348
+ `),console.log(Yo()),console.log(""),sl(t),console.log(""),rl(t),console.log(""),ll(),console.log(""),il(),console.log(""),al(),console.log("");let s=Object.entries(e),i=s.filter(([,y])=>y.unread===!0).sort((y,p)=>(p[1].lastMessageTime||"").localeCompare(y[1].lastMessageTime||""));if(i.length>0){let y=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
349
+ `);for(let p=0;p<y.length;p++){let[v,C]=y[p],_=C.category?` [${C.category}]`:"",R=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${v}${_}${R?` \u2014 ${R}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let r=new Date().toISOString().slice(0,10),a=s.filter(([,y])=>y.followUpNote),l=a.filter(([,y])=>!y.followUpDate||y.followUpDate<=r),c=a.filter(([,y])=>y.followUpDate&&y.followUpDate>r);if(a.length>0){console.log(` FOLLOW-UPS (${l.length} due, ${c.length} scheduled):
350
+ `);for(let[y,p]of l){let v=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${y}${v} \u2014 ${p.followUpNote}`)}for(let[y,p]of c.slice(0,5))console.log(` \u{1F4C5} ${y} [${p.followUpDate}] \u2014 ${p.followUpNote}`);c.length>5&&console.log(` ... +${c.length-5} more scheduled`),console.log()}let u=y=>y.actionNeeded&&y.actionNeeded!=="none"&&(!y.reviewedAtPreview||ze(y.lastMessagePreview)!==ze(y.reviewedAtPreview)),d=s.filter(([,y])=>u(y)).sort((y,p)=>(p[1].lastSynced||"").localeCompare(y[1].lastSynced||""));if(d.length>0){let y=d.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${d.length}):
351
+ `);for(let p=0;p<y.length;p++){let[v,C]=y[p],_=C.priority||C.suggestedPriority||"",R=C.category?` [${C.category}]`:"",E=C.summary||"";console.log(` ${p+1}. ${_?`[${_}] `:""}${v}${R} \u2014 ${E}`)}d.length>20&&console.log(` ... +${d.length-20} more`),console.log()}let f=s.filter(([,y])=>y.actionNeeded==="schedule_call").sort((y,p)=>{let v={high:0,medium:1,low:2}[y[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return v-C});if(f.length>0){let y=f.slice(0,5);console.log(` CALLS TO SCHEDULE (${f.length}):
352
+ `);for(let p=0;p<y.length;p++){let[v,C]=y[p],_=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${_}`)}f.length>5&&console.log(` ... +${f.length-5} more`),console.log()}let m=s.filter(([,y])=>y.conversationStatus==="unanswered_by_us"&&y.actionNeeded!=="schedule_call"&&(y.suggestedPriority==="high"||y.priority==="high")&&!u(y)).sort((y,p)=>(p[1].lastSynced||"").localeCompare(y[1].lastSynced||""));if(m.length>0){let y=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
353
+ `);for(let p=0;p<y.length;p++){let[v,C]=y[p],_=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${R}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let h=s.filter(([,y])=>y.conversationStatus==="unanswered_by_us"&&y.actionNeeded!=="schedule_call"&&y.suggestedPriority==="medium"&&y.priority!=="high"&&!u(y)).sort((y,p)=>(p[1].lastSynced||"").localeCompare(y[1].lastSynced||""));if(h.length>0){let y=h.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${h.length}):
354
+ `);for(let p=0;p<y.length;p++){let[v,C]=y[p],_=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${R}`)}h.length>5&&console.log(` ... +${h.length-5} more`),console.log()}let g=Object.entries(t).filter(([y,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(y)&&!(p.name&&n.has(p.name))).sort((y,p)=>{let v={high:0,medium:1,low:2}[y[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return v!==C?v-C:(p[1].connectionDate||"").localeCompare(y[1].connectionDate||"")});if(g.length>0){let y=g.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${g.length}):
355
+ `);for(let p=0;p<y.length;p++){let[,v]=y[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",_=v.connectionDate?ul(v.connectionDate):"",R=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${R}${_?` (${_})`:""}`)}g.length>10&&console.log(` ... +${g.length-10} more`),console.log()}let b=s.filter(([,y])=>Ze(y));if(b.length>0){let y=b.filter(([,v])=>Ze(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Ze(v);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${y} confirmed, ${p} pending)`),y>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let w=s.filter(([,y])=>y.conversationStatus==="unanswered_by_us").length,S=s.filter(([,y])=>y.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${d.length} unreviewed, ${w} need reply, ${g.length} new connections, ${S} ball in their court`),console.log(`
356
356
  \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
357
- `)}function Ai(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=tt();dn(e,null,null)}async function Ri(){if(console.log(`
357
+ `)}function ul(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 fl(){let e=lt();In(e,null,null)}async function dl(){if(console.log(`
358
358
  LinkedIn Sync-All
359
- `),Fo){_i();return}if(jo){let a=St("sync-all","report");Ti(),He(a,"success");return}if(Lo){let a=St("sync-all","enrich");try{Si(),He(a,"success")}catch(l){throw He(a,"error",null,l.message),l}return}let e=Po?"backfill":ln?"full":"incremental",t=St("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: ${ft}`);let o=tt(),s=await so(),r={browser:s.browser,page:s.page};try{await Nt(r.page);let a=null,l=[];if(Po)l=await vi(r,o);else{let i=0;for(;;)try{a=await hi(r.page,o);break}catch(u){if(!De(u))throw u;if(i++,i>=an)throw new Error(`Phase 1 failed ${an} times on CDP death \u2014 giving up. Last: ${u.message}`);console.log(`
360
- \u26A0 Phase 1 CDP dead (attempt ${i}/${an}). Recovering and restarting Phase 1...`),await Ct(r,`Phase 1 attempt ${i}`)}let d=new Set;l=await yi(r,a.toReRead,o,d),n.scanned=a.totalCards||0,n.toReRead=a.toReRead?.size||0;let c=new Set(l.map(u=>u.name)),f=0;for(let[u,{card:m}]of a.toReRead){if(c.has(u)||d.has(u))continue;let y=o[u];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||pe(o))}n.threadsRead=l.length,n.newMessages=l.reduce((i,d)=>i+(d.newMessages||0),0);try{let i=await wi(r,o,l);i&&(n.autoEnriched=i.enriched,i.authWall&&(n.autoEnrichAuthWall=!0))}catch(i){console.log(`
361
- \u26A0 Auto-enrich phase crashed: ${i.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
362
- `)}l.length>0&&bi(o,l),dn(o,a,l,{unreadCards:a?.unreadCards,readUnread:un}),Ie.pageRecoveries>0&&console.log(`
363
- CDP page recoveries this run: ${Ie.pageRecoveries}`),W||Mt(),He(t,"success",n)}catch(a){console.error(`
364
- Error:`,a.message),cn&&console.error(a.stack),He(t,"error",n,a.message)}finally{if(!W&&!jo&&!Lo&&!Fo)try{Mt()}catch{}await r.browser.close()}}Ri();
359
+ `),ws){cl();return}if(gs){let r=jt("sync-all","report");fl(),Ke(r,"success");return}if(ys){let r=jt("sync-all","enrich");try{nl(),Ke(r,"success")}catch(a){throw Ke(r,"error",null,a.message),a}return}let e=hs?"backfill":Tn?"full":"incremental",t=jt("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: ${kt}`);let o=lt(),s=await Ro(),i={browser:s.browser,page:s.page};try{await nn(i.page);let r=null,a=[];if(hs)a=await ol(i,o);else{let l=0;for(;;)try{r=await Zi(i.page,o);break}catch(f){if(!je(f))throw f;if(l++,l>=_n)throw new Error(`Phase 1 failed ${_n} times on CDP death \u2014 giving up. Last: ${f.message}`);console.log(`
360
+ \u26A0 Phase 1 CDP dead (attempt ${l}/${_n}). Recovering and restarting Phase 1...`),await Ut(i,`Phase 1 attempt ${l}`)}let c=new Set;a=await Xi(i,r.toReRead,o,c),n.scanned=r.totalCards||0,n.toReRead=r.toReRead?.size||0;let u=new Set(a.map(f=>f.name)),d=0;for(let[f,{card:m}]of r.toReRead){if(u.has(f)||c.has(f))continue;let h=o[f];h&&(h.lastMessageBy=m.lastMessageBy,h.lastMessageTime=m.lastMessageTime||h.lastMessageTime,h.unread=m.unread,d++)}d>0&&(console.log(` Pending re-read: ${d} threads (raise --max or re-run to drain).`),W||ye(o))}n.threadsRead=a.length,n.newMessages=a.reduce((l,c)=>l+(c.newMessages||0),0);try{let l=await el(i,o,a);l&&(n.autoEnriched=l.enriched,l.authWall&&(n.autoEnrichAuthWall=!0))}catch(l){console.log(`
361
+ \u26A0 Auto-enrich phase crashed: ${l.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
362
+ `)}a.length>0&&tl(o,a),In(o,r,a,{unreadCards:r?.unreadCards,readUnread:Dn}),Pe.pageRecoveries>0&&console.log(`
363
+ CDP page recoveries this run: ${Pe.pageRecoveries}`),W||zt(),Ke(t,"success",n)}catch(r){console.error(`
364
+ Error:`,r.message),Rn&&console.error(r.stack),Ke(t,"error",n,r.message)}finally{if(!W&&!gs&&!ys&&!ws)try{zt()}catch{}await i.browser.close()}}dl();