ilml-plugin-linkedin 1.20.2 → 1.20.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/connect.mjs +49 -49
- package/dist/enrichProfile.mjs +10 -10
- package/dist/enrichProfiles.mjs +34 -35
- package/dist/funnelRunner.mjs +38 -38
- package/dist/messageBot.mjs +62 -63
- package/dist/readPost.mjs +10 -10
- package/dist/run.mjs +58 -59
- package/dist/scout.mjs +38 -39
- package/dist/src/saveLoginState.mjs +4 -4
- package/dist/syncAll.mjs +77 -78
- package/dist/syncConnections.mjs +30 -31
- package/dist/verifyAbout.mjs +18 -19
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +20 -21
- package/dist/visit.mjs +34 -35
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Eo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Eo(e,n,{get:t[n],enumerable:!0})};async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}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 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 Ke=ce(()=>{});import{getPluginConfig as Mo}from"@ilivemylife/graph-sdk";var Lo,fe,te,ft,dt,mt=ce(async()=>{Lo=await Mo();for(let[e,t]of Object.entries(Lo))process.env[e]===void 0&&(process.env[e]=t);fe=process.env.LINKEDIN_NAME,te=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ft=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.NEEDS_REVIEW])),dt=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.REJECTED,te.NEEDS_REVIEW]))});import"dotenv/config";import*as O from"fs";import*as M from"path";import{fileURLToPath as Po}from"url";function an(){Ce=null,Bo=null,ne=null,Jo=null,Vo=null,Ho=null}function Qe(){O.existsSync(oe)||O.mkdirSync(oe,{recursive:!0})}function gt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.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 yt(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${M.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let r=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.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{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function Fe(){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 nn(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=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=nn(n),s=nn(e[r].name);if(i&&s&&i===s)return r}return t}function Yo(){O.existsSync(ht)||O.mkdirSync(ht,{recursive:!0})}function cn(e){let t=ye(e);return t?M.join(ht,`${t}.json`):null}function Ko(e){let t=cn(e);return t?yt(t,`profile-history/${ye(e)}.json`)||[]:[]}function zo(e,t){let n=cn(e);if(!n)return;Yo();let o=Ko(e);o.unshift(t);try{gt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ye(e)}: ${r.message}`)}}function on(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 Qo(e,t){if(!e)return[];let n=[];for(let o of Go){let r=e[o],i=t[o];on(r)||on(i)||rn(r)!==rn(i)&&n.push(o)}return n}function Zo(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 re(){return Ce||(Qe(),Ce=yt(pt,"people.json")||{},Ce)}function Ze(e){Qe(),Ce=e;try{gt(pt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${M.resolve(pt)}`)}}function ze(e,t={}){if(!e)return null;let n=re(),o=Fe(),r=new Date().toISOString(),i=$e(n,e,t.name),s=n[i];if(s){let c=Qo(s,t);c.length>0&&(zo(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:Zo(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 Wo)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 Ze(n),n[i]}function un(e,t){if(!e||!t)return;let n=re(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Fe(),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(),Ze(n))}function fn(e){return e&&re()[e]?.connectionStatus||null}function dn(e,t,n={}){if(!e)return;if(n.profileInfo)ze(e,n.profileInfo);else{let c=re(),l=$e(c,e,n.profileInfo?.name);c[l]||ze(e,{})}let o=re(),r=$e(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let s=Fe();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(),Ze(o)}function mn(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ye(t);if(!o)return;let r=re(),i=$e(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(),Ze(r)))}function pn(){return ne||(Qe(),ne=yt(sn,"quota.json"),(!ne||!ne.connections)&&(ne={connections:[]}),ne)}function Xo(e){Qe(),ne=e;try{gt(sn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function hn(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}),Xo(n)}function gn(){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 wt(){let e=gn(),t=Fe(),n=e.filter(l=>l.date===t).length,o=e.length,r=n>=Ne,i=o>=Oe,s=!r&&!i,c={allowed:s,daily:{sent:n,max:Ne},weekly:{sent:o,max:Oe}};return s||(c.reason=r?`Daily limit reached (${n}/${Ne})`:`Weekly limit reached (${o}/${Oe})`),c}function bt(){let e=gn(),t=Fe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Ne,remaining:Ne-n},weekly:{sent:o,max:Oe,remaining:Oe-o}}}var Uo,qo,oe,pt,oi,sn,ri,si,ii,ht,ln,Ne,Oe,Ce,Bo,ne,Jo,Vo,Ho,Wo,Go,Xe=ce(async()=>{await mt();Uo=Po(import.meta.url),qo=M.dirname(M.dirname(Uo)),oe=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(qo,"collected-profiles"),pt=M.join(oe,"people.json"),oi=M.join(oe,"jobs.json"),sn=M.join(oe,"quota.json"),ri=M.join(oe,"conversations.json"),si=M.join(oe,"sync-state.json"),ii=M.join(oe,"application-questions.json"),ht=M.join(oe,"profile-history"),ln=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ne=ln(process.env.CONNECT_MAX_DAILY,20),Oe=ln(process.env.CONNECT_MAX_WEEKLY,100),Ce=null,Bo=null,ne=null,Jo=null,Vo=null,Ho=null;Wo=["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"],Go=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var yn={};ee(yn,{extractCertificationsFromDetails:()=>rr,extractEducationFromDetails:()=>nr,extractExperienceFromDetails:()=>er,extractFeaturedFromDetails:()=>tr,extractRecommendationsFromDetails:()=>sr,extractSkillsFromDetails:()=>or});async function er(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await 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 f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(y=>y.tagName==="DIV");if(m.length<3)continue;let g=m.filter(y=>(y.textContent||"").trim().length>50);g.length<3||(d.textContent||"").length<500||f.push({el:d,count:g.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[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 f=u[0]||null,d=null,m=null;if(u[1]){let k=u[1].split("\xB7").map(_=>_.trim());d=k[0]||null,k[1]&&(m=k[1])}let g=u.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),y=null,p=null;if(g>=0){let k=u[g].split("\xB7").map(_=>_.trim());y=k[0]||null,k[1]&&(p=k[1])}let h=null,v=-1;if(g>=0&&u[g+1]){let k=u[g+1],_=/^[>*\-•]|^>/.test(k),X=/https?:\/\//.test(k),K=/\d{4}/.test(k),L=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!_&&!X&&!K&&k.length<100&&L&&(h=k,v=g+1)}let $=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&&($={listed:k[1].split(",").map(_=>_.trim()),additional:parseInt(k[2],10)})}let T=new Set([0,1,g,v,w].filter(k=>k>=0)),D=u.filter((k,_)=>!T.has(_)),R=D.length>0?D.join(`
|
|
1
|
+
var Po=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Po(e,n,{get:t[n],enumerable:!0})};async function S(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}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 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 Qe=ce(()=>{});import{getPluginConfig as Yo}from"@ilivemylife/graph-sdk";var Ko,fe,te,pt,ht,gt=ce(async()=>{Ko=await Yo();for(let[e,t]of Object.entries(Ko))process.env[e]===void 0&&(process.env[e]=t);fe=process.env.LINKEDIN_NAME,te=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),pt=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.NEEDS_REVIEW])),ht=Object.freeze(new Set([te.DRAFT,te.CONFIRMED,te.REJECTED,te.NEEDS_REVIEW]))});import"dotenv/config";import*as O from"fs";import*as M from"path";import{fileURLToPath as zo}from"url";function mn(){Ce=null,Xo=null,ne=null,er=null,tr=null,nr=null}function Xe(){O.existsSync(oe)||O.mkdirSync(oe,{recursive:!0})}function bt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.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 St(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${M.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let r=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.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{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function Fe(){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 an(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=an(n),s=an(e[r].name);if(i&&s&&i===s)return r}return t}function sr(){O.existsSync(wt)||O.mkdirSync(wt,{recursive:!0})}function pn(e){let t=ye(e);return t?M.join(wt,`${t}.json`):null}function ir(e){let t=pn(e);return t?St(t,`profile-history/${ye(e)}.json`)||[]:[]}function lr(e,t){let n=pn(e);if(!n)return;sr();let o=ir(e);o.unshift(t);try{bt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${ye(e)}: ${r.message}`)}}function cn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function un(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function ar(e,t){if(!e)return[];let n=[];for(let o of rr){let r=e[o],i=t[o];cn(r)||cn(i)||un(r)!==un(i)&&n.push(o)}return n}function cr(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 re(){return Ce||(Xe(),Ce=St(yt,"people.json")||{},Ce)}function et(e){Xe(),Ce=e;try{bt(yt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${M.resolve(yt)}`)}}function Ze(e,t={}){if(!e)return null;let n=re(),o=Fe(),r=new Date().toISOString(),i=xe(n,e,t.name),s=n[i];if(s){let c=ar(s,t);c.length>0&&(lr(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:cr(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 or)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 et(n),n[i]}function hn(e,t){if(!e||!t)return;let n=re(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Fe(),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(),et(n))}function gn(e){return e&&re()[e]?.connectionStatus||null}function yn(e,t,n={}){if(!e)return;if(n.profileInfo)Ze(e,n.profileInfo);else{let c=re(),l=xe(c,e,n.profileInfo?.name);c[l]||Ze(e,{})}let o=re(),r=xe(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let s=Fe();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(),et(o)}function wn(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ye(t);if(!o)return;let r=re(),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(),et(r)))}function bn(){return ne||(Xe(),ne=St(fn,"quota.json"),(!ne||!ne.connections)&&(ne={connections:[]}),ne)}function ur(e){Xe(),ne=e;try{bt(fn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Sn(e,t="unknown"){let n=bn(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),ur(n)}function kn(){let e=bn(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function kt(){let e=kn(),t=Fe(),n=e.filter(l=>l.date===t).length,o=e.length,r=n>=Ne,i=o>=Oe,s=!r&&!i,c={allowed:s,daily:{sent:n,max:Ne},weekly:{sent:o,max:Oe}};return s||(c.reason=r?`Daily limit reached (${n}/${Ne})`:`Weekly limit reached (${o}/${Oe})`),c}function vt(){let e=kn(),t=Fe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Ne,remaining:Ne-n},weekly:{sent:o,max:Oe,remaining:Oe-o}}}var Qo,Zo,oe,yt,bi,fn,Si,ki,vi,wt,dn,Ne,Oe,Ce,Xo,ne,er,tr,nr,or,rr,tt=ce(async()=>{await gt();Qo=zo(import.meta.url),Zo=M.dirname(M.dirname(Qo)),oe=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(Zo,"collected-profiles"),yt=M.join(oe,"people.json"),bi=M.join(oe,"jobs.json"),fn=M.join(oe,"quota.json"),Si=M.join(oe,"conversations.json"),ki=M.join(oe,"sync-state.json"),vi=M.join(oe,"application-questions.json"),wt=M.join(oe,"profile-history"),dn=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ne=dn(process.env.CONNECT_MAX_DAILY,20),Oe=dn(process.env.CONNECT_MAX_WEEKLY,100),Ce=null,Xo=null,ne=null,er=null,tr=null,nr=null;or=["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"],rr=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var vn={};ee(vn,{extractCertificationsFromDetails:()=>hr,extractEducationFromDetails:()=>mr,extractExperienceFromDetails:()=>fr,extractFeaturedFromDetails:()=>dr,extractRecommendationsFromDetails:()=>gr,extractSkillsFromDetails:()=>pr});async function fr(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await 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 f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(y=>y.tagName==="DIV");if(m.length<3)continue;let g=m.filter(y=>(y.textContent||"").trim().length>50);g.length<3||(d.textContent||"").length<500||f.push({el:d,count:g.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[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 f=u[0]||null,d=null,m=null;if(u[1]){let k=u[1].split("\xB7").map(_=>_.trim());d=k[0]||null,k[1]&&(m=k[1])}let g=u.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),y=null,p=null;if(g>=0){let k=u[g].split("\xB7").map(_=>_.trim());y=k[0]||null,k[1]&&(p=k[1])}let h=null,v=-1;if(g>=0&&u[g+1]){let k=u[g+1],_=/^[>*\-•]|^>/.test(k),X=/https?:\/\//.test(k),K=/\d{4}/.test(k),P=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!_&&!X&&!K&&k.length<100&&P&&(h=k,v=g+1)}let x=null,w=-1,$=u[u.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){w=u.length-1;let k=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);k&&(x={listed:k[1].split(",").map(_=>_.trim()),additional:parseInt(k[2],10)})}let R=new Set([0,1,g,v,w].filter(k=>k>=0)),D=u.filter((k,_)=>!R.has(_)),T=D.length>0?D.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:f,company:d,employmentType:m,dates:y,duration:p,location:h,description:
|
|
4
|
-
`).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return a(d)}).filter(u=>u.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Me(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:f,company:d,employmentType:m,dates:y,duration:p,location:h,description:T,skills:x,_raw:u}}return l.map(u=>{let d=(u.innerText||"").trim().split(`
|
|
4
|
+
`).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return a(d)}).filter(u=>u.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Me(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let s=0;s<4;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(700);await S(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await S(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await S(600)}async function Le(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function dr(e,t){return Le(t,"featured","extractFeaturedFromDetails",async()=>(await Me(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${Pe}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var Eo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function mr(e,t){return Le(t,"education","extractEducationFromDetails",async()=>(await Me(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${Pe}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var Eo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function pr(e,t){return Le(t,"skills","extractSkillsFromDetails",async()=>(await Me(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${Pe}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var Eo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function hr(e,t){return Le(t,"certifications","extractCertificationsFromDetails",async()=>(await Me(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${Pe}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var Eo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function gr(e,t){return Le(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Me(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${Pe}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var Eo=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var
|
|
175
|
+
})()`)))}var Pe,Cn=ce(()=>{Qe();Pe=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,21 +235,21 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});var vn={};ee(vn,{BLOCK_MARKERS:()=>bn,dedupeAndCap:()=>kn,extractSidePanelProfiles:()=>ir,normalizeFundUrl:()=>et,normalizeProfileUrl:()=>xe,scanRelatedBlocks:()=>Sn});function xe(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 et(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function Sn(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,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=[],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 f=e.find(([p])=>u.includes(p));if(!f)continue;let d=f[1],m=s(a);if(!m)continue;let g=0,y=new Set;for(let p of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let h=p.href||p.getAttribute("href")||"",v=r(h);if(!v)continue;let $=p.querySelector('span[aria-hidden="true"]'),w=o($?$.textContent:p.getAttribute("aria-label")||p.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=p.closest("li")||p.parentElement;R&&(T=Array.from(R.querySelectorAll("p, span")).map(_=>o(_.textContent)).filter(_=>_&&_!==x&&!/^view\b/i.test(_)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(_)&&/[a-z]/i.test(_)&&_.length>2)[0]||"")}c.push({href:h,name:x,headline:T,block:d,rank:g++})}}return c}function kn(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=xe(t.seedUrl||""),r=new Map,i={};for(let s of e||[]){let c=xe(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 ir(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(Sn,bn)}catch{return[]}return kn(n,t)}var bn,St=ce(()=>{bn=[["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 _n={};ee(_n,{getJobDecision:()=>dr,getLastVisit:()=>Sr,getScoutStats:()=>kr,loadCompanies:()=>At,loadDiscoveredPeople:()=>He,loadJobDecisions:()=>xt,loadScoutedJobs:()=>$t,loadVisitLog:()=>ot,recordCompany:()=>yr,recordDiscoveredEdge:()=>hr,recordDiscoveredEdges:()=>gr,recordVisit:()=>br,resetCaches:()=>Ct,saveCompany:()=>wr,saveDiscoveredPerson:()=>mr,saveScoutedJob:()=>ur,setJobDecision:()=>fr});import"dotenv/config";import*as V from"fs";import*as B from"path";import{fileURLToPath as lr}from"url";function de(){V.existsSync(be)||V.mkdirSync(be,{recursive:!0})}function me(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 Ct(){Ue=null,qe=null,Be=null,Je=null,we=null}function $t(){return Ue||(Ue=Ve(Cn)||{},Ue)}function ur(e,t){if(!e)return;de();let n=$t(),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{me(Cn,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function xt(){return qe||(qe=Ve(xn)||{},qe)}function fr(e,t,n={}){if(!e||!t)return;de();let o=xt(),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{me(xn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function dr(e){return xt()[e]||null}function He(){return Be||(Be=Ve(nt)||{},Be)}function Ae(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function An(e,t){let n=xe(t)||t;if(e[n])return n;let o=Ae(t);if(!o)return n;let r=null;for(let[i,s]of Object.entries(e)){if(Ae(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 mr(e,t){if(!e)return;de();let n=He(),o=new Date().toISOString().slice(0,10),r=An(n,e),i=Ae(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&&Ae(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{me(nt,n)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function pr(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 En(e,t,n={},o){if(!t)return;let r=Ae(t);t=An(e,t);let i=n.seedUrl?{...n,seedUrl:xe(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=pr(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=[]),kt(a.categories,n.category),tt(a.categories,n.categories),tt(a.sectors,n.sectors),tt(a.aliases,n.aliases),r&&Ae(a.canonicalUrl||t)!==r&&kt(a.aliases,r),tt(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 hr(e,t={}){if(!e)return;de();let n=He();En(n,e,t,new Date().toISOString());try{me(nt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function gr(e){if(!Array.isArray(e)||e.length===0)return;de();let t=He(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(En(t,r.url,r,n),o++);if(o)try{me(nt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function yr(e={}){if(!e||!e.name)return;de();let t=e.key||et(e.website)||et(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=At(),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{me(vt,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function At(){return Je||(Je=Ve(vt)||{},Je)}function wr(e,t){if(!e)return;de();let n=At(),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{me(vt,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function ot(){return we||(we=Ve($n)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function br(e,t={}){if(!e)return;de();let n=ot();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{me($n,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Sr(e){let t=ot();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function kr(){let e=$t(),t=He(),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 i=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})`),l=ot(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(a)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var ar,cr,be,Cn,nt,$n,vt,xn,Ue,qe,Be,kt,tt,Je,we,Et=ce(()=>{St();ar=lr(import.meta.url),cr=B.dirname(B.dirname(ar)),be=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join(cr,"market-research"),Cn=B.join(be,"scouted-jobs.json"),nt=B.join(be,"discovered-people.json"),$n=B.join(be,"visit-log.json"),vt=B.join(be,"companies.json"),xn=B.join(be,"job-decisions.json");Ue=null;qe=null;Be=null;kt=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},tt=(e,t)=>{if(Array.isArray(t))for(let n of t)kt(e,n)};Je=null;we=null});var Pn={};ee(Pn,{computeEngagement:()=>It,detectCategory:()=>Rn,detectCategoryFromTitle:()=>rt,determineAction:()=>Mn,determineLastMessageBy:()=>jn,determineSituation:()=>Tn,enrichConversation:()=>vr,enrichPerson:()=>_r,enrichPersonContext:()=>Ln,extractAutoTags:()=>On,generateSummary:()=>Nn,normPreview:()=>_t});function vr(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!dt.has(l.status)),i=$r(t,e.profileUrl,n),s=jn(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Rn(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Tn(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===fe?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=It(r,t),e.personContext=Ln(i),e.summary=Nn(e,t,i),e.autoTags=On(e,t,i);let c=Mn(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Cr(e),e}function Rn(e,t,n){if(!e||e.length===0)return n?.title?rt(n.title):null;let o=e.filter(r=>r.sender!==fe&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,i]of Object.entries(Dn))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(o))return r}if(n?.title){let r=rt(n.title);if(r)return r}return null}function rt(e){if(!e)return null;for(let[t,n]of Object.entries(Dn))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Tn(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 In.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!==fe&&i.sender!=="Unknown");return In.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function jn(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===fe)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Nn(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(`${Dt(i)}: ${Ee(s,40)}`):s?r.push(Ee(s,50)):r.push(t.split(" ")[0]);let a=o.filter(g=>g.sender!==fe&&g.sender!=="Unknown").map(g=>g.text).join(" "),u=xr(a),f=Ar(a),d=Er(a),m=[];return u&&m.push(u),d&&d!==l&&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 On(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!dt.has(a.status)),i=r.map(a=>a.text).join(" "),s=r.filter(a=>a.sender!==fe&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=Fn(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||It(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=>ft.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function Fn(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 Mn(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&_t(e.lastMessagePreview)===_t(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(i=>ft.has(i.status));return r?r.status===te.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:`${Dt(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 It(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===fe?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 Ln(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Cr(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 $r(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 _t(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function Dt(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 xr(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 Ar(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 Er(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 _r(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=rt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Ir(e),e.personSummary=Dr(e),e.personAutoTags=Rr(e);let n=Tr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=jr(e)),e}function Ir(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 Dr(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 Rr(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=Fn("",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 Tr(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:`${Dt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function jr(e){let t=e.category;if(!t)return null;let n=Nr(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 Nr(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 Dn,In,Un=ce(async()=>{await mt();await Xe();Dn={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]}};In=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Bn={};ee(Bn,{DEFAULT_PROFILE_INTERESTS:()=>qn,computeFit:()=>Mr,detectSectors:()=>Fr});function Fr(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(Or))r.some(i=>i.test(t))&&n.push(o);return n}function Mr(e,t=qn){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 Or,qn,Jn=ce(()=>{Or={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/]};qn={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Ms from"puppeteer";import"dotenv/config";import*as J from"fs";import*as ue from"path";import{fileURLToPath as jo}from"url";import"dotenv/config";import{createGraphClient as _o,resolveToken as Io}from"@ilivemylife/graph-sdk";import{config as Do}from"dotenv";Do();var zt=Io()||process.env.TOKEN;zt||(console.error(`
|
|
238
|
+
`});var En={};ee(En,{BLOCK_MARKERS:()=>xn,dedupeAndCap:()=>An,extractSidePanelProfiles:()=>yr,normalizeFundUrl:()=>nt,normalizeProfileUrl:()=>$e,scanRelatedBlocks:()=>$n});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 nt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function $n(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,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=[],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 f=e.find(([p])=>u.includes(p));if(!f)continue;let d=f[1],m=s(a);if(!m)continue;let g=0,y=new Set;for(let p of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let h=p.href||p.getAttribute("href")||"",v=r(h);if(!v)continue;let x=p.querySelector('span[aria-hidden="true"]'),w=o(x?x.textContent:p.getAttribute("aria-label")||p.textContent),$=i(w);if(!$||y.has(v))continue;y.add(v);let R="",D=w.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(D&&(R=o(D[1])),!R){let T=p.closest("li")||p.parentElement;T&&(R=Array.from(T.querySelectorAll("p, span")).map(_=>o(_.textContent)).filter(_=>_&&_!==$&&!/^view\b/i.test(_)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(_)&&/[a-z]/i.test(_)&&_.length>2)[0]||"")}c.push({href:h,name:$,headline:R,block:d,rank:g++})}}return c}function An(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 yr(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($n,xn)}catch{return[]}return An(n,t)}var xn,Ct=ce(()=>{xn=[["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 jn={};ee(jn,{getJobDecision:()=>Cr,getLastVisit:()=>Tr,getScoutStats:()=>Rr,loadCompanies:()=>It,loadDiscoveredPeople:()=>He,loadJobDecisions:()=>_t,loadScoutedJobs:()=>Et,loadVisitLog:()=>st,recordCompany:()=>_r,recordDiscoveredEdge:()=>Ar,recordDiscoveredEdges:()=>Er,recordVisit:()=>Dr,resetCaches:()=>At,saveCompany:()=>Ir,saveDiscoveredPerson:()=>xr,saveScoutedJob:()=>kr,setJobDecision:()=>vr});import"dotenv/config";import*as V from"fs";import*as B from"path";import{fileURLToPath as wr}from"url";function de(){V.existsSync(be)||V.mkdirSync(be,{recursive:!0})}function me(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 At(){Ue=null,qe=null,Be=null,Je=null,we=null}function Et(){return Ue||(Ue=Ve(_n)||{},Ue)}function kr(e,t){if(!e)return;de();let n=Et(),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{me(_n,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function _t(){return qe||(qe=Ve(Dn)||{},qe)}function vr(e,t,n={}){if(!e||!t)return;de();let o=_t(),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{me(Dn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function Cr(e){return _t()[e]||null}function He(){return Be||(Be=Ve(rt)||{},Be)}function Ae(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function Tn(e,t){let n=$e(t)||t;if(e[n])return n;let o=Ae(t);if(!o)return n;let r=null;for(let[i,s]of Object.entries(e)){if(Ae(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 xr(e,t){if(!e)return;de();let n=He(),o=new Date().toISOString().slice(0,10),r=Tn(n,e),i=Ae(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&&Ae(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{me(rt,n)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function $r(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 Rn(e,t,n={},o){if(!t)return;let r=Ae(t);t=Tn(e,t);let i=n.seedUrl?{...n,seedUrl:$e(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=$r(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=[]),xt(a.categories,n.category),ot(a.categories,n.categories),ot(a.sectors,n.sectors),ot(a.aliases,n.aliases),r&&Ae(a.canonicalUrl||t)!==r&&xt(a.aliases,r),ot(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 Ar(e,t={}){if(!e)return;de();let n=He();Rn(n,e,t,new Date().toISOString());try{me(rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function Er(e){if(!Array.isArray(e)||e.length===0)return;de();let t=He(),n=new Date().toISOString(),o=0;for(let r of e)!r||!r.url||(Rn(t,r.url,r,n),o++);if(o)try{me(rt,t)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function _r(e={}){if(!e||!e.name)return;de();let t=e.key||nt(e.website)||nt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=It(),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{me($t,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function It(){return Je||(Je=Ve($t)||{},Je)}function Ir(e,t){if(!e)return;de();let n=It(),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{me($t,n)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}function st(){return we||(we=Ve(In)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function Dr(e,t={}){if(!e)return;de();let n=st();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{me(In,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function Tr(e){let t=st();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function Rr(){let e=Et(),t=He(),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 i=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})`),l=st(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(a)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var br,Sr,be,_n,rt,In,$t,Dn,Ue,qe,Be,xt,ot,Je,we,Dt=ce(()=>{Ct();br=wr(import.meta.url),Sr=B.dirname(B.dirname(br)),be=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join(Sr,"market-research"),_n=B.join(be,"scouted-jobs.json"),rt=B.join(be,"discovered-people.json"),In=B.join(be,"visit-log.json"),$t=B.join(be,"companies.json"),Dn=B.join(be,"job-decisions.json");Ue=null;qe=null;Be=null;xt=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},ot=(e,t)=>{if(Array.isArray(t))for(let n of t)xt(e,n)};Je=null;we=null});var Vn={};ee(Vn,{computeEngagement:()=>Rt,detectCategory:()=>Fn,detectCategoryFromTitle:()=>it,determineAction:()=>Bn,determineLastMessageBy:()=>Pn,determineSituation:()=>Mn,enrichConversation:()=>jr,enrichPerson:()=>Lr,enrichPersonContext:()=>Jn,extractAutoTags:()=>Un,generateSummary:()=>Ln,normPreview:()=>Tt});function jr(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!ht.has(l.status)),i=Or(t,e.profileUrl,n),s=Pn(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Fn(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Mn(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===fe?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=Rt(r,t),e.personContext=Jn(i),e.summary=Ln(e,t,i),e.autoTags=Un(e,t,i);let c=Bn(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Nr(e),e}function Fn(e,t,n){if(!e||e.length===0)return n?.title?it(n.title):null;let o=e.filter(r=>r.sender!==fe&&r.sender!=="Unknown"&&r.sender!=="").map(r=>r.text).join(" ");for(let[r,i]of Object.entries(On))if(i.theirMessages){for(let s of i.theirMessages)if(s.test(o))return r}if(n?.title){let r=it(n.title);if(r)return r}return null}function it(e){if(!e)return null;for(let[t,n]of Object.entries(On))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Mn(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 Nn.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!==fe&&i.sender!=="Unknown");return Nn.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Pn(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===fe)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Ln(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(`${jt(i)}: ${Ee(s,40)}`):s?r.push(Ee(s,50)):r.push(t.split(" ")[0]);let a=o.filter(g=>g.sender!==fe&&g.sender!=="Unknown").map(g=>g.text).join(" "),u=Fr(a),f=Mr(a),d=Pr(a),m=[];return u&&m.push(u),d&&d!==l&&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 Un(e,t,n){let o=[],r=(e.messages||[]).filter(a=>!ht.has(a.status)),i=r.map(a=>a.text).join(" "),s=r.filter(a=>a.sender!==fe&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=qn(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||Rt(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=>pt.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function qn(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 Bn(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Tt(e.lastMessagePreview)===Tt(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let r=(e.messages||[]).find(i=>pt.has(i.status));return r?r.status===te.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:`${jt(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 Rt(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===fe?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 Jn(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Nr(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 Or(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 Tt(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function jt(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 Fr(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 Mr(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 Pr(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 Lr(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=it(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Ur(e),e.personSummary=qr(e),e.personAutoTags=Br(e);let n=Jr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Vr(e)),e}function Ur(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 qr(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 Br(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=qn("",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 Jr(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:`${jt(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Vr(e){let t=e.category;if(!t)return null;let n=Hr(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 Hr(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 On,Nn,Hn=ce(async()=>{await gt();await tt();On={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]}};Nn=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Gn={};ee(Gn,{DEFAULT_PROFILE_INTERESTS:()=>Wn,computeFit:()=>Yr,detectSectors:()=>Gr});function Gr(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(Wr))r.some(i=>i.test(t))&&n.push(o);return n}function Yr(e,t=Wn){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 Wr,Wn,Yn=ce(()=>{Wr={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/]};Wn={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Xs from"puppeteer";import"dotenv/config";import*as J from"fs";import*as ue from"path";import{fileURLToPath as Vo}from"url";import"dotenv/config";import{createGraphClient as Lo,resolveToken as Uo}from"@ilivemylife/graph-sdk";import{config as qo}from"dotenv";qo();var tn=Uo()||process.env.TOKEN;tn||(console.error(`
|
|
239
239
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
240
240
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
241
241
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
242
|
-
`),process.exit(1));var
|
|
242
|
+
`),process.exit(1));var nn=Lo({token:tn});function Bo(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Jo({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Bo(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${l} \u2014 ${s}${c}`}async function on({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(o)||o.length===0)return;let l=`**${Jo({scriptName:e,mode:t,status:n,error:r,duration:i})}**
|
|
243
243
|
|
|
244
244
|
${o.join(`
|
|
245
|
-
`)}`;try{await Qt.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var No=jo(import.meta.url),Oo=ue.dirname(ue.dirname(No)),at=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(Oo,"collected-profiles"),ct=ue.join(at,"run-log.json");function Fo(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 Xt(){try{if(!J.existsSync(ct))return{runs:[]};let e=JSON.parse(J.readFileSync(ct,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function en(e){J.existsSync(at)||J.mkdirSync(at,{recursive:!0});try{Fo(ct,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function tn(e,t="default"){let n=Xt();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 i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),en(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ut(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=Xt(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}en(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Zt({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Ke();Ke();await Xe();async function Hn(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 Vn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Lr(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 e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await Hn(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 f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=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 A=(C||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(A)},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"))],_=Array.from(R.querySelectorAll("h2")),X=k.find(C=>{let A=C.textContent&&C.textContent.trim(),E=(A||"").replace(/\s*\(\d+\)$/,"").trim();return A&&A.length>1&&A.length<100&&!w.has(E)&&!x.has(E)}),K=X?X.textContent.trim():null,L=X?X.parentElement:null;for(;L&&L!==R&&!Array.from(L.children).filter(A=>A.tagName==="P").some(A=>{let E=A.textContent&&A.textContent.trim();return E&&E.length>5&&!T(E)});)L=L.parentElement;let le=null,De=null,Re=null,Te=null;if(L&&L!==R){let C=Array.from(L.children).filter(E=>E.tagName==="P").filter(E=>{let ae=E.textContent&&E.textContent.trim();return ae&&ae.length>5&&!T(ae)});if(C[0]&&(le=C[0].textContent.trim()),C[1]){let E=C[1].textContent.trim().split(/\s*[·•]\s*/);De=E[0]||null,E.length>1&&(Re=E.slice(1).join(" \xB7 "))}let A=Array.from(L.children).filter(E=>E.tagName==="DIV");for(let E=A.length-1;E>=0;E--){let ae=A[E].textContent&&A[E].textContent.trim();if(ae&&!(K&&ae.startsWith(K))&&(Te=ae.split(/[·•]/)[0].trim(),Te))break}}let Ge=null;if(L){let C=L.querySelectorAll("p, span, div");for(let A of C){let E=(A.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ge=E;break}}}let j=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),F=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=F&&F.src||null,N=R.textContent||"",z=null,Bt=N.match(/(\d+\+?)\s+connections\b/i);Bt&&(z=Bt[1]+" connections");let Ye=null,Jt=N.match(/(\d+)\s+mutual connection/i),Vt=N.match(/and\s+(\d+)\s+other mutual/i),vo=N.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Jt?Ye=parseInt(Jt[1],10):Vt?Ye=2+parseInt(Vt[1],10):vo&&(Ye=2);let Ht=null,Wt=null,Gt=_.find(C=>C.textContent&&C.textContent.trim()==="About");if(Gt){let C=Gt.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let A=(C.textContent||"").trim();A=A.replace(/^About\s*/,"").trim();let E=A.match(/Top skills\s*(.+?)$/i);if(E){let lt=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ao=>Ao.trim()).filter(Boolean);lt.length>0&<.length<10&&(Wt=lt)}A=A.split(/\n?…\s*more/i)[0].trim(),A=A.split(/\n?\.\.\.\s*more/i)[0].trim(),A=A.split(/\bTop skills\b/i)[0].trim(),A=A.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ht=A||null}}let Yt=null,Kt=_.find(C=>C.textContent&&C.textContent.trim()==="Activity");if(Kt){let C=Kt.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let A=(C.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);A&&(Yt=parseInt(A[1].replace(/,/g,""),10))}}let Co=[...new Set(_.map(C=>(C.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(C=>C&&C.length>1&&C.length<60&&C!==K).filter(C=>w.has(C)))],je=document.body.textContent||"",$o=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),xo=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:K,title:le,location:Te,currentCompany:De,currentSchool:Re,connectionDegree:Ge,hasVerifiedBadge:j,photoUrl:P,connectionsLevel:z,mutualConnectionsCount:Ye,followers:Yt,openToWork:$o,hiring:xo,about:Ht,topSkills:Wt,availableSections:Co}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,g=null,y=null,p=null,h=null,v=null;if(o||r||i||s||c||l){let w=await Promise.resolve().then(()=>(wn(),yn));o&&(m=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(g=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),i&&(y=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),s&&(p=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),c&&(h=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${h.length} entries`)),l&&(v=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...g!==null&&{featured:g},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...h!==null&&{recommendations:h},...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 _e(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=f=>f&&!f.closest(r),s=f=>Array.from(document.querySelectorAll(f)).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(f=>f.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 Rt(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],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of d){let p=y.getBoundingClientRect();if(p.width===0||p.height===0||y.closest(g))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(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(p=>{let h=p.getAttribute("aria-label")||"";return(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&m.test(h)}).map(p=>p.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]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let p of m){if(p.closest(g))continue;let h=p.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(h)&&(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&y.test(h))return p}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():"",i=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),g=f.className.includes("sticky-header")||f.className.includes("sticky"),y=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(f.getAttribute("aria-label")||"").toLowerCase(),h=p.includes("invite"),v=d?p.includes(d):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:h,matchesName:v,ariaLabel:p}},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(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,g=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:g,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 g=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",p=m.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let g of d.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==f)return g;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 S(500),await e.evaluate(d=>d.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 d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let g of m){let y=g.querySelector('a[href*="custom-invite"]');if(y)return y;for(let p of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(p.innerText?.trim()==="Connect")return p}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 g of d)for(let y of g.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&m.push(p)}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 l=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 g=d.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}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 Pr(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(f=>f.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 Ur(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 Rt(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 Ie(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ie(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 qr(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=wt();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 Br(e,t,n);return s.connectionSent&&!i&&hn(t,o),s}async function Br(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(`
|
|
246
|
-
--- Connecting: ${a} ---`),c.length>0){let h=re()[t]?.location;if(Vn(h,c))return console.log(` \u26A0 Excluded location (stored): ${h}`),l.reason="excluded_location",l.profileInfo={location:h},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await Hn(e,t),await S(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:h,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(St(),vn)),{recordDiscoveredEdges:$}=await Promise.resolve().then(()=>(Et(),_n)),{detectCategoryFromTitle:w}=await Un().then(()=>Pn),{detectSectors:x}=await Promise.resolve().then(()=>(Jn(),Bn)),T=v(t)||t,D=await h(e,{seedUrl:T}),R=D.map(k=>{let _=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:_?[_]:[],sectors:x(k.headline||"")}});$(R),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(h){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${h.message}`)}l.profileInfo=await e.evaluate(()=>{let h=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=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},$={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 $;let x=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],T=Array.from(w.querySelectorAll("h2")),D=x.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!h.has(F)&&F!=="0 notifications"}),R=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==w&&!Array.from(k.children).filter(P=>P.tagName==="P").some(P=>{let N=P.textContent&&P.textContent.trim();return N&&N.length>5&&!v(N)});)k=k.parentElement;let _=null,X=null,K=null;if(k&&k!==w){let j=Array.from(k.children),F=j.filter(N=>N.tagName==="P").filter(N=>{let z=N.textContent&&N.textContent.trim();return z&&z.length>5&&!v(z)});F[0]&&(_=F[0].textContent.trim()),F[1]&&(X=F[1].textContent.trim());let P=j.filter(N=>N.tagName==="DIV");for(let N=P.length-1;N>=0;N--){let z=P[N].textContent&&P[N].textContent.trim();if(z&&!(R&&z.startsWith(R))&&(K=z.split(/[·•]/)[0].trim(),K))break}}let L=null;if(k){let j=k.querySelectorAll("p, span, div");for(let F of j){let P=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){L=P;break}}}let le=null,De=T.find(j=>j.textContent&&j.textContent.trim()==="About");if(De){let j=De.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(le=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,le&&(le=le.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let Re=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Te=Re&&Re.src||null,Ge=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:_,location:K,about:le,company:X,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:Te,hasVerifiedBadge:Ge}});try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(l.resolvedUrl=h.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let h=l.profileInfo?.location,v=re()[t]?.location,$=h||v;if(Vn($,c))return console.log(` \u26A0 Excluded location (${h?"live":"stored"}): ${$}`),l.reason="excluded_location",l;!h&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await _e(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await ge(e);let d=await Rt(e);if(d||await ge(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),d=await Rt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let h=await _e(e,{detail:!0});return s&&(h.status==="connected"||h.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=d.method;let m=await Pr(e,d.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 h=await _e(e);if(h==="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: ${h} \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 $=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($){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),$),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 _e(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($){return console.log(" More dropdown failed:",$.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 h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of h){let $=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!$)continue;let w=($.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||$.querySelector('input[type="email"], input[name="email"]'))return!0;let x=$.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 h=await e.$('button[aria-label="Dismiss"]');if(h)try{await h.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"]'),p=await e.$('button[aria-label="Send without a note"]');if(!y&&!p){let h=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let $=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!$,sendWithout:!!w}});if(h.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(h.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));p=v?.asElement?.()||null,p||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 $=await Ur(e);return l.success=$,l.connectionSent=$,l.reason=$?"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 $=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",$);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 Ie(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(p)return console.log(" Sending without note..."),await Ie(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(y&&!o){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h)return await Ie(e,h)?(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 h=p;if(h)return await Ie(e,h)?(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(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 S(4e3)),await ge(e),await S(500);let v=await e.$$('button[id*="profile-overflow-action"]'),$=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){$=w;break}}!$&&v.length>0&&($=v[v.length-1]);for(let w of v)w!==$&&await w.dispose().catch(()=>{});if($)try{await e.evaluate(x=>x.scrollIntoView({behavior:"smooth",block:"center"}),$),await S(500),await $.click().catch(()=>e.evaluate(x=>x.click(),$)),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 _e(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 _e(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 Ie(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 Wn(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,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!s){let m=
|
|
245
|
+
`)}`;try{await nn.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Ho=Vo(import.meta.url),Wo=ue.dirname(ue.dirname(Ho)),ft=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(Wo,"collected-profiles"),dt=ue.join(ft,"run-log.json");function Go(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 rn(){try{if(!J.existsSync(dt))return{runs:[]};let e=JSON.parse(J.readFileSync(dt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function sn(e){J.existsSync(ft)||J.mkdirSync(ft,{recursive:!0});try{Go(dt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ln(e,t="default"){let n=rn();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 i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),sn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function mt(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=rn(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}sn(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";on({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Qe();Qe();await tt();async function zn(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 Kn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Kr(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 e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(1500),await zn(e,t));let u=0;for(let w=0;w<2;w++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let D=1;D<=6;D++)await e.evaluate(T=>window.scrollTo(0,T),$*D/6),await S(900);let R=await e.evaluate(()=>document.body.scrollHeight);if(R===u)break;u=R}await S(800);let f=null;try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(f=w.split("?")[0].replace(/\/+$/,""))}catch{}let d=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"]),$=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=C=>{let A=(C||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(A)},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:[]},T=document.querySelector("main");if(!T)return D;let k=[...Array.from(T.querySelectorAll("h1")),...Array.from(T.querySelectorAll("h2"))],_=Array.from(T.querySelectorAll("h2")),X=k.find(C=>{let A=C.textContent&&C.textContent.trim(),E=(A||"").replace(/\s*\(\d+\)$/,"").trim();return A&&A.length>1&&A.length<100&&!w.has(E)&&!$.has(E)}),K=X?X.textContent.trim():null,P=X?X.parentElement:null;for(;P&&P!==T&&!Array.from(P.children).filter(A=>A.tagName==="P").some(A=>{let E=A.textContent&&A.textContent.trim();return E&&E.length>5&&!R(E)});)P=P.parentElement;let le=null,De=null,Te=null,Re=null;if(P&&P!==T){let C=Array.from(P.children).filter(E=>E.tagName==="P").filter(E=>{let ae=E.textContent&&E.textContent.trim();return ae&&ae.length>5&&!R(ae)});if(C[0]&&(le=C[0].textContent.trim()),C[1]){let E=C[1].textContent.trim().split(/\s*[·•]\s*/);De=E[0]||null,E.length>1&&(Te=E.slice(1).join(" \xB7 "))}let A=Array.from(P.children).filter(E=>E.tagName==="DIV");for(let E=A.length-1;E>=0;E--){let ae=A[E].textContent&&A[E].textContent.trim();if(ae&&!(K&&ae.startsWith(K))&&(Re=ae.split(/[·•]/)[0].trim(),Re))break}}let Ke=null;if(P){let C=P.querySelectorAll("p, span, div");for(let A of C){let E=(A.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ke=E;break}}}let j=!!T.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),F=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),L=F&&F.src||null,N=T.textContent||"",z=null,Gt=N.match(/(\d+\+?)\s+connections\b/i);Gt&&(z=Gt[1]+" connections");let ze=null,Yt=N.match(/(\d+)\s+mutual connection/i),Kt=N.match(/and\s+(\d+)\s+other mutual/i),jo=N.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Yt?ze=parseInt(Yt[1],10):Kt?ze=2+parseInt(Kt[1],10):jo&&(ze=2);let zt=null,Qt=null,Zt=_.find(C=>C.textContent&&C.textContent.trim()==="About");if(Zt){let C=Zt.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let A=(C.textContent||"").trim();A=A.replace(/^About\s*/,"").trim();let E=A.match(/Top skills\s*(.+?)$/i);if(E){let ut=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Mo=>Mo.trim()).filter(Boolean);ut.length>0&&ut.length<10&&(Qt=ut)}A=A.split(/\n?…\s*more/i)[0].trim(),A=A.split(/\n?\.\.\.\s*more/i)[0].trim(),A=A.split(/\bTop skills\b/i)[0].trim(),A=A.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),zt=A||null}}let Xt=null,en=_.find(C=>C.textContent&&C.textContent.trim()==="Activity");if(en){let C=en.parentElement;for(;C&&C.tagName!=="SECTION";)C=C.parentElement;if(C){let A=(C.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);A&&(Xt=parseInt(A[1].replace(/,/g,""),10))}}let No=[...new Set(_.map(C=>(C.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(C=>C&&C.length>1&&C.length<60&&C!==K).filter(C=>w.has(C)))],je=document.body.textContent||"",Oo=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),Fo=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:K,title:le,location:Re,currentCompany:De,currentSchool:Te,connectionDegree:Ke,hasVerifiedBadge:j,photoUrl:L,connectionsLevel:z,mutualConnectionsCount:ze,followers:Xt,openToWork:Oo,hiring:Fo,about:zt,topSkills:Qt,availableSections:No}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,g=null,y=null,p=null,h=null,v=null;if(o||r||i||s||c||l){let w=await Promise.resolve().then(()=>(Cn(),vn));o&&(m=await w.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(g=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${g.length} entries`)),i&&(y=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),s&&(p=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),c&&(h=await w.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${h.length} entries`)),l&&(v=await w.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...g!==null&&{featured:g},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...h!==null&&{recommendations:h},...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 _e(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=f=>f&&!f.closest(r),s=f=>Array.from(document.querySelectorAll(f)).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(f=>f.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 Nt(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],g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of d){let p=y.getBoundingClientRect();if(p.width===0||p.height===0||y.closest(g))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(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),g=document.querySelectorAll("button[aria-label]");return Array.from(g).filter(p=>{let h=p.getAttribute("aria-label")||"";return(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&m.test(h)}).map(p=>p.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]"),g='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',y=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let p of m){if(p.closest(g))continue;let h=p.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(h)&&(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&y.test(h))return p}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():"",i=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),g=f.className.includes("sticky-header")||f.className.includes("sticky"),y=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(f.getAttribute("aria-label")||"").toLowerCase(),h=p.includes("invite"),v=d?p.includes(d):!0;return{isMuted:m,isStickyHeader:g,inRecommendations:y,hasInvite:h,matchesName:v,ariaLabel:p}},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(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,g=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:g,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 g=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",p=m.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:g==="Follow"||g==="Message"||g==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let g of d.querySelectorAll("button"))if(g.innerText?.trim()==="More"&&g!==f)return g;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 S(500),await e.evaluate(d=>d.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 d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let g of m){let y=g.querySelector('a[href*="custom-invite"]');if(y)return y;for(let p of g.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(p.innerText?.trim()==="Connect")return p}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 g of d)for(let y of g.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&m.push(p)}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 l=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 g=d.getBoundingClientRect();if(!(g.width===0||g.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}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 zr(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(f=>f.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 Qr(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 Nt(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 Ie(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ie(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 Zr(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=kt();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 Xr(e,t,n);return s.connectionSent&&!i&&Sn(t,o),s}async function Xr(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(`
|
|
246
|
+
--- Connecting: ${a} ---`),c.length>0){let h=re()[t]?.location;if(Kn(h,c))return console.log(` \u26A0 Excluded location (stored): ${h}`),l.reason="excluded_location",l.profileInfo={location:h},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(5e3),await ge(e)&&(console.log(" Dismissed Premium overlay"),await S(2e3),await zn(e,t),await S(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:h,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(Ct(),En)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Dt(),jn)),{detectCategoryFromTitle:w}=await Hn().then(()=>Vn),{detectSectors:$}=await Promise.resolve().then(()=>(Yn(),Gn)),R=v(t)||t,D=await h(e,{seedUrl:R}),T=D.map(k=>{let _=k.headline?w(k.headline):null;return{url:k.url,seedUrl:R,block:k.block,rank:k.rank,name:k.name,headline:k.headline,categories:_?[_]:[],sectors:$(k.headline||"")}});x(T),D.length&&console.log(` \xB7 discovery: harvested ${D.length} related profiles`)}catch(h){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${h.message}`)}l.profileInfo=await e.evaluate(()=>{let h=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=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},x={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 x;let $=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],R=Array.from(w.querySelectorAll("h2")),D=$.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!h.has(F)&&F!=="0 notifications"}),T=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==w&&!Array.from(k.children).filter(L=>L.tagName==="P").some(L=>{let N=L.textContent&&L.textContent.trim();return N&&N.length>5&&!v(N)});)k=k.parentElement;let _=null,X=null,K=null;if(k&&k!==w){let j=Array.from(k.children),F=j.filter(N=>N.tagName==="P").filter(N=>{let z=N.textContent&&N.textContent.trim();return z&&z.length>5&&!v(z)});F[0]&&(_=F[0].textContent.trim()),F[1]&&(X=F[1].textContent.trim());let L=j.filter(N=>N.tagName==="DIV");for(let N=L.length-1;N>=0;N--){let z=L[N].textContent&&L[N].textContent.trim();if(z&&!(T&&z.startsWith(T))&&(K=z.split(/[·•]/)[0].trim(),K))break}}let P=null;if(k){let j=k.querySelectorAll("p, span, div");for(let F of j){let L=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(L==="1st"||L==="2nd"||L==="3rd"){P=L;break}}}let le=null,De=R.find(j=>j.textContent&&j.textContent.trim()==="About");if(De){let j=De.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(le=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,le&&(le=le.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]'),Re=Te&&Te.src||null,Ke=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:T,title:_,location:K,about:le,company:X,connectionDegree:P,connectionsCount:null,mutualConnections:null,photoUrl:Re,hasVerifiedBadge:Ke}});try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(l.resolvedUrl=h.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let h=l.profileInfo?.location,v=re()[t]?.location,x=h||v;if(Kn(x,c))return console.log(` \u26A0 Excluded location (${h?"live":"stored"}): ${x}`),l.reason="excluded_location",l;!h&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await _e(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await ge(e);let d=await Nt(e);if(d||await ge(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await S(2e3),d=await Nt(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let h=await _e(e,{detail:!0});return s&&(h.status==="connected"||h.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=d.method;let m=await zr(e,d.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 h=await _e(e);if(h==="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: ${h} \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 x=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(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(R=>R.click(),x),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 _e(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(x){return console.log(" More dropdown failed:",x.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 h=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let v of h){let x=v.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!x)continue;let w=(x.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(w)||x.querySelector('input[type="email"], input[name="email"]'))return!0;let $=x.querySelector('button[aria-label="Send without a note"]');if($&&($.disabled||$.getAttribute("aria-disabled")==="true"||($.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let h=await e.$('button[aria-label="Dismiss"]');if(h)try{await h.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"]'),p=await e.$('button[aria-label="Send without a note"]');if(!y&&!p){let h=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let x=v.querySelector('button[aria-label="Add a note"]'),w=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!w}});if(h.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(h.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));p=v?.asElement?.()||null,p||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 x=await Qr(e);return l.success=x,l.connectionSent=x,l.reason=x?"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 x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),w=o.replace("{name}",x);await v.type(w,{delay:20}),await S(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($)return await Ie(e,$)?(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(p)return console.log(" Sending without note..."),await Ie(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(y&&!o){console.log(" No message provided, sending without note...");let h=await e.$('button[aria-label="Send without a note"]');if(h)return await Ie(e,h)?(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 h=p;if(h)return await Ie(e,h)?(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(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 S(4e3)),await ge(e),await S(500);let v=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let w of v){let $=await e.evaluate(R=>{let D=R.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!R.closest('.sticky-header, [class*="sticky"]')}},w);if($.visible&&!$.inSticky){x=w;break}}!x&&v.length>0&&(x=v[v.length-1]);for(let w of v)w!==x&&await w.dispose().catch(()=>{});if(x)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),x),await S(500),await x.click().catch(()=>e.evaluate($=>$.click(),x)),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(T=>T.click(),w),await S(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await S(3e3),await _e(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 _e(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 Ie(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 Qn(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,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
247
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${s?"View Only":`Connect (max ${i})`}`),s||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!s){let m=vt();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 g=t[m];try{if(e.isClosed()){console.log(`
|
|
248
248
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
249
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=
|
|
249
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=gn(g.profileUrl);if(y==="pending"||y==="connected"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl} \u2014 skipped (db: ${y})`),y==="pending"||y==="sent_with_note"||y==="sent_without_note"||y==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(g,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${g.name||g.profileUrl}`);let p=null;if(s){let h=await Kr(e,g.profileUrl);h?(Ze(g.profileUrl,{...h,source:u}),f.viewed++,p={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h,resolvedUrl:h.resolvedUrl}):(f.errors++,p={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let h=kt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(p=await Zr(e,g.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:u,skipQuotaGate:!0}),p.success)f.connectionsSent++;else switch(p.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(p?.fatal){console.log(`
|
|
250
250
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(p?.reason==="error"){if(d++,d>=3){console.log(`
|
|
251
|
-
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(p&&p.reason&&(
|
|
252
|
-
=== 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=bt();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 U from"fs";import*as se from"path";import{fileURLToPath as Jr}from"url";var Vr=Jr(import.meta.url),Hr=se.dirname(se.dirname(Vr)),We=process.env.DATA_DIR?se.resolve(process.env.DATA_DIR,"collected-profiles"):se.join(Hr,"collected-profiles");function Tt(){U.existsSync(We)||U.mkdirSync(We,{recursive:!0})}function Wr(){return new Date().toISOString().split("T")[0]}function Gn(e,t=null){let n=t||Wr();return se.join(We,`${e}-${n}.json`)}function Yn(e,t=null){Tt();let n=Gn(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 Kn(e,t=null){return Yn(e,t).filter(o=>!o.processed)}function zn(e,t,n,o=null){Tt();let r=Gn(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 Qn(e){let t=Yn(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 Zn(){Tt();try{return U.readdirSync(We).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(se.join(We,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 Ut from"os";import*as I from"path";import{fileURLToPath as gs}from"url";var Ot={};ee(Ot,{NAME:()=>Yr,VERSION:()=>Gr,up:()=>Qr});import*as H from"fs";import*as st from"path";var Gr=1,Yr="normalize-jobs-and-questions",Kr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],zr=50;function jt(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Nt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.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 Qr(e,t){let n=st.join(e,"jobs.json"),o=st.join(t,"scouted-jobs.json"),r=st.join(e,"application-questions.json"),i=jt(n)||{},s=jt(o)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let m of Kr)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),c++}c>0?(Nt(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=jt(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 g=(d.questions||[]).map(y=>{let p={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=zr?p.options=y.options:(p.optionsOmitted=!0,f++)),y.page&&(p.page=y.page),y.wasPreFilled&&(p.wasPreFilled=!0),y.wasRetry&&(p.wasRetry=!0),p});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||g.length,questions:g})}Nt(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(l.length>0){for(let u of l)delete s[u];Nt(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 Ft={};ee(Ft,{NAME:()=>Xr,VERSION:()=>Zr,up:()=>ns});import*as W from"fs";import*as Xn from"path";var Zr=2,Xr="reset-unread-flags";function es(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function ts(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 ns(e){let t=Xn.join(e,"conversations.json"),n=es(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}ts(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Mt={};ee(Mt,{NAME:()=>rs,VERSION:()=>os,up:()=>cs});import*as G from"fs";import*as eo from"path";var os=3,rs="recompute-last-message-by",ss=new Set(["draft","confirmed","rejected","needs_review"]);function is(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function ls(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}}function as(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!ss.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 cs(e){let t=eo.join(e,"conversations.json"),n=is(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=as(a,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}ls(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 Lt={};ee(Lt,{NAME:()=>fs,VERSION:()=>us,up:()=>hs});import*as Y from"fs";import*as to from"path";var us=4,fs="split-connection-timestamps",ds=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ms(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ps(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}}async function hs(e){let t=to.join(e,"people.json"),n=ms(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++,ds.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}ps(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 Xe();Et();var ys=gs(import.meta.url),ws=I.dirname(ys),bs=I.dirname(I.dirname(ws));function Ss(e){return e&&(e==="~"?Ut.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(Ut.homedir(),e.slice(2)):e)}var Q=process.env.DATA_DIR?I.resolve(Ss(process.env.DATA_DIR)):bs,ke=I.join(Q,"collected-profiles"),ve=I.join(Q,"market-research"),q=I.join(Q,".schema-version"),no=[I.join(ke,".schema-version"),I.join(ve,".schema-version")],pe=4,ie=[{version:1,module:Ot},{version:2,module:Ft},{version:3,module:Mt},{version:4,module:Lt}];(function(){ie.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ie){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=ie.length?ie[ie.length-1].version:0;if(n!==pe)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${pe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ie.length;o++){let r=o+1;if(ie[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ie[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 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(p&&p.reason&&(yn(g.profileUrl,p.reason,{method:p.method,messageSent:p.messageSent,profileInfo:p.profileInfo}),p.resolvedUrl&&wn(g.profileUrl,p.resolvedUrl),hn(g.profileUrl,{source:u||"funnel",jobId:g.jobId||g.fromJob?.jobId||null,jobTitle:g.fromJob?.title||null,jobCompany:g.fromJob?.company||null,action:p.reason})),l&&await l(g,f,p),m<t.length-1){let h=c+Math.random()*2e3;await S(h)}}if(console.log(`
|
|
252
|
+
=== 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=vt();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 U from"fs";import*as se from"path";import{fileURLToPath as es}from"url";var ts=es(import.meta.url),ns=se.dirname(se.dirname(ts)),We=process.env.DATA_DIR?se.resolve(process.env.DATA_DIR,"collected-profiles"):se.join(ns,"collected-profiles");function Ot(){U.existsSync(We)||U.mkdirSync(We,{recursive:!0})}function os(){return new Date().toISOString().split("T")[0]}function Zn(e,t=null){let n=t||os();return se.join(We,`${e}-${n}.json`)}function Xn(e,t=null){Ot();let n=Zn(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 eo(e,t=null){return Xn(e,t).filter(o=>!o.processed)}function to(e,t,n,o=null){Ot();let r=Zn(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 no(e){let t=Xn(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 oo(){Ot();try{return U.readdirSync(We).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(se.join(We,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 Jt from"os";import*as I from"path";import{fileURLToPath as Es}from"url";var Pt={};ee(Pt,{NAME:()=>ss,VERSION:()=>rs,up:()=>as});import*as H from"fs";import*as lt from"path";var rs=1,ss="normalize-jobs-and-questions",is=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ls=50;function Ft(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function Mt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.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 as(e,t){let n=lt.join(e,"jobs.json"),o=lt.join(t,"scouted-jobs.json"),r=lt.join(e,"application-questions.json"),i=Ft(n)||{},s=Ft(o)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let f=s[u],d=i[u];for(let m of is)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),c++}c>0?(Mt(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Ft(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 g=(d.questions||[]).map(y=>{let p={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=ls?p.options=y.options:(p.optionsOmitted=!0,f++)),y.page&&(p.page=y.page),y.wasPreFilled&&(p.wasPreFilled=!0),y.wasRetry&&(p.wasRetry=!0),p});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||g.length,questions:g})}Mt(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(l.length>0){for(let u of l)delete s[u];Mt(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 Lt={};ee(Lt,{NAME:()=>us,VERSION:()=>cs,up:()=>ms});import*as W from"fs";import*as ro from"path";var cs=2,us="reset-unread-flags";function fs(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function ds(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 ms(e){let t=ro.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}ds(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ut={};ee(Ut,{NAME:()=>hs,VERSION:()=>ps,up:()=>Ss});import*as G from"fs";import*as so from"path";var ps=3,hs="recompute-last-message-by",gs=new Set(["draft","confirmed","rejected","needs_review"]);function ys(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function ws(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}}function bs(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!gs.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 Ss(e){let t=so.join(e,"conversations.json"),n=ys(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=bs(a,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=f,r++}if(r===0){console.log(" No conversations to recompute.");return}ws(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 qt={};ee(qt,{NAME:()=>vs,VERSION:()=>ks,up:()=>As});import*as Y from"fs";import*as io from"path";var ks=4,vs="split-connection-timestamps",Cs=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function xs(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function $s(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}}async function As(e){let t=io.join(e,"people.json"),n=xs(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++,Cs.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}$s(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 tt();Dt();var _s=Es(import.meta.url),Is=I.dirname(_s),Ds=I.dirname(I.dirname(Is));function Ts(e){return e&&(e==="~"?Jt.homedir():e.startsWith("~/")||e.startsWith("~\\")?I.join(Jt.homedir(),e.slice(2)):e)}var Q=process.env.DATA_DIR?I.resolve(Ts(process.env.DATA_DIR)):Ds,ke=I.join(Q,"collected-profiles"),ve=I.join(Q,"market-research"),q=I.join(Q,".schema-version"),lo=[I.join(ke,".schema-version"),I.join(ve,".schema-version")],pe=4,ie=[{version:1,module:Pt},{version:2,module:Lt},{version:3,module:Ut},{version:4,module:qt}];(function(){ie.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ie){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=ie.length?ie[ie.length-1].version:0;if(n!==pe)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${pe}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ie.length;o++){let r=o+1;if(ie[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ie[o].version}`)}})();function fo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
253
253
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
254
254
|
`),process.exit(1));try{b.mkdirSync(Q,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
255
255
|
[FATAL] Cannot create DATA_DIR (${Q}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -259,48 +259,48 @@ ${o.join(`
|
|
|
259
259
|
[FATAL] DATA_DIR (${Q}) 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.
|
|
260
260
|
`),process.exit(1));for(let t of[ke,ve]){let n;try{n=b.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
261
261
|
[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.
|
|
262
|
-
`),process.exit(1))}}var Se=I.join(Q,".migration-lock");function
|
|
262
|
+
`),process.exit(1))}}var Se=I.join(Q,".migration-lock");function Rs(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync(Se,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync(Se,"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,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}o&&i<r&&(console.error(`
|
|
263
263
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Se}
|
|
264
264
|
`),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.
|
|
265
|
-
`),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Se+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,Se),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function
|
|
265
|
+
`),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Se+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,Se),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Vt(){try{if(JSON.parse(b.readFileSync(Se,"utf-8")).pid!==process.pid)return;b.unlinkSync(Se)}catch{}}var ao=!1;function js(){if(ao)return;ao=!0;let e=()=>{try{Vt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ns(){if(b.existsSync(q))return;let e=[],t=[];for(let i of lo)if(b.existsSync(i))try{e.push({file:i,schema:at(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
|
|
266
266
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
267
267
|
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.
|
|
268
268
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
|
|
269
269
|
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
270
|
-
`),process.exit(1)}let o=e[0].schema,r=q+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,q)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of
|
|
270
|
+
`),process.exit(1)}let o=e[0].schema,r=q+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,q)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of lo)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${q}`)}function Os(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 at(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function co(){if(Ns(),!b.existsSync(q))return{version:0,migrations:[]};let e;try{e=at(q)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
271
271
|
[FATAL] ${q} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
272
|
-
`),process.exit(1)}let t
|
|
272
|
+
`),process.exit(1)}let t=Os(e);return t===null&&(console.error(`
|
|
273
273
|
[FATAL] ${q} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
274
|
-
`),process.exit(1)),t}function
|
|
274
|
+
`),process.exit(1)),t}function mo(e){try{b.chmodSync(e,384)}catch{}}function Fs(e){if(fo(),b.existsSync(q))try{if(b.lstatSync(q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${q}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=q+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),mo(t),b.renameSync(t,q)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function uo(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return b.statSync(I.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=I.join(e,c),a=I.join(e,c+n);if(b.existsSync(a)){i++;continue}try{ho(l,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(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${I.basename(e)}/ (${n})${c}`)}}var Bt=!1;async function po(){if(Bt)return;fo(),qs();let t=co().version;if(t===pe){Bt=!0;return}js(),Rs(),process.on("exit",Vt),t>pe&&(console.error(`
|
|
275
275
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${pe}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
276
276
|
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${pe}.
|
|
277
277
|
`),process.exit(1)),console.log(`
|
|
278
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=
|
|
278
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=Bs();if(!n.ok){console.error(`
|
|
279
279
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
280
280
|
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'.
|
|
281
281
|
`),process.exit(1)}let o=ie.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
282
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{
|
|
282
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{uo(ke,r.version),uo(ve,r.version)}catch(l){console.error(`
|
|
283
283
|
[FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
284
284
|
`),process.exit(1)}let c=r.module;try{await c.up(ke,ve)}catch(l){console.error(`
|
|
285
|
-
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=
|
|
285
|
+
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=Js(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.
|
|
286
286
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
287
287
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
288
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:l},u=
|
|
288
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:l},u=co();u.version=r.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Fs(u)}catch(l){console.error(`
|
|
289
289
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
290
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
290
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{mn()}catch{}try{At()}catch{}Bt=!0,Vt(),console.log(`
|
|
291
291
|
\u2713 Schema is now at v${pe}
|
|
292
|
-
`)}var
|
|
292
|
+
`)}var Ms=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Ps(e){let t=e.toLowerCase();return Ms.some(n=>n.test(t))}var Ls=6e4;function Us(){let e=Date.now(),t=[];for(let n of[Q,ke,ve]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!Ps(r))continue;let i=I.join(n,r);try{let s=b.statSync(i);if(!s.isFile()||e-s.mtimeMs<Ls)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function qs({verbose:e=!1}={}){let t=Us();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${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 Bs(){let e=[];for(let t of[ke,ve]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=I.join(t,o);try{at(r)}catch(i){e.push({dir:I.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Js(e){let t=[],n=[];for(let i of[ke,ve]){if(!b.existsSync(i))continue;let s=b.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=I.join(i,c),a=c.slice(0,-e.length),u=I.join(i,a);try{a.toLowerCase().endsWith(".json")?at(l):b.accessSync(l,b.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${I.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{ho(i,s),o++}catch(a){r.push(`${I.basename(l)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function ho(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),mo(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}import Z from"fs";import he from"path";var Vs="cookies.json";function go(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin","cookies.json"):Vs}function yo(){let e=go();if(!Z.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Z.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 wo(){return Z.existsSync(go())}function Hs(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin"):"."}function bo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ws(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?bo(t[1]):"default"}function So(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Z.existsSync(t)||Z.mkdirSync(t,{recursive:!0}),he.resolve(t);let n=bo(e||Ws()),o=he.join(Hs(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),he.resolve(o)}var ko=".ilml-seeded";function vo(e){return!Z.existsSync(he.join(e,ko))}function Co(e){try{Z.writeFileSync(he.join(e,ko),new Date().toISOString())}catch{}}function xo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Z.rmSync(he.join(e,n),{force:!0}),t++}catch{}return t}import Ht from"fs";import Gs from"path";var Ys={headless:!1,defaultViewport:null,protocolTimeout:3e5},Ye=new Set,$o=!1;async function ct(){let e=[...Ye].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});Ye.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Ks(){if($o)return;$o=!0;let e=t=>async()=>{await ct(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ct(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ct(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ct(),process.exit(0))}),process.on("exit",()=>{for(let t of Ye)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Wt(e){return Gs.join(e,".ilml-browser-session.json")}function Io(e,t={}){try{Ht.writeFileSync(Wt(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function zs(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Io(e,n?{wsEndpoint:n}:{})}catch{}}function Qs(e){let t=Do(e);t&&t.ownerPid===process.pid&&Ge(e)}function Ge(e){try{Ht.rmSync(Wt(e),{force:!0})}catch{}}function Do(e){try{return JSON.parse(Ht.readFileSync(Wt(e),"utf-8"))}catch{return null}}function Ao(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Eo(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function _o(e,t,{probeTimeoutMs:n=4e3}={}){let o=Do(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ao(o.ownerPid)?"live":(Ge(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await Eo(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Ge(t),"free";if(Ao(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Eo(s.close().then(()=>!0).catch(()=>!1),n,!1))return Ge(t),"free";try{s.disconnect()}catch{}return"live"}function Zs(e,t){e&&(Ks(),Ye.add(e),e.on("disconnected",()=>{Ye.delete(e),t&&Ge(t)}))}async function To(e,t={}){let n=So(),o={...Ys,...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 _o(e,n)==="live")throw new Error(r);Io(n);let i;try{i=await e.launch(o)}catch{if(await _o(e,n)==="live")throw new Error(r);xo(n);try{i=await e.launch(o)}catch(c){throw Qs(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 Zs(i,n),zs(n,i),{browser:i,profileDir:n,needsSeed:vo(n)}}async function Ro(e,t){if(!t||!t.needsSeed)return!1;if(!wo())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(...yo()),Co(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await po();function ei(){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 ti(){let e=ei();if(e.list){console.log(`
|
|
293
293
|
\u{1F4C2} Available profile files:
|
|
294
|
-
`);let a=
|
|
294
|
+
`);let a=oo();if(a.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of a)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
|
|
295
295
|
========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
|
|
296
|
-
`),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=
|
|
296
|
+
`),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=eo(e.source,e.date);console.log(`
|
|
297
297
|
Profiles to process: ${t.length}`),t.length===0&&(console.log(`
|
|
298
298
|
\u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
|
|
299
299
|
Profiles:`),t.slice(0,10).forEach((a,u)=>{console.log(` ${u+1}. ${a.name||"Unknown"} - ${a.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
|
|
300
300
|
Press Enter to start, or Ctrl+C to cancel...`),await new Promise(a=>{process.stdin.once("data",()=>a())}),console.log(`
|
|
301
301
|
\u{1F680} Starting browser...
|
|
302
|
-
`);let n=await
|
|
303
|
-
`);let i=e.viewOnly?"view-only":"connect",s=
|
|
302
|
+
`);let n=await To(Xs,{devtools:!1}),o=n.browser,r=await o.newPage();await Ro(r,n),console.log(`\u2713 Browser ready (persistent profile)
|
|
303
|
+
`);let i=e.viewOnly?"view-only":"connect",s=ln("funnel",i),c=await Qn(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)=>{to(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(`
|
|
304
304
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
305
|
-
`);let l=
|
|
306
|
-
Status breakdown:`);for(let[a,u]of Object.entries(l.statuses))console.log(` ${a}: ${u}`)}
|
|
305
|
+
`);let l=no(e.source);if(console.log(`Processed: ${l.processed}/${l.total}`),console.log(`Remaining: ${l.unprocessed}`),Object.keys(l.statuses).length>0){console.log(`
|
|
306
|
+
Status breakdown:`);for(let[a,u]of Object.entries(l.statuses))console.log(` ${a}: ${u}`)}mt(s,"success",{sent:c.connectionsSent,viewed:c.viewed,errors:c.errors,skippedPending:c.skipped?.pending||0,skippedConnected:c.skipped?.connected||0}),await o.close(),process.exit(0)}ti().catch(e=>{console.error("Funnel failed:",e);try{mt(null,"error",null,e.message)}catch{}process.exit(1)});
|