ilml-plugin-linkedin 1.14.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +3 -1
- package/dist/applyQueue.mjs +24 -24
- package/dist/connect.mjs +71 -68
- package/dist/daily.mjs +16 -16
- package/dist/enrichProfile.mjs +9 -9
- package/dist/enrichProfiles.mjs +32 -32
- package/dist/funnelRunner.mjs +36 -36
- package/dist/messageBot.mjs +55 -55
- package/dist/migrationCli.mjs +16 -16
- package/dist/profileHistory.mjs +5 -5
- package/dist/quota.mjs +3 -3
- package/dist/run.mjs +36 -36
- package/dist/scout.mjs +19 -19
- package/dist/syncAll.mjs +64 -64
- package/dist/verifyAbout.mjs +11 -11
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +22 -22
- package/dist/visit.mjs +26 -26
- package/dist/warmScan.mjs +3 -3
- package/ilml-plugin.json +13 -5
- package/package.json +1 -1
package/dist/connect.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(e,t)=>{for(var n in t)qn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Bn}from"@ilivemylife/graph-sdk";var Un,Wr,ge,Gr,Yr,at=ne(async()=>{Un=await Bn();for(let[e,t]of Object.entries(Un))process.env[e]===void 0&&(process.env[e]=t);Wr=process.env.LINKEDIN_NAME,ge=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Gr=Object.freeze(new Set([ge.DRAFT,ge.CONFIRMED,ge.NEEDS_REVIEW])),Yr=Object.freeze(new Set([ge.DRAFT,ge.CONFIRMED,ge.REJECTED,ge.NEEDS_REVIEW]))});import"dotenv/config";import*as j from"fs";import*as B from"path";import{fileURLToPath as Vn}from"url";function qt(){xe=null,Wn=null,oe=null,Gn=null,Yn=null,Qn=null}function Ye(){j.existsSync(re)||j.mkdirSync(re,{recursive:!0})}function _e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let r=0;r<3;r++)try{j.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let a=Date.now();for(;Date.now()-a<200;);continue}throw i}}function Oe(e,t){if(!j.existsSync(e))return null;try{let n=JSON.parse(j.readFileSync(e,"utf-8"));try{j.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(j.existsSync(o))try{let r=JSON.parse(j.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{j.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{j.copyFileSync(e,e+".corrupted")}catch{}return null}}function je(){return new Date().toISOString().split("T")[0]}function W(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Xn(){j.existsSync(ut)||j.mkdirSync(ut,{recursive:!0})}function Bt(e){let t=W(e);return t?B.join(ut,`${t}.json`):null}function Zn(e){let t=Bt(e);return t?Oe(t,`profile-history/${W(e)}.json`)||[]:[]}function eo(e,t){let n=Bt(e);if(!n)return;Xn();let o=Zn(e);o.unshift(t);try{_e(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${W(e)}: ${r.message}`)}}function Lt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Mt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function to(e,t){if(!e)return[];let n=[];for(let o of zn){let r=e[o],i=t[o];Lt(r)||Lt(i)||Mt(r)!==Mt(i)&&n.push(o)}return n}function no(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 H(){return xe||(Ye(),xe=Oe(ct,"people.json")||{},xe)}function dt(e){Ye(),xe=e;try{_e(ct,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(ct)}`)}}function Ge(e,t={}){if(!e)return null;let n=H(),o=je(),r=new Date().toISOString(),i=n[e];if(i){let a=to(i,t);a.length>0&&(eo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:no(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of Kn)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return dt(n),n[e]}function Ut(e,t){if(!e||!t)return;let n=H(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:je(),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(),dt(n))}function Vt(e){return e&&H()[e]?.connectionStatus||null}function Qe(e,t,n={}){if(!e)return;n.profileInfo?Ge(e,n.profileInfo):H()[e]||Ge(e,{});let o=H(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=je(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),dt(o))}function Jt(){return oe||(Ye(),oe=Oe(Pt,"quota.json"),(!oe||!oe.connections)&&(oe={connections:[]}),oe)}function oo(e){Ye(),oe=e;try{_e(Pt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ht(e,t="unknown"){let n=Jt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),oo(n)}function Wt(){let e=Jt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Fe(){let e=Wt(),t=je(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Te,i=o>=Ne,a=!r&&!i,u={allowed:a,daily:{sent:n,max:Te},weekly:{sent:o,max:Ne}};return a||(u.reason=r?`Daily limit reached (${n}/${Te})`:`Weekly limit reached (${o}/${Ne})`),u}function ye(){let e=Wt(),t=je(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Te,remaining:Te-n},weekly:{sent:o,max:Ne,remaining:Ne-o}}}var Jn,Hn,re,ct,Zr,Pt,es,ts,ns,ut,Te,Ne,xe,Wn,oe,Gn,Yn,Qn,Kn,zn,Le=ne(async()=>{await at();Jn=Vn(import.meta.url),Hn=B.dirname(B.dirname(Jn)),re=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Hn,"collected-profiles"),ct=B.join(re,"people.json"),Zr=B.join(re,"jobs.json"),Pt=B.join(re,"quota.json"),es=B.join(re,"conversations.json"),ts=B.join(re,"sync-state.json"),ns=B.join(re,"application-questions.json"),ut=B.join(re,"profile-history"),Te=20,Ne=100,xe=null,Wn=null,oe=null,Gn=null,Yn=null,Qn=null;Kn=["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"],zn=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var cn={};ce(cn,{cookiesExist:()=>nr,getCookiesPath:()=>et,loadCookies:()=>tr,saveCookies:()=>er});import Ee from"fs";import an from"path";function et(){let e=process.env.ILML_SCOPE_DIR;return e?an.join(e,"plugins-state","linkedin","cookies.json"):Xo}function Zo(){let e=et(),t=an.dirname(e);return t&&t!=="."&&!Ee.existsSync(t)&&Ee.mkdirSync(t,{recursive:!0}),e}function er(e){let t=Zo();return Ee.writeFileSync(t,JSON.stringify(e)),t}function tr(){let e=et();if(!Ee.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ee.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 nr(){return Ee.existsSync(et())}var Xo,un=ne(()=>{Xo="cookies.json"});var dn={};ce(dn,{cleanSearchName:()=>ar,delayed:()=>S,dismissPremiumOverlay:()=>me,ensureInboxPage:()=>ir,parseLinkedInTime:()=>sr,safeParseInt:()=>lr,stripDesignations:()=>cr,utilityFunction:()=>or});function or(){console.log("Utility function called...")}function qe(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function sr(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=qe(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=rr[o[1].toLowerCase()],s=qe(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=$t[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),l=parseInt(r[3],10),c=qe(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=$t[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),l=qe(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=$t[a[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(a[2],10),l=qe(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 S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ir(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 S(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 lr(e){return parseInt(e,10)||0}async function me(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 ar(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 cr(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 $t,rr,tt=ne(()=>{$t={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},rr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var fn={};ce(fn,{extractCertificationsFromDetails:()=>mr,extractEducationFromDetails:()=>fr,extractExperienceFromDetails:()=>ur,extractFeaturedFromDetails:()=>dr,extractRecommendationsFromDetails:()=>hr,extractSkillsFromDetails:()=>pr});async function ur(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let g=p.filter(h=>(h.textContent||"").trim().length>50);g.length<3||(f.textContent||"").length<500||d.push({el:f,count:g.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[1].split("\xB7").map(_=>_.trim());f=$[0]||null,$[1]&&(p=$[1])}let g=c.findIndex($=>/(\d{4}|present)/i.test($)&&/(-|–|—)/i.test($)&&$.length<80),h=null,w=null;if(g>=0){let $=c[g].split("\xB7").map(_=>_.trim());h=$[0]||null,$[1]&&(w=$[1])}let m=null,y=-1;if(g>=0&&c[g+1]){let $=c[g+1],_=/^[>*\-•]|^>/.test($),O=/https?:\/\//.test($),I=/\d{4}/.test($),q=/,/.test($)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test($);!_&&!O&&!I&&$.length<100&&q&&(m=$,y=g+1)}let k=null,C=-1,v=c[c.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){C=c.length-1;let $=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);$&&(k={listed:$[1].split(",").map(_=>_.trim()),additional:parseInt($[2],10)})}let T=new Set([0,1,g,y,C].filter($=>$>=0)),A=c.filter(($,_)=>!T.has(_)),U=A.length>0?A.join(`
|
|
1
|
+
var Jn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var n in t)Jn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Hn}from"@ilivemylife/graph-sdk";var Wn,Xr,Se,Zr,es,dt=re(async()=>{Wn=await Hn();for(let[e,t]of Object.entries(Wn))process.env[e]===void 0&&(process.env[e]=t);Xr=process.env.LINKEDIN_NAME,Se=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Zr=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.NEEDS_REVIEW])),es=Object.freeze(new Set([Se.DRAFT,Se.CONFIRMED,Se.REJECTED,Se.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as U from"path";import{fileURLToPath as Yn}from"url";function Jt(){Ee=null,Kn=null,se=null,zn=null,Xn=null,Zn=null}function ze(){F.existsSync(ie)||F.mkdirSync(ie,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let r=0;r<3;r++)try{F.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 Le(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${U.resolve(e)}`);let o=e+".backup";if(F.existsSync(o))try{let r=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.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{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function Me(){return new Date().toISOString().split("T")[0]}function Q(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function no(){F.existsSync(pt)||F.mkdirSync(pt,{recursive:!0})}function Ht(e){let t=Q(e);return t?U.join(pt,`${t}.json`):null}function oo(e){let t=Ht(e);return t?Le(t,`profile-history/${Q(e)}.json`)||[]:[]}function ro(e,t){let n=Ht(e);if(!n)return;no();let o=oo(e);o.unshift(t);try{Fe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${Q(e)}: ${r.message}`)}}function qt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Bt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function so(e,t){if(!e)return[];let n=[];for(let o of to){let r=e[o],i=t[o];qt(r)||qt(i)||Bt(r)!==Bt(i)&&n.push(o)}return n}function io(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 G(){return Ee||(ze(),Ee=Le(ft,"people.json")||{},Ee)}function mt(e){ze(),Ee=e;try{Fe(ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${U.resolve(ft)}`)}}function Ke(e,t={}){if(!e)return null;let n=G(),o=Me(),r=new Date().toISOString(),i=n[e];if(i){let a=so(i,t);a.length>0&&(ro(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:io(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of eo)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return mt(n),n[e]}function Wt(e,t){if(!e||!t)return;let n=G(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Me(),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(),mt(n))}function Yt(e){return e&&G()[e]?.connectionStatus||null}function Xe(e,t,n={}){if(!e)return;n.profileInfo?Ke(e,n.profileInfo):G()[e]||Ke(e,{});let o=G(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=Me(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),mt(o))}function Gt(){return se||(ze(),se=Le(Ut,"quota.json"),(!se||!se.connections)&&(se={connections:[]}),se)}function lo(e){ze(),se=e;try{Fe(Ut,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Qt(e,t="unknown"){let n=Gt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),lo(n)}function Kt(){let e=Gt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Pe(){let e=Kt(),t=Me(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Oe,i=o>=je,a=!r&&!i,u={allowed:a,daily:{sent:n,max:Oe},weekly:{sent:o,max:je}};return a||(u.reason=r?`Daily limit reached (${n}/${Oe})`:`Weekly limit reached (${o}/${je})`),u}function be(){let e=Kt(),t=Me(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Oe,remaining:Oe-n},weekly:{sent:o,max:je,remaining:je-o}}}var Gn,Qn,ie,ft,ss,Ut,is,ls,as,pt,Vt,Oe,je,Ee,Kn,se,zn,Xn,Zn,eo,to,qe=re(async()=>{await dt();Gn=Yn(import.meta.url),Qn=U.dirname(U.dirname(Gn)),ie=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"collected-profiles"):U.join(Qn,"collected-profiles"),ft=U.join(ie,"people.json"),ss=U.join(ie,"jobs.json"),Ut=U.join(ie,"quota.json"),is=U.join(ie,"conversations.json"),ls=U.join(ie,"sync-state.json"),as=U.join(ie,"application-questions.json"),pt=U.join(ie,"profile-history"),Vt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Oe=Vt(process.env.CONNECT_MAX_DAILY,20),je=Vt(process.env.CONNECT_MAX_WEEKLY,100),Ee=null,Kn=null,se=null,zn=null,Xn=null,Zn=null;eo=["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"],to=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var pn={};fe(pn,{cookiesExist:()=>ir,getCookiesPath:()=>ot,loadCookies:()=>sr,saveCookies:()=>rr});import Ie from"fs";import fn from"path";function ot(){let e=process.env.ILML_SCOPE_DIR;return e?fn.join(e,"plugins-state","linkedin","cookies.json"):nr}function or(){let e=ot(),t=fn.dirname(e);return t&&t!=="."&&!Ie.existsSync(t)&&Ie.mkdirSync(t,{recursive:!0}),e}function rr(e){let t=or();return Ie.writeFileSync(t,JSON.stringify(e)),t}function sr(){let e=ot();if(!Ie.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ie.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 ir(){return Ie.existsSync(ot())}var nr,mn=re(()=>{nr="cookies.json"});var hn={};fe(hn,{cleanSearchName:()=>fr,delayed:()=>S,dismissPremiumOverlay:()=>ye,ensureInboxPage:()=>ur,parseLinkedInTime:()=>cr,safeParseInt:()=>dr,stripDesignations:()=>pr,utilityFunction:()=>lr});function lr(){console.log("Utility function called...")}function Ve(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 cr(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=Ve(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=Ve(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=At[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),l=parseInt(r[3],10),c=Ve(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=At[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),l=Ve(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=At[a[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(a[2],10),l=Ve(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 S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ur(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 S(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 dr(e){return parseInt(e,10)||0}async function ye(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 fr(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 pr(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 At,ar,rt=re(()=>{At={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 gn={};fe(gn,{extractCertificationsFromDetails:()=>wr,extractEducationFromDetails:()=>gr,extractExperienceFromDetails:()=>mr,extractFeaturedFromDetails:()=>hr,extractRecommendationsFromDetails:()=>Sr,extractSkillsFromDetails:()=>yr});async function mr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function a(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(h=>h.tagName==="DIV");if(p.length<3)continue;let g=p.filter(h=>(h.textContent||"").trim().length>50);g.length<3||(f.textContent||"").length<500||d.push({el:f,count:g.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 v=c[1].split("\xB7").map(O=>O.trim());f=v[0]||null,v[1]&&(p=v[1])}let g=c.findIndex(v=>/(\d{4}|present)/i.test(v)&&/(-|–|—)/i.test(v)&&v.length<80),h=null,w=null;if(g>=0){let v=c[g].split("\xB7").map(O=>O.trim());h=v[0]||null,v[1]&&(w=v[1])}let m=null,y=-1;if(g>=0&&c[g+1]){let v=c[g+1],O=/^[>*\-•]|^>/.test(v),V=/https?:\/\//.test(v),N=/\d{4}/.test(v),j=/,/.test(v)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(v);!O&&!V&&!N&&v.length<100&&j&&(m=v,y=g+1)}let k=null,$=-1,D=c[c.length-1];if(D&&/and\s+\+\d+\s+skills?$/i.test(D)){$=c.length-1;let v=D.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);v&&(k={listed:v[1].split(",").map(O=>O.trim()),additional:parseInt(v[2],10)})}let C=new Set([0,1,g,y,$].filter(v=>v>=0)),I=c.filter((v,O)=>!C.has(O)),M=I.length>0?I.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:d,company:f,employmentType:p,dates:h,duration:w,location:m,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
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:d,company:f,employmentType:p,dates:h,duration:w,location:m,description:M,skills:k,_raw:c}}return s.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 Je(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let a=0;a<4;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)i++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function We(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function hr(e,t){return We(t,"featured","extractFeaturedFromDetails",async()=>(await Je(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${He}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(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 gr(e,t){return We(t,"education","extractEducationFromDetails",async()=>(await Je(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${He}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(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 yr(e,t){return We(t,"skills","extractSkillsFromDetails",async()=>(await Je(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${He}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function wr(e,t){return We(t,"certifications","extractCertificationsFromDetails",async()=>(await Je(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${He}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(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 Sr(e,t){return We(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Je(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${He}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var qn=Object.defineProperty;var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var ce=(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 He,yn=re(()=>{rt();He=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,86 +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 gn={};ce(gn,{clickConnectButton:()=>xt,default:()=>wr,detectConnectionStatus:()=>$e,findConnectButton:()=>Je,runFunnel:()=>hn,sendConnectionRequest:()=>Et,shouldExcludeLocation:()=>nt,viewProfile:()=>Ct});async function mn(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 S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function nt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Ct(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 S(3e3),await me(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await mn(e,t));let c=0;for(let k=0;k<2;k++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(A=>window.scrollTo(0,A),C*T/6),await S(900);let v=await e.evaluate(()=>document.body.scrollHeight);if(v===c)break;c=v}await S(800);let d=await e.evaluate(()=>{let k=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"]),C=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"]),v=x=>{let E=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(E)},T={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:[]},A=document.querySelector("main");if(!A)return T;let U=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],$=Array.from(A.querySelectorAll("h2")),_=U.find(x=>{let E=x.textContent&&x.textContent.trim(),D=(E||"").replace(/\s*\(\d+\)$/,"").trim();return E&&E.length>1&&E.length<100&&!k.has(D)&&!C.has(D)}),O=_?_.textContent.trim():null,I=_?_.parentElement:null;for(;I&&I!==A&&!Array.from(I.children).filter(E=>E.tagName==="P").some(E=>{let D=E.textContent&&E.textContent.trim();return D&&D.length>5&&!v(D)});)I=I.parentElement;let q=null,V=null,X=null,Ce=null;if(I&&I!==A){let x=Array.from(I.children).filter(D=>D.tagName==="P").filter(D=>{let ae=D.textContent&&D.textContent.trim();return ae&&ae.length>5&&!v(ae)});if(x[0]&&(q=x[0].textContent.trim()),x[1]){let D=x[1].textContent.trim().split(/\s*[·•]\s*/);V=D[0]||null,D.length>1&&(X=D.slice(1).join(" \xB7 "))}let E=Array.from(I.children).filter(D=>D.tagName==="DIV");for(let D=E.length-1;D>=0;D--){let ae=E[D].textContent&&E[D].textContent.trim();if(ae&&!(O&&ae.startsWith(O))&&(Ce=ae.split(/[·•]/)[0].trim(),Ce))break}}let He=null;if(I){let x=I.querySelectorAll("p, span, div");for(let E of x){let D=(E.textContent||"").trim().replace(/^[·•]\s*/,"");if(D==="1st"||D==="2nd"||D==="3rd"){He=D;break}}}let it=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),N=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),L=N&&N.src||null,M=A.textContent||"",P=null,Z=M.match(/(\d+\+?)\s+connections\b/i);Z&&(P=Z[1]+" connections");let We=null,Rt=M.match(/(\d+)\s+mutual connection/i),Tt=M.match(/and\s+(\d+)\s+other mutual/i),jn=M.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Rt?We=parseInt(Rt[1],10):Tt?We=2+parseInt(Tt[1],10):jn&&(We=2);let Nt=null,_t=null,Ot=$.find(x=>x.textContent&&x.textContent.trim()==="About");if(Ot){let x=Ot.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let E=(x.textContent||"").trim();E=E.replace(/^About\s*/,"").trim();let D=E.match(/Top skills\s*(.+?)$/i);if(D){let lt=D[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Pn=>Pn.trim()).filter(Boolean);lt.length>0&<.length<10&&(_t=lt)}E=E.split(/\n?…\s*more/i)[0].trim(),E=E.split(/\n?\.\.\.\s*more/i)[0].trim(),E=E.split(/\bTop skills\b/i)[0].trim(),E=E.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Nt=E||null}}let jt=null,Ft=$.find(x=>x.textContent&&x.textContent.trim()==="Activity");if(Ft){let x=Ft.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let E=(x.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);E&&(jt=parseInt(E[1].replace(/,/g,""),10))}}let Fn=[...new Set($.map(x=>(x.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(x=>x&&x.length>1&&x.length<60&&x!==O).filter(x=>k.has(x)))],Re=document.body.textContent||"",Ln=/#OpenToWork\b/i.test(Re)||/\bOpen to work\b/.test(Re),Mn=/#Hiring\b/i.test(Re)||/\bI'?m hiring\b/i.test(Re)||/\bWe are hiring\b/i.test(Re);return{name:O,title:q,location:Ce,currentCompany:V,currentSchool:X,connectionDegree:He,hasVerifiedBadge:it,photoUrl:L,connectionsLevel:P,mutualConnectionsCount:We,followers:jt,openToWork:Ln,hiring:Mn,about:Nt,topSkills:_t,availableSections:Fn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,g=null,h=null,w=null,m=null;if(o||r||i||a||u||s){let k=await Promise.resolve().then(()=>(pn(),fn));o&&(f=await k.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await k.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(g=await k.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),a&&(h=await k.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),u&&(w=await k.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),s&&(m=await k.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${m.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...g!==null&&{education:g},...h!==null&&{skillsFull:h},...w!==null&&{recommendations:w},...m!==null&&{certifications:m}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function $e(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(s=>s.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),a={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!r,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:a}:r&&!i?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Je(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=null,g=null;for(let h of d){let w=h.getBoundingClientRect();if(w.width===0||w.height===0)continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=h;break}g||(g=h)}return p||g||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(h=>{let w=h.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&f.test(w)}).map(h=>h.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 g of f){let h=g.getAttribute("aria-label")||"";if((h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&p.test(h))return g}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"),g=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(c.getAttribute("aria-label")||"").toLowerCase(),w=h.includes("invite"),m=d?h.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:g,hasInvite:w,matchesName:m,ariaLabel:h}},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(),g=f.getAttribute("aria-label")||"",h=f.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||g.includes("Follow")||g.includes("Message")||g.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 S(500),await e.evaluate(c=>c.click(),a),await S(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 g of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}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 g of p.querySelectorAll('[role="menuitem"], a, div')){let h=g.innerText?.trim();h&&h.length<40&&f.push(h)}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 xt(e,t){await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(l=>({tag:l.tagName,ariaLabel:l.getAttribute("aria-label"),href:l.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await S(2e3);let l=e.url();if(l.includes("premium")||l.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(l=>l.click(),t),await S(3e3)):(await e.evaluate(l=>l.click(),t),await S(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),s=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${s}`:` \u26A0 No modal after connect click \u2014 ${s}`),"success"}async function gr(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await Je(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Et(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Fe();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 yr(e,t,n);return a.connectionSent&&!i&&Ht(t,o),a}async function yr(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};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
-
--- Connecting: ${l} ---`),u.length>0){let m=H()[t]?.location;if(nt(m,u))return console.log(` \u26A0 Excluded location (stored): ${m}`),s.reason="excluded_location",s.profileInfo={location:m},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await me(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await mn(e,t),await S(2e3)),s.profileInfo=await e.evaluate(()=>{let m=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"]),y=N=>{let L=(N||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},k={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return k;let v=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],T=Array.from(C.querySelectorAll("h2")),A=v.find(N=>{let L=N.textContent&&N.textContent.trim();return L&&L.length>1&&L.length<100&&!m.has(L)&&L!=="0 notifications"}),U=A?A.textContent.trim():null,$=A?A.parentElement:null;for(;$&&$!==C&&!Array.from($.children).filter(M=>M.tagName==="P").some(M=>{let P=M.textContent&&M.textContent.trim();return P&&P.length>5&&!y(P)});)$=$.parentElement;let _=null,O=null,I=null;if($&&$!==C){let N=Array.from($.children),L=N.filter(P=>P.tagName==="P").filter(P=>{let Z=P.textContent&&P.textContent.trim();return Z&&Z.length>5&&!y(Z)});L[0]&&(_=L[0].textContent.trim()),L[1]&&(O=L[1].textContent.trim());let M=N.filter(P=>P.tagName==="DIV");for(let P=M.length-1;P>=0;P--){let Z=M[P].textContent&&M[P].textContent.trim();if(Z&&!(U&&Z.startsWith(U))&&(I=Z.split(/[·•]/)[0].trim(),I))break}}let q=null;if($){let N=$.querySelectorAll("p, span, div");for(let L of N){let M=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){q=M;break}}}let V=null,X=T.find(N=>N.textContent&&N.textContent.trim()==="About");if(X){let N=X.parentElement;for(;N&&N.tagName!=="SECTION";)N=N.parentElement;N&&(V=(N.textContent||"").trim().replace(/^About\s*/,"").trim()||null,V&&(V=V.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Ce=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),He=Ce&&Ce.src||null,it=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:U,title:_,location:I,about:V,company:O,connectionDegree:q,connectionsCount:null,mutualConnections:null,photoUrl:He,hasVerifiedBadge:it}}),u.length>0){let m=s.profileInfo?.location,y=H()[t]?.location,k=m||y;if(nt(k,u))return console.log(` \u26A0 Excluded location (${m?"live":"stored"}): ${k}`),s.reason="excluded_location",s;!m&&y==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await $e(e);if(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 me(e);let f=await Je(e);if(!f&&(await me(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),f=await Je(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;if(s.method=f.method,await xt(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let m=await $e(e);if(m==="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: ${m} \u2014 trying More dropdown...`),await me(e),await S(1e3);let y=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(y)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),y),await S(500),await y.click().catch(()=>e.evaluate(C=>C.click(),y)),await S(2e3);let k=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(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),k),await S(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),s.reason="premium_required",s;if(await $e(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 S(500),s.reason="premium_required",s}catch(k){return console.log(" More dropdown failed:",k.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 m=await e.$('button[aria-label="Dismiss"]');return m&&await m.click(),await S(500),s.reason="email_required",s}let h=await e.$('button[aria-label="Add a note"]'),w=await e.$('button[aria-label="Send without a note"]');if(!h&&!w){let m=await e.evaluate(()=>{let y=document.querySelector("#interop-outlet")?.shadowRoot;if(!y)return{addNote:!1,sendWithout:!1};let k=y.querySelector('button[aria-label="Add a note"]'),C=y.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!C}});if(m.addNote){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=y?.asElement?.()||null,h||await y.dispose().catch(()=>{})}if(m.sendWithout){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));w=y?.asElement?.()||null,w||await y.dispose().catch(()=>{})}}if(r){if(h&&o){if(console.log(" Adding personalized note..."),await h.click(),await S(1500),await e.$("div.modal-upsell")){let k=await gr(e);return s.success=k,s.connectionSent=k,s.reason=k?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let y=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(y){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",k);await y.type(C,{delay:20}),await S(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v){try{await v.evaluate(T=>T.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=C,s}}}else if(w){console.log(" Sending without note...");try{await w.evaluate(m=>m.click())}catch{console.log(" Click timeout, likely still sent")}return await S(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(h&&!o){console.log(" No message provided, sending without note...");let m=await e.$('button[aria-label="Send without a note"]');if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(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 m=w;if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(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 S(4e3)),await me(e),await S(500);let y=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let C of y){let v=await e.evaluate(T=>{let A=T.getBoundingClientRect();return{visible:A.width>0&&A.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},C);if(v.visible&&!v.inSticky){k=C;break}}!k&&y.length>0&&(k=y[y.length-1]);for(let C of y)C!==k&&await C.dispose().catch(()=>{});if(k)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),k),await S(500),await k.click().catch(()=>e.evaluate(v=>v.click(),k)),await S(2e3);let C=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(C){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(U=>U.click(),C),await S(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await $e(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 $e(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 A=await e.$('button[aria-label="Send without a note"]');if(A){console.log(" Modal appeared via More dropdown, sending without note...");try{await A.evaluate(U=>U.click())}catch{}return await S(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(C){console.log(" More dropdown fallback failed:",C.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 S(1e3)}catch{s.fatal=!0}return s}}async function hn(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 ${i})`}`),a||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!a){let p=
|
|
238
|
+
`});var bn={};fe(bn,{clickConnectButton:()=>It,default:()=>vr,detectConnectionStatus:()=>Ae,findConnectButton:()=>Ye,runFunnel:()=>Sn,sendConnectionRequest:()=>Dt,shouldExcludeLocation:()=>st,viewProfile:()=>Et});async function wn(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 S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function st(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Et(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 S(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await wn(e,t));let c=0;for(let k=0;k<2;k++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(I=>window.scrollTo(0,I),$*C/6),await S(900);let D=await e.evaluate(()=>document.body.scrollHeight);if(D===c)break;c=D}await S(800);let d=await e.evaluate(()=>{let k=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"]),D=x=>{let A=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(A)},C={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},I=document.querySelector("main");if(!I)return C;let M=[...Array.from(I.querySelectorAll("h1")),...Array.from(I.querySelectorAll("h2"))],v=Array.from(I.querySelectorAll("h2")),O=M.find(x=>{let A=x.textContent&&x.textContent.trim(),E=(A||"").replace(/\s*\(\d+\)$/,"").trim();return A&&A.length>1&&A.length<100&&!k.has(E)&&!$.has(E)}),V=O?O.textContent.trim():null,N=O?O.parentElement:null;for(;N&&N!==I&&!Array.from(N.children).filter(A=>A.tagName==="P").some(A=>{let E=A.textContent&&A.textContent.trim();return E&&E.length>5&&!D(E)});)N=N.parentElement;let j=null,W=null,_=null,J=null;if(N&&N!==I){let x=Array.from(N.children).filter(E=>E.tagName==="P").filter(E=>{let de=E.textContent&&E.textContent.trim();return de&&de.length>5&&!D(de)});if(x[0]&&(j=x[0].textContent.trim()),x[1]){let E=x[1].textContent.trim().split(/\s*[·•]\s*/);W=E[0]||null,E.length>1&&(_=E.slice(1).join(" \xB7 "))}let A=Array.from(N.children).filter(E=>E.tagName==="DIV");for(let E=A.length-1;E>=0;E--){let de=A[E].textContent&&A[E].textContent.trim();if(de&&!(V&&de.startsWith(V))&&(J=de.split(/[·•]/)[0].trim(),J))break}}let H=null;if(N){let x=N.querySelectorAll("p, span, div");for(let A of x){let E=(A.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){H=E;break}}}let ue=!!I.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=T&&T.src||null,q=I.textContent||"",B=null,te=q.match(/(\d+\+?)\s+connections\b/i);te&&(B=te[1]+" connections");let Qe=null,_t=q.match(/(\d+)\s+mutual connection/i),Ot=q.match(/and\s+(\d+)\s+other mutual/i),Pn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);_t?Qe=parseInt(_t[1],10):Ot?Qe=2+parseInt(Ot[1],10):Pn&&(Qe=2);let jt=null,Ft=null,Lt=v.find(x=>x.textContent&&x.textContent.trim()==="About");if(Lt){let x=Lt.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let A=(x.textContent||"").trim();A=A.replace(/^About\s*/,"").trim();let E=A.match(/Top skills\s*(.+?)$/i);if(E){let ut=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Vn=>Vn.trim()).filter(Boolean);ut.length>0&&ut.length<10&&(Ft=ut)}A=A.split(/\n?…\s*more/i)[0].trim(),A=A.split(/\n?\.\.\.\s*more/i)[0].trim(),A=A.split(/\bTop skills\b/i)[0].trim(),A=A.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),jt=A||null}}let Mt=null,Pt=v.find(x=>x.textContent&&x.textContent.trim()==="Activity");if(Pt){let x=Pt.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let A=(x.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);A&&(Mt=parseInt(A[1].replace(/,/g,""),10))}}let qn=[...new Set(v.map(x=>(x.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(x=>x&&x.length>1&&x.length<60&&x!==V).filter(x=>k.has(x)))],_e=document.body.textContent||"",Bn=/#OpenToWork\b/i.test(_e)||/\bOpen to work\b/.test(_e),Un=/#Hiring\b/i.test(_e)||/\bI'?m hiring\b/i.test(_e)||/\bWe are hiring\b/i.test(_e);return{name:V,title:j,location:J,currentCompany:W,currentSchool:_,connectionDegree:H,hasVerifiedBadge:ue,photoUrl:P,connectionsLevel:B,mutualConnectionsCount:Qe,followers:Mt,openToWork:Bn,hiring:Un,about:jt,topSkills:Ft,availableSections:qn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,g=null,h=null,w=null,m=null;if(o||r||i||a||u||s){let k=await Promise.resolve().then(()=>(yn(),gn));o&&(f=await k.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await k.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(g=await k.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),a&&(h=await k.extractSkillsFromDetails(e,t),console.log(` + Skills: ${h.length} entries`)),u&&(w=await k.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),s&&(m=await k.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${m.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...g!==null&&{education:g},...h!==null&&{skillsFull:h},...w!==null&&{recommendations:w},...m!==null&&{certifications:m}}}catch(l){console.error(`Error viewing profile ${t}:`,l.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(l.message||""))throw l;return null}}async function Ae(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(s=>s.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),a={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!r,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:a}:r&&!i?{status:"connected",debug:a}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:a}:{status:"not_connected",debug:a}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ye(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=null,g=null;for(let h of d){let w=h.getBoundingClientRect();if(w.width===0||w.height===0)continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f)){p=h;break}g||(g=h)}return p||g||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(h=>{let w=h.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&f.test(w)}).map(h=>h.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 g of f){let h=g.getAttribute("aria-label")||"";if((h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&p.test(h))return g}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"),g=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,h=(c.getAttribute("aria-label")||"").toLowerCase(),w=h.includes("invite"),m=d?h.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:g,hasInvite:w,matchesName:m,ariaLabel:h}},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(),g=f.getAttribute("aria-label")||"",h=f.getBoundingClientRect();return h.top<100||h.top>600||h.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||g.includes("Follow")||g.includes("Message")||g.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 S(500),await e.evaluate(c=>c.click(),a),await S(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 g of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}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 g of p.querySelectorAll('[role="menuitem"], a, div')){let h=g.innerText?.trim();h&&h.length<40&&f.push(h)}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 It(e,t){await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(l=>({tag:l.tagName,ariaLabel:l.getAttribute("aria-label"),href:l.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(c=>c.click(),t)]),await S(2e3);let l=e.url();if(l.includes("premium")||l.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(l=>l.click(),t),await S(3e3)):(await e.evaluate(l=>l.click(),t),await S(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),s=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${s}`:` \u26A0 No modal after connect click \u2014 ${s}`),"success"}async function br(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await Ye(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Dt(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Pe();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 kr(e,t,n);return a.connectionSent&&!i&&Qt(t,o),a}async function kr(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};try{let l=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
239
|
+
--- Connecting: ${l} ---`),u.length>0){let m=G()[t]?.location;if(st(m,u))return console.log(` \u26A0 Excluded location (stored): ${m}`),s.reason="excluded_location",s.profileInfo={location:m},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await wn(e,t),await S(2e3)),s.profileInfo=await e.evaluate(()=>{let m=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"]),y=T=>{let P=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},k={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},$=document.querySelector("main");if(!$)return k;let D=[...Array.from($.querySelectorAll("h1")),...Array.from($.querySelectorAll("h2"))],C=Array.from($.querySelectorAll("h2")),I=D.find(T=>{let P=T.textContent&&T.textContent.trim();return P&&P.length>1&&P.length<100&&!m.has(P)&&P!=="0 notifications"}),M=I?I.textContent.trim():null,v=I?I.parentElement:null;for(;v&&v!==$&&!Array.from(v.children).filter(q=>q.tagName==="P").some(q=>{let B=q.textContent&&q.textContent.trim();return B&&B.length>5&&!y(B)});)v=v.parentElement;let O=null,V=null,N=null;if(v&&v!==$){let T=Array.from(v.children),P=T.filter(B=>B.tagName==="P").filter(B=>{let te=B.textContent&&B.textContent.trim();return te&&te.length>5&&!y(te)});P[0]&&(O=P[0].textContent.trim()),P[1]&&(V=P[1].textContent.trim());let q=T.filter(B=>B.tagName==="DIV");for(let B=q.length-1;B>=0;B--){let te=q[B].textContent&&q[B].textContent.trim();if(te&&!(M&&te.startsWith(M))&&(N=te.split(/[·•]/)[0].trim(),N))break}}let j=null;if(v){let T=v.querySelectorAll("p, span, div");for(let P of T){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){j=q;break}}}let W=null,_=C.find(T=>T.textContent&&T.textContent.trim()==="About");if(_){let T=_.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(W=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,W&&(W=W.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let J=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=J&&J.src||null,ue=!!$.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:M,title:O,location:N,about:W,company:V,connectionDegree:j,connectionsCount:null,mutualConnections:null,photoUrl:H,hasVerifiedBadge:ue}}),u.length>0){let m=s.profileInfo?.location,y=G()[t]?.location,k=m||y;if(st(k,u))return console.log(` \u26A0 Excluded location (${m?"live":"stored"}): ${k}`),s.reason="excluded_location",s;!m&&y==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ae(e);if(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 ye(e);let f=await Ye(e);if(!f&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),f=await Ye(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;if(s.method=f.method,await It(e,f.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let m=await Ae(e);if(m==="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: ${m} \u2014 trying More dropdown...`),await ye(e),await S(1e3);let y=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(y)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),y),await S(500),await y.click().catch(()=>e.evaluate($=>$.click(),y)),await S(2e3);let k=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(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),k),await S(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),s.reason="premium_required",s;if(await Ae(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 S(500),s.reason="premium_required",s}catch(k){return console.log(" More dropdown failed:",k.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 m=await e.$('button[aria-label="Dismiss"]');return m&&await m.click(),await S(500),s.reason="email_required",s}let h=await e.$('button[aria-label="Add a note"]'),w=await e.$('button[aria-label="Send without a note"]');if(!h&&!w){let m=await e.evaluate(()=>{let y=document.querySelector("#interop-outlet")?.shadowRoot;if(!y)return{addNote:!1,sendWithout:!1};let k=y.querySelector('button[aria-label="Add a note"]'),$=y.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!$}});if(m.addNote){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));h=y?.asElement?.()||null,h||await y.dispose().catch(()=>{})}if(m.sendWithout){let y=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));w=y?.asElement?.()||null,w||await y.dispose().catch(()=>{})}}if(r){if(h&&o){if(console.log(" Adding personalized note..."),await h.click(),await S(1500),await e.$("div.modal-upsell")){let k=await br(e);return s.success=k,s.connectionSent=k,s.reason=k?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let y=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(y){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),$=o.replace("{name}",k);await y.type($,{delay:20}),await S(500);let D=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(D){try{await D.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=$,s}}}else if(w){console.log(" Sending without note...");try{await w.evaluate(m=>m.click())}catch{console.log(" Click timeout, likely still sent")}return await S(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(h&&!o){console.log(" No message provided, sending without note...");let m=await e.$('button[aria-label="Send without a note"]');if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(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 m=w;if(m){try{await m.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await S(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 S(4e3)),await ye(e),await S(500);let y=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let $ of y){let D=await e.evaluate(C=>{let I=C.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},$);if(D.visible&&!D.inSticky){k=$;break}}!k&&y.length>0&&(k=y[y.length-1]);for(let $ of y)$!==k&&await $.dispose().catch(()=>{});if(k)try{await e.evaluate(D=>D.scrollIntoView({behavior:"smooth",block:"center"}),k),await S(500),await k.click().catch(()=>e.evaluate(D=>D.click(),k)),await S(2e3);let $=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($){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(M=>M.click(),$),await S(3e3);let D=e.url();if(D.includes("/premium/")||D.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await Ae(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 Ae(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 I=await e.$('button[aria-label="Send without a note"]');if(I){console.log(" Modal appeared via More dropdown, sending without note...");try{await I.evaluate(M=>M.click())}catch{}return await S(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($){console.log(" More dropdown fallback failed:",$.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 S(1e3)}catch{s.fatal=!0}return s}}async function Sn(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 ${i})`}`),a||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),l.length>0&&console.log(`Excluding locations: ${l.join(", ")}`),!a){let p=be();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 g=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(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=
|
|
242
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let h=Yt(g.profileUrl);if(h==="pending"||h==="connected"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${h})`),h==="pending"||h==="sent_with_note"||h==="sent_without_note"||h==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(g,d,{success:!1,reason:h,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl}`);let w=null;if(a){let m=await Et(e,g.profileUrl);m?(Ke(g.profileUrl,{...m,source:c}),d.viewed++,w={success:!0,reason:"viewed",connectionSent:!1,profileInfo:m}):(d.errors++,w={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let m=Pe();if(!m.allowed){console.log(` \u26A0 Global quota exhausted: ${m.reason}`);break}if(w=await Dt(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:l,source:c,skipQuotaGate:!0}),w.success)d.connectionsSent++;else switch(w.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(w?.fatal){console.log(`
|
|
243
243
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(w?.reason==="error"){if(f++,f>=3){console.log(`
|
|
244
|
-
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(w&&w.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(w&&w.reason&&(Xe(g.profileUrl,w.reason,{method:w.method,messageSent:w.messageSent,profileInfo:w.profileInfo}),Wt(g.profileUrl,{source:c||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:w.reason})),s&&await s(g,d,w),p<t.length-1){let m=u+Math.random()*2e3;await S(m)}}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=be();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}var vr,kn=re(async()=>{rt();await qe();vr={viewProfile:Et,detectConnectionStatus:Ae,findConnectButton:Ye,clickConnectButton:It,sendConnectionRequest:Dt,runFunnel:Sn,shouldExcludeLocation:st}});import{createGraphClient as $r,resolveToken as Cr}from"@ilivemylife/graph-sdk";import{config as xr}from"dotenv";var vn,$n,Cn=re(()=>{xr();vn=Cr()||process.env.TOKEN;vn||(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));$n=$r({token:vn})});import"dotenv/config";function Ar(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 Er({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",a=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${Ar(r)}`:"",s=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",l=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${l} \u2014 ${s} \u2014 ${a}${u}`}async function xn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let a=process.env.NODE_RUN_REPORTS;if(!a||!Array.isArray(o)||o.length===0)return;let s=`**${Er({scriptName:e,mode:t,status:n,error:r,duration:i})}**
|
|
250
250
|
|
|
251
251
|
${o.join(`
|
|
252
|
-
`)}`;try{await
|
|
253
|
-
`)}var xr,Er,At,It,An=ne(()=>{vn();xr=Cr(import.meta.url),Er=he.dirname(he.dirname(xr)),At=process.env.DATA_DIR?he.resolve(process.env.DATA_DIR,"collected-profiles"):he.join(Er,"collected-profiles"),It=he.join(At,"run-log.json")});await at();await Le();import"dotenv/config";import*as Ke from"fs";import*as ue from"path";import{fileURLToPath as ro}from"url";var so=ro(import.meta.url),io=ue.dirname(ue.dirname(so)),ft=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(io,"collected-profiles"),Yt=ue.join(ft,"connect-queue.json"),lo=1,we=300,ze=["queued","approved","sent","skipped","failed"],de=["high","normal","low"],Gt={high:0,normal:1,low:2};function ao(){Ke.existsSync(ft)||Ke.mkdirSync(ft,{recursive:!0})}function pt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=we?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:de.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:ze.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ee(){let e=Oe(Yt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(pt).filter(n=>n.url):[]}function fe(e){ao(),_e(Yt,{version:lo,entries:e.map(pt)})}function se(e){return W(e)||(e||"").trim().toLowerCase()}function Me(e,t){let n=se(t);return e.find(o=>se(o.url)===n)||null}function mt(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=>se(l.url)));for(let l of t){let c=l?.url;if(!c){u.skippedNoUrl++;continue}let d=se(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>we&&u.notesTooLong++;let p=f.length>0&&f.length<=we;e.push(pt({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 Qt(e){return[...e].sort((t,n)=>{let o=(Gt[t.priority]??1)-(Gt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function Se(e,t){return e.filter(n=>n.status===t)}await Le();import"dotenv/config";import*as b from"fs";import*as kt from"os";import*as R from"path";import{fileURLToPath as jo}from"url";var yt={};ce(yt,{NAME:()=>uo,VERSION:()=>co,up:()=>mo});import*as Y from"fs";import*as Xe from"path";var co=1,uo="normalize-jobs-and-questions",fo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],po=50;function ht(e){return Y.existsSync(e)?JSON.parse(Y.readFileSync(e,"utf-8")):null}function gt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function mo(e,t){let n=Xe.join(e,"jobs.json"),o=Xe.join(t,"scouted-jobs.json"),r=Xe.join(e,"application-questions.json"),i=ht(n)||{},a=ht(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 fo)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(gt(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=ht(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 g=(f.questions||[]).map(h=>{let w={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=po?w.options=h.options:(w.optionsOmitted=!0,d++)),h.page&&(w.page=h.page),h.wasPreFilled&&(w.wasPreFilled=!0),h.wasRetry&&(w.wasRetry=!0),w});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||g.length,questions:g})}gt(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];gt(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 wt={};ce(wt,{NAME:()=>go,VERSION:()=>ho,up:()=>So});import*as Q from"fs";import*as Kt from"path";var ho=2,go="reset-unread-flags";function yo(e){return Q.existsSync(e)?JSON.parse(Q.readFileSync(e,"utf-8")):null}function wo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Q.writeFileSync(o,n)}catch(r){try{Q.unlinkSync(o)}catch{}throw r}try{Q.renameSync(o,e)}catch(r){try{Q.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 So(e){let t=Kt.join(e,"conversations.json"),n=yo(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}wo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var St={};ce(St,{NAME:()=>ko,VERSION:()=>bo,up:()=>Eo});import*as K from"fs";import*as zt from"path";var bo=3,ko="recompute-last-message-by",vo=new Set(["draft","confirmed","rejected","needs_review"]);function $o(e){return K.existsSync(e)?JSON.parse(K.readFileSync(e,"utf-8")):null}function Co(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{K.writeFileSync(o,n)}catch(r){try{K.unlinkSync(o)}catch{}throw r}try{K.renameSync(o,e)}catch(r){try{K.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function xo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!vo.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 Eo(e){let t=zt.join(e,"conversations.json"),n=$o(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=xo(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}Co(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.")}await Le();import"dotenv/config";import*as G from"path";import{fileURLToPath as Ao}from"url";var Io=Ao(import.meta.url),Do=G.dirname(G.dirname(Io)),Pe=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"market-research"):G.join(Do,"market-research"),ds=G.join(Pe,"scouted-jobs.json"),fs=G.join(Pe,"discovered-people.json"),ps=G.join(Pe,"visit-log.json"),ms=G.join(Pe,"companies.json"),hs=G.join(Pe,"job-decisions.json");function Xt(){Ro=null,To=null,No=null,_o=null,Oo=null}var Ro=null;var To=null;var No=null;var _o=null;var Oo=null;var Fo=jo(import.meta.url),Lo=R.dirname(Fo),Mo=R.dirname(R.dirname(Lo));function Po(e){return e&&(e==="~"?kt.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(kt.homedir(),e.slice(2)):e)}var te=process.env.DATA_DIR?R.resolve(Po(process.env.DATA_DIR)):Mo,ke=R.join(te,"collected-profiles"),ve=R.join(te,"market-research"),J=R.join(te,".schema-version"),Zt=[R.join(ke,".schema-version"),R.join(ve,".schema-version")],pe=3,ie=[{version:1,module:yt},{version:2,module:wt},{version:3,module:St}];(function(){ie.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ie){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ie.length?ie[ie.length-1].version:0;if(n!==pe)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${pe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ie.length;o++){let r=o+1;if(ie[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ie[o].version}`)}})();function on(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
252
|
+
`)}`;try{await $n.addMessage(a,s)}catch(l){console.error(`[runReport] Failed to post end-of-session message: ${l.message}`)}}var An=re(()=>{Cn()});var Rn={};fe(Rn,{endRun:()=>_r,formatScriptStatus:()=>Fr,getLastRun:()=>jr,getRunHistory:()=>Or,getTodayRunSummary:()=>In,startRun:()=>Nr,timeAgo:()=>Dn});import"dotenv/config";import*as ee from"fs";import*as we from"path";import{fileURLToPath as Ir}from"url";function Tr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let r=0;r<3;r++)try{ee.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 De(){try{if(!ee.existsSync(Tt))return{runs:[]};let e=JSON.parse(ee.readFileSync(Tt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function En(e){ee.existsSync(Rt)||ee.mkdirSync(Rt,{recursive:!0});try{Tr(Tt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Nr(e,t="default"){let n=De();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 i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(a=>new Date(a.timestamp).getTime()>i),En(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function _r(e,t,n=null,o=null){if(!e)return;let r=null;try{let a=De(),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 s=a.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}En(a)}catch(a){console.error(`[runLog] Failed to end run: ${a.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let a=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";xn({scriptName:e.script,mode:e.mode,status:a,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function Or(e=7){let t=De(),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 jr(e=null){let t=De(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function In(){let e=new Date().toISOString().slice(0,10),t=De(),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 Dn(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 Fr(){let e=["sync-all","messages","funnel","sync","apply"],t=De(),n=In(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let a=t.runs.filter(h=>h.script===i),u=[...a].reverse().find(h=>h.status==="success"),s=a[a.length-1],l=u||s,c=l?Dn(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 h=l.stats,w=Object.entries(h).filter(([,m])=>typeof m=="number"&&m>0).slice(0,3).map(([m,y])=>`${y} ${m}`);w.length&&(p=` (${w.join(", ")})`)}let g=l?.duration?` ${Math.round(l.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${c.padEnd(16)}${g}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[i,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: ${i} \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 Dr,Rr,Rt,Tt,Tn=re(()=>{An();Dr=Ir(import.meta.url),Rr=we.dirname(we.dirname(Dr)),Rt=process.env.DATA_DIR?we.resolve(process.env.DATA_DIR,"collected-profiles"):we.join(Rr,"collected-profiles"),Tt=we.join(Rt,"run-log.json")});import*as at from"fs";import*as Re from"path";await dt();await qe();import"dotenv/config";import*as Ze from"fs";import*as pe from"path";import{fileURLToPath as ao}from"url";var co=ao(import.meta.url),uo=pe.dirname(pe.dirname(co)),ht=process.env.DATA_DIR?pe.resolve(process.env.DATA_DIR,"collected-profiles"):pe.join(uo,"collected-profiles"),Xt=pe.join(ht,"connect-queue.json"),fo=1,ke=300,et=["queued","approved","sent","skipped","failed"],me=["high","normal","low"],zt={high:0,normal:1,low:2};function po(){Ze.existsSync(ht)||Ze.mkdirSync(ht,{recursive:!0})}function gt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ke?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:me.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:et.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ne(){let e=Le(Xt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(gt).filter(n=>n.url):[]}function he(e){po(),Fe(Xt,{version:fo,entries:e.map(gt)})}function le(e){return Q(e)||(e||"").trim().toLowerCase()}function Be(e,t){let n=le(t);return e.find(o=>le(o.url)===n)||null}function yt(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=>le(l.url)));for(let l of t){let c=l?.url;if(!c){u.skippedNoUrl++;continue}let d=le(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>ke&&u.notesTooLong++;let p=f.length>0&&f.length<=ke;e.push(gt({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 Zt(e){return[...e].sort((t,n)=>{let o=(zt[t.priority]??1)-(zt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ve(e,t){return e.filter(n=>n.status===t)}await qe();import"dotenv/config";import*as b from"fs";import*as Ct from"os";import*as R from"path";import{fileURLToPath as Po}from"url";var bt={};fe(bt,{NAME:()=>ho,VERSION:()=>mo,up:()=>wo});import*as z from"fs";import*as tt from"path";var mo=1,ho="normalize-jobs-and-questions",go=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],yo=50;function wt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function St(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 wo(e,t){let n=tt.join(e,"jobs.json"),o=tt.join(t,"scouted-jobs.json"),r=tt.join(e,"application-questions.json"),i=wt(n)||{},a=wt(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 go)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(St(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let l=wt(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 g=(f.questions||[]).map(h=>{let w={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=yo?w.options=h.options:(w.optionsOmitted=!0,d++)),h.page&&(w.page=h.page),h.wasPreFilled&&(w.wasPreFilled=!0),h.wasRetry&&(w.wasRetry=!0),w});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||g.length,questions:g})}St(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];St(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 kt={};fe(kt,{NAME:()=>bo,VERSION:()=>So,up:()=>$o});import*as X from"fs";import*as en from"path";var So=2,bo="reset-unread-flags";function ko(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function vo(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 $o(e){let t=en.join(e,"conversations.json"),n=ko(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}vo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var vt={};fe(vt,{NAME:()=>xo,VERSION:()=>Co,up:()=>Ro});import*as Z from"fs";import*as tn from"path";var Co=3,xo="recompute-last-message-by",Ao=new Set(["draft","confirmed","rejected","needs_review"]);function Eo(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function Io(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 Do(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Ao.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 Ro(e){let t=tn.join(e,"conversations.json"),n=Eo(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=Do(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}Io(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.")}await qe();import"dotenv/config";import*as K from"path";import{fileURLToPath as To}from"url";var No=To(import.meta.url),_o=K.dirname(K.dirname(No)),Ue=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(_o,"market-research"),ys=K.join(Ue,"scouted-jobs.json"),ws=K.join(Ue,"discovered-people.json"),Ss=K.join(Ue,"visit-log.json"),bs=K.join(Ue,"companies.json"),ks=K.join(Ue,"job-decisions.json");function nn(){Oo=null,jo=null,Fo=null,Lo=null,Mo=null}var Oo=null;var jo=null;var Fo=null;var Lo=null;var Mo=null;var qo=Po(import.meta.url),Bo=R.dirname(qo),Uo=R.dirname(R.dirname(Bo));function Vo(e){return e&&(e==="~"?Ct.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(Ct.homedir(),e.slice(2)):e)}var oe=process.env.DATA_DIR?R.resolve(Vo(process.env.DATA_DIR)):Uo,Ce=R.join(oe,"collected-profiles"),xe=R.join(oe,"market-research"),Y=R.join(oe,".schema-version"),on=[R.join(Ce,".schema-version"),R.join(xe,".schema-version")],ge=3,ae=[{version:1,module:bt},{version:2,module:kt},{version:3,module:vt}];(function(){ae.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ae){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ae.length?ae[ae.length-1].version:0;if(n!==ge)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ge}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ae.length;o++){let r=o+1;if(ae[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ae[o].version}`)}})();function an(){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{b.mkdirSync(
|
|
256
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
257
|
-
`),process.exit(1))}let e;try{e=b.statSync(
|
|
258
|
-
[FATAL] DATA_DIR (${
|
|
255
|
+
`),process.exit(1));try{b.mkdirSync(oe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
256
|
+
[FATAL] Cannot create DATA_DIR (${oe}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
257
|
+
`),process.exit(1))}let e;try{e=b.statSync(oe)}catch(t){console.error(`
|
|
258
|
+
[FATAL] DATA_DIR (${oe}) 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 (${oe}) 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[Ce,xe]){let n;try{n=b.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 $e=R.join(oe,".migration-lock");function Jo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync($e,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync($e,"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,i=1/0;if(t.startedAt){let a=Date.parse(t.startedAt);Number.isNaN(a)||(i=Date.now()-a)}o&&i<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: ${$e}
|
|
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&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n
|
|
266
|
+
`),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=$e+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,$e),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function xt(){try{if(JSON.parse(b.readFileSync($e,"utf-8")).pid!==process.pid)return;b.unlinkSync($e)}catch{}}var rn=!1;function Ho(){if(rn)return;rn=!0;let e=()=>{try{xt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Wo(){if(b.existsSync(Y))return;let e=[],t=[];for(let i of on)if(b.existsSync(i))try{e.push({file:i,schema:nt(i)})}catch(a){t.push({file:i,err:a.message})}if(t.length>0){console.error(`
|
|
267
267
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
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
269
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
|
|
270
270
|
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
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
|
|
276
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
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${
|
|
271
|
+
`),process.exit(1)}let o=e[0].schema,r=Y+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,Y)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of on)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Y}`)}function Yo(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 nt(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function sn(){if(Wo(),!b.existsSync(Y))return{version:0,migrations:[]};let e;try{e=nt(Y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
272
|
+
[FATAL] ${Y} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
273
|
+
`),process.exit(1)}let t=Yo(e);return t===null&&(console.error(`
|
|
274
|
+
[FATAL] ${Y} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
275
|
+
`),process.exit(1)),t}function cn(e){try{b.chmodSync(e,384)}catch{}}function Go(e){if(an(),b.existsSync(Y))try{if(b.lstatSync(Y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=Y+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),cn(t),b.renameSync(t,Y)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function ln(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let s=u.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return b.statSync(R.join(e,u)).isFile()}catch{return!1}}),r=0,i=0,a=[];for(let u of o){let s=R.join(e,u),l=R.join(e,u+n);if(b.existsSync(l)){i++;continue}try{dn(s,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 ${R.basename(e)}/: `+a.map(s=>`${s.file} (${s.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||i>0){let u=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${R.basename(e)}/ (${n})${u}`)}}var $t=!1;async function un(){if($t)return;an(),Zo();let t=sn().version;if(t===ge){$t=!0;return}Ho(),Jo(),process.on("exit",xt),t>ge&&(console.error(`
|
|
276
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ge}.`),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
|
+
`),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${ge}.
|
|
278
278
|
`),process.exit(1)),console.log(`
|
|
279
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
279
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${ge}`);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 i=`v${String(r.version).padStart(3,"0")}`,a=`.pre-${i}.backup`;try{
|
|
282
|
+
`),process.exit(1)}let o=ae.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
283
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,a=`.pre-${i}.backup`;try{ln(Ce,r.version),ln(xe,r.version)}catch(s){console.error(`
|
|
284
284
|
[FATAL] Pre-migration backup failed for ${i}: ${s.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(
|
|
286
|
-
[FATAL] Migration ${i} failed: ${s.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let l=
|
|
285
|
+
`),process.exit(1)}let u=r.module;try{await u.up(Ce,xe)}catch(s){console.error(`
|
|
286
|
+
[FATAL] Migration ${i} failed: ${s.message}`),console.error(` Attempting auto-rollback from ${a} files...`);try{let l=tr(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 s=new Date().toISOString(),l={version:r.version,name:u.NAME||i,appliedAt:s},c=
|
|
289
|
+
`)}process.exit(1)}try{let s=new Date().toISOString(),l={version:r.version,name:u.NAME||i,appliedAt:s},c=sn();c.version=r.version,c.migratedAt=s,c.migrations=c.migrations||[],c.migrations.push(l),Go(c)}catch(s){console.error(`
|
|
290
290
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${s.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
291
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
292
|
-
\u2713 Schema is now at v${
|
|
293
|
-
`)}var
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
291
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Jt()}catch{}try{nn()}catch{}$t=!0,xt(),console.log(`
|
|
292
|
+
\u2713 Schema is now at v${ge}
|
|
293
|
+
`)}var Qo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Ko(e){let t=e.toLowerCase();return Qo.some(n=>n.test(t))}var zo=6e4;function Xo(){let e=Date.now(),t=[];for(let n of[oe,Ce,xe]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!Ko(r))continue;let i=R.join(n,r);try{let a=b.statSync(i);if(!a.isFile()||e-a.mtimeMs<zo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function Zo({verbose:e=!1}={}){let t=Xo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${R.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[Ce,xe]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=R.join(t,o);try{nt(r)}catch(i){e.push({dir:R.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function tr(e){let t=[],n=[];for(let i of[Ce,xe]){if(!b.existsSync(i))continue;let a=b.readdirSync(i).filter(u=>u.endsWith(e));for(let u of a){let s=R.join(i,u),l=u.slice(0,-e.length),c=R.join(i,l);try{l.toLowerCase().endsWith(".json")?nt(s):b.accessSync(s,b.constants.R_OK),t.push({backupPath:s,originalPath:c,fileName:u,dir:i})}catch(d){n.push(`${R.basename(i)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:a,fileName:u,dir:s}of t)try{dn(i,a),o++}catch(l){r.push(`${R.basename(s)}/${u}: ${l.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function dn(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),cn(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var On=new Set(["connected"]),jn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Nn=new Set(["pending","connected","excluded_location","email_required","premium_required"]),Lr=3,it=process.env.DATA_DIR?Re.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):Re.resolve("collected-profiles","connect-diagnostics");async function Mr(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)}));at.mkdirSync(it,{recursive:!0});let i={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};at.appendFileSync(Re.join(it,"connect-failures.jsonl"),JSON.stringify(i)+`
|
|
294
|
+
`);let a=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Re.join(it,`fail-${a}.png`)})}catch{}return r.modal||""}catch{return""}}var Te=process.argv.slice(2),Fn=Te[0],Ne=Te.filter(e=>!e.startsWith("--")),Ge=e=>Te.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),ce=e=>{let t=Te.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&L(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},Nt=()=>new Date().toISOString();function ct(){let e=G(),t=new Map;for(let[n,o]of Object.entries(e)){let r=Q(o.profileUrl||n);r&&t.set(r,o)}return t}function Ln(e,t){let n=e.get(Q(t));return n?On.has(n.connectionStatus)||jn.has(n.connectionStatus):!1}async function Pr(){let e=Ne[1];if(!e)return L("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 L(`Could not read/parse ${e}: ${l.message}`)}if(!Array.isArray(t))return L("File must be a JSON array of { url, note?, name? }.");let n=ce("tag")||"untagged",o=ce("priority");if(o&&!me.includes(o))return L(`--priority must be one of: ${me.join(", ")}`);let r=o||"normal",i=ne(),a=ct(),u=yt(i,t,{tag:n,priority:r,nowIso:Nt(),alreadyEngaged:l=>Ln(a,l)});he(i),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 ${ke} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let s=i.filter(l=>l.status==="queued"&&l.withNote).length;console.log(`
|
|
296
|
+
Queue now: ${ve(i,"queued").length} queued, ${ve(i,"approved").length} approved.`),s&&console.log(` ${s} 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 _n=["founder","investor","hiring_manager","peer"];function qr(){let e=ce("category");if(e===void 0&&Ge("valuable")&&(e=_n.join(",")),!e)return L(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
297
|
+
(shortcut: --valuable = ${_n.join(",")})`);let t=e.split(",").map(m=>m.trim()).filter(Boolean),n=m=>{let y=ce(m);if(y===void 0)return;let k=parseInt(y,10);return!Number.isInteger(k)||k<0?L(`--${m} must be a non-negative integer.`):k},o=n("min-posts")??0,r=n("max"),i=ce("priority");if(i&&!me.includes(i))return L(`--priority must be one of: ${me.join(", ")}`);let a=ce("tag"),u=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map(m=>m.trim().toLowerCase()).filter(Boolean),s=m=>{if(!m)return!1;let y=String(m).toLowerCase();return u.some(k=>y.includes(k))},l=G(),c=[],d=0;for(let[m,y]of Object.entries(l))if(t.includes(y.category)&&!(On.has(y.connectionStatus)||jn.has(y.connectionStatus))&&y.connectionDegree!=="1st"&&!((y.jobIds?.length||0)<o)){if(s(y.location)){d++;continue}c.push({url:y.profileUrl||m,p:y})}let f={high:0,medium:1,low:2};c.sort((m,y)=>(f[m.p.personPriority]??1)-(f[y.p.personPriority]??1)||(y.p.mutualConnections||0)-(m.p.mutualConnections||0)||(y.p.jobIds?.length||0)-(m.p.jobIds?.length||0)),r!==void 0&&(c=c.slice(0,r));let p=c.map(m=>({url:m.url,tag:a||m.p.category,priority:i||(m.p.personPriority==="high"?"high":"normal")})),g=ne(),h=ct(),w=yt(g,p,{alreadyEngaged:m=>Ln(h,m),nowIso:Nt()});he(g),console.log(`
|
|
297
298
|
Filled ${w.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}.`),w.skippedDup&&console.log(` ${w.skippedDup} already in queue \u2014 skipped.`),w.skippedEngaged&&console.log(` ${w.skippedEngaged} already connected/pending \u2014 skipped.`),d&&console.log(` ${d} in excluded locations \u2014 skipped.`),console.log(`
|
|
298
|
-
Queue now: ${
|
|
299
|
+
Queue now: ${ve(g,"queued").length} queued, ${ve(g,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function Br(){let e=ne();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=ce("status"),n=ct(),o=be();console.log(`
|
|
299
300
|
=== Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
|
|
300
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(" ")+`
|
|
301
|
-
`),t&&!
|
|
302
|
-
`);let i=t?e.filter(l=>l.status===t):e,a={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...i].sort((l,c)=>(a[l.status]??9)-(a[c.status]??9));for(let l of u){let c=n.get(
|
|
303
|
-
${s} pending entries
|
|
304
|
-
${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function
|
|
305
|
-
Note
|
|
306
|
-
Note cleared
|
|
307
|
-
Priority set to ${t}.`)}async function
|
|
308
|
-
Nothing approved to send.`),
|
|
309
|
-
Connection quota is used up (${
|
|
310
|
-
Nothing to send (--max=${
|
|
311
|
-
=== Connect run ===`),console.log(` Approved: ${
|
|
302
|
+
`),t&&!et.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${et.join(", ")})
|
|
303
|
+
`);let i=t?e.filter(l=>l.status===t):e,a={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...i].sort((l,c)=>(a[l.status]??9)-(a[c.status]??9));for(let l of u){let c=n.get(Q(l.url)),d=c&&c.name||"",f=c&&c.title?` \xB7 ${c.title.slice(0,40)}`:"",p=c&&c.mutualConnections?` \xB7 ${c.mutualConnections} mutual`:"",g=l.withNote?"\u{1F4DD}":" ",h=l.priority==="high"?"\u2B06high ":l.priority==="low"?"\u2B07low ":"normal";console.log(` [${l.status.padEnd(8)}] ${h} ${g} ${d}${f}${p}`),console.log(` ${l.url} (tag=${l.tag})`)}let s=e.filter(l=>(l.status==="queued"||l.status==="approved")&&l.withNote).length;s&&console.log(`
|
|
304
|
+
${s} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function lt(e,t,n,o){let r=ne(),i=0;for(let a of r)e(a)&&t.includes(a.status)&&(a.status=n,i++);return he(r),console.log(`
|
|
305
|
+
${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function Ur(){let e=["queued","failed"];if(Ge("all"))return lt(()=>!0,e,"approved","Approved");let t=ce("tag");if(t)return lt(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=Ne[1];if(!n)return L("Usage: connect approve <url> | --all | --tag=X");let o=le(n);return lt(r=>le(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function Vr(){let e=Ne[1];if(!e)return L("Usage: connect skip <url>");let t=le(e);return lt(n=>le(n.url)===t,["queued","approved"],"skipped","Skipped")}function Jr(){let e=Te[1],t=Te[2];if(!e||t===void 0)return L('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return L("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>ke)return L(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${ke}. Shorten it.`);let o=ne(),r=Be(o,e);if(!r)return L("Not in queue.");r.note=n,r.withNote=!0,he(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 Hr(){let e=Ne[1];if(!e)return L("Usage: connect no-note <url>");let t=ne(),n=Be(t,e);if(!n)return L("Not in queue.");n.note=null,n.withNote=!1,he(t),console.log(`
|
|
307
|
+
Note reminder cleared.`)}function Wr(){let e=Ne[1],t=Ne[2];if(!e||!me.includes(t))return L(`Usage: connect priority <url> <${me.join("|")}>`);let n=ne(),o=Be(n,e);if(!o)return L("Not in queue.");o.priority=t,he(n),console.log(`
|
|
308
|
+
Priority set to ${t}.`)}async function Yr(){let e=Ge("dry-run"),t=Ge("yes"),n=Ge("with-notes"),o=ce("max"),r=1/0;if(o!==void 0){let C=parseInt(o,10);if(!Number.isInteger(C)||C<0)return L("--max must be a non-negative integer.");r=C}let i=be(),a=Math.min(i.daily.remaining,i.weekly.remaining),u=ne(),s=Zt(ve(u,"approved"));if(!s.length){let C=ve(u,"queued").length;console.log(`
|
|
309
|
+
Nothing approved to send.`),C&&console.log(` ${C} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(a<=0){console.log(`
|
|
310
|
+
Connection quota is used up (${i.daily.remaining}/${i.daily.max} today, ${i.weekly.remaining}/${i.weekly.max} week). Try again later.`);return}let l=s.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(C=>C.withNote).length;console.log(`
|
|
312
|
+
=== Connect run ===`),console.log(` Approved: ${s.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=ct();if(l.forEach((C,I)=>{let M=d.get(Q(C.url));console.log(` ${I+1}. ${C.withNote?"\u{1F4DD}":" "} ${M?.name||C.url} (${C.priority}, tag=${C.tag})`)}),e){console.log(`
|
|
312
313
|
[dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
|
|
313
|
-
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(
|
|
314
|
-
[!] ${
|
|
315
|
-
`);try{
|
|
316
|
-
|
|
317
|
-
|
|
314
|
+
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(C=>process.stdin.once("data",()=>C())));let f=(await import("puppeteer")).default,{loadCookies:p}=await Promise.resolve().then(()=>(mn(),pn)),{sendConnectionRequest:g}=await kn().then(()=>bn),{delayed:h}=await Promise.resolve().then(()=>(rt(),hn)),{startRun:w,endRun:m}=await Promise.resolve().then(()=>(Tn(),Rn)),y=w("connect","run"),k,$;try{k=await f.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),$=await k.newPage(),await $.setCookie(...p())}catch(C){console.error(`
|
|
315
|
+
[!] ${C.message}
|
|
316
|
+
`);try{k&&await k.close()}catch{}try{m(y,"error",null,C.message)}catch{}process.exit(1)}let D=0;try{let C=G(),I=new Map;for(let[j,W]of Object.entries(C)){let _=Q(W.profileUrl||j);_&&I.set(_,j)}let M=0,v=0,O=0,V=0;for(let j of l){if(!Pe().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let W=n&&j.withNote,_=await g($,j.url,{message:W?j.note:null,useCustomMessage:W,source:j.tag,skipQuotaGate:!0}),J;if(_.connectionSent?(J="sent",M++):Nn.has(_.reason)?(J="skipped",v++):(J="failed",O++),J==="failed"){V++;let H=await Mr($,j,_.reason);console.log(` \u2717 ${j.url.slice(-32)} \u2014 ${_.reason||"failed"}${H?` \xB7 LinkedIn: "${H.slice(0,120)}"`:""}`)}else V=0;if(_.connectionSent||Nn.has(_.reason)){let H=I.get(Q(j.url))||j.url;try{Xe(H,_.reason,{method:_.method,messageSent:_.messageSent,profileInfo:_.profileInfo})}catch{}}try{let H=ne(),ue=Be(H,j.url);ue&&(ue.status=J,J==="sent"&&(ue.sentAt=Nt()),ue.result=_.reason||_.error||J,he(H))}catch(H){console.error(` \u26A0 Could not persist queue update for ${j.url}: ${H.message}`)}if(_.fatal){console.log(`
|
|
317
|
+
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(V>=Lr){console.log(`
|
|
318
|
+
\u26A0 ${V} 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: ${it}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await h(3e3+Math.random()*2e3)}let N=be();console.log(`
|
|
319
|
+
=== Done: ${M} sent, ${v} skipped, ${O} failed ===`),console.log(`Connection quota left: ${N.daily.remaining}/${N.daily.max} today, ${N.weekly.remaining}/${N.weekly.max} week.`);try{m(y,"success",{sent:M,skipped:v,failed:O})}catch{}}catch(C){console.error(`
|
|
320
|
+
[!] Run aborted: ${C.message}`);try{m(y,"error",null,C.message)}catch{}D=1}finally{try{await k.close()}catch{}}process.exit(D)}function L(e){console.error(e),process.exit(1)}function Gr(){console.log(`connect \u2014 connect queue
|
|
318
321
|
|
|
319
322
|
connect add <file.json> [--tag=X] [--priority=high|normal|low]
|
|
320
323
|
connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
@@ -322,4 +325,4 @@ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(v=>process.stdin
|
|
|
322
325
|
connect approve <url> | --all | --tag=X
|
|
323
326
|
connect note <url> "custom note" connect no-note <url>
|
|
324
327
|
connect skip <url> connect priority <url> <high|normal|low>
|
|
325
|
-
connect run [--max=N] [--dry-run] [--yes]`)}var
|
|
328
|
+
connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var Qr={add:Pr,fill:qr,list:Br,approve:Ur,skip:Vr,note:Jr,"no-note":Hr,priority:Wr,run:Yr},Mn=Qr[Fn];Mn||(Gr(),process.exit(Fn?1:0));await un();await Mn();
|