ilml-plugin-linkedin 1.6.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/applyQueue.mjs +18 -18
- package/dist/daily.mjs +16 -16
- package/dist/enrichProfiles.mjs +264 -0
- package/dist/funnelRunner.mjs +47 -47
- package/dist/messageBot.mjs +31 -31
- package/dist/migrationCli.mjs +17 -17
- package/dist/profileHistory.mjs +9 -0
- package/dist/run.mjs +57 -58
- package/dist/scout.mjs +42 -42
- package/dist/syncAll.mjs +114 -114
- package/dist/verifyAbout.mjs +214 -0
- package/dist/viewers.mjs +70 -70
- package/dist/visit.mjs +115 -115
- package/ilml-plugin.json +3 -1
- package/package.json +5 -1
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,71 +1,71 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ot=Object.defineProperty;var Je=(e,t)=>{for(var o in t)Ot(e,o,{get:t[o],enumerable:!0})};import Yo from"puppeteer";import"dotenv/config";import*as q from"fs";import*as K from"path";import{fileURLToPath as Ft}from"url";import"dotenv/config";import{createGraphClient as jt,resolveToken as Tt}from"@ilivemylife/graph-sdk";import{config as _t}from"dotenv";_t();var He=Tt()||process.env.TOKEN;He||(console.error(`
|
|
2
2
|
[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.
|
|
3
3
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
4
4
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
5
|
-
`),process.exit(1));var
|
|
5
|
+
`),process.exit(1));var Ve=jt({token:He});function Rt(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),s=t%60;return s?`${o}m ${s}s`:`${o}m`}function Nt({scriptName:e,mode:t,status:o,error:s,duration:r}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Rt(r)}`:"",n=o==="error"?`error${s?`: ${String(s).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${n} \u2014 ${l}${c}`}async function We({scriptName:e,mode:t,status:o,summaryLines:s,error:r,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(s)||s.length===0)return;let n=`**${Nt({scriptName:e,mode:t,status:o,error:r,duration:i})}**
|
|
6
6
|
|
|
7
7
|
${s.join(`
|
|
8
|
-
`)}`;try{await ke.addMessage(l,n)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var yo=go(import.meta.url),wo=P.dirname(P.dirname(yo)),se=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(wo,"collected-profiles"),re=P.join(se,"run-log.json");function So(e,o){let t=JSON.stringify(o,null,2),s=e+".tmp";O.writeFileSync(s,t);for(let r=0;r<3;r++)try{O.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ce(){try{if(!O.existsSync(re))return{runs:[]};let e=JSON.parse(O.readFileSync(re,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ie(e){O.existsSync(se)||O.mkdirSync(se,{recursive:!0});try{So(re,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function Ee(e,o="default"){let t=Ce();for(let l of t.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let s=new Date,r={timestamp:s.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(l=>new Date(l.timestamp).getTime()>i),Ie(t),{script:e,mode:o,startTime:s.getTime(),runIndex:t.runs.length-1}}function ie(e,o,t=null,s=null){if(!e)return;let r=null;try{let l=Ce(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=t,c.error=s,r=c.duration;else{let n=l.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());n&&(n.status=o,n.result=o,n.duration=Date.now()-e.startTime,n.stats=t,n.error=s,r=n.duration)}Ie(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";$e({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:s,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}async function y(e){let o=Math.floor(Math.random()*2001),t=e+o;return new Promise(s=>setTimeout(s,t))}async function B(e){return await e.evaluate(()=>{let o=document.querySelectorAll("div.artdeco-modal--is-open");for(let s of o){let r=s.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||c){let n=s.querySelector('button[aria-label="Dismiss"]')||s.querySelector("button.artdeco-modal__dismiss")||s.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:r.substring(0,80)};let a=s.querySelectorAll("button");for(let u of a){let d=u.innerText?.trim().toLowerCase()||"",h=u.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||h.includes("dismiss"))return u.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let t=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(t){let s=t.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||t.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(s)return s.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import"dotenv/config";import*as C from"fs";import*as E from"path";import{fileURLToPath as bo}from"url";var vo=bo(import.meta.url),ko=E.dirname(E.dirname(vo)),L=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"collected-profiles"):E.join(ko,"collected-profiles"),le=E.join(L,"people.json"),Bt=E.join(L,"jobs.json"),xe=E.join(L,"quota.json"),Jt=E.join(L,"conversations.json"),Wt=E.join(L,"sync-state.json"),Vt=E.join(L,"application-questions.json"),Y=20,Q=100,H=null,$o=null,N=null,Co=null,Io=null,Eo=null;function Ae(){H=null,$o=null,N=null,Co=null,Io=null,Eo=null}function ee(){C.existsSync(L)||C.mkdirSync(L,{recursive:!0})}function De(e,o){let t=JSON.stringify(o,null,2),s=e+".tmp";C.writeFileSync(s,t);for(let r=0;r<3;r++)try{C.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Oe(e,o){if(!C.existsSync(e))return null;try{let t=JSON.parse(C.readFileSync(e,"utf-8"));try{C.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${E.resolve(e)}`);let s=e+".backup";if(C.existsSync(s))try{let r=JSON.parse(C.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{C.copyFileSync(s,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{C.copyFileSync(e,e+".corrupted")}catch{}return null}}function z(){return new Date().toISOString().split("T")[0]}var je=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];function oe(){return H||(ee(),H=Oe(le,"people.json")||{},H)}function ae(e){ee(),H=e;try{De(le,e)}catch(o){console.error(`[!] Failed to save people.json: ${o.message}`),console.error(` Path: ${E.resolve(le)}`)}}function xo(e,o={}){if(!e)return null;let t=oe(),s=z(),r=new Date().toISOString(),i=t[e];if(i){i.seenCount=(i.seenCount||1)+1,i.lastSeen=s,i.lastUpdated=r,o.source&&!i.sources?.includes(o.source)&&(i.sources=i.sources||[],i.sources.push(o.source));for(let l of je)o[l]!=null&&(i[l]=o[l])}else t[e]={name:o.name||null,title:o.title||null,location:o.location||null,company:o.company||null,connectionDegree:o.connectionDegree||null,connectionsCount:o.connectionsCount||null,mutualConnections:o.mutualConnections||null,photoUrl:o.photoUrl||null,hasVerifiedBadge:o.hasVerifiedBadge||!1,firstSeen:s,lastSeen:s,seenCount:1,sources:o.source?[o.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r};return ae(t),t[e]}function _e(e,o){if(!e||!o)return;let t=oe(),s=t[e];if(!s)return;s.encounters||(s.encounters=[]);let i={date:z(),source:o.source||"unknown",action:o.action||"unknown"};o.jobId&&(i.jobId=String(o.jobId)),o.jobTitle&&(i.jobTitle=o.jobTitle),o.jobCompany&&(i.jobCompany=o.jobCompany),!s.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(s.encounters.push(i),s.lastUpdated=new Date().toISOString(),ae(t))}function Re(e){return e&&oe()[e]?.connectionStatus||null}function Te(e,o,t={}){if(!e)return;let s=oe(),r=s[e];if(r||(xo(e,t.profileInfo||{}),r=s[e]),!!r){if(r.connectionStatus=o,r.connectionDate=z(),r.connectionMethod=t.method||r.connectionMethod,r.messageSent=t.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),t.profileInfo)for(let i of je)t.profileInfo[i]!=null&&(r[i]=t.profileInfo[i]);ae(s)}}function Ne(){return N||(ee(),N=Oe(xe,"quota.json"),(!N||!N.connections)&&(N={connections:[]}),N)}function Ao(e){ee(),N=e;try{De(xe,e)}catch(o){console.error(`[!] Failed to save quota.json: ${o.message}`)}}function Fe(e,o="unknown"){let t=Ne(),s=new Date;t.connections.push({date:s.toISOString().split("T")[0],time:s.toTimeString().split(" ")[0],profileUrl:e,source:o}),Ao(t)}function Me(){let e=Ne(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(s=>s.date>=t)}function Pe(){let e=Me(),o=z(),t=e.filter(n=>n.date===o).length,s=e.length,r=t>=Y,i=s>=Q,l=!r&&!i,c={allowed:l,daily:{sent:t,max:Y},weekly:{sent:s,max:Q}};return l||(c.reason=r?`Daily limit reached (${t}/${Y})`:`Weekly limit reached (${s}/${Q})`),c}function ce(){let e=Me(),o=z(),t=e.filter(r=>r.date===o).length,s=e.length;return{daily:{sent:t,max:Y,remaining:Y-t},weekly:{sent:s,max:Q,remaining:Q-s}}}async function Le(e,o){let t=e.url();if(t.includes("/in/"))return!1;if(t.includes("/login")||t.includes("/authwall")||t.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${t.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3);let s=e.url();return s.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${s.slice(0,80)}`),!0}function Do(e,o=[]){if(!e||!o||o.length===0)return!1;let t=e.toLowerCase();return o.some(s=>t.includes(s.toLowerCase()))}async function Oo(e,o){try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(2e3+Math.random()*2e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await y(1500),await Le(e,o));let s=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim()||null,i=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,c=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,a=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,d=document.querySelector(".dist-value")?.textContent?.trim()||null,m=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,g=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),S=g?parseInt(g[1],10):null,k=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,$=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:r,title:i,location:l,about:c,company:a,connectionDegree:d,connectionsCount:m,mutualConnections:S,photoUrl:k,hasVerifiedBadge:$}});return console.log(`Viewed: ${s.name} - ${s.title}`),{...s,profileUrl:o}}catch(t){console.error(`Error viewing profile ${o}:`,t.message);try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{}return null}}async function K(e){let o=await e.evaluate(()=>{let t=document.querySelectorAll('button[aria-label*="Pending"]'),s=Array.from(t).map(n=>n.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:t.length,pendingLabels:s,hasMessageBtn:!!r,hasConnectBtn:!!i};return t.length>0?{status:"pending",debug:l}:r&&!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(o.debug)),o.status}async function ue(e){let o=null,t=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(n=a.textContent?.trim(),n&&!n.includes("notification")))return n;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${t}"`),t){let n=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),o=await e.evaluateHandle(u=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),h=u.toLowerCase().split(" ")[0],m=null,w=null;for(let p of d){let g=p.getBoundingClientRect();if(g.width===0||g.height===0)continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(h)){m=p;break}w||(w=p)}return m||w||null},t);let a=o?.asElement?.()||null;if(a||await o?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(t){let n=t.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let a=await e.evaluate(d=>{let h=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let g=p.getAttribute("aria-label")||"";return(g.toLowerCase().includes("invite")||g.toLowerCase().includes("connect"))&&h.test(g)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},n);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),o=await e.evaluateHandle(d=>{let h=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let w of h){let p=w.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return w}return null},n);let u=o?.asElement?.()||null;if(u||await o?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,method:"name_matched_button"}}if(o=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),o&&t){let n=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),o),a=t.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(a)&&(console.log(` Skipping primary button: wrong person (${n})`),o=null)}if(o||(o=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),o)return console.log(" Found: primary button"),{button:o,method:"primary_button"};let s=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');s.length===0&&(s=await e.$$('button[aria-label="Connect"]'));let r=t?t.split(" ")[0].toLowerCase():"",i=null;for(let n of s){let a=await e.evaluate((u,d)=>{let h=u.className.includes("muted"),m=u.className.includes("sticky-header")||u.className.includes("sticky"),w=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(u.getAttribute("aria-label")||"").toLowerCase(),g=p.includes("invite"),S=d?p.includes(d):!0;return{isMuted:h,isStickyHeader:m,inRecommendations:w,hasInvite:g,matchesName:S,ariaLabel:p}},n,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=n;break}}for(let n of s)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(o=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),o||(o=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),o)return console.log(" Found: supplementary section"),{button:o,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let n of c){let a=await e.evaluate(u=>{let d=u.getBoundingClientRect(),h=d.width>0&&d.height>0,m=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:h,isInStickyHeader:m,top:d.top}},n);if(a.isVisible&&!a.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of c)n!==l&&await n.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 n=await e.evaluateHandle(()=>{let u=Array.from(document.querySelectorAll("button, a")).find(h=>{let m=h.innerText?.trim(),w=h.getAttribute("aria-label")||"",p=h.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||w.includes("Follow")||w.includes("Message")||w.includes("Invite")});if(!u)return null;let d=u.parentElement;for(let h=0;h<8&&d;h++){for(let m of d.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==u)return m;d=d.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),l),await y(500),await e.evaluate(u=>u.click(),l),await y(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),a||(a=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect"]')),!a){let u=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let h of d){let m=h.querySelector('a[href*="custom-invite"]');if(m)return m;for(let w of h.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(w.innerText?.trim()==="Connect")return w}return null});a=u?.asElement?.()||null,a||await u?.dispose?.().catch(()=>{})}if(!a){let u=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),h=[];for(let m of d)for(let w of m.querySelectorAll('[role="menuitem"], a, div')){let p=w.innerText?.trim();p&&p.length<40&&h.push(p)}return[...new Set(h)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(o=await e.$('button[aria-label*="Invite"]'),o&&t){let n=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),o),a=t.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(a)&&(console.log(` Skipping generic button: wrong person (${n})`),o=null)}return o||(o=await e.$('button[aria-label="Connect"]')),o?(console.log(" Found: generic button"),{button:o,method:"generic_button"}):null}async function jo(e,o){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),o),await y(500);let t=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),o),r=t.tag==="A"&&t.href&&t.href.includes("custom-invite"),i=t.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),o)]),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(),o),await y(3e3)):(await e.evaluate(a=>a.click(),o),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 c=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(c?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function _o(e){console.log(" Upsell: Premium required for notes");let o=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");o?await o.click():await e.keyboard.press("Escape"),await y(1500);let t=await ue(e);if(t){await e.evaluate(r=>r.click(),t),await y(2e3);let s=await e.$('button[aria-label="Send without a note"]');if(s){try{await s.evaluate(r=>r.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 Ro(e,o,t={}){let{message:s=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=t,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let a=o.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
9
|
-
--- Connecting: ${a} ---`),await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(5e3),await B(e)&&(console.log(" Dismissed Premium overlay"),await y(2e3),await Le(e,o),await y(2e3)),n.profileInfo=await e.evaluate(()=>{let S=document.querySelector("h1")?.textContent?.trim()||null,b=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,k=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,I=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,q=document.querySelector(".dist-value")?.textContent?.trim()||null,ro=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Se=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),io=Se?parseInt(Se[1],10):null,lo=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,ao=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:S,title:b,location:k,company:I,connectionDegree:q,connectionsCount:ro,mutualConnections:io,photoUrl:lo,hasVerifiedBadge:ao}}),c.length>0&&Do(n.profileInfo?.location,c))return console.log(` \u26A0 Excluded location: ${n.profileInfo.location}`),n.reason="excluded_location",n;let d=await K(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await B(e);let h=await ue(e);if(!h&&(await B(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await y(2e3),h=await ue(e)),!h))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=h.method,await jo(e,h.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(4e3);let S=await K(e);if(S==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${S} \u2014 trying More dropdown...`),await B(e),await y(1e3);let b=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(b)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),b),await y(500),await b.click().catch(()=>e.evaluate($=>$.click(),b)),await y(2e3);let k=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(k){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),k),await y(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),n.reason="premium_required",n;if(await K(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;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),n.reason="premium_required",n}catch(k){return console.log(" More dropdown failed:",k.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let S=await e.$('button[aria-label="Dismiss"]');return S&&await S.click(),await y(500),n.reason="email_required",n}let p=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!p&&!g){let S=await e.evaluate(()=>{let b=document.querySelector("#interop-outlet")?.shadowRoot;if(!b)return{addNote:!1,sendWithout:!1};let k=b.querySelector('button[aria-label="Add a note"]'),$=b.querySelector('button[aria-label="Send without a note"]');return{addNote:!!k,sendWithout:!!$}});if(S.addNote){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=b?.asElement?.()||null,p||await b.dispose().catch(()=>{})}if(S.sendWithout){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=b?.asElement?.()||null,g||await b.dispose().catch(()=>{})}}if(r){if(p&&s){if(console.log(" Adding personalized note..."),await p.click(),await y(1500),await e.$("div.modal-upsell")){let k=await _o(e);return n.success=k,n.connectionSent=k,n.reason=k?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let b=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(b){let k=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),$=s.replace("{name}",k);await b.type($,{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(T=>T.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=$,n}}}else if(g){console.log(" Sending without note...");try{await g.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(p&&!s){console.log(" No message provided, sending without note...");let S=await e.$('button[aria-label="Send without a note"]');if(S){try{await S.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let S=g;if(S){try{await S.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}if(h.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(4e3)),await B(e),await y(500);let b=await e.$$('button[id*="profile-overflow-action"]'),k=null;for(let $ of b){let I=await e.evaluate(T=>{let q=T.getBoundingClientRect();return{visible:q.width>0&&q.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},$);if(I.visible&&!I.inSticky){k=$;break}}!k&&b.length>0&&(k=b[b.length-1]);for(let $ of b)$!==k&&await $.dispose().catch(()=>{});if(k)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),k),await y(500),await k.click().catch(()=>e.evaluate(I=>I.click(),k)),await y(2e3);let $=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if($){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(G=>G.click(),$),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(o,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await K(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await K(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let q=await e.$('button[aria-label="Send without a note"]');if(q){console.log(" Modal appeared via More dropdown, sending without note...");try{await q.evaluate(G=>G.click())}catch{}return await y(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch($){console.log(" More dropdown fallback failed:",$.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(a){console.error(` \u2717 Error: ${a.message}`),n.reason="error",n.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{n.fatal=!0}return n}}async function Ue(e,o,t={}){let{message:s=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:n=null,excludeLocations:a=[],source:u="unknown"}=t,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
10
|
-
=== Running Funnel: ${
|
|
8
|
+
`)}`;try{await Ve.addMessage(l,n)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Pt=Ft(import.meta.url),Mt=K.dirname(K.dirname(Pt)),Ce=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"collected-profiles"):K.join(Mt,"collected-profiles"),Ae=K.join(Ce,"run-log.json");function Lt(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";q.writeFileSync(s,o);for(let r=0;r<3;r++)try{q.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ge(){try{if(!q.existsSync(Ae))return{runs:[]};let e=JSON.parse(q.readFileSync(Ae,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ye(e){q.existsSync(Ce)||q.mkdirSync(Ce,{recursive:!0});try{Lt(Ae,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ze(e,t="default"){let o=Ge();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let s=new Date,r={timestamp:s.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),Ye(o),{script:e,mode:t,startTime:s.getTime(),runIndex:o.runs.length-1}}function Ie(e,t,o=null,s=null){if(!e)return;let r=null;try{let l=Ge(),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=o,c.error=s,r=c.duration;else{let n=l.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=s,r=n.duration)}Ye(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";We({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:s,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}async function S(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(s=>setTimeout(s,o))}async function te(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let s of t){let r=s.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||c){let n=s.querySelector('button[aria-label="Dismiss"]')||s.querySelector("button.artdeco-modal__dismiss")||s.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:r.substring(0,80)};let a=s.querySelectorAll("button");for(let u of a){let f=u.innerText?.trim().toLowerCase()||"",h=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||h.includes("dismiss"))return u.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let s=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(s)return s.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import"dotenv/config";import*as D from"fs";import*as T from"path";import{fileURLToPath as Ut}from"url";var qt=Ut(import.meta.url),Bt=T.dirname(T.dirname(qt)),W=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(Bt,"collected-profiles"),xe=T.join(W,"people.json"),dn=T.join(W,"jobs.json"),Ze=T.join(W,"quota.json"),pn=T.join(W,"conversations.json"),mn=T.join(W,"sync-state.json"),hn=T.join(W,"application-questions.json"),Ee=T.join(W,"profile-history"),ue=20,fe=100,ie=null,Jt=null,V=null,Ht=null,Vt=null,Wt=null;function Xe(){ie=null,Jt=null,V=null,Ht=null,Vt=null,Wt=null}function be(){D.existsSync(W)||D.mkdirSync(W,{recursive:!0})}function De(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";D.writeFileSync(s,o);for(let r=0;r<3;r++)try{D.renameSync(s,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Oe(e,t){if(!D.existsSync(e))return null;try{let o=JSON.parse(D.readFileSync(e,"utf-8"));try{D.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${T.resolve(e)}`);let s=e+".backup";if(D.existsSync(s))try{let r=JSON.parse(D.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{D.copyFileSync(s,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{D.copyFileSync(e,e+".corrupted")}catch{}return null}}function de(){return new Date().toISOString().split("T")[0]}var Gt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],Yt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function je(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function zt(){D.existsSync(Ee)||D.mkdirSync(Ee,{recursive:!0})}function et(e){let t=je(e);return t?T.join(Ee,`${t}.json`):null}function Qt(e){let t=et(e);return t?Oe(t,`profile-history/${je(e)}.json`)||[]:[]}function Kt(e,t){let o=et(e);if(!o)return;zt();let s=Qt(e);s.unshift(t);try{De(o,s)}catch(r){console.error(`[!] Failed to append profile-history for ${je(e)}: ${r.message}`)}}function Qe(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ke(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Zt(e,t){if(!e)return[];let o=[];for(let s of Yt){let r=e[s],i=t[s];Qe(r)||Qe(i)||Ke(r)!==Ke(i)&&o.push(s)}return o}function Xt(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[s,r]of Object.entries(e))t.has(s)||(o[s]=r);return o}function Z(){return ie||(be(),ie=Oe(xe,"people.json")||{},ie)}function Te(e){be(),ie=e;try{De(xe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${T.resolve(xe)}`)}}function Se(e,t={}){if(!e)return null;let o=Z(),s=de(),r=new Date().toISOString(),i=o[e];if(i){let l=Zt(i,t);l.length>0&&(Kt(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:Xt(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=s,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let c of Gt)t[c]!=null&&(i[c]=t[c]);Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else o[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,firstSeen:s,lastSeen:s,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Te(o),o[e]}function tt(e,t){if(!e||!t)return;let o=Z(),s=o[e];if(!s)return;s.encounters||(s.encounters=[]);let i={date:de(),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),!s.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(s.encounters.push(i),s.lastUpdated=new Date().toISOString(),Te(o))}function ot(e){return e&&Z()[e]?.connectionStatus||null}function nt(e,t,o={}){if(!e)return;o.profileInfo?Se(e,o.profileInfo):Z()[e]||Se(e,{});let s=Z(),r=s[e];r&&(r.connectionStatus=t,r.connectionDate=de(),r.connectionMethod=o.method||r.connectionMethod,r.messageSent=o.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),Te(s))}function st(){return V||(be(),V=Oe(Ze,"quota.json"),(!V||!V.connections)&&(V={connections:[]}),V)}function eo(e){be(),V=e;try{De(Ze,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function rt(e,t="unknown"){let o=st(),s=new Date;o.connections.push({date:s.toISOString().split("T")[0],time:s.toTimeString().split(" ")[0],profileUrl:e,source:t}),eo(o)}function it(){let e=st(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(s=>s.date>=o)}function lt(){let e=it(),t=de(),o=e.filter(n=>n.date===t).length,s=e.length,r=o>=ue,i=s>=fe,l=!r&&!i,c={allowed:l,daily:{sent:o,max:ue},weekly:{sent:s,max:fe}};return l||(c.reason=r?`Daily limit reached (${o}/${ue})`:`Weekly limit reached (${s}/${fe})`),c}function _e(){let e=it(),t=de(),o=e.filter(r=>r.date===t).length,s=e.length;return{daily:{sent:o,max:ue,remaining:ue-o},weekly:{sent:s,max:fe,remaining:fe-s}}}async function ct(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let s=e.url();return s.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${s.slice(0,80)}`),!0}function at(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(s=>o.includes(s.toLowerCase()))}async function to(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await ct(e,t));let s=0;for(let i=0;i<2;i++){let l=await e.evaluate(()=>document.body.scrollHeight);for(let n=1;n<=6;n++)await e.evaluate(a=>window.scrollTo(0,a),l*n/6),await S(900);let c=await e.evaluate(()=>document.body.scrollHeight);if(c===s)break;s=c}await S(800);let r=await e.evaluate(()=>{let i=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"]),l=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),c=y=>{let $=(y||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},n={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},a=document.querySelector("main");if(!a)return n;let u=[...Array.from(a.querySelectorAll("h1")),...Array.from(a.querySelectorAll("h2"))],f=Array.from(a.querySelectorAll("h2")),h=u.find(y=>{let $=y.textContent&&y.textContent.trim(),C=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!i.has(C)&&!l.has(C)}),p=h?h.textContent.trim():null,g=h?h.parentElement:null;for(;g&&g!==a&&!Array.from(g.children).filter($=>$.tagName==="P").some($=>{let C=$.textContent&&$.textContent.trim();return C&&C.length>5&&!c(C)});)g=g.parentElement;let d=null,b=null,w=null,k=null;if(g&&g!==a){let y=Array.from(g.children).filter(C=>C.tagName==="P").filter(C=>{let Q=C.textContent&&C.textContent.trim();return Q&&Q.length>5&&!c(Q)});if(y[0]&&(d=y[0].textContent.trim()),y[1]){let C=y[1].textContent.trim().split(/\s*[·•]\s*/);b=C[0]||null,C.length>1&&(w=C.slice(1).join(" \xB7 "))}let $=Array.from(g.children).filter(C=>C.tagName==="DIV");for(let C=$.length-1;C>=0;C--){let Q=$[C].textContent&&$[C].textContent.trim();if(Q&&!(p&&Q.startsWith(p))&&(k=Q.split(/[·•]/)[0].trim(),k))break}}let A=null;if(g){let y=g.querySelectorAll("p, span, div");for(let $ of y){let C=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(C==="1st"||C==="2nd"||C==="3rd"){A=C;break}}}let v=!!a.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),O=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=O&&O.src||null,_=a.textContent||"",U=null,F=_.match(/(\d+\+?)\s+connections\b/i);F&&(U=F[1]+" connections");let ee=null,le=_.match(/(\d+)\s+mutual connection/i),re=_.match(/and\s+(\d+)\s+other mutual/i),ge=_.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);le?ee=parseInt(le[1],10):re?ee=2+parseInt(re[1],10):ge&&(ee=2);let z=null,ae=null,ce=f.find(y=>y.textContent&&y.textContent.trim()==="About");if(ce){let y=ce.parentElement;for(;y&&y.tagName!=="SECTION";)y=y.parentElement;if(y){let $=(y.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let C=$.match(/Top skills\s*(.+?)$/i);if(C){let $e=C[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Dt=>Dt.trim()).filter(Boolean);$e.length>0&&$e.length<10&&(ae=$e)}$=$.split(/\n?…\s*more/i)[0].trim(),$=$.split(/\n?\.\.\.\s*more/i)[0].trim(),$=$.split(/\bTop skills\b/i)[0].trim(),$=$.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),z=$||null}}let ye=null,we=f.find(y=>y.textContent&&y.textContent.trim()==="Activity");if(we){let y=we.parentElement;for(;y&&y.tagName!=="SECTION";)y=y.parentElement;if(y){let $=(y.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(ye=parseInt($[1].replace(/,/g,""),10))}}let x=[...new Set(f.map(y=>(y.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(y=>y&&y.length>1&&y.length<60&&y!==p).filter(y=>i.has(y)))],E=document.body.textContent||"",R=/#OpenToWork\b/i.test(E)||/\bOpen to work\b/.test(E),j=/#Hiring\b/i.test(E)||/\bI'?m hiring\b/i.test(E)||/\bWe are hiring\b/i.test(E);return{name:p,title:d,location:k,currentCompany:b,currentSchool:w,connectionDegree:A,hasVerifiedBadge:v,photoUrl:M,connectionsLevel:U,mutualConnectionsCount:ee,followers:ye,openToWork:R,hiring:j,about:z,topSkills:ae,availableSections:x}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}return null}}async function pe(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),s=Array.from(o).map(n=>n.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:s,hasMessageBtn:!!r,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:r&&!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 Re(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(n=a.textContent?.trim(),n&&!n.includes("notification")))return n;let u=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(u)return u.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let u=document.querySelectorAll('a[href*="custom-invite"]');return{count:u.length,labels:Array.from(u).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(u=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),h=u.toLowerCase().split(" ")[0],p=null,g=null;for(let d of f){let b=d.getBoundingClientRect();if(b.width===0||b.height===0)continue;if((d.getAttribute("aria-label")||"").toLowerCase().includes(h)){p=d;break}g||(g=d)}return p||g||null},o);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let a=await e.evaluate(f=>{let h=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(d=>{let b=d.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&h.test(b)}).map(d=>d.getAttribute("aria-label")?.slice(0,50))},n);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(f=>{let h=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of h){let d=g.getAttribute("aria-label")||"";if((d.toLowerCase().includes("invite")||d.toLowerCase().includes("connect"))&&p.test(d))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: button matching profile name"),{button:u,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),a=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(a)&&(console.log(` Skipping primary button: wrong person (${n})`),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 s=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');s.length===0&&(s=await e.$$('button[aria-label="Connect"]'));let r=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of s){let a=await e.evaluate((u,f)=>{let h=u.className.includes("muted"),p=u.className.includes("sticky-header")||u.className.includes("sticky"),g=u.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,d=(u.getAttribute("aria-label")||"").toLowerCase(),b=d.includes("invite"),w=f?d.includes(f):!0;return{isMuted:h,isStickyHeader:p,inRecommendations:g,hasInvite:b,matchesName:w,ariaLabel:d}},n,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=n;break}}for(let n of s)n!==i&&await n.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 n of c){let a=await e.evaluate(u=>{let f=u.getBoundingClientRect(),h=f.width>0&&f.height>0,p=u.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:h,isInStickyHeader:p,top:f.top}},n);if(a.isVisible&&!a.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of c)n!==l&&await n.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 n=await e.evaluateHandle(()=>{let u=Array.from(document.querySelectorAll("button, a")).find(h=>{let p=h.innerText?.trim(),g=h.getAttribute("aria-label")||"",d=h.getBoundingClientRect();return d.top<100||d.top>600||d.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!u)return null;let f=u.parentElement;for(let h=0;h<8&&f;h++){for(let p of f.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==u)return p;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),l),await S(500),await e.evaluate(u=>u.click(),l),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),a||(a=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect"]')),!a){let u=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let h of f){let p=h.querySelector('a[href*="custom-invite"]');if(p)return p;for(let g of h.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});a=u?.asElement?.()||null,a||await u?.dispose?.().catch(()=>{})}if(!a){let u=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),h=[];for(let p of f)for(let g of p.querySelectorAll('[role="menuitem"], a, div')){let d=g.innerText?.trim();d&&d.length<40&&h.push(d)}return[...new Set(h)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(u)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(u=>(u.getAttribute("aria-label")||"").toLowerCase(),t),a=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(a)&&(console.log(` Skipping generic button: wrong person (${n})`),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 oo(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let o=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(u=>u.click(),t)]),await S(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 S(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await S(3e3)):(await e.evaluate(a=>a.click(),t),await S(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 c=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(c?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function no(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let o=await Re(e);if(o){await e.evaluate(r=>r.click(),o),await S(2e3);let s=await e.$('button[aria-label="Send without a note"]');if(s){try{await s.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function so(e,t,o={}){let{message:s=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
9
|
+
--- Connecting: ${a} ---`),c.length>0){let w=Z()[t]?.location;if(at(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),n.reason="excluded_location",n.profileInfo={location:w},n}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await te(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await ct(e,t),await S(2e3)),n.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"]),k=x=>{let E=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(E)},A={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},v=document.querySelector("main");if(!v)return A;let O=[...Array.from(v.querySelectorAll("h1")),...Array.from(v.querySelectorAll("h2"))],M=Array.from(v.querySelectorAll("h2")),_=O.find(x=>{let E=x.textContent&&x.textContent.trim();return E&&E.length>1&&E.length<100&&!w.has(E)&&E!=="0 notifications"}),U=_?_.textContent.trim():null,F=_?_.parentElement:null;for(;F&&F!==v&&!Array.from(F.children).filter(R=>R.tagName==="P").some(R=>{let j=R.textContent&&R.textContent.trim();return j&&j.length>5&&!k(j)});)F=F.parentElement;let ee=null,le=null,re=null;if(F&&F!==v){let x=Array.from(F.children),E=x.filter(j=>j.tagName==="P").filter(j=>{let y=j.textContent&&j.textContent.trim();return y&&y.length>5&&!k(y)});E[0]&&(ee=E[0].textContent.trim()),E[1]&&(le=E[1].textContent.trim());let R=x.filter(j=>j.tagName==="DIV");for(let j=R.length-1;j>=0;j--){let y=R[j].textContent&&R[j].textContent.trim();if(y&&!(U&&y.startsWith(U))&&(re=y.split(/[·•]/)[0].trim(),re))break}}let ge=null;if(F){let x=F.querySelectorAll("p, span, div");for(let E of x){let R=(E.textContent||"").trim().replace(/^[·•]\s*/,"");if(R==="1st"||R==="2nd"||R==="3rd"){ge=R;break}}}let z=null,ae=M.find(x=>x.textContent&&x.textContent.trim()==="About");if(ae){let x=ae.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;x&&(z=(x.textContent||"").trim().replace(/^About\s*/,"").trim()||null,z&&(z=z.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let ce=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ye=ce&&ce.src||null,we=!!v.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:U,title:ee,location:re,about:z,company:le,connectionDegree:ge,connectionsCount:null,mutualConnections:null,photoUrl:ye,hasVerifiedBadge:we}}),c.length>0){let w=n.profileInfo?.location,k=Z()[t]?.location,A=w||k;if(at(A,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${A}`),n.reason="excluded_location",n;!w&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await pe(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await te(e);let h=await Re(e);if(!h&&(await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),h=await Re(e)),!h))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=h.method,await oo(e,h.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let w=await pe(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await te(e),await S(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),k),await S(500),await k.click().catch(()=>e.evaluate(v=>v.click(),k)),await S(2e3);let A=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(A){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),A),await S(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),n.reason="premium_required",n;if(await pe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),n.reason="premium_required",n}catch(A){return console.log(" More dropdown failed:",A.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}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 S(500),n.reason="email_required",n}let d=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!d&&!b){let w=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let A=k.querySelector('button[aria-label="Add a note"]'),v=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!A,sendWithout:!!v}});if(w.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));d=k?.asElement?.()||null,d||await k.dispose().catch(()=>{})}if(w.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=k?.asElement?.()||null,b||await k.dispose().catch(()=>{})}}if(r){if(d&&s){if(console.log(" Adding personalized note..."),await d.click(),await S(1500),await e.$("div.modal-upsell")){let A=await no(e);return n.success=A,n.connectionSent=A,n.reason=A?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let A=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),v=s.replace("{name}",A);await k.type(v,{delay:20}),await S(500);let O=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(O){try{await O.evaluate(M=>M.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=v,n}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(d&&!s){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(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w){try{await w.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await S(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}if(h.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3)),await te(e),await S(500);let k=await e.$$('button[id*="profile-overflow-action"]'),A=null;for(let v of k){let O=await e.evaluate(M=>{let _=M.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},v);if(O.visible&&!O.inSticky){A=v;break}}!A&&k.length>0&&(A=k[k.length-1]);for(let v of k)v!==A&&await v.dispose().catch(()=>{});if(A)try{await e.evaluate(O=>O.scrollIntoView({behavior:"smooth",block:"center"}),A),await S(500),await A.click().catch(()=>e.evaluate(O=>O.click(),A)),await S(2e3);let v=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(v){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(U=>U.click(),v),await S(3e3);let O=e.url();if(O.includes("/premium/")||O.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await pe(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await pe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let _=await e.$('button[aria-label="Send without a note"]');if(_){console.log(" Modal appeared via More dropdown, sending without note...");try{await _.evaluate(U=>U.click())}catch{}return await S(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(v){console.log(" More dropdown fallback failed:",v.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(a){console.error(` \u2717 Error: ${a.message}`),n.reason="error",n.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{n.fatal=!0}return n}}async function ut(e,t,o={}){let{message:s=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:n=null,excludeLocations:a=[],source:u="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
10
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!l){let p=_e();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let h=0;for(let p=0;p<t.length;p++){let g=t[p];try{if(e.isClosed()){console.log(`
|
|
11
11
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
12
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!
|
|
13
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),
|
|
14
|
-
\u26A0 ${h} consecutive errors \u2014 aborting funnel`);break}}else h=0;if(
|
|
15
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${
|
|
12
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let d=ot(g.profileUrl);if(d==="pending"||d==="connected"||d==="sent_with_note"||d==="sent_without_note"||d==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${d})`),d==="pending"||d==="sent_with_note"||d==="sent_without_note"||d==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,n&&await n(g,f,{success:!1,reason:d,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${g.name||g.profileUrl}`);let b=null;if(l){let w=await to(e,g.profileUrl);w?(Se(g.profileUrl,{...w,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=lt();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await so(e,g.profileUrl,{message:s,useCustomMessage:r,excludeLocations:a}),b.success)f.connectionsSent++,b.connectionSent&&rt(g.profileUrl,u);else switch(b.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(b?.fatal){console.log(`
|
|
13
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(b?.reason==="error"){if(h++,h>=3){console.log(`
|
|
14
|
+
\u26A0 ${h} consecutive errors \u2014 aborting funnel`);break}}else h=0;if(b&&b.reason&&(nt(g.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),tt(g.profileUrl,{source:u||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:b.reason})),n&&await n(g,f,b),p<t.length-1){let w=c+Math.random()*2e3;await S(w)}}if(console.log(`
|
|
15
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let p=_e();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return f}import"dotenv/config";import*as N from"fs";import*as G from"path";import{fileURLToPath as ro}from"url";var io=ro(import.meta.url),lo=G.dirname(G.dirname(io)),me=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"collected-profiles"):G.join(lo,"collected-profiles");function Ne(){N.existsSync(me)||N.mkdirSync(me,{recursive:!0})}function ao(){return new Date().toISOString().split("T")[0]}function ft(e,t=null){let o=t||ao();return G.join(me,`${e}-${o}.json`)}function dt(e,t=null){Ne();let o=ft(e,t);try{if(N.existsSync(o)){let s=N.readFileSync(o,"utf-8"),r=JSON.parse(s);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${o}`),r.profiles}}catch(s){console.error(`Error loading profiles from ${o}:`,s.message)}return[]}function pt(e,t=null){return dt(e,t).filter(s=>!s.processed)}function mt(e,t,o,s=null){Ne();let r=ft(e,s);try{if(!N.existsSync(r))return;let i=JSON.parse(N.readFileSync(r,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let c=o.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:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),N.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function ht(e){let t=dt(e),o=t.filter(r=>r.processed),s=t.filter(r=>!r.processed);return{total:t.length,processed:o.length,unprocessed:s.length,statuses:o.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function gt(){Ne();try{return N.readdirSync(me).filter(t=>t.endsWith(".json")).map(t=>{let[o,s]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(N.readFileSync(G.join(me,t),"utf-8"));return{file:t,source:o,date:s,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:s,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as m from"fs";import*as qe from"os";import*as I from"path";import{fileURLToPath as Eo}from"url";var Me={};Je(Me,{NAME:()=>uo,VERSION:()=>co,up:()=>mo});import*as B from"fs";import*as ke from"path";var co=1,uo="normalize-jobs-and-questions",fo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],po=50;function Fe(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function Pe(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{B.writeFileSync(s,o)}catch(r){try{B.unlinkSync(s)}catch{}throw r}try{B.renameSync(s,e)}catch(r){try{B.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function mo(e,t){let o=ke.join(e,"jobs.json"),s=ke.join(t,"scouted-jobs.json"),r=ke.join(e,"application-questions.json"),i=Fe(o)||{},l=Fe(s)||{},c=0,n=[];for(let u of Object.keys(i)){if(!l[u])continue;let f=l[u],h=i[u];for(let p of fo)f[p]!=null&&h[p]==null&&(h[p]=f[p]);n.push(u),c++}c>0?(Pe(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Fe(r);if(a&&Array.isArray(a.applications)){let u={},f=0;for(let h of a.applications){let p=h.jobId||"unknown";u[p]||(u[p]={applications:[]});let g=(h.questions||[]).map(d=>{let b={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=po?b.options=d.options:(b.optionsOmitted=!0,f++)),d.page&&(b.page=d.page),d.wasPreFilled&&(b.wasPreFilled=!0),d.wasRetry&&(b.wasRetry=!0),b});u[p].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||g.length,questions:g})}Pe(r,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(n.length>0){for(let u of n)delete l[u];Pe(s,l),console.log(` Phase 3: Removed ${n.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 Le={};Je(Le,{NAME:()=>go,VERSION:()=>ho,up:()=>So});import*as J from"fs";import*as yt from"path";var ho=2,go="reset-unread-flags";function yo(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function wo(e,t){let o=JSON.stringify(t,null,2),s=e+".tmp";try{J.writeFileSync(s,o)}catch(r){try{J.unlinkSync(s)}catch{}throw r}try{J.renameSync(s,e)}catch(r){try{J.unlinkSync(s)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function So(e){let t=yt.join(e,"conversations.json"),o=yo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let s=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,s++);if(s===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}wo(t,o),console.log(` Reset unread=false on ${s} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}import"dotenv/config";import*as L from"path";import{fileURLToPath as bo}from"url";var ko=bo(import.meta.url),vo=L.dirname(L.dirname(ko)),he=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(vo,"market-research"),An=L.join(he,"scouted-jobs.json"),In=L.join(he,"discovered-people.json"),xn=L.join(he,"visit-log.json"),En=L.join(he,"companies.json"),Dn=L.join(he,"job-decisions.json");function wt(){$o=null,Co=null,Ao=null,Io=null,xo=null}var $o=null;var Co=null;var Ao=null;var Io=null;var xo=null;var Do=Eo(import.meta.url),Oo=I.dirname(Do),jo=I.dirname(I.dirname(Oo));function To(e){return e&&(e==="~"?qe.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(qe.homedir(),e.slice(2)):e)}var H=process.env.DATA_DIR?I.resolve(To(process.env.DATA_DIR)):jo,ne=I.join(H,"collected-profiles"),se=I.join(H,"market-research"),P=I.join(H,".schema-version"),St=[I.join(ne,".schema-version"),I.join(se,".schema-version")],X=2,Y=[{version:1,module:Me},{version:2,module:Le}];(function(){Y.sort((s,r)=>s.version-r.version);let t=new Set;for(let s of Y){if(!Number.isInteger(s.version)||s.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(s.version)} (must be positive integer)`);if(t.has(s.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${s.version}`);t.add(s.version);let r=s.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${s.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==s.version)throw new Error(`MIGRATION_REGISTRY: v${s.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=Y.length?Y[Y.length-1].version:0;if(o!==X)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${X}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let s=0;s<Y.length;s++){let r=s+1;if(Y[s].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${s} but found v${Y[s].version}`)}})();function $t(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
16
16
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
17
|
-
`),process.exit(1));try{
|
|
18
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
19
|
-
`),process.exit(1))}let e;try{e=
|
|
20
|
-
[FATAL] DATA_DIR (${
|
|
17
|
+
`),process.exit(1));try{m.mkdirSync(H,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
18
|
+
[FATAL] Cannot create DATA_DIR (${H}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
19
|
+
`),process.exit(1))}let e;try{e=m.statSync(H)}catch(t){console.error(`
|
|
20
|
+
[FATAL] DATA_DIR (${H}) is not accessible: ${t.message}
|
|
21
21
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
22
|
-
[FATAL] DATA_DIR (${
|
|
23
|
-
`),process.exit(1));for(let
|
|
24
|
-
[FATAL] Data subdirectory is a symbolic link: ${
|
|
25
|
-
`),process.exit(1))}}var
|
|
26
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${
|
|
22
|
+
[FATAL] DATA_DIR (${H}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
23
|
+
`),process.exit(1));for(let t of[ne,se]){let o;try{o=m.lstatSync(t)}catch(s){if(s.code==="ENOENT")continue;throw s}o.isSymbolicLink()&&(console.error(`
|
|
24
|
+
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
25
|
+
`),process.exit(1))}}var oe=I.join(H,".migration-lock");function _o(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return m.writeFileSync(oe,e,{flag:"wx"}),!0}catch(s){if(s.code!=="EEXIST")throw s}let t;try{t=JSON.parse(m.readFileSync(oe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let s=!1;try{process.kill(t.pid,0),s=!0}catch(l){l.code==="EPERM"&&(s=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}s&&i<r&&(console.error(`
|
|
26
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${oe}
|
|
27
27
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
28
|
-
`),process.exit(1)),s&&i>=r&&console.log(` Lock holder PID ${
|
|
29
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of
|
|
28
|
+
`),process.exit(1)),s&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=oe+".tmp";try{return m.writeFileSync(o,e),m.renameSync(o,oe),!0}catch(s){try{m.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${s.message}`)}}function Be(){try{if(JSON.parse(m.readFileSync(oe,"utf-8")).pid!==process.pid)return;m.unlinkSync(oe)}catch{}}var bt=!1;function Ro(){if(bt)return;bt=!0;let e=()=>{try{Be()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function No(){if(m.existsSync(P))return;let e=[],t=[];for(let i of St)if(m.existsSync(i))try{e.push({file:i,schema:ve(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
|
|
29
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
30
30
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
31
|
-
`),process.exit(1)}if(e.length===0)return;let
|
|
31
|
+
`),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
|
|
32
32
|
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
33
|
-
`),process.exit(1)}let s=e[0].schema,r=
|
|
34
|
-
[FATAL] ${
|
|
35
|
-
`),process.exit(1)}let
|
|
36
|
-
[FATAL] ${
|
|
37
|
-
`),process.exit(1)),
|
|
38
|
-
[FATAL] Your data schema is at v${
|
|
39
|
-
`),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${
|
|
33
|
+
`),process.exit(1)}let s=e[0].schema,r=P+".tmp";try{m.writeFileSync(r,JSON.stringify(s,null,2)),m.renameSync(r,P)}catch(i){try{m.unlinkSync(r)}catch{}throw i}for(let i of St)if(m.existsSync(i))try{m.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${P}`)}function Fo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function ve(e){let t=m.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function kt(){if(No(),!m.existsSync(P))return{version:0,migrations:[]};let e;try{e=ve(P)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
34
|
+
[FATAL] ${P} is not valid JSON: ${o.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.
|
|
35
|
+
`),process.exit(1)}let t=Fo(e);return t===null&&(console.error(`
|
|
36
|
+
[FATAL] ${P} 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.
|
|
37
|
+
`),process.exit(1)),t}function Ct(e){try{m.chmodSync(e,384)}catch{}}function Po(e){if($t(),m.existsSync(P))try{if(m.lstatSync(P).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${P}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=P+".tmp";try{m.writeFileSync(t,JSON.stringify(e,null,2)),Ct(t),m.renameSync(t,P)}catch(o){try{m.unlinkSync(t)}catch{}throw o}}function vt(e,t){if(!m.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,s=m.readdirSync(e).filter(c=>{let n=c.toLowerCase();if(n.includes(".backup")||n===".schema-version"||n.endsWith(".tmp"))return!1;try{return m.statSync(I.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let c of s){let n=I.join(e,c),a=I.join(e,c+o);if(m.existsSync(a)){i++;continue}try{It(n,a),r++}catch(u){l.push({file:c,err:u.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${I.basename(e)}/: `+l.map(n=>`${n.file} (${n.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${I.basename(e)}/ (${o})${c}`)}}var Ue=!1;async function At(){if(Ue)return;$t(),Bo();let t=kt().version;if(t===X){Ue=!0;return}Ro(),_o(),process.on("exit",Be),t>X&&(console.error(`
|
|
38
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${X}.`),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.
|
|
39
|
+
`),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${X}.
|
|
40
40
|
`),process.exit(1)),console.log(`
|
|
41
|
-
\u{1F4E6} Schema migration: v${
|
|
42
|
-
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of
|
|
41
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${X}`);let o=Jo();if(!o.ok){console.error(`
|
|
42
|
+
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of o.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
43
43
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
44
|
-
`),process.exit(1)}let s=
|
|
45
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{
|
|
44
|
+
`),process.exit(1)}let s=Y.filter(r=>r.version>t);for(let r of s){console.log(`
|
|
45
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{vt(ne,r.version),vt(se,r.version)}catch(n){console.error(`
|
|
46
46
|
[FATAL] Pre-migration backup failed for ${i}: ${n.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
47
|
-
`),process.exit(1)}let c=r.module;try{await c.up(
|
|
48
|
-
[FATAL] Migration ${i} failed: ${n.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=
|
|
47
|
+
`),process.exit(1)}let c=r.module;try{await c.up(ne,se)}catch(n){console.error(`
|
|
48
|
+
[FATAL] Migration ${i} failed: ${n.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=Ho(l);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
49
49
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
50
50
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
51
|
-
`)}process.exit(1)}try{let n=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:n},u=
|
|
52
|
-
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${n.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${
|
|
53
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
54
|
-
\u2713 Schema is now at v${
|
|
55
|
-
`)}var
|
|
51
|
+
`)}process.exit(1)}try{let n=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:n},u=kt();u.version=r.version,u.migratedAt=n,u.migrations=u.migrations||[],u.migrations.push(a),Po(u)}catch(n){console.error(`
|
|
52
|
+
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${n.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
53
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Xe()}catch{}try{wt()}catch{}Ue=!0,Be(),console.log(`
|
|
54
|
+
\u2713 Schema is now at v${X}
|
|
55
|
+
`)}var Mo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Lo(e){let t=e.toLowerCase();return Mo.some(o=>o.test(t))}var Uo=6e4;function qo(){let e=Date.now(),t=[];for(let o of[H,ne,se]){if(!m.existsSync(o))continue;let s;try{s=m.readdirSync(o)}catch{continue}for(let r of s){if(!Lo(r))continue;let i=I.join(o,r);try{let l=m.statSync(i);if(!l.isFile()||e-l.mtimeMs<Uo)continue;t.push({dir:o,file:r,fullPath:i})}catch{}}}return t}function Bo({verbose:e=!1}={}){let t=qo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let s of t)try{m.unlinkSync(s.fullPath),o++,e&&console.log(` Removed orphan: ${I.basename(s.dir)}/${s.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${s.fullPath}: ${r.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Jo(){let e=[];for(let t of[ne,se]){if(!m.existsSync(t))continue;let o=m.readdirSync(t).filter(s=>{let r=s.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let s of o){let r=I.join(t,s);try{ve(r)}catch(i){e.push({dir:I.basename(t),file:s,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ho(e){let t=[],o=[];for(let i of[ne,se]){if(!m.existsSync(i))continue;let l=m.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let n=I.join(i,c),a=c.slice(0,-e.length),u=I.join(i,a);try{a.toLowerCase().endsWith(".json")?ve(n):m.accessSync(n,m.constants.R_OK),t.push({backupPath:n,originalPath:u,fileName:c,dir:i})}catch(f){o.push(`${I.basename(i)}/${c}: ${f.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let s=0,r=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:n}of t)try{It(i,l),s++}catch(a){r.push(`${I.basename(n)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:s}:{ok:!0,restored:s}}function It(e,t){let o=t+".tmp";try{m.copyFileSync(e,o),Ct(o)}catch(s){try{m.unlinkSync(o)}catch{}throw s}try{m.renameSync(o,t)}catch(s){try{m.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${t} (${s.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=s.code,r}throw s}}import xt from"fs";import Vo from"path";var Wo="cookies.json";function Go(){let e=process.env.ILML_SCOPE_DIR;return e?Vo.join(e,"plugins-state","linkedin","cookies.json"):Wo}function Et(){let e=Go();if(!xt.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=xt.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read cookies at ${e}: ${s.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}await At();function zo(){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(o=>o.trim()).filter(Boolean));return e}async function Qo(){let e=zo();if(e.list){console.log(`
|
|
56
56
|
\u{1F4C2} Available profile files:
|
|
57
|
-
`);let n=
|
|
57
|
+
`);let n=gt();if(n.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let a of n)console.log(` ${a.file}`),console.log(` Total: ${a.count}, Unprocessed: ${a.unprocessed}`);console.log(""),process.exit(0)}console.log(`
|
|
58
58
|
========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
|
|
59
|
-
`),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
|
|
60
|
-
Profiles to process: ${
|
|
59
|
+
`),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=pt(e.source,e.date);console.log(`
|
|
60
|
+
Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
61
61
|
\u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
|
|
62
|
-
Profiles:`),
|
|
62
|
+
Profiles:`),t.slice(0,10).forEach((n,a)=>{console.log(` ${a+1}. ${n.name||"Unknown"} - ${n.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
|
|
63
63
|
Press Enter to start, or Ctrl+C to cancel...`),await new Promise(n=>{process.stdin.once("data",()=>n())}),console.log(`
|
|
64
64
|
\u{1F680} Starting browser...
|
|
65
|
-
`);let
|
|
65
|
+
`);let o=await Yo.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),s=await o.newPage();try{let n=Et();await s.setCookie(...n),console.log(`\u2713 Cookies loaded
|
|
66
66
|
`)}catch(n){console.error(`
|
|
67
67
|
[!] ${n.message}
|
|
68
|
-
`),await
|
|
68
|
+
`),await o.close(),process.exit(1)}let r=e.viewOnly?"view-only":"connect",i=ze("funnel",r),l=await ut(s,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(n,a,u)=>{mt(e.source,n.profileUrl,{status:u.reason,connectionSent:u.connectionSent,withCustomMessage:u.withCustomMessage,message:u.messageSent,method:u.method,reason:u.reason,error:u.error,profileInfo:u.profileInfo})}});console.log(`
|
|
69
69
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
70
|
-
`);let c=
|
|
71
|
-
Status breakdown:`);for(let[n,a]of Object.entries(c.statuses))console.log(` ${n}: ${a}`)}
|
|
70
|
+
`);let c=ht(e.source);if(console.log(`Processed: ${c.processed}/${c.total}`),console.log(`Remaining: ${c.unprocessed}`),Object.keys(c.statuses).length>0){console.log(`
|
|
71
|
+
Status breakdown:`);for(let[n,a]of Object.entries(c.statuses))console.log(` ${n}: ${a}`)}Ie(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await o.close(),process.exit(0)}Qo().catch(e=>{console.error("Funnel failed:",e);try{Ie(null,"error",null,e.message)}catch{}process.exit(1)});
|