ilml-plugin-linkedin 1.20.0 → 1.20.2

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.
@@ -1,7 +1,7 @@
1
- var $o=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)$o(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 No}from"@ilivemylife/graph-sdk";var Oo,fe,te,ft,dt,mt=ce(async()=>{Oo=await No();for(let[e,t]of Object.entries(Oo))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 L from"path";import{fileURLToPath as Fo}from"url";function an(){Ce=null,Po=null,ne=null,Uo=null,qo=null,Bo=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: ${L.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 Ho(){O.existsSync(ht)||O.mkdirSync(ht,{recursive:!0})}function cn(e){let t=ye(e);return t?L.join(ht,`${t}.json`):null}function Wo(e){let t=cn(e);return t?yt(t,`profile-history/${ye(e)}.json`)||[]:[]}function Go(e,t){let n=cn(e);if(!n)return;Ho();let o=Wo(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 Yo(e,t){if(!e)return[];let n=[];for(let o of Vo){let r=e[o],i=t[o];on(r)||on(i)||rn(r)!==rn(i)&&n.push(o)}return n}function Ko(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: ${L.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=Yo(s,t);c.length>0&&(Go(i,{capturedAt:r,previousLastUpdated:s.lastUpdated||null,changedFields:c,snapshot:Ko(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 Jo)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 zo(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}),zo(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 Mo,Lo,oe,pt,ti,sn,ni,oi,ri,ht,ln,Ne,Oe,Ce,Po,ne,Uo,qo,Bo,Jo,Vo,Xe=ce(async()=>{await mt();Mo=Fo(import.meta.url),Lo=L.dirname(L.dirname(Mo)),oe=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(Lo,"collected-profiles"),pt=L.join(oe,"people.json"),ti=L.join(oe,"jobs.json"),sn=L.join(oe,"quota.json"),ni=L.join(oe,"conversations.json"),oi=L.join(oe,"sync-state.json"),ri=L.join(oe,"application-questions.json"),ht=L.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,Po=null,ne=null,Uo=null,qo=null,Bo=null;Jo=["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"],Vo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var yn={};ee(yn,{extractCertificationsFromDetails:()=>tr,extractEducationFromDetails:()=>Xo,extractExperienceFromDetails:()=>Qo,extractFeaturedFromDetails:()=>Zo,extractRecommendationsFromDetails:()=>nr,extractSkillsFromDetails:()=>er});async function Qo(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 p=m.filter(y=>(y.textContent||"").trim().length>50);p.length<3||(d.textContent||"").length<500||f.push({el:d,count:p.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(T=>T.trim());d=k[0]||null,k[1]&&(m=k[1])}let p=u.findIndex(k=>/(\d{4}|present)/i.test(k)&&/(-|–|—)/i.test(k)&&k.length<80),y=null,g=null;if(p>=0){let k=u[p].split("\xB7").map(T=>T.trim());y=k[0]||null,k[1]&&(g=k[1])}let h=null,v=-1;if(p>=0&&u[p+1]){let k=u[p+1],T=/^[>*\-•]|^&gt;/.test(k),z=/https?:\/\//.test(k),M=/\d{4}/.test(k),P=/,/.test(k)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(k);!T&&!z&&!M&&k.length<100&&P&&(h=k,v=p+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(T=>T.trim()),additional:parseInt(k[2],10)})}let R=new Set([0,1,p,v,w].filter(k=>k>=0)),I=u.filter((k,T)=>!R.has(T)),D=I.length>0?I.join(`
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],_=/^[>*\-•]|^&gt;/.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(`
2
2
 
3
- `):null;return{title:f,company:d,employmentType:m,dates:y,duration:g,location:h,description:D,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 Pe(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 Zo(e,t){return Pe(t,"featured","extractFeaturedFromDetails",async()=>(await Me(e,t,"featured"),await e.evaluate(`(() => {
3
+ `):null;return{title:f,company:d,employmentType:m,dates:y,duration:p,location:h,description:R,skills:$,_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 Pe(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 tr(e,t){return Pe(t,"featured","extractFeaturedFromDetails",async()=>(await Me(e,t,"featured"),await e.evaluate(`(() => {
5
5
  ${Le}
6
6
 
7
7
  const main = document.querySelector('main');
@@ -42,7 +42,7 @@ var $o=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 Xo(e,t){return Pe(t,"education","extractEducationFromDetails",async()=>(await Me(e,t,"education"),await e.evaluate(`(() => {
45
+ })()`)))}async function nr(e,t){return Pe(t,"education","extractEducationFromDetails",async()=>(await Me(e,t,"education"),await e.evaluate(`(() => {
46
46
  ${Le}
47
47
 
48
48
  const main = document.querySelector('main');
@@ -79,7 +79,7 @@ var $o=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 er(e,t){return Pe(t,"skills","extractSkillsFromDetails",async()=>(await Me(e,t,"skills"),await e.evaluate(`(() => {
82
+ })()`)))}async function or(e,t){return Pe(t,"skills","extractSkillsFromDetails",async()=>(await Me(e,t,"skills"),await e.evaluate(`(() => {
83
83
  ${Le}
84
84
 
85
85
  const main = document.querySelector('main');
@@ -111,7 +111,7 @@ var $o=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 tr(e,t){return Pe(t,"certifications","extractCertificationsFromDetails",async()=>(await Me(e,t,"certifications"),await e.evaluate(`(() => {
114
+ })()`)))}async function rr(e,t){return Pe(t,"certifications","extractCertificationsFromDetails",async()=>(await Me(e,t,"certifications"),await e.evaluate(`(() => {
115
115
  ${Le}
116
116
 
117
117
  const main = document.querySelector('main');
@@ -136,7 +136,7 @@ var $o=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 nr(e,t){return Pe(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Me(e,t,"recommendations"),await e.evaluate(`(() => {
139
+ })()`)))}async function sr(e,t){return Pe(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Me(e,t,"recommendations"),await e.evaluate(`(() => {
140
140
  ${Le}
141
141
 
142
142
  const main = document.querySelector('main');
@@ -235,72 +235,72 @@ 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 bn={};ee(bn,{extractSidePanelProfiles:()=>rr,normalizeFundUrl:()=>et,normalizeProfileUrl:()=>xe});function xe(e){if(!e||typeof e!="string"||/custom-invite|\/search\/|miniProfile/.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}async function rr(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10;try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(c=>setTimeout(c,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(c=>setTimeout(c,1200))}catch{}let o;try{o=await e.evaluate(c=>{let l=m=>(m||"").replace(/\s+/g," ").trim(),a=m=>l(m).replace(/^View\s+/i,"").split(/\s*[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\b(1st|2nd|3rd)\b.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),u=m=>{let p=m;for(let y=0;y<6&&p.parentElement;y++)if(p=p.parentElement,p.querySelectorAll('a[href*="/in/"]').length>=2)return p;return m.parentElement},f=[],d=Array.from(document.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let m of d){let p=l(m.textContent).toLowerCase();if(!p)continue;let y=c.find(([$])=>p.includes($));if(!y)continue;let[,g]=y,h=u(m);if(!h)continue;let v=Array.from(h.querySelectorAll('a[href*="/in/"]')),x=0,w=new Set;for(let $ of v){let R=$.href||$.getAttribute("href")||"";if(!/\/in\//.test(R))continue;let I=$.querySelector('span[aria-hidden="true"]'),D=a(I?I.textContent:$.getAttribute("aria-label")||$.textContent);if(!D||w.has(R))continue;w.add(R);let k=$.closest("li")||$.parentElement,T="";k&&(T=Array.from(k.querySelectorAll("p, span")).map(M=>l(M.textContent)).filter(M=>M&&M!==D&&!/^view\b/i.test(M)&&M.length>2)[0]||""),f.push({href:R,name:D,headline:T,block:g,rank:x++})}}return f},or)}catch{return[]}let r=xe(t.seedUrl||""),i=new Map,s={};for(let c of o){let l=xe(c.href);l&&(r&&l===r||(s[c.block]=s[c.block]||0,!(s[c.block]>=n)&&(i.has(l)||(s[c.block]++,i.set(l,{url:l,name:c.name,headline:c.headline||null,block:c.block,rank:c.rank})))))}return Array.from(i.values())}var or,St=ce(()=>{or=[["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 xn={};ee(xn,{getJobDecision:()=>ur,getLastVisit:()=>wr,getScoutStats:()=>br,loadCompanies:()=>At,loadDiscoveredPeople:()=>He,loadJobDecisions:()=>xt,loadScoutedJobs:()=>$t,loadVisitLog:()=>ot,recordCompany:()=>hr,recordDiscoveredEdge:()=>mr,recordDiscoveredEdges:()=>pr,recordVisit:()=>yr,resetCaches:()=>Ct,saveCompany:()=>gr,saveDiscoveredPerson:()=>fr,saveScoutedJob:()=>ar,setJobDecision:()=>cr});import"dotenv/config";import*as H from"fs";import*as J from"path";import{fileURLToPath as sr}from"url";function de(){H.existsSync(be)||H.mkdirSync(be,{recursive:!0})}function me(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";H.writeFileSync(o,n);for(let r=0;r<3;r++)try{H.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(H.existsSync(e))return JSON.parse(H.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(Sn)||{},Ue)}function ar(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(Sn,n)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}function xt(){return qe||(qe=Ve(vn)||{},qe)}function cr(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(vn,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function ur(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 Cn(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 fr(e,t){if(!e)return;de();let n=He(),o=new Date().toISOString().slice(0,10),r=Cn(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 dr(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 $n(e,t,n={},o){if(!t)return;let r=Ae(t);t=Cn(e,t);let i=n.seedUrl?{...n,seedUrl:xe(n.seedUrl)||n.seedUrl}:n,s=o.slice(0,10),{edge:c,match:l}=dr(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=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 mr(e,t={}){if(!e)return;de();let n=He();$n(n,e,t,new Date().toISOString());try{me(nt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function pr(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||($n(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 hr(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 gr(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(kn)||{visits:[]},Array.isArray(we.visits)||(we.visits=[]),we)}function yr(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(kn,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function wr(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 br(){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 ir,lr,be,Sn,nt,kn,vt,vn,Ue,qe,Be,kt,tt,Je,we,Et=ce(()=>{St();ir=sr(import.meta.url),lr=J.dirname(J.dirname(ir)),be=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"market-research"):J.join(lr,"market-research"),Sn=J.join(be,"scouted-jobs.json"),nt=J.join(be,"discovered-people.json"),kn=J.join(be,"visit-log.json"),vt=J.join(be,"companies.json"),vn=J.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 Fn={};ee(Fn,{computeEngagement:()=>It,detectCategory:()=>_n,detectCategoryFromTitle:()=>rt,determineAction:()=>Nn,determineLastMessageBy:()=>Dn,determineSituation:()=>In,enrichConversation:()=>Sr,enrichPerson:()=>Ar,enrichPersonContext:()=>On,extractAutoTags:()=>Tn,generateSummary:()=>Rn,normPreview:()=>_t});function Sr(e,t,n){if(!e)return e;let r=(e.messages||[]).filter(l=>!dt.has(l.status)),i=vr(t,e.profileUrl,n),s=Dn(r,t);if(e.lastMessageBy=s,e.conversationStatus=s==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=_n(r,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=In(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=On(i),e.summary=Rn(e,t,i),e.autoTags=Tn(e,t,i);let c=Nn(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=kr(e),e}function _n(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(En))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(En))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function In(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 An.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 An.test(r?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Dn(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 Rn(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(p=>p.sender!==fe&&p.sender!=="Unknown").map(p=>p.text).join(" "),u=Cr(a),f=$r(a),d=xr(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 Tn(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=jn(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 jn(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 Nn(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 On(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function kr(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 vr(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 Cr(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 $r(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 xr(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 Ar(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=rt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Er(e),e.personSummary=_r(e),e.personAutoTags=Ir(e);let n=Dr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Rr(e)),e}function Er(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 _r(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 Ir(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=jn("",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 Dr(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 Rr(e){let t=e.category;if(!t)return null;let n=Tr(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 Tr(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 En,An,Mn=ce(async()=>{await mt();await Xe();En={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]}};An=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Pn={};ee(Pn,{DEFAULT_PROFILE_INTERESTS:()=>Ln,computeFit:()=>Or,detectSectors:()=>Nr});function Nr(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(jr))r.some(i=>i.test(t))&&n.push(o);return n}function Or(e,t=Ln){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 jr,Ln,Un=ce(()=>{jr={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/]};Ln={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});import Os from"puppeteer";import"dotenv/config";import*as V from"fs";import*as ue from"path";import{fileURLToPath as Do}from"url";import"dotenv/config";import{createGraphClient as xo,resolveToken as Ao}from"@ilivemylife/graph-sdk";import{config as Eo}from"dotenv";Eo();var zt=Ao()||process.env.TOKEN;zt||(console.error(`
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(`
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 Qt=xo({token:zt});function _o(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 Io({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?` ${_o(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 Zt({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=`**${Io({scriptName:e,mode:t,status:n,error:r,duration:i})}**
242
+ `),process.exit(1));var Qt=_o({token:zt});function Ro(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 To({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?` ${Ro(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 Zt({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=`**${To({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 Ro=Do(import.meta.url),To=ue.dirname(ue.dirname(Ro)),at=process.env.DATA_DIR?ue.resolve(process.env.DATA_DIR,"collected-profiles"):ue.join(To,"collected-profiles"),ct=ue.join(at,"run-log.json");function jo(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 Xt(){try{if(!V.existsSync(ct))return{runs:[]};let e=JSON.parse(V.readFileSync(ct,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function en(e){V.existsSync(at)||V.mkdirSync(at,{recursive:!0});try{jo(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 Bn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: 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 qn(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Fr(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 Bn(e,t));let u=0;for(let w=0;w<2;w++){let $=await e.evaluate(()=>document.body.scrollHeight);for(let I=1;I<=6;I++)await e.evaluate(D=>window.scrollTo(0,D),$*I/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)},I={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:[]},D=document.querySelector("main");if(!D)return I;let k=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],T=Array.from(D.querySelectorAll("h2")),z=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)}),M=z?z.textContent.trim():null,P=z?z.parentElement:null;for(;P&&P!==D&&!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,Re=null,Te=null;if(P&&P!==D){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&&(Re=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&&!(M&&ae.startsWith(M))&&(Te=ae.split(/[·•]/)[0].trim(),Te))break}}let Ge=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"){Ge=E;break}}}let j=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),F=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=F&&F.src||null,N=D.textContent||"",Q=null,Bt=N.match(/(\d+\+?)\s+connections\b/i);Bt&&(Q=Bt[1]+" connections");let Ye=null,Jt=N.match(/(\d+)\s+mutual connection/i),Vt=N.match(/and\s+(\d+)\s+other mutual/i),bo=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):bo&&(Ye=2);let Ht=null,Wt=null,Gt=T.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(Co=>Co.trim()).filter(Boolean);lt.length>0&&lt.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=T.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 So=[...new Set(T.map(C=>(C.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(C=>C&&C.length>1&&C.length<60&&C!==M).filter(C=>w.has(C)))],je=document.body.textContent||"",ko=/#OpenToWork\b/i.test(je)||/\bOpen to work\b/.test(je),vo=/#Hiring\b/i.test(je)||/\bI'?m hiring\b/i.test(je)||/\bWe are hiring\b/i.test(je);return{name:M,title:le,location:Te,currentCompany:De,currentSchool:Re,connectionDegree:Ge,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:Q,mutualConnectionsCount:Ye,followers:Yt,openToWork:ko,hiring:vo,about:Ht,topSkills:Wt,availableSections:So}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,p=null,y=null,g=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&&(p=await w.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(y=await w.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),s&&(g=await w.extractSkillsFromDetails(e,t),console.log(` + Skills: ${g.length} entries`)),c&&(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},...p!==null&&{featured:p},...y!==null&&{education:y},...g!==null&&{skillsFull:g},...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],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of d){let g=y.getBoundingClientRect();if(g.width===0||g.height===0||y.closest(p))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"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(g=>{let h=g.getAttribute("aria-label")||"";return(h.toLowerCase().includes("invite")||h.toLowerCase().includes("connect"))&&m.test(h)}).map(g=>g.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),p='[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 g of m){if(g.closest(p))continue;let h=g.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 g}return null},a);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let a=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),p=f.className.includes("sticky-header")||f.className.includes("sticky"),y=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,g=(f.getAttribute("aria-label")||"").toLowerCase(),h=g.includes("invite"),v=d?g.includes(d):!0;return{isMuted:m,isStickyHeader:p,inRecommendations:y,hasInvite:h,matchesName:v,ariaLabel:g}},a,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=a;break}}for(let a of o)a!==i&&await a.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let s=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,p=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:p,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 p=m.innerText?.trim(),y=m.getAttribute("aria-label")||"",g=m.getBoundingClientRect();return g.top<100||g.top>600||g.width===0?!1:p==="Follow"||p==="Message"||p==="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 p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==f)return p;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 p of m){let y=p.querySelector('a[href*="custom-invite"]');if(y)return y;for(let g of p.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(g.innerText?.trim()==="Connect")return g}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let p of d)for(let y of p.querySelectorAll('[role="menuitem"], a, div')){let g=y.innerText?.trim();g&&g.length<40&&m.push(g)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(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 p=d.getBoundingClientRect();if(!(p.width===0||p.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 Mr(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 Lr(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 Pr(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 Ur(e,t,n);return s.connectionSent&&!i&&hn(t,o),s}async function Ur(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(qn(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 Bn(e,t),await S(2e3)),process.env.LINKEDIN_DISCOVERY==="1")try{let{extractSidePanelProfiles:h,normalizeProfileUrl:v}=await Promise.resolve().then(()=>(St(),bn)),{recordDiscoveredEdges:x}=await Promise.resolve().then(()=>(Et(),xn)),{detectCategoryFromTitle:w}=await Mn().then(()=>Fn),{detectSectors:$}=await Promise.resolve().then(()=>(Un(),Pn)),R=v(t)||t,I=await h(e,{seedUrl:R}),D=I.map(k=>{let T=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:T?[T]:[],sectors:$(k.headline||"")}});x(D),I.length&&console.log(` \xB7 discovery: harvested ${I.length} related profiles`)}catch(h){process.env.LINKEDIN_DISCOVERY_DEBUG==="1"&&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")),I=$.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!h.has(F)&&F!=="0 notifications"}),D=I?I.textContent.trim():null,k=I?I.parentElement:null;for(;k&&k!==w&&!Array.from(k.children).filter(U=>U.tagName==="P").some(U=>{let N=U.textContent&&U.textContent.trim();return N&&N.length>5&&!v(N)});)k=k.parentElement;let T=null,z=null,M=null;if(k&&k!==w){let j=Array.from(k.children),F=j.filter(N=>N.tagName==="P").filter(N=>{let Q=N.textContent&&N.textContent.trim();return Q&&Q.length>5&&!v(Q)});F[0]&&(T=F[0].textContent.trim()),F[1]&&(z=F[1].textContent.trim());let U=j.filter(N=>N.tagName==="DIV");for(let N=U.length-1;N>=0;N--){let Q=U[N].textContent&&U[N].textContent.trim();if(Q&&!(D&&Q.startsWith(D))&&(M=Q.split(/[·•]/)[0].trim(),M))break}}let P=null;if(k){let j=k.querySelectorAll("p, span, div");for(let F of j){let U=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){P=U;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 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:D,title:T,location:M,about:le,company:z,connectionDegree:P,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,x=h||v;if(qn(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 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 Mr(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"]'),g=await e.$('button[aria-label="Send without a note"]');if(!y&&!g){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"]'));g=v?.asElement?.()||null,g||await v.dispose().catch(()=>{})}}if(r)if(y&&o){if(console.log(" Adding personalized note..."),await y.click(),await S(1500),await e.$("div.modal-upsell")){let x=await Lr(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(g)return console.log(" Sending without note..."),await Ie(e,g)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(y&&!o){console.log(" No message provided, sending without note...");let 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=g;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 I=R.getBoundingClientRect();return{visible:I.width>0&&I.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(D=>D.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 I=await e.$('button[aria-label="Send without a note"]');if(I)return console.log(" Modal appeared via More dropdown, sending without note..."),await Ie(e,I)?(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 Jn(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=bt();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 p=t[m];try{if(e.isClosed()){console.log(`
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&&lt.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=bt();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(!p.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=fn(p.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}] ${p.name||p.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(p,f,{success:!1,reason:y,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${p.name||p.profileUrl}`);let g=null;if(s){let h=await Fr(e,p.profileUrl);h?(ze(p.profileUrl,{...h,source:u}),f.viewed++,g={success:!0,reason:"viewed",connectionSent:!1,profileInfo:h,resolvedUrl:h.resolvedUrl}):(f.errors++,g={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=wt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(g=await Pr(e,p.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:u,skipQuotaGate:!0}),g.success)f.connectionsSent++;else switch(g.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(g?.fatal){console.log(`
250
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(g?.reason==="error"){if(d++,d>=3){console.log(`
251
- \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(g&&g.reason&&(dn(p.profileUrl,g.reason,{method:g.method,messageSent:g.messageSent,profileInfo:g.profileInfo}),g.resolvedUrl&&mn(p.profileUrl,g.resolvedUrl),un(p.profileUrl,{source:u||"funnel",jobId:p.jobId||p.fromJob?.jobId||null,jobTitle:p.fromJob?.title||null,jobCompany:p.fromJob?.company||null,action:g.reason})),l&&await l(p,f,g),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=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 q from"fs";import*as se from"path";import{fileURLToPath as qr}from"url";var Br=qr(import.meta.url),Jr=se.dirname(se.dirname(Br)),We=process.env.DATA_DIR?se.resolve(process.env.DATA_DIR,"collected-profiles"):se.join(Jr,"collected-profiles");function Tt(){q.existsSync(We)||q.mkdirSync(We,{recursive:!0})}function Vr(){return new Date().toISOString().split("T")[0]}function Vn(e,t=null){let n=t||Vr();return se.join(We,`${e}-${n}.json`)}function Hn(e,t=null){Tt();let n=Vn(e,t);try{if(q.existsSync(n)){let o=q.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function Wn(e,t=null){return Hn(e,t).filter(o=>!o.processed)}function Gn(e,t,n,o=null){Tt();let r=Vn(e,o);try{if(!q.existsSync(r))return;let i=JSON.parse(q.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(),q.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Yn(e){let t=Hn(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 Kn(){Tt();try{return q.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(q.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 _ from"path";import{fileURLToPath as ps}from"url";var Ot={};ee(Ot,{NAME:()=>Wr,VERSION:()=>Hr,up:()=>Kr});import*as W from"fs";import*as st from"path";var Hr=1,Wr="normalize-jobs-and-questions",Gr=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Yr=50;function jt(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function Nt(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 Kr(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 Gr)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 p=(d.questions||[]).map(y=>{let g={type:y.type||"input",question:y.question||"",answer:y.answer||""};return y.options&&(y.options.length<=Yr?g.options=y.options:(g.optionsOmitted=!0,f++)),y.page&&(g.page=y.page),y.wasPreFilled&&(g.wasPreFilled=!0),y.wasRetry&&(g.wasRetry=!0),g});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||p.length,questions:p})}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:()=>Qr,VERSION:()=>zr,up:()=>es});import*as G from"fs";import*as zn from"path";var zr=2,Qr="reset-unread-flags";function Zr(e){return G.existsSync(e)?JSON.parse(G.readFileSync(e,"utf-8")):null}function Xr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{G.writeFileSync(o,n)}catch(r){try{G.unlinkSync(o)}catch{}throw r}try{G.renameSync(o,e)}catch(r){try{G.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function es(e){let t=zn.join(e,"conversations.json"),n=Zr(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}Xr(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:()=>ns,VERSION:()=>ts,up:()=>ls});import*as Y from"fs";import*as Qn from"path";var ts=3,ns="recompute-last-message-by",os=new Set(["draft","confirmed","rejected","needs_review"]);function rs(e){return Y.existsSync(e)?JSON.parse(Y.readFileSync(e,"utf-8")):null}function ss(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function is(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!os.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 ls(e){let t=Qn.join(e,"conversations.json"),n=rs(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=is(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}ss(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:()=>cs,VERSION:()=>as,up:()=>ms});import*as K from"fs";import*as Zn from"path";var as=4,cs="split-connection-timestamps",us=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function fs(e){if(!K.existsSync(e))return null;let t=K.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ds(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{K.writeFileSync(o,n)}catch(r){try{K.unlinkSync(o)}catch{}throw r}try{K.renameSync(o,e)}catch(r){try{K.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function ms(e){let t=Zn.join(e,"people.json"),n=fs(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++,us.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}ds(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 hs=ps(import.meta.url),gs=_.dirname(hs),ys=_.dirname(_.dirname(gs));function ws(e){return e&&(e==="~"?Ut.homedir():e.startsWith("~/")||e.startsWith("~\\")?_.join(Ut.homedir(),e.slice(2)):e)}var Z=process.env.DATA_DIR?_.resolve(ws(process.env.DATA_DIR)):ys,ke=_.join(Z,"collected-profiles"),ve=_.join(Z,"market-research"),B=_.join(Z,".schema-version"),Xn=[_.join(ke,".schema-version"),_.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 oo(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
249
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!g.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let y=fn(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 Lr(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=wt();if(!h.allowed){console.log(` \u26A0 Global quota exhausted: ${h.reason}`);break}if(p=await qr(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
+ \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&&(dn(g.profileUrl,p.reason,{method:p.method,messageSent:p.messageSent,profileInfo:p.profileInfo}),p.resolvedUrl&&mn(g.profileUrl,p.resolvedUrl),un(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=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(`
253
253
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
- `),process.exit(1));try{b.mkdirSync(Z,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
- [FATAL] Cannot create DATA_DIR (${Z}): ${t.message}`),console.error(` Fix the path or permissions and try again.
256
- `),process.exit(1))}let e;try{e=b.statSync(Z)}catch(t){console.error(`
257
- [FATAL] DATA_DIR (${Z}) is not accessible: ${t.message}
254
+ `),process.exit(1));try{b.mkdirSync(Q,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
+ [FATAL] Cannot create DATA_DIR (${Q}): ${t.message}`),console.error(` Fix the path or permissions and try again.
256
+ `),process.exit(1))}let e;try{e=b.statSync(Q)}catch(t){console.error(`
257
+ [FATAL] DATA_DIR (${Q}) is not accessible: ${t.message}
258
258
  `),process.exit(1)}e.isDirectory()||(console.error(`
259
- [FATAL] DATA_DIR (${Z}) 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.
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=_.join(Z,".migration-lock");function bs(){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(`
262
+ `),process.exit(1))}}var Se=I.join(Q,".migration-lock");function ks(){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 qt(){try{if(JSON.parse(b.readFileSync(Se,"utf-8")).pid!==process.pid)return;b.unlinkSync(Se)}catch{}}var eo=!1;function Ss(){if(eo)return;eo=!0;let e=()=>{try{qt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ks(){if(b.existsSync(B))return;let e=[],t=[];for(let i of Xn)if(b.existsSync(i))try{e.push({file:i,schema:it(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
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 qt(){try{if(JSON.parse(b.readFileSync(Se,"utf-8")).pid!==process.pid)return;b.unlinkSync(Se)}catch{}}var oo=!1;function vs(){if(oo)return;oo=!0;let e=()=>{try{qt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Cs(){if(b.existsSync(q))return;let e=[],t=[];for(let i of no)if(b.existsSync(i))try{e.push({file:i,schema:it(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=B+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,B)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of Xn)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${B}`)}function vs(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 it(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function to(){if(ks(),!b.existsSync(B))return{version:0,migrations:[]};let e;try{e=it(B)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
271
- [FATAL] ${B} 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=vs(e);return t===null&&(console.error(`
273
- [FATAL] ${B} 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 ro(e){try{b.chmodSync(e,384)}catch{}}function Cs(e){if(oo(),b.existsSync(B))try{if(b.lstatSync(B).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${B}. 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=B+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),ro(t),b.renameSync(t,B)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function no(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(_.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=_.join(e,c),a=_.join(e,c+n);if(b.existsSync(a)){i++;continue}try{io(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 ${_.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 ${_.basename(e)}/ (${n})${c}`)}}var Pt=!1;async function so(){if(Pt)return;oo(),_s();let t=to().version;if(t===pe){Pt=!0;return}Ss(),bs(),process.on("exit",qt),t>pe&&(console.error(`
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 no)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${q}`)}function $s(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 it(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ro(){if(Cs(),!b.existsSync(q))return{version:0,migrations:[]};let e;try{e=it(q)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
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=$s(e);return t===null&&(console.error(`
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 lo(e){try{b.chmodSync(e,384)}catch{}}function xs(e){if(io(),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)),lo(t),b.renameSync(t,q)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function so(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{co(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 Pt=!1;async function ao(){if(Pt)return;io(),Ds();let t=ro().version;if(t===pe){Pt=!0;return}vs(),ks(),process.on("exit",qt),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=Is();if(!n.ok){console.error(`
278
+ \u{1F4E6} Schema migration: v${t} \u2192 v${pe}`);let n=Rs();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{no(ke,r.version),no(ve,r.version)}catch(l){console.error(`
282
+ Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{so(ke,r.version),so(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=Ds(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.
285
+ [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=Ts(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=to();u.version=r.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Cs(u)}catch(l){console.error(`
288
+ `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||i,appliedAt:l},u=ro();u.version=r.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),xs(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
290
  `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{an()}catch{}try{Ct()}catch{}Pt=!0,qt(),console.log(`
291
291
  \u2713 Schema is now at v${pe}
292
- `)}var $s=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function xs(e){let t=e.toLowerCase();return $s.some(n=>n.test(t))}var As=6e4;function Es(){let e=Date.now(),t=[];for(let n of[Z,ke,ve]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!xs(r))continue;let i=_.join(n,r);try{let s=b.statSync(i);if(!s.isFile()||e-s.mtimeMs<As)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function _s({verbose:e=!1}={}){let t=Es();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: ${_.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 Is(){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=_.join(t,o);try{it(r)}catch(i){e.push({dir:_.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ds(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=_.join(i,c),a=c.slice(0,-e.length),u=_.join(i,a);try{a.toLowerCase().endsWith(".json")?it(l):b.accessSync(l,b.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${_.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{io(i,s),o++}catch(a){r.push(`${_.basename(l)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function io(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),ro(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 X from"fs";import he from"path";var Rs="cookies.json";function lo(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin","cookies.json"):Rs}function ao(){let e=lo();if(!X.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=X.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 co(){return X.existsSync(lo())}function Ts(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin"):"."}function uo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function js(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?uo(t[1]):"default"}function fo(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return X.existsSync(t)||X.mkdirSync(t,{recursive:!0}),he.resolve(t);let n=uo(e||js()),o=he.join(Ts(),"chrome-profile",n);return X.existsSync(o)||X.mkdirSync(o,{recursive:!0}),he.resolve(o)}var mo=".ilml-seeded";function po(e){return!X.existsSync(he.join(e,mo))}function ho(e){try{X.writeFileSync(he.join(e,mo),new Date().toISOString())}catch{}}function go(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{X.rmSync(he.join(e,n),{force:!0}),t++}catch{}return t}var Ns={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function yo(e,t={}){let n=fo(),o={...Ns,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{go(n);try{r=await e.launch(o)}catch(s){throw 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: ${s.message})`)}}return{browser:r,profileDir:n,needsSeed:po(n)}}async function wo(e,t){if(!t||!t.needsSeed)return!1;if(!co())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(...ao()),ho(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await so();function Fs(){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 Ms(){let e=Fs();if(e.list){console.log(`
292
+ `)}var As=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Es(e){let t=e.toLowerCase();return As.some(n=>n.test(t))}var _s=6e4;function Is(){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(!Es(r))continue;let i=I.join(n,r);try{let s=b.statSync(i);if(!s.isFile()||e-s.mtimeMs<_s)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function Ds({verbose:e=!1}={}){let t=Is();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 Rs(){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{it(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 Ts(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")?it(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{co(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 co(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),lo(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 js="cookies.json";function uo(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin","cookies.json"):js}function fo(){let e=uo();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 mo(){return Z.existsSync(uo())}function Ns(){let e=process.env.ILML_SCOPE_DIR;return e?he.join(e,"plugins-state","linkedin"):"."}function po(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Os(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?po(t[1]):"default"}function ho(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=po(e||Os()),o=he.join(Ns(),"chrome-profile",n);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),he.resolve(o)}var go=".ilml-seeded";function yo(e){return!Z.existsSync(he.join(e,go))}function wo(e){try{Z.writeFileSync(he.join(e,go),new Date().toISOString())}catch{}}function bo(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Z.rmSync(he.join(e,n),{force:!0}),t++}catch{}return t}var Fs={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function So(e,t={}){let n=ho(),o={...Fs,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{bo(n);try{r=await e.launch(o)}catch(s){throw 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: ${s.message})`)}}return{browser:r,profileDir:n,needsSeed:yo(n)}}async function ko(e,t){if(!t||!t.needsSeed)return!1;if(!mo())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(...fo()),wo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await ao();function Ls(){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 Ps(){let e=Ls();if(e.list){console.log(`
293
293
  \u{1F4C2} Available profile files:
294
- `);let a=Kn();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(`
294
+ `);let a=Zn();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=Wn(e.source,e.date);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=Kn(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 yo(Os,{devtools:!1}),o=n.browser,r=await o.newPage();await wo(r,n),console.log(`\u2713 Browser ready (persistent profile)
303
- `);let i=e.viewOnly?"view-only":"connect",s=tn("funnel",i),c=await Jn(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)=>{Gn(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(`
302
+ `);let n=await So(Ms,{devtools:!1}),o=n.browser,r=await o.newPage();await ko(r,n),console.log(`\u2713 Browser ready (persistent profile)
303
+ `);let i=e.viewOnly?"view-only":"connect",s=tn("funnel",i),c=await Wn(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)=>{zn(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=Yn(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}`)}ut(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)}Ms().catch(e=>{console.error("Funnel failed:",e);try{ut(null,"error",null,e.message)}catch{}process.exit(1)});
305
+ `);let l=Qn(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}`)}ut(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)}Ps().catch(e=>{console.error("Funnel failed:",e);try{ut(null,"error",null,e.message)}catch{}process.exit(1)});