ilml-plugin-linkedin 1.20.22 → 1.20.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/applyQueue.mjs +38 -38
- package/dist/connect.mjs +78 -77
- package/dist/daily.mjs +34 -34
- package/dist/enrichProfiles.mjs +50 -50
- package/dist/funnelRunner.mjs +61 -60
- package/dist/messageBot.mjs +67 -67
- package/dist/migrationCli.mjs +44 -44
- package/dist/peopleSearchCli.mjs +13 -0
- package/dist/quota.mjs +34 -34
- package/dist/run.mjs +65 -64
- package/dist/scout.mjs +33 -33
- package/dist/syncAll.mjs +99 -98
- package/dist/syncConnections.mjs +48 -48
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +35 -35
- package/dist/visit.mjs +48 -48
- package/ilml-plugin.json +19 -1
- package/package.json +2 -1
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Qo=Object.defineProperty;var ee=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{for(var n in t)Qo(e,n,{get:t[n],enumerable:!0})};import B from"fs";import oe from"path";function bt(){let e=process.env.ILML_SCOPE_DIR;return e?oe.join(e,"plugins-state","linkedin","cookies.json"):fr}function dr(){let e=bt(),t=oe.dirname(e);return t&&t!=="."&&!B.existsSync(t)&&B.mkdirSync(t,{recursive:!0}),e}function pn(e){let t=dr();return B.writeFileSync(t,JSON.stringify(e)),t}function hn(){let e=bt();if(!B.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=B.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 gn(){return B.existsSync(bt())}function mr(){let e=process.env.ILML_SCOPE_DIR;return e?oe.join(e,"plugins-state","linkedin"):"."}function yn(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function pr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?yn(t[1]):"default"}function wn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return B.existsSync(t)||B.mkdirSync(t,{recursive:!0}),oe.resolve(t);let n=yn(e||pr()),o=oe.join(mr(),"chrome-profile",n);return B.existsSync(o)||B.mkdirSync(o,{recursive:!0}),oe.resolve(o)}function Sn(e){return!B.existsSync(oe.join(e,bn))}function kn(e){try{B.writeFileSync(oe.join(e,bn),new Date().toISOString())}catch{}}function vn(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{B.rmSync(oe.join(e,n),{force:!0}),t++}catch{}return t}var fr,bn,tt=ee(()=>{fr="cookies.json";bn=".ilml-seeded"});async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function hr(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let l=Date.now();for(;Date.now()-l<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-l;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(s=>setTimeout(s,o))}return!1}function gr(e){return xn.test(e||"")}async function yr(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),l=Date.now(),s=!1;for(;Date.now()-l<r;){let i="wait";try{i=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",xn.source)}catch{}if(i==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(f=>f.name==="li_at")){let f=pn(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${f}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(i==="creds"){if(!o){let a=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}s||(s=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function bn(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await ur(e,t,{timeout:o,label:n});if(!r&&fr(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return r}async function Ce(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:i=6e4,autoRecover:s=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await bn(e,{readySelector:n,label:o,timeout:r})}catch(c){if(s&&c.code==="SESSION_EXPIRED"){await dr(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await bn(e,{readySelector:n,label:o,timeout:r})}throw c}}async function ge(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"),s=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||s||c){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let u of a){let d=u.innerText?.trim().toLowerCase()||"",f=u.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return u.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})}var Sn,Ze=X(()=>{Xe();Sn=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function pr(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function vn(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&n.set("distance",String(i)),kn(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),kn(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let s=pr(e.JOB_SEARCH_COMPANY_IDS);s.length&&n.set("f_C",s.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",mr[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+n.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(l+="&"+a),l}var mr,kn,Cn=X(()=>{mr={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},kn=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as hr}from"@ilivemylife/graph-sdk";var gr,An,de,oe,yt,wt,bt=X(async()=>{Cn();gr=await hr();for(let[e,t]of Object.entries(gr))process.env[e]===void 0&&(process.env[e]=t);An=vn(process.env);An&&(process.env.LINKEDIN_SEARCH_URL=An);de=process.env.LINKEDIN_NAME,oe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),yt=Object.freeze(new Set([oe.DRAFT,oe.CONFIRMED,oe.NEEDS_REVIEW])),wt=Object.freeze(new Set([oe.DRAFT,oe.CONFIRMED,oe.REJECTED,oe.NEEDS_REVIEW]))});import"dotenv/config";import*as j from"fs";import*as L from"path";import{fileURLToPath as yr}from"url";function Dn(){Ae=null,Sr=null,re=null,kr=null,vr=null,Cr=null}function tt(){j.existsSync(se)||j.mkdirSync(se,{recursive:!0})}function vt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let r=0;r<3;r++)try{j.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ct(e,t){if(!j.existsSync(e))return null;try{let n=JSON.parse(j.readFileSync(e,"utf-8"));try{j.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${L.resolve(e)}`);let o=e+".backup";if(j.existsSync(o))try{let r=JSON.parse(j.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{j.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{j.copyFileSync(e,e+".corrupted")}catch{}return null}}function Le(){return new Date().toISOString().split("T")[0]}function ye(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function xn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function xe(e,t,n=null){if(!t||e[t])return t;let o=ye(t);if(!o)return t;let r=null;for(let[i,s]of Object.entries(e)){if(ye(s.profileUrl||i)===o)return i;!r&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=i)}if(r){let i=xn(n),s=xn(e[r].name);if(i&&s&&i===s)return r}return t}function _r(){j.existsSync(kt)||j.mkdirSync(kt,{recursive:!0})}function Rn(e){let t=ye(e);return t?L.join(kt,`${t}.json`):null}function $r(e){let t=Rn(e);return t?Ct(t,`profile-history/${ye(e)}.json`)||[]:[]}function Er(e,t){let n=Rn(e);if(!n)return;_r();let o=$r(e);o.unshift(t);try{vt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ye(e)}: ${r.message}`)}}function _n(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function $n(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Ir(e,t){if(!e)return[];let n=[];for(let o of xr){let r=e[o],i=t[o];_n(r)||_n(i)||$n(r)!==$n(i)&&n.push(o)}return n}function Dr(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 ie(){return Ae||(tt(),Ae=Ct(St,"people.json")||{},Ae)}function nt(e){tt(),Ae=e;try{vt(St,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${L.resolve(St)}`)}}function et(e,t={}){if(!e)return null;let n=ie(),o=Le(),r=new Date().toISOString(),i=xe(n,e,t.name),s=n[i];if(s){let c=Ir(s,t);c.length>0&&(Er(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:Dr(s)}),s.lastSnapshotAt=r),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=r,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let l of Ar)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(s[l])&&s[l].length>0)continue;s[l]=t[l]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=r)}else n[i]={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,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return nt(n),n[i]}function Tn(e,t){if(!e||!t)return;let n=ie(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Le(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),nt(n))}function On(e){return e&&ie()[e]?.connectionStatus||null}function Nn(e,t,n={}){if(!e)return;if(n.profileInfo)et(e,n.profileInfo);else{let c=ie(),l=xe(c,e,n.profileInfo?.name);c[l]||et(e,{})}let o=ie(),r=xe(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let s=Le();i.connectionStatus=t,t==="connected"?i.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=s)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),nt(o)}function jn(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ye(t);if(!o)return;let r=ie(),i=xe(r,e),s=r[i];if(!s)return;let c=ye(s.profileUrl||i);o!==c&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(o)||(s.aliases.push(o),s.lastUpdated=new Date().toISOString(),nt(r)))}function Pn(){return re||(tt(),re=Ct(En,"quota.json"),(!re||!re.connections)&&(re={connections:[]}),re)}function Rr(e){tt(),re=e;try{vt(En,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Ln(e,t="unknown"){let n=Pn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Rr(n)}function Fn(){let e=Pn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function At(){let e=Fn(),t=Le(),n=e.filter(l=>l.date===t).length,o=e.length,r=n>=je,i=o>=Pe,s=!r&&!i,c={allowed:s,daily:{sent:n,max:je},weekly:{sent:o,max:Pe}};return s||(c.reason=r?`Daily limit reached (${n}/${je})`:`Weekly limit reached (${o}/${Pe})`),c}function xt(){let e=Fn(),t=Le(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:je,remaining:je-n},weekly:{sent:o,max:Pe,remaining:Pe-o}}}var wr,br,se,St,Ji,En,Hi,Vi,Wi,kt,In,je,Pe,Ae,Sr,re,kr,vr,Cr,Ar,xr,ot=X(async()=>{await bt();wr=yr(import.meta.url),br=L.dirname(L.dirname(wr)),se=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(br,"collected-profiles"),St=L.join(se,"people.json"),Ji=L.join(se,"jobs.json"),En=L.join(se,"quota.json"),Hi=L.join(se,"conversations.json"),Vi=L.join(se,"sync-state.json"),Wi=L.join(se,"application-questions.json"),kt=L.join(se,"profile-history"),In=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},je=In(process.env.CONNECT_MAX_DAILY,20),Pe=In(process.env.CONNECT_MAX_WEEKLY,100),Ae=null,Sr=null,re=null,kr=null,vr=null,Cr=null;Ar=["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"],xr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Mn={};te(Mn,{extractCertificationsFromDetails:()=>Pr,extractEducationFromDetails:()=>Nr,extractExperienceFromDetails:()=>Tr,extractFeaturedFromDetails:()=>Or,extractRecommendationsFromDetails:()=>Lr,extractSkillsFromDetails:()=>jr});async function Tr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await Ce(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await S(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(900);await S(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)r++,await S(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function s(u){let d=[];for(let f of u.querySelectorAll("div")){let m=Array.from(f.children).filter(y=>y.tagName==="DIV");if(m.length<3)continue;let h=m.filter(y=>(y.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,m)=>m.count-f.count||f.totalText-m.totalText),d[0]?.el}let c=s(i);if(!c)return[];let l=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function a(u){let d=u[0]||null,f=null,m=null;if(u[1]){let k=u[1].split("\xB7").map(E=>E.trim());f=k[0]||null,k[1]&&(m=k[1])}let h=u.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),y=null,g=null;if(h>=0){let k=u[h].split("\xB7").map(E=>E.trim());y=k[0]||null,k[1]&&(g=k[1])}let p=null,v=-1;if(h>=0&&u[h+1]){let k=u[h+1],E=/^[>*\-•]|^>/.test(k),ee=/https?:\/\//.test(k),z=/\d{4}/.test(k),F=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!E&&!ee&&!z&&k.length<100&&F&&(p=k,v=h+1)}let A=null,w=-1,x=u[u.length-1];if(x&&/and\s+\+\d+\s+skills?$/i.test(x)){w=u.length-1;let k=x.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(A={listed:k[1].split(",").map(E=>E.trim()),additional:parseInt(k[2],10)})}let T=new Set([0,1,h,v,w].filter(k=>k>=0)),D=u.filter((k,E)=>!T.has(E)),R=D.length>0?D.join(`
|
|
3
|
+
`))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function Cn(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await hr(e,t,{timeout:o,label:n});if(!r&&gr(e.url())){let l=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}return r}async function Ae(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:l=6e4,autoRecover:s=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:l});try{return await Cn(e,{readySelector:n,label:o,timeout:r})}catch(c){if(s&&c.code==="SESSION_EXPIRED"){await yr(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:l})}catch{}return await Cn(e,{readySelector:n,label:o,timeout:r})}throw c}}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||"",l=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),s=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(l||s||c){let i=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(i)return i.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let u of a){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.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})}var xn,nt=ee(()=>{tt();xn=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function br(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function $n(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let l=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(l)&&l>0&&n.set("distance",String(l)),An(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),An(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let s=br(e.JOB_SEARCH_COMPANY_IDS);s.length&&n.set("f_C",s.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&n.set("f_TPR",wr[c]||c),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let i="https://www.linkedin.com/jobs/search/?"+n.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(i+="&"+a),i}var wr,An,_n=ee(()=>{wr={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},An=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as Sr}from"@ilivemylife/graph-sdk";var kr,En,me,re,St,kt,vt=ee(async()=>{_n();kr=await Sr();for(let[e,t]of Object.entries(kr))process.env[e]===void 0&&(process.env[e]=t);En=$n(process.env);En&&(process.env.LINKEDIN_SEARCH_URL=En);me=process.env.LINKEDIN_NAME,re=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),St=Object.freeze(new Set([re.DRAFT,re.CONFIRMED,re.NEEDS_REVIEW])),kt=Object.freeze(new Set([re.DRAFT,re.CONFIRMED,re.REJECTED,re.NEEDS_REVIEW]))});import"dotenv/config";import*as N from"fs";import*as F from"path";import{fileURLToPath as vr}from"url";function jn(){$e=null,Ar=null,se=null,$r=null,_r=null,Er=null}function rt(){N.existsSync(ie)||N.mkdirSync(ie,{recursive:!0})}function At(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";N.writeFileSync(o,n);for(let r=0;r<3;r++)try{N.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw l}}function $t(e,t){if(!N.existsSync(e))return null;try{let n=JSON.parse(N.readFileSync(e,"utf-8"));try{N.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${F.resolve(e)}`);let o=e+".backup";if(N.existsSync(o))try{let r=JSON.parse(N.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{N.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{N.copyFileSync(e,e+".corrupted")}catch{}return null}}function Me(){return new Date().toISOString().split("T")[0]}function we(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function In(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function _e(e,t,n=null){if(!t||e[t])return t;let o=we(t);if(!o)return t;let r=null;for(let[l,s]of Object.entries(e)){if(we(s.profileUrl||l)===o)return l;!r&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=l)}if(r){let l=In(n),s=In(e[r].name);if(l&&s&&l===s)return r}return t}function Rr(){N.existsSync(xt)||N.mkdirSync(xt,{recursive:!0})}function Nn(e){let t=we(e);return t?F.join(xt,`${t}.json`):null}function Tr(e){let t=Nn(e);return t?$t(t,`profile-history/${we(e)}.json`)||[]:[]}function Or(e,t){let n=Nn(e);if(!n)return;Rr();let o=Tr(e);o.unshift(t);try{At(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${we(e)}: ${r.message}`)}}function Dn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Rn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function jr(e,t){if(!e)return[];let n=[];for(let o of Dr){let r=e[o],l=t[o];Dn(r)||Dn(l)||Rn(r)!==Rn(l)&&n.push(o)}return n}function Nr(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 le(){return $e||(rt(),$e=$t(Ct,"people.json")||{},$e)}function st(e){rt(),$e=e;try{At(Ct,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${F.resolve(Ct)}`)}}function ot(e,t={}){if(!e)return null;let n=le(),o=Me(),r=new Date().toISOString(),l=_e(n,e,t.name),s=n[l];if(s){let c=jr(s,t);c.length>0&&(Or(l,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:Nr(s)}),s.lastSnapshotAt=r),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=r,t.source&&!s.sources?.includes(t.source)&&(s.sources=s.sources||[],s.sources.push(t.source));for(let i of Ir)if(t[i]!=null){if(Array.isArray(t[i])&&t[i].length===0&&Array.isArray(s[i])&&s[i].length>0)continue;s[i]=t[i]}Array.isArray(t.availableSections)&&(s.lastFullVisitAt=r)}else n[l]={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,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return st(n),n[l]}function Pn(e,t){if(!e||!t)return;let n=le(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let l={date:Me(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(l.jobId=String(t.jobId)),t.jobTitle&&(l.jobTitle=t.jobTitle),t.jobCompany&&(l.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===l.date&&c.source===l.source&&c.action===l.action&&(c.jobId||"")===(l.jobId||""))&&(o.encounters.push(l),o.lastUpdated=new Date().toISOString(),st(n))}function Fn(e){return e&&le()[e]?.connectionStatus||null}function Ln(e,t,n={}){if(!e)return;if(n.profileInfo)ot(e,n.profileInfo);else{let c=le(),i=_e(c,e,n.profileInfo?.name);c[i]||ot(e,{})}let o=le(),r=_e(o,e,n.profileInfo?.name),l=o[r];if(!l)return;let s=Me();l.connectionStatus=t,t==="connected"?l.connectionDate=s:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(l.requestedConnectionAt||(l.requestedConnectionAt=s)),l.connectionMethod=n.method||l.connectionMethod,l.messageSent=n.messageSent||l.messageSent,l.lastUpdated=new Date().toISOString(),st(o)}function Mn(e,t,n={}){if(n.dryRun||!e||!t)return;let o=we(t);if(!o)return;let r=le(),l=_e(r,e),s=r[l];if(!s)return;let c=we(s.profileUrl||l);o!==c&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(o)||(s.aliases.push(o),s.lastUpdated=new Date().toISOString(),st(r)))}function Un(){return se||(rt(),se=$t(Tn,"quota.json"),(!se||!se.connections)&&(se={connections:[]}),se)}function Pr(e){rt(),se=e;try{At(Tn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function qn(e,t="unknown"){let n=Un(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Pr(n)}function Bn(){let e=Un(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function _t(){let e=Bn(),t=Me(),n=e.filter(i=>i.date===t).length,o=e.length,r=n>=Fe,l=o>=Le,s=!r&&!l,c={allowed:s,daily:{sent:n,max:Fe},weekly:{sent:o,max:Le}};return s||(c.reason=r?`Daily limit reached (${n}/${Fe})`:`Weekly limit reached (${o}/${Le})`),c}function Et(){let e=Bn(),t=Me(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Fe,remaining:Fe-n},weekly:{sent:o,max:Le,remaining:Le-o}}}var Cr,xr,ie,Ct,el,Tn,tl,nl,ol,xt,On,Fe,Le,$e,Ar,se,$r,_r,Er,Ir,Dr,it=ee(async()=>{await vt();Cr=vr(import.meta.url),xr=F.dirname(F.dirname(Cr)),ie=process.env.DATA_DIR?F.resolve(process.env.DATA_DIR,"collected-profiles"):F.join(xr,"collected-profiles"),Ct=F.join(ie,"people.json"),el=F.join(ie,"jobs.json"),Tn=F.join(ie,"quota.json"),tl=F.join(ie,"conversations.json"),nl=F.join(ie,"sync-state.json"),ol=F.join(ie,"application-questions.json"),xt=F.join(ie,"profile-history"),On=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Fe=On(process.env.CONNECT_MAX_DAILY,20),Le=On(process.env.CONNECT_MAX_WEEKLY,100),$e=null,Ar=null,se=null,$r=null,_r=null,Er=null;Ir=["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"],Dr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Jn={};te(Jn,{extractCertificationsFromDetails:()=>qr,extractEducationFromDetails:()=>Mr,extractExperienceFromDetails:()=>Fr,extractFeaturedFromDetails:()=>Lr,extractRecommendationsFromDetails:()=>Br,extractSkillsFromDetails:()=>Ur});async function Fr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await Ae(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await k(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let l=0;l<5;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let s of document.querySelectorAll("button"))if(/^Load more$/i.test((s.textContent||"").trim()))return s.click(),!0;return!1});)r++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let l=document.querySelector("main");if(!l)return[];function s(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(w=>w.tagName==="DIV");if(m.length<3)continue;let h=m.filter(w=>(w.textContent||"").trim().length>50);h.length<3||(d.textContent||"").length<500||f.push({el:d,count:h.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let c=s(l);if(!c)return[];let i=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function a(u){let f=u[0]||null,d=null,m=null;if(u[1]){let b=u[1].split("\xB7").map(T=>T.trim());d=b[0]||null,b[1]&&(m=b[1])}let h=u.findIndex(b=>/(\d{4}|present)/i.test(b)&&/(-|–|—)/i.test(b)&&b.length<80),w=null,g=null;if(h>=0){let b=u[h].split("\xB7").map(T=>T.trim());w=b[0]||null,b[1]&&(g=b[1])}let p=null,v=-1;if(h>=0&&u[h+1]){let b=u[h+1],T=/^[>*\-•]|^>/.test(b),M=/https?:\/\//.test(b),X=/\d{4}/.test(b),L=/,/.test(b)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(b);!T&&!M&&!X&&b.length<100&&L&&(p=b,v=h+1)}let C=null,y=-1,A=u[u.length-1];if(A&&/and\s+\+\d+\s+skills?$/i.test(A)){y=u.length-1;let b=A.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);b&&(C={listed:b[1].split(",").map(T=>T.trim()),additional:parseInt(b[2],10)})}let R=new Set([0,1,h,v,y].filter(b=>b>=0)),D=u.filter((b,T)=>!R.has(T)),_=D.length>0?D.join(`
|
|
4
4
|
|
|
5
|
-
`):null;return{title:
|
|
6
|
-
`).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return a(
|
|
7
|
-
${
|
|
5
|
+
`):null;return{title:f,company:d,employmentType:m,dates:w,duration:g,location:p,description:_,skills:C,_raw:u}}return i.map(u=>{let d=(u.innerText||"").trim().split(`
|
|
6
|
+
`).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return a(d)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Ue(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await Ae(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await k(1e3);let r=e.url();if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let l=0;for(;l<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});)l++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function Be(e,t,n,o){try{return await o()}catch(r){let l=r.message||"";if(r.code==="SESSION_EXPIRED"||/^session expired/i.test(l))throw r;return/not available on profile/i.test(l)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${l.slice(0,120)}`),[])}}async function Lr(e,t){return Be(t,"featured","extractFeaturedFromDetails",async()=>(await Ue(e,t,"featured"),await e.evaluate(`(() => {
|
|
7
|
+
${qe}
|
|
8
8
|
|
|
9
9
|
const main = document.querySelector('main');
|
|
10
10
|
if (!main) return [];
|
|
@@ -44,8 +44,8 @@ var Wo=Object.defineProperty;var X=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{f
|
|
|
44
44
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
45
45
|
return true;
|
|
46
46
|
});
|
|
47
|
-
})()`)))}async function
|
|
48
|
-
${
|
|
47
|
+
})()`)))}async function Mr(e,t){return Be(t,"education","extractEducationFromDetails",async()=>(await Ue(e,t,"education"),await e.evaluate(`(() => {
|
|
48
|
+
${qe}
|
|
49
49
|
|
|
50
50
|
const main = document.querySelector('main');
|
|
51
51
|
if (!main) return [];
|
|
@@ -81,8 +81,8 @@ var Wo=Object.defineProperty;var X=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{f
|
|
|
81
81
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
82
82
|
return true;
|
|
83
83
|
});
|
|
84
|
-
})()`)))}async function
|
|
85
|
-
${
|
|
84
|
+
})()`)))}async function Ur(e,t){return Be(t,"skills","extractSkillsFromDetails",async()=>(await Ue(e,t,"skills"),await e.evaluate(`(() => {
|
|
85
|
+
${qe}
|
|
86
86
|
|
|
87
87
|
const main = document.querySelector('main');
|
|
88
88
|
if (!main) return [];
|
|
@@ -113,8 +113,8 @@ var Wo=Object.defineProperty;var X=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{f
|
|
|
113
113
|
skills.push({ name, endorsements, _raw: lines });
|
|
114
114
|
}
|
|
115
115
|
return skills;
|
|
116
|
-
})()`)))}async function
|
|
117
|
-
${
|
|
116
|
+
})()`)))}async function qr(e,t){return Be(t,"certifications","extractCertificationsFromDetails",async()=>(await Ue(e,t,"certifications"),await e.evaluate(`(() => {
|
|
117
|
+
${qe}
|
|
118
118
|
|
|
119
119
|
const main = document.querySelector('main');
|
|
120
120
|
if (!main) return [];
|
|
@@ -138,8 +138,8 @@ var Wo=Object.defineProperty;var X=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{f
|
|
|
138
138
|
|
|
139
139
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
140
140
|
}).filter(e => e.name);
|
|
141
|
-
})()`)))}async function
|
|
142
|
-
${
|
|
141
|
+
})()`)))}async function Br(e,t){return Be(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Ue(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
142
|
+
${qe}
|
|
143
143
|
|
|
144
144
|
const main = document.querySelector('main');
|
|
145
145
|
if (!main) return [];
|
|
@@ -174,7 +174,7 @@ var Wo=Object.defineProperty;var X=(e,t)=>()=>(e&&(t=e(e=0)),t);var te=(e,t)=>{f
|
|
|
174
174
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
175
175
|
return true;
|
|
176
176
|
});
|
|
177
|
-
})()`)))}var
|
|
177
|
+
})()`)))}var qe,Hn=ee(()=>{nt();qe=`
|
|
178
178
|
function findEntryContainer(root) {
|
|
179
179
|
const candidates = [];
|
|
180
180
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -237,71 +237,72 @@ function findEntryContainer(root) {
|
|
|
237
237
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
238
238
|
return candidates[0]?.el;
|
|
239
239
|
}
|
|
240
|
-
`});var Hn={};te(Hn,{BLOCK_MARKERS:()=>qn,dedupeAndCap:()=>Jn,extractSidePanelProfiles:()=>Fr,normalizeFundUrl:()=>rt,normalizeProfileUrl:()=>_e,scanRelatedBlocks:()=>Bn});function _e(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function rt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Bn(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=a=>(a||"").replace(/\s+/g," ").trim(),r=a=>{let u=String(a||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=a=>o(a).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=a=>{let u=a,d=null;for(let f=0;f<6&&u.parentElement;f++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){d||(d=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return d||a.parentElement},c=[],l=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let a of l){let u=o(a.textContent).toLowerCase();if(!u)continue;let d=e.find(([g])=>u.includes(g));if(!d)continue;let f=d[1],m=s(a);if(!m)continue;let h=0,y=new Set;for(let g of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let p=g.href||g.getAttribute("href")||"",v=r(p);if(!v)continue;let A=g.querySelector('span[aria-hidden="true"]'),w=o(A?A.textContent:g.getAttribute("aria-label")||g.textContent),x=i(w);if(!x||y.has(v))continue;y.add(v);let T="",D=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(D&&(T=o(D[1])),!T){let R=g.closest("li")||g.parentElement;R&&(T=Array.from(R.querySelectorAll("p, span")).map(E=>o(E.textContent)).filter(E=>E&&E!==x&&!/^view\b/i.test(E)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(E)&&/[a-z]/i.test(E)&&E.length>2)[0]||"")}c.push({href:p,name:x,headline:T,block:f,rank:h++})}}return c}function Jn(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=_e(t.seedUrl||""),r=new Map,i={};for(let s of e||[]){let c=_e(s.href);c&&(o&&c===o||(i[s.block]=i[s.block]||0,!(i[s.block]>=n)&&(r.has(c)||(i[s.block]++,r.set(c,{url:c,name:s.name,headline:s.headline||null,block:s.block,rank:s.rank})))))}return Array.from(r.values())}async function Fr(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Bn,qn)}catch{return[]}return Jn(n,t)}var qn,_t=X(()=>{qn=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var zn={};te(zn,{getJobDecision:()=>Hr,getLastVisit:()=>Xr,getScoutStats:()=>Zr,loadCompanies:()=>Tt,loadDiscoveredPeople:()=>We,loadJobDecisions:()=>Rt,loadScoutedJobs:()=>Dt,loadVisitLog:()=>lt,recordCompany:()=>Kr,recordDiscoveredEdge:()=>Gr,recordDiscoveredEdges:()=>Yr,recordVisit:()=>Qr,resetCaches:()=>It,saveCompany:()=>zr,saveDiscoveredPerson:()=>Vr,saveScoutedJob:()=>Br,setJobDecision:()=>Jr});import"dotenv/config";import*as V from"fs";import*as J from"path";import{fileURLToPath as Mr}from"url";function me(){V.existsSync(be)||V.mkdirSync(be,{recursive:!0})}function pe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";V.writeFileSync(o,n);for(let r=0;r<3;r++)try{V.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ve(e){try{if(V.existsSync(e))return JSON.parse(V.readFileSync(e,"utf-8"))}catch{}return null}function It(){qe=null,Be=null,Je=null,He=null,we=null}function Dt(){return qe||(qe=Ve(Vn)||{},qe)}function Br(e,t){if(!e)return;me();let n=Dt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,i]of Object.entries(t))i!=null&&(n[e][r]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{pe(Vn,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function Rt(){return Be||(Be=Ve(Gn)||{},Be)}function Jr(e,t,n={}){if(!e||!t)return;me();let o=Rt(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{pe(Gn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Hr(e){return Rt()[e]||null}function We(){return Je||(Je=Ve(it)||{},Je)}function $e(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Yn(e,t){let n=_e(t)||t;if(e[n])return n;let o=$e(t);if(!o)return n;let r=null;for(let[i,s]of Object.entries(e)){if($e(s&&(s.canonicalUrl||s.profileUrl)||i)===o)return i;!r&&s&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=i)}return r||n}function Vr(e,t){if(!e)return;me();let n=We(),o=new Date().toISOString().slice(0,10),r=Yn(n,e),i=$e(e);if(n[r]){let s=n[r];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&$e(s.canonicalUrl||s.profileUrl||r)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=o,s.seenCount=(s.seenCount||1)+1}else n[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{pe(it,n)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Wr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function Kn(e,t,n={},o){if(!t)return;let r=$e(t);t=Yn(e,t);let i=n.seedUrl?{...n,seedUrl:_e(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=Wr(i,o),a=e[t];a||(a=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),n.name&&(a.name=n.name),n.headline&&(!a.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(a.headline))&&(a.headline=n.headline),n.location&&(a.location=a.location||n.location),n.company&&(a.company=n.company),n.companyUrl&&(a.companyUrl=a.companyUrl||n.companyUrl),n.isConnected!=null&&(a.isConnected=n.isConnected),n.connectionsCount!=null&&(a.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(a.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(a.connectGate=n.connectGate),n.note&&!a.note&&(a.note=n.note),n.whyUseful&&!a.whyUseful&&(a.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(a.extra={...a.extra||{},...n.extra}),Array.isArray(a.sources)||(a.sources=[]);let u=a.sources.find(l);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):a.sources.push(c),Array.isArray(a.categories)||(a.categories=[]),Array.isArray(a.sectors)||(a.sectors=[]),Array.isArray(a.aliases)||(a.aliases=[]),Array.isArray(a.graphRefs)||(a.graphRefs=[]),$t(a.categories,n.category),st(a.categories,n.categories),st(a.sectors,n.sectors),st(a.aliases,n.aliases),r&&$e(a.canonicalUrl||t)!==r&&$t(a.aliases,r),st(a.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(a.affiliations)||(a.affiliations=[]);for(let d of n.affiliations)!d||!d.companyKey||a.affiliations.some(f=>f.companyKey===d.companyKey&&f.role===d.role)||a.affiliations.push(d)}a.lastSeen=s,a.seenCount=(a.seenCount||0)+1}function Gr(e,t={}){if(!e)return;me();let n=We();Kn(n,e,t,new Date().toISOString());try{pe(it,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Yr(e){if(!Array.isArray(e)||e.length===0)return;me();let t=We(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(Kn(t,r.url,r,n),o++);if(o)try{pe(it,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function Kr(e={}){if(!e||!e.name)return;me();let t=e.key||rt(e.website)||rt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=Tt(),o=new Date().toISOString().slice(0,10),r=(l,a)=>{a&&Array.isArray(l)&&!l.includes(a)&&l.push(a)},i=(l,a)=>{if(Array.isArray(a))for(let u of a)r(l,u)},s=n[t];s||(s=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!s[l]&&(s[l]=e[l]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[l])||(s[l]=[]),i(s[l],e[l]);Array.isArray(s.people)||(s.people=[]);let c=l=>{if(!l||!l.url)return;let a=s.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));a?l.current!=null&&(a.current=l.current):s.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(l=>c({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let l of e.portfolio||[]){let a=l&&(l.key||l.name);a&&!s.portfolio.some(u=>(u.key||u.name)===a)&&s.portfolio.push(l)}s.lastSeen=o,s.seenCount=(s.seenCount||0)+1;try{pe(Et,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function Tt(){return He||(He=Ve(Et)||{},He)}function zr(e,t){if(!e)return;me();let n=Tt(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{pe(Et,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function lt(){return we||(we=Ve(Wn)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function Qr(e,t={}){if(!e)return;me();let n=lt();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{pe(Wn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Xr(e){let t=lt();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function Zr(){let e=Dt(),t=We(),n=Object.values(e),o=Object.values(t),r={};for(let f of n)f.company&&(r[f.company]=(r[f.company]||0)+1);let i=Object.entries(r).sort((f,m)=>m[1]-f[1]).slice(0,5).map(([f,m])=>`${f} (${m})`),s={};for(let f of n)for(let m of f.techStack||[])s[m]=(s[m]||0)+1;let c=Object.entries(s).sort((f,m)=>m[1]-f[1]).slice(0,8).map(([f,m])=>`${f} (${m})`),l=lt(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(f=>f.date.startsWith(a)).length,d=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:d,todayVisited:u,lastScoutDate:n.length>0?n.sort((f,m)=>(m.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}var Ur,qr,be,Vn,it,Wn,Et,Gn,qe,Be,Je,$t,st,He,we,Ot=X(()=>{_t();Ur=Mr(import.meta.url),qr=J.dirname(J.dirname(Ur)),be=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"market-research"):J.join(qr,"market-research"),Vn=J.join(be,"scouted-jobs.json"),it=J.join(be,"discovered-people.json"),Wn=J.join(be,"visit-log.json"),Et=J.join(be,"companies.json"),Gn=J.join(be,"job-decisions.json");qe=null;Be=null;Je=null;$t=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},st=(e,t)=>{if(Array.isArray(t))for(let n of t)$t(e,n)};He=null;we=null});var lo={};te(lo,{computeEngagement:()=>jt,detectCategory:()=>Zn,detectCategoryFromTitle:()=>at,determineAction:()=>so,determineLastMessageBy:()=>to,determineSituation:()=>eo,enrichConversation:()=>es,enrichPerson:()=>is,enrichPersonContext:()=>io,extractAutoTags:()=>oo,generateSummary:()=>no,normPreview:()=>Nt});function es(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!wt.has(l.status)),i=ns(t,e.profileUrl,n),s=to(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Zn(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=eo(r,s,t),r.length>0){let l=r[r.length-1];e.lastMessageTime=l.time}if(r.length>0&&!e.initiatedBy){let l=r[0];l.sender===de?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=jt(r,t),e.personContext=io(i),e.summary=no(e,t,i),e.autoTags=oo(e,t,i);let c=so(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=ts(e),e}function Zn(e,t,n){if(!e||e.length===0)return n?.title?at(n.title):null;let o=e.filter(r=>r.sender!==de&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,i]of Object.entries(Xn))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(o))return r}if(n?.title){let r=at(n.title);if(r)return r}return null}function at(e){if(!e)return null;for(let[t,n]of Object.entries(Xn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function eo(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Qn.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(i=>i.sender!==de&&i.sender!=="Unknown");return Qn.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function to(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let i=r.sender;if(i===de)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function no(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],i=e.category,s=n?.title,c=n?.company,l=n?.location;i==="recruiter"&&c?r.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):i==="founder"&&c?r.push(`Founder of ${c}`):i&&s?r.push(`${Pt(i)}: ${Ee(s,40)}`):s?r.push(Ee(s,50)):r.push(t.split(" ")[0]);let a=o.filter(h=>h.sender!==de&&h.sender!=="Unknown").map(h=>h.text).join(" "),u=os(a),d=rs(a),f=ss(a),m=[];return u&&m.push(u),f&&f!==l&&m.push(f),d&&m.push(d),m.length>0&&r.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function oo(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!wt.has(a.status)),i=r.map(a=>a.text).join(" "),s=r.filter(a=>a.sender!==de&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=ro(s,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let l=e.engagement||jt(r,t);return l.messageCount>=6&&o.push("active-thread"),l.theirCount===0&&l.ourCount>0&&o.push("no-response"),l.ourCount===0&&l.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(a=>yt.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function ro(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let s of o)i.includes(s)&&n.push(s.replace(/\s+/g,"-"));for(let[s,c]of r)i.includes(s)&&n.push(c);return n}function so(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Nt(e.lastMessagePreview)===Nt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(i=>yt.has(i.status));return r?r.status===oe.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Pt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function jt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,i=!1,s=!1,c=e.map(l=>l.text).join(" ");for(let l of e)l.sender===de?n++:l.sender==="Unknown"||l.sender===""?r++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:i,hasSalary:s}}function io(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function ts(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function ns(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=xe(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Nt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Pt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ee(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function os(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function rs(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function ss(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function is(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=at(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}ls(e),e.personSummary=as(e),e.personAutoTags=cs(e);let n=us(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=fs(e)),e}function ls(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function as(e){let t=[],n=e.category,o=e.title,r=e.company,i=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${Ee(o,40)} at ${Ee(r,30)}`):o?t.push(Ee(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${Ee(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function cs(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=ro("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function us(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Pt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function fs(e){let t=e.category;if(!t)return null;let n=ds(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ds(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var Xn,Qn,ao=X(async()=>{await bt();await ot();Xn={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]}};Qn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var uo={};te(uo,{DEFAULT_PROFILE_INTERESTS:()=>co,computeFit:()=>hs,detectSectors:()=>ps});function ps(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(ms))r.some(i=>i.test(t))&&n.push(o);return n}function hs(e,t=co){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let i of e){let s=n(t&&t[i]);s>r&&(r=s)}return Math.min(1,r/o)}var ms,co,fo=X(()=>{ms={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};co={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import yi from"puppeteer";import"dotenv/config";import*as H from"fs";import*as fe from"path";import{fileURLToPath as er}from"url";import"dotenv/config";import{createGraphClient as Go,resolveToken as Yo}from"@ilivemylife/graph-sdk";import{config as Ko}from"dotenv";Ko();var rn=Yo()||process.env.TOKEN;rn||(console.error(`
|
|
240
|
+
`});var Yn={};te(Yn,{BLOCK_MARKERS:()=>Vn,dedupeAndCap:()=>Gn,extractSidePanelProfiles:()=>Jr,normalizeFundUrl:()=>lt,normalizeProfileUrl:()=>Ee,scanRelatedBlocks:()=>Wn});function Ee(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function lt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Wn(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=a=>(a||"").replace(/\s+/g," ").trim(),r=a=>{let u=String(a||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},l=a=>o(a).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),s=a=>{let u=a,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||a.parentElement},c=[],i=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let a of i){let u=o(a.textContent).toLowerCase();if(!u)continue;let f=e.find(([p])=>u.includes(p));if(!f)continue;let d=f[1],m=s(a);if(!m)continue;let h=0,w=new Set,g=/[·•]\s*(1st|2nd|3rd)\b/i;for(let p of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let v=p.href||p.getAttribute("href")||"",C=r(v);if(!C||w.has(C))continue;let y="",A="",R=p,D=null;for(let _=0;_<8&&R.parentElement;_++)if(R=R.parentElement,(R.innerText||"").trim().length>15&&R.querySelectorAll('a[href*="/in/"]').length<=2){D=R;break}if(D){let _=(D.innerText||"").split(`
|
|
241
|
+
`).map(o).filter(Boolean),b=_.findIndex(T=>g.test(T));b>=0&&(y=o(_[b].split(/[·•]/)[0]).replace(/^View\s+/i,""),!y&&b>0&&(y=o(_[b-1]).replace(/^View\s+/i,"")),A=_.slice(b+1).filter(M=>!g.test(M)&&!/^view\b/i.test(M)&&!/mutual connection/i.test(M)&&/[a-z]/i.test(M)&&M.length>2)[0]||"")}if(!y){let _=p.querySelector('span[aria-hidden="true"]'),b=o(_?_.textContent:p.getAttribute("aria-label")||p.textContent);if(y=l(b),y){let T=b.match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i);T&&(A=o(T[1]))}}y&&(w.add(C),c.push({href:v,name:y,title:A,block:d,rank:h++}))}}return c}function Gn(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Ee(t.seedUrl||""),r=new Map,l={};for(let s of e||[]){let c=Ee(s.href);c&&(o&&c===o||(l[s.block]=l[s.block]||0,!(l[s.block]>=n)&&(r.has(c)||(l[s.block]++,r.set(c,{url:c,name:s.name,title:s.title||null,block:s.block,rank:s.rank})))))}return Array.from(r.values())}async function Jr(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(Wn,Vn)}catch{return[]}return Gn(n,t)}var Vn,It=ee(()=>{Vn=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"],["explore premium profiles","explore_premium"]]});var eo={};te(eo,{getJobDecision:()=>Kr,getLastVisit:()=>os,getScoutStats:()=>rs,loadCompanies:()=>Nt,loadDiscoveredPeople:()=>Ye,loadJobDecisions:()=>jt,loadScoutedJobs:()=>Ot,loadVisitLog:()=>ut,recordCompany:()=>es,recordDiscoveredEdge:()=>Xr,recordDiscoveredEdges:()=>Zr,recordVisit:()=>ns,resetCaches:()=>Tt,saveCompany:()=>ts,saveDiscoveredPerson:()=>zr,saveScoutedJob:()=>Gr,setJobDecision:()=>Yr});import"dotenv/config";import*as W from"fs";import*as H from"path";import{fileURLToPath as Hr}from"url";function pe(){W.existsSync(Se)||W.mkdirSync(Se,{recursive:!0})}function he(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";W.writeFileSync(o,n);for(let r=0;r<3;r++)try{W.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw l}}function Ge(e){try{if(W.existsSync(e))return JSON.parse(W.readFileSync(e,"utf-8"))}catch{}return null}function Tt(){Je=null,He=null,Ve=null,We=null,be=null}function Ot(){return Je||(Je=Ge(Kn)||{},Je)}function Gr(e,t){if(!e)return;pe();let n=Ot(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[r,l]of Object.entries(t))l!=null&&(n[e][r]=l);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{he(Kn,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function jt(){return He||(He=Ge(Qn)||{},He)}function Yr(e,t,n={}){if(!e||!t)return;pe();let o=jt(),r=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=r,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:r,updatedAt:r,reason:n.reason||null,score:n.score??null,source:n.source||null};try{he(Qn,o)}catch(l){console.error(`[!] Failed to save job-decisions.json: ${l.message}`)}}function Kr(e){return jt()[e]||null}function Ye(){return Ve||(Ve=Ge(ct)||{},Ve)}function Ie(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Xn(e,t){let n=Ee(t)||t;if(e[n])return n;let o=Ie(t);if(!o)return n;let r=null;for(let[l,s]of Object.entries(e)){if(Ie(s&&(s.canonicalUrl||s.profileUrl)||l)===o)return l;!r&&s&&Array.isArray(s.aliases)&&s.aliases.includes(o)&&(r=l)}return r||n}function zr(e,t){if(!e)return;pe();let n=Ye(),o=new Date().toISOString().slice(0,10),r=Xn(n,e),l=Ie(e);if(n[r]){let s=n[r];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),l&&Ie(s.canonicalUrl||s.profileUrl||r)!==l&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(l)||s.aliases.push(l)),s.lastSeen=o,s.seenCount=(s.seenCount||1)+1}else n[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{he(ct,n)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Qr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function Zn(e,t,n={},o){if(!t)return;let r=Ie(t);t=Xn(e,t);let l=n.seedUrl?{...n,seedUrl:Ee(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:i}=Qr(l,o),a=e[t];a||(a=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,title:n.title||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:s,firstSeen:s,lastSeen:s}),n.name&&(a.name=n.name),n.title&&(!a.title||/^[·•\s]*(1st|2nd|3rd)\b/i.test(a.title))&&(a.title=n.title),n.location&&(a.location=a.location||n.location),n.company&&(a.company=n.company),n.companyUrl&&(a.companyUrl=a.companyUrl||n.companyUrl),n.isConnected!=null&&(a.isConnected=n.isConnected),n.connectionsCount!=null&&(a.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(a.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(a.connectGate=n.connectGate),n.note&&!a.note&&(a.note=n.note),n.whyUseful&&!a.whyUseful&&(a.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(a.extra={...a.extra||{},...n.extra}),Array.isArray(a.sources)||(a.sources=[]);let u=a.sources.find(i);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):a.sources.push(c),Array.isArray(a.categories)||(a.categories=[]),Array.isArray(a.sectors)||(a.sectors=[]),Array.isArray(a.aliases)||(a.aliases=[]),Array.isArray(a.graphRefs)||(a.graphRefs=[]),Dt(a.categories,n.category),at(a.categories,n.categories),at(a.sectors,n.sectors),at(a.aliases,n.aliases),r&&Ie(a.canonicalUrl||t)!==r&&Dt(a.aliases,r),at(a.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(a.affiliations)||(a.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||a.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||a.affiliations.push(f)}a.lastSeen=s,a.seenCount=(a.seenCount||0)+1}function Xr(e,t={}){if(!e)return;pe();let n=Ye();Zn(n,e,t,new Date().toISOString());try{he(ct,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Zr(e){if(!Array.isArray(e)||e.length===0)return;pe();let t=Ye(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(Zn(t,r.url,r,n),o++);if(o)try{he(ct,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function es(e={}){if(!e||!e.name)return;pe();let t=e.key||lt(e.website)||lt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=Nt(),o=new Date().toISOString().slice(0,10),r=(i,a)=>{a&&Array.isArray(i)&&!i.includes(a)&&i.push(a)},l=(i,a)=>{if(Array.isArray(a))for(let u of a)r(i,u)},s=n[t];s||(s=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(s.name=e.name),e.website&&(s.website=s.website||e.website),e.linkedinUrl&&(s.linkedinUrl=s.linkedinUrl||e.linkedinUrl);for(let i of["size","check","stage","location","industries","about"])e[i]&&!s[i]&&(s[i]=e[i]);e.note&&!s.note&&(s.note=e.note),e.whyUseful&&!s.whyUseful&&(s.whyUseful=e.whyUseful),e.fitScore!=null&&(s.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(s.extra={...s.extra||{},...e.extra});for(let i of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(s[i])||(s[i]=[]),l(s[i],e[i]);Array.isArray(s.people)||(s.people=[]);let c=i=>{if(!i||!i.url)return;let a=s.people.find(u=>u.url===i.url&&(u.role||null)===(i.role||null));a?i.current!=null&&(a.current=i.current):s.people.push({url:i.url,name:i.name||null,role:i.role||null,current:i.current??null,from:i.from??null,to:i.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(i=>c({url:i.url,name:i.name,role:"Partner",current:!0})),Array.isArray(s.portfolio)||(s.portfolio=[]);for(let i of e.portfolio||[]){let a=i&&(i.key||i.name);a&&!s.portfolio.some(u=>(u.key||u.name)===a)&&s.portfolio.push(i)}s.lastSeen=o,s.seenCount=(s.seenCount||0)+1;try{he(Rt,n)}catch(i){console.error(`[!] Failed to save companies.json: ${i.message}`)}return t}function Nt(){return We||(We=Ge(Rt)||{},We)}function ts(e,t){if(!e)return;pe();let n=Nt(),o=new Date().toISOString().slice(0,10);if(n[e]){let r=n[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=o,r.jobCount=r.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{he(Rt,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function ut(){return be||(be=Ge(zn)||{visits:[]},Array.isArray(be.visits)||(be.visits=[]),be)}function ns(e,t={}){if(!e)return;pe();let n=ut();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(r=>new Date(r.date).getTime()>o);try{he(zn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function os(e){let t=ut();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function rs(){let e=Ot(),t=Ye(),n=Object.values(e),o=Object.values(t),r={};for(let d of n)d.company&&(r[d.company]=(r[d.company]||0)+1);let l=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),s={};for(let d of n)for(let m of d.techStack||[])s[m]=(s[m]||0)+1;let c=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),i=ut(),a=new Date().toISOString().slice(0,10),u=i.visits.filter(d=>d.date.startsWith(a)).length,f=new Set(i.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:l,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var Vr,Wr,Se,Kn,ct,zn,Rt,Qn,Je,He,Ve,Dt,at,We,be,Pt=ee(()=>{It();Vr=Hr(import.meta.url),Wr=H.dirname(H.dirname(Vr)),Se=process.env.DATA_DIR?H.resolve(process.env.DATA_DIR,"market-research"):H.join(Wr,"market-research"),Kn=H.join(Se,"scouted-jobs.json"),ct=H.join(Se,"discovered-people.json"),zn=H.join(Se,"visit-log.json"),Rt=H.join(Se,"companies.json"),Qn=H.join(Se,"job-decisions.json");Je=null;He=null;Ve=null;Dt=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},at=(e,t)=>{if(Array.isArray(t))for(let n of t)Dt(e,n)};We=null;be=null});var fo={};te(fo,{computeEngagement:()=>Lt,detectCategory:()=>oo,detectCategoryFromTitle:()=>ft,determineAction:()=>co,determineLastMessageBy:()=>so,determineSituation:()=>ro,enrichConversation:()=>ss,enrichPerson:()=>fs,enrichPersonContext:()=>uo,extractAutoTags:()=>lo,generateSummary:()=>io,normPreview:()=>Ft});function ss(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(i=>!kt.has(i.status)),l=ls(t,e.profileUrl,n),s=so(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let i=oo(r,t,l);i&&(e.category=i,e.categorySource=e.categorySource||"message_content")}if(e.situation=ro(r,s,t),r.length>0){let i=r[r.length-1];e.lastMessageTime=i.time}if(r.length>0&&!e.initiatedBy){let i=r[0];i.sender===me?e.initiatedBy="us":i.sender!=="Unknown"&&i.sender!==""&&(e.initiatedBy="them")}e.engagement=Lt(r,t),e.personContext=uo(l),e.summary=io(e,t,l),e.autoTags=lo(e,t,l);let c=co(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=is(e),e}function oo(e,t,n){if(!e||e.length===0)return n?.title?ft(n.title):null;let o=e.filter(r=>r.sender!==me&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,l]of Object.entries(no))if(l.theirMessages){for(let s of l.theirMessages)if(s.test(o))return r}if(n?.title){let r=ft(n.title);if(r)return r}return null}function ft(e){if(!e)return null;for(let[t,n]of Object.entries(no))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function ro(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return to.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let r=[...e].reverse().find(l=>l.sender!==me&&l.sender!=="Unknown");return to.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function so(e,t){if(!e||e.length===0)return"them";let n=[...e].map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,l)=>l.t-r.t).map(r=>r.m),o=n.length>0?n:[...e].reverse();for(let r of o){let l=r.sender;if(l===me)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}function io(e,t,n){let o=e.messages||[];if(o.length===0)return null;let r=[],l=e.category,s=n?.title,c=n?.company,i=n?.location;l==="recruiter"&&c?r.push(`Recruiter from ${c}`):l==="hiring_manager"&&c?r.push(`Hiring manager at ${c}`):l==="founder"&&c?r.push(`Founder of ${c}`):l&&s?r.push(`${Mt(l)}: ${De(s,40)}`):s?r.push(De(s,50)):r.push(t.split(" ")[0]);let a=o.filter(h=>h.sender!==me&&h.sender!=="Unknown").map(h=>h.text).join(" "),u=as(a),f=cs(a),d=us(a),m=[];return u&&m.push(u),d&&d!==i&&m.push(d),f&&m.push(f),m.length>0&&r.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?r.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?r.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?r.push("needs reply"):e.conversationStatus==="awaiting_reply"&&r.push("waiting on them"),r.join(". ").replace(/\.\./g,".")}function lo(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!kt.has(a.status)),l=r.map(a=>a.text).join(" "),s=r.filter(a=>a.sender!==me&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=ao(s,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(l)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(l)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(l)&&o.push("remote"),/\b(hybrid)\b/i.test(l)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(l)&&o.push("onsite"),/\b(java)\b/i.test(l)&&!/javascript/i.test(l)&&o.push("java"),/\b(python)\b/i.test(l)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(l)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(l)&&o.push("backend"),/\b(full.?stack)\b/i.test(l)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(l)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(l)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(l)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(l)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(l)&&o.push("has-salary");let i=e.engagement||Lt(r,t);return i.messageCount>=6&&o.push("active-thread"),i.theirCount===0&&i.ourCount>0&&o.push("no-response"),i.ourCount===0&&i.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(a=>St.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function ao(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],r=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],l=(e+" "+(t||"")).toLowerCase();for(let s of o)l.includes(s)&&n.push(s.replace(/\s+/g,"-"));for(let[s,c]of r)l.includes(s)&&n.push(c);return n}function co(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Ft(e.lastMessagePreview)===Ft(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(l=>St.has(l.status));return r?r.status===re.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${Mt(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function Lt(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,r=0,l=!1,s=!1,c=e.map(i=>i.text).join(" ");for(let i of e)i.sender===me?n++:i.sender==="Unknown"||i.sender===""?r++:o++;return l=/\b(job|role|position|opening)\b/i.test(c),s=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:r,hasJob:l,hasSalary:s}}function uo(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function is(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function ls(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let r=_e(n,t,e);if(n[r])return n[r]}if(!e)return null;let o=Object.values(n).filter(r=>r.name===e);return o.length===1?o[0]:null}function Ft(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Mt(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function De(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function as(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function cs(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function us(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function fs(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=ft(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}ds(e),e.personSummary=ms(e),e.personAutoTags=ps(e);let n=hs(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=gs(e)),e}function ds(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function ms(e){let t=[],n=e.category,o=e.title,r=e.company,l=e.location;if(n==="recruiter"&&r?t.push(`Recruiter at ${r}`):n==="hiring_manager"&&r?t.push(`Hiring manager at ${r}`):n==="founder"&&r?t.push(`Founder of ${r}`):o&&r?t.push(`${De(o,40)} at ${De(r,30)}`):o?t.push(De(o,50)):e.name&&t.push(e.name.split(" ")[0]),l&&t.push(l),e.connectionDate){let s=new Date(e.connectionDate);if(!isNaN(s)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[s.getMonth()]} ${s.getDate()}`)}}if(e.jobCount>0){let s=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(s+=` (last: ${De(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(s+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}s+=")"}t.push(s)}return t.join(". ").replace(/\.\./g,".")||null}function ps(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=ao("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function hs(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${Mt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function gs(e){let t=e.category;if(!t)return null;let n=ys(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ys(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var no,to,mo=ee(async()=>{await vt();await it();no={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]}};to=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var ho={};te(ho,{DEFAULT_PROFILE_INTERESTS:()=>po,computeFit:()=>Ss,detectSectors:()=>bs});function bs(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(ws))r.some(l=>l.test(t))&&n.push(o);return n}function Ss(e,t=po){if(!Array.isArray(e)||e.length===0)return 0;let n=l=>typeof l=="number"&&Number.isFinite(l)?l:0,o=Math.max(1,...Object.values(t||{}).map(n)),r=0;for(let l of e){let s=n(t&&t[l]);s>r&&(r=s)}return Math.min(1,r/o)}var ws,po,go=ee(()=>{ws={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};po={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Ei from"puppeteer";import"dotenv/config";import*as V from"fs";import*as de from"path";import{fileURLToPath as sr}from"url";import"dotenv/config";import{createGraphClient as Xo,resolveToken as Zo}from"@ilivemylife/graph-sdk";import{config as er}from"dotenv";er();var cn=Zo()||process.env.TOKEN;cn||(console.error(`
|
|
241
242
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
242
243
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
243
244
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
244
|
-
`),process.exit(1));var
|
|
245
|
-
`)}async function
|
|
246
|
-
\u2717 ${e}${f} failed: ${l.message||l}`)}let u=Date.now()-s.startTime,d=!l&&c.stoppedReason?String(c.stoppedReason):null;try{sr(s,l?"error":d?"partial":"success",{...c,summaryLines:a,__deferReport:!0},l?l.message||String(l):null)}catch(f){console.error(`[runLog] endRun failed: ${f.message}`)}if(a.length>0&&process.env.NODE_RUN_REPORTS){let f=l?"error":d?"stopped":c.dailyLimitHit?"quota-reached":"done";try{await mt({scriptName:s.script,mode:s.mode,status:f,summaryLines:a,error:l?l.message||String(l):null,stoppedReason:d,duration:u})}catch(m){console.error(`[runLog] report post failed: ${m.message}`)}}if(l&&i)throw l;return c}Ze();Ze();await ot();async function po(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: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function mo(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function gs(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:s=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=n;try{await Ce(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await S(1500),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await po(e,t));let u=0;for(let w=0;w<2;w++){let x=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(R=>window.scrollTo(0,R),x*D/6),await S(900);let T=await e.evaluate(()=>document.body.scrollHeight);if(T===u)break;u=T}await S(800);let d=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(d=w.split("?")[0].replace(/\/+$/,""))}catch{}let f=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),x=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"]),T=C=>{let _=(C||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},D={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:[]},R=document.querySelector("main");if(!R)return D;let k=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],E=Array.from(R.querySelectorAll("h2")),ee=k.find(C=>{let _=C.textContent&&C.textContent.trim(),$=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!w.has($)&&!x.has($)}),z=ee?ee.textContent.trim():null,F=ee?ee.parentElement:null;for(;F&&F!==R&&!Array.from(F.children).filter(_=>_.tagName==="P").some(_=>{let $=_.textContent&&_.textContent.trim();return $&&$.length>5&&!T($)});)F=F.parentElement;let ce=null,Re=null,Te=null,Oe=null;if(F&&F!==R){let C=Array.from(F.children).filter($=>$.tagName==="P").filter($=>{let ue=$.textContent&&$.textContent.trim();return ue&&ue.length>5&&!T(ue)});if(C[0]&&(ce=C[0].textContent.trim()),C[1]){let $=C[1].textContent.trim().split(/\s*[·•]\s*/);Re=$[0]||null,$.length>1&&(Te=$.slice(1).join(" \xB7 "))}let _=Array.from(F.children).filter($=>$.tagName==="DIV");for(let $=_.length-1;$>=0;$--){let ue=_[$].textContent&&_[$].textContent.trim();if(ue&&!(z&&ue.startsWith(z))&&(Oe=ue.split(/[·•]/)[0].trim(),Oe))break}}let ze=null;if(F){let C=F.querySelectorAll("p, span, div");for(let _ of C){let $=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if($==="1st"||$==="2nd"||$==="3rd"){ze=$;break}}}let O=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),P=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),M=P&&P.src||null,N=R.textContent||"",Q=null,zt=N.match(/(\d+\+?)\s+connections\b/i);zt&&(Q=zt[1]+" connections");let Qe=null,Qt=N.match(/(\d+)\s+mutual connection/i),Xt=N.match(/and\s+(\d+)\s+other mutual/i),qo=N.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Qt?Qe=parseInt(Qt[1],10):Xt?Qe=2+parseInt(Xt[1],10):qo&&(Qe=2);let Zt=null,en=null,tn=E.find(C=>C.textContent&&C.textContent.trim()==="About");if(tn){let C=tn.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let _=(C.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let $=_.match(/Top skills\s*(.+?)$/i);if($){let dt=$[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Vo=>Vo.trim()).filter(Boolean);dt.length>0&&dt.length<10&&(en=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(),Zt=_||null}}let nn=null,on=E.find(C=>C.textContent&&C.textContent.trim()==="Activity");if(on){let C=on.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let _=(C.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(nn=parseInt(_[1].replace(/,/g,""),10))}}let Bo=[...new Set(E.map(C=>(C.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(C=>C&&C.length>1&&C.length<60&&C!==z).filter(C=>w.has(C)))],Ne=document.body.textContent||"",Jo=/#OpenToWork\b/i.test(Ne)||/\bOpen to work\b/.test(Ne),Ho=/#Hiring\b/i.test(Ne)||/\bI'?m hiring\b/i.test(Ne)||/\bWe are hiring\b/i.test(Ne);return{name:z,title:ce,location:Oe,currentCompany:Re,currentSchool:Te,connectionDegree:ze,hasVerifiedBadge:O,photoUrl:M,connectionsLevel:Q,mutualConnectionsCount:Qe,followers:nn,openToWork:Jo,hiring:Ho,about:Zt,topSkills:en,availableSections:Bo}});console.log(`Viewed: ${f.name} - ${f.title}`);let m=null,h=null,y=null,g=null,p=null,v=null;if(o||r||i||s||c||l){let w=await Promise.resolve().then(()=>(Un(),Mn));o&&(m=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(h=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),i&&(y=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),s&&(g=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),c&&(p=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${p.length} entries`)),l&&(v=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...f,profileUrl:t,resolvedUrl:d,...m!==null&&{experience:m},...h!==null&&{featured:h},...y!==null&&{education:y},...g!==null&&{skillsFull:g},...p!==null&&{recommendations:p},...v!==null&&{certifications:v}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Ie(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=d=>d&&!d.closest(r),s=d=>Array.from(document.querySelectorAll(d)).filter(i),c=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,a=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(d=>d.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!a};return c.length>0?{status:"pending",debug:u}:l&&!a?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await S(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function Lt(e){let t=null,n=await e.evaluate(()=>{let a=document.querySelector("h1")?.textContent?.trim();if(a&&!a.includes("notification"))return a;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(a=u.textContent?.trim(),a&&!a.includes("notification")))return a;let d=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(d)return d.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let a=await e.evaluate(()=>{let d=document.querySelectorAll('a[href*="custom-invite"]');return{count:d.length,labels:Array.from(d).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});a.count>0&&console.log(` S0: ${a.count} custom-invite links: ${JSON.stringify(a.labels)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),m=d.toLowerCase().split(" ")[0],h='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let g=y.getBoundingClientRect();if(g.width===0||g.height===0||y.closest(h))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(m))return y}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let a=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${a}"`);let u=await e.evaluate(f=>{let m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),h=document.querySelectorAll("button[aria-label]");return Array.from(h).filter(g=>{let p=g.getAttribute("aria-label")||"";return(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let m=document.querySelectorAll("button[aria-label]"),h='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of m){if(g.closest(h))continue;let p=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(p)&&(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&y.test(p))return g}return null},a);let d=t?.asElement?.()||null;if(d||await t?.dispose?.().catch(()=>{}),d)return console.log(" Found: button matching profile name"),{button:d,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 a=await e.evaluate(d=>(d.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),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 a of o){let u=await e.evaluate((d,f)=>{let m=d.className.includes("muted"),h=d.className.includes("sticky-header")||d.className.includes("sticky"),y=d.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(d.getAttribute("aria-label")||"").toLowerCase(),p=g.includes("invite"),v=f?g.includes(f):!0;return{isMuted:m,isStickyHeader:h,inRecommendations:y,hasInvite:p,matchesName:v,ariaLabel:g}},a,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=a;break}}for(let a of o)a!==i&&await a.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 s=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(d=>{let f=d.getBoundingClientRect(),m=f.width>0&&f.height>0,h=d.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:h,top:f.top}},a);if(u.isVisible&&!u.isInStickyHeader){s=a,console.log(" Found More button by ID pattern (main)");break}}for(let a of c)a!==s&&await a.dispose().catch(()=>{});if(!s&&c.length>0&&(s=c[c.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let a=await e.evaluateHandle(()=>{let d=Array.from(document.querySelectorAll("button, a")).find(m=>{let h=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",g=m.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:h==="Follow"||h==="Message"||h==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!d)return null;let f=d.parentElement;for(let m=0;m<8&&f;m++){for(let h of f.querySelectorAll("button"))if(h.innerText?.trim()==="More"&&h!==d)return h;f=f.parentElement}return null});s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(f=>f.scrollIntoView({behavior:"smooth",block:"center"}),s),await S(500),await e.evaluate(f=>f.click(),s),await S(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let f=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let h of m){let y=h.querySelector('a[href*="custom-invite"]');if(y)return y;for(let g of h.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=f?.asElement?.()||null,u||await f?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let d=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let h of f)for(let y of h.querySelectorAll('[role="menuitem"], a, div')){let g=y.innerText?.trim();g&&g.length<40&&m.push(g)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(d)}`),await e.keyboard.press("Escape"),d.some(f=>/remove (your )?connection/i.test(f)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(a){console.log(" More dropdown click failed:",a.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(a=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',d=(a||"").split(" ")[0].toLowerCase();for(let f of document.querySelectorAll("button[aria-label]")){if(f.closest(u))continue;let m=(f.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let h=f.getBoundingClientRect();if(!(h.width===0||h.height===0)){if(m.includes("invite")){if(d&&m.includes(d))return f;continue}if(m==="connect")return f}}return null},n||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function ys(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await S(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",s=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"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 S(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await S(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await S(3e3)):(await e.evaluate(u=>u.click(),t),await S(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function ws(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await S(1500);let n=await Lt(e);if(n){await e.evaluate(r=>r.click(),n),await S(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await De(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function De(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(s=>{let c=l=>!!(l&&l.querySelector(s));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),i=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let c=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,n);return s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(c=>c.click())}catch{}if(await S(3e3),await r())return!1;if(await o())return!0;if(s===0){let c=await i();if(!c)return await o();t=c,await S(600)}}return await o()}async function bs(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=At();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let s=await Ss(e,t,n);return s.connectionSent&&!i&&Ln(t,o),s}async function Ss(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:s=!0,excludeLocations:c=[]}=n,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
247
|
-
--- Connecting: ${a} ---`),c.length>0){let p=ie()[t]?.location;if(mo(p,c))return console.log(` \u26A0 Excluded location (stored): ${p}`),l.reason="excluded_location",l.profileInfo={location:p},l}try{await Ce(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(p){if(p.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;throw p}if(await S(2e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await po(e,t),await S(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:p,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(_t(),Hn)),{recordDiscoveredEdges:A}=await Promise.resolve().then(()=>(Ot(),zn)),{detectCategoryFromTitle:w}=await ao().then(()=>lo),{detectSectors:x}=await Promise.resolve().then(()=>(fo(),uo)),T=v(t)||t,D=await p(e,{seedUrl:T}),R=D.map(k=>{let E=k.headline?w(k.headline):null;return{url:k.url,seedUrl:T,block:k.block,rank:k.rank,name:k.name,headline:k.headline,categories:E?[E]:[],sectors:x(k.headline||"")}});A(R),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(p){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${p.message}`)}l.profileInfo=await e.evaluate(()=>{let p=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"]),v=O=>{let P=(O||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},A={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},w=document.querySelector("main");if(!w)return A;let x=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],T=Array.from(w.querySelectorAll("h2")),D=x.find(O=>{let P=O.textContent&&O.textContent.trim();return P&&P.length>1&&P.length<100&&!p.has(P)&&P!=="0 notifications"}),R=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==w&&!Array.from(k.children).filter(M=>M.tagName==="P").some(M=>{let N=M.textContent&&M.textContent.trim();return N&&N.length>5&&!v(N)});)k=k.parentElement;let E=null,ee=null,z=null;if(k&&k!==w){let O=Array.from(k.children),P=O.filter(N=>N.tagName==="P").filter(N=>{let Q=N.textContent&&N.textContent.trim();return Q&&Q.length>5&&!v(Q)});P[0]&&(E=P[0].textContent.trim()),P[1]&&(ee=P[1].textContent.trim());let M=O.filter(N=>N.tagName==="DIV");for(let N=M.length-1;N>=0;N--){let Q=M[N].textContent&&M[N].textContent.trim();if(Q&&!(R&&Q.startsWith(R))&&(z=Q.split(/[·•]/)[0].trim(),z))break}}let F=null;if(k){let O=k.querySelectorAll("p, span, div");for(let P of O){let M=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){F=M;break}}}let ce=null,Re=T.find(O=>O.textContent&&O.textContent.trim()==="About");if(Re){let O=Re.parentElement;for(;O&&O.tagName!=="SECTION";)O=O.parentElement;O&&(ce=(O.textContent||"").trim().replace(/^About\s*/,"").trim()||null,ce&&(ce=ce.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Te=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Oe=Te&&Te.src||null,ze=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:E,location:z,about:ce,company:ee,connectionDegree:F,connectionsCount:null,mutualConnections:null,photoUrl:Oe,hasVerifiedBadge:ze}});try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(l.resolvedUrl=p.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let p=l.profileInfo?.location,v=ie()[t]?.location,A=p||v;if(mo(A,c))return console.log(` \u26A0 Excluded location (${p?"live":"stored"}): ${A}`),l.reason="excluded_location",l;!p&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ie(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await ge(e);let f=await Lt(e);if(f||await ge(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),f=await Lt(e)),f&&f.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!f){let p=await Ie(e,{detail:!0});return s&&(p.status==="connected"||p.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=f.method;let m=await ys(e,f.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3);let p=await Ie(e);if(p==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${p} \u2014 trying More dropdown...`),await ge(e),await S(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(w=>w.scrollIntoView({behavior:"smooth",block:"center"}),v),await S(500),await v.click().catch(()=>e.evaluate(w=>w.click(),v)),await S(2e3);let A=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(A){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),A),await S(3e3);let w=e.url();if(w.includes("/premium/")||w.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),l.reason="premium_required",l;if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await S(500),l.reason="premium_required",l}catch(A){return console.log(" More dropdown failed:",A.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of p){let A=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!A)continue;let w=(A.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||A.querySelector('input[type="email"], input[name="email"]'))return!0;let x=A.querySelector('button[aria-label="Send without a note"]');if(x&&(x.disabled||x.getAttribute("aria-disabled")==="true"||(x.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let p=await e.$('button[aria-label="Dismiss"]');if(p)try{await p.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await S(500),l.reason="email_required",l}let y=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!y&&!g){let p=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let A=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!A,sendWithout:!!w}});if(p.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));y=v?.asElement?.()||null,y||await v.dispose().catch(()=>{})}if(p.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=v?.asElement?.()||null,g||await v.dispose().catch(()=>{})}}if(r)if(y&&o){if(console.log(" Adding personalized note..."),await y.click(),await S(1500),await e.$("div.modal-upsell")){let A=await ws(e);return l.success=A,l.connectionSent=A,l.reason=A?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let A=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",A);await v.type(w,{delay:20}),await S(500);let x=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(x)return await De(e,x)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=w,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(g)return console.log(" Sending without note..."),await De(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(y&&!o){console.log(" No message provided, sending without note...");let p=await e.$('button[aria-label="Send without a note"]');if(p)return await De(e,p)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let p=g;if(p)return await De(e,p)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(f.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(4e3)),await ge(e),await S(500);let v=await e.$$('button[id*="profile-overflow-action"]'),A=null;for(let w of v){let x=await e.evaluate(T=>{let D=T.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},w);if(x.visible&&!x.inSticky){A=w;break}}!A&&v.length>0&&(A=v[v.length-1]);for(let w of v)w!==A&&await w.dispose().catch(()=>{});if(A)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),A),await S(500),await A.click().catch(()=>e.evaluate(x=>x.click(),A)),await S(2e3);let w=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(w){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(R=>R.click(),w),await S(3e3);let x=e.url();if(x.includes("/premium/")||x.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await Ie(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await Ie(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let D=await e.$('button[aria-label="Send without a note"]');if(D)return console.log(" Modal appeared via More dropdown, sending without note..."),await De(e,D)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(w){console.log(" More dropdown fallback failed:",w.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(a){console.error(` \u2717 Error: ${a.message}`),l.reason="error",l.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await S(1e3)}catch{l.fatal=!0}return l}}async function ho(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:s=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:l=null,excludeLocations:a=[],source:u="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
248
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${
|
|
245
|
+
`),process.exit(1));var un=Xo({token:cn});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`}var nr={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function or(e){let t=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(t)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(t)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(t)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(t)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(t)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function rr({scriptName:e,mode:t,status:n,summaryLines:o,error:r,stoppedReason:l,duration:s}){let c=n==="error"||n==="stopped"?n==="error"?"\u2717":"\u26A0":n==="quota-reached"?"\u26A0":"\u2713",i=n==="error"?"stopped early":n==="stopped"?`stopped \u2014 ${l||"did not finish"}`:n==="quota-reached"?"daily limit reached":"done",a=nr[e]||e,u=t&&t!=="default"?` \xB7 ${t}`:"",f=new Date().toISOString().slice(0,16).replace("T"," "),d=s?` \xB7 ${tr(s)}`:"",m=[];m.push(`## ${c} ${a} \u2014 ${i}`),m.push(`_${f}${u}${d}_`),m.push("");for(let h of o)m.push(`- ${h}`);if(n==="error"){m.push(""),m.push(`**What happened:** ${or(r)}`);let h=String(r||"").replace(/\s+/g," ").trim();h&&m.push(`_Technical detail: ${h.slice(0,140)}_`)}return m.join(`
|
|
246
|
+
`)}async function gt({scriptName:e,mode:t,status:n,summaryLines:o,error:r,stoppedReason:l,duration:s}){let c=process.env.NODE_RUN_REPORTS;if(!c||!Array.isArray(o)||o.length===0)return;let i=rr({scriptName:e,mode:t,status:n,summaryLines:o,error:r,stoppedReason:l,duration:s});try{await un.addMessage(c,i)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var ir=sr(import.meta.url),lr=de.dirname(de.dirname(ir)),yt=process.env.DATA_DIR?de.resolve(process.env.DATA_DIR,"collected-profiles"):de.join(lr,"collected-profiles"),wt=de.join(yt,"run-log.json");function ar(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";V.writeFileSync(o,n);for(let r=0;r<3;r++)try{V.renameSync(o,e);return}catch(l){if(r<2&&(l.code==="EPERM"||l.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw l}}function fn(){try{if(!V.existsSync(wt))return{runs:[]};let e=JSON.parse(V.readFileSync(wt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function dn(e){V.existsSync(yt)||V.mkdirSync(yt,{recursive:!0});try{ar(wt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function cr(e,t="default"){let n=fn();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.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 l=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>l),dn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ur(e,t,n=null,o=null){if(!e)return;let r=null;try{let c=fn(),i=c.runs[e.runIndex];if(i&&i.status==="running"&&i.script===e.script)i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=o,r=i.duration;else{let a=c.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration)}dn(c)}catch(c){console.error(`[runLog] Failed to end run: ${c.message}`)}let l=n&&Array.isArray(n.summaryLines)?n.summaryLines:null,s=n&&n.__deferReport===!0;if(l&&l.length>0&&process.env.NODE_RUN_REPORTS&&!s){let c=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";gt({scriptName:e.script,mode:e.mode,status:c,summaryLines:l,error:o,duration:r??Date.now()-e.startTime}).catch(i=>console.error(`[runLog] postRunReport failed: ${i.message}`))}}async function mn(e,t,n,o,r={}){let{rethrow:l=!0}=r,s=cr(e,t),c={},i=null;try{await n(c)}catch(d){i=d}let a=[];try{let d=o?o(c):[];a=(Array.isArray(d)?d:[]).filter(m=>typeof m=="string"&&m.trim())}catch(d){console.error(`[runLog] summarize threw (report still sent): ${d.message}`)}if(a.length===0&&i&&(a=["(crashed before any progress was recorded)"]),i){let d=t&&t!=="default"?` (${t})`:"";console.error(`
|
|
247
|
+
\u2717 ${e}${d} failed: ${i.message||i}`)}let u=Date.now()-s.startTime,f=!i&&c.stoppedReason?String(c.stoppedReason):null;try{ur(s,i?"error":f?"partial":"success",{...c,summaryLines:a,__deferReport:!0},i?i.message||String(i):null)}catch(d){console.error(`[runLog] endRun failed: ${d.message}`)}if(a.length>0&&process.env.NODE_RUN_REPORTS){let d=i?"error":f?"stopped":c.dailyLimitHit?"quota-reached":"done";try{await gt({scriptName:s.script,mode:s.mode,status:d,summaryLines:a,error:i?i.message||String(i):null,stoppedReason:f,duration:u})}catch(m){console.error(`[runLog] report post failed: ${m.message}`)}}if(i&&l)throw i;return c}nt();nt();await it();async function wo(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: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function yo(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function ks(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:l=!1,extractSkills:s=!1,extractRecommendations:c=!1,extractCertifications:i=!1}=n;try{await Ae(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await k(1500),await ye(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await wo(e,t));let u=0;for(let y=0;y<2;y++){let A=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(_=>window.scrollTo(0,_),A*D/6),await k(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await k(800);let f=null;try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(f=y.split("?")[0].replace(/\/+$/,""))}catch{}let d=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","Licenses & certifications","Courses","Test scores","Organizations"]),A=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"]),R=x=>{let $=(x||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},D={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:[]},_=document.querySelector("main");if(!_)return D;let b=[...Array.from(_.querySelectorAll("h1")),...Array.from(_.querySelectorAll("h2"))],T=Array.from(_.querySelectorAll("h2")),M=b.find(x=>{let $=x.textContent&&x.textContent.trim(),E=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!y.has(E)&&!A.has(E)}),X=M?M.textContent.trim():null,L=M?M.parentElement:null;for(;L&&L!==_&&!Array.from(L.children).filter($=>$.tagName==="P").some($=>{let E=$.textContent&&$.textContent.trim();return E&&E.length>5&&!R(E)});)L=L.parentElement;let ue=null,Oe=null,je=null,Ne=null;if(L&&L!==_){let x=Array.from(L.children).filter(E=>E.tagName==="P").filter(E=>{let fe=E.textContent&&E.textContent.trim();return fe&&fe.length>5&&!R(fe)});if(x[0]&&(ue=x[0].textContent.trim()),x[1]){let E=x[1].textContent.trim().split(/\s*[·•]\s*/);Oe=E[0]||null,E.length>1&&(je=E.slice(1).join(" \xB7 "))}let $=Array.from(L.children).filter(E=>E.tagName==="DIV");for(let E=$.length-1;E>=0;E--){let fe=$[E].textContent&&$[E].textContent.trim();if(fe&&!(X&&fe.startsWith(X))&&(Ne=fe.split(/[·•]/)[0].trim(),Ne))break}}let Ze=null;if(L){let x=L.querySelectorAll("p, span, div");for(let $ of x){let E=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ze=E;break}}}let O=!!_.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),P=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=P&&P.src||null,j=_.textContent||"",Z=null,en=j.match(/(\d+\+?)\s+connections\b/i);en&&(Z=en[1]+" connections");let et=null,tn=j.match(/(\d+)\s+mutual connection/i),nn=j.match(/and\s+(\d+)\s+other mutual/i),Wo=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);tn?et=parseInt(tn[1],10):nn?et=2+parseInt(nn[1],10):Wo&&(et=2);let on=null,rn=null,sn=T.find(x=>x.textContent&&x.textContent.trim()==="About");if(sn){let x=sn.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let $=(x.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let E=$.match(/Top skills\s*(.+?)$/i);if(E){let ht=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(zo=>zo.trim()).filter(Boolean);ht.length>0&&ht.length<10&&(rn=ht)}$=$.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(),on=$||null}}let ln=null,an=T.find(x=>x.textContent&&x.textContent.trim()==="Activity");if(an){let x=an.parentElement;for(;x&&x.tagName!=="SECTION";)x=x.parentElement;if(x){let $=(x.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(ln=parseInt($[1].replace(/,/g,""),10))}}let Go=[...new Set(T.map(x=>(x.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(x=>x&&x.length>1&&x.length<60&&x!==X).filter(x=>y.has(x)))],Pe=document.body.textContent||"",Yo=/#OpenToWork\b/i.test(Pe)||/\bOpen to work\b/.test(Pe),Ko=/#Hiring\b/i.test(Pe)||/\bI'?m hiring\b/i.test(Pe)||/\bWe are hiring\b/i.test(Pe);return{name:X,title:ue,location:Ne,currentCompany:Oe,currentSchool:je,connectionDegree:Ze,hasVerifiedBadge:O,photoUrl:U,connectionsLevel:Z,mutualConnectionsCount:et,followers:ln,openToWork:Yo,hiring:Ko,about:on,topSkills:rn,availableSections:Go}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,h=null,w=null,g=null,p=null,v=null;if(o||r||l||s||c||i){let y=await Promise.resolve().then(()=>(Hn(),Jn));o&&(m=await y.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(h=await y.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),l&&(w=await y.extractEducationFromDetails(e,t),console.log(` + Education: ${w.length} entries`)),s&&(g=await y.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),c&&(p=await y.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${p.length} entries`)),i&&(v=await y.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...h!==null&&{featured:h},...w!==null&&{education:w},...g!==null&&{skillsFull:g},...p!==null&&{recommendations:p},...v!==null&&{certifications:v}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Re(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let r='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',l=f=>f&&!f.closest(r),s=f=>Array.from(document.querySelectorAll(f)).filter(l),c=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),i=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,a=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!i,hasConnectBtn:!!a};return c.length>0?{status:"pending",debug:u}:i&&!a?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await k(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function Ut(e){let t=null,n=await e.evaluate(()=>{let a=document.querySelector("h1")?.textContent?.trim();if(a&&!a.includes("notification"))return a;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(a=u.textContent?.trim(),a&&!a.includes("notification")))return a;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let a=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});a.count>0&&console.log(` S0: ${a.count} custom-invite links: ${JSON.stringify(a.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],h='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let w of d){let g=w.getBoundingClientRect();if(g.width===0||g.height===0||w.closest(h))continue;if((w.getAttribute("aria-label")||"").toLowerCase().includes(m))return w}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let a=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${a}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),h=document.querySelectorAll("button[aria-label]");return Array.from(h).filter(g=>{let p=g.getAttribute("aria-label")||"";return(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),h='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',w=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let g of m){if(g.closest(h))continue;let p=g.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(p)&&(p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&w.test(p))return g}return null},a);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,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 a=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),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():"",l=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),h=f.className.includes("sticky-header")||f.className.includes("sticky"),w=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),p=g.includes("invite"),v=d?g.includes(d):!0;return{isMuted:m,isStickyHeader:h,inRecommendations:w,hasInvite:p,matchesName:v,ariaLabel:g}},a,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}l=a;break}}for(let a of o)a!==l&&await a.dispose().catch(()=>{});if(l)return console.log(" Found: secondary button"),{button:l,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 s=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,h=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:h,top:d.top}},a);if(u.isVisible&&!u.isInStickyHeader){s=a,console.log(" Found More button by ID pattern (main)");break}}for(let a of c)a!==s&&await a.dispose().catch(()=>{});if(!s&&c.length>0&&(s=c[c.length-1],console.log(" Found More button by ID pattern (last)")),s||(s=await e.$('button[aria-label="More actions"]'),s&&console.log(" Found More button by aria-label")),!s){let a=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let h=m.innerText?.trim(),w=m.getAttribute("aria-label")||"",g=m.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:h==="Follow"||h==="Message"||h==="Connect"||w.includes("Follow")||w.includes("Message")||w.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let h of d.querySelectorAll("button"))if(h.innerText?.trim()==="More"&&h!==f)return h;d=d.parentElement}return null});s=a?.asElement?.()||null,s||await a?.dispose?.().catch(()=>{}),s&&console.log(" Found More button by text (near profile actions)")}if(s)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),s),await k(500),await e.evaluate(d=>d.click(),s),await k(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let h of m){let w=h.querySelector('a[href*="custom-invite"]');if(w)return w;for(let g of h.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let h of d)for(let w of h.querySelectorAll('[role="menuitem"], a, div')){let g=w.innerText?.trim();g&&g.length<40&&m.push(g)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(a){console.log(" More dropdown click failed:",a.message),await e.keyboard.press("Escape")}let i=await e.evaluateHandle(a=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(a||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let h=d.getBoundingClientRect();if(!(h.width===0||h.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=i?.asElement?.()||null,t||await i?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function vs(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),l=n.tag==="DIV",s=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(s))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(s.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!s.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await k(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await k(2e3),"premium_redirect"}else l?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let i=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(i?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function Cs(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 k(1500);let n=await Ut(e);if(n){await e.evaluate(r=>r.click(),n),await k(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Te(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Te(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(s=>{let c=i=>!!(i&&i.querySelector(s));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),r=()=>e.evaluate(()=>{for(let s of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(s.innerText||""))return!0;return!1}),l=async()=>{let s=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(s)return s;let c=await e.evaluateHandle(i=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(i)||null,n);return s=c?.asElement?.()||null,s||await c?.dispose?.().catch(()=>{}),s};for(let s=0;s<2;s++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await r())return!1;if(await o())return!0;if(s===0){let c=await l();if(!c)return await o();t=c,await k(600)}}return await o()}async function xs(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:l=!1}=n;if(!r){let c=_t();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let s=await As(e,t,n);return s.connectionSent&&!l&&qn(t,o),s}async function As(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:l=!0,skipIfConnected:s=!0,excludeLocations:c=[]}=n,i={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
248
|
+
--- Connecting: ${a} ---`),c.length>0){let p=le()[t]?.location;if(yo(p,c))return console.log(` \u26A0 Excluded location (stored): ${p}`),i.reason="excluded_location",i.profileInfo={location:p},i}try{await Ae(e,t,{readySelector:".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",label:"profile"})}catch(p){if(p.code==="SESSION_EXPIRED")return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),i.reason="session_expired",i.fatal=!0,i;throw p}if(await k(2e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await wo(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:p,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(It(),Yn)),{recordDiscoveredEdges:C}=await Promise.resolve().then(()=>(Pt(),eo)),{detectCategoryFromTitle:y}=await mo().then(()=>fo),{detectSectors:A}=await Promise.resolve().then(()=>(go(),ho)),R=v(t)||t,D=await p(e,{seedUrl:R}),_=D.map(b=>{let T=b.title?y(b.title):null;return{url:b.url,seedUrl:R,block:b.block,rank:b.rank,name:b.name,title:b.title,categories:T?[T]:[],sectors:A(b.title||"")}});C(_),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(p){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${p.message}`)}i.profileInfo=await e.evaluate(()=>{let p=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"]),v=O=>{let P=(O||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},C={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},y=document.querySelector("main");if(!y)return C;let A=[...Array.from(y.querySelectorAll("h1")),...Array.from(y.querySelectorAll("h2"))],R=Array.from(y.querySelectorAll("h2")),D=A.find(O=>{let P=O.textContent&&O.textContent.trim();return P&&P.length>1&&P.length<100&&!p.has(P)&&P!=="0 notifications"}),_=D?D.textContent.trim():null,b=D?D.parentElement:null;for(;b&&b!==y&&!Array.from(b.children).filter(U=>U.tagName==="P").some(U=>{let j=U.textContent&&U.textContent.trim();return j&&j.length>5&&!v(j)});)b=b.parentElement;let T=null,M=null,X=null;if(b&&b!==y){let O=Array.from(b.children),P=O.filter(j=>j.tagName==="P").filter(j=>{let Z=j.textContent&&j.textContent.trim();return Z&&Z.length>5&&!v(Z)});P[0]&&(T=P[0].textContent.trim()),P[1]&&(M=P[1].textContent.trim());let U=O.filter(j=>j.tagName==="DIV");for(let j=U.length-1;j>=0;j--){let Z=U[j].textContent&&U[j].textContent.trim();if(Z&&!(_&&Z.startsWith(_))&&(X=Z.split(/[·•]/)[0].trim(),X))break}}let L=null;if(b){let O=b.querySelectorAll("p, span, div");for(let P of O){let U=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){L=U;break}}}let ue=null,Oe=R.find(O=>O.textContent&&O.textContent.trim()==="About");if(Oe){let O=Oe.parentElement;for(;O&&O.tagName!=="SECTION";)O=O.parentElement;O&&(ue=(O.textContent||"").trim().replace(/^About\s*/,"").trim()||null,ue&&(ue=ue.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let je=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ne=je&&je.src||null,Ze=!!y.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:_,title:T,location:X,about:ue,company:M,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:Ne,hasVerifiedBadge:Ze}});try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(i.resolvedUrl=p.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let p=i.profileInfo?.location,v=le()[t]?.location,C=p||v;if(yo(C,c))return console.log(` \u26A0 Excluded location (${p?"live":"stored"}): ${C}`),i.reason="excluded_location",i;!p&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Re(e,{detail:!0})).status==="pending"&&l)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;await ye(e);let d=await Ut(e);if(d||await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),d=await Ut(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),i.reason="connected",i;if(!d){let p=await Re(e,{detail:!0});return s&&(p.status==="connected"||p.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),i.reason="connected",i):(console.log(" \u2717 Connect not found"),i.reason="button_not_found",i)}i.method=d.method;let m=await vs(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),i.reason="wrong_target",i;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3);let p=await Re(e);if(p==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${p} \u2014 trying More dropdown...`),await ye(e),await k(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(y=>y.scrollIntoView({behavior:"smooth",block:"center"}),v),await k(500),await v.click().catch(()=>e.evaluate(y=>y.click(),v)),await k(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(C){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),C),await k(3e3);let y=e.url();if(y.includes("/premium/")||y.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),i.reason="premium_required",i;if(await Re(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await k(500),i.reason="premium_required",i}catch(C){return console.log(" More dropdown failed:",C.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}if(await e.evaluate(()=>{let p=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of p){let C=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!C)continue;let y=(C.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(y)||C.querySelector('input[type="email"], input[name="email"]'))return!0;let A=C.querySelector('button[aria-label="Send without a note"]');if(A&&(A.disabled||A.getAttribute("aria-disabled")==="true"||(A.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let p=await e.$('button[aria-label="Dismiss"]');if(p)try{await p.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await k(500),i.reason="email_required",i}let w=await e.$('button[aria-label="Add a note"]'),g=await e.$('button[aria-label="Send without a note"]');if(!w&&!g){let p=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let C=v.querySelector('button[aria-label="Add a note"]'),y=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!C,sendWithout:!!y}});if(p.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));w=v?.asElement?.()||null,w||await v.dispose().catch(()=>{})}if(p.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));g=v?.asElement?.()||null,g||await v.dispose().catch(()=>{})}}if(r)if(w&&o){if(console.log(" Adding personalized note..."),await w.click(),await k(1500),await e.$("div.modal-upsell")){let C=await Cs(e);return i.success=C,i.connectionSent=C,i.reason=C?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let C=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),y=o.replace("{name}",C);await v.type(y,{delay:20}),await k(500);let A=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(A)return await Te(e,A)?(console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=y,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i)}}else{if(g)return console.log(" Sending without note..."),await Te(e,g)?(console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i);if(w&&!o){console.log(" No message provided, sending without note...");let p=await e.$('button[aria-label="Send without a note"]');if(p)return await Te(e,p)?(console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i)}}else{console.log(" Sending without note (custom messages disabled)...");let p=g;if(p)return await Te(e,p)?(console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),i.reason="modal_failed",i)}if(d.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 k(4e3)),await ye(e),await k(500);let v=await e.$$('button[id*="profile-overflow-action"]'),C=null;for(let y of v){let A=await e.evaluate(R=>{let D=R.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},y);if(A.visible&&!A.inSticky){C=y;break}}!C&&v.length>0&&(C=v[v.length-1]);for(let y of v)y!==C&&await y.dispose().catch(()=>{});if(C)try{await e.evaluate(A=>A.scrollIntoView({behavior:"smooth",block:"center"}),C),await k(500),await C.click().catch(()=>e.evaluate(A=>A.click(),C)),await k(2e3);let y=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(y){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(_=>_.click(),y),await k(3e3);let A=e.url();if(A.includes("/premium/")||A.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await Re(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await Re(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let D=await e.$('button[aria-label="Send without a note"]');if(D)return console.log(" Modal appeared via More dropdown, sending without note..."),await Te(e,D)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),i.reason="modal_failed",i);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(y){console.log(" More dropdown fallback failed:",y.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(a){console.error(` \u2717 Error: ${a.message}`),i.reason="error",i.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{i.fatal=!0}return i}}async function bo(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:l=20,viewOnly:s=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:i=null,excludeLocations:a=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
249
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${l})`}`),s||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!s){let m=Et();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let h=t[m];try{if(e.isClosed()){console.log(`
|
|
249
250
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
250
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let
|
|
251
|
-
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),
|
|
252
|
-
\u26A0 ${
|
|
253
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!s){let m=xt();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}import"dotenv/config";import*as U from"fs";import*as le from"path";import{fileURLToPath as ks}from"url";var vs=ks(import.meta.url),Cs=le.dirname(le.dirname(vs)),Ge=process.env.DATA_DIR?le.resolve(process.env.DATA_DIR,"collected-profiles"):le.join(Cs,"collected-profiles");function Ft(){U.existsSync(Ge)||U.mkdirSync(Ge,{recursive:!0})}function As(){return new Date().toISOString().split("T")[0]}function go(e,t=null){let n=t||As();return le.join(Ge,`${e}-${n}.json`)}function yo(e,t=null){Ft();let n=go(e,t);try{if(U.existsSync(n)){let o=U.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function wo(e,t=null){return yo(e,t).filter(o=>!o.processed)}function bo(e,t,n,o=null){Ft();let r=go(e,o);try{if(!U.existsSync(r))return;let i=JSON.parse(U.readFileSync(r,"utf-8")),s=i.profiles.find(c=>c.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof n=="string")s.status=n;else if(typeof n=="object"){if(s.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(s.name=c.name),c.title&&(s.title=c.title),c.location&&(s.location=c.location),c.company&&(s.company=c.company),c.connectionDegree&&(s.connectionDegree=c.connectionDegree),c.connectionsCount&&(s.connectionsCount=c.connectionsCount),c.mutualConnections&&(s.mutualConnections=c.mutualConnections),c.photoUrl&&(s.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=c.hasVerifiedBadge)}s.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),U.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function So(e){let t=yo(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function ko(){Ft();try{return U.readdirSync(Ge).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(U.readFileSync(le.join(Ge,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as b from"fs";import*as Wt from"os";import*as I from"path";import{fileURLToPath as Ys}from"url";var qt={};te(qt,{NAME:()=>_s,VERSION:()=>xs,up:()=>Is});import*as W from"fs";import*as ct from"path";var xs=1,_s="normalize-jobs-and-questions",$s=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Es=50;function Mt(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function Ut(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.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 Is(e,t){let n=ct.join(e,"jobs.json"),o=ct.join(t,"scouted-jobs.json"),r=ct.join(e,"application-questions.json"),i=Mt(n)||{},s=Mt(o)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let d=s[u],f=i[u];for(let m of $s)d[m]!=null&&f[m]==null&&(f[m]=d[m]);l.push(u),c++}c>0?(Ut(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Mt(r);if(a&&Array.isArray(a.applications)){let u={},d=0;for(let f of a.applications){let m=f.jobId||"unknown";u[m]||(u[m]={applications:[]});let h=(f.questions||[]).map(y=>{let g={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=Es?g.options=y.options:(g.optionsOmitted=!0,d++)),y.page&&(g.page=y.page),y.wasPreFilled&&(g.wasPreFilled=!0),y.wasRetry&&(g.wasRetry=!0),g});u[m].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})}Ut(r,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).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(l.length>0){for(let u of l)delete s[u];Ut(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Bt={};te(Bt,{NAME:()=>Rs,VERSION:()=>Ds,up:()=>Ns});import*as G from"fs";import*as vo from"path";var Ds=2,Rs="reset-unread-flags";function Ts(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function Os(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{G.writeFileSync(o,n)}catch(r){try{G.unlinkSync(o)}catch{}throw r}try{G.renameSync(o,e)}catch(r){try{G.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 Ns(e){let t=vo.join(e,"conversations.json"),n=Ts(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}Os(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Jt={};te(Jt,{NAME:()=>Ps,VERSION:()=>js,up:()=>qs});import*as Y from"fs";import*as Co from"path";var js=3,Ps="recompute-last-message-by",Ls=new Set(["draft","confirmed","rejected","needs_review"]);function Fs(e){return Y.existsSync(e)?JSON.parse(Y.readFileSync(e,"utf-8")):null}function Ms(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Us(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Ls.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,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function qs(e){let t=Co.join(e,"conversations.json"),n=Fs(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,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=Us(a,o),d=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}Ms(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} 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.")}var Ht={};te(Ht,{NAME:()=>Js,VERSION:()=>Bs,up:()=>Gs});import*as K from"fs";import*as Ao from"path";var Bs=4,Js="split-connection-timestamps",Hs=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Vs(e){if(!K.existsSync(e))return null;let t=K.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ws(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{K.writeFileSync(o,n)}catch(r){try{K.unlinkSync(o)}catch{}throw r}try{K.renameSync(o,e)}catch(r){try{K.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Gs(e){let t=Ao.join(e,"people.json"),n=Vs(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,Hs.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ws(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await ot();Ot();var Ks=Ys(import.meta.url),zs=I.dirname(Ks),Qs=I.dirname(I.dirname(zs));function Xs(e){return e&&(e==="~"?Wt.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(Wt.homedir(),e.slice(2)):e)}var Z=process.env.DATA_DIR?I.resolve(Xs(process.env.DATA_DIR)):Qs,ke=I.join(Z,"collected-profiles"),ve=I.join(Z,"market-research"),B=I.join(Z,".schema-version"),xo=[I.join(ke,".schema-version"),I.join(ve,".schema-version")],he=4,ae=[{version:1,module:qt},{version:2,module:Bt},{version:3,module:Jt},{version:4,module:Ht}];(function(){ae.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ae){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ae.length?ae[ae.length-1].version:0;if(n!==he)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${he}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ae.length;o++){let r=o+1;if(ae[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ae[o].version}`)}})();function Io(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
251
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let w=Fn(h.profileUrl);if(w==="pending"||w==="connected"||w==="sent_with_note"||w==="sent_without_note"||w==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${w})`),w==="pending"||w==="sent_with_note"||w==="sent_without_note"||w==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,i&&await i(h,f,{success:!1,reason:w,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${h.name||h.profileUrl}`);let g=null;if(s){let p=await ks(e,h.profileUrl);p?(ot(h.profileUrl,{...p,source:u}),f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:p,resolvedUrl:p.resolvedUrl}):(f.errors++,g={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=l){console.log(` Max connections per session (${l}) reached`);break}let p=_t();if(!p.allowed){console.log(` \u26A0 Global quota exhausted: ${p.reason}`);break}if(g=await xs(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:u,skipQuotaGate:!0}),g.success)f.connectionsSent++;else switch(g.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(g?.fatal){console.log(`
|
|
252
|
+
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(d++,d>=3){console.log(`
|
|
253
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(Ln(h.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&Mn(h.profileUrl,g.resolvedUrl),Pn(h.profileUrl,{source:u||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:g.reason})),i&&await i(h,f,g),m<t.length-1){let p=c+Math.random()*2e3;await k(p)}}if(console.log(`
|
|
254
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!s){let m=Et();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}import"dotenv/config";import*as q from"fs";import*as ae from"path";import{fileURLToPath as $s}from"url";var _s=$s(import.meta.url),Es=ae.dirname(ae.dirname(_s)),Ke=process.env.DATA_DIR?ae.resolve(process.env.DATA_DIR,"collected-profiles"):ae.join(Es,"collected-profiles");function qt(){q.existsSync(Ke)||q.mkdirSync(Ke,{recursive:!0})}function Is(){return new Date().toISOString().split("T")[0]}function So(e,t=null){let n=t||Is();return ae.join(Ke,`${e}-${n}.json`)}function ko(e,t=null){qt();let n=So(e,t);try{if(q.existsSync(n)){let o=q.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function vo(e,t=null){return ko(e,t).filter(o=>!o.processed)}function Co(e,t,n,o=null){qt();let r=So(e,o);try{if(!q.existsSync(r))return;let l=JSON.parse(q.readFileSync(r,"utf-8")),s=l.profiles.find(c=>c.profileUrl===t);if(s){if(s.processed=!0,s.processedAt=new Date().toISOString(),typeof n=="string")s.status=n;else if(typeof n=="object"){if(s.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(s.name=c.name),c.title&&(s.title=c.title),c.location&&(s.location=c.location),c.company&&(s.company=c.company),c.connectionDegree&&(s.connectionDegree=c.connectionDegree),c.connectionsCount&&(s.connectionsCount=c.connectionsCount),c.mutualConnections&&(s.mutualConnections=c.mutualConnections),c.photoUrl&&(s.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(s.hasVerifiedBadge=c.hasVerifiedBadge)}s.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}l.lastUpdated=new Date().toISOString(),q.writeFileSync(r,JSON.stringify(l,null,2))}}catch(l){console.error("Error marking profile processed:",l.message)}}function xo(e){let t=ko(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,l)=>(r[l.status]=(r[l.status]||0)+1,r),{})}}function Ao(){qt();try{return q.readdirSync(Ke).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(q.readFileSync(ae.join(Ke,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(l=>!l.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as S from"fs";import*as zt from"os";import*as I from"path";import{fileURLToPath as si}from"url";var Ht={};te(Ht,{NAME:()=>Rs,VERSION:()=>Ds,up:()=>js});import*as G from"fs";import*as dt from"path";var Ds=1,Rs="normalize-jobs-and-questions",Ts=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Os=50;function Bt(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function Jt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{G.writeFileSync(o,n)}catch(r){try{G.unlinkSync(o)}catch{}throw r}try{G.renameSync(o,e)}catch(r){try{G.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function js(e,t){let n=dt.join(e,"jobs.json"),o=dt.join(t,"scouted-jobs.json"),r=dt.join(e,"application-questions.json"),l=Bt(n)||{},s=Bt(o)||{},c=0,i=[];for(let u of Object.keys(l)){if(!s[u])continue;let f=s[u],d=l[u];for(let m of Ts)f[m]!=null&&d[m]==null&&(d[m]=f[m]);i.push(u),c++}c>0?(Jt(n,l),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Bt(r);if(a&&Array.isArray(a.applications)){let u={},f=0;for(let d of a.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let h=(d.questions||[]).map(w=>{let g={type:w.type||"input",question:w.question||"",answer:w.answer||""};return w.options&&(w.options.length<=Os?g.options=w.options:(g.optionsOmitted=!0,f++)),w.page&&(g.page=w.page),w.wasPreFilled&&(g.wasPreFilled=!0),w.wasRetry&&(g.wasRetry=!0),g});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||h.length,questions:h})}Jt(r,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let u of i)delete s[u];Jt(o,s),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Vt={};te(Vt,{NAME:()=>Ps,VERSION:()=>Ns,up:()=>Ms});import*as Y from"fs";import*as $o from"path";var Ns=2,Ps="reset-unread-flags";function Fs(e){return Y.existsSync(e)?JSON.parse(Y.readFileSync(e,"utf-8")):null}function Ls(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function Ms(e){let t=$o.join(e,"conversations.json"),n=Fs(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}Ls(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Wt={};te(Wt,{NAME:()=>qs,VERSION:()=>Us,up:()=>Ws});import*as K from"fs";import*as _o from"path";var Us=3,qs="recompute-last-message-by",Bs=new Set(["draft","confirmed","rejected","needs_review"]);function Js(e){return K.existsSync(e)?JSON.parse(K.readFileSync(e,"utf-8")):null}function Hs(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{K.writeFileSync(o,n)}catch(r){try{K.unlinkSync(o)}catch{}throw r}try{K.renameSync(o,e)}catch(r){try{K.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}function Vs(e,t){if(!e||e.length===0)return"them";let n=e.filter(l=>!Bs.has(l.status));if(n.length===0)return"them";let o=n.map(l=>({m:l,t:Date.parse(l.time)})).filter(l=>Number.isFinite(l.t)).sort((l,s)=>s.t-l.t).map(l=>l.m),r=o.length>0?o:[...n].reverse();for(let l of r){let s=l.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Ws(e){let t=_o.join(e,"conversations.json"),n=Js(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,l=0,s=0;for(let c of Object.keys(n)){let i=n[c];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,l++);let a=Array.isArray(i.messages)?i.messages:[],u=Vs(a,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==u&&s++,i.lastMessageBy=u,i.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}Hs(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),l>0&&console.log(` Cleaned ${l} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Gt={};te(Gt,{NAME:()=>Ys,VERSION:()=>Gs,up:()=>Xs});import*as z from"fs";import*as Eo from"path";var Gs=4,Ys="split-connection-timestamps",Ks=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function zs(e){if(!z.existsSync(e))return null;let t=z.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Qs(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 l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function Xs(e){let t=Eo.join(e,"people.json"),n=zs(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let l of Object.keys(n)){let s=n[l];!s||typeof s!="object"||(r++,Ks.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Qs(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var Yt={};te(Yt,{NAME:()=>ei,VERSION:()=>Zs,up:()=>ri});import*as Q from"fs";import*as Io from"path";var Zs=5,ei="rename-headline-to-title",ke=/[·•]\s*(1st|2nd|3rd)\+?/i,ti=e=>(e||"").replace(/\s+/g," ").trim(),ze=e=>ti(e).replace(/^[+·•\s]+/,"").replace(/[·•\s]+$/,"");function ni(e){if(!Q.existsSync(e))return null;let t=Q.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function oi(e,t){let n=JSON.stringify(t),o=e+".tmp";try{Q.writeFileSync(o,n)}catch(r){try{Q.unlinkSync(o)}catch{}throw r}try{Q.renameSync(o,e)}catch(r){try{Q.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let l=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw l.code=r.code,l}throw r}}async function ri(e,t){let n=Io.join(t,"discovered-people.json"),o=ni(n);if(!o||typeof o!="object"){console.log(" discovered-people.json not found \u2014 nothing to migrate.");return}let r=Array.isArray(o)?o:Object.values(o),l=0,s=0,c=0;for(let i of r)if(!(!i||typeof i!="object")){if(l++,i.name&&ke.test(i.name)){let a=ze(String(i.name).split(ke)[0]),u=String(i.name).match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i),f=u?ze(u[1]):"";a&&(i.name=a,s++),f&&(!i.headline||ke.test(String(i.headline))||!ze(i.headline))&&(i.headline=f)}if(Object.prototype.hasOwnProperty.call(i,"headline")){let a=ze(i.headline||"");ke.test(a)&&(a=""),(!i.title||ke.test(String(i.title)))&&(i.title=a||(i.title&&!ke.test(String(i.title))?i.title:null)||null),delete i.headline,c++}else if(typeof i.title=="string"){let a=ze(i.title);a&&!ke.test(a)&&a!==i.title&&(i.title=a)}}if(c===0&&s===0){console.log(` Scanned ${l} discovered people \u2014 already unified (no headline field, clean names).`);return}oi(n,o),console.log(` discovered-people.json: scanned ${l}, de-glued ${s} names, moved ${c} headline\u2192title.`),console.log(" Every record now carries a single `title` field (matches people.json).")}await it();Pt();var ii=si(import.meta.url),li=I.dirname(ii),ai=I.dirname(I.dirname(li));function ci(e){return e&&(e==="~"?zt.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(zt.homedir(),e.slice(2)):e)}var ne=process.env.DATA_DIR?I.resolve(ci(process.env.DATA_DIR)):ai,Ce=I.join(ne,"collected-profiles"),xe=I.join(ne,"market-research"),J=I.join(ne,".schema-version"),Do=[I.join(Ce,".schema-version"),I.join(xe,".schema-version")],ge=5,ce=[{version:1,module:Ht},{version:2,module:Vt},{version:3,module:Wt},{version:4,module:Gt},{version:5,module:Yt}];(function(){ce.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ce){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=ce.length?ce[ce.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<ce.length;o++){let r=o+1;if(ce[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ce[o].version}`)}})();function jo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
254
255
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
255
|
-
`),process.exit(1));try{
|
|
256
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
257
|
-
`),process.exit(1))}let e;try{e=
|
|
258
|
-
[FATAL] DATA_DIR (${
|
|
256
|
+
`),process.exit(1));try{S.mkdirSync(ne,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
257
|
+
[FATAL] Cannot create DATA_DIR (${ne}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
258
|
+
`),process.exit(1))}let e;try{e=S.statSync(ne)}catch(t){console.error(`
|
|
259
|
+
[FATAL] DATA_DIR (${ne}) is not accessible: ${t.message}
|
|
259
260
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
260
|
-
[FATAL] DATA_DIR (${
|
|
261
|
-
`),process.exit(1));for(let t of[
|
|
261
|
+
[FATAL] DATA_DIR (${ne}) 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.
|
|
262
|
+
`),process.exit(1));for(let t of[Ce,xe]){let n;try{n=S.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
262
263
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
263
|
-
`),process.exit(1))}}var
|
|
264
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
264
|
+
`),process.exit(1))}}var ve=I.join(ne,".migration-lock");function ui(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return S.writeFileSync(ve,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(S.readFileSync(ve,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(s){s.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,l=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(l=Date.now()-s)}o&&l<r&&(console.error(`
|
|
265
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ve}
|
|
265
266
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
266
|
-
`),process.exit(1)),o&&
|
|
267
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
267
|
+
`),process.exit(1)),o&&l>=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=ve+".tmp";try{return S.writeFileSync(n,e),S.renameSync(n,ve),!0}catch(o){try{S.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Qt(){try{if(JSON.parse(S.readFileSync(ve,"utf-8")).pid!==process.pid)return;S.unlinkSync(ve)}catch{}}var Ro=!1;function fi(){if(Ro)return;Ro=!0;let e=()=>{try{Qt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function di(){if(S.existsSync(J))return;let e=[],t=[];for(let l of Do)if(S.existsSync(l))try{e.push({file:l,schema:mt(l)})}catch(s){t.push({file:l,err:s.message})}if(t.length>0){console.error(`
|
|
268
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let l of t)console.error(` ${l.file}: ${l.err}`);console.error(`
|
|
268
269
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
269
|
-
`),process.exit(1)}if(e.length===0)return;let n=e.map(
|
|
270
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
271
|
-
`),process.exit(1)}let o=e[0].schema,r=
|
|
272
|
-
[FATAL] ${
|
|
273
|
-
`),process.exit(1)}let t=
|
|
274
|
-
[FATAL] ${
|
|
275
|
-
`),process.exit(1)),t}function
|
|
276
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
277
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
270
|
+
`),process.exit(1)}if(e.length===0)return;let n=e.map(l=>l.schema.version);if(new Set(n).size>1){console.error(`
|
|
271
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let l of e)console.error(` ${l.file}: v${l.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
272
|
+
`),process.exit(1)}let o=e[0].schema,r=J+".tmp";try{S.writeFileSync(r,JSON.stringify(o,null,2)),S.renameSync(r,J)}catch(l){try{S.unlinkSync(r)}catch{}throw l}for(let l of Do)if(S.existsSync(l))try{S.unlinkSync(l)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${J}`)}function mi(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function mt(e){let t=S.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function To(){if(di(),!S.existsSync(J))return{version:0,migrations:[]};let e;try{e=mt(J)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
273
|
+
[FATAL] ${J} 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.
|
|
274
|
+
`),process.exit(1)}let t=mi(e);return t===null&&(console.error(`
|
|
275
|
+
[FATAL] ${J} 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.
|
|
276
|
+
`),process.exit(1)),t}function No(e){try{S.chmodSync(e,384)}catch{}}function pi(e){if(jo(),S.existsSync(J))try{if(S.lstatSync(J).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${J}. 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=J+".tmp";try{S.writeFileSync(t,JSON.stringify(e,null,2)),No(t),S.renameSync(t,J)}catch(n){try{S.unlinkSync(t)}catch{}throw n}}function Oo(e,t){if(!S.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=S.readdirSync(e).filter(c=>{let i=c.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return S.statSync(I.join(e,c)).isFile()}catch{return!1}}),r=0,l=0,s=[];for(let c of o){let i=I.join(e,c),a=I.join(e,c+n);if(S.existsSync(a)){l++;continue}try{Fo(i,a),r++}catch(u){s.push({file:c,err:u.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${I.basename(e)}/: `+s.map(i=>`${i.file} (${i.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||l>0){let c=l>0?` (${l} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${I.basename(e)}/ (${n})${c}`)}}var Kt=!1;async function Po(){if(Kt)return;jo(),bi();let t=To().version;if(t===ge){Kt=!0;return}fi(),ui(),process.on("exit",Qt),t>ge&&(console.error(`
|
|
277
|
+
[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.
|
|
278
|
+
`),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
279
|
`),process.exit(1)),console.log(`
|
|
279
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
280
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${ge}`);let n=Si();if(!n.ok){console.error(`
|
|
280
281
|
[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
282
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
282
|
-
`),process.exit(1)}let o=
|
|
283
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let
|
|
284
|
-
[FATAL] Pre-migration backup failed for ${
|
|
285
|
-
`),process.exit(1)}let c=r.module;try{await c.up(
|
|
286
|
-
[FATAL] Migration ${
|
|
283
|
+
`),process.exit(1)}let o=ce.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
284
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let l=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${l}.backup`;try{Oo(Ce,r.version),Oo(xe,r.version)}catch(i){console.error(`
|
|
285
|
+
[FATAL] Pre-migration backup failed for ${l}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
286
|
+
`),process.exit(1)}let c=r.module;try{await c.up(Ce,xe)}catch(i){console.error(`
|
|
287
|
+
[FATAL] Migration ${l} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=ki(s);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
287
288
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
288
289
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
289
|
-
`)}process.exit(1)}try{let
|
|
290
|
-
[FATAL] Migration ${
|
|
291
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
292
|
-
\u2713 Schema is now at v${
|
|
293
|
-
`)}var
|
|
290
|
+
`)}process.exit(1)}try{let i=new Date().toISOString(),a={version:r.version,name:c.NAME||l,appliedAt:i},u=To();u.version=r.version,u.migratedAt=i,u.migrations=u.migrations||[],u.migrations.push(a),pi(u)}catch(i){console.error(`
|
|
291
|
+
[FATAL] Migration ${l} applied successfully but schema version file could NOT be updated: ${i.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 ${l}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
292
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${l} complete`)}try{jn()}catch{}try{Tt()}catch{}Kt=!0,Qt(),console.log(`
|
|
293
|
+
\u2713 Schema is now at v${ge}
|
|
294
|
+
`)}var hi=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function gi(e){let t=e.toLowerCase();return hi.some(n=>n.test(t))}var yi=6e4;function wi(){let e=Date.now(),t=[];for(let n of[ne,Ce,xe]){if(!S.existsSync(n))continue;let o;try{o=S.readdirSync(n)}catch{continue}for(let r of o){if(!gi(r))continue;let l=I.join(n,r);try{let s=S.statSync(l);if(!s.isFile()||e-s.mtimeMs<yi)continue;t.push({dir:n,file:r,fullPath:l})}catch{}}}return t}function bi({verbose:e=!1}={}){let t=wi();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{S.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${I.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 Si(){let e=[];for(let t of[Ce,xe]){if(!S.existsSync(t))continue;let n=S.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=I.join(t,o);try{mt(r)}catch(l){e.push({dir:I.basename(t),file:o,err:l.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ki(e){let t=[],n=[];for(let l of[Ce,xe]){if(!S.existsSync(l))continue;let s=S.readdirSync(l).filter(c=>c.endsWith(e));for(let c of s){let i=I.join(l,c),a=c.slice(0,-e.length),u=I.join(l,a);try{a.toLowerCase().endsWith(".json")?mt(i):S.accessSync(i,S.constants.R_OK),t.push({backupPath:i,originalPath:u,fileName:c,dir:l})}catch(f){n.push(`${I.basename(l)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:l,originalPath:s,fileName:c,dir:i}of t)try{Fo(l,s),o++}catch(a){r.push(`${I.basename(i)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Fo(e,t){let n=t+".tmp";try{S.copyFileSync(e,n),No(n)}catch(o){try{S.unlinkSync(n)}catch{}throw o}try{S.renameSync(n,t)}catch(o){try{S.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}}tt();tt();import Xt from"fs";import vi from"path";var Ci={headless:!1,defaultViewport:null,protocolTimeout:3e5},Xe=new Set,Lo=!1;async function pt(){let e=[...Xe].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});Xe.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function xi(){if(Lo)return;Lo=!0;let e=t=>async()=>{await pt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await pt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await pt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await pt(),process.exit(0))}),process.on("exit",()=>{for(let t of Xe)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Zt(e){return vi.join(e,".ilml-browser-session.json")}function Bo(e,t={}){try{Xt.writeFileSync(Zt(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ai(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Bo(e,n?{wsEndpoint:n}:{})}catch{}}function $i(e){let t=Jo(e);t&&t.ownerPid===process.pid&&Qe(e)}function Qe(e){try{Xt.rmSync(Zt(e),{force:!0})}catch{}}function Jo(e){try{return JSON.parse(Xt.readFileSync(Zt(e),"utf-8"))}catch{return null}}function Mo(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Uo(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),l=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([l,r])}async function qo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Jo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Mo(o.ownerPid)?"live":(Qe(t),"free");let r=Symbol("timeout"),l=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Uo(l,n,r);if(s===r)return l.then(i=>{if(i)try{i.disconnect()}catch{}}),"live";if(!s)return Qe(t),"free";if(Mo(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Uo(s.close().then(()=>!0).catch(()=>!1),n,!1))return Qe(t),"free";try{s.disconnect()}catch{}return"live"}function _i(e,t){e&&(xi(),Xe.add(e),e.on("disconnected",()=>{Xe.delete(e),t&&Qe(t)}))}async function Ho(e,t={}){let n=wn(),o={...Ci,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await qo(e,n)==="live")throw new Error(r);Bo(n);let l;try{l=await e.launch(o)}catch{if(await qo(e,n)==="live")throw new Error(r);vn(n);try{l=await e.launch(o)}catch(c){throw $i(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return _i(l,n),Ai(n,l),{browser:l,profileDir:n,needsSeed:Sn(n)}}async function Vo(e,t){if(!t||!t.needsSeed)return!1;if(!gn())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...hn()),kn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await Po();function Ii(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function Di(){let e=Ii();if(e.list){console.log(`
|
|
294
295
|
\u{1F4C2} Available profile files:
|
|
295
|
-
`);let s=
|
|
296
|
+
`);let s=Ao();if(s.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let c of s)console.log(` ${c.file}`),console.log(` Total: ${c.count}, Unprocessed: ${c.unprocessed}`);console.log(""),process.exit(0)}console.log(`
|
|
296
297
|
========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
|
|
297
|
-
`),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=
|
|
298
|
+
`),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=vo(e.source,e.date);console.log(`
|
|
298
299
|
Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
299
300
|
\u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
|
|
300
301
|
Profiles:`),t.slice(0,10).forEach((s,c)=>{console.log(` ${c+1}. ${s.name||"Unknown"} - ${s.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
|
|
301
302
|
Press Enter to start, or Ctrl+C to cancel...`),await new Promise(s=>{process.stdin.once("data",()=>s())}),console.log(`
|
|
302
303
|
\u{1F680} Starting browser...
|
|
303
|
-
`);let n=await
|
|
304
|
-
`);let
|
|
304
|
+
`);let n=await Ho(Ei,{devtools:!1}),o=n.browser,r=await o.newPage();await Vo(r,n),console.log(`\u2713 Browser ready (persistent profile)
|
|
305
|
+
`);let l=e.viewOnly?"view-only":"connect";await mn("funnel",l,async s=>{try{let c=await bo(r,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(a,u,f)=>{Co(e.source,a.profileUrl,{status:f.reason,connectionSent:f.connectionSent,withCustomMessage:f.withCustomMessage,message:f.messageSent,method:f.method,reason:f.reason,error:f.error,profileInfo:f.profileInfo})}});console.log(`
|
|
305
306
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
306
|
-
`);let
|
|
307
|
-
Status breakdown:`);for(let[a,u]of Object.entries(
|
|
307
|
+
`);let i=xo(e.source);if(console.log(`Processed: ${i.processed}/${i.total}`),console.log(`Remaining: ${i.unprocessed}`),Object.keys(i.statuses).length>0){console.log(`
|
|
308
|
+
Status breakdown:`);for(let[a,u]of Object.entries(i.statuses))console.log(` ${a}: ${u}`)}s.sent=c.connectionsSent,s.viewed=c.viewed,s.errors=c.errors,s.skippedPending=c.skipped?.pending||0,s.skippedConnected=c.skipped?.connected||0}finally{await o.close().catch(()=>{})}},s=>[`${s.sent??0} sent, ${s.viewed??0} viewed, ${s.errors??0} errors`,s.skippedPending||s.skippedConnected?`Skipped: ${s.skippedPending} pending, ${s.skippedConnected} connected`:null]),process.exit(0)}Di().catch(()=>{process.exit(1)});
|