ilml-plugin-linkedin 1.14.3 → 1.14.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 +3 -0
- package/dist/connect.mjs +19 -19
- package/dist/enrichProfile.mjs +3 -3
- package/dist/enrichProfiles.mjs +30 -30
- package/dist/funnelRunner.mjs +10 -10
- package/dist/run.mjs +18 -18
- package/dist/syncAll.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.14.4
|
|
4
|
+
- **`connect run` now recognises people you're already connected to (or already have a pending request with) and skips them cleanly — instead of logging a false failure.** When a queued person is already a 1st-degree connection, their profile shows "Message" and no "Connect" — but the "More profiles for you" sidebar has its own Connect controls, which made connect think a Connect button was still present, miss that you're already connected, and record a `button_not_found` "failure". The already-connected / already-pending check now ignores that sidebar and reads only the open profile, so such entries are marked **skipped (already connected)** instead of failed: they don't count toward the "3 failures in a row" safety stop and don't burn quota. It stays conservative about writing anything back to your contacts — a real send is recorded, but a merely-inferred "already connected" only refreshes a person you already have, it won't invent a connection for an unknown profile (the source of truth for who you're connected to remains `sync`). Net effect — the failure list holds only real problems. Same root cause as 1.14.3 (recommendation-sidebar bleed), applied to status detection. No schema change.
|
|
5
|
+
|
|
3
6
|
## 1.14.3
|
|
4
7
|
- **`connect run` no longer sends the request to the wrong person.** On some profiles — typically well-known people you're not connected to, whose own "Connect" is tucked under the "More" menu — LinkedIn shows a "More profiles for you" sidebar where each suggested person has their own Connect control. Connect could grab the first of those sidebar controls and send the request to that person instead of the profile you queued, while the log still reported your intended target as sent (and your quota was spent on it). Connect now acts only on the Connect control that belongs to the open profile: it ignores the recommendation sidebar, and as a final check refuses to click any "Invite X to connect" control whose name doesn't match the profile it's on — a mismatch is skipped (and your quota left intact) rather than sent to the wrong person. This was a long-standing latent issue that only surfaced on profiles without their own inline Connect button. No schema change.
|
|
5
8
|
|
package/dist/connect.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Hn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var n in t)Hn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Wn}from"@ilivemylife/graph-sdk";var Gn,Yn,pe,Kn,Qn,Qe=re(async()=>{Gn=await Wn();for(let[e,t]of Object.entries(Gn))process.env[e]===void 0&&(process.env[e]=t);Yn=process.env.LINKEDIN_NAME,pe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Kn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.NEEDS_REVIEW])),Qn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.REJECTED,pe.NEEDS_REVIEW]))});import"dotenv/config";import*as M from"fs";import*as B from"path";import{fileURLToPath as zn}from"url";function Vt(){Ee=null,eo=null,se=null,to=null,no=null,oo=null}function Xe(){M.existsSync(ie)||M.mkdirSync(ie,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";M.writeFileSync(o,n);for(let r=0;r<3;r++)try{M.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let c=Date.now();for(;Date.now()-c<200;);continue}throw i}}function Le(e,t){if(!M.existsSync(e))return null;try{let n=JSON.parse(M.readFileSync(e,"utf-8"));try{M.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(M.existsSync(o))try{let r=JSON.parse(M.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{M.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{M.copyFileSync(e,e+".corrupted")}catch{}return null}}function Pe(){return new Date().toISOString().split("T")[0]}function K(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function io(){M.existsSync(pt)||M.mkdirSync(pt,{recursive:!0})}function Ht(e){let t=K(e);return t?B.join(pt,`${t}.json`):null}function ao(e){let t=Ht(e);return t?Le(t,`profile-history/${K(e)}.json`)||[]:[]}function lo(e,t){let n=Ht(e);if(!n)return;io();let o=ao(e);o.unshift(t);try{Fe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${K(e)}: ${r.message}`)}}function qt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ut(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function co(e,t){if(!e)return[];let n=[];for(let o of so){let r=e[o],i=t[o];qt(r)||qt(i)||Ut(r)!==Ut(i)&&n.push(o)}return n}function uo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return Ee||(Xe(),Ee=Le(ft,"people.json")||{},Ee)}function mt(e){Xe(),Ee=e;try{Fe(ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(ft)}`)}}function ze(e,t={}){if(!e)return null;let n=Y(),o=Pe(),r=new Date().toISOString(),i=n[e];if(i){let c=co(i,t);c.length>0&&(lo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:uo(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of ro)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return mt(n),n[e]}function Wt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.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),!o.encounters.some(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),mt(n))}function Gt(e){return e&&Y()[e]?.connectionStatus||null}function Ze(e,t,n={}){if(!e)return;n.profileInfo?ze(e,n.profileInfo):Y()[e]||ze(e,{});let o=Y(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=Pe(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),mt(o))}function Yt(){return se||(Xe(),se=Le(Bt,"quota.json"),(!se||!se.connections)&&(se={connections:[]}),se)}function fo(e){Xe(),se=e;try{Fe(Bt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Kt(e,t="unknown"){let n=Yt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),fo(n)}function Qt(){let e=Yt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function qe(){let e=Qt(),t=Pe(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Oe,i=o>=Me,c=!r&&!i,u={allowed:c,daily:{sent:n,max:Oe},weekly:{sent:o,max:Me}};return c||(u.reason=r?`Daily limit reached (${n}/${Oe})`:`Weekly limit reached (${o}/${Me})`),u}function Se(){let e=Qt(),t=Pe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Oe,remaining:Oe-n},weekly:{sent:o,max:Me,remaining:Me-o}}}var Xn,Zn,ie,ft,as,Bt,ls,cs,us,pt,Jt,Oe,Me,Ee,eo,se,to,no,oo,ro,so,Ue=re(async()=>{await Qe();Xn=zn(import.meta.url),Zn=B.dirname(B.dirname(Xn)),ie=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Zn,"collected-profiles"),ft=B.join(ie,"people.json"),as=B.join(ie,"jobs.json"),Bt=B.join(ie,"quota.json"),ls=B.join(ie,"conversations.json"),cs=B.join(ie,"sync-state.json"),us=B.join(ie,"application-questions.json"),pt=B.join(ie,"profile-history"),Jt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Oe=Jt(process.env.CONNECT_MAX_DAILY,20),Me=Jt(process.env.CONNECT_MAX_WEEKLY,100),Ee=null,eo=null,se=null,to=null,no=null,oo=null;ro=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],so=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var mn={};fe(mn,{cookiesExist:()=>dr,getCookiesPath:()=>rt,loadCookies:()=>ur,saveCookies:()=>cr});import _e from"fs";import pn from"path";function rt(){let e=process.env.ILML_SCOPE_DIR;return e?pn.join(e,"plugins-state","linkedin","cookies.json"):ar}function lr(){let e=rt(),t=pn.dirname(e);return t&&t!=="."&&!_e.existsSync(t)&&_e.mkdirSync(t,{recursive:!0}),e}function cr(e){let t=lr();return _e.writeFileSync(t,JSON.stringify(e)),t}function ur(){let e=rt();if(!_e.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_e.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function dr(){return _e.existsSync(rt())}var ar,hn=re(()=>{ar="cookies.json"});var gn={};fe(gn,{cleanSearchName:()=>yr,delayed:()=>w,dismissPremiumOverlay:()=>we,ensureInboxPage:()=>hr,parseLinkedInTime:()=>mr,safeParseInt:()=>gr,stripDesignations:()=>wr,utilityFunction:()=>fr});function fr(){console.log("Utility function called...")}function Ve(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function mr(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let u=Ve(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=pr[o[1].toLowerCase()],s=Ve(o[2]||""),a=new Date(t),d=a.getDay()-u;return d<=0&&(d+=7),a.setDate(a.getDate()-d),s?a.setHours(s.hours,s.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=At[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),a=parseInt(r[3],10),l=Ve(r[4]||"");return new Date(a,u,s,l?.hours||0,l?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=At[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),a=Ve(i[3]||""),l=t.getFullYear(),d=new Date(l,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(l-1),d.toISOString()}let c=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(c){let u=At[c[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(c[2],10),a=Ve(c[3]||""),l=t.getFullYear(),d=new Date(l,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(l-1),d.toISOString()}return null}async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function hr(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function gr(e){return parseInt(e,10)||0}async function we(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),c=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||c||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let l of a){let d=l.innerText?.trim().toLowerCase()||"",f=l.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return l.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function yr(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function wr(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var At,pr,st=re(()=>{At={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},pr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var yn={};fe(yn,{extractCertificationsFromDetails:()=>$r,extractEducationFromDetails:()=>kr,extractExperienceFromDetails:()=>br,extractFeaturedFromDetails:()=>Sr,extractRecommendationsFromDetails:()=>Cr,extractSkillsFromDetails:()=>vr});async function br(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function c(l){let d=[];for(let f of l.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=c(i);if(!u)return[];let s=Array.from(u.children).filter(l=>l.tagName==="DIV").filter(l=>(l.textContent||"").trim().length>50);function a(l){let d=l[0]||null,f=null,p=null;if(l[1]){let x=l[1].split("\xB7").map(j=>j.trim());f=x[0]||null,x[1]&&(p=x[1])}let h=l.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),m=null,S=null;if(h>=0){let x=l[h].split("\xB7").map(j=>j.trim());m=x[0]||null,x[1]&&(S=x[1])}let y=null,k=-1;if(h>=0&&l[h+1]){let x=l[h+1],j=/^[>*\-•]|^>/.test(x),J=/https?:\/\//.test(x),R=/\d{4}/.test(x),O=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!j&&!J&&!R&&x.length<100&&O&&(y=x,k=h+1)}let v=null,C=-1,$=l[l.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){C=l.length-1;let x=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(v={listed:x[1].split(",").map(j=>j.trim()),additional:parseInt(x[2],10)})}let g=new Set([0,1,h,k,C].filter(x=>x>=0)),E=l.filter((x,j)=>!g.has(j)),L=E.length>0?E.join(`
|
|
1
|
+
var Hn=Object.defineProperty;var re=(e,t)=>()=>(e&&(t=e(e=0)),t);var de=(e,t)=>{for(var n in t)Hn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Wn}from"@ilivemylife/graph-sdk";var Gn,Yn,fe,Kn,Qn,Qe=re(async()=>{Gn=await Wn();for(let[e,t]of Object.entries(Gn))process.env[e]===void 0&&(process.env[e]=t);Yn=process.env.LINKEDIN_NAME,fe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Kn=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.NEEDS_REVIEW])),Qn=Object.freeze(new Set([fe.DRAFT,fe.CONFIRMED,fe.REJECTED,fe.NEEDS_REVIEW]))});import"dotenv/config";import*as M from"fs";import*as B from"path";import{fileURLToPath as zn}from"url";function Vt(){Ee=null,eo=null,se=null,to=null,no=null,oo=null}function Xe(){M.existsSync(ie)||M.mkdirSync(ie,{recursive:!0})}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";M.writeFileSync(o,n);for(let r=0;r<3;r++)try{M.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let c=Date.now();for(;Date.now()-c<200;);continue}throw i}}function Le(e,t){if(!M.existsSync(e))return null;try{let n=JSON.parse(M.readFileSync(e,"utf-8"));try{M.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(M.existsSync(o))try{let r=JSON.parse(M.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{M.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{M.copyFileSync(e,e+".corrupted")}catch{}return null}}function Pe(){return new Date().toISOString().split("T")[0]}function K(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function io(){M.existsSync(pt)||M.mkdirSync(pt,{recursive:!0})}function Ht(e){let t=K(e);return t?B.join(pt,`${t}.json`):null}function ao(e){let t=Ht(e);return t?Le(t,`profile-history/${K(e)}.json`)||[]:[]}function lo(e,t){let n=Ht(e);if(!n)return;io();let o=ao(e);o.unshift(t);try{Fe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${K(e)}: ${r.message}`)}}function qt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ut(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function co(e,t){if(!e)return[];let n=[];for(let o of so){let r=e[o],i=t[o];qt(r)||qt(i)||Ut(r)!==Ut(i)&&n.push(o)}return n}function uo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return Ee||(Xe(),Ee=Le(ft,"people.json")||{},Ee)}function mt(e){Xe(),Ee=e;try{Fe(ft,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(ft)}`)}}function ze(e,t={}){if(!e)return null;let n=Y(),o=Pe(),r=new Date().toISOString(),i=n[e];if(i){let c=co(i,t);c.length>0&&(lo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:uo(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of ro)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return mt(n),n[e]}function Wt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.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),!o.encounters.some(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),mt(n))}function Gt(e){return e&&Y()[e]?.connectionStatus||null}function Ze(e,t,n={}){if(!e)return;n.profileInfo?ze(e,n.profileInfo):Y()[e]||ze(e,{});let o=Y(),r=o[e];r&&(r.connectionStatus=t,r.connectionDate=Pe(),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),mt(o))}function Yt(){return se||(Xe(),se=Le(Bt,"quota.json"),(!se||!se.connections)&&(se={connections:[]}),se)}function fo(e){Xe(),se=e;try{Fe(Bt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Kt(e,t="unknown"){let n=Yt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),fo(n)}function Qt(){let e=Yt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function qe(){let e=Qt(),t=Pe(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Oe,i=o>=Me,c=!r&&!i,u={allowed:c,daily:{sent:n,max:Oe},weekly:{sent:o,max:Me}};return c||(u.reason=r?`Daily limit reached (${n}/${Oe})`:`Weekly limit reached (${o}/${Me})`),u}function Se(){let e=Qt(),t=Pe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Oe,remaining:Oe-n},weekly:{sent:o,max:Me,remaining:Me-o}}}var Xn,Zn,ie,ft,as,Bt,ls,cs,us,pt,Jt,Oe,Me,Ee,eo,se,to,no,oo,ro,so,Ue=re(async()=>{await Qe();Xn=zn(import.meta.url),Zn=B.dirname(B.dirname(Xn)),ie=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Zn,"collected-profiles"),ft=B.join(ie,"people.json"),as=B.join(ie,"jobs.json"),Bt=B.join(ie,"quota.json"),ls=B.join(ie,"conversations.json"),cs=B.join(ie,"sync-state.json"),us=B.join(ie,"application-questions.json"),pt=B.join(ie,"profile-history"),Jt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Oe=Jt(process.env.CONNECT_MAX_DAILY,20),Me=Jt(process.env.CONNECT_MAX_WEEKLY,100),Ee=null,eo=null,se=null,to=null,no=null,oo=null;ro=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],so=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var mn={};de(mn,{cookiesExist:()=>dr,getCookiesPath:()=>rt,loadCookies:()=>ur,saveCookies:()=>cr});import _e from"fs";import pn from"path";function rt(){let e=process.env.ILML_SCOPE_DIR;return e?pn.join(e,"plugins-state","linkedin","cookies.json"):ar}function lr(){let e=rt(),t=pn.dirname(e);return t&&t!=="."&&!_e.existsSync(t)&&_e.mkdirSync(t,{recursive:!0}),e}function cr(e){let t=lr();return _e.writeFileSync(t,JSON.stringify(e)),t}function ur(){let e=rt();if(!_e.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_e.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function dr(){return _e.existsSync(rt())}var ar,hn=re(()=>{ar="cookies.json"});var gn={};de(gn,{cleanSearchName:()=>yr,delayed:()=>w,dismissPremiumOverlay:()=>ye,ensureInboxPage:()=>hr,parseLinkedInTime:()=>mr,safeParseInt:()=>gr,stripDesignations:()=>wr,utilityFunction:()=>fr});function fr(){console.log("Utility function called...")}function Ve(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function mr(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let u=Ve(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=pr[o[1].toLowerCase()],s=Ve(o[2]||""),a=new Date(t),d=a.getDay()-u;return d<=0&&(d+=7),a.setDate(a.getDate()-d),s?a.setHours(s.hours,s.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=At[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),a=parseInt(r[3],10),l=Ve(r[4]||"");return new Date(a,u,s,l?.hours||0,l?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=At[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),a=Ve(i[3]||""),l=t.getFullYear(),d=new Date(l,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(l-1),d.toISOString()}let c=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(c){let u=At[c[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(c[2],10),a=Ve(c[3]||""),l=t.getFullYear(),d=new Date(l,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(l-1),d.toISOString()}return null}async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function hr(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function gr(e){return parseInt(e,10)||0}async function ye(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),c=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||c||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let l of a){let d=l.innerText?.trim().toLowerCase()||"",f=l.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return l.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function yr(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function wr(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}var At,pr,st=re(()=>{At={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},pr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var yn={};de(yn,{extractCertificationsFromDetails:()=>$r,extractEducationFromDetails:()=>kr,extractExperienceFromDetails:()=>br,extractFeaturedFromDetails:()=>Sr,extractRecommendationsFromDetails:()=>Cr,extractSkillsFromDetails:()=>vr});async function br(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function c(l){let d=[];for(let f of l.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=c(i);if(!u)return[];let s=Array.from(u.children).filter(l=>l.tagName==="DIV").filter(l=>(l.textContent||"").trim().length>50);function a(l){let d=l[0]||null,f=null,p=null;if(l[1]){let x=l[1].split("\xB7").map(j=>j.trim());f=x[0]||null,x[1]&&(p=x[1])}let h=l.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),m=null,S=null;if(h>=0){let x=l[h].split("\xB7").map(j=>j.trim());m=x[0]||null,x[1]&&(S=x[1])}let y=null,k=-1;if(h>=0&&l[h+1]){let x=l[h+1],j=/^[>*\-•]|^>/.test(x),J=/https?:\/\//.test(x),R=/\d{4}/.test(x),O=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!j&&!J&&!R&&x.length<100&&O&&(y=x,k=h+1)}let v=null,C=-1,$=l[l.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){C=l.length-1;let x=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(v={listed:x[1].split(",").map(j=>j.trim()),additional:parseInt(x[2],10)})}let g=new Set([0,1,h,k,C].filter(x=>x>=0)),E=l.filter((x,j)=>!g.has(j)),L=E.length>0?E.join(`
|
|
2
2
|
|
|
3
3
|
`):null;return{title:d,company:f,employmentType:p,dates:m,duration:S,location:y,description:L,skills:v,_raw:l}}return s.map(l=>{let f=(l.innerText||"").trim().split(`
|
|
4
4
|
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return a(f)}).filter(l=>l.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function He(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let c=0;c<4;c++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function Ge(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Sr(e,t){return Ge(t,"featured","extractFeaturedFromDetails",async()=>(await He(e,t,"featured"),await e.evaluate(`(() => {
|
|
@@ -235,8 +235,8 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});var kn={};fe(kn,{clickConnectButton:()=>_t,default:()=>Er,detectConnectionStatus:()=>Ae,findConnectButton:()=>Ye,runFunnel:()=>Sn,sendConnectionRequest:()=>It,shouldExcludeLocation:()=>it,viewProfile:()=>Et});async function bn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function it(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Et(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:c=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await bn(e,t));let l=0;for(let v=0;v<2;v++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let g=1;g<=6;g++)await e.evaluate(E=>window.scrollTo(0,E),C*g/6),await w(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===l)break;l=$}await w(800);let d=await e.evaluate(()=>{let v=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),C=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),$=A=>{let _=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},g={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:[]},E=document.querySelector("main");if(!E)return g;let L=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],x=Array.from(E.querySelectorAll("h2")),j=L.find(A=>{let _=A.textContent&&A.textContent.trim(),I=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!v.has(I)&&!C.has(I)}),J=j?j.textContent.trim():null,R=j?j.parentElement:null;for(;R&&R!==E&&!Array.from(R.children).filter(_=>_.tagName==="P").some(_=>{let I=_.textContent&&_.textContent.trim();return I&&I.length>5&&!$(I)});)R=R.parentElement;let O=null,W=null,N=null,V=null;if(R&&R!==E){let A=Array.from(R.children).filter(I=>I.tagName==="P").filter(I=>{let de=I.textContent&&I.textContent.trim();return de&&de.length>5&&!$(de)});if(A[0]&&(O=A[0].textContent.trim()),A[1]){let I=A[1].textContent.trim().split(/\s*[·•]\s*/);W=I[0]||null,I.length>1&&(N=I.slice(1).join(" \xB7 "))}let _=Array.from(R.children).filter(I=>I.tagName==="DIV");for(let I=_.length-1;I>=0;I--){let de=_[I].textContent&&_[I].textContent.trim();if(de&&!(J&&de.startsWith(J))&&(V=de.split(/[·•]/)[0].trim(),V))break}}let H=null;if(R){let A=R.querySelectorAll("p, span, div");for(let _ of A){let I=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if(I==="1st"||I==="2nd"||I==="3rd"){H=I;break}}}let ue=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=T&&T.src||null,q=E.textContent||"",U=null,te=q.match(/(\d+\+?)\s+connections\b/i);te&&(U=te[1]+" connections");let Ke=null,Nt=q.match(/(\d+)\s+mutual connection/i),jt=q.match(/and\s+(\d+)\s+other mutual/i),qn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Nt?Ke=parseInt(Nt[1],10):jt?Ke=2+parseInt(jt[1],10):qn&&(Ke=2);let Ot=null,Mt=null,Ft=x.find(A=>A.textContent&&A.textContent.trim()==="About");if(Ft){let A=Ft.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let I=_.match(/Top skills\s*(.+?)$/i);if(I){let dt=I[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Vn=>Vn.trim()).filter(Boolean);dt.length>0&&dt.length<10&&(Mt=dt)}_=_.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(),Ot=_||null}}let Lt=null,Pt=x.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(Pt){let A=Pt.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(Lt=parseInt(_[1].replace(/,/g,""),10))}}let Un=[...new Set(x.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==J).filter(A=>v.has(A)))],je=document.body.textContent||"",Bn=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),Jn=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:J,title:O,location:V,currentCompany:W,currentSchool:N,connectionDegree:H,hasVerifiedBadge:ue,photoUrl:P,connectionsLevel:U,mutualConnectionsCount:Ke,followers:Lt,openToWork:Bn,hiring:Jn,about:Ot,topSkills:Mt,availableSections:Un}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,S=null,y=null;if(o||r||i||c||u||s){let v=await Promise.resolve().then(()=>(wn(),yn));o&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),c&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),u&&(S=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),s&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...y!==null&&{certifications:y}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Ae(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll('button[aria-label*="Pending"]'),o=Array.from(n).map(s=>s.getAttribute("aria-label")),r=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),c={pendingCount:n.length,pendingLabels:o,hasMessageBtn:!!r,hasConnectBtn:!!i};return n.length>0?{status:"pending",debug:c}:r&&!i?{status:"connected",debug:c}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:c}:{status:"not_connected",debug:c}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ye(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(s=a.textContent?.trim(),s&&!s.includes("notification")))return s;let l=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(l)return l.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let l=document.querySelectorAll('a[href*="custom-invite"]');return{count:l.length,labels:Array.from(l).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(l=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=l.toLowerCase().split(" ")[0],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(p))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f))return h}return null},n);let 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(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let a=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&f.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},s);let l=t?.asElement?.()||null;if(l||await t?.dispose?.().catch(()=>{}),l)return console.log(" Found: button matching profile name"),{button:l,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let s=await e.evaluate(l=>(l.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let a=await e.evaluate((l,d)=>{let f=l.className.includes("muted"),p=l.className.includes("sticky-header")||l.className.includes("sticky"),h=l.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(l.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:S,matchesName:y,ariaLabel:m}},s,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let c=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let a=await e.evaluate(l=>{let d=l.getBoundingClientRect(),f=d.width>0&&d.height>0,p=l.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(a.isVisible&&!a.isInStickyHeader){c=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==c&&await s.dispose().catch(()=>{});if(!c&&u.length>0&&(c=u[u.length-1],console.log(" Found More button by ID pattern (last)")),c||(c=await e.$('button[aria-label="More actions"]'),c&&console.log(" Found More button by aria-label")),!c){let s=await e.evaluateHandle(()=>{let l=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!l)return null;let d=l.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==l)return p;d=d.parentElement}return null});c=s?.asElement?.()||null,c||await s?.dispose?.().catch(()=>{}),c&&console.log(" Found More button by text (near profile actions)")}if(c)try{if(await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),c),await w(500),await e.evaluate(l=>l.click(),c),await w(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 l=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});a=l?.asElement?.()||null,a||await l?.dispose?.().catch(()=>{})}if(!a){let l=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(l)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(l=>(l.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function _t(e,t){await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(l=>({tag:l.tagName,ariaLabel:l.getAttribute("aria-label"),href:l.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",c=(n.ariaLabel||"").toLowerCase();if(c.includes("invite")){let l=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(l&&!c.includes(l))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${l})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let l=e.url();if(l.includes("premium")||l.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(l=>l.click(),t),await w(3e3)):(await e.evaluate(l=>l.click(),t),await w(3e3));let u=e.url();if(u.includes("/premium/")||u.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function xr(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 w(1500);let n=await Ye(e);if(n){await e.evaluate(r=>r.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function It(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=qe();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let c=await Ar(e,t,n);return c.connectionSent&&!i&&Kt(t,o),c}async function Ar(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:c=!0,excludeLocations:u=[]}=n,s={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(`
|
|
239
|
-
--- Connecting: ${a} ---`),u.length>0){let y=Y()[t]?.location;if(it(y,u))return console.log(` \u26A0 Excluded location (stored): ${y}`),s.reason="excluded_location",s.profileInfo={location:y},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await bn(e,t),await w(2e3)),s.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=T=>{let P=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return v;let $=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],g=Array.from(C.querySelectorAll("h2")),E=$.find(T=>{let P=T.textContent&&T.textContent.trim();return P&&P.length>1&&P.length<100&&!y.has(P)&&P!=="0 notifications"}),L=E?E.textContent.trim():null,x=E?E.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(q=>q.tagName==="P").some(q=>{let U=q.textContent&&q.textContent.trim();return U&&U.length>5&&!k(U)});)x=x.parentElement;let j=null,J=null,R=null;if(x&&x!==C){let T=Array.from(x.children),P=T.filter(U=>U.tagName==="P").filter(U=>{let te=U.textContent&&U.textContent.trim();return te&&te.length>5&&!k(te)});P[0]&&(j=P[0].textContent.trim()),P[1]&&(J=P[1].textContent.trim());let q=T.filter(U=>U.tagName==="DIV");for(let U=q.length-1;U>=0;U--){let te=q[U].textContent&&q[U].textContent.trim();if(te&&!(L&&te.startsWith(L))&&(R=te.split(/[·•]/)[0].trim(),R))break}}let O=null;if(x){let T=x.querySelectorAll("p, span, div");for(let P of T){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){O=q;break}}}let W=null,N=g.find(T=>T.textContent&&T.textContent.trim()==="About");if(N){let T=N.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(W=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,W&&(W=W.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let V=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),H=V&&V.src||null,ue=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:L,title:j,location:R,about:W,company:J,connectionDegree:O,connectionsCount:null,mutualConnections:null,photoUrl:H,hasVerifiedBadge:ue}}),u.length>0){let y=s.profileInfo?.location,k=Y()[t]?.location,v=y||k;if(it(v,u))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),s.reason="excluded_location",s;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ae(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&c)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await we(e);let f=await Ye(e);if(!f&&(await we(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),f=await Ye(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=f.method;let p=await _t(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await Ae(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await we(e),await w(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),k),await w(500),await k.click().catch(()=>e.evaluate(C=>C.click(),k)),await w(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..."),await e.evaluate(g=>g.click(),v),await w(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),s.reason="premium_required",s;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),s.reason="premium_required",s}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),C=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!C}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=k?.asElement?.()||null,S||await k.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let v=await xr(e);return s.success=v,s.connectionSent=v,s.reason=v?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",v);await k.type(C,{delay:20}),await w(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=C,s}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let y=S;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await we(e),await w(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let C of k){let $=await e.evaluate(g=>{let E=g.getBoundingClientRect();return{visible:E.width>0&&E.height>0,inSticky:!!g.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){v=C;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let C of k)C!==v&&await C.dispose().catch(()=>{});if(v)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate($=>$.click(),v)),await w(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(L=>L.click(),C),await w(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await Ae(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let E=await e.$('button[aria-label="Send without a note"]');if(E){console.log(" Modal appeared via More dropdown, sending without note...");try{await E.evaluate(L=>L.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(a){console.error(` \u2717 Error: ${a.message}`),s.reason="error",s.error=a.message;let l=a.message.toLowerCase();if(l.includes("detached")||l.includes("session closed")||l.includes("target closed")||l.includes("browser has disconnected")||l.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{s.fatal=!0}return s}}async function Sn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:c=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:a=[],source:l="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
238
|
+
`});var kn={};de(kn,{clickConnectButton:()=>_t,default:()=>Er,detectConnectionStatus:()=>Ae,findConnectButton:()=>Ye,runFunnel:()=>Sn,sendConnectionRequest:()=>It,shouldExcludeLocation:()=>it,viewProfile:()=>Et});async function bn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function it(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Et(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:c=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await bn(e,t));let l=0;for(let v=0;v<2;v++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let g=1;g<=6;g++)await e.evaluate(E=>window.scrollTo(0,E),C*g/6),await w(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===l)break;l=$}await w(800);let d=await e.evaluate(()=>{let v=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),C=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),$=A=>{let _=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},g={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:[]},E=document.querySelector("main");if(!E)return g;let L=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],x=Array.from(E.querySelectorAll("h2")),j=L.find(A=>{let _=A.textContent&&A.textContent.trim(),I=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!v.has(I)&&!C.has(I)}),J=j?j.textContent.trim():null,R=j?j.parentElement:null;for(;R&&R!==E&&!Array.from(R.children).filter(_=>_.tagName==="P").some(_=>{let I=_.textContent&&_.textContent.trim();return I&&I.length>5&&!$(I)});)R=R.parentElement;let O=null,H=null,N=null,V=null;if(R&&R!==E){let A=Array.from(R.children).filter(I=>I.tagName==="P").filter(I=>{let ue=I.textContent&&I.textContent.trim();return ue&&ue.length>5&&!$(ue)});if(A[0]&&(O=A[0].textContent.trim()),A[1]){let I=A[1].textContent.trim().split(/\s*[·•]\s*/);H=I[0]||null,I.length>1&&(N=I.slice(1).join(" \xB7 "))}let _=Array.from(R.children).filter(I=>I.tagName==="DIV");for(let I=_.length-1;I>=0;I--){let ue=_[I].textContent&&_[I].textContent.trim();if(ue&&!(J&&ue.startsWith(J))&&(V=ue.split(/[·•]/)[0].trim(),V))break}}let be=null;if(R){let A=R.querySelectorAll("p, span, div");for(let _ of A){let I=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if(I==="1st"||I==="2nd"||I==="3rd"){be=I;break}}}let W=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),D=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=D&&D.src||null,q=E.textContent||"",U=null,te=q.match(/(\d+\+?)\s+connections\b/i);te&&(U=te[1]+" connections");let Ke=null,Nt=q.match(/(\d+)\s+mutual connection/i),jt=q.match(/and\s+(\d+)\s+other mutual/i),qn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Nt?Ke=parseInt(Nt[1],10):jt?Ke=2+parseInt(jt[1],10):qn&&(Ke=2);let Ot=null,Mt=null,Ft=x.find(A=>A.textContent&&A.textContent.trim()==="About");if(Ft){let A=Ft.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let I=_.match(/Top skills\s*(.+?)$/i);if(I){let dt=I[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Vn=>Vn.trim()).filter(Boolean);dt.length>0&&dt.length<10&&(Mt=dt)}_=_.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(),Ot=_||null}}let Lt=null,Pt=x.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(Pt){let A=Pt.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(Lt=parseInt(_[1].replace(/,/g,""),10))}}let Un=[...new Set(x.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==J).filter(A=>v.has(A)))],je=document.body.textContent||"",Bn=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),Jn=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:J,title:O,location:V,currentCompany:H,currentSchool:N,connectionDegree:be,hasVerifiedBadge:W,photoUrl:P,connectionsLevel:U,mutualConnectionsCount:Ke,followers:Lt,openToWork:Bn,hiring:Jn,about:Ot,topSkills:Mt,availableSections:Un}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,S=null,y=null;if(o||r||i||c||u||s){let v=await Promise.resolve().then(()=>(wn(),yn));o&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),c&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),u&&(S=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),s&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...y!==null&&{certifications:y}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Ae(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=a=>a&&!a.closest(n),r=a=>Array.from(document.querySelectorAll(a)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),c=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(a=>a.getAttribute("aria-label")),hasMessageBtn:!!c,hasConnectBtn:!!u};return i.length>0?{status:"pending",debug:s}:c&&!u?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ye(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(s=a.textContent?.trim(),s&&!s.includes("notification")))return s;let l=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(l)return l.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let l=document.querySelectorAll('a[href*="custom-invite"]');return{count:l.length,labels:Array.from(l).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(l=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=l.toLowerCase().split(" ")[0],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(p))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f))return h}return null},n);let 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(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let a=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&f.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},s);let l=t?.asElement?.()||null;if(l||await t?.dispose?.().catch(()=>{}),l)return console.log(" Found: button matching profile name"),{button:l,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let s=await e.evaluate(l=>(l.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let a=await e.evaluate((l,d)=>{let f=l.className.includes("muted"),p=l.className.includes("sticky-header")||l.className.includes("sticky"),h=l.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(l.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:S,matchesName:y,ariaLabel:m}},s,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let c=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let a=await e.evaluate(l=>{let d=l.getBoundingClientRect(),f=d.width>0&&d.height>0,p=l.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(a.isVisible&&!a.isInStickyHeader){c=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==c&&await s.dispose().catch(()=>{});if(!c&&u.length>0&&(c=u[u.length-1],console.log(" Found More button by ID pattern (last)")),c||(c=await e.$('button[aria-label="More actions"]'),c&&console.log(" Found More button by aria-label")),!c){let s=await e.evaluateHandle(()=>{let l=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!l)return null;let d=l.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==l)return p;d=d.parentElement}return null});c=s?.asElement?.()||null,c||await s?.dispose?.().catch(()=>{}),c&&console.log(" Found More button by text (near profile actions)")}if(c)try{if(await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),c),await w(500),await e.evaluate(l=>l.click(),c),await w(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 l=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});a=l?.asElement?.()||null,a||await l?.dispose?.().catch(()=>{})}if(!a){let l=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(l)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(l=>(l.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function _t(e,t){await e.evaluate(l=>l.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(l=>({tag:l.tagName,ariaLabel:l.getAttribute("aria-label"),href:l.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",c=(n.ariaLabel||"").toLowerCase();if(c.includes("invite")){let l=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(l&&!c.includes(l))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${l})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let l=e.url();if(l.includes("premium")||l.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(l=>l.click(),t),await w(3e3)):(await e.evaluate(l=>l.click(),t),await w(3e3));let u=e.url();if(u.includes("/premium/")||u.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function xr(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 w(1500);let n=await Ye(e);if(n){await e.evaluate(r=>r.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function It(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=qe();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let c=await Ar(e,t,n);return c.connectionSent&&!i&&Kt(t,o),c}async function Ar(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:c=!0,excludeLocations:u=[]}=n,s={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(`
|
|
239
|
+
--- Connecting: ${a} ---`),u.length>0){let y=Y()[t]?.location;if(it(y,u))return console.log(` \u26A0 Excluded location (stored): ${y}`),s.reason="excluded_location",s.profileInfo={location:y},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await bn(e,t),await w(2e3)),s.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=D=>{let P=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return v;let $=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],g=Array.from(C.querySelectorAll("h2")),E=$.find(D=>{let P=D.textContent&&D.textContent.trim();return P&&P.length>1&&P.length<100&&!y.has(P)&&P!=="0 notifications"}),L=E?E.textContent.trim():null,x=E?E.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(q=>q.tagName==="P").some(q=>{let U=q.textContent&&q.textContent.trim();return U&&U.length>5&&!k(U)});)x=x.parentElement;let j=null,J=null,R=null;if(x&&x!==C){let D=Array.from(x.children),P=D.filter(U=>U.tagName==="P").filter(U=>{let te=U.textContent&&U.textContent.trim();return te&&te.length>5&&!k(te)});P[0]&&(j=P[0].textContent.trim()),P[1]&&(J=P[1].textContent.trim());let q=D.filter(U=>U.tagName==="DIV");for(let U=q.length-1;U>=0;U--){let te=q[U].textContent&&q[U].textContent.trim();if(te&&!(L&&te.startsWith(L))&&(R=te.split(/[·•]/)[0].trim(),R))break}}let O=null;if(x){let D=x.querySelectorAll("p, span, div");for(let P of D){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){O=q;break}}}let H=null,N=g.find(D=>D.textContent&&D.textContent.trim()==="About");if(N){let D=N.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(H=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let V=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),be=V&&V.src||null,W=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:L,title:j,location:R,about:H,company:J,connectionDegree:O,connectionsCount:null,mutualConnections:null,photoUrl:be,hasVerifiedBadge:W}}),u.length>0){let y=s.profileInfo?.location,k=Y()[t]?.location,v=y||k;if(it(v,u))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),s.reason="excluded_location",s;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ae(e);if(d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&c)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await ye(e);let f=await Ye(e);if(!f&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),f=await Ye(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=f.method;let p=await _t(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await Ae(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await ye(e),await w(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),k),await w(500),await k.click().catch(()=>e.evaluate(C=>C.click(),k)),await w(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..."),await e.evaluate(g=>g.click(),v),await w(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),s.reason="premium_required",s;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),s.reason="premium_required",s}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),C=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!C}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=k?.asElement?.()||null,S||await k.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let v=await xr(e);return s.success=v,s.connectionSent=v,s.reason=v?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",v);await k.type(C,{delay:20}),await w(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=C,s}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let y=S;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await ye(e),await w(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let C of k){let $=await e.evaluate(g=>{let E=g.getBoundingClientRect();return{visible:E.width>0&&E.height>0,inSticky:!!g.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){v=C;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let C of k)C!==v&&await C.dispose().catch(()=>{});if(v)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate($=>$.click(),v)),await w(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(L=>L.click(),C),await w(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await Ae(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let E=await e.$('button[aria-label="Send without a note"]');if(E){console.log(" Modal appeared via More dropdown, sending without note...");try{await E.evaluate(L=>L.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(a){console.error(` \u2717 Error: ${a.message}`),s.reason="error",s.error=a.message;let l=a.message.toLowerCase();if(l.includes("detached")||l.includes("session closed")||l.includes("target closed")||l.includes("browser has disconnected")||l.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{s.fatal=!0}return s}}async function Sn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:c=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:a=[],source:l="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
240
|
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${c?"View Only":`Connect (max ${i})`}`),c||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!c){let p=Se();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
|
|
241
241
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
242
242
|
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=Gt(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let S=null;if(c){let y=await Et(e,h.profileUrl);y?(ze(h.profileUrl,{...y,source:l}),d.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=qe();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(S=await It(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:l,skipQuotaGate:!0}),S.success)d.connectionsSent++;else switch(S.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(S?.fatal){console.log(`
|
|
@@ -249,8 +249,8 @@ function findEntryContainer(root) {
|
|
|
249
249
|
`),process.exit(1));Cn=_r({token:$n})});import"dotenv/config";function Tr(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Rr({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",c=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${Tr(r)}`:"",s=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${s} \u2014 ${c}${u}`}async function An({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let c=process.env.NODE_RUN_REPORTS;if(!c||!Array.isArray(o)||o.length===0)return;let s=`**${Rr({scriptName:e,mode:t,status:n,error:r,duration:i})}**
|
|
250
250
|
|
|
251
251
|
${o.join(`
|
|
252
|
-
`)}`;try{await Cn.addMessage(c,s)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var En=re(()=>{xn()});var Tn={};
|
|
253
|
-
`)}var jr,Or,Dt,Tt,Rn=re(()=>{En();jr=Nr(import.meta.url),Or=be.dirname(be.dirname(jr)),Dt=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(Or,"collected-profiles"),Tt=be.join(Dt,"run-log.json")});import*as ct from"fs";import*as Te from"path";await Qe();await Ue();import"dotenv/config";import*as et from"fs";import*as me from"path";import{fileURLToPath as po}from"url";var mo=po(import.meta.url),ho=me.dirname(me.dirname(mo)),ht=process.env.DATA_DIR?me.resolve(process.env.DATA_DIR,"collected-profiles"):me.join(ho,"collected-profiles"),Xt=me.join(ht,"connect-queue.json"),go=1,ke=300,tt=["queued","approved","sent","skipped","failed"],he=["high","normal","low"],zt={high:0,normal:1,low:2};function yo(){et.existsSync(ht)||et.mkdirSync(ht,{recursive:!0})}function gt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ke?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:he.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:tt.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ne(){let e=Le(Xt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(gt).filter(n=>n.url):[]}function ge(e){yo(),Fe(Xt,{version:go,entries:e.map(gt)})}function ae(e){return K(e)||(e||"").trim().toLowerCase()}function Be(e,t){let n=ae(t);return e.find(o=>ae(o.url)===n)||null}function yt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:c}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(a=>ae(a.url)));for(let a of t){let l=a?.url;if(!l){u.skippedNoUrl++;continue}let d=ae(l);if(s.has(d)){u.skippedDup++;continue}if(i(l)){u.skippedEngaged++;continue}let f=typeof a.note=="string"?a.note.trim():"";f.length>ke&&u.notesTooLong++;let p=f.length>0&&f.length<=ke;e.push(gt({url:l,tag:a.tag||o,priority:a.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:c||null})),s.add(d),u.added++}return u}function Zt(e){return[...e].sort((t,n)=>{let o=(zt[t.priority]??1)-(zt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ve(e,t){return e.filter(n=>n.status===t)}await Ue();await Qe();var wo={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};function en(e){if(!e)return null;for(let[t,n]of Object.entries(wo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}import"dotenv/config";import*as b from"fs";import*as Ct from"os";import*as D from"path";import{fileURLToPath as Vo}from"url";var St={};fe(St,{NAME:()=>So,VERSION:()=>bo,up:()=>$o});import*as z from"fs";import*as nt from"path";var bo=1,So="normalize-jobs-and-questions",ko=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],vo=50;function wt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function bt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function $o(e,t){let n=nt.join(e,"jobs.json"),o=nt.join(t,"scouted-jobs.json"),r=nt.join(e,"application-questions.json"),i=wt(n)||{},c=wt(o)||{},u=0,s=[];for(let l of Object.keys(i)){if(!c[l])continue;let d=c[l],f=i[l];for(let p of ko)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(l),u++}u>0?(bt(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=wt(r);if(a&&Array.isArray(a.applications)){let l={},d=0;for(let f of a.applications){let p=f.jobId||"unknown";l[p]||(l[p]={applications:[]});let h=(f.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=vo?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});l[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}bt(r,l),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(l).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} 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(s.length>0){for(let l of s)delete c[l];bt(o,c),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var kt={};fe(kt,{NAME:()=>xo,VERSION:()=>Co,up:()=>_o});import*as X from"fs";import*as tn from"path";var Co=2,xo="reset-unread-flags";function Ao(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function Eo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function _o(e){let t=tn.join(e,"conversations.json"),n=Ao(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Eo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var vt={};fe(vt,{NAME:()=>Do,VERSION:()=>Io,up:()=>Oo});import*as Z from"fs";import*as nn from"path";var Io=3,Do="recompute-last-message-by",To=new Set(["draft","confirmed","rejected","needs_review"]);function Ro(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function No(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function jo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!To.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,c)=>c.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let c=i.sender;if(c===t)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function Oo(e){let t=nn.join(e,"conversations.json"),n=Ro(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,c=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let a=Array.isArray(s.messages)?s.messages:[],l=jo(a,o),d=l==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==l&&c++,s.lastMessageBy=l,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}No(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${c} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await Ue();import"dotenv/config";import*as Q from"path";import{fileURLToPath as Mo}from"url";var Fo=Mo(import.meta.url),Lo=Q.dirname(Q.dirname(Fo)),Je=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Lo,"market-research"),ks=Q.join(Je,"scouted-jobs.json"),vs=Q.join(Je,"discovered-people.json"),$s=Q.join(Je,"visit-log.json"),Cs=Q.join(Je,"companies.json"),xs=Q.join(Je,"job-decisions.json");function on(){Po=null,qo=null,Uo=null,Bo=null,Jo=null}var Po=null;var qo=null;var Uo=null;var Bo=null;var Jo=null;var Ho=Vo(import.meta.url),Wo=D.dirname(Ho),Go=D.dirname(D.dirname(Wo));function Yo(e){return e&&(e==="~"?Ct.homedir():e.startsWith("~/")||e.startsWith("~\\")?D.join(Ct.homedir(),e.slice(2)):e)}var oe=process.env.DATA_DIR?D.resolve(Yo(process.env.DATA_DIR)):Go,Ce=D.join(oe,"collected-profiles"),xe=D.join(oe,"market-research"),G=D.join(oe,".schema-version"),rn=[D.join(Ce,".schema-version"),D.join(xe,".schema-version")],ye=3,le=[{version:1,module:St},{version:2,module:kt},{version:3,module:vt}];(function(){le.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of le){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=le.length?le[le.length-1].version:0;if(n!==ye)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ye}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<le.length;o++){let r=o+1;if(le[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${le[o].version}`)}})();function cn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
252
|
+
`)}`;try{await Cn.addMessage(c,s)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var En=re(()=>{xn()});var Tn={};de(Tn,{endRun:()=>Lr,formatScriptStatus:()=>Ur,getLastRun:()=>qr,getRunHistory:()=>Pr,getTodayRunSummary:()=>In,startRun:()=>Fr,timeAgo:()=>Dn});import"dotenv/config";import*as ee from"fs";import*as we from"path";import{fileURLToPath as Nr}from"url";function Mr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let r=0;r<3;r++)try{ee.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let c=Date.now();for(;Date.now()-c<200;);continue}throw i}}function Ie(){try{if(!ee.existsSync(Tt))return{runs:[]};let e=JSON.parse(ee.readFileSync(Tt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function _n(e){ee.existsSync(Dt)||ee.mkdirSync(Dt,{recursive:!0});try{Mr(Tt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Fr(e,t="default"){let n=Ie();for(let c of n.runs)c.status==="running"&&(c.status="interrupted",c.result="interrupted",c.timestamp&&(c.duration=Date.now()-new Date(c.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(c=>new Date(c.timestamp).getTime()>i),_n(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Lr(e,t,n=null,o=null){if(!e)return;let r=null;try{let c=Ie(),u=c.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration;else{let s=c.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}_n(c)}catch(c){console.error(`[runLog] Failed to end run: ${c.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let c=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";An({scriptName:e.script,mode:e.mode,status:c,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function Pr(e=7){let t=Ie(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function qr(e=null){let t=Ie(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function In(){let e=new Date().toISOString().slice(0,10),t=Ie(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function Dn(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function Ur(){let e=["sync-all","messages","funnel","sync","apply"],t=Ie(),n=In(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let c=t.runs.filter(m=>m.script===i),u=[...c].reverse().find(m=>m.status==="success"),s=c[c.length-1],a=u||s,l=a?Dn(a.timestamp):"never",f=(a?Math.floor((Date.now()-new Date(a.timestamp).getTime())/864e5):1/0)>1?" \u26A0":a?.status==="error"?" \u2717":" \u2713",p="";if(a?.stats){let m=a.stats,S=Object.entries(m).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);S.length&&(p=` (${S.join(", ")})`)}let h=a?.duration?` ${Math.round(a.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${l.padEnd(16)}${h}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[i,c]of r){let u=[];c.success&&u.push(`${c.success} success`),c.error&&u.push(`${c.error} error`),c.interrupted&&u.push(`${c.interrupted} interrupted`),c.running&&u.push(`${c.running} running`),o.push(` Today: ${i} \xD7${c.total} (${u.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
|
|
253
|
+
`)}var jr,Or,Dt,Tt,Rn=re(()=>{En();jr=Nr(import.meta.url),Or=we.dirname(we.dirname(jr)),Dt=process.env.DATA_DIR?we.resolve(process.env.DATA_DIR,"collected-profiles"):we.join(Or,"collected-profiles"),Tt=we.join(Dt,"run-log.json")});import*as ct from"fs";import*as Te from"path";await Qe();await Ue();import"dotenv/config";import*as et from"fs";import*as pe from"path";import{fileURLToPath as po}from"url";var mo=po(import.meta.url),ho=pe.dirname(pe.dirname(mo)),ht=process.env.DATA_DIR?pe.resolve(process.env.DATA_DIR,"collected-profiles"):pe.join(ho,"collected-profiles"),Xt=pe.join(ht,"connect-queue.json"),go=1,ke=300,tt=["queued","approved","sent","skipped","failed"],me=["high","normal","low"],zt={high:0,normal:1,low:2};function yo(){et.existsSync(ht)||et.mkdirSync(ht,{recursive:!0})}function gt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ke?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:me.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:tt.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function ne(){let e=Le(Xt,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(gt).filter(n=>n.url):[]}function he(e){yo(),Fe(Xt,{version:go,entries:e.map(gt)})}function ae(e){return K(e)||(e||"").trim().toLowerCase()}function Be(e,t){let n=ae(t);return e.find(o=>ae(o.url)===n)||null}function yt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:c}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(a=>ae(a.url)));for(let a of t){let l=a?.url;if(!l){u.skippedNoUrl++;continue}let d=ae(l);if(s.has(d)){u.skippedDup++;continue}if(i(l)){u.skippedEngaged++;continue}let f=typeof a.note=="string"?a.note.trim():"";f.length>ke&&u.notesTooLong++;let p=f.length>0&&f.length<=ke;e.push(gt({url:l,tag:a.tag||o,priority:a.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:c||null})),s.add(d),u.added++}return u}function Zt(e){return[...e].sort((t,n)=>{let o=(zt[t.priority]??1)-(zt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function ve(e,t){return e.filter(n=>n.status===t)}await Ue();await Qe();var wo={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};function en(e){if(!e)return null;for(let[t,n]of Object.entries(wo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}import"dotenv/config";import*as b from"fs";import*as Ct from"os";import*as T from"path";import{fileURLToPath as Vo}from"url";var St={};de(St,{NAME:()=>So,VERSION:()=>bo,up:()=>$o});import*as z from"fs";import*as nt from"path";var bo=1,So="normalize-jobs-and-questions",ko=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],vo=50;function wt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function bt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function $o(e,t){let n=nt.join(e,"jobs.json"),o=nt.join(t,"scouted-jobs.json"),r=nt.join(e,"application-questions.json"),i=wt(n)||{},c=wt(o)||{},u=0,s=[];for(let l of Object.keys(i)){if(!c[l])continue;let d=c[l],f=i[l];for(let p of ko)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(l),u++}u>0?(bt(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=wt(r);if(a&&Array.isArray(a.applications)){let l={},d=0;for(let f of a.applications){let p=f.jobId||"unknown";l[p]||(l[p]={applications:[]});let h=(f.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=vo?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});l[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}bt(r,l),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(l).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} 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(s.length>0){for(let l of s)delete c[l];bt(o,c),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var kt={};de(kt,{NAME:()=>xo,VERSION:()=>Co,up:()=>_o});import*as X from"fs";import*as tn from"path";var Co=2,xo="reset-unread-flags";function Ao(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function Eo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function _o(e){let t=tn.join(e,"conversations.json"),n=Ao(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Eo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var vt={};de(vt,{NAME:()=>Do,VERSION:()=>Io,up:()=>Oo});import*as Z from"fs";import*as nn from"path";var Io=3,Do="recompute-last-message-by",To=new Set(["draft","confirmed","rejected","needs_review"]);function Ro(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function No(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function jo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!To.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,c)=>c.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let c=i.sender;if(c===t)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function Oo(e){let t=nn.join(e,"conversations.json"),n=Ro(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,c=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let a=Array.isArray(s.messages)?s.messages:[],l=jo(a,o),d=l==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==l&&c++,s.lastMessageBy=l,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}No(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${c} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}await Ue();import"dotenv/config";import*as Q from"path";import{fileURLToPath as Mo}from"url";var Fo=Mo(import.meta.url),Lo=Q.dirname(Q.dirname(Fo)),Je=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Lo,"market-research"),ks=Q.join(Je,"scouted-jobs.json"),vs=Q.join(Je,"discovered-people.json"),$s=Q.join(Je,"visit-log.json"),Cs=Q.join(Je,"companies.json"),xs=Q.join(Je,"job-decisions.json");function on(){Po=null,qo=null,Uo=null,Bo=null,Jo=null}var Po=null;var qo=null;var Uo=null;var Bo=null;var Jo=null;var Ho=Vo(import.meta.url),Wo=T.dirname(Ho),Go=T.dirname(T.dirname(Wo));function Yo(e){return e&&(e==="~"?Ct.homedir():e.startsWith("~/")||e.startsWith("~\\")?T.join(Ct.homedir(),e.slice(2)):e)}var oe=process.env.DATA_DIR?T.resolve(Yo(process.env.DATA_DIR)):Go,Ce=T.join(oe,"collected-profiles"),xe=T.join(oe,"market-research"),G=T.join(oe,".schema-version"),rn=[T.join(Ce,".schema-version"),T.join(xe,".schema-version")],ge=3,le=[{version:1,module:St},{version:2,module:kt},{version:3,module:vt}];(function(){le.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of le){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=le.length?le[le.length-1].version:0;if(n!==ge)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ge}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<le.length;o++){let r=o+1;if(le[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${le[o].version}`)}})();function cn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
254
254
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
255
255
|
`),process.exit(1));try{b.mkdirSync(oe,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
256
256
|
[FATAL] Cannot create DATA_DIR (${oe}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -260,7 +260,7 @@ ${o.join(`
|
|
|
260
260
|
[FATAL] DATA_DIR (${oe}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
261
261
|
`),process.exit(1));for(let t of[Ce,xe]){let n;try{n=b.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
262
262
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
263
|
-
`),process.exit(1))}}var $e=
|
|
263
|
+
`),process.exit(1))}}var $e=T.join(oe,".migration-lock");function Ko(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync($e,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync($e,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(c){c.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let c=Date.parse(t.startedAt);Number.isNaN(c)||(i=Date.now()-c)}o&&i<r&&(console.error(`
|
|
264
264
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${$e}
|
|
265
265
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
266
266
|
`),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=$e+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,$e),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function xt(){try{if(JSON.parse(b.readFileSync($e,"utf-8")).pid!==process.pid)return;b.unlinkSync($e)}catch{}}var sn=!1;function Qo(){if(sn)return;sn=!0;let e=()=>{try{xt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function zo(){if(b.existsSync(G))return;let e=[],t=[];for(let i of rn)if(b.existsSync(i))try{e.push({file:i,schema:ot(i)})}catch(c){t.push({file:i,err:c.message})}if(t.length>0){console.error(`
|
|
@@ -272,11 +272,11 @@ ${o.join(`
|
|
|
272
272
|
[FATAL] ${G} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
273
273
|
`),process.exit(1)}let t=Xo(e);return t===null&&(console.error(`
|
|
274
274
|
[FATAL] ${G} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
275
|
-
`),process.exit(1)),t}function un(e){try{b.chmodSync(e,384)}catch{}}function Zo(e){if(cn(),b.existsSync(G))try{if(b.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=G+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),un(t),b.renameSync(t,G)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function ln(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let s=u.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return b.statSync(
|
|
276
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
277
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
275
|
+
`),process.exit(1)),t}function un(e){try{b.chmodSync(e,384)}catch{}}function Zo(e){if(cn(),b.existsSync(G))try{if(b.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=G+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),un(t),b.renameSync(t,G)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function ln(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let s=u.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return b.statSync(T.join(e,u)).isFile()}catch{return!1}}),r=0,i=0,c=[];for(let u of o){let s=T.join(e,u),a=T.join(e,u+n);if(b.existsSync(a)){i++;continue}try{fn(s,a),r++}catch(l){c.push({file:u,err:l.message})}}if(c.length>0){let u=new Error(`Failed to back up ${c.length} file(s) in ${T.basename(e)}/: `+c.map(s=>`${s.file} (${s.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||i>0){let u=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${T.basename(e)}/ (${n})${u}`)}}var $t=!1;async function dn(){if($t)return;cn(),rr();let t=an().version;if(t===ge){$t=!0;return}Qo(),Ko(),process.on("exit",xt),t>ge&&(console.error(`
|
|
276
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ge}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
277
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${ge}.
|
|
278
278
|
`),process.exit(1)),console.log(`
|
|
279
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
279
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${ge}`);let n=sr();if(!n.ok){console.error(`
|
|
280
280
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
281
281
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
282
282
|
`),process.exit(1)}let o=le.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
@@ -289,22 +289,22 @@ ${o.join(`
|
|
|
289
289
|
`)}process.exit(1)}try{let s=new Date().toISOString(),a={version:r.version,name:u.NAME||i,appliedAt:s},l=an();l.version=r.version,l.migratedAt=s,l.migrations=l.migrations||[],l.migrations.push(a),Zo(l)}catch(s){console.error(`
|
|
290
290
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${s.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
291
291
|
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Vt()}catch{}try{on()}catch{}$t=!0,xt(),console.log(`
|
|
292
|
-
\u2713 Schema is now at v${
|
|
293
|
-
`)}var er=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tr(e){let t=e.toLowerCase();return er.some(n=>n.test(t))}var nr=6e4;function or(){let e=Date.now(),t=[];for(let n of[oe,Ce,xe]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!tr(r))continue;let i=
|
|
294
|
-
`);let c=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Te.join(at,`fail-${c}.png`)})}catch{}return r.modal||""}catch{return""}}var Re=process.argv.slice(2),Fn=Re[0],Ne=Re.filter(e=>!e.startsWith("--")),De=e=>Re.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),ce=e=>{let t=Re.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&F(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},Rt=()=>new Date().toISOString();function ut(){let e=Y(),t=new Map;for(let[n,o]of Object.entries(e)){let r=K(o.profileUrl||n);r&&t.set(r,o)}return t}function Ln(e,t){let n=e.get(K(t));return n?On.has(n.connectionStatus)||Mn.has(n.connectionStatus):!1}async function Vr(){let e=Ne[1];if(!e)return F("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(a){return F(`Could not read/parse ${e}: ${a.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=ce("tag")||"untagged",o=ce("priority");if(o&&!
|
|
292
|
+
\u2713 Schema is now at v${ge}
|
|
293
|
+
`)}var er=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tr(e){let t=e.toLowerCase();return er.some(n=>n.test(t))}var nr=6e4;function or(){let e=Date.now(),t=[];for(let n of[oe,Ce,xe]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!tr(r))continue;let i=T.join(n,r);try{let c=b.statSync(i);if(!c.isFile()||e-c.mtimeMs<nr)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function rr({verbose:e=!1}={}){let t=or();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${T.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function sr(){let e=[];for(let t of[Ce,xe]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=T.join(t,o);try{ot(r)}catch(i){e.push({dir:T.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ir(e){let t=[],n=[];for(let i of[Ce,xe]){if(!b.existsSync(i))continue;let c=b.readdirSync(i).filter(u=>u.endsWith(e));for(let u of c){let s=T.join(i,u),a=u.slice(0,-e.length),l=T.join(i,a);try{a.toLowerCase().endsWith(".json")?ot(s):b.accessSync(s,b.constants.R_OK),t.push({backupPath:s,originalPath:l,fileName:u,dir:i})}catch(d){n.push(`${T.basename(i)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:c,fileName:u,dir:s}of t)try{fn(i,c),o++}catch(a){r.push(`${T.basename(s)}/${u}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function fn(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),un(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var On=new Set(["connected"]),Mn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Nn=new Set(["pending","connected","excluded_location","email_required","premium_required"]),Br=3,at=process.env.DATA_DIR?Te.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):Te.resolve("collected-profiles","connect-diagnostics");async function Jr(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(a=>Array.from(document.querySelectorAll(a)).map(l=>(l.innerText||"").trim()).filter(Boolean).join(" | "))('[role="alertdialog"], [role="dialog"], .artdeco-modal, .artdeco-toast-item, .ip-fuse-limit-alert, .artdeco-inline-feedback').slice(0,1e3),body:(document.body.innerText||"").slice(0,1500)}));ct.mkdirSync(at,{recursive:!0});let i={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};ct.appendFileSync(Te.join(at,"connect-failures.jsonl"),JSON.stringify(i)+`
|
|
294
|
+
`);let c=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Te.join(at,`fail-${c}.png`)})}catch{}return r.modal||""}catch{return""}}var Re=process.argv.slice(2),Fn=Re[0],Ne=Re.filter(e=>!e.startsWith("--")),De=e=>Re.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),ce=e=>{let t=Re.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&F(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},Rt=()=>new Date().toISOString();function ut(){let e=Y(),t=new Map;for(let[n,o]of Object.entries(e)){let r=K(o.profileUrl||n);r&&t.set(r,o)}return t}function Ln(e,t){let n=e.get(K(t));return n?On.has(n.connectionStatus)||Mn.has(n.connectionStatus):!1}async function Vr(){let e=Ne[1];if(!e)return F("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(a){return F(`Could not read/parse ${e}: ${a.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=ce("tag")||"untagged",o=ce("priority");if(o&&!me.includes(o))return F(`--priority must be one of: ${me.join(", ")}`);let r=o||"normal",i=ne(),c=ut(),u=yt(i,t,{tag:n,priority:r,nowIso:Rt(),alreadyEngaged:a=>Ln(c,a)});he(i),console.log(`
|
|
295
295
|
Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${ke} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let s=i.filter(a=>a.status==="queued"&&a.withNote).length;console.log(`
|
|
296
296
|
Queue now: ${ve(i,"queued").length} queued, ${ve(i,"approved").length} approved.`),s&&console.log(` ${s} queued entries have a note saved \u2014 sent only with \`connect run --with-notes\`.`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var jn=["founder","investor","hiring_manager","peer"];function Hr(){let e=ce("category");if(e===void 0&&De("valuable")&&(e=jn.join(",")),!e)return F(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
|
|
297
|
-
(shortcut: --valuable = ${jn.join(",")})`);let t=e.split(",").map($=>$.trim()).filter(Boolean),n=$=>{let g=ce($);if(g===void 0)return;let E=parseInt(g,10);return!Number.isInteger(E)||E<0?F(`--${$} must be a non-negative integer.`):E},o=n("min-posts")??0,r=n("max"),i=ce("priority");if(i&&!
|
|
297
|
+
(shortcut: --valuable = ${jn.join(",")})`);let t=e.split(",").map($=>$.trim()).filter(Boolean),n=$=>{let g=ce($);if(g===void 0)return;let E=parseInt(g,10);return!Number.isInteger(E)||E<0?F(`--${$} must be a non-negative integer.`):E},o=n("min-posts")??0,r=n("max"),i=ce("priority");if(i&&!me.includes(i))return F(`--priority must be one of: ${me.join(", ")}`);let c=ce("tag"),u=!De("no-validate"),s=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),a=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map($=>$.trim().toLowerCase()).filter(Boolean),l=$=>{if(!$)return!1;let g=String($).toLowerCase();return a.some(E=>g.includes(E))},d=Y(),f=[],p=0,h=0,m=0;for(let[$,g]of Object.entries(d))if(t.includes(g.category)&&!(On.has(g.connectionStatus)||Mn.has(g.connectionStatus))&&g.connectionDegree!=="1st"&&!((g.jobIds?.length||0)<o)){if(l(g.location)){p++;continue}if(u&&s.has(g.category)){let E=(typeof g.title=="string"?g.title:"").trim();if(!E){h++;continue}if(en(E)!==g.category){m++;continue}}f.push({url:g.profileUrl||$,p:g})}let S={high:0,medium:1,low:2};f.sort(($,g)=>(S[$.p.personPriority]??1)-(S[g.p.personPriority]??1)||(g.p.mutualConnections||0)-($.p.mutualConnections||0)||(g.p.jobIds?.length||0)-($.p.jobIds?.length||0)),r!==void 0&&(f=f.slice(0,r));let y=f.map($=>({url:$.url,tag:c||$.p.category,priority:i||($.p.personPriority==="high"?"high":"normal")})),k=ne(),v=ut(),C=yt(k,y,{alreadyEngaged:$=>Ln(v,$),nowIso:Rt()});he(k),console.log(`
|
|
298
298
|
Filled ${C.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}${u?"":" (--no-validate)"}.`),C.skippedDup&&console.log(` ${C.skippedDup} already in queue \u2014 skipped.`),C.skippedEngaged&&console.log(` ${C.skippedEngaged} already connected/pending \u2014 skipped.`),p&&console.log(` ${p} in excluded locations \u2014 skipped.`),m&&console.log(` ${m} filtered \u2014 title doesn't confirm the category (likely mis-tagged by enrichment).`),h&&console.log(` ${h} skipped \u2014 no title stored to validate (held; not visited, to avoid ban risk).`),console.log(`
|
|
299
299
|
Queue now: ${ve(k,"queued").length} queued, ${ve(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function Wr(){let e=ne();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=ce("status"),n=ut(),o=Se();console.log(`
|
|
300
300
|
=== Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
|
|
301
301
|
`);let r={};for(let a of e)r[a.status]=(r[a.status]||0)+1;console.log("Status: "+Object.entries(r).map(([a,l])=>`${a}=${l}`).join(" ")+`
|
|
302
302
|
`),t&&!tt.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${tt.join(", ")})
|
|
303
303
|
`);let i=t?e.filter(a=>a.status===t):e,c={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...i].sort((a,l)=>(c[a.status]??9)-(c[l.status]??9));for(let a of u){let l=n.get(K(a.url)),d=l&&l.name||"",f=l&&l.title?` \xB7 ${l.title.slice(0,40)}`:"",p=l&&l.mutualConnections?` \xB7 ${l.mutualConnections} mutual`:"",h=a.withNote?"\u{1F4DD}":" ",m=a.priority==="high"?"\u2B06high ":a.priority==="low"?"\u2B07low ":"normal";console.log(` [${a.status.padEnd(8)}] ${m} ${h} ${d}${f}${p}`),console.log(` ${a.url} (tag=${a.tag})`)}let s=e.filter(a=>(a.status==="queued"||a.status==="approved")&&a.withNote).length;s&&console.log(`
|
|
304
|
-
${s} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function lt(e,t,n,o){let r=ne(),i=0;for(let c of r)e(c)&&t.includes(c.status)&&(c.status=n,i++);return
|
|
305
|
-
${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function Gr(){let e=["queued","failed"];if(De("all"))return lt(()=>!0,e,"approved","Approved");let t=ce("tag");if(t)return lt(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=Ne[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=ae(n);return lt(r=>ae(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function Yr(){let e=Ne[1];if(!e)return F("Usage: connect skip <url>");let t=ae(e);return lt(n=>ae(n.url)===t,["queued","approved"],"skipped","Skipped")}function Kr(){let e=Re[1],t=Re[2];if(!e||t===void 0)return F('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return F("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>ke)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${ke}. Shorten it.`);let o=ne(),r=Be(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,
|
|
306
|
-
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function Qr(){let e=Ne[1];if(!e)return F("Usage: connect no-note <url>");let t=ne(),n=Be(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,
|
|
307
|
-
Note reminder cleared.`)}function zr(){let e=Ne[1],t=Ne[2];if(!e||!
|
|
304
|
+
${s} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function lt(e,t,n,o){let r=ne(),i=0;for(let c of r)e(c)&&t.includes(c.status)&&(c.status=n,i++);return he(r),console.log(`
|
|
305
|
+
${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function Gr(){let e=["queued","failed"];if(De("all"))return lt(()=>!0,e,"approved","Approved");let t=ce("tag");if(t)return lt(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=Ne[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=ae(n);return lt(r=>ae(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function Yr(){let e=Ne[1];if(!e)return F("Usage: connect skip <url>");let t=ae(e);return lt(n=>ae(n.url)===t,["queued","approved"],"skipped","Skipped")}function Kr(){let e=Re[1],t=Re[2];if(!e||t===void 0)return F('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return F("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>ke)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${ke}. Shorten it.`);let o=ne(),r=Be(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,he(o),console.log(`
|
|
306
|
+
Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function Qr(){let e=Ne[1];if(!e)return F("Usage: connect no-note <url>");let t=ne(),n=Be(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,he(t),console.log(`
|
|
307
|
+
Note reminder cleared.`)}function zr(){let e=Ne[1],t=Ne[2];if(!e||!me.includes(t))return F(`Usage: connect priority <url> <${me.join("|")}>`);let n=ne(),o=Be(n,e);if(!o)return F("Not in queue.");o.priority=t,he(n),console.log(`
|
|
308
308
|
Priority set to ${t}.`)}async function Xr(){let e=De("dry-run"),t=De("yes"),n=De("with-notes"),o=ce("max"),r=1/0;if(o!==void 0){let g=parseInt(o,10);if(!Number.isInteger(g)||g<0)return F("--max must be a non-negative integer.");r=g}let i=Se(),c=Math.min(i.daily.remaining,i.weekly.remaining),u=ne(),s=Zt(ve(u,"approved"));if(!s.length){let g=ve(u,"queued").length;console.log(`
|
|
309
309
|
Nothing approved to send.`),g&&console.log(` ${g} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(c<=0){console.log(`
|
|
310
310
|
Connection quota is used up (${i.daily.remaining}/${i.daily.max} today, ${i.weekly.remaining}/${i.weekly.max} week). Try again later.`);return}let a=s.slice(0,Math.min(r,c));if(!a.length){console.log(`
|
|
@@ -313,7 +313,7 @@ Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let l=a.filter(g=>g.with
|
|
|
313
313
|
[dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
|
|
314
314
|
Press Enter to send, or Ctrl+C to cancel...`),await new Promise(g=>process.stdin.once("data",()=>g())));let f=(await import("puppeteer")).default,{loadCookies:p}=await Promise.resolve().then(()=>(hn(),mn)),{sendConnectionRequest:h}=await vn().then(()=>kn),{delayed:m}=await Promise.resolve().then(()=>(st(),gn)),{startRun:S,endRun:y}=await Promise.resolve().then(()=>(Rn(),Tn)),k=S("connect","run"),v,C;try{v=await f.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),C=await v.newPage(),await C.setCookie(...p())}catch(g){console.error(`
|
|
315
315
|
[!] ${g.message}
|
|
316
|
-
`);try{v&&await v.close()}catch{}try{y(k,"error",null,g.message)}catch{}process.exit(1)}let $=0;try{let g=Y(),E=new Map;for(let[O,
|
|
316
|
+
`);try{v&&await v.close()}catch{}try{y(k,"error",null,g.message)}catch{}process.exit(1)}let $=0;try{let g=Y(),E=new Map;for(let[O,H]of Object.entries(g)){let N=K(H.profileUrl||O);N&&E.set(N,O)}let L=0,x=0,j=0,J=0;for(let O of a){if(!qe().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let H=n&&O.withNote,N=await h(C,O.url,{message:H?O.note:null,useCustomMessage:H,source:O.tag,skipQuotaGate:!0}),V;if(N.connectionSent?(V="sent",L++):Nn.has(N.reason)?(V="skipped",x++):(V="failed",j++),V==="failed"){J++;let W=await Jr(C,O,N.reason);console.log(` \u2717 ${O.url.slice(-32)} \u2014 ${N.reason||"failed"}${W?` \xB7 LinkedIn: "${W.slice(0,120)}"`:""}`)}else J=0;let be=E.get(K(O.url));if(N.connectionSent||Nn.has(N.reason)&&be){let W=be||O.url;try{Ze(W,N.reason,{method:N.method,messageSent:N.messageSent,profileInfo:N.profileInfo})}catch{}}try{let W=ne(),D=Be(W,O.url);D&&(D.status=V,V==="sent"&&(D.sentAt=Rt()),D.result=N.reason||N.error||V,he(W))}catch(W){console.error(` \u26A0 Could not persist queue update for ${O.url}: ${W.message}`)}if(N.fatal){console.log(`
|
|
317
317
|
\u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(J>=Br){console.log(`
|
|
318
318
|
\u26A0 ${J} sends failed in a row \u2014 stopping to protect your account (this is often LinkedIn's invite limit).`),console.log(` What LinkedIn showed on each failure is saved to: ${at}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await m(3e3+Math.random()*2e3)}let R=Se();console.log(`
|
|
319
319
|
=== Done: ${L} sent, ${x} skipped, ${j} failed ===`),console.log(`Connection quota left: ${R.daily.remaining}/${R.daily.max} today, ${R.weekly.remaining}/${R.weekly.max} week.`);try{y(k,"success",{sent:L,skipped:x,failed:j})}catch{}}catch(g){console.error(`
|