ilml-plugin-linkedin 1.11.4 → 1.11.6

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,60 +1,60 @@
1
- var At=Object.defineProperty;var Ne=(e,t)=>{for(var o in t)At(e,o,{get:t[o],enumerable:!0})};import jt from"puppeteer";import{addExtra as Ot}from"puppeteer-extra";import Nt from"puppeteer-extra-plugin-stealth";async function R(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function Le(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let n of t){let s=n.innerText||"",r=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),i=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||i||l){let c=n.querySelector('button[aria-label="Dismiss"]')||n.querySelector("button.artdeco-modal__dismiss")||n.querySelector("button[data-test-modal-close-btn]");if(c)return c.click(),{dismissed:!0,matched:s.substring(0,80)};let a=n.querySelectorAll("button");for(let m of a){let w=m.innerText?.trim().toLowerCase()||"",d=m.getAttribute("aria-label")?.toLowerCase()||"";if(w==="not now"||w==="no thanks"||w==="dismiss"||d.includes("dismiss"))return m.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let n=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(n)return n.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{getPluginConfig as xt}from"@ilivemylife/graph-sdk";var Et=await xt();for(let[e,t]of Object.entries(Et))process.env[e]===void 0&&(process.env[e]=t);var _t=process.env.LINKEDIN_NAME,q=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),en=Object.freeze(new Set([q.DRAFT,q.CONFIRMED,q.NEEDS_REVIEW])),It=Object.freeze(new Set([q.DRAFT,q.CONFIRMED,q.REJECTED,q.NEEDS_REVIEW]));import Fe from"fs";import Tt from"path";var Dt="cookies.json";function Rt(){let e=process.env.ILML_SCOPE_DIR;return e?Tt.join(e,"plugins-state","linkedin","cookies.json"):Dt}function Me(){let e=Rt();if(!Fe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Fe.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}var Pe=Ot(jt);Pe.use(Nt());async function qe(){let e=await Pe.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
2
- Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let o=await e.newPage();await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let n=Me();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
1
+ var _t=Object.defineProperty;var ae=(e,t)=>{for(var o in t)_t(e,o,{get:t[o],enumerable:!0})};import Lt from"puppeteer";import{addExtra as Mt}from"puppeteer-extra";import Ft from"puppeteer-extra-plugin-stealth";async function j(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function Fe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let n of t){let s=n.innerText||"",r=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),i=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),l=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||i||l){let a=n.querySelector('button[aria-label="Dismiss"]')||n.querySelector("button.artdeco-modal__dismiss")||n.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:s.substring(0,80)};let c=n.querySelectorAll("button");for(let f of c){let g=f.innerText?.trim().toLowerCase()||"",d=f.getAttribute("aria-label")?.toLowerCase()||"";if(g==="not now"||g==="no thanks"||g==="dismiss"||d.includes("dismiss"))return f.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let n=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(n)return n.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}import{getPluginConfig as It}from"@ilivemylife/graph-sdk";var Tt=await It();for(let[e,t]of Object.entries(Tt))process.env[e]===void 0&&(process.env[e]=t);var Dt=process.env.LINKEDIN_NAME,U=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),dn=Object.freeze(new Set([U.DRAFT,U.CONFIRMED,U.NEEDS_REVIEW])),Rt=Object.freeze(new Set([U.DRAFT,U.CONFIRMED,U.REJECTED,U.NEEDS_REVIEW]));import Pe from"fs";import jt from"path";var Ot="cookies.json";function Nt(){let e=process.env.ILML_SCOPE_DIR;return e?jt.join(e,"plugins-state","linkedin","cookies.json"):Ot}function qe(){let e=Nt();if(!Pe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Pe.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}var Ue=Mt(Lt);Ue.use(Ft());async function Be(){let e=await Ue.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
2
+ Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let o=await e.newPage();await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let n=qe();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
3
3
  [!] ${n.message}
4
- `),await e.close(),process.exit(1)}return{browser:e,page:o}}import"dotenv/config";import*as v from"fs";import*as C from"path";import{fileURLToPath as Lt}from"url";var Ft=Lt(import.meta.url),Mt=C.dirname(C.dirname(Ft)),O=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"collected-profiles"):C.join(Mt,"collected-profiles"),le=C.join(O,"people.json"),bn=C.join(O,"jobs.json"),Sn=C.join(O,"quota.json"),vn=C.join(O,"conversations.json"),kn=C.join(O,"sync-state.json"),Cn=C.join(O,"application-questions.json"),ae=C.join(O,"profile-history");var G=null,Pt=null,qt=null,Ut=null,Bt=null,Vt=null;function Ve(){G=null,Pt=null,qt=null,Ut=null,Bt=null,Vt=null}function He(){v.existsSync(O)||v.mkdirSync(O,{recursive:!0})}function Je(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";v.writeFileSync(n,o);for(let s=0;s<3;s++)try{v.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function We(e,t){if(!v.existsSync(e))return null;try{let o=JSON.parse(v.readFileSync(e,"utf-8"));try{v.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${C.resolve(e)}`);let n=e+".backup";if(v.existsSync(n))try{let s=JSON.parse(v.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{v.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{v.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ht(){return new Date().toISOString().split("T")[0]}var Jt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],Wt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Gt(){v.existsSync(ae)||v.mkdirSync(ae,{recursive:!0})}function Ge(e){let t=ce(e);return t?C.join(ae,`${t}.json`):null}function Yt(e){let t=Ge(e);return t?We(t,`profile-history/${ce(e)}.json`)||[]:[]}function zt(e,t){let o=Ge(e);if(!o)return;Gt();let n=Yt(e);n.unshift(t);try{Je(o,n)}catch(s){console.error(`[!] Failed to append profile-history for ${ce(e)}: ${s.message}`)}}function Ue(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Be(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Qt(e,t){if(!e)return[];let o=[];for(let n of Wt){let s=e[n],r=t[n];Ue(s)||Ue(r)||Be(s)!==Be(r)&&o.push(n)}return o}function Kt(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[n,s]of Object.entries(e))t.has(n)||(o[n]=s);return o}function Q(){return G||(He(),G=We(le,"people.json")||{},G)}function Zt(e){He(),G=e;try{Je(le,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${C.resolve(le)}`)}}function ue(e,t={}){if(!e)return null;let o=Q(),n=Ht(),s=new Date().toISOString(),r=o[e];if(r){let i=Qt(r,t);i.length>0&&(zt(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:i,snapshot:Kt(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=n,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let l of Jt)t[l]!=null&&(r[l]=t[l]);Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,firstSeen:n,lastSeen:n,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Zt(o),o[e]}async function Xt(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await R(3e3);let n=e.url();return n.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${n.slice(0,80)}`),!0}async function Ye(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await R(3e3),await Le(e)&&(console.log(" Dismissed Premium overlay"),await R(1500),await Xt(e,t));let n=0;for(let r=0;r<2;r++){let i=await e.evaluate(()=>document.body.scrollHeight);for(let c=1;c<=6;c++)await e.evaluate(a=>window.scrollTo(0,a),i*c/6),await R(900);let l=await e.evaluate(()=>document.body.scrollHeight);if(l===n)break;n=l}await R(800);let s=await e.evaluate(()=>{let r=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"]),i=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"]),l=f=>{let h=(f||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(h)},c={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:[]},a=document.querySelector("main");if(!a)return c;let m=[...Array.from(a.querySelectorAll("h1")),...Array.from(a.querySelectorAll("h2"))],w=Array.from(a.querySelectorAll("h2")),d=m.find(f=>{let h=f.textContent&&f.textContent.trim(),b=(h||"").replace(/\s*\(\d+\)$/,"").trim();return h&&h.length>1&&h.length<100&&!r.has(b)&&!i.has(b)}),y=d?d.textContent.trim():null,k=d?d.parentElement:null;for(;k&&k!==a&&!Array.from(k.children).filter(h=>h.tagName==="P").some(h=>{let b=h.textContent&&h.textContent.trim();return b&&b.length>5&&!l(b)});)k=k.parentElement;let $=null,D=null,g=null,p=null;if(k&&k!==a){let f=Array.from(k.children).filter(b=>b.tagName==="P").filter(b=>{let F=b.textContent&&b.textContent.trim();return F&&F.length>5&&!l(F)});if(f[0]&&($=f[0].textContent.trim()),f[1]){let b=f[1].textContent.trim().split(/\s*[·•]\s*/);D=b[0]||null,b.length>1&&(g=b.slice(1).join(" \xB7 "))}let h=Array.from(k.children).filter(b=>b.tagName==="DIV");for(let b=h.length-1;b>=0;b--){let F=h[b].textContent&&h[b].textContent.trim();if(F&&!(y&&F.startsWith(y))&&(p=F.split(/[·•]/)[0].trim(),p))break}}let L=null;if(k){let f=k.querySelectorAll("p, span, div");for(let h of f){let b=(h.textContent||"").trim().replace(/^[·•]\s*/,"");if(b==="1st"||b==="2nd"||b==="3rd"){L=b;break}}}let wt=!!a.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),Ae=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),bt=Ae&&Ae.src||null,ee=a.textContent||"",xe=null,Ee=ee.match(/(\d+\+?)\s+connections\b/i);Ee&&(xe=Ee[1]+" connections");let te=null,_e=ee.match(/(\d+)\s+mutual connection/i),Ie=ee.match(/and\s+(\d+)\s+other mutual/i),St=ee.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);_e?te=parseInt(_e[1],10):Ie?te=2+parseInt(Ie[1],10):St&&(te=2);let Te=null,De=null,Re=w.find(f=>f.textContent&&f.textContent.trim()==="About");if(Re){let f=Re.parentElement;for(;f&&f.tagName!=="SECTION";)f=f.parentElement;if(f){let h=(f.textContent||"").trim();h=h.replace(/^About\s*/,"").trim();let b=h.match(/Top skills\s*(.+?)$/i);if(b){let ie=b[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map($t=>$t.trim()).filter(Boolean);ie.length>0&&ie.length<10&&(De=ie)}h=h.split(/\n?…\s*more/i)[0].trim(),h=h.split(/\n?\.\.\.\s*more/i)[0].trim(),h=h.split(/\bTop skills\b/i)[0].trim(),h=h.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Te=h||null}}let je=null,Oe=w.find(f=>f.textContent&&f.textContent.trim()==="Activity");if(Oe){let f=Oe.parentElement;for(;f&&f.tagName!=="SECTION";)f=f.parentElement;if(f){let h=(f.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);h&&(je=parseInt(h[1].replace(/,/g,""),10))}}let vt=[...new Set(w.map(f=>(f.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(f=>f&&f.length>1&&f.length<60&&f!==y).filter(f=>r.has(f)))],z=document.body.textContent||"",kt=/#OpenToWork\b/i.test(z)||/\bOpen to work\b/.test(z),Ct=/#Hiring\b/i.test(z)||/\bI'?m hiring\b/i.test(z)||/\bWe are hiring\b/i.test(z);return{name:y,title:$,location:p,currentCompany:D,currentSchool:g,connectionDegree:L,hasVerifiedBadge:wt,photoUrl:bt,connectionsLevel:xe,mutualConnectionsCount:te,followers:je,openToWork:kt,hiring:Ct,about:Te,topSkills:De,availableSections:vt}});return console.log(`Viewed: ${s.name} - ${s.title}`),{...s,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await R(1e3)}catch{}return null}}import"dotenv/config";import*as E from"fs";import*as x from"path";import{fileURLToPath as eo}from"url";var to=eo(import.meta.url),oo=x.dirname(x.dirname(to)),B=process.env.DATA_DIR?x.resolve(process.env.DATA_DIR,"market-research"):x.join(oo,"market-research"),no=x.join(B,"scouted-jobs.json"),so=x.join(B,"discovered-people.json"),ze=x.join(B,"visit-log.json"),Ln=x.join(B,"companies.json"),Fn=x.join(B,"job-decisions.json");function ro(){E.existsSync(B)||E.mkdirSync(B,{recursive:!0})}function io(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";E.writeFileSync(n,o);for(let s=0;s<3;s++)try{E.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function de(e){try{if(E.existsSync(e))return JSON.parse(E.readFileSync(e,"utf-8"))}catch{}return null}function Qe(){K=null,ao=null,Z=null,co=null,U=null}var K=null;function lo(){return K||(K=de(no)||{},K)}var ao=null;var Z=null;function oe(){return Z||(Z=de(so)||{},Z)}var co=null;var U=null;function Y(){return U||(U=de(ze)||{visits:[]},Array.isArray(U.visits)||(U.visits=[]),U)}function Ke(e,t={}){if(!e)return;ro();let o=Y();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let n=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(s=>new Date(s.date).getTime()>n);try{io(ze,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function Ze(e){let t=Y();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function Xe(){let e=lo(),t=oe(),o=Object.values(e),n=Object.values(t),s={};for(let d of o)d.company&&(s[d.company]=(s[d.company]||0)+1);let r=Object.entries(s).sort((d,y)=>y[1]-d[1]).slice(0,5).map(([d,y])=>`${d} (${y})`),i={};for(let d of o)for(let y of d.techStack||[])i[y]=(i[y]||0)+1;let l=Object.entries(i).sort((d,y)=>y[1]-d[1]).slice(0,8).map(([d,y])=>`${d} (${y})`),c=Y(),a=new Date().toISOString().slice(0,10),m=c.visits.filter(d=>d.date.startsWith(a)).length,w=new Set(c.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:n.length,topCompanies:r,topTech:l,totalVisited:w,todayVisited:m,lastScoutDate:o.length>0?o.sort((d,y)=>(y.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}async function et(e,t,o={}){let{maxVisits:n=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:i=!1}=o,l={visited:0,skipped:0,errors:0},c=Date.now()-r*24*60*60*1e3;for(let a of t){if(l.visited>=n)break;if(!a.profileUrl)continue;let m=Ze(a.profileUrl);if(m&&new Date(m).getTime()>c){l.skipped++;continue}try{let w=await Ye(e,a.profileUrl),d=a.source||"visit";w&&ue(a.profileUrl,{...w,source:d}),Ke(a.profileUrl,{name:w?.name||a.name||null,source:d}),l.visited++,i?console.log(` [${l.visited}] ${w?.name||a.profileUrl} \u2014 ${w?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let y=Math.random()*4e3;await R(s+y)}catch(w){l.errors++,i&&console.error(` Error visiting ${a.name||a.profileUrl}: ${w.message?.slice(0,60)}`);let d=(w.message||"").toLowerCase();if(d.includes("detached")||d.includes("session closed")||d.includes("target closed")){console.log(" Fatal browser error \u2014 stopping visits");break}}}return l}function tt(e={}){let{limit:t=150,revisitDays:o=14}=e,n=Y(),s=new Set(n.visits?.map(g=>g.profileUrl)||[]),r=new Map;for(let g of n.visits||[]){let p=r.get(g.profileUrl);(!p||g.date>p)&&r.set(g.profileUrl,g.date)}let i=Date.now()-7*24*60*60*1e3,l=Date.now()-o*24*60*60*1e3;function c(g){let p=r.get(g);return p&&new Date(p).getTime()>i}let a=oe(),m=Object.entries(a).filter(([g])=>!s.has(g)).map(([g,p])=>({profileUrl:g,name:p.name,source:"new-discovered",priority:1,jobCount:p.jobIds?.length||0})),w=Q(),d=Object.entries(w).filter(([g,p])=>p.connectionStatus==="connected"||c(g)?!1:(p.jobCount||p.jobIds?.length||0)>=2).map(([g,p])=>({profileUrl:g,name:p.name,source:"active-recruiter",priority:2,jobCount:p.jobCount||p.jobIds?.length||0})),y=Object.entries(w).filter(([g,p])=>{let L=p.connectionStatus;return!(!L||L==="connected"||L==="pending"||L==="sent_without_note"||L==="sent_with_note"||c(g)||(p.jobCount||p.jobIds?.length||0)>=2)}).map(([g,p])=>({profileUrl:g,name:p.name,source:"unconnected",priority:3,jobCount:p.jobCount||p.jobIds?.length||0})),k=[...r.entries()].filter(([g,p])=>new Date(p).getTime()<l).map(([g,p])=>({profileUrl:g,name:null,source:"revisit",priority:4,lastVisit:p})),$=g=>g.sort(()=>Math.random()-.5);return m.sort((g,p)=>p.jobCount-g.jobCount),d.sort((g,p)=>p.jobCount-g.jobCount),$(y),$(k),[...m,...d,...y,...k].slice(0,t)}function ot(){let e=oe();return Object.entries(e).map(([t,o])=>({profileUrl:t,name:o.name,source:"discovered"}))}function fe(){let e=Q();return Object.entries(e).filter(([,t])=>{let o=t.connectionStatus;return o&&o!=="connected"&&o!=="pending"&&o!=="sent_without_note"&&o!=="sent_with_note"}).map(([t,o])=>({profileUrl:t,name:o.name,source:"unconnected"}))}function me(e=14){let t=Y(),o=Date.now()-e*24*60*60*1e3,n=new Map;for(let s of t.visits){let r=n.get(s.profileUrl);(!r||s.date>r.date)&&n.set(s.profileUrl,s)}return[...n.entries()].filter(([,s])=>new Date(s.date).getTime()<o).map(([s,r])=>({profileUrl:s,name:r.name,source:"revisit"}))}import"dotenv/config";import*as _ from"fs";import*as M from"path";import{fileURLToPath as go}from"url";import"dotenv/config";import{createGraphClient as uo,resolveToken as fo}from"@ilivemylife/graph-sdk";import{config as mo}from"dotenv";mo();var nt=fo()||process.env.TOKEN;nt||(console.error(`
4
+ `),await e.close(),process.exit(1)}return{browser:e,page:o}}import"dotenv/config";import*as v from"fs";import*as C from"path";import{fileURLToPath as Pt}from"url";var qt=Pt(import.meta.url),Ut=C.dirname(C.dirname(qt)),N=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"collected-profiles"):C.join(Ut,"collected-profiles"),ce=C.join(N,"people.json"),In=C.join(N,"jobs.json"),Tn=C.join(N,"quota.json"),Dn=C.join(N,"conversations.json"),Rn=C.join(N,"sync-state.json"),jn=C.join(N,"application-questions.json"),ue=C.join(N,"profile-history");var Y=null,Bt=null,Vt=null,Ht=null,Jt=null,Wt=null;function Je(){Y=null,Bt=null,Vt=null,Ht=null,Jt=null,Wt=null}function We(){v.existsSync(N)||v.mkdirSync(N,{recursive:!0})}function Ge(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";v.writeFileSync(n,o);for(let s=0;s<3;s++)try{v.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Ye(e,t){if(!v.existsSync(e))return null;try{let o=JSON.parse(v.readFileSync(e,"utf-8"));try{v.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${C.resolve(e)}`);let n=e+".backup";if(v.existsSync(n))try{let s=JSON.parse(v.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{v.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{v.copyFileSync(e,e+".corrupted")}catch{}return null}}function Gt(){return new Date().toISOString().split("T")[0]}var Yt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections"],zt=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function de(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Kt(){v.existsSync(ue)||v.mkdirSync(ue,{recursive:!0})}function ze(e){let t=de(e);return t?C.join(ue,`${t}.json`):null}function Qt(e){let t=ze(e);return t?Ye(t,`profile-history/${de(e)}.json`)||[]:[]}function Zt(e,t){let o=ze(e);if(!o)return;Kt();let n=Qt(e);n.unshift(t);try{Ge(o,n)}catch(s){console.error(`[!] Failed to append profile-history for ${de(e)}: ${s.message}`)}}function Ve(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function He(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Xt(e,t){if(!e)return[];let o=[];for(let n of zt){let s=e[n],r=t[n];Ve(s)||Ve(r)||He(s)!==He(r)&&o.push(n)}return o}function eo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),o={};for(let[n,s]of Object.entries(e))t.has(n)||(o[n]=s);return o}function Q(){return Y||(We(),Y=Ye(ce,"people.json")||{},Y)}function to(e){We(),Y=e;try{Ge(ce,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${C.resolve(ce)}`)}}function fe(e,t={}){if(!e)return null;let o=Q(),n=Gt(),s=new Date().toISOString(),r=o[e];if(r){let i=Xt(r,t);i.length>0&&(Zt(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:i,snapshot:eo(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=n,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let l of Yt)t[l]!=null&&(r[l]=t[l]);Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,firstSeen:n,lastSeen:n,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return to(o),o[e]}async function oo(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let n=e.url();return n.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${n.slice(0,80)}`),!0}async function Ke(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3),await Fe(e)&&(console.log(" Dismissed Premium overlay"),await j(1500),await oo(e,t));let n=0;for(let r=0;r<2;r++){let i=await e.evaluate(()=>document.body.scrollHeight);for(let a=1;a<=6;a++)await e.evaluate(c=>window.scrollTo(0,c),i*a/6),await j(900);let l=await e.evaluate(()=>document.body.scrollHeight);if(l===n)break;n=l}await j(800);let s=await e.evaluate(()=>{let r=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"]),i=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"]),l=m=>{let h=(m||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(h)},a={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:[]},c=document.querySelector("main");if(!c)return a;let f=[...Array.from(c.querySelectorAll("h1")),...Array.from(c.querySelectorAll("h2"))],g=Array.from(c.querySelectorAll("h2")),d=f.find(m=>{let h=m.textContent&&m.textContent.trim(),b=(h||"").replace(/\s*\(\d+\)$/,"").trim();return h&&h.length>1&&h.length<100&&!r.has(b)&&!i.has(b)}),w=d?d.textContent.trim():null,k=d?d.parentElement:null;for(;k&&k!==c&&!Array.from(k.children).filter(h=>h.tagName==="P").some(h=>{let b=h.textContent&&h.textContent.trim();return b&&b.length>5&&!l(b)});)k=k.parentElement;let $=null,R=null,y=null,p=null;if(k&&k!==c){let m=Array.from(k.children).filter(b=>b.tagName==="P").filter(b=>{let F=b.textContent&&b.textContent.trim();return F&&F.length>5&&!l(F)});if(m[0]&&($=m[0].textContent.trim()),m[1]){let b=m[1].textContent.trim().split(/\s*[·•]\s*/);R=b[0]||null,b.length>1&&(y=b.slice(1).join(" \xB7 "))}let h=Array.from(k.children).filter(b=>b.tagName==="DIV");for(let b=h.length-1;b>=0;b--){let F=h[b].textContent&&h[b].textContent.trim();if(F&&!(w&&F.startsWith(w))&&(p=F.split(/[·•]/)[0].trim(),p))break}}let M=null;if(k){let m=k.querySelectorAll("p, span, div");for(let h of m){let b=(h.textContent||"").trim().replace(/^[·•]\s*/,"");if(b==="1st"||b==="2nd"||b==="3rd"){M=b;break}}}let vt=!!c.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),_e=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),kt=_e&&_e.src||null,te=c.textContent||"",Ie=null,Te=te.match(/(\d+\+?)\s+connections\b/i);Te&&(Ie=Te[1]+" connections");let oe=null,De=te.match(/(\d+)\s+mutual connection/i),Re=te.match(/and\s+(\d+)\s+other mutual/i),Ct=te.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);De?oe=parseInt(De[1],10):Re?oe=2+parseInt(Re[1],10):Ct&&(oe=2);let je=null,Oe=null,Ne=g.find(m=>m.textContent&&m.textContent.trim()==="About");if(Ne){let m=Ne.parentElement;for(;m&&m.tagName!=="SECTION";)m=m.parentElement;if(m){let h=(m.textContent||"").trim();h=h.replace(/^About\s*/,"").trim();let b=h.match(/Top skills\s*(.+?)$/i);if(b){let le=b[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(xt=>xt.trim()).filter(Boolean);le.length>0&&le.length<10&&(Oe=le)}h=h.split(/\n?…\s*more/i)[0].trim(),h=h.split(/\n?\.\.\.\s*more/i)[0].trim(),h=h.split(/\bTop skills\b/i)[0].trim(),h=h.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),je=h||null}}let Le=null,Me=g.find(m=>m.textContent&&m.textContent.trim()==="Activity");if(Me){let m=Me.parentElement;for(;m&&m.tagName!=="SECTION";)m=m.parentElement;if(m){let h=(m.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);h&&(Le=parseInt(h[1].replace(/,/g,""),10))}}let $t=[...new Set(g.map(m=>(m.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(m=>m&&m.length>1&&m.length<60&&m!==w).filter(m=>r.has(m)))],K=document.body.textContent||"",At=/#OpenToWork\b/i.test(K)||/\bOpen to work\b/.test(K),Et=/#Hiring\b/i.test(K)||/\bI'?m hiring\b/i.test(K)||/\bWe are hiring\b/i.test(K);return{name:w,title:$,location:p,currentCompany:R,currentSchool:y,connectionDegree:M,hasVerifiedBadge:vt,photoUrl:kt,connectionsLevel:Ie,mutualConnectionsCount:oe,followers:Le,openToWork:At,hiring:Et,about:je,topSkills:Oe,availableSections:$t}});return console.log(`Viewed: ${s.name} - ${s.title}`),{...s,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await j(1e3)}catch{}return null}}import"dotenv/config";import*as x from"fs";import*as E from"path";import{fileURLToPath as no}from"url";var so=no(import.meta.url),ro=E.dirname(E.dirname(so)),V=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"market-research"):E.join(ro,"market-research"),io=E.join(V,"scouted-jobs.json"),lo=E.join(V,"discovered-people.json"),Qe=E.join(V,"visit-log.json"),Wn=E.join(V,"companies.json"),Gn=E.join(V,"job-decisions.json");function ao(){x.existsSync(V)||x.mkdirSync(V,{recursive:!0})}function co(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";x.writeFileSync(n,o);for(let s=0;s<3;s++)try{x.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function me(e){try{if(x.existsSync(e))return JSON.parse(x.readFileSync(e,"utf-8"))}catch{}return null}function Ze(){Z=null,fo=null,X=null,mo=null,B=null}var Z=null;function uo(){return Z||(Z=me(io)||{},Z)}var fo=null;var X=null;function ne(){return X||(X=me(lo)||{},X)}var mo=null;var B=null;function z(){return B||(B=me(Qe)||{visits:[]},Array.isArray(B.visits)||(B.visits=[]),B)}function Xe(e,t={}){if(!e)return;ao();let o=z();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let n=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(s=>new Date(s.date).getTime()>n);try{co(Qe,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function et(e){let t=z();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function tt(){let e=uo(),t=ne(),o=Object.values(e),n=Object.values(t),s={};for(let d of o)d.company&&(s[d.company]=(s[d.company]||0)+1);let r=Object.entries(s).sort((d,w)=>w[1]-d[1]).slice(0,5).map(([d,w])=>`${d} (${w})`),i={};for(let d of o)for(let w of d.techStack||[])i[w]=(i[w]||0)+1;let l=Object.entries(i).sort((d,w)=>w[1]-d[1]).slice(0,8).map(([d,w])=>`${d} (${w})`),a=z(),c=new Date().toISOString().slice(0,10),f=a.visits.filter(d=>d.date.startsWith(c)).length,g=new Set(a.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:n.length,topCompanies:r,topTech:l,totalVisited:g,todayVisited:f,lastScoutDate:o.length>0?o.sort((d,w)=>(w.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}async function ot(e,t,o={}){let{maxVisits:n=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:i=!1}=o,l={visited:0,skipped:0,errors:0},a=Date.now()-r*24*60*60*1e3;for(let c of t){if(l.visited>=n)break;if(!c.profileUrl)continue;let f=et(c.profileUrl);if(f&&new Date(f).getTime()>a){l.skipped++;continue}try{let g=await Ke(e,c.profileUrl),d=c.source||"visit";g&&fe(c.profileUrl,{...g,source:d}),Xe(c.profileUrl,{name:g?.name||c.name||null,source:d}),l.visited++,i?console.log(` [${l.visited}] ${g?.name||c.profileUrl} \u2014 ${g?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let w=Math.random()*4e3;await j(s+w)}catch(g){l.errors++,i&&console.error(` Error visiting ${c.name||c.profileUrl}: ${g.message?.slice(0,60)}`);let d=(g.message||"").toLowerCase();if(d.includes("detached")||d.includes("session closed")||d.includes("target closed")){console.log(" Fatal browser error \u2014 stopping visits");break}}}return l}function nt(e={}){let{limit:t=150,revisitDays:o=14}=e,n=z(),s=new Set(n.visits?.map(y=>y.profileUrl)||[]),r=new Map;for(let y of n.visits||[]){let p=r.get(y.profileUrl);(!p||y.date>p)&&r.set(y.profileUrl,y.date)}let i=Date.now()-7*24*60*60*1e3,l=Date.now()-o*24*60*60*1e3;function a(y){let p=r.get(y);return p&&new Date(p).getTime()>i}let c=ne(),f=Object.entries(c).filter(([y])=>!s.has(y)).map(([y,p])=>({profileUrl:y,name:p.name,source:"new-discovered",priority:1,jobCount:p.jobIds?.length||0})),g=Q(),d=Object.entries(g).filter(([y,p])=>p.connectionStatus==="connected"||a(y)?!1:(p.jobCount||p.jobIds?.length||0)>=2).map(([y,p])=>({profileUrl:y,name:p.name,source:"active-recruiter",priority:2,jobCount:p.jobCount||p.jobIds?.length||0})),w=Object.entries(g).filter(([y,p])=>{let M=p.connectionStatus;return!(!M||M==="connected"||M==="pending"||M==="sent_without_note"||M==="sent_with_note"||a(y)||(p.jobCount||p.jobIds?.length||0)>=2)}).map(([y,p])=>({profileUrl:y,name:p.name,source:"unconnected",priority:3,jobCount:p.jobCount||p.jobIds?.length||0})),k=[...r.entries()].filter(([y,p])=>new Date(p).getTime()<l).map(([y,p])=>({profileUrl:y,name:null,source:"revisit",priority:4,lastVisit:p})),$=y=>y.sort(()=>Math.random()-.5);return f.sort((y,p)=>p.jobCount-y.jobCount),d.sort((y,p)=>p.jobCount-y.jobCount),$(w),$(k),[...f,...d,...w,...k].slice(0,t)}function st(){let e=ne();return Object.entries(e).map(([t,o])=>({profileUrl:t,name:o.name,source:"discovered"}))}function pe(){let e=Q();return Object.entries(e).filter(([,t])=>{let o=t.connectionStatus;return o&&o!=="connected"&&o!=="pending"&&o!=="sent_without_note"&&o!=="sent_with_note"}).map(([t,o])=>({profileUrl:t,name:o.name,source:"unconnected"}))}function he(e=14){let t=z(),o=Date.now()-e*24*60*60*1e3,n=new Map;for(let s of t.visits){let r=n.get(s.profileUrl);(!r||s.date>r.date)&&n.set(s.profileUrl,s)}return[...n.entries()].filter(([,s])=>new Date(s.date).getTime()<o).map(([s,r])=>({profileUrl:s,name:r.name,source:"revisit"}))}import"dotenv/config";import*as _ from"fs";import*as P from"path";import{fileURLToPath as bo}from"url";import"dotenv/config";import{createGraphClient as po,resolveToken as ho}from"@ilivemylife/graph-sdk";import{config as go}from"dotenv";go();var rt=ho()||process.env.TOKEN;rt||(console.error(`
5
5
  [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.
6
6
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
7
7
  `),console.error(` Or add ILML_TOKEN=... to .env
8
- `),process.exit(1));var st=uo({token:nt});function po(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n?`${o}m ${n}s`:`${o}m`}function ho({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${po(s)}`:"",c=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function rt({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let c=`**${ho({scriptName:e,mode:t,status:o,error:s,duration:r})}**
8
+ `),process.exit(1));var it=po({token:rt});function yo(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n?`${o}m ${n}s`:`${o}m`}function wo({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${yo(s)}`:"",a=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${c} \u2014 ${a} \u2014 ${i}${l}`}async function lt({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let a=`**${wo({scriptName:e,mode:t,status:o,error:s,duration:r})}**
9
9
 
10
10
  ${n.join(`
11
- `)}`;try{await st.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var yo=go(import.meta.url),wo=M.dirname(M.dirname(yo)),pe=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(wo,"collected-profiles"),he=M.join(pe,"run-log.json");function bo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";_.writeFileSync(n,o);for(let s=0;s<3;s++)try{_.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function it(){try{if(!_.existsSync(he))return{runs:[]};let e=JSON.parse(_.readFileSync(he,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function lt(e){_.existsSync(pe)||_.mkdirSync(pe,{recursive:!0});try{bo(he,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function at(e,t="default"){let o=it();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),lt(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function ge(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=it(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,s=c.duration)}lt(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";rt({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as u from"fs";import*as ke from"os";import*as S from"path";import{fileURLToPath as To}from"url";var be={};Ne(be,{NAME:()=>vo,VERSION:()=>So,up:()=>$o});import*as I from"fs";import*as ne from"path";var So=1,vo="normalize-jobs-and-questions",ko=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Co=50;function ye(e){return I.existsSync(e)?JSON.parse(I.readFileSync(e,"utf-8")):null}function we(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{I.writeFileSync(n,o)}catch(s){try{I.unlinkSync(n)}catch{}throw s}try{I.renameSync(n,e)}catch(s){try{I.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function $o(e,t){let o=ne.join(e,"jobs.json"),n=ne.join(t,"scouted-jobs.json"),s=ne.join(e,"application-questions.json"),r=ye(o)||{},i=ye(n)||{},l=0,c=[];for(let m of Object.keys(r)){if(!i[m])continue;let w=i[m],d=r[m];for(let y of ko)w[y]!=null&&d[y]==null&&(d[y]=w[y]);c.push(m),l++}l>0?(we(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ye(s);if(a&&Array.isArray(a.applications)){let m={},w=0;for(let d of a.applications){let y=d.jobId||"unknown";m[y]||(m[y]={applications:[]});let k=(d.questions||[]).map($=>{let D={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=Co?D.options=$.options:(D.optionsOmitted=!0,w++)),$.page&&(D.page=$.page),$.wasPreFilled&&(D.wasPreFilled=!0),$.wasRetry&&(D.wasRetry=!0),D});m[y].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||k.length,questions:k})}we(s,m),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(m).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} 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(c.length>0){for(let m of c)delete i[m];we(n,i),console.log(` Phase 3: Removed ${c.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 Se={};Ne(Se,{NAME:()=>xo,VERSION:()=>Ao,up:()=>Io});import*as T from"fs";import*as ct from"path";var Ao=2,xo="reset-unread-flags";function Eo(e){return T.existsSync(e)?JSON.parse(T.readFileSync(e,"utf-8")):null}function _o(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{T.writeFileSync(n,o)}catch(s){try{T.unlinkSync(n)}catch{}throw s}try{T.renameSync(n,e)}catch(s){try{T.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Io(e){let t=ct.join(e,"conversations.json"),o=Eo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}_o(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Do=To(import.meta.url),Ro=S.dirname(Do),jo=S.dirname(S.dirname(Ro));function Oo(e){return e&&(e==="~"?ke.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(ke.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?S.resolve(Oo(process.env.DATA_DIR)):jo,H=S.join(j,"collected-profiles"),J=S.join(j,"market-research"),A=S.join(j,".schema-version"),ut=[S.join(H,".schema-version"),S.join(J,".schema-version")],P=2,N=[{version:1,module:be},{version:2,module:Se}];(function(){N.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of N){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=N.length?N[N.length-1].version:0;if(o!==P)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${P}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<N.length;n++){let s=n+1;if(N[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${N[n].version}`)}})();function pt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
11
+ `)}`;try{await it.addMessage(i,a)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var So=bo(import.meta.url),vo=P.dirname(P.dirname(So)),ge=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(vo,"collected-profiles"),ye=P.join(ge,"run-log.json");function ko(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";_.writeFileSync(n,o);for(let s=0;s<3;s++)try{_.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function at(){try{if(!_.existsSync(ye))return{runs:[]};let e=JSON.parse(_.readFileSync(ye,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ct(e){_.existsSync(ge)||_.mkdirSync(ge,{recursive:!0});try{ko(ye,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ut(e,t="default"){let o=at();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),ct(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function we(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=at(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration;else{let a=i.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=n,s=a.duration)}ct(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";lt({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as u from"fs";import*as Ae from"os";import*as S from"path";import{fileURLToPath as qo}from"url";var ve={};ae(ve,{NAME:()=>$o,VERSION:()=>Co,up:()=>xo});import*as I from"fs";import*as se from"path";var Co=1,$o="normalize-jobs-and-questions",Ao=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Eo=50;function be(e){return I.existsSync(e)?JSON.parse(I.readFileSync(e,"utf-8")):null}function Se(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{I.writeFileSync(n,o)}catch(s){try{I.unlinkSync(n)}catch{}throw s}try{I.renameSync(n,e)}catch(s){try{I.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function xo(e,t){let o=se.join(e,"jobs.json"),n=se.join(t,"scouted-jobs.json"),s=se.join(e,"application-questions.json"),r=be(o)||{},i=be(n)||{},l=0,a=[];for(let f of Object.keys(r)){if(!i[f])continue;let g=i[f],d=r[f];for(let w of Ao)g[w]!=null&&d[w]==null&&(d[w]=g[w]);a.push(f),l++}l>0?(Se(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=be(s);if(c&&Array.isArray(c.applications)){let f={},g=0;for(let d of c.applications){let w=d.jobId||"unknown";f[w]||(f[w]={applications:[]});let k=(d.questions||[]).map($=>{let R={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=Eo?R.options=$.options:(R.optionsOmitted=!0,g++)),$.page&&(R.page=$.page),$.wasPreFilled&&(R.wasPreFilled=!0),$.wasRetry&&(R.wasRetry=!0),R});f[w].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||k.length,questions:k})}Se(s,f),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),g>0&&console.log(` Phase 2: Stripped bloated options from ${g} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let f of a)delete i[f];Se(n,i),console.log(` Phase 3: Removed ${a.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 ke={};ae(ke,{NAME:()=>Io,VERSION:()=>_o,up:()=>Ro});import*as T from"fs";import*as dt from"path";var _o=2,Io="reset-unread-flags";function To(e){return T.existsSync(e)?JSON.parse(T.readFileSync(e,"utf-8")):null}function Do(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{T.writeFileSync(n,o)}catch(s){try{T.unlinkSync(n)}catch{}throw s}try{T.renameSync(n,e)}catch(s){try{T.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Ro(e){let t=dt.join(e,"conversations.json"),o=To(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Do(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ce={};ae(Ce,{NAME:()=>Oo,VERSION:()=>jo,up:()=>Po});import*as D from"fs";import*as ft from"path";var jo=3,Oo="recompute-last-message-by",No=new Set(["draft","confirmed","rejected","needs_review"]);function Lo(e){return D.existsSync(e)?JSON.parse(D.readFileSync(e,"utf-8")):null}function Mo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{D.writeFileSync(n,o)}catch(s){try{D.unlinkSync(n)}catch{}throw s}try{D.renameSync(n,e)}catch(s){try{D.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Fo(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!No.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Po(e){let t=ft.join(e,"conversations.json"),o=Lo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.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 s=0,r=0,i=0;for(let l of Object.keys(o)){let a=o[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let c=Array.isArray(a.messages)?a.messages:[],f=Fo(c,n),g=f==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==f&&i++,a.lastMessageBy=f,a.conversationStatus=g,s++}if(s===0){console.log(" No conversations to recompute.");return}Mo(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Uo=qo(import.meta.url),Bo=S.dirname(Uo),Vo=S.dirname(S.dirname(Bo));function Ho(e){return e&&(e==="~"?Ae.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(Ae.homedir(),e.slice(2)):e)}var O=process.env.DATA_DIR?S.resolve(Ho(process.env.DATA_DIR)):Vo,J=S.join(O,"collected-profiles"),W=S.join(O,"market-research"),A=S.join(O,".schema-version"),mt=[S.join(J,".schema-version"),S.join(W,".schema-version")],q=3,L=[{version:1,module:ve},{version:2,module:ke},{version:3,module:Ce}];(function(){L.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of L){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=L.length?L[L.length-1].version:0;if(o!==q)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<L.length;n++){let s=n+1;if(L[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${L[n].version}`)}})();function yt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
12
12
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
13
- `),process.exit(1));try{u.mkdirSync(j,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
- [FATAL] Cannot create DATA_DIR (${j}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
- `),process.exit(1))}let e;try{e=u.statSync(j)}catch(t){console.error(`
16
- [FATAL] DATA_DIR (${j}) is not accessible: ${t.message}
13
+ `),process.exit(1));try{u.mkdirSync(O,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
+ [FATAL] Cannot create DATA_DIR (${O}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
+ `),process.exit(1))}let e;try{e=u.statSync(O)}catch(t){console.error(`
16
+ [FATAL] DATA_DIR (${O}) is not accessible: ${t.message}
17
17
  `),process.exit(1)}e.isDirectory()||(console.error(`
18
- [FATAL] DATA_DIR (${j}) 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.
19
- `),process.exit(1));for(let t of[H,J]){let o;try{o=u.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
18
+ [FATAL] DATA_DIR (${O}) 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.
19
+ `),process.exit(1));for(let t of[J,W]){let o;try{o=u.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
20
20
  [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.
21
- `),process.exit(1))}}var V=S.join(j,".migration-lock");function No(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(V,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(u.readFileSync(V,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}n&&r<s&&(console.error(`
22
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${V}
21
+ `),process.exit(1))}}var H=S.join(O,".migration-lock");function Jo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(H,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(u.readFileSync(H,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}n&&r<s&&(console.error(`
22
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${H}
23
23
  `),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.
24
- `),process.exit(1)),n&&r>=s&&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 o=V+".tmp";try{return u.writeFileSync(o,e),u.renameSync(o,V),!0}catch(n){try{u.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function Ce(){try{if(JSON.parse(u.readFileSync(V,"utf-8")).pid!==process.pid)return;u.unlinkSync(V)}catch{}}var dt=!1;function Lo(){if(dt)return;dt=!0;let e=()=>{try{Ce()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Fo(){if(u.existsSync(A))return;let e=[],t=[];for(let r of ut)if(u.existsSync(r))try{e.push({file:r,schema:se(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
24
+ `),process.exit(1)),n&&r>=s&&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 o=H+".tmp";try{return u.writeFileSync(o,e),u.renameSync(o,H),!0}catch(n){try{u.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function Ee(){try{if(JSON.parse(u.readFileSync(H,"utf-8")).pid!==process.pid)return;u.unlinkSync(H)}catch{}}var pt=!1;function Wo(){if(pt)return;pt=!0;let e=()=>{try{Ee()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Go(){if(u.existsSync(A))return;let e=[],t=[];for(let r of mt)if(u.existsSync(r))try{e.push({file:r,schema:re(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
25
25
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
26
26
  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.
27
27
  `),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
28
28
  [FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.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.
29
- `),process.exit(1)}let n=e[0].schema,s=A+".tmp";try{u.writeFileSync(s,JSON.stringify(n,null,2)),u.renameSync(s,A)}catch(r){try{u.unlinkSync(s)}catch{}throw r}for(let r of ut)if(u.existsSync(r))try{u.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${A}`)}function Mo(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 se(e){let t=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ft(){if(Fo(),!u.existsSync(A))return{version:0,migrations:[]};let e;try{e=se(A)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
29
+ `),process.exit(1)}let n=e[0].schema,s=A+".tmp";try{u.writeFileSync(s,JSON.stringify(n,null,2)),u.renameSync(s,A)}catch(r){try{u.unlinkSync(s)}catch{}throw r}for(let r of mt)if(u.existsSync(r))try{u.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${A}`)}function Yo(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=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ht(){if(Go(),!u.existsSync(A))return{version:0,migrations:[]};let e;try{e=re(A)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
30
30
  [FATAL] ${A} is not valid JSON: ${o.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.
31
- `),process.exit(1)}let t=Mo(e);return t===null&&(console.error(`
31
+ `),process.exit(1)}let t=Yo(e);return t===null&&(console.error(`
32
32
  [FATAL] ${A} 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.
33
- `),process.exit(1)),t}function ht(e){try{u.chmodSync(e,384)}catch{}}function Po(e){if(pt(),u.existsSync(A))try{if(u.lstatSync(A).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${A}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=A+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),ht(t),u.renameSync(t,A)}catch(o){try{u.unlinkSync(t)}catch{}throw o}}function mt(e,t){if(!u.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=u.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return u.statSync(S.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let c=S.join(e,l),a=S.join(e,l+o);if(u.existsSync(a)){r++;continue}try{yt(c,a),s++}catch(m){i.push({file:l,err:m.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${S.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${S.basename(e)}/ (${o})${l}`)}}var ve=!1;async function gt(){if(ve)return;pt(),Ho();let t=ft().version;if(t===P){ve=!0;return}Lo(),No(),process.on("exit",Ce),t>P&&(console.error(`
34
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${P}.`),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.
35
- `),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${P}.
33
+ `),process.exit(1)),t}function wt(e){try{u.chmodSync(e,384)}catch{}}function zo(e){if(yt(),u.existsSync(A))try{if(u.lstatSync(A).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${A}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=A+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),wt(t),u.renameSync(t,A)}catch(o){try{u.unlinkSync(t)}catch{}throw o}}function gt(e,t){if(!u.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=u.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return u.statSync(S.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let a=S.join(e,l),c=S.join(e,l+o);if(u.existsSync(c)){r++;continue}try{St(a,c),s++}catch(f){i.push({file:l,err:f.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${S.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${S.basename(e)}/ (${o})${l}`)}}var $e=!1;async function bt(){if($e)return;yt(),en();let t=ht().version;if(t===q){$e=!0;return}Wo(),Jo(),process.on("exit",Ee),t>q&&(console.error(`
34
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${q}.`),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.
35
+ `),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${q}.
36
36
  `),process.exit(1)),console.log(`
37
- \u{1F4E6} Schema migration: v${t} \u2192 v${P}`);let o=Jo();if(!o.ok){console.error(`
37
+ \u{1F4E6} Schema migration: v${t} \u2192 v${q}`);let o=tn();if(!o.ok){console.error(`
38
38
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
39
39
  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'.
40
- `),process.exit(1)}let n=N.filter(s=>s.version>t);for(let s of n){console.log(`
41
- Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{mt(H,s.version),mt(J,s.version)}catch(c){console.error(`
42
- [FATAL] Pre-migration backup failed for ${r}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
43
- `),process.exit(1)}let l=s.module;try{await l.up(H,J)}catch(c){console.error(`
44
- [FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=Wo(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.
45
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
46
- `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
47
- `)}process.exit(1)}try{let c=new Date().toISOString(),a={version:s.version,name:l.NAME||r,appliedAt:c},m=ft();m.version=s.version,m.migratedAt=c,m.migrations=m.migrations||[],m.migrations.push(a),Po(m)}catch(c){console.error(`
48
- [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
49
- `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{Ve()}catch{}try{Qe()}catch{}ve=!0,Ce(),console.log(`
50
- \u2713 Schema is now at v${P}
51
- `)}var qo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Uo(e){let t=e.toLowerCase();return qo.some(o=>o.test(t))}var Bo=6e4;function Vo(){let e=Date.now(),t=[];for(let o of[j,H,J]){if(!u.existsSync(o))continue;let n;try{n=u.readdirSync(o)}catch{continue}for(let s of n){if(!Uo(s))continue;let r=S.join(o,s);try{let i=u.statSync(r);if(!i.isFile()||e-i.mtimeMs<Bo)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function Ho({verbose:e=!1}={}){let t=Vo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{u.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${S.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Jo(){let e=[];for(let t of[H,J]){if(!u.existsSync(t))continue;let o=u.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=S.join(t,n);try{se(s)}catch(r){e.push({dir:S.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Wo(e){let t=[],o=[];for(let r of[H,J]){if(!u.existsSync(r))continue;let i=u.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let c=S.join(r,l),a=l.slice(0,-e.length),m=S.join(r,a);try{a.toLowerCase().endsWith(".json")?se(c):u.accessSync(c,u.constants.R_OK),t.push({backupPath:c,originalPath:m,fileName:l,dir:r})}catch(w){o.push(`${S.basename(r)}/${l}: ${w.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:c}of t)try{yt(r,i),n++}catch(a){s.push(`${S.basename(c)}/${l}: ${a.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function yt(e,t){let o=t+".tmp";try{u.copyFileSync(e,o),ht(o)}catch(n){try{u.unlinkSync(o)}catch{}throw n}try{u.renameSync(o,t)}catch(n){try{u.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${t} (${n.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 s.code=n.code,s}throw n}}await gt();var X=process.argv.slice(2),re=X.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",$e=parseInt(X.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),W=parseInt(X.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),Go=X.includes("--list"),Yo=X.includes("--verbose");function zo(){let e=Xe();console.log(`
52
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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=fe();if(console.log(` Unconnected recruiters: ${t.length}`),W>0){let o=me(W);console.log(` Revisit (>${W}d ago): ${o.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
53
- `)}async function Qo(){if(console.log(`
40
+ `),process.exit(1)}let n=L.filter(s=>s.version>t);for(let s of n){console.log(`
41
+ Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{gt(J,s.version),gt(W,s.version)}catch(a){console.error(`
42
+ [FATAL] Pre-migration backup failed for ${r}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
43
+ `),process.exit(1)}let l=s.module;try{await l.up(J,W)}catch(a){console.error(`
44
+ [FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let c=on(i);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
45
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
46
+ `))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
47
+ `)}process.exit(1)}try{let a=new Date().toISOString(),c={version:s.version,name:l.NAME||r,appliedAt:a},f=ht();f.version=s.version,f.migratedAt=a,f.migrations=f.migrations||[],f.migrations.push(c),zo(f)}catch(a){console.error(`
48
+ [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
49
+ `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{Je()}catch{}try{Ze()}catch{}$e=!0,Ee(),console.log(`
50
+ \u2713 Schema is now at v${q}
51
+ `)}var Ko=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Qo(e){let t=e.toLowerCase();return Ko.some(o=>o.test(t))}var Zo=6e4;function Xo(){let e=Date.now(),t=[];for(let o of[O,J,W]){if(!u.existsSync(o))continue;let n;try{n=u.readdirSync(o)}catch{continue}for(let s of n){if(!Qo(s))continue;let r=S.join(o,s);try{let i=u.statSync(r);if(!i.isFile()||e-i.mtimeMs<Zo)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function en({verbose:e=!1}={}){let t=Xo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{u.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${S.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function tn(){let e=[];for(let t of[J,W]){if(!u.existsSync(t))continue;let o=u.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=S.join(t,n);try{re(s)}catch(r){e.push({dir:S.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function on(e){let t=[],o=[];for(let r of[J,W]){if(!u.existsSync(r))continue;let i=u.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let a=S.join(r,l),c=l.slice(0,-e.length),f=S.join(r,c);try{c.toLowerCase().endsWith(".json")?re(a):u.accessSync(a,u.constants.R_OK),t.push({backupPath:a,originalPath:f,fileName:l,dir:r})}catch(g){o.push(`${S.basename(r)}/${l}: ${g.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of t)try{St(r,i),n++}catch(c){s.push(`${S.basename(a)}/${l}: ${c.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function St(e,t){let o=t+".tmp";try{u.copyFileSync(e,o),wt(o)}catch(n){try{u.unlinkSync(o)}catch{}throw n}try{u.renameSync(o,t)}catch(n){try{u.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${t} (${n.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 s.code=n.code,s}throw n}}await bt();var ee=process.argv.slice(2),ie=ee.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",xe=parseInt(ee.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),G=parseInt(ee.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),nn=ee.includes("--list"),sn=ee.includes("--verbose");function rn(){let e=tt();console.log(`
52
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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=pe();if(console.log(` Unconnected recruiters: ${t.length}`),G>0){let o=he(G);console.log(` Revisit (>${G}d ago): ${o.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
53
+ `)}async function ln(){if(console.log(`
54
54
  LinkedIn Profile Visitor
55
- `),Go){zo();return}let e=[],t="";if(W>0?(e=me(W),t=`revisit (>${W} days)`):re==="people"?(e=fe(),t="unconnected recruiters (people.json)"):re==="scouted"||re==="discovered"?(e=ot(),t="discovered recruiters (market-research)"):(e=tt({limit:$e}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${$e}
55
+ `),nn){rn();return}let e=[],t="";if(G>0?(e=he(G),t=`revisit (>${G} days)`):ie==="people"?(e=pe(),t="unconnected recruiters (people.json)"):ie==="scouted"||ie==="discovered"?(e=st(),t="discovered recruiters (market-research)"):(e=nt({limit:xe}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${xe}
56
56
  `),e.length===0){console.log(` No profiles to visit. Run npm run scout first.
57
- `);return}let o=at("visit",re),{browser:n,page:s}=await qe();try{let r=await et(s,e,{maxVisits:$e,verbose:Yo,skipRecentDays:W>0?0:7});console.log(`
57
+ `);return}let o=ut("visit",ie),{browser:n,page:s}=await Be();try{let r=await ot(s,e,{maxVisits:xe,verbose:sn,skipRecentDays:G>0?0:7});console.log(`
58
58
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${r.visited}`),console.log(` Skipped: ${r.skipped} (visited recently)`),console.log(` Errors: ${r.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
59
- `),ge(o,"success",r)}catch(r){console.error(`
60
- Error:`,r.message),ge(o,"error",null,r.message)}finally{await n.close().catch(()=>{})}}Qo().catch(e=>{console.error("Visit failed:",e),process.exit(1)});
59
+ `),we(o,"success",r)}catch(r){console.error(`
60
+ Error:`,r.message),we(o,"error",null,r.message)}finally{await n.close().catch(()=>{})}}ln().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.11.4",
3
+ "version": "1.11.6",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
5
5
  "commands": {
6
6
  "apply": { "run": "node dist/run.mjs" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ilml-plugin-linkedin",
3
- "version": "1.11.4",
3
+ "version": "1.11.6",
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": [