ilml-plugin-linkedin 1.20.7 → 1.20.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/visit.mjs CHANGED
@@ -1,7 +1,9 @@
1
- var jn=Object.defineProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{for(var n in t)jn(e,n,{get:t[n],enumerable:!0})};async function C(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function On(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function Ln(e){return Nn.test(e||"")}async function Oe(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await On(e,t,{timeout:o,label:n});if(!r&&Ln(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function Ne(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4}={}){return await e.goto(t,{waitUntil:"domcontentloaded",timeout:s}),Oe(e,{readySelector:n,label:o,timeout:r})}async function bt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=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(s||i||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 u=o.querySelectorAll("button");for(let f of u){let g=f.innerText?.trim().toLowerCase()||"",a=f.getAttribute("aria-label")?.toLowerCase()||"";if(g==="not now"||g==="no thanks"||g==="dismiss"||a.includes("dismiss"))return f.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 Nn,pe=ie(()=>{Nn=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as Fn}from"@ilivemylife/graph-sdk";var Pn,Mn,z,Nr,qn,Le=ie(async()=>{Pn=await Fn();for(let[e,t]of Object.entries(Pn))process.env[e]===void 0&&(process.env[e]=t);Mn=process.env.LINKEDIN_NAME,z=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Nr=Object.freeze(new Set([z.DRAFT,z.CONFIRMED,z.NEEDS_REVIEW])),qn=Object.freeze(new Set([z.DRAFT,z.CONFIRMED,z.REJECTED,z.NEEDS_REVIEW]))});import"dotenv/config";import*as A from"fs";import*as E from"path";import{fileURLToPath as Xn}from"url";function Vt(){le=null,no=null,oo=null,ro=null,so=null,io=null}function Ht(){A.existsSync(B)||A.mkdirSync(B,{recursive:!0})}function Jt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";A.writeFileSync(o,n);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Wt(e,t){if(!A.existsSync(e))return null;try{let n=JSON.parse(A.readFileSync(e,"utf-8"));try{A.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${E.resolve(e)}`);let o=e+".backup";if(A.existsSync(o))try{let r=JSON.parse(A.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{A.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{A.copyFileSync(e,e+".corrupted")}catch{}return null}}function lo(){return new Date().toISOString().split("T")[0]}function Q(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Mt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Gt(e,t,n=null){if(!t||e[t])return t;let o=Q(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(Q(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Mt(n),i=Mt(e[r].name);if(s&&i&&s===i)return r}return t}function uo(){A.existsSync(qe)||A.mkdirSync(qe,{recursive:!0})}function Yt(e){let t=Q(e);return t?E.join(qe,`${t}.json`):null}function fo(e){let t=Yt(e);return t?Wt(t,`profile-history/${Q(e)}.json`)||[]:[]}function mo(e,t){let n=Yt(e);if(!n)return;uo();let o=fo(e);o.unshift(t);try{Jt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${Q(e)}: ${r.message}`)}}function qt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ut(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function po(e,t){if(!e)return[];let n=[];for(let o of ao){let r=e[o],s=t[o];qt(r)||qt(s)||Ut(r)!==Ut(s)&&n.push(o)}return n}function ho(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 ce(){return le||(Ht(),le=Wt(Me,"people.json")||{},le)}function Kt(e){Ht(),le=e;try{Jt(Me,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${E.resolve(Me)}`)}}function Ue(e,t={}){if(!e)return null;let n=ce(),o=lo(),r=new Date().toISOString(),s=Gt(n,e,t.name),i=n[s];if(i){let c=po(i,t);c.length>0&&(mo(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:ho(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of co)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={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 Kt(n),n[s]}function Be(e,t,n={}){if(n.dryRun||!e||!t)return;let o=Q(t);if(!o)return;let r=ce(),s=Gt(r,e),i=r[s];if(!i)return;let c=Q(i.profileUrl||s);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),Kt(r)))}var eo,to,B,Me,ss,is,ls,cs,as,qe,Bt,us,fs,le,no,oo,ro,so,io,co,ao,$e=ie(async()=>{await Le();eo=Xn(import.meta.url),to=E.dirname(E.dirname(eo)),B=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"collected-profiles"):E.join(to,"collected-profiles"),Me=E.join(B,"people.json"),ss=E.join(B,"jobs.json"),is=E.join(B,"quota.json"),ls=E.join(B,"conversations.json"),cs=E.join(B,"sync-state.json"),as=E.join(B,"application-questions.json"),qe=E.join(B,"profile-history"),Bt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},us=Bt(process.env.CONNECT_MAX_DAILY,20),fs=Bt(process.env.CONNECT_MAX_WEEKLY,100),le=null,no=null,oo=null,ro=null,so=null,io=null;co=["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"],ao=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var zt={};me(zt,{extractCertificationsFromDetails:()=>So,extractEducationFromDetails:()=>wo,extractExperienceFromDetails:()=>go,extractFeaturedFromDetails:()=>yo,extractRecommendationsFromDetails:()=>vo,extractSkillsFromDetails:()=>bo});async function go(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await Oe(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await C(1e3);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(900);await C(1e3);let o=0;for(;o<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});)o++,await C(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function s(u){let f=[];for(let g of u.querySelectorAll("div")){let a=Array.from(g.children).filter($=>$.tagName==="DIV");if(a.length<3)continue;let m=a.filter($=>($.textContent||"").trim().length>50);m.length<3||(g.textContent||"").length<500||f.push({el:g,count:m.length,totalText:(g.textContent||"").length})}return f.sort((g,a)=>a.count-g.count||g.totalText-a.totalText),f[0]?.el}let i=s(r);if(!i)return[];let c=Array.from(i.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function l(u){let f=u[0]||null,g=null,a=null;if(u[1]){let w=u[1].split("\xB7").map(D=>D.trim());g=w[0]||null,w[1]&&(a=w[1])}let m=u.findIndex(w=>/(\d{4}|present)/i.test(w)&&/(-|–|—)/i.test(w)&&w.length<80),$=null,k=null;if(m>=0){let w=u[m].split("\xB7").map(D=>D.trim());$=w[0]||null,w[1]&&(k=w[1])}let _=null,y=-1;if(m>=0&&u[m+1]){let w=u[m+1],D=/^[>*\-•]|^&gt;/.test(w),fe=/https?:\/\//.test(w),re=/\d{4}/.test(w),se=/,/.test(w)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(w);!D&&!fe&&!re&&w.length<100&&se&&(_=w,y=m+1)}let h=null,U=-1,x=u[u.length-1];if(x&&/and\s+\+\d+\s+skills?$/i.test(x)){U=u.length-1;let w=x.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);w&&(h={listed:w[1].split(",").map(D=>D.trim()),additional:parseInt(w[2],10)})}let ue=new Set([0,1,m,y,U].filter(w=>w>=0)),H=u.filter((w,D)=>!ue.has(D)),K=H.length>0?H.join(`
1
+ var Ln=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{for(var n in t)Ln(e,n,{get:t[n],enumerable:!0})};import I from"fs";import B from"path";function Le(){let e=process.env.ILML_SCOPE_DIR;return e?B.join(e,"plugins-state","linkedin","cookies.json"):Fn}function Pn(){let e=Le(),t=B.dirname(e);return t&&t!=="."&&!I.existsSync(t)&&I.mkdirSync(t,{recursive:!0}),e}function vt(e){let t=Pn();return I.writeFileSync(t,JSON.stringify(e)),t}function kt(){let e=Le();if(!I.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=I.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 Ct(){return I.existsSync(Le())}function Mn(){let e=process.env.ILML_SCOPE_DIR;return e?B.join(e,"plugins-state","linkedin"):"."}function xt(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function qn(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?xt(t[1]):"default"}function At(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),B.resolve(t);let n=xt(e||qn()),o=B.join(Mn(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),B.resolve(o)}function $t(e){return!I.existsSync(B.join(e,Et))}function _t(e){try{I.writeFileSync(B.join(e,Et),new Date().toISOString())}catch{}}function It(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(B.join(e,n),{force:!0}),t++}catch{}return t}var Fn,Et,Ae=z(()=>{Fn="cookies.json";Et=".ilml-seeded"});async function C(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Un(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function Bn(e){return Rt.test(e||"")}async function Vn(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let l="wait";try{l=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Rt.source)}catch{}if(l==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(p=>p.name==="li_at")){let p=vt(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${p}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(l==="creds"){if(!o){let a=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}i||(i=!0,console.log(`
2
+ \u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
3
+ `))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function Ee(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await Un(e,t,{timeout:o,label:n});if(!r&&Bn(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function Fe(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await Ee(e,{readySelector:n,label:o,timeout:r})}catch(c){if(i&&c.code==="SESSION_EXPIRED"){await Vn(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await Ee(e,{readySelector:n,label:o,timeout:r})}throw c}}async function Dt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=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(s||i||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 d of a){let p=d.innerText?.trim().toLowerCase()||"",u=d.getAttribute("aria-label")?.toLowerCase()||"";if(p==="not now"||p==="no thanks"||p==="dismiss"||u.includes("dismiss"))return d.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 Rt,pe=z(()=>{Ae();Rt=/\/authwall|\/login|\/checkpoint|\/uas\/login/});import{getPluginConfig as Hn}from"@ilivemylife/graph-sdk";var Jn,Wn,Q,Vr,Gn,Pe=z(async()=>{Jn=await Hn();for(let[e,t]of Object.entries(Jn))process.env[e]===void 0&&(process.env[e]=t);Wn=process.env.LINKEDIN_NAME,Q=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Vr=Object.freeze(new Set([Q.DRAFT,Q.CONFIRMED,Q.NEEDS_REVIEW])),Gn=Object.freeze(new Set([Q.DRAFT,Q.CONFIRMED,Q.REJECTED,Q.NEEDS_REVIEW]))});import"dotenv/config";import*as A from"fs";import*as $ from"path";import{fileURLToPath as oo}from"url";function Wt(){le=null,io=null,lo=null,ao=null,co=null,uo=null}function Gt(){A.existsSync(V)||A.mkdirSync(V,{recursive:!0})}function Yt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";A.writeFileSync(o,n);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Kt(e,t){if(!A.existsSync(e))return null;try{let n=JSON.parse(A.readFileSync(e,"utf-8"));try{A.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${$.resolve(e)}`);let o=e+".backup";if(A.existsSync(o))try{let r=JSON.parse(A.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{A.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{A.copyFileSync(e,e+".corrupted")}catch{}return null}}function fo(){return new Date().toISOString().split("T")[0]}function X(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Bt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function zt(e,t,n=null){if(!t||e[t])return t;let o=X(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(X(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Bt(n),i=Bt(e[r].name);if(s&&i&&s===i)return r}return t}function ho(){A.existsSync(Be)||A.mkdirSync(Be,{recursive:!0})}function Qt(e){let t=X(e);return t?$.join(Be,`${t}.json`):null}function go(e){let t=Qt(e);return t?Kt(t,`profile-history/${X(e)}.json`)||[]:[]}function yo(e,t){let n=Qt(e);if(!n)return;ho();let o=go(e);o.unshift(t);try{Yt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${X(e)}: ${r.message}`)}}function Vt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ht(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function wo(e,t){if(!e)return[];let n=[];for(let o of po){let r=e[o],s=t[o];Vt(r)||Vt(s)||Ht(r)!==Ht(s)&&n.push(o)}return n}function bo(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 ae(){return le||(Gt(),le=Kt(Ue,"people.json")||{},le)}function Xt(e){Gt(),le=e;try{Yt(Ue,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${$.resolve(Ue)}`)}}function Ve(e,t={}){if(!e)return null;let n=ae(),o=fo(),r=new Date().toISOString(),s=zt(n,e,t.name),i=n[s];if(i){let c=wo(i,t);c.length>0&&(yo(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:c,snapshot:bo(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of mo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={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 Xt(n),n[s]}function He(e,t,n={}){if(n.dryRun||!e||!t)return;let o=X(t);if(!o)return;let r=ae(),s=zt(r,e),i=r[s];if(!i)return;let c=X(i.profileUrl||s);o!==c&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),Xt(r)))}var ro,so,V,Ue,us,ds,fs,ms,ps,Be,Jt,hs,gs,le,io,lo,ao,co,uo,mo,po,_e=z(async()=>{await Pe();ro=oo(import.meta.url),so=$.dirname($.dirname(ro)),V=process.env.DATA_DIR?$.resolve(process.env.DATA_DIR,"collected-profiles"):$.join(so,"collected-profiles"),Ue=$.join(V,"people.json"),us=$.join(V,"jobs.json"),ds=$.join(V,"quota.json"),fs=$.join(V,"conversations.json"),ms=$.join(V,"sync-state.json"),ps=$.join(V,"application-questions.json"),Be=$.join(V,"profile-history"),Jt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},hs=Jt(process.env.CONNECT_MAX_DAILY,20),gs=Jt(process.env.CONNECT_MAX_WEEKLY,100),le=null,io=null,lo=null,ao=null,co=null,uo=null;mo=["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"],po=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Zt={};me(Zt,{extractCertificationsFromDetails:()=>xo,extractEducationFromDetails:()=>ko,extractExperienceFromDetails:()=>So,extractFeaturedFromDetails:()=>vo,extractRecommendationsFromDetails:()=>Ao,extractSkillsFromDetails:()=>Co});async function So(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await Ee(e,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await C(1e3);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(900);await C(1e3);let o=0;for(;o<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});)o++,await C(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function s(a){let d=[];for(let p of a.querySelectorAll("div")){let u=Array.from(p.children).filter(E=>E.tagName==="DIV");if(u.length<3)continue;let m=u.filter(E=>(E.textContent||"").trim().length>50);m.length<3||(p.textContent||"").length<500||d.push({el:p,count:m.length,totalText:(p.textContent||"").length})}return d.sort((p,u)=>u.count-p.count||p.totalText-u.totalText),d[0]?.el}let i=s(r);if(!i)return[];let c=Array.from(i.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function l(a){let d=a[0]||null,p=null,u=null;if(a[1]){let w=a[1].split("\xB7").map(T=>T.trim());p=w[0]||null,w[1]&&(u=w[1])}let m=a.findIndex(w=>/(\d{4}|present)/i.test(w)&&/(-|–|—)/i.test(w)&&w.length<80),E=null,k=null;if(m>=0){let w=a[m].split("\xB7").map(T=>T.trim());E=w[0]||null,w[1]&&(k=w[1])}let _=null,y=-1;if(m>=0&&a[m+1]){let w=a[m+1],T=/^[>*\-•]|^&gt;/.test(w),de=/https?:\/\//.test(w),se=/\d{4}/.test(w),ie=/,/.test(w)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(w);!T&&!de&&!se&&w.length<100&&ie&&(_=w,y=m+1)}let g=null,U=-1,x=a[a.length-1];if(x&&/and\s+\+\d+\s+skills?$/i.test(x)){U=a.length-1;let w=x.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);w&&(g={listed:w[1].split(",").map(T=>T.trim()),additional:parseInt(w[2],10)})}let ue=new Set([0,1,m,y,U].filter(w=>w>=0)),J=a.filter((w,T)=>!ue.has(T)),K=J.length>0?J.join(`
2
4
 
3
- `):null;return{title:f,company:g,employmentType:a,dates:$,duration:k,location:_,description:K,skills:h,_raw:u}}return c.map(u=>{let g=(u.innerText||"").trim().split(`
4
- `).map(a=>a.trim()).filter(a=>a&&a.length<5e3);return l(g)}).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 ye(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await C(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 i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(700);await C(800);let s=0;for(;s<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});)s++,await C(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(600)}async function be(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function yo(e,t){return be(t,"featured","extractFeaturedFromDetails",async()=>(await ye(e,t,"featured"),await e.evaluate(`(() => {
5
+ `):null;return{title:d,company:p,employmentType:u,dates:E,duration:k,location:_,description:K,skills:g,_raw:a}}return c.map(a=>{let p=(a.innerText||"").trim().split(`
6
+ `).map(u=>u.trim()).filter(u=>u&&u.length<5e3);return l(p)}).filter(a=>a.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 ye(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await C(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 i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(700);await C(800);let s=0;for(;s<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});)s++,await C(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await C(600)}async function be(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function vo(e,t){return be(t,"featured","extractFeaturedFromDetails",async()=>(await ye(e,t,"featured"),await e.evaluate(`(() => {
5
7
  ${we}
6
8
 
7
9
  const main = document.querySelector('main');
@@ -42,7 +44,7 @@ var jn=Object.defineProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{
42
44
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
45
  return true;
44
46
  });
45
- })()`)))}async function wo(e,t){return be(t,"education","extractEducationFromDetails",async()=>(await ye(e,t,"education"),await e.evaluate(`(() => {
47
+ })()`)))}async function ko(e,t){return be(t,"education","extractEducationFromDetails",async()=>(await ye(e,t,"education"),await e.evaluate(`(() => {
46
48
  ${we}
47
49
 
48
50
  const main = document.querySelector('main');
@@ -79,7 +81,7 @@ var jn=Object.defineProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{
79
81
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
82
  return true;
81
83
  });
82
- })()`)))}async function bo(e,t){return be(t,"skills","extractSkillsFromDetails",async()=>(await ye(e,t,"skills"),await e.evaluate(`(() => {
84
+ })()`)))}async function Co(e,t){return be(t,"skills","extractSkillsFromDetails",async()=>(await ye(e,t,"skills"),await e.evaluate(`(() => {
83
85
  ${we}
84
86
 
85
87
  const main = document.querySelector('main');
@@ -111,7 +113,7 @@ var jn=Object.defineProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{
111
113
  skills.push({ name, endorsements, _raw: lines });
112
114
  }
113
115
  return skills;
114
- })()`)))}async function So(e,t){return be(t,"certifications","extractCertificationsFromDetails",async()=>(await ye(e,t,"certifications"),await e.evaluate(`(() => {
116
+ })()`)))}async function xo(e,t){return be(t,"certifications","extractCertificationsFromDetails",async()=>(await ye(e,t,"certifications"),await e.evaluate(`(() => {
115
117
  ${we}
116
118
 
117
119
  const main = document.querySelector('main');
@@ -136,7 +138,7 @@ var jn=Object.defineProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{
136
138
 
137
139
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
140
  }).filter(e => e.name);
139
- })()`)))}async function vo(e,t){return be(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ye(e,t,"recommendations"),await e.evaluate(`(() => {
141
+ })()`)))}async function Ao(e,t){return be(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ye(e,t,"recommendations"),await e.evaluate(`(() => {
140
142
  ${we}
141
143
 
142
144
  const main = document.querySelector('main');
@@ -172,7 +174,7 @@ var jn=Object.defineProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{
172
174
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
175
  return true;
174
176
  });
175
- })()`)))}var we,Qt=ie(()=>{pe();we=`
177
+ })()`)))}var we,en=z(()=>{pe();we=`
176
178
  function findEntryContainer(root) {
177
179
  const candidates = [];
178
180
  for (const div of root.querySelectorAll('div')) {
@@ -235,60 +237,60 @@ function findEntryContainer(root) {
235
237
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
238
  return candidates[0]?.el;
237
239
  }
238
- `});var Xt=ie(()=>{});import"dotenv/config";import*as j from"fs";import*as R from"path";import{fileURLToPath as Co}from"url";function _o(){j.existsSync(X)||j.mkdirSync(X,{recursive:!0})}function Io(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(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ve(e){try{if(j.existsSync(e))return JSON.parse(j.readFileSync(e,"utf-8"))}catch{}return null}function tn(){Se=null,Do=null,ve=null,To=null,Z=null}function Ro(){return Se||(Se=Ve($o)||{},Se)}function Ee(){return ve||(ve=Ve(Eo)||{},ve)}function ae(){return Z||(Z=Ve(en)||{visits:[]},Array.isArray(Z.visits)||(Z.visits=[]),Z)}function nn(e,t={}){if(!e)return;_o();let n=ae();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{Io(en,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function on(e){let t=ae();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function rn(){let e=Ro(),t=Ee(),n=Object.values(e),o=Object.values(t),r={};for(let a of n)a.company&&(r[a.company]=(r[a.company]||0)+1);let s=Object.entries(r).sort((a,m)=>m[1]-a[1]).slice(0,5).map(([a,m])=>`${a} (${m})`),i={};for(let a of n)for(let m of a.techStack||[])i[m]=(i[m]||0)+1;let c=Object.entries(i).sort((a,m)=>m[1]-a[1]).slice(0,8).map(([a,m])=>`${a} (${m})`),l=ae(),u=new Date().toISOString().slice(0,10),f=l.visits.filter(a=>a.date.startsWith(u)).length,g=new Set(l.visits.map(a=>a.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:c,totalVisited:g,todayVisited:f,lastScoutDate:n.length>0?n.sort((a,m)=>(m.scoutedAt||"").localeCompare(a.scoutedAt||""))[0]?.scoutedAt:null}}var xo,Ao,X,$o,Eo,en,Is,Rs,Se,Do,ve,To,Z,_e=ie(()=>{Xt();xo=Co(import.meta.url),Ao=R.dirname(R.dirname(xo)),X=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"market-research"):R.join(Ao,"market-research"),$o=R.join(X,"scouted-jobs.json"),Eo=R.join(X,"discovered-people.json"),en=R.join(X,"visit-log.json"),Is=R.join(X,"companies.json"),Rs=R.join(X,"job-decisions.json");Se=null;Do=null,ve=null;To=null,Z=null});import zn from"puppeteer";import{addExtra as Qn}from"puppeteer-extra";import Zn from"puppeteer-extra-plugin-stealth";pe();await Le();import M from"fs";import W from"path";var Un="cookies.json";function St(){let e=process.env.ILML_SCOPE_DIR;return e?W.join(e,"plugins-state","linkedin","cookies.json"):Un}function vt(){let e=St();if(!M.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=M.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 kt(){return M.existsSync(St())}function Bn(){let e=process.env.ILML_SCOPE_DIR;return e?W.join(e,"plugins-state","linkedin"):"."}function Ct(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Vn(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ct(t[1]):"default"}function xt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return M.existsSync(t)||M.mkdirSync(t,{recursive:!0}),W.resolve(t);let n=Ct(e||Vn()),o=W.join(Bn(),"chrome-profile",n);return M.existsSync(o)||M.mkdirSync(o,{recursive:!0}),W.resolve(o)}var At=".ilml-seeded";function $t(e){return!M.existsSync(W.join(e,At))}function Et(e){try{M.writeFileSync(W.join(e,At),new Date().toISOString())}catch{}}function _t(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{M.rmSync(W.join(e,n),{force:!0}),t++}catch{}return t}import Fe from"fs";import Hn from"path";var Jn={headless:!1,defaultViewport:null,protocolTimeout:3e5},ge=new Set,It=!1;async function Ae(){let e=[...ge].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ge.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Wn(){if(It)return;It=!0;let e=t=>async()=>{await Ae(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ae(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ae(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ae(),process.exit(0))}),process.on("exit",()=>{for(let t of ge)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Pe(e){return Hn.join(e,".ilml-browser-session.json")}function jt(e,t={}){try{Fe.writeFileSync(Pe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Gn(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();jt(e,n?{wsEndpoint:n}:{})}catch{}}function Yn(e){let t=Ot(e);t&&t.ownerPid===process.pid&&he(e)}function he(e){try{Fe.rmSync(Pe(e),{force:!0})}catch{}}function Ot(e){try{return JSON.parse(Fe.readFileSync(Pe(e),"utf-8"))}catch{return null}}function Rt(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Dt(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Tt(e,t,{probeTimeoutMs:n=4e3}={}){let o=Ot(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Rt(o.ownerPid)?"live":(he(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Dt(s,n,r);if(i===r)return s.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!i)return he(t),"free";if(Rt(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Dt(i.close().then(()=>!0).catch(()=>!1),n,!1))return he(t),"free";try{i.disconnect()}catch{}return"live"}function Kn(e,t){e&&(Wn(),ge.add(e),e.on("disconnected",()=>{ge.delete(e),t&&he(t)}))}async function Nt(e,t={}){let n=xt(),o={...Jn,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Tt(e,n)==="live")throw new Error(r);jt(n);let s;try{s=await e.launch(o)}catch{if(await Tt(e,n)==="live")throw new Error(r);_t(n);try{s=await e.launch(o)}catch(c){throw Yn(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return Kn(s,n),Gn(n,s),{browser:s,profileDir:n,needsSeed:$t(n)}}async function Lt(e,t){if(!t||!t.needsSeed)return!1;if(!kt())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(...vt()),Et(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Ft=Qn(zn);Ft.use(Zn());async function Pt(){let{browser:e,profileDir:t,needsSeed:n}=await Nt(Ft),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Lt(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}pe();await $e();async function ko(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 C(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function Zt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=n;try{await Ne(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await C(1500),await bt(e)&&(console.log(" Dismissed Premium overlay"),await C(1500),await ko(e,t));let f=0;for(let x=0;x<2;x++){let ue=await e.evaluate(()=>document.body.scrollHeight);for(let K=1;K<=6;K++)await e.evaluate(w=>window.scrollTo(0,w),ue*K/6),await C(900);let H=await e.evaluate(()=>document.body.scrollHeight);if(H===f)break;f=H}await C(800);let g=null;try{let x=e.url();x&&/\/in\/[^/?#]/.test(x)&&(g=x.split("?")[0].replace(/\/+$/,""))}catch{}let a=await e.evaluate(()=>{let x=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"]),ue=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"]),H=p=>{let b=(p||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(b)},K={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:[]},w=document.querySelector("main");if(!w)return K;let D=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],fe=Array.from(w.querySelectorAll("h2")),re=D.find(p=>{let b=p.textContent&&p.textContent.trim(),S=(b||"").replace(/\s*\(\d+\)$/,"").trim();return b&&b.length>1&&b.length<100&&!x.has(S)&&!ue.has(S)}),se=re?re.textContent.trim():null,T=re?re.parentElement:null;for(;T&&T!==w&&!Array.from(T.children).filter(b=>b.tagName==="P").some(b=>{let S=b.textContent&&b.textContent.trim();return S&&S.length>5&&!H(S)});)T=T.parentElement;let st=null,it=null,lt=null,Te=null;if(T&&T!==w){let p=Array.from(T.children).filter(S=>S.tagName==="P").filter(S=>{let J=S.textContent&&S.textContent.trim();return J&&J.length>5&&!H(J)});if(p[0]&&(st=p[0].textContent.trim()),p[1]){let S=p[1].textContent.trim().split(/\s*[·•]\s*/);it=S[0]||null,S.length>1&&(lt=S.slice(1).join(" \xB7 "))}let b=Array.from(T.children).filter(S=>S.tagName==="DIV");for(let S=b.length-1;S>=0;S--){let J=b[S].textContent&&b[S].textContent.trim();if(J&&!(se&&J.startsWith(se))&&(Te=J.split(/[·•]/)[0].trim(),Te))break}}let ct=null;if(T){let p=T.querySelectorAll("p, span, div");for(let b of p){let S=(b.textContent||"").trim().replace(/^[·•]\s*/,"");if(S==="1st"||S==="2nd"||S==="3rd"){ct=S;break}}}let $n=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),at=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),En=at&&at.src||null,Ce=w.textContent||"",ut=null,ft=Ce.match(/(\d+\+?)\s+connections\b/i);ft&&(ut=ft[1]+" connections");let xe=null,dt=Ce.match(/(\d+)\s+mutual connection/i),mt=Ce.match(/and\s+(\d+)\s+other mutual/i),_n=Ce.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);dt?xe=parseInt(dt[1],10):mt?xe=2+parseInt(mt[1],10):_n&&(xe=2);let pt=null,ht=null,gt=fe.find(p=>p.textContent&&p.textContent.trim()==="About");if(gt){let p=gt.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let b=(p.textContent||"").trim();b=b.replace(/^About\s*/,"").trim();let S=b.match(/Top skills\s*(.+?)$/i);if(S){let je=S[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Tn=>Tn.trim()).filter(Boolean);je.length>0&&je.length<10&&(ht=je)}b=b.split(/\n?…\s*more/i)[0].trim(),b=b.split(/\n?\.\.\.\s*more/i)[0].trim(),b=b.split(/\bTop skills\b/i)[0].trim(),b=b.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),pt=b||null}}let yt=null,wt=fe.find(p=>p.textContent&&p.textContent.trim()==="Activity");if(wt){let p=wt.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let b=(p.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);b&&(yt=parseInt(b[1].replace(/,/g,""),10))}}let In=[...new Set(fe.map(p=>(p.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(p=>p&&p.length>1&&p.length<60&&p!==se).filter(p=>x.has(p)))],de=document.body.textContent||"",Rn=/#OpenToWork\b/i.test(de)||/\bOpen to work\b/.test(de),Dn=/#Hiring\b/i.test(de)||/\bI'?m hiring\b/i.test(de)||/\bWe are hiring\b/i.test(de);return{name:se,title:st,location:Te,currentCompany:it,currentSchool:lt,connectionDegree:ct,hasVerifiedBadge:$n,photoUrl:En,connectionsLevel:ut,mutualConnectionsCount:xe,followers:yt,openToWork:Rn,hiring:Dn,about:pt,topSkills:ht,availableSections:In}});console.log(`Viewed: ${a.name} - ${a.title}`);let m=null,$=null,k=null,_=null,y=null,h=null;if(o||r||s||i||c||l){let x=await Promise.resolve().then(()=>(Qt(),zt));o&&(m=await x.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&($=await x.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${$.length} entries`)),s&&(k=await x.extractEducationFromDetails(e,t),console.log(` + Education: ${k.length} entries`)),i&&(_=await x.extractSkillsFromDetails(e,t),console.log(` + Skills: ${_.length} entries`)),c&&(y=await x.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(h=await x.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${h.length} entries`))}return{...a,profileUrl:t,resolvedUrl:g,...m!==null&&{experience:m},...$!==null&&{featured:$},...k!==null&&{education:k},..._!==null&&{skillsFull:_},...y!==null&&{recommendations:y},...h!==null&&{certifications:h}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await C(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}_e();await $e();pe();async function sn(e,t,n={}){let{maxVisits:o=50,delayBetween:r=4e3,skipRecentDays:s=7,verbose:i=!1,extractExperience:c=!1}=n,l={visited:0,skipped:0,errors:0},u=Date.now()-s*24*60*60*1e3;for(let f of t){if(l.visited>=o)break;if(!f.profileUrl)continue;let g=on(f.profileUrl);if(g&&new Date(g).getTime()>u){l.skipped++;continue}try{let a=await Zt(e,f.profileUrl,{extractExperience:c}),m=f.source||"visit";if(a){let k={...a,source:m};c&&Array.isArray(a.experience)&&a.experience.length>0&&(k._lastEnrichedAt=new Date().toISOString()),Ue(f.profileUrl,k),a.resolvedUrl&&Be(f.profileUrl,a.resolvedUrl)}nn(f.profileUrl,{name:a?.name||f.name||null,source:m}),l.visited++,i?console.log(` [${l.visited}] ${a?.name||f.profileUrl} \u2014 ${a?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let $=Math.random()*4e3;await C(r+$)}catch(a){l.errors++,i&&console.error(` Error visiting ${f.name||f.profileUrl}: ${a.message?.slice(0,60)}`);let m=(a.message||"").toLowerCase();if(m.includes("detached")||m.includes("session closed")||m.includes("target closed")||m.includes("session expired")||m.includes("bounced to")||m.includes("authwall")||m.includes("checkpoint")||m.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return l}function ln(e={}){let{limit:t=150,revisitDays:n=14}=e,o=ae(),r=new Set(o.visits?.map(y=>y.profileUrl)||[]),s=new Map;for(let y of o.visits||[]){let h=s.get(y.profileUrl);(!h||y.date>h)&&s.set(y.profileUrl,y.date)}let i=Date.now()-7*24*60*60*1e3,c=Date.now()-n*24*60*60*1e3;function l(y){let h=s.get(y);return h&&new Date(h).getTime()>i}let u=Ee(),f=Object.entries(u).filter(([y])=>!r.has(y)).map(([y,h])=>({profileUrl:y,name:h.name,source:"new-discovered",priority:1,jobCount:h.jobIds?.length||0})),g=ce(),a=Object.entries(g).filter(([y,h])=>h.connectionStatus==="connected"||l(y)?!1:(h.jobCount||h.jobIds?.length||0)>=2).map(([y,h])=>({profileUrl:y,name:h.name,source:"active-recruiter",priority:2,jobCount:h.jobCount||h.jobIds?.length||0})),m=Object.entries(g).filter(([y,h])=>{let U=h.connectionStatus;return!(!U||U==="connected"||U==="pending"||U==="sent_without_note"||U==="sent_with_note"||l(y)||(h.jobCount||h.jobIds?.length||0)>=2)}).map(([y,h])=>({profileUrl:y,name:h.name,source:"unconnected",priority:3,jobCount:h.jobCount||h.jobIds?.length||0})),$=[...s.entries()].filter(([y,h])=>new Date(h).getTime()<c).map(([y,h])=>({profileUrl:y,name:null,source:"revisit",priority:4,lastVisit:h})),k=y=>y.sort(()=>Math.random()-.5);return f.sort((y,h)=>h.jobCount-y.jobCount),a.sort((y,h)=>h.jobCount-y.jobCount),k(m),k($),[...f,...a,...m,...$].slice(0,t)}function cn(){let e=Ee();return Object.entries(e).map(([t,n])=>({profileUrl:t,name:n.name,source:"discovered"}))}function He(){let e=ce();return Object.entries(e).filter(([,t])=>{let n=t.connectionStatus;return n&&n!=="connected"&&n!=="pending"&&n!=="sent_without_note"&&n!=="sent_with_note"}).map(([t,n])=>({profileUrl:t,name:n.name,source:"unconnected"}))}function Je(e=14){let t=ae(),n=Date.now()-e*24*60*60*1e3,o=new Map;for(let r of t.visits){let s=o.get(r.profileUrl);(!s||r.date>s.date)&&o.set(r.profileUrl,r)}return[...o.entries()].filter(([,r])=>new Date(r.date).getTime()<n).map(([r,s])=>({profileUrl:r,name:s.name,source:"revisit"}))}_e();import"dotenv/config";import*as O from"fs";import*as G from"path";import{fileURLToPath as Po}from"url";import"dotenv/config";import{createGraphClient as jo,resolveToken as Oo}from"@ilivemylife/graph-sdk";import{config as No}from"dotenv";No();var an=Oo()||process.env.TOKEN;an||(console.error(`
240
+ `});var nn=z(()=>{});import"dotenv/config";import*as j from"fs";import*as D from"path";import{fileURLToPath as $o}from"url";function To(){j.existsSync(ee)||j.mkdirSync(ee,{recursive:!0})}function Oo(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(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Je(e){try{if(j.existsSync(e))return JSON.parse(j.readFileSync(e,"utf-8"))}catch{}return null}function rn(){Se=null,No=null,ve=null,Lo=null,Z=null}function jo(){return Se||(Se=Je(Ro)||{},Se)}function Ie(){return ve||(ve=Je(Do)||{},ve)}function ce(){return Z||(Z=Je(on)||{visits:[]},Array.isArray(Z.visits)||(Z.visits=[]),Z)}function sn(e,t={}){if(!e)return;To();let n=ce();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{Oo(on,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function ln(e){let t=ce();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function an(){let e=jo(),t=Ie(),n=Object.values(e),o=Object.values(t),r={};for(let u of n)u.company&&(r[u.company]=(r[u.company]||0)+1);let s=Object.entries(r).sort((u,m)=>m[1]-u[1]).slice(0,5).map(([u,m])=>`${u} (${m})`),i={};for(let u of n)for(let m of u.techStack||[])i[m]=(i[m]||0)+1;let c=Object.entries(i).sort((u,m)=>m[1]-u[1]).slice(0,8).map(([u,m])=>`${u} (${m})`),l=ce(),a=new Date().toISOString().slice(0,10),d=l.visits.filter(u=>u.date.startsWith(a)).length,p=new Set(l.visits.map(u=>u.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:c,totalVisited:p,todayVisited:d,lastScoutDate:n.length>0?n.sort((u,m)=>(m.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}var _o,Io,ee,Ro,Do,on,js,Ns,Se,No,ve,Lo,Z,Re=z(()=>{nn();_o=$o(import.meta.url),Io=D.dirname(D.dirname(_o)),ee=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"market-research"):D.join(Io,"market-research"),Ro=D.join(ee,"scouted-jobs.json"),Do=D.join(ee,"discovered-people.json"),on=D.join(ee,"visit-log.json"),js=D.join(ee,"companies.json"),Ns=D.join(ee,"job-decisions.json");Se=null;No=null,ve=null;Lo=null,Z=null});import eo from"puppeteer";import{addExtra as to}from"puppeteer-extra";import no from"puppeteer-extra-plugin-stealth";pe();await Pe();Ae();Ae();import Me from"fs";import Yn from"path";var Kn={headless:!1,defaultViewport:null,protocolTimeout:3e5},ge=new Set,Tt=!1;async function $e(){let e=[...ge].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ge.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function zn(){if(Tt)return;Tt=!0;let e=t=>async()=>{await $e(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await $e(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await $e(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await $e(),process.exit(0))}),process.on("exit",()=>{for(let t of ge)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function qe(e){return Yn.join(e,".ilml-browser-session.json")}function Lt(e,t={}){try{Me.writeFileSync(qe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Qn(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Lt(e,n?{wsEndpoint:n}:{})}catch{}}function Xn(e){let t=Ft(e);t&&t.ownerPid===process.pid&&he(e)}function he(e){try{Me.rmSync(qe(e),{force:!0})}catch{}}function Ft(e){try{return JSON.parse(Me.readFileSync(qe(e),"utf-8"))}catch{return null}}function Ot(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function jt(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Nt(e,t,{probeTimeoutMs:n=4e3}={}){let o=Ft(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ot(o.ownerPid)?"live":(he(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await jt(s,n,r);if(i===r)return s.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!i)return he(t),"free";if(Ot(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await jt(i.close().then(()=>!0).catch(()=>!1),n,!1))return he(t),"free";try{i.disconnect()}catch{}return"live"}function Zn(e,t){e&&(zn(),ge.add(e),e.on("disconnected",()=>{ge.delete(e),t&&he(t)}))}async function Pt(e,t={}){let n=At(),o={...Kn,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Nt(e,n)==="live")throw new Error(r);Lt(n);let s;try{s=await e.launch(o)}catch{if(await Nt(e,n)==="live")throw new Error(r);It(n);try{s=await e.launch(o)}catch(c){throw Xn(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return Zn(s,n),Qn(n,s),{browser:s,profileDir:n,needsSeed:$t(n)}}async function Mt(e,t){if(!t||!t.needsSeed)return!1;if(!Ct())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(...kt()),_t(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var qt=to(eo);qt.use(no());async function Ut(){let{browser:e,profileDir:t,needsSeed:n}=await Pt(qt),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Mt(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}pe();await _e();async function Eo(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 C(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function tn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=n;try{await Fe(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await C(1500),await Dt(e)&&(console.log(" Dismissed Premium overlay"),await C(1500),await Eo(e,t));let d=0;for(let x=0;x<2;x++){let ue=await e.evaluate(()=>document.body.scrollHeight);for(let K=1;K<=6;K++)await e.evaluate(w=>window.scrollTo(0,w),ue*K/6),await C(900);let J=await e.evaluate(()=>document.body.scrollHeight);if(J===d)break;d=J}await C(800);let p=null;try{let x=e.url();x&&/\/in\/[^/?#]/.test(x)&&(p=x.split("?")[0].replace(/\/+$/,""))}catch{}let u=await e.evaluate(()=>{let x=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"]),ue=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"]),J=h=>{let b=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(b)},K={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:[]},w=document.querySelector("main");if(!w)return K;let T=[...Array.from(w.querySelectorAll("h1")),...Array.from(w.querySelectorAll("h2"))],de=Array.from(w.querySelectorAll("h2")),se=T.find(h=>{let b=h.textContent&&h.textContent.trim(),S=(b||"").replace(/\s*\(\d+\)$/,"").trim();return b&&b.length>1&&b.length<100&&!x.has(S)&&!ue.has(S)}),ie=se?se.textContent.trim():null,O=se?se.parentElement:null;for(;O&&O!==w&&!Array.from(O.children).filter(b=>b.tagName==="P").some(b=>{let S=b.textContent&&b.textContent.trim();return S&&S.length>5&&!J(S)});)O=O.parentElement;let lt=null,at=null,ct=null,je=null;if(O&&O!==w){let h=Array.from(O.children).filter(S=>S.tagName==="P").filter(S=>{let W=S.textContent&&S.textContent.trim();return W&&W.length>5&&!J(W)});if(h[0]&&(lt=h[0].textContent.trim()),h[1]){let S=h[1].textContent.trim().split(/\s*[·•]\s*/);at=S[0]||null,S.length>1&&(ct=S.slice(1).join(" \xB7 "))}let b=Array.from(O.children).filter(S=>S.tagName==="DIV");for(let S=b.length-1;S>=0;S--){let W=b[S].textContent&&b[S].textContent.trim();if(W&&!(ie&&W.startsWith(ie))&&(je=W.split(/[·•]/)[0].trim(),je))break}}let ut=null;if(O){let h=O.querySelectorAll("p, span, div");for(let b of h){let S=(b.textContent||"").trim().replace(/^[·•]\s*/,"");if(S==="1st"||S==="2nd"||S==="3rd"){ut=S;break}}}let In=!!w.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),dt=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Rn=dt&&dt.src||null,Ce=w.textContent||"",ft=null,mt=Ce.match(/(\d+\+?)\s+connections\b/i);mt&&(ft=mt[1]+" connections");let xe=null,pt=Ce.match(/(\d+)\s+mutual connection/i),ht=Ce.match(/and\s+(\d+)\s+other mutual/i),Dn=Ce.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);pt?xe=parseInt(pt[1],10):ht?xe=2+parseInt(ht[1],10):Dn&&(xe=2);let gt=null,yt=null,wt=de.find(h=>h.textContent&&h.textContent.trim()==="About");if(wt){let h=wt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let b=(h.textContent||"").trim();b=b.replace(/^About\s*/,"").trim();let S=b.match(/Top skills\s*(.+?)$/i);if(S){let Ne=S[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Nn=>Nn.trim()).filter(Boolean);Ne.length>0&&Ne.length<10&&(yt=Ne)}b=b.split(/\n?…\s*more/i)[0].trim(),b=b.split(/\n?\.\.\.\s*more/i)[0].trim(),b=b.split(/\bTop skills\b/i)[0].trim(),b=b.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),gt=b||null}}let bt=null,St=de.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(St){let h=St.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let b=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);b&&(bt=parseInt(b[1].replace(/,/g,""),10))}}let Tn=[...new Set(de.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==ie).filter(h=>x.has(h)))],fe=document.body.textContent||"",On=/#OpenToWork\b/i.test(fe)||/\bOpen to work\b/.test(fe),jn=/#Hiring\b/i.test(fe)||/\bI'?m hiring\b/i.test(fe)||/\bWe are hiring\b/i.test(fe);return{name:ie,title:lt,location:je,currentCompany:at,currentSchool:ct,connectionDegree:ut,hasVerifiedBadge:In,photoUrl:Rn,connectionsLevel:ft,mutualConnectionsCount:xe,followers:bt,openToWork:On,hiring:jn,about:gt,topSkills:yt,availableSections:Tn}});console.log(`Viewed: ${u.name} - ${u.title}`);let m=null,E=null,k=null,_=null,y=null,g=null;if(o||r||s||i||c||l){let x=await Promise.resolve().then(()=>(en(),Zt));o&&(m=await x.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),r&&(E=await x.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${E.length} entries`)),s&&(k=await x.extractEducationFromDetails(e,t),console.log(` + Education: ${k.length} entries`)),i&&(_=await x.extractSkillsFromDetails(e,t),console.log(` + Skills: ${_.length} entries`)),c&&(y=await x.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),l&&(g=await x.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${g.length} entries`))}return{...u,profileUrl:t,resolvedUrl:p,...m!==null&&{experience:m},...E!==null&&{featured:E},...k!==null&&{education:k},..._!==null&&{skillsFull:_},...y!==null&&{recommendations:y},...g!==null&&{certifications:g}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await C(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}Re();await _e();pe();async function cn(e,t,n={}){let{maxVisits:o=50,delayBetween:r=4e3,skipRecentDays:s=7,verbose:i=!1,extractExperience:c=!1}=n,l={visited:0,skipped:0,errors:0},a=Date.now()-s*24*60*60*1e3;for(let d of t){if(l.visited>=o)break;if(!d.profileUrl)continue;let p=ln(d.profileUrl);if(p&&new Date(p).getTime()>a){l.skipped++;continue}try{let u=await tn(e,d.profileUrl,{extractExperience:c}),m=d.source||"visit";if(u){let k={...u,source:m};c&&Array.isArray(u.experience)&&u.experience.length>0&&(k._lastEnrichedAt=new Date().toISOString()),Ve(d.profileUrl,k),u.resolvedUrl&&He(d.profileUrl,u.resolvedUrl)}sn(d.profileUrl,{name:u?.name||d.name||null,source:m}),l.visited++,i?console.log(` [${l.visited}] ${u?.name||d.profileUrl} \u2014 ${u?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let E=Math.random()*4e3;await C(r+E)}catch(u){l.errors++,i&&console.error(` Error visiting ${d.name||d.profileUrl}: ${u.message?.slice(0,60)}`);let m=(u.message||"").toLowerCase();if(m.includes("detached")||m.includes("session closed")||m.includes("target closed")||m.includes("session expired")||m.includes("bounced to")||m.includes("authwall")||m.includes("checkpoint")||m.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return l}function un(e={}){let{limit:t=150,revisitDays:n=14}=e,o=ce(),r=new Set(o.visits?.map(y=>y.profileUrl)||[]),s=new Map;for(let y of o.visits||[]){let g=s.get(y.profileUrl);(!g||y.date>g)&&s.set(y.profileUrl,y.date)}let i=Date.now()-7*24*60*60*1e3,c=Date.now()-n*24*60*60*1e3;function l(y){let g=s.get(y);return g&&new Date(g).getTime()>i}let a=Ie(),d=Object.entries(a).filter(([y])=>!r.has(y)).map(([y,g])=>({profileUrl:y,name:g.name,source:"new-discovered",priority:1,jobCount:g.jobIds?.length||0})),p=ae(),u=Object.entries(p).filter(([y,g])=>g.connectionStatus==="connected"||l(y)?!1:(g.jobCount||g.jobIds?.length||0)>=2).map(([y,g])=>({profileUrl:y,name:g.name,source:"active-recruiter",priority:2,jobCount:g.jobCount||g.jobIds?.length||0})),m=Object.entries(p).filter(([y,g])=>{let U=g.connectionStatus;return!(!U||U==="connected"||U==="pending"||U==="sent_without_note"||U==="sent_with_note"||l(y)||(g.jobCount||g.jobIds?.length||0)>=2)}).map(([y,g])=>({profileUrl:y,name:g.name,source:"unconnected",priority:3,jobCount:g.jobCount||g.jobIds?.length||0})),E=[...s.entries()].filter(([y,g])=>new Date(g).getTime()<c).map(([y,g])=>({profileUrl:y,name:null,source:"revisit",priority:4,lastVisit:g})),k=y=>y.sort(()=>Math.random()-.5);return d.sort((y,g)=>g.jobCount-y.jobCount),u.sort((y,g)=>g.jobCount-y.jobCount),k(m),k(E),[...d,...u,...m,...E].slice(0,t)}function dn(){let e=Ie();return Object.entries(e).map(([t,n])=>({profileUrl:t,name:n.name,source:"discovered"}))}function We(){let e=ae();return Object.entries(e).filter(([,t])=>{let n=t.connectionStatus;return n&&n!=="connected"&&n!=="pending"&&n!=="sent_without_note"&&n!=="sent_with_note"}).map(([t,n])=>({profileUrl:t,name:n.name,source:"unconnected"}))}function Ge(e=14){let t=ce(),n=Date.now()-e*24*60*60*1e3,o=new Map;for(let r of t.visits){let s=o.get(r.profileUrl);(!s||r.date>s.date)&&o.set(r.profileUrl,r)}return[...o.entries()].filter(([,r])=>new Date(r.date).getTime()<n).map(([r,s])=>({profileUrl:r,name:s.name,source:"revisit"}))}Re();import"dotenv/config";import*as N from"fs";import*as G from"path";import{fileURLToPath as Bo}from"url";import"dotenv/config";import{createGraphClient as Fo,resolveToken as Po}from"@ilivemylife/graph-sdk";import{config as Mo}from"dotenv";Mo();var fn=Po()||process.env.TOKEN;fn||(console.error(`
239
241
  [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
242
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
241
243
  `),console.error(` Or add ILML_TOKEN=... to .env
242
- `),process.exit(1));var un=jo({token:an});function Lo(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 Fo({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Lo(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${u} \u2014 ${l} \u2014 ${i}${c}`}async function fn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=`**${Fo({scriptName:e,mode:t,status:n,error:r,duration:s})}**
244
+ `),process.exit(1));var mn=Fo({token:fn});function qo(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 Uo({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${qo(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${a} \u2014 ${l} \u2014 ${i}${c}`}async function pn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=`**${Uo({scriptName:e,mode:t,status:n,error:r,duration:s})}**
243
245
 
244
246
  ${o.join(`
245
- `)}`;try{await un.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Mo=Po(import.meta.url),qo=G.dirname(G.dirname(Mo)),We=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"collected-profiles"):G.join(qo,"collected-profiles"),Ge=G.join(We,"run-log.json");function Uo(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(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function dn(){try{if(!O.existsSync(Ge))return{runs:[]};let e=JSON.parse(O.readFileSync(Ge,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function mn(e){O.existsSync(We)||O.mkdirSync(We,{recursive:!0});try{Uo(Ge,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function pn(e,t="default"){let n=dn();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.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 s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),mn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Ye(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=dn(),c=i.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=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.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)}mn(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";fn({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as d from"fs";import*as nt from"os";import*as v from"path";import{fileURLToPath as fr}from"url";var Qe={};me(Qe,{NAME:()=>Vo,VERSION:()=>Bo,up:()=>Wo});import*as N from"fs";import*as Ie from"path";var Bo=1,Vo="normalize-jobs-and-questions",Ho=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Jo=50;function Ke(e){return N.existsSync(e)?JSON.parse(N.readFileSync(e,"utf-8")):null}function ze(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{N.writeFileSync(o,n)}catch(r){try{N.unlinkSync(o)}catch{}throw r}try{N.renameSync(o,e)}catch(r){try{N.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Wo(e,t){let n=Ie.join(e,"jobs.json"),o=Ie.join(t,"scouted-jobs.json"),r=Ie.join(e,"application-questions.json"),s=Ke(n)||{},i=Ke(o)||{},c=0,l=[];for(let f of Object.keys(s)){if(!i[f])continue;let g=i[f],a=s[f];for(let m of Ho)g[m]!=null&&a[m]==null&&(a[m]=g[m]);l.push(f),c++}c>0?(ze(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ke(r);if(u&&Array.isArray(u.applications)){let f={},g=0;for(let a of u.applications){let m=a.jobId||"unknown";f[m]||(f[m]={applications:[]});let $=(a.questions||[]).map(k=>{let _={type:k.type||"input",question:k.question||"",answer:k.answer||""};return k.options&&(k.options.length<=Jo?_.options=k.options:(_.optionsOmitted=!0,g++)),k.page&&(_.page=k.page),k.wasPreFilled&&(_.wasPreFilled=!0),k.wasRetry&&(_.wasRetry=!0),_});f[m].applications.push({applicationId:a.applicationId,date:a.date,result:a.result||"submitted",formPages:a.formPages||null,duration:a.duration||null,retries:a.retries||0,failedField:a.failedField||null,questionCount:a.questionCount||$.length,questions:$})}ze(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),g>0&&console.log(` Phase 2: Stripped bloated options from ${g} questions`)}else u&&!u.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 f of l)delete i[f];ze(o,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ze={};me(Ze,{NAME:()=>Yo,VERSION:()=>Go,up:()=>Qo});import*as L from"fs";import*as hn from"path";var Go=2,Yo="reset-unread-flags";function Ko(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function zo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Qo(e){let t=hn.join(e,"conversations.json"),n=Ko(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}zo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Xe={};me(Xe,{NAME:()=>Xo,VERSION:()=>Zo,up:()=>rr});import*as F from"fs";import*as gn from"path";var Zo=3,Xo="recompute-last-message-by",er=new Set(["draft","confirmed","rejected","needs_review"]);function tr(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function nr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function or(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!er.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function rr(e){let t=gn.join(e,"conversations.json"),n=tr(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,s=0,i=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,s++);let u=Array.isArray(l.messages)?l.messages:[],f=or(u,o),g=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&i++,l.lastMessageBy=f,l.conversationStatus=g,r++}if(r===0){console.log(" No conversations to recompute.");return}nr(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var et={};me(et,{NAME:()=>ir,VERSION:()=>sr,up:()=>ur});import*as P from"fs";import*as yn from"path";var sr=4,ir="split-connection-timestamps",lr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function cr(e){if(!P.existsSync(e))return null;let t=P.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ar(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{P.writeFileSync(o,n)}catch(r){try{P.unlinkSync(o)}catch{}throw r}try{P.renameSync(o,e)}catch(r){try{P.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ur(e){let t=yn.join(e,"people.json"),n=cr(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,lr.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ar(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 $e();_e();var dr=fr(import.meta.url),mr=v.dirname(dr),pr=v.dirname(v.dirname(mr));function hr(e){return e&&(e==="~"?nt.homedir():e.startsWith("~/")||e.startsWith("~\\")?v.join(nt.homedir(),e.slice(2)):e)}var q=process.env.DATA_DIR?v.resolve(hr(process.env.DATA_DIR)):pr,te=v.join(q,"collected-profiles"),ne=v.join(q,"market-research"),I=v.join(q,".schema-version"),wn=[v.join(te,".schema-version"),v.join(ne,".schema-version")],Y=4,V=[{version:1,module:Qe},{version:2,module:Ze},{version:3,module:Xe},{version:4,module:et}];(function(){V.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of V){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=V.length?V[V.length-1].version:0;if(n!==Y)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Y}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<V.length;o++){let r=o+1;if(V[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${V[o].version}`)}})();function kn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
247
+ `)}`;try{await mn.addMessage(i,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Vo=Bo(import.meta.url),Ho=G.dirname(G.dirname(Vo)),Ye=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"collected-profiles"):G.join(Ho,"collected-profiles"),Ke=G.join(Ye,"run-log.json");function Jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";N.writeFileSync(o,n);for(let r=0;r<3;r++)try{N.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function hn(){try{if(!N.existsSync(Ke))return{runs:[]};let e=JSON.parse(N.readFileSync(Ke,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function gn(e){N.existsSync(Ye)||N.mkdirSync(Ye,{recursive:!0});try{Jo(Ke,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function yn(e,t="default"){let n=hn();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.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 s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),gn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ze(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=hn(),c=i.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=i.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)}gn(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";pn({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as f from"fs";import*as rt from"os";import*as v from"path";import{fileURLToPath as hr}from"url";var Ze={};me(Ze,{NAME:()=>Go,VERSION:()=>Wo,up:()=>zo});import*as L from"fs";import*as De from"path";var Wo=1,Go="normalize-jobs-and-questions",Yo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ko=50;function Qe(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Xe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function zo(e,t){let n=De.join(e,"jobs.json"),o=De.join(t,"scouted-jobs.json"),r=De.join(e,"application-questions.json"),s=Qe(n)||{},i=Qe(o)||{},c=0,l=[];for(let d of Object.keys(s)){if(!i[d])continue;let p=i[d],u=s[d];for(let m of Yo)p[m]!=null&&u[m]==null&&(u[m]=p[m]);l.push(d),c++}c>0?(Xe(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Qe(r);if(a&&Array.isArray(a.applications)){let d={},p=0;for(let u of a.applications){let m=u.jobId||"unknown";d[m]||(d[m]={applications:[]});let E=(u.questions||[]).map(k=>{let _={type:k.type||"input",question:k.question||"",answer:k.answer||""};return k.options&&(k.options.length<=Ko?_.options=k.options:(_.optionsOmitted=!0,p++)),k.page&&(_.page=k.page),k.wasPreFilled&&(_.wasPreFilled=!0),k.wasRetry&&(_.wasRetry=!0),_});d[m].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||E.length,questions:E})}Xe(r,d),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(d).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} 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 d of l)delete i[d];Xe(o,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var et={};me(et,{NAME:()=>Xo,VERSION:()=>Qo,up:()=>tr});import*as F from"fs";import*as wn from"path";var Qo=2,Xo="reset-unread-flags";function Zo(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function er(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function tr(e){let t=wn.join(e,"conversations.json"),n=Zo(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}er(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var tt={};me(tt,{NAME:()=>or,VERSION:()=>nr,up:()=>ar});import*as P from"fs";import*as bn from"path";var nr=3,or="recompute-last-message-by",rr=new Set(["draft","confirmed","rejected","needs_review"]);function sr(e){return P.existsSync(e)?JSON.parse(P.readFileSync(e,"utf-8")):null}function ir(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{P.writeFileSync(o,n)}catch(r){try{P.unlinkSync(o)}catch{}throw r}try{P.renameSync(o,e)}catch(r){try{P.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function lr(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!rr.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ar(e){let t=bn.join(e,"conversations.json"),n=sr(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,s=0,i=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,s++);let a=Array.isArray(l.messages)?l.messages:[],d=lr(a,o),p=d==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==d&&i++,l.lastMessageBy=d,l.conversationStatus=p,r++}if(r===0){console.log(" No conversations to recompute.");return}ir(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var nt={};me(nt,{NAME:()=>ur,VERSION:()=>cr,up:()=>pr});import*as M from"fs";import*as Sn from"path";var cr=4,ur="split-connection-timestamps",dr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function fr(e){if(!M.existsSync(e))return null;let t=M.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function mr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{M.writeFileSync(o,n)}catch(r){try{M.unlinkSync(o)}catch{}throw r}try{M.renameSync(o,e)}catch(r){try{M.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function pr(e){let t=Sn.join(e,"people.json"),n=fr(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,dr.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}mr(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 _e();Re();var gr=hr(import.meta.url),yr=v.dirname(gr),wr=v.dirname(v.dirname(yr));function br(e){return e&&(e==="~"?rt.homedir():e.startsWith("~/")||e.startsWith("~\\")?v.join(rt.homedir(),e.slice(2)):e)}var q=process.env.DATA_DIR?v.resolve(br(process.env.DATA_DIR)):wr,ne=v.join(q,"collected-profiles"),oe=v.join(q,"market-research"),R=v.join(q,".schema-version"),vn=[v.join(ne,".schema-version"),v.join(oe,".schema-version")],Y=4,H=[{version:1,module:Ze},{version:2,module:et},{version:3,module:tt},{version:4,module:nt}];(function(){H.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of H){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=H.length?H[H.length-1].version:0;if(n!==Y)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Y}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<H.length;o++){let r=o+1;if(H[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${H[o].version}`)}})();function An(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
246
248
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
247
- `),process.exit(1));try{d.mkdirSync(q,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
249
+ `),process.exit(1));try{f.mkdirSync(q,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
248
250
  [FATAL] Cannot create DATA_DIR (${q}): ${t.message}`),console.error(` Fix the path or permissions and try again.
249
- `),process.exit(1))}let e;try{e=d.statSync(q)}catch(t){console.error(`
251
+ `),process.exit(1))}let e;try{e=f.statSync(q)}catch(t){console.error(`
250
252
  [FATAL] DATA_DIR (${q}) is not accessible: ${t.message}
251
253
  `),process.exit(1)}e.isDirectory()||(console.error(`
252
254
  [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.
253
- `),process.exit(1));for(let t of[te,ne]){let n;try{n=d.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
255
+ `),process.exit(1));for(let t of[ne,oe]){let n;try{n=f.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
254
256
  [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.
255
- `),process.exit(1))}}var ee=v.join(q,".migration-lock");function gr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return d.writeFileSync(ee,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(d.readFileSync(ee,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
256
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ee}
257
+ `),process.exit(1))}}var te=v.join(q,".migration-lock");function Sr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return f.writeFileSync(te,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(f.readFileSync(te,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
258
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${te}
257
259
  `),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.
258
- `),process.exit(1)),o&&s>=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=ee+".tmp";try{return d.writeFileSync(n,e),d.renameSync(n,ee),!0}catch(o){try{d.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function ot(){try{if(JSON.parse(d.readFileSync(ee,"utf-8")).pid!==process.pid)return;d.unlinkSync(ee)}catch{}}var bn=!1;function yr(){if(bn)return;bn=!0;let e=()=>{try{ot()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function wr(){if(d.existsSync(I))return;let e=[],t=[];for(let s of wn)if(d.existsSync(s))try{e.push({file:s,schema:Re(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
260
+ `),process.exit(1)),o&&s>=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=te+".tmp";try{return f.writeFileSync(n,e),f.renameSync(n,te),!0}catch(o){try{f.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function st(){try{if(JSON.parse(f.readFileSync(te,"utf-8")).pid!==process.pid)return;f.unlinkSync(te)}catch{}}var kn=!1;function vr(){if(kn)return;kn=!0;let e=()=>{try{st()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function kr(){if(f.existsSync(R))return;let e=[],t=[];for(let s of vn)if(f.existsSync(s))try{e.push({file:s,schema:Te(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
259
261
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
260
262
  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.
261
263
  `),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
262
264
  [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.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.
263
- `),process.exit(1)}let o=e[0].schema,r=I+".tmp";try{d.writeFileSync(r,JSON.stringify(o,null,2)),d.renameSync(r,I)}catch(s){try{d.unlinkSync(r)}catch{}throw s}for(let s of wn)if(d.existsSync(s))try{d.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${I}`)}function br(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 Re(e){let t=d.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Sn(){if(wr(),!d.existsSync(I))return{version:0,migrations:[]};let e;try{e=Re(I)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
264
- [FATAL] ${I} 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.
265
- `),process.exit(1)}let t=br(e);return t===null&&(console.error(`
266
- [FATAL] ${I} 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.
267
- `),process.exit(1)),t}function Cn(e){try{d.chmodSync(e,384)}catch{}}function Sr(e){if(kn(),d.existsSync(I))try{if(d.lstatSync(I).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${I}. 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=I+".tmp";try{d.writeFileSync(t,JSON.stringify(e,null,2)),Cn(t),d.renameSync(t,I)}catch(n){try{d.unlinkSync(t)}catch{}throw n}}function vn(e,t){if(!d.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=d.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return d.statSync(v.join(e,c)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let c of o){let l=v.join(e,c),u=v.join(e,c+n);if(d.existsSync(u)){s++;continue}try{An(l,u),r++}catch(f){i.push({file:c,err:f.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${v.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||s>0){let c=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${v.basename(e)}/ (${n})${c}`)}}var tt=!1;async function xn(){if(tt)return;kn(),Ar();let t=Sn().version;if(t===Y){tt=!0;return}yr(),gr(),process.on("exit",ot),t>Y&&(console.error(`
265
+ `),process.exit(1)}let o=e[0].schema,r=R+".tmp";try{f.writeFileSync(r,JSON.stringify(o,null,2)),f.renameSync(r,R)}catch(s){try{f.unlinkSync(r)}catch{}throw s}for(let s of vn)if(f.existsSync(s))try{f.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${R}`)}function Cr(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 Te(e){let t=f.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Cn(){if(kr(),!f.existsSync(R))return{version:0,migrations:[]};let e;try{e=Te(R)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
266
+ [FATAL] ${R} 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.
267
+ `),process.exit(1)}let t=Cr(e);return t===null&&(console.error(`
268
+ [FATAL] ${R} 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.
269
+ `),process.exit(1)),t}function En(e){try{f.chmodSync(e,384)}catch{}}function xr(e){if(An(),f.existsSync(R))try{if(f.lstatSync(R).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${R}. 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=R+".tmp";try{f.writeFileSync(t,JSON.stringify(e,null,2)),En(t),f.renameSync(t,R)}catch(n){try{f.unlinkSync(t)}catch{}throw n}}function xn(e,t){if(!f.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=f.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return f.statSync(v.join(e,c)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let c of o){let l=v.join(e,c),a=v.join(e,c+n);if(f.existsSync(a)){s++;continue}try{_n(l,a),r++}catch(d){i.push({file:c,err:d.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${v.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||s>0){let c=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${v.basename(e)}/ (${n})${c}`)}}var ot=!1;async function $n(){if(ot)return;An(),Ir();let t=Cn().version;if(t===Y){ot=!0;return}vr(),Sr(),process.on("exit",st),t>Y&&(console.error(`
268
270
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Y}.`),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.
269
271
  `),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${Y}.
270
272
  `),process.exit(1)),console.log(`
271
- \u{1F4E6} Schema migration: v${t} \u2192 v${Y}`);let n=$r();if(!n.ok){console.error(`
273
+ \u{1F4E6} Schema migration: v${t} \u2192 v${Y}`);let n=Rr();if(!n.ok){console.error(`
272
274
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
273
275
  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'.
274
- `),process.exit(1)}let o=V.filter(r=>r.version>t);for(let r of o){console.log(`
275
- Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{vn(te,r.version),vn(ne,r.version)}catch(l){console.error(`
276
+ `),process.exit(1)}let o=H.filter(r=>r.version>t);for(let r of o){console.log(`
277
+ Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{xn(ne,r.version),xn(oe,r.version)}catch(l){console.error(`
276
278
  [FATAL] Pre-migration backup failed for ${s}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
277
- `),process.exit(1)}let c=r.module;try{await c.up(te,ne)}catch(l){console.error(`
278
- [FATAL] Migration ${s} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=Er(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
279
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
280
- `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
281
- `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:r.version,name:c.NAME||s,appliedAt:l},f=Sn();f.version=r.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),Sr(f)}catch(l){console.error(`
279
+ `),process.exit(1)}let c=r.module;try{await c.up(ne,oe)}catch(l){console.error(`
280
+ [FATAL] Migration ${s} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=Dr(i);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.
281
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
282
+ `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
283
+ `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||s,appliedAt:l},d=Cn();d.version=r.version,d.migratedAt=l,d.migrations=d.migrations||[],d.migrations.push(a),xr(d)}catch(l){console.error(`
282
284
  [FATAL] Migration ${s} 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 ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
283
- `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Vt()}catch{}try{tn()}catch{}tt=!0,ot(),console.log(`
285
+ `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Wt()}catch{}try{rn()}catch{}ot=!0,st(),console.log(`
284
286
  \u2713 Schema is now at v${Y}
285
- `)}var vr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function kr(e){let t=e.toLowerCase();return vr.some(n=>n.test(t))}var Cr=6e4;function xr(){let e=Date.now(),t=[];for(let n of[q,te,ne]){if(!d.existsSync(n))continue;let o;try{o=d.readdirSync(n)}catch{continue}for(let r of o){if(!kr(r))continue;let s=v.join(n,r);try{let i=d.statSync(s);if(!i.isFile()||e-i.mtimeMs<Cr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Ar({verbose:e=!1}={}){let t=xr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{d.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${v.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 $r(){let e=[];for(let t of[te,ne]){if(!d.existsSync(t))continue;let n=d.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=v.join(t,o);try{Re(r)}catch(s){e.push({dir:v.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Er(e){let t=[],n=[];for(let s of[te,ne]){if(!d.existsSync(s))continue;let i=d.readdirSync(s).filter(c=>c.endsWith(e));for(let c of i){let l=v.join(s,c),u=c.slice(0,-e.length),f=v.join(s,u);try{u.toLowerCase().endsWith(".json")?Re(l):d.accessSync(l,d.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:s})}catch(g){n.push(`${v.basename(s)}/${c}: ${g.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:c,dir:l}of t)try{An(s,i),o++}catch(u){r.push(`${v.basename(l)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function An(e,t){let n=t+".tmp";try{d.copyFileSync(e,n),Cn(n)}catch(o){try{d.unlinkSync(n)}catch{}throw o}try{d.renameSync(n,t)}catch(o){try{d.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}}await xn();var ke=process.argv.slice(2),De=ke.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",rt=parseInt(ke.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),oe=parseInt(ke.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),_r=ke.includes("--list"),Ir=ke.includes("--verbose");function Rr(){let e=rn();console.log(`
286
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE VISIT STATS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Unique profiles visited: ${e.totalVisited}`),console.log(` Today: ${e.todayVisited}`),console.log(` Discovered recruiters: ${e.totalRecruiters} (potential visits)`);let t=He();if(console.log(` Unconnected recruiters: ${t.length}`),oe>0){let n=Je(oe);console.log(` Revisit (>${oe}d ago): ${n.length}`)}console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
287
- `)}async function Dr(){if(console.log(`
287
+ `)}var Ar=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Er(e){let t=e.toLowerCase();return Ar.some(n=>n.test(t))}var $r=6e4;function _r(){let e=Date.now(),t=[];for(let n of[q,ne,oe]){if(!f.existsSync(n))continue;let o;try{o=f.readdirSync(n)}catch{continue}for(let r of o){if(!Er(r))continue;let s=v.join(n,r);try{let i=f.statSync(s);if(!i.isFile()||e-i.mtimeMs<$r)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Ir({verbose:e=!1}={}){let t=_r();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{f.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${v.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 Rr(){let e=[];for(let t of[ne,oe]){if(!f.existsSync(t))continue;let n=f.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=v.join(t,o);try{Te(r)}catch(s){e.push({dir:v.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Dr(e){let t=[],n=[];for(let s of[ne,oe]){if(!f.existsSync(s))continue;let i=f.readdirSync(s).filter(c=>c.endsWith(e));for(let c of i){let l=v.join(s,c),a=c.slice(0,-e.length),d=v.join(s,a);try{a.toLowerCase().endsWith(".json")?Te(l):f.accessSync(l,f.constants.R_OK),t.push({backupPath:l,originalPath:d,fileName:c,dir:s})}catch(p){n.push(`${v.basename(s)}/${c}: ${p.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:c,dir:l}of t)try{_n(s,i),o++}catch(a){r.push(`${v.basename(l)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function _n(e,t){let n=t+".tmp";try{f.copyFileSync(e,n),En(n)}catch(o){try{f.unlinkSync(n)}catch{}throw o}try{f.renameSync(n,t)}catch(o){try{f.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}}await $n();var ke=process.argv.slice(2),Oe=ke.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",it=parseInt(ke.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),re=parseInt(ke.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),Tr=ke.includes("--list"),Or=ke.includes("--verbose");function jr(){let e=an();console.log(`
288
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE VISIT STATS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Unique profiles visited: ${e.totalVisited}`),console.log(` Today: ${e.todayVisited}`),console.log(` Discovered recruiters: ${e.totalRecruiters} (potential visits)`);let t=We();if(console.log(` Unconnected recruiters: ${t.length}`),re>0){let n=Ge(re);console.log(` Revisit (>${re}d ago): ${n.length}`)}console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
289
+ `)}async function Nr(){if(console.log(`
288
290
  LinkedIn Profile Visitor
289
- `),_r){Rr();return}let e=[],t="";if(oe>0?(e=Je(oe),t=`revisit (>${oe} days)`):De==="people"?(e=He(),t="unconnected recruiters (people.json)"):De==="scouted"||De==="discovered"?(e=cn(),t="discovered recruiters (market-research)"):(e=ln({limit:rt}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${rt}
291
+ `),Tr){jr();return}let e=[],t="";if(re>0?(e=Ge(re),t=`revisit (>${re} days)`):Oe==="people"?(e=We(),t="unconnected recruiters (people.json)"):Oe==="scouted"||Oe==="discovered"?(e=dn(),t="discovered recruiters (market-research)"):(e=un({limit:it}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${it}
290
292
  `),e.length===0){console.log(` No profiles to visit. Run npm run scout first.
291
- `);return}let n=pn("visit",De),{browser:o,page:r}=await Pt();try{let s=await sn(r,e,{maxVisits:rt,verbose:Ir,skipRecentDays:oe>0?0:7});console.log(`
293
+ `);return}let n=yn("visit",Oe),{browser:o,page:r}=await Ut();try{let s=await cn(r,e,{maxVisits:it,verbose:Or,skipRecentDays:re>0?0:7});console.log(`
292
294
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" Visit Complete"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Visited: ${s.visited}`),console.log(` Skipped: ${s.skipped} (visited recently)`),console.log(` Errors: ${s.errors}`),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
293
- `),Ye(n,"success",s)}catch(s){console.error(`
294
- Error:`,s.message),Ye(n,"error",null,s.message)}finally{await o.close().catch(()=>{})}}Dr().catch(e=>{console.error("Visit failed:",e),process.exit(1)});
295
+ `),ze(n,"success",s)}catch(s){console.error(`
296
+ Error:`,s.message),ze(n,"error",null,s.message)}finally{await o.close().catch(()=>{})}}Nr().catch(e=>{console.error("Visit failed:",e),process.exit(1)});
package/ilml-plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "linkedin",
3
- "version": "1.20.7",
3
+ "version": "1.20.9",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
5
5
  "commands": {
6
6
  "help": { "run": "node dist/help.mjs", "description": "List all commands with descriptions; or `help <cmd>` for detailed info on one command (usage, flags, ban-risk, when-to-use). Reads ilml-plugin.json directly.", "usage": "ilml linkedin help [<cmd>]", "useWhen": "You forgot what a command does, or you're an AI agent picking the right tool." },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ilml-plugin-linkedin",
3
- "version": "1.20.7",
3
+ "version": "1.20.9",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data and run AI-assisted workflows under your direction.",
5
5
  "type": "module",
6
6
  "files": [