ilml-plugin-linkedin 1.14.2 → 1.14.3
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 +3 -0
- package/dist/connect.mjs +46 -46
- package/dist/enrichProfile.mjs +3 -3
- package/dist/funnelRunner.mjs +19 -19
- package/dist/run.mjs +24 -24
- package/dist/syncAll.mjs +48 -48
- package/dist/verifyAbout.mjs +15 -15
- package/dist/version.mjs +1 -1
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/enrichProfile.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(t,e)=>{for(var n in e)et(t,n,{get:e[n],enumerable:!0})};async function w(t){let e=Math.floor(Math.random()*2001),n=t+e;return new Promise(o=>setTimeout(o,n))}async function $e(t){return await t.evaluate(()=>{let e=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of e){let i=o.innerText||"",s=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),f=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),d=i.includes("Get hired faster")||i.includes("Get hired 2x");if(s||f||d){let D=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(D)return D.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let a of $){let S=a.innerText?.trim().toLowerCase()||"",p=a.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||p.includes("dismiss"))return a.click(),{dismissed:!0,matched:i.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var re=Ae(()=>{});var je={};tt(je,{extractCertificationsFromDetails:()=>St,extractEducationFromDetails:()=>yt,extractExperienceFromDetails:()=>wt,extractFeaturedFromDetails:()=>gt,extractRecommendationsFromDetails:()=>kt,extractSkillsFromDetails:()=>bt});async function wt(t,e){let n=e.replace(/\/+$/,"")+"/details/experience/";try{await t.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let s=0;s<5;s++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let i=0;for(;i<5&&await t.evaluate(()=>{for(let f of document.querySelectorAll("button"))if(/^Load more$/i.test((f.textContent||"").trim()))return f.click(),!0;return!1});)i++,await w(1500),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await t.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function f(a){let S=[];for(let p of a.querySelectorAll("div")){let h=Array.from(p.children).filter(v=>v.tagName==="DIV");if(h.length<3)continue;let y=h.filter(v=>(v.textContent||"").trim().length>50);y.length<3||(p.textContent||"").length<500||S.push({el:p,count:y.length,totalText:(p.textContent||"").length})}return S.sort((p,h)=>h.count-p.count||p.totalText-h.totalText),S[0]?.el}let d=f(s);if(!d)return[];let D=Array.from(d.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function $(a){let S=a[0]||null,p=null,h=null;if(a[1]){let c=a[1].split("\xB7").map(k=>k.trim());p=c[0]||null,c[1]&&(h=c[1])}let y=a.findIndex(c=>/(\d{4}|present)/i.test(c)&&/(-|–|—)/i.test(c)&&c.length<80),v=null,L=null;if(y>=0){let c=a[y].split("\xB7").map(k=>k.trim());v=c[0]||null,c[1]&&(L=c[1])}let
|
|
1
|
+
var et=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var tt=(t,e)=>{for(var n in e)et(t,n,{get:e[n],enumerable:!0})};async function w(t){let e=Math.floor(Math.random()*2001),n=t+e;return new Promise(o=>setTimeout(o,n))}async function $e(t){return await t.evaluate(()=>{let e=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of e){let i=o.innerText||"",s=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),f=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),d=i.includes("Get hired faster")||i.includes("Get hired 2x");if(s||f||d){let D=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(D)return D.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let a of $){let S=a.innerText?.trim().toLowerCase()||"",p=a.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||p.includes("dismiss"))return a.click(),{dismissed:!0,matched:i.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var re=Ae(()=>{});var je={};tt(je,{extractCertificationsFromDetails:()=>St,extractEducationFromDetails:()=>yt,extractExperienceFromDetails:()=>wt,extractFeaturedFromDetails:()=>gt,extractRecommendationsFromDetails:()=>kt,extractSkillsFromDetails:()=>bt});async function wt(t,e){let n=e.replace(/\/+$/,"")+"/details/experience/";try{await t.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let s=0;s<5;s++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let i=0;for(;i<5&&await t.evaluate(()=>{for(let f of document.querySelectorAll("button"))if(/^Load more$/i.test((f.textContent||"").trim()))return f.click(),!0;return!1});)i++,await w(1500),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await t.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function f(a){let S=[];for(let p of a.querySelectorAll("div")){let h=Array.from(p.children).filter(v=>v.tagName==="DIV");if(h.length<3)continue;let y=h.filter(v=>(v.textContent||"").trim().length>50);y.length<3||(p.textContent||"").length<500||S.push({el:p,count:y.length,totalText:(p.textContent||"").length})}return S.sort((p,h)=>h.count-p.count||p.totalText-h.totalText),S[0]?.el}let d=f(s);if(!d)return[];let D=Array.from(d.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function $(a){let S=a[0]||null,p=null,h=null;if(a[1]){let c=a[1].split("\xB7").map(k=>k.trim());p=c[0]||null,c[1]&&(h=c[1])}let y=a.findIndex(c=>/(\d{4}|present)/i.test(c)&&/(-|–|—)/i.test(c)&&c.length<80),v=null,L=null;if(y>=0){let c=a[y].split("\xB7").map(k=>k.trim());v=c[0]||null,c[1]&&(L=c[1])}let T=null,ne=-1;if(y>=0&&a[y+1]){let c=a[y+1],k=/^[>*\-•]|^>/.test(c),P=/https?:\/\//.test(c),x=/\d{4}/.test(c),V=/,/.test(c)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(c);!k&&!P&&!x&&c.length<100&&V&&(T=c,ne=y+1)}let b=null,j=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){j=a.length-1;let c=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);c&&(b={listed:c[1].split(",").map(k=>k.trim()),additional:parseInt(c[2],10)})}let M=new Set([0,1,y,ne,j].filter(c=>c>=0)),C=a.filter((c,k)=>!M.has(k)),oe=C.length>0?C.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:S,company:p,employmentType:h,dates:v,duration:L,location:
|
|
3
|
+
`):null;return{title:S,company:p,employmentType:h,dates:v,duration:L,location:T,description:oe,skills:b,_raw:a}}return D.map(a=>{let p=(a.innerText||"").trim().split(`
|
|
4
4
|
`).map(h=>h.trim()).filter(h=>h&&h.length<5e3);return $(p)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${e}: ${o.message?.slice(0,120)}`),[]}}async function B(t,e,n){let o=e.replace(/\/+$/,"")+`/details/${n}/`;await t.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let i=t.url();if(/\/(login|authwall|checkpoint)/i.test(i))throw new Error(`Session expired \u2014 bounced to ${i} when fetching /details/${n}/`);if(!i.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${i})`);for(let f=0;f<4;f++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let s=0;for(;s<5&&await t.evaluate(()=>{for(let d of document.querySelectorAll("button"))if(/^Load more$/i.test((d.textContent||"").trim()))return d.click(),!0;return!1});)s++,await w(1300),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function U(t,e,n,o){try{return await o()}catch(i){let s=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw i;return/not available on profile/i.test(s)?(console.log(` (${e}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${t}: ${s.slice(0,120)}`),[])}}async function gt(t,e){return U(e,"featured","extractFeaturedFromDetails",async()=>(await B(t,e,"featured"),await t.evaluate(`(() => {
|
|
5
5
|
${H}
|
|
6
6
|
|
|
@@ -235,7 +235,7 @@ 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
|
-
`});import"dotenv/config";import It from"puppeteer";re();import{getPluginConfig as nt}from"@ilivemylife/graph-sdk";var ot=await nt();for(let[t,e]of Object.entries(ot))process.env[t]===void 0&&(process.env[t]=e);var Lt=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Mt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),Tt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as g from"path";import{fileURLToPath as it}from"url";var st=it(import.meta.url),rt=g.dirname(g.dirname(st)),A=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(rt,"collected-profiles"),le=g.join(A,"people.json"),Pt=g.join(A,"jobs.json"),Ot=g.join(A,"quota.json"),qt=g.join(A,"conversations.json"),Bt=g.join(A,"sync-state.json"),Ht=g.join(A,"application-questions.json"),ae=g.join(A,"profile-history"),Le=(t,e)=>{let n=parseInt(t,10);return Number.isInteger(n)&&n>=0?n:e},Ut=Le(process.env.CONNECT_MAX_DAILY,20),Vt=Le(process.env.CONNECT_MAX_WEEKLY,100),q=null;function Me(){m.existsSync(A)||m.mkdirSync(A,{recursive:!0})}function Te(t,e){let n=JSON.stringify(e,null,2),o=t+".tmp";m.writeFileSync(o,n);for(let i=0;i<3;i++)try{m.renameSync(o,t);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let f=Date.now();for(;Date.now()-f<200;);continue}throw s}}function Fe(t,e){if(!m.existsSync(t))return null;try{let n=JSON.parse(m.readFileSync(t,"utf-8"));try{m.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(t)}`);let o=t+".backup";if(m.existsSync(o))try{let i=JSON.parse(m.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{m.copyFileSync(o,t)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{m.copyFileSync(t,t+".corrupted")}catch{}return null}}function lt(){return new Date().toISOString().split("T")[0]}var at=["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"],ct=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(t){if(!t)return null;let e=t.match(/\/in\/([^/?#]+)/);return e?e[1].toLowerCase():null}function ut(){m.existsSync(ae)||m.mkdirSync(ae,{recursive:!0})}function Ne(t){let e=ce(t);return e?g.join(ae,`${e}.json`):null}function dt(t){let e=Ne(t);return e?Fe(e,`profile-history/${ce(t)}.json`)||[]:[]}function ft(t,e){let n=Ne(t);if(!n)return;ut();let o=dt(t);o.unshift(e);try{Te(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${ce(t)}: ${i.message}`)}}function _e(t){return!!(t==null||Array.isArray(t)&&t.length===0||typeof t=="string"&&!t.trim())}function De(t){return Array.isArray(t)?[...t].map(e=>String(e).trim()).sort().join("||"):typeof t=="string"?t.replace(/\s+/g," ").trim():t}function mt(t,e){if(!t)return[];let n=[];for(let o of ct){let i=t[o],s=e[o];_e(i)||_e(s)||De(i)!==De(s)&&n.push(o)}return n}function pt(t){let e=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(t))e.has(o)||(n[o]=i);return n}function Re(){return q||(Me(),q=Fe(le,"people.json")||{},q)}function ht(t){Me(),q=t;try{Te(le,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${g.resolve(le)}`)}}function ue(t,e={}){if(!t)return null;let n=Re(),o=lt(),i=new Date().toISOString(),s=n[t];if(s){let f=mt(s,e);f.length>0&&(ft(t,{capturedAt:i,previousLastUpdated:s.lastUpdated||null,changedFields:f,snapshot:pt(s)}),s.lastSnapshotAt=i),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=i,e.source&&!s.sources?.includes(e.source)&&(s.sources=s.sources||[],s.sources.push(e.source));for(let d of at)if(e[d]!=null){if(Array.isArray(e[d])&&e[d].length===0&&Array.isArray(s[d])&&s[d].length>0)continue;s[d]=e[d]}Array.isArray(e.availableSections)&&(s.lastFullVisitAt=i)}else n[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,about:e.about||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,currentCompany:e.currentCompany||null,currentSchool:e.currentSchool||null,connectionsLevel:e.connectionsLevel||null,mutualConnectionsCount:e.mutualConnectionsCount||null,followers:e.followers||null,openToWork:e.openToWork||!1,hiring:e.hiring||!1,topSkills:e.topSkills||null,availableSections:e.availableSections||null,experience:e.experience||null,featuredLinks:e.featuredLinks||null,_lastEnrichedAt:e._lastEnrichedAt||null,featured:e.featured||null,education:e.education||null,skillsFull:e.skillsFull||null,recommendations:e.recommendations||null,certifications:e.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(e.availableSections)?i:null};return ht(n),n[t]}async function Ct(t,e){let n=t.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 t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Oe(t,e,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:f=!1,extractRecommendations:d=!1,extractCertifications:D=!1}=n;try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await $e(t)&&(console.log(" Dismissed Premium overlay"),await w(1500),await Ct(t,e));let a=0;for(let b=0;b<2;b++){let j=await t.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await t.evaluate(C=>window.scrollTo(0,C),j*T/6),await w(900);let I=await t.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await w(800);let S=await t.evaluate(()=>{let b=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"]),j=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"]),I=r=>{let l=(r||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},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:[]},C=document.querySelector("main");if(!C)return T;let oe=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],c=Array.from(C.querySelectorAll("h2")),k=oe.find(r=>{let l=r.textContent&&r.textContent.trim(),u=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!b.has(u)&&!j.has(u)}),P=k?k.textContent.trim():null,x=k?k.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(l=>l.tagName==="P").some(l=>{let u=l.textContent&&l.textContent.trim();return u&&u.length>5&&!I(u)});)x=x.parentElement;let V=null,pe=null,he=null,ie=null;if(x&&x!==C){let r=Array.from(x.children).filter(u=>u.tagName==="P").filter(u=>{let _=u.textContent&&u.textContent.trim();return _&&_.length>5&&!I(_)});if(r[0]&&(V=r[0].textContent.trim()),r[1]){let u=r[1].textContent.trim().split(/\s*[·•]\s*/);pe=u[0]||null,u.length>1&&(he=u.slice(1).join(" \xB7 "))}let l=Array.from(x.children).filter(u=>u.tagName==="DIV");for(let u=l.length-1;u>=0;u--){let _=l[u].textContent&&l[u].textContent.trim();if(_&&!(P&&_.startsWith(P))&&(ie=_.split(/[·•]/)[0].trim(),ie))break}}let we=null;if(x){let r=x.querySelectorAll("p, span, div");for(let l of r){let u=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){we=u;break}}}let Ke=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ge=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ye=ge&&ge.src||null,W=C.textContent||"",ye=null,be=W.match(/(\d+\+?)\s+connections\b/i);be&&(ye=be[1]+" connections");let J=null,Se=W.match(/(\d+)\s+mutual connection/i),ke=W.match(/and\s+(\d+)\s+other mutual/i),Ge=W.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Se?J=parseInt(Se[1],10):ke?J=2+parseInt(ke[1],10):Ge&&(J=2);let Ce=null,xe=null,ve=c.find(r=>r.textContent&&r.textContent.trim()==="About");if(ve){let r=ve.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let u=l.match(/Top skills\s*(.+?)$/i);if(u){let se=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Xe=>Xe.trim()).filter(Boolean);se.length>0&&se.length<10&&(xe=se)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ce=l||null}}let Ee=null,Ie=c.find(r=>r.textContent&&r.textContent.trim()==="Activity");if(Ie){let r=Ie.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(Ee=parseInt(l[1].replace(/,/g,""),10))}}let Qe=[...new Set(c.map(r=>(r.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(r=>r&&r.length>1&&r.length<60&&r!==P).filter(r=>b.has(r)))],O=document.body.textContent||"",ze=/#OpenToWork\b/i.test(O)||/\bOpen to work\b/.test(O),Ze=/#Hiring\b/i.test(O)||/\bI'?m hiring\b/i.test(O)||/\bWe are hiring\b/i.test(O);return{name:P,title:V,location:ie,currentCompany:pe,currentSchool:he,connectionDegree:we,hasVerifiedBadge:Ke,photoUrl:Ye,connectionsLevel:ye,mutualConnectionsCount:J,followers:Ee,openToWork:ze,hiring:Ze,about:Ce,topSkills:xe,availableSections:Qe}});console.log(`Viewed: ${S.name} - ${S.title}`);let p=null,h=null,y=null,v=null,L=null,M=null;if(o||i||s||f||d||D){let b=await Promise.resolve().then(()=>(Pe(),je));o&&(p=await b.extractExperienceFromDetails(t,e),console.log(` + Experience: ${p.length} entries`)),i&&(h=await b.extractFeaturedFromDetails(t,e),console.log(` + Featured: ${h.length} entries`)),s&&(y=await b.extractEducationFromDetails(t,e),console.log(` + Education: ${y.length} entries`)),f&&(v=await b.extractSkillsFromDetails(t,e),console.log(` + Skills: ${v.length} entries`)),d&&(L=await b.extractRecommendationsFromDetails(t,e),console.log(` + Recommendations: ${L.length} entries`)),D&&(M=await b.extractCertificationsFromDetails(t,e),console.log(` + Certifications: ${M.length} entries`))}return{...S,profileUrl:e,...p!==null&&{experience:p},...h!==null&&{featured:h},...y!==null&&{education:y},...v!==null&&{skillsFull:v},...L!==null&&{recommendations:L},...M!==null&&{certifications:M}}}catch($){console.error(`Error viewing profile ${e}:`,$.message);try{await t.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}import qe from"fs";import xt from"path";var vt="cookies.json";function Et(){let t=process.env.ILML_SCOPE_DIR;return t?xt.join(t,"plugins-state","linkedin","cookies.json"):vt}function Be(){let t=Et();if(!qe.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=qe.readFileSync(t,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${t}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(e)}catch{throw new Error(`Cookies file at ${t} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${t} is empty or not an array. Run: ilml linkedin login`);return n}function He(t){return t?t.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function Ue(t){return(t||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var E=process.argv.slice(2),At=E.includes("--help")||E.includes("-h"),N=E.find(t=>t.startsWith("http")),R=E.includes("--full"),Y=R||E.includes("--with-experience"),G=R||E.includes("--with-featured"),Q=R||E.includes("--with-education"),z=R||E.includes("--with-skills"),Z=R||E.includes("--with-recommendations"),X=R||E.includes("--with-certifications"),Ve=[["experience",Y],["featured",G],["education",Q],["skills",z],["recommendations",Z],["certifications",X]],We=Ve.filter(([,t])=>t).length,fe=1+We;function Je(){console.log(`
|
|
238
|
+
`});import"dotenv/config";import It from"puppeteer";re();import{getPluginConfig as nt}from"@ilivemylife/graph-sdk";var ot=await nt();for(let[t,e]of Object.entries(ot))process.env[t]===void 0&&(process.env[t]=e);var Lt=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Tt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),Mt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as g from"path";import{fileURLToPath as it}from"url";var st=it(import.meta.url),rt=g.dirname(g.dirname(st)),A=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(rt,"collected-profiles"),le=g.join(A,"people.json"),Pt=g.join(A,"jobs.json"),Ot=g.join(A,"quota.json"),qt=g.join(A,"conversations.json"),Bt=g.join(A,"sync-state.json"),Ht=g.join(A,"application-questions.json"),ae=g.join(A,"profile-history"),Le=(t,e)=>{let n=parseInt(t,10);return Number.isInteger(n)&&n>=0?n:e},Ut=Le(process.env.CONNECT_MAX_DAILY,20),Vt=Le(process.env.CONNECT_MAX_WEEKLY,100),q=null;function Te(){m.existsSync(A)||m.mkdirSync(A,{recursive:!0})}function Me(t,e){let n=JSON.stringify(e,null,2),o=t+".tmp";m.writeFileSync(o,n);for(let i=0;i<3;i++)try{m.renameSync(o,t);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let f=Date.now();for(;Date.now()-f<200;);continue}throw s}}function Fe(t,e){if(!m.existsSync(t))return null;try{let n=JSON.parse(m.readFileSync(t,"utf-8"));try{m.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(t)}`);let o=t+".backup";if(m.existsSync(o))try{let i=JSON.parse(m.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{m.copyFileSync(o,t)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{m.copyFileSync(t,t+".corrupted")}catch{}return null}}function lt(){return new Date().toISOString().split("T")[0]}var at=["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"],ct=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(t){if(!t)return null;let e=t.match(/\/in\/([^/?#]+)/);return e?e[1].toLowerCase():null}function ut(){m.existsSync(ae)||m.mkdirSync(ae,{recursive:!0})}function Ne(t){let e=ce(t);return e?g.join(ae,`${e}.json`):null}function dt(t){let e=Ne(t);return e?Fe(e,`profile-history/${ce(t)}.json`)||[]:[]}function ft(t,e){let n=Ne(t);if(!n)return;ut();let o=dt(t);o.unshift(e);try{Me(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${ce(t)}: ${i.message}`)}}function _e(t){return!!(t==null||Array.isArray(t)&&t.length===0||typeof t=="string"&&!t.trim())}function De(t){return Array.isArray(t)?[...t].map(e=>String(e).trim()).sort().join("||"):typeof t=="string"?t.replace(/\s+/g," ").trim():t}function mt(t,e){if(!t)return[];let n=[];for(let o of ct){let i=t[o],s=e[o];_e(i)||_e(s)||De(i)!==De(s)&&n.push(o)}return n}function pt(t){let e=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(t))e.has(o)||(n[o]=i);return n}function Re(){return q||(Te(),q=Fe(le,"people.json")||{},q)}function ht(t){Te(),q=t;try{Me(le,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${g.resolve(le)}`)}}function ue(t,e={}){if(!t)return null;let n=Re(),o=lt(),i=new Date().toISOString(),s=n[t];if(s){let f=mt(s,e);f.length>0&&(ft(t,{capturedAt:i,previousLastUpdated:s.lastUpdated||null,changedFields:f,snapshot:pt(s)}),s.lastSnapshotAt=i),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=i,e.source&&!s.sources?.includes(e.source)&&(s.sources=s.sources||[],s.sources.push(e.source));for(let d of at)if(e[d]!=null){if(Array.isArray(e[d])&&e[d].length===0&&Array.isArray(s[d])&&s[d].length>0)continue;s[d]=e[d]}Array.isArray(e.availableSections)&&(s.lastFullVisitAt=i)}else n[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,about:e.about||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,currentCompany:e.currentCompany||null,currentSchool:e.currentSchool||null,connectionsLevel:e.connectionsLevel||null,mutualConnectionsCount:e.mutualConnectionsCount||null,followers:e.followers||null,openToWork:e.openToWork||!1,hiring:e.hiring||!1,topSkills:e.topSkills||null,availableSections:e.availableSections||null,experience:e.experience||null,featuredLinks:e.featuredLinks||null,_lastEnrichedAt:e._lastEnrichedAt||null,featured:e.featured||null,education:e.education||null,skillsFull:e.skillsFull||null,recommendations:e.recommendations||null,certifications:e.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(e.availableSections)?i:null};return ht(n),n[t]}async function Ct(t,e){let n=t.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 t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Oe(t,e,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:f=!1,extractRecommendations:d=!1,extractCertifications:D=!1}=n;try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await $e(t)&&(console.log(" Dismissed Premium overlay"),await w(1500),await Ct(t,e));let a=0;for(let b=0;b<2;b++){let j=await t.evaluate(()=>document.body.scrollHeight);for(let M=1;M<=6;M++)await t.evaluate(C=>window.scrollTo(0,C),j*M/6),await w(900);let I=await t.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await w(800);let S=await t.evaluate(()=>{let b=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"]),j=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"]),I=r=>{let l=(r||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},M={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:[]},C=document.querySelector("main");if(!C)return M;let oe=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],c=Array.from(C.querySelectorAll("h2")),k=oe.find(r=>{let l=r.textContent&&r.textContent.trim(),u=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!b.has(u)&&!j.has(u)}),P=k?k.textContent.trim():null,x=k?k.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(l=>l.tagName==="P").some(l=>{let u=l.textContent&&l.textContent.trim();return u&&u.length>5&&!I(u)});)x=x.parentElement;let V=null,pe=null,he=null,ie=null;if(x&&x!==C){let r=Array.from(x.children).filter(u=>u.tagName==="P").filter(u=>{let _=u.textContent&&u.textContent.trim();return _&&_.length>5&&!I(_)});if(r[0]&&(V=r[0].textContent.trim()),r[1]){let u=r[1].textContent.trim().split(/\s*[·•]\s*/);pe=u[0]||null,u.length>1&&(he=u.slice(1).join(" \xB7 "))}let l=Array.from(x.children).filter(u=>u.tagName==="DIV");for(let u=l.length-1;u>=0;u--){let _=l[u].textContent&&l[u].textContent.trim();if(_&&!(P&&_.startsWith(P))&&(ie=_.split(/[·•]/)[0].trim(),ie))break}}let we=null;if(x){let r=x.querySelectorAll("p, span, div");for(let l of r){let u=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){we=u;break}}}let Ke=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ge=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ye=ge&&ge.src||null,W=C.textContent||"",ye=null,be=W.match(/(\d+\+?)\s+connections\b/i);be&&(ye=be[1]+" connections");let J=null,Se=W.match(/(\d+)\s+mutual connection/i),ke=W.match(/and\s+(\d+)\s+other mutual/i),Ge=W.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Se?J=parseInt(Se[1],10):ke?J=2+parseInt(ke[1],10):Ge&&(J=2);let Ce=null,xe=null,ve=c.find(r=>r.textContent&&r.textContent.trim()==="About");if(ve){let r=ve.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let u=l.match(/Top skills\s*(.+?)$/i);if(u){let se=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Xe=>Xe.trim()).filter(Boolean);se.length>0&&se.length<10&&(xe=se)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ce=l||null}}let Ee=null,Ie=c.find(r=>r.textContent&&r.textContent.trim()==="Activity");if(Ie){let r=Ie.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(Ee=parseInt(l[1].replace(/,/g,""),10))}}let Qe=[...new Set(c.map(r=>(r.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(r=>r&&r.length>1&&r.length<60&&r!==P).filter(r=>b.has(r)))],O=document.body.textContent||"",ze=/#OpenToWork\b/i.test(O)||/\bOpen to work\b/.test(O),Ze=/#Hiring\b/i.test(O)||/\bI'?m hiring\b/i.test(O)||/\bWe are hiring\b/i.test(O);return{name:P,title:V,location:ie,currentCompany:pe,currentSchool:he,connectionDegree:we,hasVerifiedBadge:Ke,photoUrl:Ye,connectionsLevel:ye,mutualConnectionsCount:J,followers:Ee,openToWork:ze,hiring:Ze,about:Ce,topSkills:xe,availableSections:Qe}});console.log(`Viewed: ${S.name} - ${S.title}`);let p=null,h=null,y=null,v=null,L=null,T=null;if(o||i||s||f||d||D){let b=await Promise.resolve().then(()=>(Pe(),je));o&&(p=await b.extractExperienceFromDetails(t,e),console.log(` + Experience: ${p.length} entries`)),i&&(h=await b.extractFeaturedFromDetails(t,e),console.log(` + Featured: ${h.length} entries`)),s&&(y=await b.extractEducationFromDetails(t,e),console.log(` + Education: ${y.length} entries`)),f&&(v=await b.extractSkillsFromDetails(t,e),console.log(` + Skills: ${v.length} entries`)),d&&(L=await b.extractRecommendationsFromDetails(t,e),console.log(` + Recommendations: ${L.length} entries`)),D&&(T=await b.extractCertificationsFromDetails(t,e),console.log(` + Certifications: ${T.length} entries`))}return{...S,profileUrl:e,...p!==null&&{experience:p},...h!==null&&{featured:h},...y!==null&&{education:y},...v!==null&&{skillsFull:v},...L!==null&&{recommendations:L},...T!==null&&{certifications:T}}}catch($){console.error(`Error viewing profile ${e}:`,$.message);try{await t.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}import qe from"fs";import xt from"path";var vt="cookies.json";function Et(){let t=process.env.ILML_SCOPE_DIR;return t?xt.join(t,"plugins-state","linkedin","cookies.json"):vt}function Be(){let t=Et();if(!qe.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=qe.readFileSync(t,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${t}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(e)}catch{throw new Error(`Cookies file at ${t} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${t} is empty or not an array. Run: ilml linkedin login`);return n}function He(t){return t?t.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function Ue(t){return(t||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var E=process.argv.slice(2),At=E.includes("--help")||E.includes("-h"),N=E.find(t=>t.startsWith("http")),R=E.includes("--full"),Y=R||E.includes("--with-experience"),G=R||E.includes("--with-featured"),Q=R||E.includes("--with-education"),z=R||E.includes("--with-skills"),Z=R||E.includes("--with-recommendations"),X=R||E.includes("--with-certifications"),Ve=[["experience",Y],["featured",G],["education",Q],["skills",z],["recommendations",Z],["certifications",X]],We=Ve.filter(([,t])=>t).length,fe=1+We;function Je(){console.log(`
|
|
239
239
|
enrich-profile \u2014 visit ONE LinkedIn profile and save what we learn
|
|
240
240
|
|
|
241
241
|
USAGE
|
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var nn=Object.defineProperty;var at=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ee=(e,t)=>{for(var n in t)nn(e,n,{get:t[n],enumerable:!0})};async function y(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ie(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),
|
|
1
|
+
var nn=Object.defineProperty;var at=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ee=(e,t)=>{for(var n in t)nn(e,n,{get:t[n],enumerable:!0})};async function y(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ie(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||l||c){let r=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(r)return r.click(),{dismissed:!0,matched:s.substring(0,80)};let u=o.querySelectorAll("button");for(let a of u){let d=a.innerText?.trim().toLowerCase()||"",m=a.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||m.includes("dismiss"))return a.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Ae=at(()=>{});var At={};Ee(At,{extractCertificationsFromDetails:()=>jn,extractEducationFromDetails:()=>_n,extractExperienceFromDetails:()=>Tn,extractFeaturedFromDetails:()=>Rn,extractRecommendationsFromDetails:()=>Nn,extractSkillsFromDetails:()=>On});async function Tn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await y(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 y(900);await y(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)s++,await y(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await y(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function l(a){let d=[];for(let m of a.querySelectorAll("div")){let f=Array.from(m.children).filter(p=>p.tagName==="DIV");if(f.length<3)continue;let h=f.filter(p=>(p.textContent||"").trim().length>50);h.length<3||(m.textContent||"").length<500||d.push({el:m,count:h.length,totalText:(m.textContent||"").length})}return d.sort((m,f)=>f.count-m.count||m.totalText-f.totalText),d[0]?.el}let c=l(i);if(!c)return[];let r=Array.from(c.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function u(a){let d=a[0]||null,m=null,f=null;if(a[1]){let k=a[1].split("\xB7").map(F=>F.trim());m=k[0]||null,k[1]&&(f=k[1])}let h=a.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),p=null,S=null;if(h>=0){let k=a[h].split("\xB7").map(F=>F.trim());p=k[0]||null,k[1]&&(S=k[1])}let w=null,$=-1;if(h>=0&&a[h+1]){let k=a[h+1],F=/^[>*\-•]|^>/.test(k),K=/https?:\/\//.test(k),L=/\d{4}/.test(k),se=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!F&&!K&&!L&&k.length<100&&se&&(w=k,$=h+1)}let b=null,C=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){C=a.length-1;let k=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(b={listed:k[1].split(",").map(F=>F.trim()),additional:parseInt(k[2],10)})}let _=new Set([0,1,h,$,C].filter(k=>k>=0)),D=a.filter((k,F)=>!_.has(F)),B=D.length>0?D.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:d,company:m,employmentType:f,dates:p,duration:S,location:w,description:B,skills:b,_raw:
|
|
4
|
-
`).map(f=>f.trim()).filter(f=>f&&f.length<5e3);return u(m)}).filter(
|
|
3
|
+
`):null;return{title:d,company:m,employmentType:f,dates:p,duration:S,location:w,description:B,skills:b,_raw:a}}return r.map(a=>{let m=(a.innerText||"").trim().split(`
|
|
4
|
+
`).map(f=>f.trim()).filter(f=>f&&f.length<5e3);return u(m)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function we(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await y(700);await y(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await y(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await y(600)}async function be(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Rn(e,t){return be(t,"featured","extractFeaturedFromDetails",async()=>(await we(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
5
|
${Se}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
@@ -235,21 +235,21 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});import
|
|
238
|
+
`});import Lo from"puppeteer";import"dotenv/config";import*as J from"fs";import*as ne from"path";import{fileURLToPath as cn}from"url";import"dotenv/config";import{createGraphClient as on,resolveToken as rn}from"@ilivemylife/graph-sdk";import{config as sn}from"dotenv";sn();var ct=rn()||process.env.TOKEN;ct||(console.error(`
|
|
239
239
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
240
240
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
241
241
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
242
|
-
`),process.exit(1));var ut=on({token:ct});function ln(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 an({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),
|
|
242
|
+
`),process.exit(1));var ut=on({token:ct});function ln(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 an({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${ln(s)}`:"",r=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${r} \u2014 ${l}${c}`}async function dt({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let r=`**${an({scriptName:e,mode:t,status:n,error:s,duration:i})}**
|
|
243
243
|
|
|
244
244
|
${o.join(`
|
|
245
|
-
`)}`;try{await ut.addMessage(l,r)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var un=cn(import.meta.url),dn=ne.dirname(ne.dirname(un)),je=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(dn,"collected-profiles"),Ne=ne.join(je,"run-log.json");function fn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let s=0;s<3;s++)try{J.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ft(){try{if(!J.existsSync(Ne))return{runs:[]};let e=JSON.parse(J.readFileSync(Ne,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function mt(e){J.existsSync(je)||J.mkdirSync(je,{recursive:!0});try{fn(Ne,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function pt(e,t="default"){let n=ft();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),mt(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Fe(e,t,n=null,o=null){if(!e)return;let s=null;try{let l=ft(),a=l.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration;else{let r=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());r&&(r.status=t,r.result=t,r.duration=Date.now()-e.startTime,r.stats=n,r.error=o,s=r.duration)}mt(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";dt({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}Ae();Ae();import{getPluginConfig as mn}from"@ilivemylife/graph-sdk";var pn=await mn();for(let[e,t]of Object.entries(pn))process.env[e]===void 0&&(process.env[e]=t);var Zo=process.env.LINKEDIN_NAME,le=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),er=Object.freeze(new Set([le.DRAFT,le.CONFIRMED,le.NEEDS_REVIEW])),tr=Object.freeze(new Set([le.DRAFT,le.CONFIRMED,le.REJECTED,le.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as L from"path";import{fileURLToPath as hn}from"url";var gn=hn(import.meta.url),yn=L.dirname(L.dirname(gn)),Q=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(yn,"collected-profiles"),Me=L.join(Q,"people.json"),ir=L.join(Q,"jobs.json"),yt=L.join(Q,"quota.json"),lr=L.join(Q,"conversations.json"),ar=L.join(Q,"sync-state.json"),cr=L.join(Q,"application-questions.json"),Le=L.join(Q,"profile-history"),wt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},he=wt(process.env.CONNECT_MAX_DAILY,20),ge=wt(process.env.CONNECT_MAX_WEEKLY,100),fe=null,wn=null,z=null,Sn=null,bn=null,kn=null;function St(){fe=null,wn=null,z=null,Sn=null,bn=null,kn=null}function De(){R.existsSync(Q)||R.mkdirSync(Q,{recursive:!0})}function Pe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";R.writeFileSync(o,n);for(let s=0;s<3;s++)try{R.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function qe(e,t){if(!R.existsSync(e))return null;try{let n=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${L.resolve(e)}`);let o=e+".backup";if(R.existsSync(o))try{let s=JSON.parse(R.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{R.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}var vn=["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"],$n=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Be(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Cn(){R.existsSync(Le)||R.mkdirSync(Le,{recursive:!0})}function bt(e){let t=Be(e);return t?L.join(Le,`${t}.json`):null}function xn(e){let t=bt(e);return t?qe(t,`profile-history/${Be(e)}.json`)||[]:[]}function En(e,t){let n=bt(e);if(!n)return;Cn();let o=xn(e);o.unshift(t);try{Pe(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Be(e)}: ${s.message}`)}}function ht(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function gt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function An(e,t){if(!e)return[];let n=[];for(let o of $n){let s=e[o],i=t[o];ht(s)||ht(i)||gt(s)!==gt(i)&&n.push(o)}return n}function In(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function oe(){return fe||(De(),fe=qe(Me,"people.json")||{},fe)}function Ue(e){De(),fe=e;try{Pe(Me,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${L.resolve(Me)}`)}}function Ie(e,t={}){if(!e)return null;let n=oe(),o=ye(),s=new Date().toISOString(),i=n[e];if(i){let l=An(i,t);l.length>0&&(En(e,{capturedAt:s,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:In(i)}),i.lastSnapshotAt=s),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=s,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let a of vn)if(t[a]!=null){if(Array.isArray(t[a])&&t[a].length===0&&Array.isArray(i[a])&&i[a].length>0)continue;i[a]=t[a]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=s)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Ue(n),n[e]}function kt(e,t){if(!e||!t)return;let n=oe(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Ue(n))}function vt(e){return e&&oe()[e]?.connectionStatus||null}function $t(e,t,n={}){if(!e)return;n.profileInfo?Ie(e,n.profileInfo):oe()[e]||Ie(e,{});let o=oe(),s=o[e];s&&(s.connectionStatus=t,s.connectionDate=ye(),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),Ue(o))}function Ct(){return z||(De(),z=qe(yt,"quota.json"),(!z||!z.connections)&&(z={connections:[]}),z)}function Dn(e){De(),z=e;try{Pe(yt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function xt(e,t="unknown"){let n=Ct(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Dn(n)}function Et(){let e=Ct(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Je(){let e=Et(),t=ye(),n=e.filter(r=>r.date===t).length,o=e.length,s=n>=he,i=o>=ge,l=!s&&!i,a={allowed:l,daily:{sent:n,max:he},weekly:{sent:o,max:ge}};return l||(a.reason=s?`Daily limit reached (${n}/${he})`:`Weekly limit reached (${o}/${ge})`),a}function Ve(){let e=Et(),t=ye(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:he,remaining:he-n},weekly:{sent:o,max:ge,remaining:ge-o}}}async function Tt(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 y(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Dt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Fn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:a=!1,extractCertifications:r=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await ie(e)&&(console.log(" Dismissed Premium overlay"),await y(1500),await Tt(e,t));let c=0;for(let b=0;b<2;b++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(D=>window.scrollTo(0,D),C*_/6),await y(900);let I=await e.evaluate(()=>document.body.scrollHeight);if(I===c)break;c=I}await y(800);let d=await e.evaluate(()=>{let b=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"]),I=v=>{let x=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},_={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},D=document.querySelector("main");if(!D)return _;let B=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],k=Array.from(D.querySelectorAll("h2")),F=B.find(v=>{let x=v.textContent&&v.textContent.trim(),E=(x||"").replace(/\s*\(\d+\)$/,"").trim();return x&&x.length>1&&x.length<100&&!b.has(E)&&!C.has(E)}),K=F?F.textContent.trim():null,M=F?F.parentElement:null;for(;M&&M!==D&&!Array.from(M.children).filter(x=>x.tagName==="P").some(x=>{let E=x.textContent&&x.textContent.trim();return E&&E.length>5&&!I(E)});)M=M.parentElement;let se=null,ee=null,me=null,de=null;if(M&&M!==D){let v=Array.from(M.children).filter(E=>E.tagName==="P").filter(E=>{let te=E.textContent&&E.textContent.trim();return te&&te.length>5&&!I(te)});if(v[0]&&(se=v[0].textContent.trim()),v[1]){let E=v[1].textContent.trim().split(/\s*[·•]\s*/);ee=E[0]||null,E.length>1&&(me=E.slice(1).join(" \xB7 "))}let x=Array.from(M.children).filter(E=>E.tagName==="DIV");for(let E=x.length-1;E>=0;E--){let te=x[E].textContent&&x[E].textContent.trim();if(te&&!(K&&te.startsWith(K))&&(de=te.split(/[·•]/)[0].trim(),de))break}}let Ce=null;if(M){let v=M.querySelectorAll("p, span, div");for(let x of v){let E=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ce=E;break}}}let _e=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),O=T&&T.src||null,j=D.textContent||"",N=null,Y=j.match(/(\d+\+?)\s+connections\b/i);Y&&(N=Y[1]+" connections");let xe=null,tt=j.match(/(\d+)\s+mutual connection/i),nt=j.match(/and\s+(\d+)\s+other mutual/i),Qt=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);tt?xe=parseInt(tt[1],10):nt?xe=2+parseInt(nt[1],10):Qt&&(xe=2);let ot=null,rt=null,st=k.find(v=>v.textContent&&v.textContent.trim()==="About");if(st){let v=st.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").trim();x=x.replace(/^About\s*/,"").trim();let E=x.match(/Top skills\s*(.+?)$/i);if(E){let Oe=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(tn=>tn.trim()).filter(Boolean);Oe.length>0&&Oe.length<10&&(rt=Oe)}x=x.split(/\n?…\s*more/i)[0].trim(),x=x.split(/\n?\.\.\.\s*more/i)[0].trim(),x=x.split(/\bTop skills\b/i)[0].trim(),x=x.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ot=x||null}}let it=null,lt=k.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(lt){let v=lt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);x&&(it=parseInt(x[1].replace(/,/g,""),10))}}let Xt=[...new Set(k.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==K).filter(v=>b.has(v)))],pe=document.body.textContent||"",Zt=/#OpenToWork\b/i.test(pe)||/\bOpen to work\b/.test(pe),en=/#Hiring\b/i.test(pe)||/\bI'?m hiring\b/i.test(pe)||/\bWe are hiring\b/i.test(pe);return{name:K,title:se,location:de,currentCompany:ee,currentSchool:me,connectionDegree:Ce,hasVerifiedBadge:_e,photoUrl:O,connectionsLevel:N,mutualConnectionsCount:xe,followers:it,openToWork:Zt,hiring:en,about:ot,topSkills:rt,availableSections:Xt}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,f=null,h=null,p=null,S=null,w=null;if(o||s||i||l||a||r){let b=await Promise.resolve().then(()=>(It(),At));o&&(m=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(f=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${f.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(p=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),a&&(S=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),r&&(w=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...d,profileUrl:t,...m!==null&&{experience:m},...f!==null&&{featured:f},...h!==null&&{education:h},...p!==null&&{skillsFull:p},...S!==null&&{recommendations:S},...w!==null&&{certifications:w}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function ke(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(r=>r.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!s,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:l}:s&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function He(e){let t=null,n=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim();if(r&&!r.includes("notification"))return r;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(r=u.textContent?.trim(),r&&!r.includes("notification")))return r;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 r=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))}});r.count>0&&console.log(` S0: ${r.count} custom-invite links: ${JSON.stringify(r.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=c.toLowerCase().split(" ")[0],f=null,h=null;for(let p of d){let S=p.getBoundingClientRect();if(S.width===0||S.height===0)continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(m)){f=p;break}h||(h=p)}return f||h||null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let r=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${r}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),f=document.querySelectorAll("button[aria-label]");return Array.from(f).filter(p=>{let S=p.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&m.test(S)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},r);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of m){let p=h.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&f.test(p))return h}return null},r);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 r=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping primary button: wrong person (${r})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let r of o){let u=await e.evaluate((c,d)=>{let m=c.className.includes("muted"),f=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(c.getAttribute("aria-label")||"").toLowerCase(),S=p.includes("invite"),w=d?p.includes(d):!0;return{isMuted:m,isStickyHeader:f,inRecommendations:h,hasInvite:S,matchesName:w,ariaLabel:p}},r,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=r;break}}for(let r of o)r!==i&&await r.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let r of a){let u=await e.evaluate(c=>{let d=c.getBoundingClientRect(),m=d.width>0&&d.height>0,f=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:f,top:d.top}},r);if(u.isVisible&&!u.isInStickyHeader){l=r,console.log(" Found More button by ID pattern (main)");break}}for(let r of a)r!==l&&await r.dispose().catch(()=>{});if(!l&&a.length>0&&(l=a[a.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let r=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(m=>{let f=m.innerText?.trim(),h=m.getAttribute("aria-label")||"",p=m.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:f==="Follow"||f==="Message"||f==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let m=0;m<8&&d;m++){for(let f of d.querySelectorAll("button"))if(f.innerText?.trim()==="More"&&f!==c)return f;d=d.parentElement}return null});l=r?.asElement?.()||null,l||await r?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await y(500),await e.evaluate(c=>c.click(),l),await y(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of d){let f=m.querySelector('a[href*="custom-invite"]');if(f)return f;for(let h of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let f of d)for(let h of f.querySelectorAll('[role="menuitem"], a, div')){let p=h.innerText?.trim();p&&p.length<40&&m.push(p)}return[...new Set(m)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(r){console.log(" More dropdown click failed:",r.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let r=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping generic button: wrong person (${r})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Mn(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await y(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV";if(s){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 y(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await y(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await y(3e3)):(await e.evaluate(u=>u.click(),t),await y(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let a=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),r=e.url();return console.log(a?` \u2713 Connect sent \u2014 ${r}`:` \u26A0 No modal after connect click \u2014 ${r}`),"success"}async function Ln(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 y(1500);let n=await He(e);if(n){await e.evaluate(s=>s.click(),n),await y(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Pn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let a=Je();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let l=await qn(e,t,n);return l.connectionSent&&!i&&xt(t,o),l}async function qn(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:a=[]}=n,r={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
246
|
-
--- Connecting: ${u} ---`),a.length>0){let w=oe()[t]?.location;if(Dt(w,a))return console.log(` \u26A0 Excluded location (stored): ${w}`),r.reason="excluded_location",r.profileInfo={location:w},r}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(5e3),await ie(e)&&(console.log(" Dismissed Premium overlay"),await y(2e3),await Tt(e,t),await y(2e3)),r.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),$=T=>{let O=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},b={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 b;let I=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],_=Array.from(C.querySelectorAll("h2")),D=I.find(T=>{let O=T.textContent&&T.textContent.trim();return O&&O.length>1&&O.length<100&&!w.has(O)&&O!=="0 notifications"}),B=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==C&&!Array.from(k.children).filter(j=>j.tagName==="P").some(j=>{let N=j.textContent&&j.textContent.trim();return N&&N.length>5&&!$(N)});)k=k.parentElement;let F=null,K=null,M=null;if(k&&k!==C){let T=Array.from(k.children),O=T.filter(N=>N.tagName==="P").filter(N=>{let Y=N.textContent&&N.textContent.trim();return Y&&Y.length>5&&!$(Y)});O[0]&&(F=O[0].textContent.trim()),O[1]&&(K=O[1].textContent.trim());let j=T.filter(N=>N.tagName==="DIV");for(let N=j.length-1;N>=0;N--){let Y=j[N].textContent&&j[N].textContent.trim();if(Y&&!(B&&Y.startsWith(B))&&(M=Y.split(/[·•]/)[0].trim(),M))break}}let se=null;if(k){let T=k.querySelectorAll("p, span, div");for(let O of T){let j=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){se=j;break}}}let ee=null,me=_.find(T=>T.textContent&&T.textContent.trim()==="About");if(me){let T=me.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(ee=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,ee&&(ee=ee.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let de=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ce=de&&de.src||null,_e=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:B,title:F,location:M,about:ee,company:K,connectionDegree:se,connectionsCount:null,mutualConnections:null,photoUrl:Ce,hasVerifiedBadge:_e}}),a.length>0){let w=r.profileInfo?.location,$=oe()[t]?.location,b=w||$;if(Dt(b,a))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${b}`),r.reason="excluded_location",r;!w&&$==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await ke(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),r.reason="pending",r;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),r.reason="connected",r;await ie(e);let m=await He(e);if(!m&&(await ie(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await y(2e3),m=await He(e)),!m))return console.log(" \u2717 Connect not found"),r.reason="button_not_found",r;if(r.method=m.method,await Mn(e,m.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(4e3);let w=await ke(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await ie(e),await y(1e3);let $=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if($)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),$),await y(500),await $.click().catch(()=>e.evaluate(C=>C.click(),$)),await y(2e3);let b=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(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(_=>_.click(),b),await y(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 y(3e3),r.reason="premium_required",r;if(await ke(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.method="more_dropdown",r.withCustomMessage=!1,r;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await y(500),r.reason="premium_required",r}catch(b){return console.log(" More dropdown failed:",b.message),await e.keyboard.press("Escape").catch(()=>{}),r.reason="premium_required",r}else return console.log(" \u2717 No More button found \u2014 Premium required"),r.reason="premium_required",r}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await y(500),r.reason="email_required",r}let p=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!p&&!S){let w=await e.evaluate(()=>{let $=document.querySelector("#interop-outlet")?.shadowRoot;if(!$)return{addNote:!1,sendWithout:!1};let b=$.querySelector('button[aria-label="Add a note"]'),C=$.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=$?.asElement?.()||null,p||await $.dispose().catch(()=>{})}if(w.sendWithout){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=$?.asElement?.()||null,S||await $.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await y(1500),await e.$("div.modal-upsell")){let b=await Ln(e);return r.success=b,r.connectionSent=b,r.reason=b?"sent_without_note_upsell":"upsell_failed",r.withCustomMessage=!1,r}let $=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if($){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",b);await $.type(C,{delay:20}),await y(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(_=>_.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (with note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_with_note",r.withCustomMessage=!0,r.messageSent=C,r}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}else if(p&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}}else{console.log(" Sending without note (custom messages disabled)...");let w=S;if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}if(m.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 y(4e3)),await ie(e),await y(500);let $=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of $){let I=await e.evaluate(_=>{let D=_.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!_.closest('.sticky-header, [class*="sticky"]')}},C);if(I.visible&&!I.inSticky){b=C;break}}!b&&$.length>0&&(b=$[$.length-1]);for(let C of $)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),b),await y(500),await b.click().catch(()=>e.evaluate(I=>I.click(),b)),await y(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..."),r.method="more_dropdown",await e.evaluate(B=>B.click(),C),await y(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await ke(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r):(r.reason="premium_required",r);if(await ke(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;let D=await e.$('button[aria-label="Send without a note"]');if(D){console.log(" Modal appeared via More dropdown, sending without note...");try{await D.evaluate(B=>B.click())}catch{}return await y(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),r.reason="modal_failed",r}catch(u){console.error(` \u2717 Error: ${u.message}`),r.reason="error",r.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return r.fatal=!0,r;try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{r.fatal=!0}return r}}async function Rt(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:r=null,excludeLocations:u=[],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(`
|
|
245
|
+
`)}`;try{await ut.addMessage(l,r)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var un=cn(import.meta.url),dn=ne.dirname(ne.dirname(un)),je=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(dn,"collected-profiles"),Ne=ne.join(je,"run-log.json");function fn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let s=0;s<3;s++)try{J.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ft(){try{if(!J.existsSync(Ne))return{runs:[]};let e=JSON.parse(J.readFileSync(Ne,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function mt(e){J.existsSync(je)||J.mkdirSync(je,{recursive:!0});try{fn(Ne,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function pt(e,t="default"){let n=ft();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),mt(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Fe(e,t,n=null,o=null){if(!e)return;let s=null;try{let l=ft(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,s=c.duration;else{let r=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());r&&(r.status=t,r.result=t,r.duration=Date.now()-e.startTime,r.stats=n,r.error=o,s=r.duration)}mt(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";dt({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Ae();Ae();import{getPluginConfig as mn}from"@ilivemylife/graph-sdk";var pn=await mn();for(let[e,t]of Object.entries(pn))process.env[e]===void 0&&(process.env[e]=t);var Zo=process.env.LINKEDIN_NAME,le=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),er=Object.freeze(new Set([le.DRAFT,le.CONFIRMED,le.NEEDS_REVIEW])),tr=Object.freeze(new Set([le.DRAFT,le.CONFIRMED,le.REJECTED,le.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as M from"path";import{fileURLToPath as hn}from"url";var gn=hn(import.meta.url),yn=M.dirname(M.dirname(gn)),Q=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(yn,"collected-profiles"),Le=M.join(Q,"people.json"),ir=M.join(Q,"jobs.json"),yt=M.join(Q,"quota.json"),lr=M.join(Q,"conversations.json"),ar=M.join(Q,"sync-state.json"),cr=M.join(Q,"application-questions.json"),Me=M.join(Q,"profile-history"),wt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},he=wt(process.env.CONNECT_MAX_DAILY,20),ge=wt(process.env.CONNECT_MAX_WEEKLY,100),fe=null,wn=null,z=null,Sn=null,bn=null,kn=null;function St(){fe=null,wn=null,z=null,Sn=null,bn=null,kn=null}function De(){R.existsSync(Q)||R.mkdirSync(Q,{recursive:!0})}function Pe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";R.writeFileSync(o,n);for(let s=0;s<3;s++)try{R.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function qe(e,t){if(!R.existsSync(e))return null;try{let n=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${M.resolve(e)}`);let o=e+".backup";if(R.existsSync(o))try{let s=JSON.parse(R.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{R.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}var vn=["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"],$n=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Be(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Cn(){R.existsSync(Me)||R.mkdirSync(Me,{recursive:!0})}function bt(e){let t=Be(e);return t?M.join(Me,`${t}.json`):null}function xn(e){let t=bt(e);return t?qe(t,`profile-history/${Be(e)}.json`)||[]:[]}function En(e,t){let n=bt(e);if(!n)return;Cn();let o=xn(e);o.unshift(t);try{Pe(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Be(e)}: ${s.message}`)}}function ht(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function gt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function An(e,t){if(!e)return[];let n=[];for(let o of $n){let s=e[o],i=t[o];ht(s)||ht(i)||gt(s)!==gt(i)&&n.push(o)}return n}function In(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function oe(){return fe||(De(),fe=qe(Le,"people.json")||{},fe)}function Ue(e){De(),fe=e;try{Pe(Le,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${M.resolve(Le)}`)}}function Ie(e,t={}){if(!e)return null;let n=oe(),o=ye(),s=new Date().toISOString(),i=n[e];if(i){let l=An(i,t);l.length>0&&(En(e,{capturedAt:s,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:In(i)}),i.lastSnapshotAt=s),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=s,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let c of vn)if(t[c]!=null){if(Array.isArray(t[c])&&t[c].length===0&&Array.isArray(i[c])&&i[c].length>0)continue;i[c]=t[c]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=s)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Ue(n),n[e]}function kt(e,t){if(!e||!t)return;let n=oe(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:ye(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Ue(n))}function vt(e){return e&&oe()[e]?.connectionStatus||null}function $t(e,t,n={}){if(!e)return;n.profileInfo?Ie(e,n.profileInfo):oe()[e]||Ie(e,{});let o=oe(),s=o[e];s&&(s.connectionStatus=t,s.connectionDate=ye(),s.connectionMethod=n.method||s.connectionMethod,s.messageSent=n.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),Ue(o))}function Ct(){return z||(De(),z=qe(yt,"quota.json"),(!z||!z.connections)&&(z={connections:[]}),z)}function Dn(e){De(),z=e;try{Pe(yt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function xt(e,t="unknown"){let n=Ct(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Dn(n)}function Et(){let e=Ct(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Je(){let e=Et(),t=ye(),n=e.filter(r=>r.date===t).length,o=e.length,s=n>=he,i=o>=ge,l=!s&&!i,c={allowed:l,daily:{sent:n,max:he},weekly:{sent:o,max:ge}};return l||(c.reason=s?`Daily limit reached (${n}/${he})`:`Weekly limit reached (${o}/${ge})`),c}function Ve(){let e=Et(),t=ye(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:he,remaining:he-n},weekly:{sent:o,max:ge,remaining:ge-o}}}async function Tt(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 y(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Dt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Fn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:c=!1,extractCertifications:r=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await ie(e)&&(console.log(" Dismissed Premium overlay"),await y(1500),await Tt(e,t));let a=0;for(let b=0;b<2;b++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(D=>window.scrollTo(0,D),C*_/6),await y(900);let I=await e.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await y(800);let d=await e.evaluate(()=>{let b=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"]),I=v=>{let x=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},_={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},D=document.querySelector("main");if(!D)return _;let B=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],k=Array.from(D.querySelectorAll("h2")),F=B.find(v=>{let x=v.textContent&&v.textContent.trim(),E=(x||"").replace(/\s*\(\d+\)$/,"").trim();return x&&x.length>1&&x.length<100&&!b.has(E)&&!C.has(E)}),K=F?F.textContent.trim():null,L=F?F.parentElement:null;for(;L&&L!==D&&!Array.from(L.children).filter(x=>x.tagName==="P").some(x=>{let E=x.textContent&&x.textContent.trim();return E&&E.length>5&&!I(E)});)L=L.parentElement;let se=null,ee=null,me=null,de=null;if(L&&L!==D){let v=Array.from(L.children).filter(E=>E.tagName==="P").filter(E=>{let te=E.textContent&&E.textContent.trim();return te&&te.length>5&&!I(te)});if(v[0]&&(se=v[0].textContent.trim()),v[1]){let E=v[1].textContent.trim().split(/\s*[·•]\s*/);ee=E[0]||null,E.length>1&&(me=E.slice(1).join(" \xB7 "))}let x=Array.from(L.children).filter(E=>E.tagName==="DIV");for(let E=x.length-1;E>=0;E--){let te=x[E].textContent&&x[E].textContent.trim();if(te&&!(K&&te.startsWith(K))&&(de=te.split(/[·•]/)[0].trim(),de))break}}let Ce=null;if(L){let v=L.querySelectorAll("p, span, div");for(let x of v){let E=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ce=E;break}}}let _e=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),O=T&&T.src||null,j=D.textContent||"",N=null,Y=j.match(/(\d+\+?)\s+connections\b/i);Y&&(N=Y[1]+" connections");let xe=null,tt=j.match(/(\d+)\s+mutual connection/i),nt=j.match(/and\s+(\d+)\s+other mutual/i),Qt=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);tt?xe=parseInt(tt[1],10):nt?xe=2+parseInt(nt[1],10):Qt&&(xe=2);let ot=null,rt=null,st=k.find(v=>v.textContent&&v.textContent.trim()==="About");if(st){let v=st.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").trim();x=x.replace(/^About\s*/,"").trim();let E=x.match(/Top skills\s*(.+?)$/i);if(E){let Oe=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(tn=>tn.trim()).filter(Boolean);Oe.length>0&&Oe.length<10&&(rt=Oe)}x=x.split(/\n?…\s*more/i)[0].trim(),x=x.split(/\n?\.\.\.\s*more/i)[0].trim(),x=x.split(/\bTop skills\b/i)[0].trim(),x=x.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ot=x||null}}let it=null,lt=k.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(lt){let v=lt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);x&&(it=parseInt(x[1].replace(/,/g,""),10))}}let Xt=[...new Set(k.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==K).filter(v=>b.has(v)))],pe=document.body.textContent||"",Zt=/#OpenToWork\b/i.test(pe)||/\bOpen to work\b/.test(pe),en=/#Hiring\b/i.test(pe)||/\bI'?m hiring\b/i.test(pe)||/\bWe are hiring\b/i.test(pe);return{name:K,title:se,location:de,currentCompany:ee,currentSchool:me,connectionDegree:Ce,hasVerifiedBadge:_e,photoUrl:O,connectionsLevel:N,mutualConnectionsCount:xe,followers:it,openToWork:Zt,hiring:en,about:ot,topSkills:rt,availableSections:Xt}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,f=null,h=null,p=null,S=null,w=null;if(o||s||i||l||c||r){let b=await Promise.resolve().then(()=>(It(),At));o&&(m=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(f=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${f.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(p=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),c&&(S=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),r&&(w=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...d,profileUrl:t,...m!==null&&{experience:m},...f!==null&&{featured:f},...h!==null&&{education:h},...p!==null&&{skillsFull:p},...S!==null&&{recommendations:S},...w!==null&&{certifications:w}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function ke(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(r=>r.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!s,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:l}:s&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function He(e){let t=null,n=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim();if(r&&!r.includes("notification"))return r;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(r=u.textContent?.trim(),r&&!r.includes("notification")))return r;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let r=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});r.count>0&&console.log(` S0: ${r.count} custom-invite links: ${JSON.stringify(r.labels)}`),t=await e.evaluateHandle(a=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=a.toLowerCase().split(" ")[0],f='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let p=h.getBoundingClientRect();if(p.width===0||p.height===0||h.closest(f))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(m))return h}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let r=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${r}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),f=document.querySelectorAll("button[aria-label]");return Array.from(f).filter(p=>{let S=p.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&m.test(S)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},r);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of m){let p=h.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&f.test(p))return h}return null},r);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let r=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping primary button: wrong person (${r})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let r of o){let u=await e.evaluate((a,d)=>{let m=a.className.includes("muted"),f=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(a.getAttribute("aria-label")||"").toLowerCase(),S=p.includes("invite"),w=d?p.includes(d):!0;return{isMuted:m,isStickyHeader:f,inRecommendations:h,hasInvite:S,matchesName:w,ariaLabel:p}},r,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=r;break}}for(let r of o)r!==i&&await r.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let r of c){let u=await e.evaluate(a=>{let d=a.getBoundingClientRect(),m=d.width>0&&d.height>0,f=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:f,top:d.top}},r);if(u.isVisible&&!u.isInStickyHeader){l=r,console.log(" Found More button by ID pattern (main)");break}}for(let r of c)r!==l&&await r.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let r=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(m=>{let f=m.innerText?.trim(),h=m.getAttribute("aria-label")||"",p=m.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:f==="Follow"||f==="Message"||f==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let d=a.parentElement;for(let m=0;m<8&&d;m++){for(let f of d.querySelectorAll("button"))if(f.innerText?.trim()==="More"&&f!==a)return f;d=d.parentElement}return null});l=r?.asElement?.()||null,l||await r?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await y(500),await e.evaluate(a=>a.click(),l),await y(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let a=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let m of d){let f=m.querySelector('a[href*="custom-invite"]');if(f)return f;for(let h of m.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=a?.asElement?.()||null,u||await a?.dispose?.().catch(()=>{})}if(!u){let a=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let f of d)for(let h of f.querySelectorAll('[role="menuitem"], a, div')){let p=h.innerText?.trim();p&&p.length<40&&m.push(p)}return[...new Set(m)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(r){console.log(" More dropdown click failed:",r.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let r=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping generic button: wrong person (${r})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Ln(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await y(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!l.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await y(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await y(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await y(3e3)):(await e.evaluate(a=>a.click(),t),await y(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let r=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(r?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Mn(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 y(1500);let n=await He(e);if(n){await e.evaluate(s=>s.click(),n),await y(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Pn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=Je();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let l=await qn(e,t,n);return l.connectionSent&&!i&&xt(t,o),l}async function qn(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=n,r={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
246
|
+
--- Connecting: ${u} ---`),c.length>0){let w=oe()[t]?.location;if(Dt(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),r.reason="excluded_location",r.profileInfo={location:w},r}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(5e3),await ie(e)&&(console.log(" Dismissed Premium overlay"),await y(2e3),await Tt(e,t),await y(2e3)),r.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),$=T=>{let O=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},b={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 b;let I=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],_=Array.from(C.querySelectorAll("h2")),D=I.find(T=>{let O=T.textContent&&T.textContent.trim();return O&&O.length>1&&O.length<100&&!w.has(O)&&O!=="0 notifications"}),B=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==C&&!Array.from(k.children).filter(j=>j.tagName==="P").some(j=>{let N=j.textContent&&j.textContent.trim();return N&&N.length>5&&!$(N)});)k=k.parentElement;let F=null,K=null,L=null;if(k&&k!==C){let T=Array.from(k.children),O=T.filter(N=>N.tagName==="P").filter(N=>{let Y=N.textContent&&N.textContent.trim();return Y&&Y.length>5&&!$(Y)});O[0]&&(F=O[0].textContent.trim()),O[1]&&(K=O[1].textContent.trim());let j=T.filter(N=>N.tagName==="DIV");for(let N=j.length-1;N>=0;N--){let Y=j[N].textContent&&j[N].textContent.trim();if(Y&&!(B&&Y.startsWith(B))&&(L=Y.split(/[·•]/)[0].trim(),L))break}}let se=null;if(k){let T=k.querySelectorAll("p, span, div");for(let O of T){let j=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){se=j;break}}}let ee=null,me=_.find(T=>T.textContent&&T.textContent.trim()==="About");if(me){let T=me.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(ee=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,ee&&(ee=ee.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let de=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ce=de&&de.src||null,_e=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:B,title:F,location:L,about:ee,company:K,connectionDegree:se,connectionsCount:null,mutualConnections:null,photoUrl:Ce,hasVerifiedBadge:_e}}),c.length>0){let w=r.profileInfo?.location,$=oe()[t]?.location,b=w||$;if(Dt(b,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${b}`),r.reason="excluded_location",r;!w&&$==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await ke(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),r.reason="pending",r;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),r.reason="connected",r;await ie(e);let m=await He(e);if(!m&&(await ie(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await y(2e3),m=await He(e)),!m))return console.log(" \u2717 Connect not found"),r.reason="button_not_found",r;r.method=m.method;let f=await Ln(e,m.button);if(f==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),r.reason="wrong_target",r;if(f==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(4e3);let w=await ke(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await ie(e),await y(1e3);let $=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if($)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),$),await y(500),await $.click().catch(()=>e.evaluate(C=>C.click(),$)),await y(2e3);let b=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(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(_=>_.click(),b),await y(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 y(3e3),r.reason="premium_required",r;if(await ke(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.method="more_dropdown",r.withCustomMessage=!1,r;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await y(500),r.reason="premium_required",r}catch(b){return console.log(" More dropdown failed:",b.message),await e.keyboard.press("Escape").catch(()=>{}),r.reason="premium_required",r}else return console.log(" \u2717 No More button found \u2014 Premium required"),r.reason="premium_required",r}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await y(500),r.reason="email_required",r}let p=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!p&&!S){let w=await e.evaluate(()=>{let $=document.querySelector("#interop-outlet")?.shadowRoot;if(!$)return{addNote:!1,sendWithout:!1};let b=$.querySelector('button[aria-label="Add a note"]'),C=$.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=$?.asElement?.()||null,p||await $.dispose().catch(()=>{})}if(w.sendWithout){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=$?.asElement?.()||null,S||await $.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await y(1500),await e.$("div.modal-upsell")){let b=await Mn(e);return r.success=b,r.connectionSent=b,r.reason=b?"sent_without_note_upsell":"upsell_failed",r.withCustomMessage=!1,r}let $=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if($){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",b);await $.type(C,{delay:20}),await y(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(_=>_.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (with note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_with_note",r.withCustomMessage=!0,r.messageSent=C,r}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}else if(p&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}}else{console.log(" Sending without note (custom messages disabled)...");let w=S;if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}if(m.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 y(4e3)),await ie(e),await y(500);let $=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of $){let I=await e.evaluate(_=>{let D=_.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!_.closest('.sticky-header, [class*="sticky"]')}},C);if(I.visible&&!I.inSticky){b=C;break}}!b&&$.length>0&&(b=$[$.length-1]);for(let C of $)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),b),await y(500),await b.click().catch(()=>e.evaluate(I=>I.click(),b)),await y(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..."),r.method="more_dropdown",await e.evaluate(B=>B.click(),C),await y(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await ke(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r):(r.reason="premium_required",r);if(await ke(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;let D=await e.$('button[aria-label="Send without a note"]');if(D){console.log(" Modal appeared via More dropdown, sending without note...");try{await D.evaluate(B=>B.click())}catch{}return await y(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),r.reason="modal_failed",r}catch(u){console.error(` \u2717 Error: ${u.message}`),r.reason="error",r.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return r.fatal=!0,r;try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{r.fatal=!0}return r}}async function Rt(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:r=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
247
|
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let f=Ve();console.log(`Quota: today ${f.daily.sent}/${f.daily.max} | week ${f.weekly.sent}/${f.weekly.max}`)}console.log("");let m=0;for(let f=0;f<t.length;f++){let h=t[f];try{if(e.isClosed()){console.log(`
|
|
248
248
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
249
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${f+1}/${t.length}] Skipping - no URL`);continue}let p=vt(h.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,r&&await r(h,d,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl}`);let S=null;if(l){let w=await Fn(e,h.profileUrl);w?(Ie(h.profileUrl,{...w,source:
|
|
249
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${f+1}/${t.length}] Skipping - no URL`);continue}let p=vt(h.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,r&&await r(h,d,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl}`);let S=null;if(l){let w=await Fn(e,h.profileUrl);w?(Ie(h.profileUrl,{...w,source:a}),d.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(d.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=Je();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(S=await Pn(e,h.profileUrl,{message:o,useCustomMessage:s,excludeLocations:u,source:a,skipQuotaGate:!0}),S.success)d.connectionsSent++;else switch(S.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(S?.fatal){console.log(`
|
|
250
250
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(S?.reason==="error"){if(m++,m>=3){console.log(`
|
|
251
|
-
\u26A0 ${m} consecutive errors \u2014 aborting funnel`);break}}else m=0;if(S&&S.reason&&($t(h.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),kt(h.profileUrl,{source:
|
|
252
|
-
=== 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}`),!l){let f=Ve();console.log(` Connection quota left: today ${f.daily.remaining} of ${f.daily.max} | week ${f.weekly.remaining} of ${f.weekly.max}`)}return d}import"dotenv/config";import*as P from"fs";import*as X from"path";import{fileURLToPath as Bn}from"url";var Un=Bn(import.meta.url),Jn=X.dirname(X.dirname(Un)),ve=process.env.DATA_DIR?X.resolve(process.env.DATA_DIR,"collected-profiles"):X.join(Jn,"collected-profiles");function We(){P.existsSync(ve)||P.mkdirSync(ve,{recursive:!0})}function Vn(){return new Date().toISOString().split("T")[0]}function _t(e,t=null){let n=t||Vn();return X.join(ve,`${e}-${n}.json`)}function Ot(e,t=null){We();let n=_t(e,t);try{if(P.existsSync(n)){let o=P.readFileSync(n,"utf-8"),s=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${s.profiles.length} profiles from ${n}`),s.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function jt(e,t=null){return Ot(e,t).filter(o=>!o.processed)}function Nt(e,t,n,o=null){We();let s=_t(e,o);try{if(!P.existsSync(s))return;let i=JSON.parse(P.readFileSync(s,"utf-8")),l=i.profiles.find(a=>a.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let a=n.profileInfo;a.name&&(l.name=a.name),a.title&&(l.title=a.title),a.location&&(l.location=a.location),a.company&&(l.company=a.company),a.connectionDegree&&(l.connectionDegree=a.connectionDegree),a.connectionsCount&&(l.connectionsCount=a.connectionsCount),a.mutualConnections&&(l.mutualConnections=a.mutualConnections),a.photoUrl&&(l.photoUrl=a.photoUrl),a.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=a.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),P.writeFileSync(s,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Ft(e){let t=Ot(e),n=t.filter(s=>s.processed),o=t.filter(s=>!s.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((s,i)=>(s[i.status]=(s[i.status]||0)+1,s),{})}}function Mt(){We();try{return P.readdirSync(ve).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let s=JSON.parse(P.readFileSync(X.join(ve,t),"utf-8"));return{file:t,source:n,date:o,count:s.profiles?.length||0,unprocessed:s.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as g from"fs";import*as Ze from"os";import*as A from"path";import{fileURLToPath as yo}from"url";var Ke={};Ee(Ke,{NAME:()=>Wn,VERSION:()=>Hn,up:()=>Kn});import*as V from"fs";import*as Te from"path";var Hn=1,Wn="normalize-jobs-and-questions",Yn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Gn=50;function Ye(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Ge(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(s){try{V.unlinkSync(o)}catch{}throw s}try{V.renameSync(o,e)}catch(s){try{V.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Kn(e,t){let n=Te.join(e,"jobs.json"),o=Te.join(t,"scouted-jobs.json"),s=Te.join(e,"application-questions.json"),i=Ye(n)||{},l=Ye(o)||{},a=0,r=[];for(let c of Object.keys(i)){if(!l[c])continue;let d=l[c],m=i[c];for(let f of Yn)d[f]!=null&&m[f]==null&&(m[f]=d[f]);r.push(c),a++}a>0?(Ge(n,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ye(s);if(u&&Array.isArray(u.applications)){let c={},d=0;for(let m of u.applications){let f=m.jobId||"unknown";c[f]||(c[f]={applications:[]});let h=(m.questions||[]).map(p=>{let S={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Gn?S.options=p.options:(S.optionsOmitted=!0,d++)),p.page&&(S.page=p.page),p.wasPreFilled&&(S.wasPreFilled=!0),p.wasRetry&&(S.wasRetry=!0),S});c[f].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||h.length,questions:h})}Ge(s,c),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(r.length>0){for(let c of r)delete l[c];Ge(o,l),console.log(` Phase 3: Removed ${r.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ze={};Ee(ze,{NAME:()=>Qn,VERSION:()=>zn,up:()=>eo});import*as H from"fs";import*as Lt from"path";var zn=2,Qn="reset-unread-flags";function Xn(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Zn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(s){try{H.unlinkSync(o)}catch{}throw s}try{H.renameSync(o,e)}catch(s){try{H.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function eo(e){let t=Lt.join(e,"conversations.json"),n=Xn(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zn(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Qe={};Ee(Qe,{NAME:()=>no,VERSION:()=>to,up:()=>lo});import*as W from"fs";import*as Pt from"path";var to=3,no="recompute-last-message-by",oo=new Set(["draft","confirmed","rejected","needs_review"]);function ro(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function so(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(s){try{W.unlinkSync(o)}catch{}throw s}try{W.renameSync(o,e)}catch(s){try{W.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function io(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!oo.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,l)=>l.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function lo(e){let t=Pt.join(e,"conversations.json"),n=ro(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,l=0;for(let a of Object.keys(n)){let r=n[a];if(!r||typeof r!="object")continue;Object.prototype.hasOwnProperty.call(r,"_cardSynced")&&(delete r._cardSynced,i++);let u=Array.isArray(r.messages)?r.messages:[],c=io(u,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";r.lastMessageBy!==c&&l++,r.lastMessageBy=c,r.conversationStatus=d,s++}if(s===0){console.log(" No conversations to recompute.");return}so(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${l} 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.")}import"dotenv/config";import*as U from"path";import{fileURLToPath as ao}from"url";var co=ao(import.meta.url),uo=U.dirname(U.dirname(co)),$e=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(uo,"market-research"),br=U.join($e,"scouted-jobs.json"),kr=U.join($e,"discovered-people.json"),vr=U.join($e,"visit-log.json"),$r=U.join($e,"companies.json"),Cr=U.join($e,"job-decisions.json");function qt(){fo=null,mo=null,po=null,ho=null,go=null}var fo=null;var mo=null;var po=null;var ho=null;var go=null;var wo=yo(import.meta.url),So=A.dirname(wo),bo=A.dirname(A.dirname(So));function ko(e){return e&&(e==="~"?Ze.homedir():e.startsWith("~/")||e.startsWith("~\\")?A.join(Ze.homedir(),e.slice(2)):e)}var G=process.env.DATA_DIR?A.resolve(ko(process.env.DATA_DIR)):bo,ce=A.join(G,"collected-profiles"),ue=A.join(G,"market-research"),q=A.join(G,".schema-version"),Bt=[A.join(ce,".schema-version"),A.join(ue,".schema-version")],re=3,Z=[{version:1,module:Ke},{version:2,module:ze},{version:3,module:Qe}];(function(){Z.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of Z){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=Z.length?Z[Z.length-1].version:0;if(n!==re)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${re}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<Z.length;o++){let s=o+1;if(Z[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${Z[o].version}`)}})();function Ht(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
251
|
+
\u26A0 ${m} consecutive errors \u2014 aborting funnel`);break}}else m=0;if(S&&S.reason&&($t(h.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),kt(h.profileUrl,{source:a||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:S.reason})),r&&await r(h,d,S),f<t.length-1){let w=c+Math.random()*2e3;await y(w)}}if(console.log(`
|
|
252
|
+
=== 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}`),!l){let f=Ve();console.log(` Connection quota left: today ${f.daily.remaining} of ${f.daily.max} | week ${f.weekly.remaining} of ${f.weekly.max}`)}return d}import"dotenv/config";import*as P from"fs";import*as X from"path";import{fileURLToPath as Bn}from"url";var Un=Bn(import.meta.url),Jn=X.dirname(X.dirname(Un)),ve=process.env.DATA_DIR?X.resolve(process.env.DATA_DIR,"collected-profiles"):X.join(Jn,"collected-profiles");function We(){P.existsSync(ve)||P.mkdirSync(ve,{recursive:!0})}function Vn(){return new Date().toISOString().split("T")[0]}function _t(e,t=null){let n=t||Vn();return X.join(ve,`${e}-${n}.json`)}function Ot(e,t=null){We();let n=_t(e,t);try{if(P.existsSync(n)){let o=P.readFileSync(n,"utf-8"),s=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${s.profiles.length} profiles from ${n}`),s.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function jt(e,t=null){return Ot(e,t).filter(o=>!o.processed)}function Nt(e,t,n,o=null){We();let s=_t(e,o);try{if(!P.existsSync(s))return;let i=JSON.parse(P.readFileSync(s,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),P.writeFileSync(s,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Ft(e){let t=Ot(e),n=t.filter(s=>s.processed),o=t.filter(s=>!s.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((s,i)=>(s[i.status]=(s[i.status]||0)+1,s),{})}}function Lt(){We();try{return P.readdirSync(ve).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let s=JSON.parse(P.readFileSync(X.join(ve,t),"utf-8"));return{file:t,source:n,date:o,count:s.profiles?.length||0,unprocessed:s.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as g from"fs";import*as Ze from"os";import*as A from"path";import{fileURLToPath as yo}from"url";var Ke={};Ee(Ke,{NAME:()=>Wn,VERSION:()=>Hn,up:()=>Kn});import*as V from"fs";import*as Te from"path";var Hn=1,Wn="normalize-jobs-and-questions",Yn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Gn=50;function Ye(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Ge(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(s){try{V.unlinkSync(o)}catch{}throw s}try{V.renameSync(o,e)}catch(s){try{V.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Kn(e,t){let n=Te.join(e,"jobs.json"),o=Te.join(t,"scouted-jobs.json"),s=Te.join(e,"application-questions.json"),i=Ye(n)||{},l=Ye(o)||{},c=0,r=[];for(let a of Object.keys(i)){if(!l[a])continue;let d=l[a],m=i[a];for(let f of Yn)d[f]!=null&&m[f]==null&&(m[f]=d[f]);r.push(a),c++}c>0?(Ge(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ye(s);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let m of u.applications){let f=m.jobId||"unknown";a[f]||(a[f]={applications:[]});let h=(m.questions||[]).map(p=>{let S={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Gn?S.options=p.options:(S.optionsOmitted=!0,d++)),p.page&&(S.page=p.page),p.wasPreFilled&&(S.wasPreFilled=!0),p.wasRetry&&(S.wasRetry=!0),S});a[f].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||h.length,questions:h})}Ge(s,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(r.length>0){for(let a of r)delete l[a];Ge(o,l),console.log(` Phase 3: Removed ${r.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ze={};Ee(ze,{NAME:()=>Qn,VERSION:()=>zn,up:()=>eo});import*as H from"fs";import*as Mt from"path";var zn=2,Qn="reset-unread-flags";function Xn(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Zn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(s){try{H.unlinkSync(o)}catch{}throw s}try{H.renameSync(o,e)}catch(s){try{H.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function eo(e){let t=Mt.join(e,"conversations.json"),n=Xn(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zn(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Qe={};Ee(Qe,{NAME:()=>no,VERSION:()=>to,up:()=>lo});import*as W from"fs";import*as Pt from"path";var to=3,no="recompute-last-message-by",oo=new Set(["draft","confirmed","rejected","needs_review"]);function ro(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function so(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(s){try{W.unlinkSync(o)}catch{}throw s}try{W.renameSync(o,e)}catch(s){try{W.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function io(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!oo.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,l)=>l.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function lo(e){let t=Pt.join(e,"conversations.json"),n=ro(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,l=0;for(let c of Object.keys(n)){let r=n[c];if(!r||typeof r!="object")continue;Object.prototype.hasOwnProperty.call(r,"_cardSynced")&&(delete r._cardSynced,i++);let u=Array.isArray(r.messages)?r.messages:[],a=io(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";r.lastMessageBy!==a&&l++,r.lastMessageBy=a,r.conversationStatus=d,s++}if(s===0){console.log(" No conversations to recompute.");return}so(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${l} 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.")}import"dotenv/config";import*as U from"path";import{fileURLToPath as ao}from"url";var co=ao(import.meta.url),uo=U.dirname(U.dirname(co)),$e=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(uo,"market-research"),br=U.join($e,"scouted-jobs.json"),kr=U.join($e,"discovered-people.json"),vr=U.join($e,"visit-log.json"),$r=U.join($e,"companies.json"),Cr=U.join($e,"job-decisions.json");function qt(){fo=null,mo=null,po=null,ho=null,go=null}var fo=null;var mo=null;var po=null;var ho=null;var go=null;var wo=yo(import.meta.url),So=A.dirname(wo),bo=A.dirname(A.dirname(So));function ko(e){return e&&(e==="~"?Ze.homedir():e.startsWith("~/")||e.startsWith("~\\")?A.join(Ze.homedir(),e.slice(2)):e)}var G=process.env.DATA_DIR?A.resolve(ko(process.env.DATA_DIR)):bo,ce=A.join(G,"collected-profiles"),ue=A.join(G,"market-research"),q=A.join(G,".schema-version"),Bt=[A.join(ce,".schema-version"),A.join(ue,".schema-version")],re=3,Z=[{version:1,module:Ke},{version:2,module:ze},{version:3,module:Qe}];(function(){Z.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of Z){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=Z.length?Z[Z.length-1].version:0;if(n!==re)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${re}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<Z.length;o++){let s=o+1;if(Z[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${Z[o].version}`)}})();function Ht(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
253
253
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
254
254
|
`),process.exit(1));try{g.mkdirSync(G,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
255
255
|
[FATAL] Cannot create DATA_DIR (${G}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -271,7 +271,7 @@ ${o.join(`
|
|
|
271
271
|
[FATAL] ${q} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
272
272
|
`),process.exit(1)}let t=xo(e);return t===null&&(console.error(`
|
|
273
273
|
[FATAL] ${q} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
274
|
-
`),process.exit(1)),t}function Wt(e){try{g.chmodSync(e,384)}catch{}}function Eo(e){if(Ht(),g.existsSync(q))try{if(g.lstatSync(q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${q}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=q+".tmp";try{g.writeFileSync(t,JSON.stringify(e,null,2)),Wt(t),g.renameSync(t,q)}catch(n){try{g.unlinkSync(t)}catch{}throw n}}function Vt(e,t){if(!g.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=g.readdirSync(e).filter(
|
|
274
|
+
`),process.exit(1)),t}function Wt(e){try{g.chmodSync(e,384)}catch{}}function Eo(e){if(Ht(),g.existsSync(q))try{if(g.lstatSync(q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${q}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=q+".tmp";try{g.writeFileSync(t,JSON.stringify(e,null,2)),Wt(t),g.renameSync(t,q)}catch(n){try{g.unlinkSync(t)}catch{}throw n}}function Vt(e,t){if(!g.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=g.readdirSync(e).filter(c=>{let r=c.toLowerCase();if(r.includes(".backup")||r===".schema-version"||r.endsWith(".tmp"))return!1;try{return g.statSync(A.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,l=[];for(let c of o){let r=A.join(e,c),u=A.join(e,c+n);if(g.existsSync(u)){i++;continue}try{Gt(r,u),s++}catch(a){l.push({file:c,err:a.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${A.basename(e)}/: `+l.map(r=>`${r.file} (${r.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${A.basename(e)}/ (${n})${c}`)}}var Xe=!1;async function Yt(){if(Xe)return;Ht(),Ro();let t=Jt().version;if(t===re){Xe=!0;return}$o(),vo(),process.on("exit",et),t>re&&(console.error(`
|
|
275
275
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${re}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
276
276
|
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${re}.
|
|
277
277
|
`),process.exit(1)),console.log(`
|
|
@@ -281,17 +281,17 @@ ${o.join(`
|
|
|
281
281
|
`),process.exit(1)}let o=Z.filter(s=>s.version>t);for(let s of o){console.log(`
|
|
282
282
|
Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{Vt(ce,s.version),Vt(ue,s.version)}catch(r){console.error(`
|
|
283
283
|
[FATAL] Pre-migration backup failed for ${i}: ${r.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
284
|
-
`),process.exit(1)}let
|
|
284
|
+
`),process.exit(1)}let c=s.module;try{await c.up(ce,ue)}catch(r){console.error(`
|
|
285
285
|
[FATAL] Migration ${i} failed: ${r.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=Oo(l);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
286
286
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
287
287
|
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
288
|
-
`)}process.exit(1)}try{let r=new Date().toISOString(),u={version:s.version,name:
|
|
288
|
+
`)}process.exit(1)}try{let r=new Date().toISOString(),u={version:s.version,name:c.NAME||i,appliedAt:r},a=Jt();a.version=s.version,a.migratedAt=r,a.migrations=a.migrations||[],a.migrations.push(u),Eo(a)}catch(r){console.error(`
|
|
289
289
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${r.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
290
290
|
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{St()}catch{}try{qt()}catch{}Xe=!0,et(),console.log(`
|
|
291
291
|
\u2713 Schema is now at v${re}
|
|
292
|
-
`)}var Ao=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Io(e){let t=e.toLowerCase();return Ao.some(n=>n.test(t))}var Do=6e4;function To(){let e=Date.now(),t=[];for(let n of[G,ce,ue]){if(!g.existsSync(n))continue;let o;try{o=g.readdirSync(n)}catch{continue}for(let s of o){if(!Io(s))continue;let i=A.join(n,s);try{let l=g.statSync(i);if(!l.isFile()||e-l.mtimeMs<Do)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Ro({verbose:e=!1}={}){let t=To();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{g.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${A.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function _o(){let e=[];for(let t of[ce,ue]){if(!g.existsSync(t))continue;let n=g.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=A.join(t,o);try{Re(s)}catch(i){e.push({dir:A.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Oo(e){let t=[],n=[];for(let i of[ce,ue]){if(!g.existsSync(i))continue;let l=g.readdirSync(i).filter(
|
|
292
|
+
`)}var Ao=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Io(e){let t=e.toLowerCase();return Ao.some(n=>n.test(t))}var Do=6e4;function To(){let e=Date.now(),t=[];for(let n of[G,ce,ue]){if(!g.existsSync(n))continue;let o;try{o=g.readdirSync(n)}catch{continue}for(let s of o){if(!Io(s))continue;let i=A.join(n,s);try{let l=g.statSync(i);if(!l.isFile()||e-l.mtimeMs<Do)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Ro({verbose:e=!1}={}){let t=To();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{g.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${A.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function _o(){let e=[];for(let t of[ce,ue]){if(!g.existsSync(t))continue;let n=g.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=A.join(t,o);try{Re(s)}catch(i){e.push({dir:A.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Oo(e){let t=[],n=[];for(let i of[ce,ue]){if(!g.existsSync(i))continue;let l=g.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let r=A.join(i,c),u=c.slice(0,-e.length),a=A.join(i,u);try{u.toLowerCase().endsWith(".json")?Re(r):g.accessSync(r,g.constants.R_OK),t.push({backupPath:r,originalPath:a,fileName:c,dir:i})}catch(d){n.push(`${A.basename(i)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:r}of t)try{Gt(i,l),o++}catch(u){s.push(`${A.basename(r)}/${c}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Gt(e,t){let n=t+".tmp";try{g.copyFileSync(e,n),Wt(n)}catch(o){try{g.unlinkSync(n)}catch{}throw o}try{g.renameSync(n,t)}catch(o){try{g.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}import Kt from"fs";import jo from"path";var No="cookies.json";function Fo(){let e=process.env.ILML_SCOPE_DIR;return e?jo.join(e,"plugins-state","linkedin","cookies.json"):No}function zt(){let e=Fo();if(!Kt.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Kt.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}await Yt();function Mo(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function Po(){let e=Mo();if(e.list){console.log(`
|
|
293
293
|
\u{1F4C2} Available profile files:
|
|
294
|
-
`);let r=
|
|
294
|
+
`);let r=Lt();if(r.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of r)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
|
|
295
295
|
========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
|
|
296
296
|
`),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=jt(e.source,e.date);console.log(`
|
|
297
297
|
Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
@@ -299,10 +299,10 @@ Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
|
299
299
|
Profiles:`),t.slice(0,10).forEach((r,u)=>{console.log(` ${u+1}. ${r.name||"Unknown"} - ${r.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
|
|
300
300
|
Press Enter to start, or Ctrl+C to cancel...`),await new Promise(r=>{process.stdin.once("data",()=>r())}),console.log(`
|
|
301
301
|
\u{1F680} Starting browser...
|
|
302
|
-
`);let n=await
|
|
302
|
+
`);let n=await Lo.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),o=await n.newPage();try{let r=zt();await o.setCookie(...r),console.log(`\u2713 Cookies loaded
|
|
303
303
|
`)}catch(r){console.error(`
|
|
304
304
|
[!] ${r.message}
|
|
305
|
-
`),await n.close(),process.exit(1)}let s=e.viewOnly?"view-only":"connect",i=pt("funnel",s),l=await Rt(o,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(r,u,
|
|
305
|
+
`),await n.close(),process.exit(1)}let s=e.viewOnly?"view-only":"connect",i=pt("funnel",s),l=await Rt(o,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(r,u,a)=>{Nt(e.source,r.profileUrl,{status:a.reason,connectionSent:a.connectionSent,withCustomMessage:a.withCustomMessage,message:a.messageSent,method:a.method,reason:a.reason,error:a.error,profileInfo:a.profileInfo})}});console.log(`
|
|
306
306
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
307
|
-
`);let
|
|
308
|
-
Status breakdown:`);for(let[r,u]of Object.entries(
|
|
307
|
+
`);let c=Ft(e.source);if(console.log(`Processed: ${c.processed}/${c.total}`),console.log(`Remaining: ${c.unprocessed}`),Object.keys(c.statuses).length>0){console.log(`
|
|
308
|
+
Status breakdown:`);for(let[r,u]of Object.entries(c.statuses))console.log(` ${r}: ${u}`)}Fe(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await n.close(),process.exit(0)}Po().catch(e=>{console.error("Funnel failed:",e);try{Fe(null,"error",null,e.message)}catch{}process.exit(1)});
|