ilml-plugin-linkedin 1.17.2 → 1.18.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/CHANGELOG.md +8 -0
- package/README.md +14 -1
- package/dist/connect.mjs +73 -73
- package/dist/enrichProfile.mjs +15 -15
- package/dist/enrichProfiles.mjs +47 -49
- package/dist/funnelRunner.mjs +50 -52
- package/dist/messageBot.mjs +66 -68
- package/dist/readPost.mjs +10 -10
- package/dist/run.mjs +62 -62
- package/dist/scout.mjs +34 -36
- package/dist/src/saveLoginState.mjs +4 -3
- package/dist/syncAll.mjs +77 -79
- package/dist/syncConnections.mjs +38 -40
- package/dist/verifyAbout.mjs +18 -20
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +44 -46
- package/dist/visit.mjs +48 -50
- package/ilml-plugin.json +2 -2
- package/package.json +1 -1
package/dist/connect.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Xn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{for(var n in t)Xn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Zn}from"@ilivemylife/graph-sdk";var eo,to,me,no,oo,Xe=se(async()=>{eo=await Zn();for(let[e,t]of Object.entries(eo))process.env[e]===void 0&&(process.env[e]=t);to=process.env.LINKEDIN_NAME,me=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),no=Object.freeze(new Set([me.DRAFT,me.CONFIRMED,me.NEEDS_REVIEW])),oo=Object.freeze(new Set([me.DRAFT,me.CONFIRMED,me.REJECTED,me.NEEDS_REVIEW]))});import"dotenv/config";import*as M from"fs";import*as q from"path";import{fileURLToPath as ro}from"url";function Qt(){_e=null,ao=null,ae=null,lo=null,co=null,uo=null}function et(){M.existsSync(le)||M.mkdirSync(le,{recursive:!0})}function qe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";M.writeFileSync(o,n);for(let r=0;r<3;r++)try{M.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function Ue(e,t){if(!M.existsSync(e))return null;try{let n=JSON.parse(M.readFileSync(e,"utf-8"));try{M.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${q.resolve(e)}`);let o=e+".backup";if(M.existsSync(o))try{let r=JSON.parse(M.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{M.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{M.copyFileSync(e,e+".corrupted")}catch{}return null}}function Be(){return new Date().toISOString().split("T")[0]}function U(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Ht(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Pe(e,t,n=null){if(!t||e[t])return t;let o=U(t);if(!o)return t;let r=null;for(let[i,a]of Object.entries(e)){if(U(a.profileUrl||i)===o)return i;!r&&Array.isArray(a.aliases)&&a.aliases.includes(o)&&(r=i)}if(r){let i=Ht(n),a=Ht(e[r].name);if(i&&a&&i===a)return r}return t}function mo(){M.existsSync(yt)||M.mkdirSync(yt,{recursive:!0})}function zt(e){let t=U(e);return t?q.join(yt,`${t}.json`):null}function ho(e){let t=zt(e);return t?Ue(t,`profile-history/${U(e)}.json`)||[]:[]}function go(e,t){let n=zt(e);if(!n)return;mo();let o=ho(e);o.unshift(t);try{qe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${U(e)}: ${r.message}`)}}function Wt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Gt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function yo(e,t){if(!e)return[];let n=[];for(let o of po){let r=e[o],i=t[o];Wt(r)||Wt(i)||Gt(r)!==Gt(i)&&n.push(o)}return n}function wo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return _e||(et(),_e=Ue(gt,"people.json")||{},_e)}function tt(e){et(),_e=e;try{qe(gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${q.resolve(gt)}`)}}function Ze(e,t={}){if(!e)return null;let n=Y(),o=Be(),r=new Date().toISOString(),i=Pe(n,e,t.name),a=n[i];if(a){let u=yo(a,t);u.length>0&&(go(i,{capturedAt:r,previousLastUpdated:a.lastUpdated||null,changedFields:u,snapshot:wo(a)}),a.lastSnapshotAt=r),a.seenCount=(a.seenCount||1)+1,a.lastSeen=o,a.lastUpdated=r,t.source&&!a.sources?.includes(t.source)&&(a.sources=a.sources||[],a.sources.push(t.source));for(let s of fo)if(t[s]!=null){if(Array.isArray(t[s])&&t[s].length===0&&Array.isArray(a[s])&&a[s].length>0)continue;a[s]=t[s]}Array.isArray(t.availableSections)&&(a.lastFullVisitAt=r)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return tt(n),n[i]}function Xt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Be(),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(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),tt(n))}function Zt(e){return e&&Y()[e]?.connectionStatus||null}function nt(e,t,n={}){if(!e)return;if(n.profileInfo)Ze(e,n.profileInfo);else{let u=Y(),s=Pe(u,e,n.profileInfo?.name);u[s]||Ze(e,{})}let o=Y(),r=Pe(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let a=Be();i.connectionStatus=t,t==="connected"?i.connectionDate=a:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=a)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),tt(o)}function ot(e,t,n={}){if(n.dryRun||!e||!t)return;let o=U(t);if(!o)return;let r=Y(),i=Pe(r,e),a=r[i];if(!a)return;let u=U(a.profileUrl||i);o!==u&&(Array.isArray(a.aliases)||(a.aliases=[]),a.aliases.includes(o)||(a.aliases.push(o),a.lastUpdated=new Date().toISOString(),tt(r)))}function en(){return ae||(et(),ae=Ue(Yt,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function bo(e){et(),ae=e;try{qe(Yt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function tn(e,t="unknown"){let n=en(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),bo(n)}function nn(){let e=en(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Je(){let e=nn(),t=Be(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Me,i=o>=Le,a=!r&&!i,u={allowed:a,daily:{sent:n,max:Me},weekly:{sent:o,max:Le}};return a||(u.reason=r?`Daily limit reached (${n}/${Me})`:`Weekly limit reached (${o}/${Le})`),u}function ke(){let e=nn(),t=Be(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Me,remaining:Me-n},weekly:{sent:o,max:Le,remaining:Le-o}}}var so,io,le,gt,Ss,Yt,ks,vs,$s,yt,Kt,Me,Le,_e,ao,ae,lo,co,uo,fo,po,Ie=se(async()=>{await Xe();so=ro(import.meta.url),io=q.dirname(q.dirname(so)),le=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(io,"collected-profiles"),gt=q.join(le,"people.json"),Ss=q.join(le,"jobs.json"),Yt=q.join(le,"quota.json"),ks=q.join(le,"conversations.json"),vs=q.join(le,"sync-state.json"),$s=q.join(le,"application-questions.json"),yt=q.join(le,"profile-history"),Kt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Me=Kt(process.env.CONNECT_MAX_DAILY,20),Le=Kt(process.env.CONNECT_MAX_WEEKLY,100),_e=null,ao=null,ae=null,lo=null,co=null,uo=null;fo=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],po=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var kn={};ie(kn,{cookiesExist:()=>Cr,getCookiesPath:()=>lt,loadCookies:()=>$r,saveCookies:()=>vr});import De from"fs";import Sn from"path";function lt(){let e=process.env.ILML_SCOPE_DIR;return e?Sn.join(e,"plugins-state","linkedin","cookies.json"):Sr}function kr(){let e=lt(),t=Sn.dirname(e);return t&&t!=="."&&!De.existsSync(t)&&De.mkdirSync(t,{recursive:!0}),e}function vr(e){let t=kr();return De.writeFileSync(t,JSON.stringify(e)),t}function $r(){let e=lt();if(!De.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=De.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 Cr(){return De.existsSync(lt())}var Sr,vn=se(()=>{Sr="cookies.json"});var $n={};ie($n,{cleanSearchName:()=>Dr,delayed:()=>b,dismissPremiumOverlay:()=>be,ensureInboxPage:()=>_r,parseLinkedInTime:()=>Er,safeParseInt:()=>Ir,stripDesignations:()=>Tr,utilityFunction:()=>xr});function xr(){console.log("Utility function called...")}function We(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),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function Er(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 u=We(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=Ar[o[1].toLowerCase()],s=We(o[2]||""),l=new Date(t),d=l.getDay()-u;return d<=0&&(d+=7),l.setDate(l.getDate()-d),s?l.setHours(s.hours,s.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=Dt[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),l=parseInt(r[3],10),c=We(r[4]||"");return new Date(l,u,s,c?.hours||0,c?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=Dt[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),l=We(i[3]||""),c=t.getFullYear(),d=new Date(c,u,s,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let u=Dt[a[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(a[2],10),l=We(a[3]||""),c=t.getFullYear(),d=new Date(c,u,s,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function _r(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 b(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}function Ir(e){return parseInt(e,10)||0}async function be(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),a=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||a||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let l=o.querySelectorAll("button");for(let c of l){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function Dr(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 Tr(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 Dt,Ar,ct=se(()=>{Dt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Ar={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var Cn={};ie(Cn,{extractCertificationsFromDetails:()=>Fr,extractEducationFromDetails:()=>jr,extractExperienceFromDetails:()=>Rr,extractFeaturedFromDetails:()=>Nr,extractRecommendationsFromDetails:()=>Mr,extractSkillsFromDetails:()=>Or});async function Rr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await b(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 b(900);await b(1e3);let r=0;for(;r<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});)r++,await b(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.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,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=a(i);if(!u)return[];let s=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function l(c){let d=c[0]||null,f=null,p=null;if(c[1]){let C=c[1].split("\xB7").map(O=>O.trim());f=C[0]||null,C[1]&&(p=C[1])}let h=c.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),m=null,k=null;if(h>=0){let C=c[h].split("\xB7").map(O=>O.trim());m=C[0]||null,C[1]&&(k=C[1])}let g=null,v=-1;if(h>=0&&c[h+1]){let C=c[h+1],O=/^[>*\-•]|^>/.test(C),W=/https?:\/\//.test(C),B=/\d{4}/.test(C),I=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!O&&!W&&!B&&C.length<100&&I&&(g=C,v=h+1)}let A=null,w=-1,$=c[c.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){w=c.length-1;let C=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(A={listed:C[1].split(",").map(O=>O.trim()),additional:parseInt(C[2],10)})}let y=new Set([0,1,h,v,w].filter(C=>C>=0)),E=c.filter((C,O)=>!y.has(O)),N=E.length>0?E.join(`
|
|
1
|
+
var ao=Object.defineProperty;var oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{for(var n in t)ao(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as lo}from"@ilivemylife/graph-sdk";var co,uo,me,fo,po,Ze=oe(async()=>{co=await lo();for(let[e,t]of Object.entries(co))process.env[e]===void 0&&(process.env[e]=t);uo=process.env.LINKEDIN_NAME,me=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),fo=Object.freeze(new Set([me.DRAFT,me.CONFIRMED,me.NEEDS_REVIEW])),po=Object.freeze(new Set([me.DRAFT,me.CONFIRMED,me.REJECTED,me.NEEDS_REVIEW]))});import"dotenv/config";import*as P from"fs";import*as U from"path";import{fileURLToPath as mo}from"url";function zt(){De=null,yo=null,le=null,wo=null,bo=null,So=null}function tt(){P.existsSync(ce)||P.mkdirSync(ce,{recursive:!0})}function Ue(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";P.writeFileSync(o,n);for(let r=0;r<3;r++)try{P.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw s}}function Be(e,t){if(!P.existsSync(e))return null;try{let n=JSON.parse(P.readFileSync(e,"utf-8"));try{P.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${U.resolve(e)}`);let o=e+".backup";if(P.existsSync(o))try{let r=JSON.parse(P.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{P.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{P.copyFileSync(e,e+".corrupted")}catch{}return null}}function Je(){return new Date().toISOString().split("T")[0]}function B(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Wt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function qe(e,t,n=null){if(!t||e[t])return t;let o=B(t);if(!o)return t;let r=null;for(let[s,a]of Object.entries(e)){if(B(a.profileUrl||s)===o)return s;!r&&Array.isArray(a.aliases)&&a.aliases.includes(o)&&(r=s)}if(r){let s=Wt(n),a=Wt(e[r].name);if(s&&a&&s===a)return r}return t}function $o(){P.existsSync(yt)||P.mkdirSync(yt,{recursive:!0})}function Xt(e){let t=B(e);return t?U.join(yt,`${t}.json`):null}function Co(e){let t=Xt(e);return t?Be(t,`profile-history/${B(e)}.json`)||[]:[]}function xo(e,t){let n=Xt(e);if(!n)return;$o();let o=Co(e);o.unshift(t);try{Ue(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${B(e)}: ${r.message}`)}}function Yt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Gt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Ao(e,t){if(!e)return[];let n=[];for(let o of vo){let r=e[o],s=t[o];Yt(r)||Yt(s)||Gt(r)!==Gt(s)&&n.push(o)}return n}function Eo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return De||(tt(),De=Be(gt,"people.json")||{},De)}function nt(e){tt(),De=e;try{Ue(gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${U.resolve(gt)}`)}}function et(e,t={}){if(!e)return null;let n=Y(),o=Je(),r=new Date().toISOString(),s=qe(n,e,t.name),a=n[s];if(a){let u=Ao(a,t);u.length>0&&(xo(s,{capturedAt:r,previousLastUpdated:a.lastUpdated||null,changedFields:u,snapshot:Eo(a)}),a.lastSnapshotAt=r),a.seenCount=(a.seenCount||1)+1,a.lastSeen=o,a.lastUpdated=r,t.source&&!a.sources?.includes(t.source)&&(a.sources=a.sources||[],a.sources.push(t.source));for(let i of ko)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=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return nt(n),n[s]}function Zt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let s={date:Je(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(s.jobId=String(t.jobId)),t.jobTitle&&(s.jobTitle=t.jobTitle),t.jobCompany&&(s.jobCompany=t.jobCompany),!o.encounters.some(u=>u.date===s.date&&u.source===s.source&&u.action===s.action&&(u.jobId||"")===(s.jobId||""))&&(o.encounters.push(s),o.lastUpdated=new Date().toISOString(),nt(n))}function en(e){return e&&Y()[e]?.connectionStatus||null}function ot(e,t,n={}){if(!e)return;if(n.profileInfo)et(e,n.profileInfo);else{let u=Y(),i=qe(u,e,n.profileInfo?.name);u[i]||et(e,{})}let o=Y(),r=qe(o,e,n.profileInfo?.name),s=o[r];if(!s)return;let a=Je();s.connectionStatus=t,t==="connected"?s.connectionDate=a:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(s.requestedConnectionAt||(s.requestedConnectionAt=a)),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),nt(o)}function rt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=B(t);if(!o)return;let r=Y(),s=qe(r,e),a=r[s];if(!a)return;let u=B(a.profileUrl||s);o!==u&&(Array.isArray(a.aliases)||(a.aliases=[]),a.aliases.includes(o)||(a.aliases.push(o),a.lastUpdated=new Date().toISOString(),nt(r)))}function tn(){return le||(tt(),le=Be(Kt,"quota.json"),(!le||!le.connections)&&(le={connections:[]}),le)}function _o(e){tt(),le=e;try{Ue(Kt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function nn(e,t="unknown"){let n=tn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),_o(n)}function on(){let e=tn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ve(){let e=on(),t=Je(),n=e.filter(i=>i.date===t).length,o=e.length,r=n>=Le,s=o>=Pe,a=!r&&!s,u={allowed:a,daily:{sent:n,max:Le},weekly:{sent:o,max:Pe}};return a||(u.reason=r?`Daily limit reached (${n}/${Le})`:`Weekly limit reached (${o}/${Pe})`),u}function $e(){let e=on(),t=Je(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Le,remaining:Le-n},weekly:{sent:o,max:Pe,remaining:Pe-o}}}var ho,go,ce,gt,Ri,Kt,Ti,Ni,ji,yt,Qt,Le,Pe,De,yo,le,wo,bo,So,ko,vo,Re=oe(async()=>{await Ze();ho=mo(import.meta.url),go=U.dirname(U.dirname(ho)),ce=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"collected-profiles"):U.join(go,"collected-profiles"),gt=U.join(ce,"people.json"),Ri=U.join(ce,"jobs.json"),Kt=U.join(ce,"quota.json"),Ti=U.join(ce,"conversations.json"),Ni=U.join(ce,"sync-state.json"),ji=U.join(ce,"application-questions.json"),yt=U.join(ce,"profile-history"),Qt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Le=Qt(process.env.CONNECT_MAX_DAILY,20),Pe=Qt(process.env.CONNECT_MAX_WEEKLY,100),De=null,yo=null,le=null,wo=null,bo=null,So=null;ko=["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"],vo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});import se from"fs";import be from"path";function kn(){let e=process.env.ILML_SCOPE_DIR;return e?be.join(e,"plugins-state","linkedin","cookies.json"):Ir}function vn(){let e=kn();if(!se.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=se.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 $n(){return se.existsSync(kn())}function Dr(){let e=process.env.ILML_SCOPE_DIR;return e?be.join(e,"plugins-state","linkedin"):"."}function Cn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Rr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Cn(t[1]):"default"}function xn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return se.existsSync(t)||se.mkdirSync(t,{recursive:!0}),be.resolve(t);let n=Cn(e||Rr()),o=be.join(Dr(),"chrome-profile",n);return se.existsSync(o)||se.mkdirSync(o,{recursive:!0}),be.resolve(o)}function En(e){return!se.existsSync(be.join(e,An))}function Dt(e){try{se.writeFileSync(be.join(e,An),new Date().toISOString())}catch{}}function _n(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{se.rmSync(be.join(e,n),{force:!0}),t++}catch{}return t}var Ir,An,In=oe(()=>{Ir="cookies.json";An=".ilml-seeded"});var Dn={};ae(Dn,{launchWithProfile:()=>Nr,markProfileEstablished:()=>Or,seedCookiesIfNeeded:()=>jr});async function Nr(e,t={}){let n=xn(),o={...Tr,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{_n(n);try{r=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:r,profileDir:n,needsSeed:En(n)}}async function jr(e,t){if(!t||!t.needsSeed)return!1;if(!$n())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(...vn()),Dt(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}function Or(e){Dt(e)}var Tr,Rn=oe(()=>{In();Tr={headless:!1,defaultViewport:null,protocolTimeout:3e5}});var Tn={};ae(Tn,{cleanSearchName:()=>Ur,delayed:()=>b,dismissPremiumOverlay:()=>Se,ensureInboxPage:()=>Pr,parseLinkedInTime:()=>Lr,safeParseInt:()=>qr,stripDesignations:()=>Br,utilityFunction:()=>Mr});function Mr(){console.log("Utility function called...")}function Ye(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),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function Lr(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 u=Ye(n),i=new Date(t);return u?i.setHours(u.hours,u.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 u=Fr[o[1].toLowerCase()],i=Ye(o[2]||""),l=new Date(t),d=l.getDay()-u;return d<=0&&(d+=7),l.setDate(l.getDate()-d),i?l.setHours(i.hours,i.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=Rt[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let i=parseInt(r[2],10),l=parseInt(r[3],10),c=Ye(r[4]||"");return new Date(l,u,i,c?.hours||0,c?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let u=Rt[s[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let i=parseInt(s[2],10),l=Ye(s[3]||""),c=t.getFullYear(),d=new Date(c,u,i,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let a=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(a){let u=Rt[a[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let i=parseInt(a[2],10),l=Ye(a[3]||""),c=t.getFullYear(),d=new Date(c,u,i,l?.hours||0,l?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function b(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Pr(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 b(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}function qr(e){return parseInt(e,10)||0}async function Se(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),a=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||a||u){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:r.substring(0,80)};let l=o.querySelectorAll("button");for(let c of l){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function Ur(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 Br(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 Rt,Fr,ct=oe(()=>{Rt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Fr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var Nn={};ae(Nn,{extractCertificationsFromDetails:()=>Yr,extractEducationFromDetails:()=>Hr,extractExperienceFromDetails:()=>Jr,extractFeaturedFromDetails:()=>Vr,extractRecommendationsFromDetails:()=>Gr,extractSkillsFromDetails:()=>Wr});async function Jr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await b(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 s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(900);await b(1e3);let r=0;for(;r<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});)r++,await b(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function a(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.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,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=a(s);if(!u)return[];let i=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function l(c){let d=c[0]||null,f=null,p=null;if(c[1]){let C=c[1].split("\xB7").map(F=>F.trim());f=C[0]||null,C[1]&&(p=C[1])}let h=c.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),m=null,k=null;if(h>=0){let C=c[h].split("\xB7").map(F=>F.trim());m=C[0]||null,C[1]&&(k=C[1])}let g=null,v=-1;if(h>=0&&c[h+1]){let C=c[h+1],F=/^[>*\-•]|^>/.test(C),H=/https?:\/\//.test(C),J=/\d{4}/.test(C),M=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!F&&!H&&!J&&C.length<100&&M&&(g=C,v=h+1)}let E=null,y=-1,$=c[c.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){y=c.length-1;let C=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(E={listed:C[1].split(",").map(F=>F.trim()),additional:parseInt(C[2],10)})}let x=new Set([0,1,h,v,y].filter(C=>C>=0)),w=c.filter((C,F)=>!x.has(F)),R=w.length>0?w.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:d,company:f,employmentType:p,dates:m,duration:k,location:g,description:
|
|
4
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(f)}).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 Ge(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let a=0;a<4;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(700);await b(800);let
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:d,company:f,employmentType:p,dates:m,duration:k,location:g,description:R,skills:E,_raw:c}}return i.map(c=>{let f=(c.innerText||"").trim().split(`
|
|
4
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return l(f)}).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 Ge(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let a=0;a<4;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(700);await b(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)s++,await b(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await b(600)}async function Qe(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function Vr(e,t){return Qe(t,"featured","extractFeaturedFromDetails",async()=>(await Ge(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${Ke}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var Xn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(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
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function Hr(e,t){return Qe(t,"education","extractEducationFromDetails",async()=>(await Ge(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${Ke}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var Xn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(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
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function Wr(e,t){return Qe(t,"skills","extractSkillsFromDetails",async()=>(await Ge(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${Ke}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var Xn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function Yr(e,t){return Qe(t,"certifications","extractCertificationsFromDetails",async()=>(await Ge(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${Ke}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var Xn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Gr(e,t){return Qe(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Ge(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${Ke}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var Xn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(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
|
|
175
|
+
})()`)))}var Ke,jn=oe(()=>{ct();Ke=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,89 +235,89 @@ 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 _n={};ie(_n,{clickConnectButton:()=>Rt,default:()=>qr,detectConnectionStatus:()=>Ee,findConnectButton:()=>Qe,runFunnel:()=>En,sendConnectionRequest:()=>Nt,shouldExcludeLocation:()=>ut,viewProfile:()=>Tt});async function An(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function ut(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Tt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:a=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await be(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await An(e,t));let c=0;for(let w=0;w<2;w++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let E=1;E<=6;E++)await e.evaluate(N=>window.scrollTo(0,N),$*E/6),await b(900);let y=await e.evaluate(()=>document.body.scrollHeight);if(y===c)break;c=y}await b(800);let d=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(d=w.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),$=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),y=x=>{let _=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},E={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:[]},N=document.querySelector("main");if(!N)return E;let C=[...Array.from(N.querySelectorAll("h1")),...Array.from(N.querySelectorAll("h2"))],O=Array.from(N.querySelectorAll("h2")),W=C.find(x=>{let _=x.textContent&&x.textContent.trim(),D=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!w.has(D)&&!$.has(D)}),B=W?W.textContent.trim():null,I=W?W.parentElement:null;for(;I&&I!==N&&!Array.from(I.children).filter(_=>_.tagName==="P").some(_=>{let D=_.textContent&&_.textContent.trim();return D&&D.length>5&&!y(D)});)I=I.parentElement;let J=null,T=null,G=null,fe=null;if(I&&I!==N){let x=Array.from(I.children).filter(D=>D.tagName==="P").filter(D=>{let pe=D.textContent&&D.textContent.trim();return pe&&pe.length>5&&!y(pe)});if(x[0]&&(J=x[0].textContent.trim()),x[1]){let D=x[1].textContent.trim().split(/\s*[·•]\s*/);T=D[0]||null,D.length>1&&(G=D.slice(1).join(" \xB7 "))}let _=Array.from(I.children).filter(D=>D.tagName==="DIV");for(let D=_.length-1;D>=0;D--){let pe=_[D].textContent&&_[D].textContent.trim();if(pe&&!(B&&pe.startsWith(B))&&(fe=pe.split(/[·•]/)[0].trim(),fe))break}}let V=null;if(I){let x=I.querySelectorAll("p, span, div");for(let _ of x){let D=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if(D==="1st"||D==="2nd"||D==="3rd"){V=D;break}}}let j=!!N.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=L&&L.src||null,F=N.textContent||"",ne=null,Mt=F.match(/(\d+\+?)\s+connections\b/i);Mt&&(ne=Mt[1]+" connections");let ze=null,Lt=F.match(/(\d+)\s+mutual connection/i),Pt=F.match(/and\s+(\d+)\s+other mutual/i),Gn=F.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Lt?ze=parseInt(Lt[1],10):Pt?ze=2+parseInt(Pt[1],10):Gn&&(ze=2);let qt=null,Ut=null,Bt=O.find(x=>x.textContent&&x.textContent.trim()==="About");if(Bt){let x=Bt.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let _=(x.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let D=_.match(/Top skills\s*(.+?)$/i);if(D){let ht=D[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(zn=>zn.trim()).filter(Boolean);ht.length>0&&ht.length<10&&(Ut=ht)}_=_.split(/\n?…\s*more/i)[0].trim(),_=_.split(/\n?\.\.\.\s*more/i)[0].trim(),_=_.split(/\bTop skills\b/i)[0].trim(),_=_.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),qt=_||null}}let Jt=null,Vt=O.find(x=>x.textContent&&x.textContent.trim()==="Activity");if(Vt){let x=Vt.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let _=(x.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(Jt=parseInt(_[1].replace(/,/g,""),10))}}let Yn=[...new Set(O.map(x=>(x.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(x=>x&&x.length>1&&x.length<60&&x!==B).filter(x=>w.has(x)))],Fe=document.body.textContent||"",Kn=/#OpenToWork\b/i.test(Fe)||/\bOpen to work\b/.test(Fe),Qn=/#Hiring\b/i.test(Fe)||/\bI'?m hiring\b/i.test(Fe)||/\bWe are hiring\b/i.test(Fe);return{name:B,title:J,location:fe,currentCompany:T,currentSchool:G,connectionDegree:V,hasVerifiedBadge:j,photoUrl:H,connectionsLevel:ne,mutualConnectionsCount:ze,followers:Jt,openToWork:Kn,hiring:Qn,about:qt,topSkills:Ut,availableSections:Yn}});console.log(`Viewed: ${f.name} - ${f.title}`);let p=null,h=null,m=null,k=null,g=null,v=null;if(o||r||i||a||u||s){let w=await Promise.resolve().then(()=>(xn(),Cn));o&&(p=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(h=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),i&&(m=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${m.length} entries`)),a&&(k=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${k.length} entries`)),u&&(g=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${g.length} entries`)),s&&(v=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...p!==null&&{experience:p},...h!==null&&{featured:h},...m!==null&&{education:m},...k!==null&&{skillsFull:k},...g!==null&&{recommendations:g},...v!==null&&{certifications:v}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ee(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=l=>l&&!l.closest(n),r=l=>Array.from(document.querySelectorAll(l)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(l=>l.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!u};return i.length>0?{status:"pending",debug:s}:a&&!u?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Qe(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let l=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(l&&(s=l.textContent?.trim(),s&&!s.includes("notification")))return s;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(p))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f))return h}return null},n);let l=t?.asElement?.()||null;if(l||await t?.dispose?.().catch(()=>{}),l)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:l,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let l=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let k=m.getAttribute("aria-label")||"";return(k.toLowerCase().includes("invite")||k.toLowerCase().includes("connect"))&&f.test(k)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);l.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(l)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},s);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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 s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(l)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let l=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),k=m.includes("invite"),g=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:k,matchesName:g,ariaLabel:m}},s,r);if(!l.isMuted&&!l.isStickyHeader&&!l.inRecommendations){if(l.hasInvite&&!l.matchesName){console.log(` Skipping secondary button: wrong person (${l.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let a=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let l=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(l.isVisible&&!l.isInStickyHeader){a=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==a&&await s.dispose().catch(()=>{});if(!a&&u.length>0&&(a=u[u.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 s=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});a=s?.asElement?.()||null,a||await s?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await b(500),await e.evaluate(c=>c.click(),a),await b(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let l=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(l||(l=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),l||(l=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),l||(l=await e.$('div[role="button"][aria-label*="Invite"]')),l||(l=await e.$('div[role="button"][aria-label*="connect"]')),!l){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});l=c?.asElement?.()||null,l||await c?.dispose?.().catch(()=>{})}if(!l){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(l)return console.log(" Found: More dropdown"),{button:l,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(l)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Rt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();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(r){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 b(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 b(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await b(3e3)):(await e.evaluate(c=>c.click(),t),await b(3e3));let u=e.url();if(u.includes("/premium/")||u.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),l=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function Lr(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 b(1500);let n=await Qe(e);if(n){await e.evaluate(r=>r.click(),n),await b(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Nt(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Je();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let a=await Pr(e,t,n);return a.connectionSent&&!i&&tn(t,o),a}async function Pr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:a=!0,excludeLocations:u=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
-
--- Connecting: ${l} ---`),u.length>0){let g=Y()[t]?.location;if(ut(g,u))return console.log(` \u26A0 Excluded location (stored): ${g}`),s.reason="excluded_location",s.profileInfo={location:g},s}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await be(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await An(e,t),await b(2e3)),s.profileInfo=await e.evaluate(()=>{let g=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),v=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},A={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return A;let $=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],y=Array.from(w.querySelectorAll("h2")),E=$.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!g.has(L)&&L!=="0 notifications"}),N=E?E.textContent.trim():null,C=E?E.parentElement:null;for(;C&&C!==w&&!Array.from(C.children).filter(H=>H.tagName==="P").some(H=>{let F=H.textContent&&H.textContent.trim();return F&&F.length>5&&!v(F)});)C=C.parentElement;let O=null,W=null,B=null;if(C&&C!==w){let j=Array.from(C.children),L=j.filter(F=>F.tagName==="P").filter(F=>{let ne=F.textContent&&F.textContent.trim();return ne&&ne.length>5&&!v(ne)});L[0]&&(O=L[0].textContent.trim()),L[1]&&(W=L[1].textContent.trim());let H=j.filter(F=>F.tagName==="DIV");for(let F=H.length-1;F>=0;F--){let ne=H[F].textContent&&H[F].textContent.trim();if(ne&&!(N&&ne.startsWith(N))&&(B=ne.split(/[·•]/)[0].trim(),B))break}}let I=null;if(C){let j=C.querySelectorAll("p, span, div");for(let L of j){let H=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(H==="1st"||H==="2nd"||H==="3rd"){I=H;break}}}let J=null,T=y.find(j=>j.textContent&&j.textContent.trim()==="About");if(T){let j=T.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(J=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,J&&(J=J.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let G=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),fe=G&&G.src||null,V=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:N,title:O,location:B,about:J,company:W,connectionDegree:I,connectionsCount:null,mutualConnections:null,photoUrl:fe,hasVerifiedBadge:V}});try{let g=e.url();g&&/\/in\/[^/?#]/.test(g)&&(s.resolvedUrl=g.split("?")[0].replace(/\/+$/,""))}catch{}if(u.length>0){let g=s.profileInfo?.location,v=Y()[t]?.location,A=g||v;if(ut(A,u))return console.log(` \u26A0 Excluded location (${g?"live":"stored"}): ${A}`),s.reason="excluded_location",s;!g&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ee(e);if(s.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await be(e);let f=await Qe(e);if(!f&&(await be(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),f=await Qe(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=f.method;let p=await Rt(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let g=await Ee(e);if(g==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${g} \u2014 trying More dropdown...`),await be(e),await b(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await b(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await b(2e3);let A=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(A){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(y=>y.click(),A),await b(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),s.reason="premium_required",s;if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await b(500),s.reason="premium_required",s}catch(A){return console.log(" More dropdown failed:",A.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let g=await e.$('button[aria-label="Dismiss"]');return g&&await g.click(),await b(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),k=await e.$('button[aria-label="Send without a note"]');if(!m&&!k){let g=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let A=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!A,sendWithout:!!w}});if(g.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=v?.asElement?.()||null,m||await v.dispose().catch(()=>{})}if(g.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));k=v?.asElement?.()||null,k||await v.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await b(1500),await e.$("div.modal-upsell")){let A=await Lr(e);return s.success=A,s.connectionSent=A,s.reason=A?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let A=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",A);await v.type(w,{delay:20}),await b(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=w,s}}}else if(k){console.log(" Sending without note...");try{await k.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(m&&!o){console.log(" No message provided, sending without note...");let g=await e.$('button[aria-label="Send without a note"]');if(g){try{await g.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let g=k;if(g){try{await g.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}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 b(4e3)),await be(e),await b(500);let v=await e.$$('button[id*="profile-overflow-action"]'),A=null;for(let w of v){let $=await e.evaluate(y=>{let E=y.getBoundingClientRect();return{visible:E.width>0&&E.height>0,inSticky:!!y.closest('.sticky-header, [class*="sticky"]')}},w);if($.visible&&!$.inSticky){A=w;break}}!A&&v.length>0&&(A=v[v.length-1]);for(let w of v)w!==A&&await w.dispose().catch(()=>{});if(A)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),A),await b(500),await A.click().catch(()=>e.evaluate($=>$.click(),A)),await b(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(w){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(N=>N.click(),w),await b(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await Ee(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let E=await e.$('button[aria-label="Send without a note"]');if(E){console.log(" Modal appeared via More dropdown, sending without note...");try{await E.evaluate(N=>N.click())}catch{}return await b(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(l){console.error(` \u2717 Error: ${l.message}`),s.reason="error",s.error=l.message;let c=l.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{s.fatal=!0}return s}}async function En(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:a=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:l=[],source:c="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: ${a?"View Only":`Connect (max ${
|
|
238
|
+
`});var Fn={};ae(Fn,{clickConnectButton:()=>Nt,default:()=>zr,detectConnectionStatus:()=>Ie,findConnectButton:()=>ze,runFunnel:()=>Mn,sendConnectionRequest:()=>jt,shouldExcludeLocation:()=>ut,viewProfile:()=>Tt});async function On(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 b(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function ut(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Tt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:a=!1,extractRecommendations:u=!1,extractCertifications:i=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await Se(e)&&(console.log(" Dismissed Premium overlay"),await b(1500),await On(e,t));let c=0;for(let y=0;y<2;y++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let w=1;w<=6;w++)await e.evaluate(R=>window.scrollTo(0,R),$*w/6),await b(900);let x=await e.evaluate(()=>document.body.scrollHeight);if(x===c)break;c=x}await b(800);let d=null;try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(d=y.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),$=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),x=A=>{let I=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(I)},w={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 w;let C=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],F=Array.from(R.querySelectorAll("h2")),H=C.find(A=>{let I=A.textContent&&A.textContent.trim(),D=(I||"").replace(/\s*\(\d+\)$/,"").trim();return I&&I.length>1&&I.length<100&&!y.has(D)&&!$.has(D)}),J=H?H.textContent.trim():null,M=H?H.parentElement:null;for(;M&&M!==R&&!Array.from(M.children).filter(I=>I.tagName==="P").some(I=>{let D=I.textContent&&I.textContent.trim();return D&&D.length>5&&!x(D)});)M=M.parentElement;let j=null,K=null,T=null,W=null;if(M&&M!==R){let A=Array.from(M.children).filter(D=>D.tagName==="P").filter(D=>{let pe=D.textContent&&D.textContent.trim();return pe&&pe.length>5&&!x(pe)});if(A[0]&&(j=A[0].textContent.trim()),A[1]){let D=A[1].textContent.trim().split(/\s*[·•]\s*/);K=D[0]||null,D.length>1&&(T=D.slice(1).join(" \xB7 "))}let I=Array.from(M.children).filter(D=>D.tagName==="DIV");for(let D=I.length-1;D>=0;D--){let pe=I[D].textContent&&I[D].textContent.trim();if(pe&&!(J&&pe.startsWith(J))&&(W=pe.split(/[·•]/)[0].trim(),W))break}}let ve=null;if(M){let A=M.querySelectorAll("p, span, div");for(let I of A){let D=(I.textContent||"").trim().replace(/^[·•]\s*/,"");if(D==="1st"||D==="2nd"||D==="3rd"){ve=D;break}}}let _=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),O=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),V=O&&O.src||null,L=R.textContent||"",ne=null,Lt=L.match(/(\d+\+?)\s+connections\b/i);Lt&&(ne=Lt[1]+" connections");let Xe=null,Pt=L.match(/(\d+)\s+mutual connection/i),qt=L.match(/and\s+(\d+)\s+other mutual/i),no=L.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Pt?Xe=parseInt(Pt[1],10):qt?Xe=2+parseInt(qt[1],10):no&&(Xe=2);let Ut=null,Bt=null,Jt=F.find(A=>A.textContent&&A.textContent.trim()==="About");if(Jt){let A=Jt.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let I=(A.textContent||"").trim();I=I.replace(/^About\s*/,"").trim();let D=I.match(/Top skills\s*(.+?)$/i);if(D){let ht=D[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(so=>so.trim()).filter(Boolean);ht.length>0&&ht.length<10&&(Bt=ht)}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(),Ut=I||null}}let Vt=null,Ht=F.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(Ht){let A=Ht.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let I=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);I&&(Vt=parseInt(I[1].replace(/,/g,""),10))}}let oo=[...new Set(F.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==J).filter(A=>y.has(A)))],Fe=document.body.textContent||"",ro=/#OpenToWork\b/i.test(Fe)||/\bOpen to work\b/.test(Fe),io=/#Hiring\b/i.test(Fe)||/\bI'?m hiring\b/i.test(Fe)||/\bWe are hiring\b/i.test(Fe);return{name:J,title:j,location:W,currentCompany:K,currentSchool:T,connectionDegree:ve,hasVerifiedBadge:_,photoUrl:V,connectionsLevel:ne,mutualConnectionsCount:Xe,followers:Vt,openToWork:ro,hiring:io,about:Ut,topSkills:Bt,availableSections:oo}});console.log(`Viewed: ${f.name} - ${f.title}`);let p=null,h=null,m=null,k=null,g=null,v=null;if(o||r||s||a||u||i){let y=await Promise.resolve().then(()=>(jn(),Nn));o&&(p=await y.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(h=await y.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),s&&(m=await y.extractEducationFromDetails(e,t),console.log(` + Education: ${m.length} entries`)),a&&(k=await y.extractSkillsFromDetails(e,t),console.log(` + Skills: ${k.length} entries`)),u&&(g=await y.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${g.length} entries`)),i&&(v=await y.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...p!==null&&{experience:p},...h!==null&&{featured:h},...m!==null&&{education:m},...k!==null&&{skillsFull:k},...g!==null&&{recommendations:g},...v!==null&&{certifications:v}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await b(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ie(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=l=>l&&!l.closest(n),r=l=>Array.from(document.querySelectorAll(l)).filter(o),s=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,i={pendingCount:s.length,pendingLabels:s.map(l=>l.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!u};return s.length>0?{status:"pending",debug:i}:a&&!u?{status:"connected",debug:i}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:i}:{status:"not_connected",debug:i}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function ze(e){let t=null,n=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let l=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(l&&(i=l.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(p))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f))return h}return null},n);let l=t?.asElement?.()||null;if(l||await t?.dispose?.().catch(()=>{}),l)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:l,method:"connect_link"}}if(n){let i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let l=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let k=m.getAttribute("aria-label")||"";return(k.toLowerCase().includes("invite")||k.toLowerCase().includes("connect"))&&f.test(k)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},i);l.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(l)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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 i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(l)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",s=null;for(let i of o){let l=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),k=m.includes("invite"),g=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:k,matchesName:g,ariaLabel:m}},i,r);if(!l.isMuted&&!l.isStickyHeader&&!l.inRecommendations){if(l.hasInvite&&!l.matchesName){console.log(` Skipping secondary button: wrong person (${l.ariaLabel})`);continue}s=i;break}}for(let i of o)i!==s&&await i.dispose().catch(()=>{});if(s)return console.log(" Found: secondary button"),{button:s,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,u=await e.$$('button[id*="profile-overflow-action"]');for(let i of u){let l=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},i);if(l.isVisible&&!l.isInStickyHeader){a=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of u)i!==a&&await i.dispose().catch(()=>{});if(!a&&u.length>0&&(a=u[u.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 i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});a=i?.asElement?.()||null,a||await i?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await b(500),await e.evaluate(c=>c.click(),a),await b(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let l=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(l||(l=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),l||(l=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),l||(l=await e.$('div[role="button"][aria-label*="Invite"]')),l||(l=await e.$('div[role="button"][aria-label*="connect"]')),!l){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});l=c?.asElement?.()||null,l||await c?.dispose?.().catch(()=>{})}if(!l){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(l)return console.log(" Found: More dropdown"),{button:l,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),l=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(l)&&(console.log(` Skipping generic button: wrong person (${i})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Nt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await b(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),s=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();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(r){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 b(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 b(2e3),"premium_redirect"}else s?(await e.evaluate(c=>c.click(),t),await b(3e3)):(await e.evaluate(c=>c.click(),t),await b(3e3));let u=e.url();if(u.includes("/premium/")||u.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')),l=e.url();return console.log(i?` \u2713 Connect sent \u2014 ${l}`:` \u26A0 No modal after connect click \u2014 ${l}`),"success"}async function Kr(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 b(1500);let n=await ze(e);if(n){await e.evaluate(r=>r.click(),n),await b(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function jt(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:s=!1}=n;if(!r){let u=Ve();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let a=await Qr(e,t,n);return a.connectionSent&&!s&&nn(t,o),a}async function Qr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:s=!0,skipIfConnected:a=!0,excludeLocations:u=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
+
--- Connecting: ${l} ---`),u.length>0){let g=Y()[t]?.location;if(ut(g,u))return console.log(` \u26A0 Excluded location (stored): ${g}`),i.reason="excluded_location",i.profileInfo={location:g},i}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(5e3),await Se(e)&&(console.log(" Dismissed Premium overlay"),await b(2e3),await On(e,t),await b(2e3)),i.profileInfo=await e.evaluate(()=>{let g=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),v=_=>{let O=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},E={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},y=document.querySelector("main");if(!y)return E;let $=[...Array.from(y.querySelectorAll("h1")),...Array.from(y.querySelectorAll("h2"))],x=Array.from(y.querySelectorAll("h2")),w=$.find(_=>{let O=_.textContent&&_.textContent.trim();return O&&O.length>1&&O.length<100&&!g.has(O)&&O!=="0 notifications"}),R=w?w.textContent.trim():null,C=w?w.parentElement:null;for(;C&&C!==y&&!Array.from(C.children).filter(V=>V.tagName==="P").some(V=>{let L=V.textContent&&V.textContent.trim();return L&&L.length>5&&!v(L)});)C=C.parentElement;let F=null,H=null,J=null;if(C&&C!==y){let _=Array.from(C.children),O=_.filter(L=>L.tagName==="P").filter(L=>{let ne=L.textContent&&L.textContent.trim();return ne&&ne.length>5&&!v(ne)});O[0]&&(F=O[0].textContent.trim()),O[1]&&(H=O[1].textContent.trim());let V=_.filter(L=>L.tagName==="DIV");for(let L=V.length-1;L>=0;L--){let ne=V[L].textContent&&V[L].textContent.trim();if(ne&&!(R&&ne.startsWith(R))&&(J=ne.split(/[·•]/)[0].trim(),J))break}}let M=null;if(C){let _=C.querySelectorAll("p, span, div");for(let O of _){let V=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(V==="1st"||V==="2nd"||V==="3rd"){M=V;break}}}let j=null,K=x.find(_=>_.textContent&&_.textContent.trim()==="About");if(K){let _=K.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;_&&(j=(_.textContent||"").trim().replace(/^About\s*/,"").trim()||null,j&&(j=j.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),W=T&&T.src||null,ve=!!y.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:F,location:J,about:j,company:H,connectionDegree:M,connectionsCount:null,mutualConnections:null,photoUrl:W,hasVerifiedBadge:ve}});try{let g=e.url();g&&/\/in\/[^/?#]/.test(g)&&(i.resolvedUrl=g.split("?")[0].replace(/\/+$/,""))}catch{}if(u.length>0){let g=i.profileInfo?.location,v=Y()[t]?.location,E=g||v;if(ut(E,u))return console.log(` \u26A0 Excluded location (${g?"live":"stored"}): ${E}`),i.reason="excluded_location",i;!g&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ie(e);if(i.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&s)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(d==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await Se(e);let f=await ze(e);if(!f&&(await Se(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await b(2e3),f=await ze(e)),!f))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;i.method=f.method;let p=await Nt(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),i.reason="wrong_target",i;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(4e3);let g=await Ie(e);if(g==="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: ${g} \u2014 trying More dropdown...`),await Se(e),await b(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(y=>y.scrollIntoView({behavior:"smooth",block:"center"}),v),await b(500),await v.click().catch(()=>e.evaluate(y=>y.click(),v)),await b(2e3);let E=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(E){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(x=>x.click(),E),await b(3e3);let y=e.url();if(y.includes("/premium/")||y.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),i.reason="premium_required",i;if(await Ie(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 b(500),i.reason="premium_required",i}catch(E){return console.log(" More dropdown failed:",E.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.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let g=await e.$('button[aria-label="Dismiss"]');return g&&await g.click(),await b(500),i.reason="email_required",i}let m=await e.$('button[aria-label="Add a note"]'),k=await e.$('button[aria-label="Send without a note"]');if(!m&&!k){let g=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let E=v.querySelector('button[aria-label="Add a note"]'),y=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!E,sendWithout:!!y}});if(g.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=v?.asElement?.()||null,m||await v.dispose().catch(()=>{})}if(g.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));k=v?.asElement?.()||null,k||await v.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await b(1500),await e.$("div.modal-upsell")){let E=await Kr(e);return i.success=E,i.connectionSent=E,i.reason=E?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let E=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),y=o.replace("{name}",E);await v.type(y,{delay:20}),await b(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(x=>x.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=y,i}}}else if(k){console.log(" Sending without note...");try{await k.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(m&&!o){console.log(" No message provided, sending without note...");let g=await e.$('button[aria-label="Send without a note"]');if(g){try{await g.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let g=k;if(g){try{await g.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await b(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}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 b(4e3)),await Se(e),await b(500);let v=await e.$$('button[id*="profile-overflow-action"]'),E=null;for(let y of v){let $=await e.evaluate(x=>{let w=x.getBoundingClientRect();return{visible:w.width>0&&w.height>0,inSticky:!!x.closest('.sticky-header, [class*="sticky"]')}},y);if($.visible&&!$.inSticky){E=y;break}}!E&&v.length>0&&(E=v[v.length-1]);for(let y of v)y!==E&&await y.dispose().catch(()=>{});if(E)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),E),await b(500),await E.click().catch(()=>e.evaluate($=>$.click(),E)),await b(2e3);let y=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(y){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(R=>R.click(),y),await b(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await b(3e3),await Ie(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 Ie(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 w=await e.$('button[aria-label="Send without a note"]');if(w){console.log(" Modal appeared via More dropdown, sending without note...");try{await w.evaluate(R=>R.click())}catch{}return await b(3e3),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(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(y){console.log(" More dropdown fallback failed:",y.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(l){console.error(` \u2717 Error: ${l.message}`),i.reason="error",i.error=l.message;let c=l.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 b(1e3)}catch{i.fatal=!0}return i}}async function Mn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:s=20,viewOnly:a=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:i=null,excludeLocations:l=[],source:c="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: ${a?"View Only":`Connect (max ${s})`}`),a||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!a){let p=$e();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];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(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=
|
|
242
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=en(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,i&&await i(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let k=null;if(a){let g=await Tt(e,h.profileUrl);g?(et(h.profileUrl,{...g,source:c}),d.viewed++,k={success:!0,reason:"viewed",connectionSent:!1,profileInfo:g,resolvedUrl:g.resolvedUrl}):(d.errors++,k={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=s){console.log(` Max connections per session (${s}) reached`);break}let g=Ve();if(!g.allowed){console.log(` \u26A0 Global quota exhausted: ${g.reason}`);break}if(k=await jt(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:l,source:c,skipQuotaGate:!0}),k.success)d.connectionsSent++;else switch(k.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(k?.fatal){console.log(`
|
|
243
243
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(k?.reason==="error"){if(f++,f>=3){console.log(`
|
|
244
|
-
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(k&&k.reason&&(
|
|
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}`),!a){let p
|
|
244
|
+
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(k&&k.reason&&(ot(h.profileUrl,k.reason,{method:k.method,messageSent:k.messageSent,profileInfo:k.profileInfo}),k.resolvedUrl&&rt(h.profileUrl,k.resolvedUrl),Zt(h.profileUrl,{source:c||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:k.reason})),i&&await i(h,d,k),p<t.length-1){let g=u+Math.random()*2e3;await b(g)}}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}`),!a){let p=$e();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}var zr,Ln=oe(async()=>{ct();await Re();zr={viewProfile:Tt,detectConnectionStatus:Ie,findConnectButton:ze,clickConnectButton:Nt,sendConnectionRequest:jt,runFunnel:Mn,shouldExcludeLocation:ut}});import{createGraphClient as Xr,resolveToken as Zr}from"@ilivemylife/graph-sdk";import{config as ei}from"dotenv";var Pn,qn,Un=oe(()=>{ei();Pn=Zr()||process.env.TOKEN;Pn||(console.error(`
|
|
246
246
|
[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.
|
|
247
247
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
248
248
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
249
|
-
`),process.exit(1));
|
|
249
|
+
`),process.exit(1));qn=Xr({token:Pn})});import"dotenv/config";function ti(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 ni({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",a=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${ti(r)}`:"",i=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",l=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${l} \u2014 ${i} \u2014 ${a}${u}`}async function Bn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let a=process.env.NODE_RUN_REPORTS;if(!a||!Array.isArray(o)||o.length===0)return;let i=`**${ni({scriptName:e,mode:t,status:n,error:r,duration:s})}**
|
|
250
250
|
|
|
251
251
|
${o.join(`
|
|
252
|
-
`)}`;try{await
|
|
253
|
-
`)}var Gr,Yr,jt,Ot,Pn=se(()=>{jn();Gr=Wr(import.meta.url),Yr=Se.dirname(Se.dirname(Gr)),jt=process.env.DATA_DIR?Se.resolve(process.env.DATA_DIR,"collected-profiles"):Se.join(Yr,"collected-profiles"),Ot=Se.join(jt,"run-log.json")});import*as pt from"fs";import*as Ne from"path";await Xe();await Ie();import"dotenv/config";import*as rt from"fs";import*as he from"path";import{fileURLToPath as So}from"url";var ko=So(import.meta.url),vo=he.dirname(he.dirname(ko)),wt=process.env.DATA_DIR?he.resolve(process.env.DATA_DIR,"collected-profiles"):he.join(vo,"collected-profiles"),rn=he.join(wt,"connect-queue.json"),$o=1,ve=300,st=["queued","approved","sent","skipped","failed"],ge=["high","normal","low"],on={high:0,normal:1,low:2};function Co(){rt.existsSync(wt)||rt.mkdirSync(wt,{recursive:!0})}function bt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ve?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:ge.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:st.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function oe(){let e=Ue(rn,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(bt).filter(n=>n.url):[]}function ye(e){Co(),qe(rn,{version:$o,entries:e.map(bt)})}function ce(e){return U(e)||(e||"").trim().toLowerCase()}function Ve(e,t){let n=ce(t);return e.find(o=>ce(o.url)===n)||null}function St(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:a}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(l=>ce(l.url)));for(let l of t){let c=l?.url;if(!c){u.skippedNoUrl++;continue}let d=ce(c);if(s.has(d)){u.skippedDup++;continue}if(i(c)){u.skippedEngaged++;continue}let f=typeof l.note=="string"?l.note.trim():"";f.length>ve&&u.notesTooLong++;let p=f.length>0&&f.length<=ve;e.push(bt({url:c,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:a||null})),s.add(d),u.added++}return u}function sn(e){return[...e].sort((t,n)=>{let o=(on[t.priority]??1)-(on[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function $e(e,t){return e.filter(n=>n.status===t)}await Ie();await Xe();await Ie();var xo={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 an(e){if(!e)return null;for(let[t,n]of Object.entries(xo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}import"dotenv/config";import*as S from"fs";import*as _t from"os";import*as R from"path";import{fileURLToPath as or}from"url";var $t={};ie($t,{NAME:()=>Eo,VERSION:()=>Ao,up:()=>Do});import*as z from"fs";import*as it from"path";var Ao=1,Eo="normalize-jobs-and-questions",_o=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Io=50;function kt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function vt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Do(e,t){let n=it.join(e,"jobs.json"),o=it.join(t,"scouted-jobs.json"),r=it.join(e,"application-questions.json"),i=kt(n)||{},a=kt(o)||{},u=0,s=[];for(let c of Object.keys(i)){if(!a[c])continue;let d=a[c],f=i[c];for(let p of _o)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(vt(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=kt(r);if(l&&Array.isArray(l.applications)){let c={},d=0;for(let f of l.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let k={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Io?k.options=m.options:(k.optionsOmitted=!0,d++)),m.page&&(k.page=m.page),m.wasPreFilled&&(k.wasPreFilled=!0),m.wasRetry&&(k.wasRetry=!0),k});c[p].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})}vt(r,c),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else l&&!l.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let c of s)delete a[c];vt(o,a),console.log(` Phase 3: Removed ${s.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 Ct={};ie(Ct,{NAME:()=>Ro,VERSION:()=>To,up:()=>Oo});import*as X from"fs";import*as ln from"path";var To=2,Ro="reset-unread-flags";function No(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Oo(e){let t=ln.join(e,"conversations.json"),n=No(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}jo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var xt={};ie(xt,{NAME:()=>Mo,VERSION:()=>Fo,up:()=>Bo});import*as Z from"fs";import*as cn from"path";var Fo=3,Mo="recompute-last-message-by",Lo=new Set(["draft","confirmed","rejected","needs_review"]);function Po(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function qo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Uo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Lo.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,a)=>a.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let a=i.sender;if(a===t)return"me";if(a!=="Unknown"&&a!=="")return"them"}return"them"}async function Bo(e){let t=cn.join(e,"conversations.json"),n=Po(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,a=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let l=Array.isArray(s.messages)?s.messages:[],c=Uo(l,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==c&&a++,s.lastMessageBy=c,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}qo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${a} 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 At={};ie(At,{NAME:()=>Vo,VERSION:()=>Jo,up:()=>Yo});import*as ee from"fs";import*as un from"path";var Jo=4,Vo="split-connection-timestamps",Ho=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Wo(e){if(!ee.existsSync(e))return null;let t=ee.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Go(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ee.writeFileSync(o,n)}catch(r){try{ee.unlinkSync(o)}catch{}throw r}try{ee.renameSync(o,e)}catch(r){try{ee.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Yo(e){let t=un.join(e,"people.json"),n=Wo(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let a=n[i];!a||typeof a!="object"||(r++,Ho.has(a.connectionStatus)&&a.connectionDate&&!a.requestedConnectionAt&&(a.requestedConnectionAt=a.connectionDate,a.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Go(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Ie();import"dotenv/config";import*as Q from"path";import{fileURLToPath as Ko}from"url";var Qo=Ko(import.meta.url),zo=Q.dirname(Q.dirname(Qo)),He=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(zo,"market-research"),Os=Q.join(He,"scouted-jobs.json"),Fs=Q.join(He,"discovered-people.json"),Ms=Q.join(He,"visit-log.json"),Ls=Q.join(He,"companies.json"),Ps=Q.join(He,"job-decisions.json");function dn(){Xo=null,Zo=null,er=null,tr=null,nr=null}var Xo=null;var Zo=null;var er=null;var tr=null;var nr=null;var rr=or(import.meta.url),sr=R.dirname(rr),ir=R.dirname(R.dirname(sr));function ar(e){return e&&(e==="~"?_t.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(_t.homedir(),e.slice(2)):e)}var re=process.env.DATA_DIR?R.resolve(ar(process.env.DATA_DIR)):ir,xe=R.join(re,"collected-profiles"),Ae=R.join(re,"market-research"),K=R.join(re,".schema-version"),fn=[R.join(xe,".schema-version"),R.join(Ae,".schema-version")],we=4,ue=[{version:1,module:$t},{version:2,module:Ct},{version:3,module:xt},{version:4,module:At}];(function(){ue.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ue){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ue.length?ue[ue.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<ue.length;o++){let r=o+1;if(ue[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ue[o].version}`)}})();function gn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
252
|
+
`)}`;try{await qn.addMessage(a,i)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var Jn=oe(()=>{Un()});var Yn={};ae(Yn,{endRun:()=>li,formatScriptStatus:()=>di,getLastRun:()=>ui,getRunHistory:()=>ci,getTodayRunSummary:()=>Hn,startRun:()=>ai,timeAgo:()=>Wn});import"dotenv/config";import*as te from"fs";import*as ke from"path";import{fileURLToPath as oi}from"url";function si(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";te.writeFileSync(o,n);for(let r=0;r<3;r++)try{te.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw s}}function Te(){try{if(!te.existsSync(Mt))return{runs:[]};let e=JSON.parse(te.readFileSync(Mt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Vn(e){te.existsSync(Ot)||te.mkdirSync(Ot,{recursive:!0});try{si(Mt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ai(e,t="default"){let n=Te();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,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(a=>new Date(a.timestamp).getTime()>s),Vn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function li(e,t,n=null,o=null){if(!e)return;let r=null;try{let a=Te(),u=a.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration;else{let i=a.runs.find(l=>l.script===e.script&&l.status==="running"&&l.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,r=i.duration)}Vn(a)}catch(a){console.error(`[runLog] Failed to end run: ${a.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let a=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Bn({scriptName:e.script,mode:e.mode,status:a,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function ci(e=7){let t=Te(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function ui(e=null){let t=Te(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function Hn(){let e=new Date().toISOString().slice(0,10),t=Te(),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 r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function Wn(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function di(){let e=["sync-all","messages","funnel","sync","apply"],t=Te(),n=Hn(),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 s of e){let a=t.runs.filter(m=>m.script===s),u=[...a].reverse().find(m=>m.status==="success"),i=a[a.length-1],l=u||i,c=l?Wn(l.timestamp):"never",f=(l?Math.floor((Date.now()-new Date(l.timestamp).getTime())/864e5):1/0)>1?" \u26A0":l?.status==="error"?" \u2717":" \u2713",p="";if(l?.stats){let m=l.stats,k=Object.entries(m).filter(([,g])=>typeof g=="number"&&g>0).slice(0,3).map(([g,v])=>`${v} ${g}`);k.length&&(p=` (${k.join(", ")})`)}let h=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${s.padEnd(14)} ${c.padEnd(16)}${h}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[s,a]of r){let u=[];a.success&&u.push(`${a.success} success`),a.error&&u.push(`${a.error} error`),a.interrupted&&u.push(`${a.interrupted} interrupted`),a.running&&u.push(`${a.running} running`),o.push(` Today: ${s} \xD7${a.total} (${u.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(`
|
|
253
|
+
`)}var ri,ii,Ot,Mt,Gn=oe(()=>{Jn();ri=oi(import.meta.url),ii=ke.dirname(ke.dirname(ri)),Ot=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(ii,"collected-profiles"),Mt=ke.join(Ot,"run-log.json")});import*as pt from"fs";import*as je from"path";await Ze();await Re();import"dotenv/config";import*as it from"fs";import*as he from"path";import{fileURLToPath as Io}from"url";var Do=Io(import.meta.url),Ro=he.dirname(he.dirname(Do)),wt=process.env.DATA_DIR?he.resolve(process.env.DATA_DIR,"collected-profiles"):he.join(Ro,"collected-profiles"),sn=he.join(wt,"connect-queue.json"),To=1,Ce=300,st=["queued","approved","sent","skipped","failed"],ge=["high","normal","low"],rn={high:0,normal:1,low:2};function No(){it.existsSync(wt)||it.mkdirSync(wt,{recursive:!0})}function bt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=Ce?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:ge.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:st.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function re(){let e=Be(sn,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(bt).filter(n=>n.url):[]}function ye(e){No(),Ue(sn,{version:To,entries:e.map(bt)})}function ue(e){return B(e)||(e||"").trim().toLowerCase()}function He(e,t){let n=ue(t);return e.find(o=>ue(o.url)===n)||null}function St(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:s=()=>!1,nowIso:a}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},i=new Set(e.map(l=>ue(l.url)));for(let l of t){let c=l?.url;if(!c){u.skippedNoUrl++;continue}let d=ue(c);if(i.has(d)){u.skippedDup++;continue}if(s(c)){u.skippedEngaged++;continue}let f=typeof l.note=="string"?l.note.trim():"";f.length>Ce&&u.notesTooLong++;let p=f.length>0&&f.length<=Ce;e.push(bt({url:c,tag:l.tag||o,priority:l.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:a||null})),i.add(d),u.added++}return u}function an(e){return[...e].sort((t,n)=>{let o=(rn[t.priority]??1)-(rn[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function xe(e,t){return e.filter(n=>n.status===t)}await Re();await Ze();await Re();var jo={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 ln(e){if(!e)return null;for(let[t,n]of Object.entries(jo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}import"dotenv/config";import*as S from"fs";import*as _t from"os";import*as N from"path";import{fileURLToPath as fr}from"url";var $t={};ae($t,{NAME:()=>Mo,VERSION:()=>Oo,up:()=>Po});import*as z from"fs";import*as at from"path";var Oo=1,Mo="normalize-jobs-and-questions",Fo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Lo=50;function kt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function vt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Po(e,t){let n=at.join(e,"jobs.json"),o=at.join(t,"scouted-jobs.json"),r=at.join(e,"application-questions.json"),s=kt(n)||{},a=kt(o)||{},u=0,i=[];for(let c of Object.keys(s)){if(!a[c])continue;let d=a[c],f=s[c];for(let p of Fo)d[p]!=null&&f[p]==null&&(f[p]=d[p]);i.push(c),u++}u>0?(vt(n,s),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=kt(r);if(l&&Array.isArray(l.applications)){let c={},d=0;for(let f of l.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let k={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Lo?k.options=m.options:(k.optionsOmitted=!0,d++)),m.page&&(k.page=m.page),m.wasPreFilled&&(k.wasPreFilled=!0),m.wasRetry&&(k.wasRetry=!0),k});c[p].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})}vt(r,c),console.log(` Phase 2: Rekeyed ${l.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else l&&!l.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];vt(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 Ct={};ae(Ct,{NAME:()=>Uo,VERSION:()=>qo,up:()=>Vo});import*as X from"fs";import*as cn from"path";var qo=2,Uo="reset-unread-flags";function Bo(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function Jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Vo(e){let t=cn.join(e,"conversations.json"),n=Bo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Jo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var xt={};ae(xt,{NAME:()=>Wo,VERSION:()=>Ho,up:()=>zo});import*as Z from"fs";import*as un from"path";var Ho=3,Wo="recompute-last-message-by",Yo=new Set(["draft","confirmed","rejected","needs_review"]);function Go(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function Ko(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Qo(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Yo.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,a)=>a.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let a=s.sender;if(a===t)return"me";if(a!=="Unknown"&&a!=="")return"them"}return"them"}async function zo(e){let t=un.join(e,"conversations.json"),n=Go(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,a=0;for(let u of Object.keys(n)){let i=n[u];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let l=Array.isArray(i.messages)?i.messages:[],c=Qo(l,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==c&&a++,i.lastMessageBy=c,i.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}Ko(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${a} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var At={};ae(At,{NAME:()=>Zo,VERSION:()=>Xo,up:()=>or});import*as ee from"fs";import*as dn from"path";var Xo=4,Zo="split-connection-timestamps",er=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function tr(e){if(!ee.existsSync(e))return null;let t=ee.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{ee.writeFileSync(o,n)}catch(r){try{ee.unlinkSync(o)}catch{}throw r}try{ee.renameSync(o,e)}catch(r){try{ee.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function or(e){let t=dn.join(e,"people.json"),n=tr(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let a=n[s];!a||typeof a!="object"||(r++,er.has(a.connectionStatus)&&a.connectionDate&&!a.requestedConnectionAt&&(a.requestedConnectionAt=a.connectionDate,a.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}nr(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Re();import"dotenv/config";import*as Q from"path";import{fileURLToPath as rr}from"url";var ir=rr(import.meta.url),sr=Q.dirname(Q.dirname(ir)),We=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(sr,"market-research"),Wi=Q.join(We,"scouted-jobs.json"),Yi=Q.join(We,"discovered-people.json"),Gi=Q.join(We,"visit-log.json"),Ki=Q.join(We,"companies.json"),Qi=Q.join(We,"job-decisions.json");function fn(){ar=null,lr=null,cr=null,ur=null,dr=null}var ar=null;var lr=null;var cr=null;var ur=null;var dr=null;var pr=fr(import.meta.url),mr=N.dirname(pr),hr=N.dirname(N.dirname(mr));function gr(e){return e&&(e==="~"?_t.homedir():e.startsWith("~/")||e.startsWith("~\\")?N.join(_t.homedir(),e.slice(2)):e)}var ie=process.env.DATA_DIR?N.resolve(gr(process.env.DATA_DIR)):hr,Ee=N.join(ie,"collected-profiles"),_e=N.join(ie,"market-research"),G=N.join(ie,".schema-version"),pn=[N.join(Ee,".schema-version"),N.join(_e,".schema-version")],we=4,de=[{version:1,module:$t},{version:2,module:Ct},{version:3,module:xt},{version:4,module:At}];(function(){de.sort((o,r)=>o.version-r.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 r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=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 r=o+1;if(de[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${de[o].version}`)}})();function yn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
254
254
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
255
|
-
`),process.exit(1));try{S.mkdirSync(
|
|
256
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
257
|
-
`),process.exit(1))}let e;try{e=S.statSync(
|
|
258
|
-
[FATAL] DATA_DIR (${
|
|
255
|
+
`),process.exit(1));try{S.mkdirSync(ie,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
256
|
+
[FATAL] Cannot create DATA_DIR (${ie}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
257
|
+
`),process.exit(1))}let e;try{e=S.statSync(ie)}catch(t){console.error(`
|
|
258
|
+
[FATAL] DATA_DIR (${ie}) is not accessible: ${t.message}
|
|
259
259
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
260
|
-
[FATAL] DATA_DIR (${
|
|
261
|
-
`),process.exit(1));for(let t of[
|
|
260
|
+
[FATAL] DATA_DIR (${ie}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
261
|
+
`),process.exit(1));for(let t of[Ee,_e]){let n;try{n=S.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
262
262
|
[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.
|
|
263
|
-
`),process.exit(1))}}var
|
|
264
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
263
|
+
`),process.exit(1))}}var Ae=N.join(ie,".migration-lock");function yr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return S.writeFileSync(Ae,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(S.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 r=24*60*60*1e3,s=1/0;if(t.startedAt){let a=Date.parse(t.startedAt);Number.isNaN(a)||(s=Date.now()-a)}o&&s<r&&(console.error(`
|
|
264
|
+
[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}
|
|
265
265
|
`),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.
|
|
266
|
-
`),process.exit(1)),o&&
|
|
267
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
266
|
+
`),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ae+".tmp";try{return S.writeFileSync(n,e),S.renameSync(n,Ae),!0}catch(o){try{S.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function It(){try{if(JSON.parse(S.readFileSync(Ae,"utf-8")).pid!==process.pid)return;S.unlinkSync(Ae)}catch{}}var mn=!1;function wr(){if(mn)return;mn=!0;let e=()=>{try{It()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function br(){if(S.existsSync(G))return;let e=[],t=[];for(let s of pn)if(S.existsSync(s))try{e.push({file:s,schema:lt(s)})}catch(a){t.push({file:s,err:a.message})}if(t.length>0){console.error(`
|
|
267
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
268
268
|
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.
|
|
269
|
-
`),process.exit(1)}if(e.length===0)return;let n=e.map(
|
|
270
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
271
|
-
`),process.exit(1)}let o=e[0].schema,r=
|
|
272
|
-
[FATAL] ${
|
|
273
|
-
`),process.exit(1)}let t=
|
|
274
|
-
[FATAL] ${
|
|
275
|
-
`),process.exit(1)),t}function
|
|
269
|
+
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
270
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.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.
|
|
271
|
+
`),process.exit(1)}let o=e[0].schema,r=G+".tmp";try{S.writeFileSync(r,JSON.stringify(o,null,2)),S.renameSync(r,G)}catch(s){try{S.unlinkSync(r)}catch{}throw s}for(let s of pn)if(S.existsSync(s))try{S.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function Sr(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=S.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function hn(){if(br(),!S.existsSync(G))return{version:0,migrations:[]};let e;try{e=lt(G)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
272
|
+
[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.
|
|
273
|
+
`),process.exit(1)}let t=Sr(e);return t===null&&(console.error(`
|
|
274
|
+
[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.
|
|
275
|
+
`),process.exit(1)),t}function wn(e){try{S.chmodSync(e,384)}catch{}}function kr(e){if(yn(),S.existsSync(G))try{if(S.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{S.writeFileSync(t,JSON.stringify(e,null,2)),wn(t),S.renameSync(t,G)}catch(n){try{S.unlinkSync(t)}catch{}throw n}}function gn(e,t){if(!S.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=S.readdirSync(e).filter(u=>{let i=u.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return S.statSync(N.join(e,u)).isFile()}catch{return!1}}),r=0,s=0,a=[];for(let u of o){let i=N.join(e,u),l=N.join(e,u+n);if(S.existsSync(l)){s++;continue}try{Sn(i,l),r++}catch(c){a.push({file:u,err:c.message})}}if(a.length>0){let u=new Error(`Failed to back up ${a.length} file(s) in ${N.basename(e)}/: `+a.map(i=>`${i.file} (${i.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||s>0){let u=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${N.basename(e)}/ (${n})${u}`)}}var Et=!1;async function bn(){if(Et)return;yn(),Ar();let t=hn().version;if(t===we){Et=!0;return}wr(),yr(),process.on("exit",It),t>we&&(console.error(`
|
|
276
276
|
[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.
|
|
277
277
|
`),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}.
|
|
278
278
|
`),process.exit(1)),console.log(`
|
|
279
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${we}`);let n=
|
|
279
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${we}`);let n=Er();if(!n.ok){console.error(`
|
|
280
280
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
281
281
|
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'.
|
|
282
|
-
`),process.exit(1)}let o=
|
|
283
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let
|
|
284
|
-
[FATAL] Pre-migration backup failed for ${
|
|
285
|
-
`),process.exit(1)}let u=r.module;try{await u.up(
|
|
286
|
-
[FATAL] Migration ${
|
|
282
|
+
`),process.exit(1)}let o=de.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
283
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,a=`.pre-${s}.backup`;try{gn(Ee,r.version),gn(_e,r.version)}catch(i){console.error(`
|
|
284
|
+
[FATAL] Pre-migration backup failed for ${s}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
285
|
+
`),process.exit(1)}let u=r.module;try{await u.up(Ee,_e)}catch(i){console.error(`
|
|
286
|
+
[FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let l=_r(a);l.ok?(console.error(` \u2713 Auto-rollback restored ${l.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
287
287
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${l.error}`),console.error(` Manual recovery: copy *${a} files back over the originals.
|
|
288
288
|
`))}catch(l){console.error(` [!] Auto-rollback CRASHED while restoring: ${l.message}`),console.error(` Manual recovery: copy *${a} files back over the originals.
|
|
289
|
-
`)}process.exit(1)}try{let
|
|
290
|
-
[FATAL] Migration ${
|
|
291
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
289
|
+
`)}process.exit(1)}try{let i=new Date().toISOString(),l={version:r.version,name:u.NAME||s,appliedAt:i},c=hn();c.version=r.version,c.migratedAt=i,c.migrations=c.migrations||[],c.migrations.push(l),kr(c)}catch(i){console.error(`
|
|
290
|
+
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
291
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{zt()}catch{}try{fn()}catch{}Et=!0,It(),console.log(`
|
|
292
292
|
\u2713 Schema is now at v${we}
|
|
293
|
-
`)}var
|
|
294
|
-
`);let a=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:
|
|
295
|
-
Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${
|
|
296
|
-
Queue now: ${
|
|
297
|
-
(shortcut: --valuable = ${
|
|
298
|
-
Filled ${
|
|
299
|
-
Queue now: ${
|
|
293
|
+
`)}var vr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function $r(e){let t=e.toLowerCase();return vr.some(n=>n.test(t))}var Cr=6e4;function xr(){let e=Date.now(),t=[];for(let n of[ie,Ee,_e]){if(!S.existsSync(n))continue;let o;try{o=S.readdirSync(n)}catch{continue}for(let r of o){if(!$r(r))continue;let s=N.join(n,r);try{let a=S.statSync(s);if(!a.isFile()||e-a.mtimeMs<Cr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Ar({verbose:e=!1}={}){let t=xr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{S.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${N.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Er(){let e=[];for(let t of[Ee,_e]){if(!S.existsSync(t))continue;let n=S.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=N.join(t,o);try{lt(r)}catch(s){e.push({dir:N.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function _r(e){let t=[],n=[];for(let s of[Ee,_e]){if(!S.existsSync(s))continue;let a=S.readdirSync(s).filter(u=>u.endsWith(e));for(let u of a){let i=N.join(s,u),l=u.slice(0,-e.length),c=N.join(s,l);try{l.toLowerCase().endsWith(".json")?lt(i):S.accessSync(i,S.constants.R_OK),t.push({backupPath:i,originalPath:c,fileName:u,dir:s})}catch(d){n.push(`${N.basename(s)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:a,fileName:u,dir:i}of t)try{Sn(s,a),o++}catch(l){r.push(`${N.basename(i)}/${u}: ${l.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Sn(e,t){let n=t+".tmp";try{S.copyFileSync(e,n),wn(n)}catch(o){try{S.unlinkSync(n)}catch{}throw o}try{S.renameSync(n,t)}catch(o){try{S.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var zn=new Set(["connected"]),Xn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Kn=new Set(["pending","connected","excluded_location","email_required","premium_required"]),fi=3,dt=process.env.DATA_DIR?je.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):je.resolve("collected-profiles","connect-diagnostics");async function pi(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(l=>Array.from(document.querySelectorAll(l)).map(c=>(c.innerText||"").trim()).filter(Boolean).join(" | "))('[role="alertdialog"], [role="dialog"], .artdeco-modal, .artdeco-toast-item, .ip-fuse-limit-alert, .artdeco-inline-feedback').slice(0,1e3),body:(document.body.innerText||"").slice(0,1500)}));pt.mkdirSync(dt,{recursive:!0});let s={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};pt.appendFileSync(je.join(dt,"connect-failures.jsonl"),JSON.stringify(s)+`
|
|
294
|
+
`);let a=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:je.join(dt,`fail-${a}.png`)})}catch{}return r.modal||""}catch{return""}}var Oe=process.argv.slice(2),Zn=Oe[0],Me=Oe.filter(e=>!e.startsWith("--")),Ne=e=>Oe.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),fe=e=>{let t=Oe.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&q(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},Ft=()=>new Date().toISOString();function mt(){let e=Y(),t=new Map;for(let[n,o]of Object.entries(e)){let r=B(o.profileUrl||n);r&&!t.has(r)&&t.set(r,o)}for(let n of Object.values(e))for(let o of n.aliases||[])o&&!t.has(o)&&t.set(o,n);return t}function eo(e,t){let n=e.get(B(t));return n?zn.has(n.connectionStatus)||Xn.has(n.connectionStatus):!1}async function mi(){let e=Me[1];if(!e)return q("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(l){return q(`Could not read/parse ${e}: ${l.message}`)}if(!Array.isArray(t))return q("File must be a JSON array of { url, note?, name? }.");let n=fe("tag")||"untagged",o=fe("priority");if(o&&!ge.includes(o))return q(`--priority must be one of: ${ge.join(", ")}`);let r=o||"normal",s=re(),a=mt(),u=St(s,t,{tag:n,priority:r,nowIso:Ft(),alreadyEngaged:l=>eo(a,l)});ye(s),console.log(`
|
|
295
|
+
Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${Ce} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let i=s.filter(l=>l.status==="queued"&&l.withNote).length;console.log(`
|
|
296
|
+
Queue now: ${xe(s,"queued").length} queued, ${xe(s,"approved").length} approved.`),i&&console.log(` ${i} queued entries have a note saved \u2014 sent only with \`connect run --with-notes\`.`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var Qn=["founder","investor","hiring_manager","peer"];function hi(){let e=fe("category");if(e===void 0&&Ne("valuable")&&(e=Qn.join(",")),!e)return q(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
297
|
+
(shortcut: --valuable = ${Qn.join(",")})`);let t=e.split(",").map($=>$.trim()).filter(Boolean),n=$=>{let x=fe($);if(x===void 0)return;let w=parseInt(x,10);return!Number.isInteger(w)||w<0?q(`--${$} must be a non-negative integer.`):w},o=n("min-posts")??0,r=n("max"),s=fe("priority");if(s&&!ge.includes(s))return q(`--priority must be one of: ${ge.join(", ")}`);let a=fe("tag"),u=!Ne("no-validate"),i=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),l=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map($=>$.trim().toLowerCase()).filter(Boolean),c=$=>{if(!$)return!1;let x=String($).toLowerCase();return l.some(w=>x.includes(w))},d=Y(),f=[],p=0,h=0,m=0;for(let[$,x]of Object.entries(d))if(t.includes(x.category)&&!(zn.has(x.connectionStatus)||Xn.has(x.connectionStatus))&&x.connectionDegree!=="1st"&&!((x.jobIds?.length||0)<o)){if(c(x.location)){p++;continue}if(u&&i.has(x.category)){let w=(typeof x.title=="string"?x.title:"").trim();if(!w){h++;continue}if(ln(w)!==x.category){m++;continue}}f.push({url:x.profileUrl||$,p:x})}let k={high:0,medium:1,low:2};f.sort(($,x)=>(k[$.p.personPriority]??1)-(k[x.p.personPriority]??1)||(x.p.mutualConnections||0)-($.p.mutualConnections||0)||(x.p.jobIds?.length||0)-($.p.jobIds?.length||0)),r!==void 0&&(f=f.slice(0,r));let g=f.map($=>({url:$.url,tag:a||$.p.category,priority:s||($.p.personPriority==="high"?"high":"normal")})),v=re(),E=mt(),y=St(v,g,{alreadyEngaged:$=>eo(E,$),nowIso:Ft()});ye(v),console.log(`
|
|
298
|
+
Filled ${y.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}${u?"":" (--no-validate)"}.`),y.skippedDup&&console.log(` ${y.skippedDup} already in queue \u2014 skipped.`),y.skippedEngaged&&console.log(` ${y.skippedEngaged} already connected/pending \u2014 skipped.`),p&&console.log(` ${p} in excluded locations \u2014 skipped.`),m&&console.log(` ${m} filtered \u2014 title doesn't confirm the category (likely mis-tagged by enrichment).`),h&&console.log(` ${h} skipped \u2014 no title stored to validate (held; not visited, to avoid ban risk).`),console.log(`
|
|
299
|
+
Queue now: ${xe(v,"queued").length} queued, ${xe(v,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function gi(){let e=re();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=fe("status"),n=mt(),o=$e();console.log(`
|
|
300
300
|
=== Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
|
|
301
301
|
`);let r={};for(let l of e)r[l.status]=(r[l.status]||0)+1;console.log("Status: "+Object.entries(r).map(([l,c])=>`${l}=${c}`).join(" ")+`
|
|
302
302
|
`),t&&!st.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${st.join(", ")})
|
|
303
|
-
`);let
|
|
304
|
-
${
|
|
305
|
-
${o}: ${
|
|
306
|
-
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function
|
|
307
|
-
Note reminder cleared.`)}function
|
|
308
|
-
Priority set to ${t}.`)}async function
|
|
309
|
-
Nothing approved to send.`),
|
|
310
|
-
Connection quota is used up (${
|
|
311
|
-
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let c=l.filter(
|
|
312
|
-
=== Connect run ===`),console.log(` Approved: ${
|
|
303
|
+
`);let s=t?e.filter(l=>l.status===t):e,a={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...s].sort((l,c)=>(a[l.status]??9)-(a[c.status]??9));for(let l of u){let c=n.get(B(l.url)),d=c&&c.name||"",f=c&&c.title?` \xB7 ${c.title.slice(0,40)}`:"",p=c&&c.mutualConnections?` \xB7 ${c.mutualConnections} mutual`:"",h=l.withNote?"\u{1F4DD}":" ",m=l.priority==="high"?"\u2B06high ":l.priority==="low"?"\u2B07low ":"normal";console.log(` [${l.status.padEnd(8)}] ${m} ${h} ${d}${f}${p}`),console.log(` ${l.url} (tag=${l.tag})`)}let i=e.filter(l=>(l.status==="queued"||l.status==="approved")&&l.withNote).length;i&&console.log(`
|
|
304
|
+
${i} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function ft(e,t,n,o){let r=re(),s=0;for(let a of r)e(a)&&t.includes(a.status)&&(a.status=n,s++);return ye(r),console.log(`
|
|
305
|
+
${o}: ${s} entr${s===1?"y":"ies"} \u2192 ${n}.`),s}function yi(){let e=["queued","failed"];if(Ne("all"))return ft(()=>!0,e,"approved","Approved");let t=fe("tag");if(t)return ft(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=Me[1];if(!n)return q("Usage: connect approve <url> | --all | --tag=X");let o=ue(n);return ft(r=>ue(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function wi(){let e=Me[1];if(!e)return q("Usage: connect skip <url>");let t=ue(e);return ft(n=>ue(n.url)===t,["queued","approved"],"skipped","Skipped")}function bi(){let e=Oe[1],t=Oe[2];if(!e||t===void 0)return q('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return q("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>Ce)return q(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${Ce}. Shorten it.`);let o=re(),r=He(o,e);if(!r)return q("Not in queue.");r.note=n,r.withNote=!0,ye(o),console.log(`
|
|
306
|
+
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function Si(){let e=Me[1];if(!e)return q("Usage: connect no-note <url>");let t=re(),n=He(t,e);if(!n)return q("Not in queue.");n.note=null,n.withNote=!1,ye(t),console.log(`
|
|
307
|
+
Note reminder cleared.`)}function ki(){let e=Me[1],t=Me[2];if(!e||!ge.includes(t))return q(`Usage: connect priority <url> <${ge.join("|")}>`);let n=re(),o=He(n,e);if(!o)return q("Not in queue.");o.priority=t,ye(n),console.log(`
|
|
308
|
+
Priority set to ${t}.`)}async function vi(){let e=Ne("dry-run"),t=Ne("yes"),n=Ne("with-notes"),o=fe("max"),r=1/0;if(o!==void 0){let w=parseInt(o,10);if(!Number.isInteger(w)||w<0)return q("--max must be a non-negative integer.");r=w}let s=$e(),a=Math.min(s.daily.remaining,s.weekly.remaining),u=re(),i=an(xe(u,"approved"));if(!i.length){let w=xe(u,"queued").length;console.log(`
|
|
309
|
+
Nothing approved to send.`),w&&console.log(` ${w} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(a<=0){console.log(`
|
|
310
|
+
Connection quota is used up (${s.daily.remaining}/${s.daily.max} today, ${s.weekly.remaining}/${s.weekly.max} week). Try again later.`);return}let l=i.slice(0,Math.min(r,a));if(!l.length){console.log(`
|
|
311
|
+
Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let c=l.filter(w=>w.withNote).length;console.log(`
|
|
312
|
+
=== Connect run ===`),console.log(` Approved: ${i.length} \xB7 quota left: ${a} \xB7 sending: ${l.length}${n?` (${c} WITH a note)`:" (without notes)"}`),!n&&c&&console.log(` ${c} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let d=mt();if(l.forEach((w,R)=>{let C=d.get(B(w.url));console.log(` ${R+1}. ${w.withNote?"\u{1F4DD}":" "} ${C?.name||w.url} (${w.priority}, tag=${w.tag})`)}),e){console.log(`
|
|
313
313
|
[dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
|
|
314
|
-
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(
|
|
315
|
-
[!] ${
|
|
316
|
-
`);try{
|
|
317
|
-
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(
|
|
318
|
-
\u26A0 ${
|
|
319
|
-
=== Done: ${
|
|
320
|
-
[!] Run aborted: ${
|
|
314
|
+
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(w=>process.stdin.once("data",()=>w())));let f=(await import("puppeteer")).default,{launchWithProfile:p,seedCookiesIfNeeded:h}=await Promise.resolve().then(()=>(Rn(),Dn)),{sendConnectionRequest:m}=await Ln().then(()=>Fn),{delayed:k}=await Promise.resolve().then(()=>(ct(),Tn)),{startRun:g,endRun:v}=await Promise.resolve().then(()=>(Gn(),Yn)),E=g("connect","run"),y,$;try{let w=await p(f);y=w.browser,$=await y.newPage(),await h($,w)}catch(w){console.error(`
|
|
315
|
+
[!] ${w.message}
|
|
316
|
+
`);try{y&&await y.close()}catch{}try{v(E,"error",null,w.message)}catch{}process.exit(1)}let x=0;try{let w=Y(),R=new Map;for(let[j,K]of Object.entries(w)){let T=B(K.profileUrl||j);T&&!R.has(T)&&R.set(T,j)}for(let[j,K]of Object.entries(w))for(let T of K.aliases||[])T&&!R.has(T)&&R.set(T,j);let C=0,F=0,H=0,J=0;for(let j of l){if(!Ve().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let K=n&&j.withNote,T=await m($,j.url,{message:K?j.note:null,useCustomMessage:K,source:j.tag,skipQuotaGate:!0}),W;if(T.connectionSent?(W="sent",C++):Kn.has(T.reason)?(W="skipped",F++):(W="failed",H++),W==="failed"){J++;let _=await pi($,j,T.reason);console.log(` \u2717 ${j.url.slice(-32)} \u2014 ${T.reason||"failed"}${_?` \xB7 LinkedIn: "${_.slice(0,120)}"`:""}`)}else J=0;let ve=R.get(B(j.url));if(T.connectionSent||Kn.has(T.reason)&&ve){let _=ve||j.url;try{ot(_,T.reason,{method:T.method,messageSent:T.messageSent,profileInfo:T.profileInfo})}catch{}if(T.resolvedUrl)try{rt(_,T.resolvedUrl)}catch{}}try{let _=re(),O=He(_,j.url);O&&(O.status=W,W==="sent"&&(O.sentAt=Ft()),O.result=T.reason||T.error||W,ye(_))}catch(_){console.error(` \u26A0 Could not persist queue update for ${j.url}: ${_.message}`)}if(T.fatal){console.log(`
|
|
317
|
+
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(J>=fi){console.log(`
|
|
318
|
+
\u26A0 ${J} sends failed in a row \u2014 stopping to protect your account (this is often LinkedIn's invite limit).`),console.log(` What LinkedIn showed on each failure is saved to: ${dt}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await k(3e3+Math.random()*2e3)}let M=$e();console.log(`
|
|
319
|
+
=== Done: ${C} sent, ${F} skipped, ${H} failed ===`),console.log(`Connection quota left: ${M.daily.remaining}/${M.daily.max} today, ${M.weekly.remaining}/${M.weekly.max} week.`);try{v(E,"success",{sent:C,skipped:F,failed:H})}catch{}}catch(w){console.error(`
|
|
320
|
+
[!] Run aborted: ${w.message}`);try{v(E,"error",null,w.message)}catch{}x=1}finally{try{await y.close()}catch{}}process.exit(x)}function q(e){console.error(e),process.exit(1)}function $i(){console.log(`connect \u2014 connect queue
|
|
321
321
|
|
|
322
322
|
connect add <file.json> [--tag=X] [--priority=high|normal|low]
|
|
323
323
|
connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
@@ -325,4 +325,4 @@ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(y=>process.stdin
|
|
|
325
325
|
connect approve <url> | --all | --tag=X
|
|
326
326
|
connect note <url> "custom note" connect no-note <url>
|
|
327
327
|
connect skip <url> connect priority <url> <high|normal|low>
|
|
328
|
-
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var
|
|
328
|
+
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var Ci={add:mi,fill:hi,list:gi,approve:yi,skip:wi,note:bi,"no-note":Si,priority:ki,run:vi},to=Ci[Zn];to||($i(),process.exit(Zn?1:0));await bn();await to();
|