ilml-plugin-linkedin 1.11.2 → 1.11.4
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 +7 -0
- package/dist/applyQueue.mjs +28 -28
- package/dist/daily.mjs +24 -24
- package/dist/enrichProfiles.mjs +1 -1
- package/dist/funnelRunner.mjs +28 -28
- package/dist/messageBot.mjs +6 -6
- package/dist/migrationCli.mjs +19 -19
- package/dist/profileHistory.mjs +5 -5
- package/dist/run.mjs +40 -40
- package/dist/scout.mjs +1 -1
- package/dist/syncAll.mjs +8 -8
- package/dist/verifyAbout.mjs +1 -1
- package/dist/viewers.mjs +1 -1
- package/dist/visit.mjs +1 -1
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Tt=Object.defineProperty;var He=(e,t)=>{for(var o in t)Tt(e,o,{get:t[o],enumerable:!0})};import Ko from"puppeteer";import"dotenv/config";import*as q from"fs";import*as K from"path";import{fileURLToPath as Pt}from"url";import"dotenv/config";import{createGraphClient as jt,resolveToken as _t}from"@ilivemylife/graph-sdk";import{config as Rt}from"dotenv";Rt();var Ve=_t()||process.env.TOKEN;Ve||(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 We=jt({token:Ve});function Nt(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 Ft({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?` ${Nt(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 Ge({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=`**${Ft({scriptName:e,mode:t,status:o,error:r,duration:i})}**
|
|
6
6
|
|
|
7
7
|
${s.join(`
|
|
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=
|
|
8
|
+
`)}`;try{await We.addMessage(l,n)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Mt=Pt(import.meta.url),Lt=K.dirname(K.dirname(Mt)),Ae=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"collected-profiles"):K.join(Lt,"collected-profiles"),Ee=K.join(Ae,"run-log.json");function Ut(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 Ye(){try{if(!q.existsSync(Ee))return{runs:[]};let e=JSON.parse(q.readFileSync(Ee,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ze(e){q.existsSync(Ae)||q.mkdirSync(Ae,{recursive:!0});try{Ut(Ee,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Qe(e,t="default"){let o=Ye();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),ze(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=Ye(),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)}ze(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";Ge({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{getPluginConfig as qt}from"@ilivemylife/graph-sdk";var Bt=await qt();for(let[e,t]of Object.entries(Bt))process.env[e]===void 0&&(process.env[e]=t);var mn=process.env.LINKEDIN_NAME,oe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),hn=Object.freeze(new Set([oe.DRAFT,oe.CONFIRMED,oe.NEEDS_REVIEW])),gn=Object.freeze(new Set([oe.DRAFT,oe.CONFIRMED,oe.REJECTED,oe.NEEDS_REVIEW]));import"dotenv/config";import*as D from"fs";import*as j from"path";import{fileURLToPath as Jt}from"url";var Ht=Jt(import.meta.url),Vt=j.dirname(j.dirname(Ht)),W=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(Vt,"collected-profiles"),xe=j.join(W,"people.json"),kn=j.join(W,"jobs.json"),Xe=j.join(W,"quota.json"),vn=j.join(W,"conversations.json"),$n=j.join(W,"sync-state.json"),Cn=j.join(W,"application-questions.json"),De=j.join(W,"profile-history"),fe=20,de=100,le=null,Wt=null,V=null,Gt=null,Yt=null,zt=null;function et(){le=null,Wt=null,V=null,Gt=null,Yt=null,zt=null}function ke(){D.existsSync(W)||D.mkdirSync(W,{recursive:!0})}function Oe(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 Te(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: ${j.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 pe(){return new Date().toISOString().split("T")[0]}var Qt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],Kt=["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(De)||D.mkdirSync(De,{recursive:!0})}function tt(e){let t=je(e);return t?j.join(De,`${t}.json`):null}function Xt(e){let t=tt(e);return t?Te(t,`profile-history/${je(e)}.json`)||[]:[]}function eo(e,t){let o=tt(e);if(!o)return;Zt();let s=Xt(e);s.unshift(t);try{Oe(o,s)}catch(r){console.error(`[!] Failed to append profile-history for ${je(e)}: ${r.message}`)}}function Ke(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ze(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function to(e,t){if(!e)return[];let o=[];for(let s of Kt){let r=e[s],i=t[s];Ke(r)||Ke(i)||Ze(r)!==Ze(i)&&o.push(s)}return o}function oo(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 le||(ke(),le=Te(xe,"people.json")||{},le)}function _e(e){ke(),le=e;try{Oe(xe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${j.resolve(xe)}`)}}function be(e,t={}){if(!e)return null;let o=Z(),s=pe(),r=new Date().toISOString(),i=o[e];if(i){let l=to(i,t);l.length>0&&(eo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:oo(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 Qt)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 _e(o),o[e]}function ot(e,t){if(!e||!t)return;let o=Z(),s=o[e];if(!s)return;s.encounters||(s.encounters=[]);let i={date:pe(),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(),_e(o))}function nt(e){return e&&Z()[e]?.connectionStatus||null}function st(e,t,o={}){if(!e)return;o.profileInfo?be(e,o.profileInfo):Z()[e]||be(e,{});let s=Z(),r=s[e];r&&(r.connectionStatus=t,r.connectionDate=pe(),r.connectionMethod=o.method||r.connectionMethod,r.messageSent=o.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),_e(s))}function rt(){return V||(ke(),V=Te(Xe,"quota.json"),(!V||!V.connections)&&(V={connections:[]}),V)}function no(e){ke(),V=e;try{Oe(Xe,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function it(e,t="unknown"){let o=rt(),s=new Date;o.connections.push({date:s.toISOString().split("T")[0],time:s.toTimeString().split(" ")[0],profileUrl:e,source:t}),no(o)}function lt(){let e=rt(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(s=>s.date>=o)}function at(){let e=lt(),t=pe(),o=e.filter(n=>n.date===t).length,s=e.length,r=o>=fe,i=s>=de,l=!r&&!i,c={allowed:l,daily:{sent:o,max:fe},weekly:{sent:s,max:de}};return l||(c.reason=r?`Daily limit reached (${o}/${fe})`:`Weekly limit reached (${s}/${de})`),c}function Re(){let e=lt(),t=pe(),o=e.filter(r=>r.date===t).length,s=e.length;return{daily:{sent:o,max:fe,remaining:fe-o},weekly:{sent:s,max:de,remaining:de-s}}}async function ut(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 ct(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(s=>o.includes(s.toLowerCase()))}async function so(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 ut(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,ae=_.match(/(\d+)\s+mutual connection/i),ie=_.match(/and\s+(\d+)\s+other mutual/i),ye=_.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ae?ee=parseInt(ae[1],10):ie?ee=2+parseInt(ie[1],10):ye&&(ee=2);let z=null,ce=null,ue=f.find(y=>y.textContent&&y.textContent.trim()==="About");if(ue){let y=ue.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 Ce=C[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ot=>Ot.trim()).filter(Boolean);Ce.length>0&&Ce.length<10&&(ce=Ce)}$=$.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 we=null,Se=f.find(y=>y.textContent&&y.textContent.trim()==="Activity");if(Se){let y=Se.parentElement;for(;y&&y.tagName!=="SECTION";)y=y.parentElement;if(y){let $=(y.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(we=parseInt($[1].replace(/,/g,""),10))}}let I=[...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)))],x=document.body.textContent||"",R=/#OpenToWork\b/i.test(x)||/\bOpen to work\b/.test(x),T=/#Hiring\b/i.test(x)||/\bI'?m hiring\b/i.test(x)||/\bWe are hiring\b/i.test(x);return{name:p,title:d,location:k,currentCompany:b,currentSchool:w,connectionDegree:A,hasVerifiedBadge:v,photoUrl:M,connectionsLevel:U,mutualConnectionsCount:ee,followers:we,openToWork:R,hiring:T,about:z,topSkills:ce,availableSections:I}});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 me(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 Ne(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 ro(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 io(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 Ne(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 lo(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(ct(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 ut(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=I=>{let x=(I||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},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(I=>{let x=I.textContent&&I.textContent.trim();return x&&x.length>1&&x.length<100&&!w.has(x)&&x!=="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 T=R.textContent&&R.textContent.trim();return T&&T.length>5&&!k(T)});)F=F.parentElement;let ee=null,ae=null,ie=null;if(F&&F!==v){let I=Array.from(F.children),x=I.filter(T=>T.tagName==="P").filter(T=>{let y=T.textContent&&T.textContent.trim();return y&&y.length>5&&!k(y)});x[0]&&(ee=x[0].textContent.trim()),x[1]&&(ae=x[1].textContent.trim());let R=I.filter(T=>T.tagName==="DIV");for(let T=R.length-1;T>=0;T--){let y=R[T].textContent&&R[T].textContent.trim();if(y&&!(U&&y.startsWith(U))&&(ie=y.split(/[·•]/)[0].trim(),ie))break}}let ye=null;if(F){let I=F.querySelectorAll("p, span, div");for(let x of I){let R=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(R==="1st"||R==="2nd"||R==="3rd"){ye=R;break}}}let z=null,ce=M.find(I=>I.textContent&&I.textContent.trim()==="About");if(ce){let I=ce.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;I&&(z=(I.textContent||"").trim().replace(/^About\s*/,"").trim()||null,z&&(z=z.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let ue=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),we=ue&&ue.src||null,Se=!!v.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:U,title:ee,location:ie,about:z,company:ae,connectionDegree:ye,connectionsCount:null,mutualConnections:null,photoUrl:we,hasVerifiedBadge:Se}}),c.length>0){let w=n.profileInfo?.location,k=Z()[t]?.location,A=w||k;if(ct(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 me(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 Ne(e);if(!h&&(await te(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),h=await Ne(e)),!h))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=h.method,await ro(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 me(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 me(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 io(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 me(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 me(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 ft(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=Re();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(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let d=
|
|
12
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let d=nt(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 so(e,g.profileUrl);w?(be(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=at();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await lo(e,g.profileUrl,{message:s,useCustomMessage:r,excludeLocations:a}),b.success)f.connectionsSent++,b.connectionSent&&it(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
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&&(
|
|
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=
|
|
14
|
+
\u26A0 ${h} consecutive errors \u2014 aborting funnel`);break}}else h=0;if(b&&b.reason&&(st(g.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),ot(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=Re();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 ao}from"url";var co=ao(import.meta.url),uo=G.dirname(G.dirname(co)),he=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"collected-profiles"):G.join(uo,"collected-profiles");function Fe(){N.existsSync(he)||N.mkdirSync(he,{recursive:!0})}function fo(){return new Date().toISOString().split("T")[0]}function dt(e,t=null){let o=t||fo();return G.join(he,`${e}-${o}.json`)}function pt(e,t=null){Fe();let o=dt(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 mt(e,t=null){return pt(e,t).filter(s=>!s.processed)}function ht(e,t,o,s=null){Fe();let r=dt(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 gt(e){let t=pt(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 yt(){Fe();try{return N.readdirSync(he).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(he,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 Be from"os";import*as E from"path";import{fileURLToPath as To}from"url";var Le={};He(Le,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as B from"fs";import*as ve from"path";var po=1,mo="normalize-jobs-and-questions",ho=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],go=50;function Pe(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function Me(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 yo(e,t){let o=ve.join(e,"jobs.json"),s=ve.join(t,"scouted-jobs.json"),r=ve.join(e,"application-questions.json"),i=Pe(o)||{},l=Pe(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 ho)f[p]!=null&&h[p]==null&&(h[p]=f[p]);n.push(u),c++}c>0?(Me(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Pe(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<=go?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})}Me(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];Me(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 Ue={};He(Ue,{NAME:()=>So,VERSION:()=>wo,up:()=>vo});import*as J from"fs";import*as wt from"path";var wo=2,So="reset-unread-flags";function bo(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function ko(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 vo(e){let t=wt.join(e,"conversations.json"),o=bo(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}ko(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 $o}from"url";var Co=$o(import.meta.url),Ao=L.dirname(L.dirname(Co)),ge=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(Ao,"market-research"),Rn=L.join(ge,"scouted-jobs.json"),Nn=L.join(ge,"discovered-people.json"),Fn=L.join(ge,"visit-log.json"),Pn=L.join(ge,"companies.json"),Mn=L.join(ge,"job-decisions.json");function St(){Eo=null,Io=null,xo=null,Do=null,Oo=null}var Eo=null;var Io=null;var xo=null;var Do=null;var Oo=null;var jo=To(import.meta.url),_o=E.dirname(jo),Ro=E.dirname(E.dirname(_o));function No(e){return e&&(e==="~"?Be.homedir():e.startsWith("~/")||e.startsWith("~\\")?E.join(Be.homedir(),e.slice(2)):e)}var H=process.env.DATA_DIR?E.resolve(No(process.env.DATA_DIR)):Ro,se=E.join(H,"collected-profiles"),re=E.join(H,"market-research"),P=E.join(H,".schema-version"),bt=[E.join(se,".schema-version"),E.join(re,".schema-version")],X=2,Y=[{version:1,module:Le},{version:2,module:Ue}];(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 Ct(){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
17
|
`),process.exit(1));try{m.mkdirSync(H,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
18
18
|
[FATAL] Cannot create DATA_DIR (${H}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -20,52 +20,52 @@ ${s.join(`
|
|
|
20
20
|
[FATAL] DATA_DIR (${H}) is not accessible: ${t.message}
|
|
21
21
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
22
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[
|
|
23
|
+
`),process.exit(1));for(let t of[se,re]){let o;try{o=m.lstatSync(t)}catch(s){if(s.code==="ENOENT")continue;throw s}o.isSymbolicLink()&&(console.error(`
|
|
24
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
|
|
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: ${
|
|
25
|
+
`),process.exit(1))}}var ne=E.join(H,".migration-lock");function Fo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return m.writeFileSync(ne,e,{flag:"wx"}),!0}catch(s){if(s.code!=="EEXIST")throw s}let t;try{t=JSON.parse(m.readFileSync(ne,"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: ${ne}
|
|
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 ${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=
|
|
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=ne+".tmp";try{return m.writeFileSync(o,e),m.renameSync(o,ne),!0}catch(s){try{m.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${s.message}`)}}function Je(){try{if(JSON.parse(m.readFileSync(ne,"utf-8")).pid!==process.pid)return;m.unlinkSync(ne)}catch{}}var kt=!1;function Po(){if(kt)return;kt=!0;let e=()=>{try{Je()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Mo(){if(m.existsSync(P))return;let e=[],t=[];for(let i of bt)if(m.existsSync(i))try{e.push({file:i,schema:$e(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
|
|
29
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
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=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
|
|
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 bt)if(m.existsSync(i))try{m.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${P}`)}function Lo(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 $e(e){let t=m.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function vt(){if(Mo(),!m.existsSync(P))return{version:0,migrations:[]};let e;try{e=$e(P)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
34
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=
|
|
35
|
+
`),process.exit(1)}let t=Lo(e);return t===null&&(console.error(`
|
|
36
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
|
|
37
|
+
`),process.exit(1)),t}function At(e){try{m.chmodSync(e,384)}catch{}}function Uo(e){if(Ct(),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)),At(t),m.renameSync(t,P)}catch(o){try{m.unlinkSync(t)}catch{}throw o}}function $t(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(E.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let c of s){let n=E.join(e,c),a=E.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 ${E.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 ${E.basename(e)}/ (${o})${c}`)}}var qe=!1;async function Et(){if(qe)return;Ct(),Vo();let t=vt().version;if(t===X){qe=!0;return}Po(),Fo(),process.on("exit",Je),t>X&&(console.error(`
|
|
38
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
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${t} \u2192 v${X}`);let o=
|
|
41
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${X}`);let o=Wo();if(!o.ok){console.error(`
|
|
42
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
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{
|
|
45
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{$t(se,r.version),$t(re,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(se,re)}catch(n){console.error(`
|
|
48
|
+
[FATAL] Migration ${i} failed: ${n.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=Go(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=
|
|
51
|
+
`)}process.exit(1)}try{let n=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:n},u=vt();u.version=r.version,u.migratedAt=n,u.migrations=u.migrations||[],u.migrations.push(a),Uo(u)}catch(n){console.error(`
|
|
52
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{
|
|
53
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{et()}catch{}try{St()}catch{}qe=!0,Je(),console.log(`
|
|
54
54
|
\u2713 Schema is now at v${X}
|
|
55
|
-
`)}var
|
|
55
|
+
`)}var qo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Bo(e){let t=e.toLowerCase();return qo.some(o=>o.test(t))}var Jo=6e4;function Ho(){let e=Date.now(),t=[];for(let o of[H,se,re]){if(!m.existsSync(o))continue;let s;try{s=m.readdirSync(o)}catch{continue}for(let r of s){if(!Bo(r))continue;let i=E.join(o,r);try{let l=m.statSync(i);if(!l.isFile()||e-l.mtimeMs<Jo)continue;t.push({dir:o,file:r,fullPath:i})}catch{}}}return t}function Vo({verbose:e=!1}={}){let t=Ho();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: ${E.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 Wo(){let e=[];for(let t of[se,re]){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=E.join(t,s);try{$e(r)}catch(i){e.push({dir:E.basename(t),file:s,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Go(e){let t=[],o=[];for(let i of[se,re]){if(!m.existsSync(i))continue;let l=m.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let n=E.join(i,c),a=c.slice(0,-e.length),u=E.join(i,a);try{a.toLowerCase().endsWith(".json")?$e(n):m.accessSync(n,m.constants.R_OK),t.push({backupPath:n,originalPath:u,fileName:c,dir:i})}catch(f){o.push(`${E.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(`${E.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),At(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 Yo from"path";var zo="cookies.json";function Qo(){let e=process.env.ILML_SCOPE_DIR;return e?Yo.join(e,"plugins-state","linkedin","cookies.json"):zo}function Dt(){let e=Qo();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 Et();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 Xo(){let e=Zo();if(e.list){console.log(`
|
|
56
56
|
\u{1F4C2} Available profile files:
|
|
57
|
-
`);let n=
|
|
57
|
+
`);let n=yt();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 t=
|
|
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=mt(e.source,e.date);console.log(`
|
|
60
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
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 o=await
|
|
65
|
+
`);let o=await Ko.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),s=await o.newPage();try{let n=Dt();await s.setCookie(...n),console.log(`\u2713 Cookies loaded
|
|
66
66
|
`)}catch(n){console.error(`
|
|
67
67
|
[!] ${n.message}
|
|
68
|
-
`),await o.close(),process.exit(1)}let r=e.viewOnly?"view-only":"connect",i=
|
|
68
|
+
`),await o.close(),process.exit(1)}let r=e.viewOnly?"view-only":"connect",i=Qe("funnel",r),l=await ft(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)=>{ht(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}`)}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)}
|
|
70
|
+
`);let c=gt(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)}Xo().catch(e=>{console.error("Funnel failed:",e);try{Ie(null,"error",null,e.message)}catch{}process.exit(1)});
|