ilml-plugin-linkedin 1.20.0 → 1.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/viewers.mjs CHANGED
@@ -1,24 +1,24 @@
1
- var Qe=Object.defineProperty;var G=(e,t)=>{for(var n in t)Qe(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Co}from"url";import it from"puppeteer";import{addExtra as ct}from"puppeteer-extra";import lt from"puppeteer-extra-plugin-stealth";async function Y(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as Xe}from"@ilivemylife/graph-sdk";var Ze=await Xe();for(let[e,t]of Object.entries(Ze))process.env[e]===void 0&&(process.env[e]=t);var et=process.env.LINKEDIN_NAME,O=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),jo=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.NEEDS_REVIEW])),tt=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.REJECTED,O.NEEDS_REVIEW]));import I from"fs";import T from"path";var ot="cookies.json";function ue(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin","cookies.json"):ot}function fe(){let e=ue();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 pe(){return I.existsSync(ue())}function nt(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin"):"."}function de(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function rt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?de(t[1]):"default"}function me(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),T.resolve(t);let n=de(e||rt()),o=T.join(nt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),T.resolve(o)}var he=".ilml-seeded";function ge(e){return!I.existsSync(T.join(e,he))}function ye(e){try{I.writeFileSync(T.join(e,he),new Date().toISOString())}catch{}}function Se(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(T.join(e,n),{force:!0}),t++}catch{}return t}var st={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function we(e,t={}){let n=me(),o={...st,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{Se(n);try{r=await e.launch(o)}catch(s){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${s.message})`)}}return{browser:r,profileDir:n,needsSeed:ge(n)}}async function ve(e,t){if(!t||!t.needsSeed)return!1;if(!pe())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(...fe()),ye(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var be=ct(it);be.use(lt());async function ke(){let{browser:e,profileDir:t,needsSeed:n}=await we(be),o=async()=>{console.log(`
2
- Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let r=await e.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ve(r,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:r}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as at}from"url";var ut=at(import.meta.url),ft=g.dirname(g.dirname(ut)),x=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(ft,"collected-profiles"),pt=g.join(x,"people.json"),tn=g.join(x,"jobs.json"),on=g.join(x,"quota.json"),nn=g.join(x,"conversations.json"),rn=g.join(x,"sync-state.json"),sn=g.join(x,"application-questions.json"),cn=g.join(x,"profile-history"),Ae=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ln=Ae(process.env.CONNECT_MAX_DAILY,20),an=Ae(process.env.CONNECT_MAX_WEEKLY,100),V=null,dt=null,mt=null,ht=null,gt=null,yt=null;function Ce(){V=null,dt=null,mt=null,ht=null,gt=null,yt=null}function St(){h.existsSync(x)||h.mkdirSync(x,{recursive:!0})}function wt(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.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{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ee(){return V||(St(),V=wt(pt,"people.json")||{},V)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as vt}from"url";var bt=vt(import.meta.url),kt=S.dirname(S.dirname(bt)),H=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(kt,"market-research"),yn=S.join(H,"scouted-jobs.json"),At=S.join(H,"discovered-people.json"),Ct=S.join(H,"visit-log.json"),Sn=S.join(H,"companies.json"),wn=S.join(H,"job-decisions.json");function $e(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Ie(){Et=null,$t=null,W=null,It=null,N=null}var Et=null;var $t=null;var W=null;function De(){return W||(W=$e(At)||{},W)}var It=null;var N=null;function xe(){return N||(N=$e(Ct)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function _e(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await Y(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await Y(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let i of o){let s=i.getAttribute("href")?.split("?")[0];if(!s||r.has(s))continue;r.add(s);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
1
+ var Qe=Object.defineProperty;var G=(e,t)=>{for(var n in t)Qe(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Co}from"url";import it from"puppeteer";import{addExtra as ct}from"puppeteer-extra";import lt from"puppeteer-extra-plugin-stealth";async function Y(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as Xe}from"@ilivemylife/graph-sdk";var Ze=await Xe();for(let[e,t]of Object.entries(Ze))process.env[e]===void 0&&(process.env[e]=t);var et=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Oo=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),tt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import I from"fs";import _ from"path";var ot="cookies.json";function ue(){let e=process.env.ILML_SCOPE_DIR;return e?_.join(e,"plugins-state","linkedin","cookies.json"):ot}function fe(){let e=ue();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 pe(){return I.existsSync(ue())}function nt(){let e=process.env.ILML_SCOPE_DIR;return e?_.join(e,"plugins-state","linkedin"):"."}function de(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function rt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?de(t[1]):"default"}function me(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),_.resolve(t);let n=de(e||rt()),o=_.join(nt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),_.resolve(o)}var he=".ilml-seeded";function ge(e){return!I.existsSync(_.join(e,he))}function ye(e){try{I.writeFileSync(_.join(e,he),new Date().toISOString())}catch{}}function Se(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(_.join(e,n),{force:!0}),t++}catch{}return t}var st={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function we(e,t={}){let n=me(),o={...st,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{Se(n);try{r=await e.launch(o)}catch(s){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${s.message})`)}}return{browser:r,profileDir:n,needsSeed:ge(n)}}async function ve(e,t){if(!t||!t.needsSeed)return!1;if(!pe())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(...fe()),ye(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var be=ct(it);be.use(lt());async function ke(){let{browser:e,profileDir:t,needsSeed:n}=await we(be),o=async()=>{console.log(`
2
+ Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let r=await e.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ve(r,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:r}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as at}from"url";var ut=at(import.meta.url),ft=g.dirname(g.dirname(ut)),D=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(ft,"collected-profiles"),pt=g.join(D,"people.json"),tn=g.join(D,"jobs.json"),on=g.join(D,"quota.json"),nn=g.join(D,"conversations.json"),rn=g.join(D,"sync-state.json"),sn=g.join(D,"application-questions.json"),cn=g.join(D,"profile-history"),Ae=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ln=Ae(process.env.CONNECT_MAX_DAILY,20),an=Ae(process.env.CONNECT_MAX_WEEKLY,100),V=null,dt=null,mt=null,ht=null,gt=null,yt=null;function Ce(){V=null,dt=null,mt=null,ht=null,gt=null,yt=null}function St(){h.existsSync(D)||h.mkdirSync(D,{recursive:!0})}function wt(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.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{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ee(){return V||(St(),V=wt(pt,"people.json")||{},V)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as vt}from"url";var bt=vt(import.meta.url),kt=S.dirname(S.dirname(bt)),H=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(kt,"market-research"),yn=S.join(H,"scouted-jobs.json"),At=S.join(H,"discovered-people.json"),Ct=S.join(H,"visit-log.json"),Sn=S.join(H,"companies.json"),wn=S.join(H,"job-decisions.json");function $e(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Ie(){Et=null,$t=null,W=null,It=null,N=null}var Et=null;var $t=null;var W=null;function xe(){return W||(W=$e(At)||{},W)}var It=null;var N=null;function De(){return N||(N=$e(Ct)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function Te(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await Y(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await Y(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let i of o){let s=i.getAttribute("href")?.split("?")[0];if(!s||r.has(s))continue;r.add(s);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
3
3
  `).map(p=>p.trim()).filter(Boolean),f="";for(let p of u)if(p.length>2&&p.length<60&&!p.includes("View")&&!p.includes("profile")&&!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&!p.startsWith("3rd")){f=p;break}f||(f=i.textContent?.trim()?.split(`
4
- `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",q=u.indexOf(f);if(q>=0&&q+1<u.length){let p=u[q+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:s.startsWith("/")?"https://www.linkedin.com"+s:s,name:f,title:v||null,connectionDegree:m})}return n})}function Te(e){let t=Ee(),n=xe(),o=De(),r=new Map;for(let i of n.visits||[]){let s=r.get(i.profileUrl);(!s||i.date>s)&&r.set(i.profileUrl,i.date)}return e.map(i=>{let s=t[i.profileUrl],c=o[i.profileUrl],l=r.get(i.profileUrl);return{...i,isConnected:s?.connectionStatus==="connected",isPending:s?.connectionStatus==="pending"||s?.connectionStatus==="sent_without_note",isInPeopleDb:!!s,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:s?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as R from"path";import{fileURLToPath as jt}from"url";import"dotenv/config";import{createGraphClient as Dt,resolveToken as xt}from"@ilivemylife/graph-sdk";import{config as _t}from"dotenv";_t();var Re=xt()||process.env.TOKEN;Re||(console.error(`
4
+ `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",q=u.indexOf(f);if(q>=0&&q+1<u.length){let p=u[q+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:s.startsWith("/")?"https://www.linkedin.com"+s:s,name:f,title:v||null,connectionDegree:m})}return n})}function _e(e){let t=Ee(),n=De(),o=xe(),r=new Map;for(let i of n.visits||[]){let s=r.get(i.profileUrl);(!s||i.date>s)&&r.set(i.profileUrl,i.date)}return e.map(i=>{let s=t[i.profileUrl],c=o[i.profileUrl],l=r.get(i.profileUrl);return{...i,isConnected:s?.connectionStatus==="connected",isPending:s?.connectionStatus==="pending"||s?.connectionStatus==="sent_without_note",isInPeopleDb:!!s,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:s?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as R from"path";import{fileURLToPath as Ot}from"url";import"dotenv/config";import{createGraphClient as xt,resolveToken as Dt}from"@ilivemylife/graph-sdk";import{config as Tt}from"dotenv";Tt();var Re=Dt()||process.env.TOKEN;Re||(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 je=Dt({token:Re});function Tt(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 Rt({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Tt(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${l} \u2014 ${s}${c}`}async function Oe({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(o)||o.length===0)return;let l=`**${Rt({scriptName:e,mode:t,status:n,error:r,duration:i})}**
8
+ `),process.exit(1));var Oe=xt({token:Re});function _t(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 Rt({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${_t(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${l} \u2014 ${s}${c}`}async function je({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(o)||o.length===0)return;let l=`**${Rt({scriptName:e,mode:t,status:n,error:r,duration:i})}**
9
9
 
10
10
  ${o.join(`
11
- `)}`;try{await je.addMessage(s,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ot=jt(import.meta.url),Nt=R.dirname(R.dirname(Ot)),Q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Nt,"collected-profiles"),X=R.join(Q,"run-log.json");function Ft(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";b.writeFileSync(o,n);for(let r=0;r<3;r++)try{b.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ne(){try{if(!b.existsSync(X))return{runs:[]};let e=JSON.parse(b.readFileSync(X,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Fe(e){b.existsSync(Q)||b.mkdirSync(Q,{recursive:!0});try{Ft(X,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Le(e,t="default"){let n=Ne();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),Fe(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Z(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=Ne(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(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)}Fe(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Oe({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ce from"os";import*as d from"path";import{fileURLToPath as io}from"url";var oe={};G(oe,{NAME:()=>Pt,VERSION:()=>Lt,up:()=>qt});import*as k from"fs";import*as K from"path";var Lt=1,Pt="normalize-jobs-and-questions",Mt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ut=50;function ee(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function te(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{k.writeFileSync(o,n)}catch(r){try{k.unlinkSync(o)}catch{}throw r}try{k.renameSync(o,e)}catch(r){try{k.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function qt(e,t){let n=K.join(e,"jobs.json"),o=K.join(t,"scouted-jobs.json"),r=K.join(e,"application-questions.json"),i=ee(n)||{},s=ee(o)||{},c=0,l=[];for(let f of Object.keys(i)){if(!s[f])continue;let w=s[f],m=i[f];for(let v of Mt)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(te(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ee(r);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let q=(m.questions||[]).map(p=>{let B={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Ut?B.options=p.options:(B.optionsOmitted=!0,w++)),p.page&&(B.page=p.page),p.wasPreFilled&&(B.wasPreFilled=!0),p.wasRetry&&(B.wasRetry=!0),B});f[v].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||q.length,questions:q})}te(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} 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 s[f];te(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ne={};G(ne,{NAME:()=>Jt,VERSION:()=>Bt,up:()=>Ht});import*as A from"fs";import*as Pe from"path";var Bt=2,Jt="reset-unread-flags";function Vt(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Wt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{A.writeFileSync(o,n)}catch(r){try{A.unlinkSync(o)}catch{}throw r}try{A.renameSync(o,e)}catch(r){try{A.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ht(e){let t=Pe.join(e,"conversations.json"),n=Vt(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}Wt(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var re={};G(re,{NAME:()=>Yt,VERSION:()=>Gt,up:()=>Zt});import*as C from"fs";import*as Me from"path";var Gt=3,Yt="recompute-last-message-by",Kt=new Set(["draft","confirmed","rejected","needs_review"]);function zt(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function Qt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{C.writeFileSync(o,n)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Xt(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Kt.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Zt(e){let t=Me.join(e,"conversations.json"),n=zt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let u=Array.isArray(l.messages)?l.messages:[],f=Xt(u,o),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&s++,l.lastMessageBy=f,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}Qt(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var se={};G(se,{NAME:()=>to,VERSION:()=>eo,up:()=>so});import*as E from"fs";import*as Ue from"path";var eo=4,to="split-connection-timestamps",oo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function no(e){if(!E.existsSync(e))return null;let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ro(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{E.writeFileSync(o,n)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function so(e){let t=Ue.join(e,"people.json"),n=no(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,oo.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ro(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var co=io(import.meta.url),lo=d.dirname(co),ao=d.dirname(d.dirname(lo));function uo(e){return e&&(e==="~"?ce.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ce.homedir(),e.slice(2)):e)}var D=process.env.DATA_DIR?d.resolve(uo(process.env.DATA_DIR)):ao,P=d.join(D,"collected-profiles"),M=d.join(D,"market-research"),y=d.join(D,".schema-version"),qe=[d.join(P,".schema-version"),d.join(M,".schema-version")],j=4,_=[{version:1,module:oe},{version:2,module:ne},{version:3,module:re},{version:4,module:se}];(function(){_.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of _){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=_.length?_[_.length-1].version:0;if(n!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<_.length;o++){let r=o+1;if(_[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${_[o].version}`)}})();function We(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
11
+ `)}`;try{await Oe.addMessage(s,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var jt=Ot(import.meta.url),Nt=R.dirname(R.dirname(jt)),Q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Nt,"collected-profiles"),X=R.join(Q,"run-log.json");function Ft(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";b.writeFileSync(o,n);for(let r=0;r<3;r++)try{b.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ne(){try{if(!b.existsSync(X))return{runs:[]};let e=JSON.parse(b.readFileSync(X,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Fe(e){b.existsSync(Q)||b.mkdirSync(Q,{recursive:!0});try{Ft(X,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Le(e,t="default"){let n=Ne();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),Fe(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Z(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=Ne(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(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)}Fe(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";je({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ce from"os";import*as d from"path";import{fileURLToPath as io}from"url";var oe={};G(oe,{NAME:()=>Pt,VERSION:()=>Lt,up:()=>qt});import*as k from"fs";import*as K from"path";var Lt=1,Pt="normalize-jobs-and-questions",Mt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ut=50;function ee(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function te(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{k.writeFileSync(o,n)}catch(r){try{k.unlinkSync(o)}catch{}throw r}try{k.renameSync(o,e)}catch(r){try{k.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function qt(e,t){let n=K.join(e,"jobs.json"),o=K.join(t,"scouted-jobs.json"),r=K.join(e,"application-questions.json"),i=ee(n)||{},s=ee(o)||{},c=0,l=[];for(let f of Object.keys(i)){if(!s[f])continue;let w=s[f],m=i[f];for(let v of Mt)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(te(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ee(r);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let q=(m.questions||[]).map(p=>{let B={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Ut?B.options=p.options:(B.optionsOmitted=!0,w++)),p.page&&(B.page=p.page),p.wasPreFilled&&(B.wasPreFilled=!0),p.wasRetry&&(B.wasRetry=!0),B});f[v].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||q.length,questions:q})}te(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} 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 s[f];te(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ne={};G(ne,{NAME:()=>Jt,VERSION:()=>Bt,up:()=>Ht});import*as A from"fs";import*as Pe from"path";var Bt=2,Jt="reset-unread-flags";function Vt(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Wt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{A.writeFileSync(o,n)}catch(r){try{A.unlinkSync(o)}catch{}throw r}try{A.renameSync(o,e)}catch(r){try{A.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ht(e){let t=Pe.join(e,"conversations.json"),n=Vt(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}Wt(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var re={};G(re,{NAME:()=>Yt,VERSION:()=>Gt,up:()=>Zt});import*as C from"fs";import*as Me from"path";var Gt=3,Yt="recompute-last-message-by",Kt=new Set(["draft","confirmed","rejected","needs_review"]);function zt(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function Qt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{C.writeFileSync(o,n)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Xt(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Kt.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Zt(e){let t=Me.join(e,"conversations.json"),n=zt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let u=Array.isArray(l.messages)?l.messages:[],f=Xt(u,o),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&s++,l.lastMessageBy=f,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}Qt(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var se={};G(se,{NAME:()=>to,VERSION:()=>eo,up:()=>so});import*as E from"fs";import*as Ue from"path";var eo=4,to="split-connection-timestamps",oo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function no(e){if(!E.existsSync(e))return null;let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ro(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{E.writeFileSync(o,n)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function so(e){let t=Ue.join(e,"people.json"),n=no(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,oo.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ro(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var co=io(import.meta.url),lo=d.dirname(co),ao=d.dirname(d.dirname(lo));function uo(e){return e&&(e==="~"?ce.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ce.homedir(),e.slice(2)):e)}var x=process.env.DATA_DIR?d.resolve(uo(process.env.DATA_DIR)):ao,P=d.join(x,"collected-profiles"),M=d.join(x,"market-research"),y=d.join(x,".schema-version"),qe=[d.join(P,".schema-version"),d.join(M,".schema-version")],O=4,T=[{version:1,module:oe},{version:2,module:ne},{version:3,module:re},{version:4,module:se}];(function(){T.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of T){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=T.length?T[T.length-1].version:0;if(n!==O)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${O}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<T.length;o++){let r=o+1;if(T[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${T[o].version}`)}})();function We(){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{a.mkdirSync(D,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
- [FATAL] Cannot create DATA_DIR (${D}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
- `),process.exit(1))}let e;try{e=a.statSync(D)}catch(t){console.error(`
16
- [FATAL] DATA_DIR (${D}) is not accessible: ${t.message}
13
+ `),process.exit(1));try{a.mkdirSync(x,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
+ [FATAL] Cannot create DATA_DIR (${x}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
+ `),process.exit(1))}let e;try{e=a.statSync(x)}catch(t){console.error(`
16
+ [FATAL] DATA_DIR (${x}) is not accessible: ${t.message}
17
17
  `),process.exit(1)}e.isDirectory()||(console.error(`
18
- [FATAL] DATA_DIR (${D}) 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.
18
+ [FATAL] DATA_DIR (${x}) 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
19
  `),process.exit(1));for(let t of[P,M]){let n;try{n=a.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.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 L=d.join(D,".migration-lock");function fo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(L,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(a.readFileSync(L,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(s){s.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}o&&i<r&&(console.error(`
21
+ `),process.exit(1))}}var L=d.join(x,".migration-lock");function fo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(L,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(a.readFileSync(L,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(s){s.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}o&&i<r&&(console.error(`
22
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: ${L}
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
24
  `),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=L+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,L),!0}catch(o){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function le(){try{if(JSON.parse(a.readFileSync(L,"utf-8")).pid!==process.pid)return;a.unlinkSync(L)}catch{}}var Be=!1;function po(){if(Be)return;Be=!0;let e=()=>{try{le()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function mo(){if(a.existsSync(y))return;let e=[],t=[];for(let i of qe)if(a.existsSync(i))try{e.push({file:i,schema:z(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
@@ -30,14 +30,14 @@ ${o.join(`
30
30
  [FATAL] ${y} 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.
31
31
  `),process.exit(1)}let t=ho(e);return t===null&&(console.error(`
32
32
  [FATAL] ${y} 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 He(e){try{a.chmodSync(e,384)}catch{}}function go(e){if(We(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. 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=y+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),He(t),a.renameSync(t,y)}catch(n){try{a.unlinkSync(t)}catch{}throw n}}function Ve(e,t){if(!a.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){i++;continue}try{Ye(l,u),r++}catch(f){s.push({file:c,err:f.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${d.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${d.basename(e)}/ (${n})${c}`)}}var ie=!1;async function Ge(){if(ie)return;We(),bo();let t=Je().version;if(t===j){ie=!0;return}po(),fo(),process.on("exit",le),t>j&&(console.error(`
34
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${j}.`),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${j}.
33
+ `),process.exit(1)),t}function He(e){try{a.chmodSync(e,384)}catch{}}function go(e){if(We(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. 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=y+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),He(t),a.renameSync(t,y)}catch(n){try{a.unlinkSync(t)}catch{}throw n}}function Ve(e,t){if(!a.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){i++;continue}try{Ye(l,u),r++}catch(f){s.push({file:c,err:f.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${d.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${d.basename(e)}/ (${n})${c}`)}}var ie=!1;async function Ge(){if(ie)return;We(),bo();let t=Je().version;if(t===O){ie=!0;return}po(),fo(),process.on("exit",le),t>O&&(console.error(`
34
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${O}.`),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${O}.
36
36
  `),process.exit(1)),console.log(`
37
- \u{1F4E6} Schema migration: v${t} \u2192 v${j}`);let n=ko();if(!n.ok){console.error(`
37
+ \u{1F4E6} Schema migration: v${t} \u2192 v${O}`);let n=ko();if(!n.ok){console.error(`
38
38
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.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 o=_.filter(r=>r.version>t);for(let r of o){console.log(`
40
+ `),process.exit(1)}let o=T.filter(r=>r.version>t);for(let r of o){console.log(`
41
41
  Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Ve(P,r.version),Ve(M,r.version)}catch(l){console.error(`
42
42
  [FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
43
43
  `),process.exit(1)}let c=r.module;try{await c.up(P,M)}catch(l){console.error(`
@@ -47,16 +47,16 @@ ${o.join(`
47
47
  `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:r.version,name:c.NAME||i,appliedAt:l},f=Je();f.version=r.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),go(f)}catch(l){console.error(`
48
48
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
49
49
  `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Ce()}catch{}try{Ie()}catch{}ie=!0,le(),console.log(`
50
- \u2713 Schema is now at v${j}
51
- `)}var yo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function So(e){let t=e.toLowerCase();return yo.some(n=>n.test(t))}var wo=6e4;function vo(){let e=Date.now(),t=[];for(let n of[D,P,M]){if(!a.existsSync(n))continue;let o;try{o=a.readdirSync(n)}catch{continue}for(let r of o){if(!So(r))continue;let i=d.join(n,r);try{let s=a.statSync(i);if(!s.isFile()||e-s.mtimeMs<wo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function bo({verbose:e=!1}={}){let t=vo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{a.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${d.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 ko(){let e=[];for(let t of[P,M]){if(!a.existsSync(t))continue;let n=a.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=d.join(t,o);try{z(r)}catch(i){e.push({dir:d.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ao(e){let t=[],n=[];for(let i of[P,M]){if(!a.existsSync(i))continue;let s=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=d.join(i,c),u=c.slice(0,-e.length),f=d.join(i,u);try{u.toLowerCase().endsWith(".json")?z(l):a.accessSync(l,a.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:i})}catch(w){n.push(`${d.basename(i)}/${c}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{Ye(i,s),o++}catch(u){r.push(`${d.basename(l)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Ye(e,t){let n=t+".tmp";try{a.copyFileSync(e,n),He(n)}catch(o){try{a.unlinkSync(n)}catch{}throw o}try{a.renameSync(n,t)}catch(o){try{a.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}}var Eo=Co(import.meta.url),$o=U.dirname(Eo),ae=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join($o,"market-research"),J=U.join(ae,"profile-viewers.json");await Ge();var ze=process.argv.slice(2),Ke=ze.includes("--save"),Io=ze.includes("--list");function Do(){if(!$.existsSync(J)){console.log(`
50
+ \u2713 Schema is now at v${O}
51
+ `)}var yo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function So(e){let t=e.toLowerCase();return yo.some(n=>n.test(t))}var wo=6e4;function vo(){let e=Date.now(),t=[];for(let n of[x,P,M]){if(!a.existsSync(n))continue;let o;try{o=a.readdirSync(n)}catch{continue}for(let r of o){if(!So(r))continue;let i=d.join(n,r);try{let s=a.statSync(i);if(!s.isFile()||e-s.mtimeMs<wo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function bo({verbose:e=!1}={}){let t=vo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{a.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${d.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 ko(){let e=[];for(let t of[P,M]){if(!a.existsSync(t))continue;let n=a.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=d.join(t,o);try{z(r)}catch(i){e.push({dir:d.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ao(e){let t=[],n=[];for(let i of[P,M]){if(!a.existsSync(i))continue;let s=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=d.join(i,c),u=c.slice(0,-e.length),f=d.join(i,u);try{u.toLowerCase().endsWith(".json")?z(l):a.accessSync(l,a.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:i})}catch(w){n.push(`${d.basename(i)}/${c}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{Ye(i,s),o++}catch(u){r.push(`${d.basename(l)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Ye(e,t){let n=t+".tmp";try{a.copyFileSync(e,n),He(n)}catch(o){try{a.unlinkSync(n)}catch{}throw o}try{a.renameSync(n,t)}catch(o){try{a.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}}var Eo=Co(import.meta.url),$o=U.dirname(Eo),ae=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join($o,"market-research"),J=U.join(ae,"profile-viewers.json");await Ge();var ze=process.argv.slice(2),Ke=ze.includes("--save"),Io=ze.includes("--list");function xo(){if(!$.existsSync(J)){console.log(`
52
52
  No viewer data yet. Run: npm run viewers -- --save
53
53
  `);return}let t=JSON.parse($.readFileSync(J,"utf-8")).scans||[],n=t.flatMap(s=>s.viewers||[]),o=new Map;for(let s of n)(!o.has(s.profileUrl)||s.scanDate>o.get(s.profileUrl).scanDate)&&o.set(s.profileUrl,s);console.log(`
54
54
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 VIEWERS"),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(` Total scans: ${t.length}`),console.log(` Unique viewers: ${o.size}`);let r=[...o.values()].filter(s=>s.isConnected).length,i=[...o.values()].filter(s=>s.weVisitedThem).length;if(console.log(` Already connected: ${r}`),console.log(` We visited first: ${i} (\u2192 they responded by viewing us)`),o.size>0){console.log(`
55
55
  Recent viewers:`);let s=[...o.values()].slice(0,10);for(let c of s){let l=[];c.isConnected&&l.push("connected"),c.weVisitedThem&&l.push("we visited"),c.isDiscovered&&l.push("discovered");let u=l.length?` [${l.join(", ")}]`:"";console.log(` ${c.name} (${c.connectionDegree||"?"})${u}`),c.title&&console.log(` ${c.title.slice(0,60)}`)}}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
56
- `)}async function xo(){if(console.log(`
56
+ `)}async function Do(){if(console.log(`
57
57
  LinkedIn Profile Viewers
58
- `),Io){Do();return}let e=Le("viewers",Ke?"save":"view"),{browser:t,page:n}=await ke();try{console.log(` Extracting profile viewers...
59
- `);let o=await _e(n);console.log(` Found ${o.length} viewers`);let r=Te(o);for(let s of r){let c=[];s.isConnected?c.push("\u2713 connected"):s.isPending&&c.push("\u23F3 pending"),s.weVisitedThem&&c.push("\u{1F441} we visited"),s.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${s.name} (${s.connectionDegree||"?"})${l}`),s.title&&console.log(` ${s.title.slice(0,70)}`)}if(Ke&&r.length>0){$.existsSync(ae)||$.mkdirSync(ae,{recursive:!0});let s={scans:[]};try{$.existsSync(J)&&(s=JSON.parse($.readFileSync(J,"utf-8")))}catch{}s.scans.push({scanDate:new Date().toISOString(),viewerCount:r.length,viewers:r});let c=Date.now()-90*24*60*60*1e3;s.scans=s.scans.filter(l=>new Date(l.scanDate).getTime()>c),$.writeFileSync(J,JSON.stringify(s,null,2)),console.log(`
58
+ `),Io){xo();return}let e=Le("viewers",Ke?"save":"view"),{browser:t,page:n}=await ke();try{console.log(` Extracting profile viewers...
59
+ `);let o=await Te(n);console.log(` Found ${o.length} viewers`);let r=_e(o);for(let s of r){let c=[];s.isConnected?c.push("\u2713 connected"):s.isPending&&c.push("\u23F3 pending"),s.weVisitedThem&&c.push("\u{1F441} we visited"),s.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${s.name} (${s.connectionDegree||"?"})${l}`),s.title&&console.log(` ${s.title.slice(0,70)}`)}if(Ke&&r.length>0){$.existsSync(ae)||$.mkdirSync(ae,{recursive:!0});let s={scans:[]};try{$.existsSync(J)&&(s=JSON.parse($.readFileSync(J,"utf-8")))}catch{}s.scans.push({scanDate:new Date().toISOString(),viewerCount:r.length,viewers:r});let c=Date.now()-90*24*60*60*1e3;s.scans=s.scans.filter(l=>new Date(l.scanDate).getTime()>c),$.writeFileSync(J,JSON.stringify(s,null,2)),console.log(`
60
60
  Saved ${r.length} viewers to ${J}`)}let i={viewers:r.length,connected:r.filter(s=>s.isConnected).length,weVisitedFirst:r.filter(s=>s.weVisitedThem).length};console.log(`
61
61
  Summary: ${i.viewers} viewers, ${i.connected} connected, ${i.weVisitedFirst} we visited first`),Z(e,"success",i)}catch(o){console.error(`
62
- Error:`,o.message),Z(e,"error",null,o.message)}finally{await t.close().catch(()=>{})}}xo().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
62
+ Error:`,o.message),Z(e,"error",null,o.message)}finally{await t.close().catch(()=>{})}}Do().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
package/ilml-plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "linkedin",
3
- "version": "1.20.0",
3
+ "version": "1.20.2",
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." },
@@ -68,6 +68,7 @@
68
68
  "flags": {
69
69
  "add <file.json>": "Add profiles from a JSON array [{url, note?, name?}] to the queue. Dedupes against the queue and skips people already connected/pending. Combine with --tag=X and --priority=high|normal|low.",
70
70
  "fill --category=...": "Fill the queue from people already categorised in your contacts DB (not yet connected). e.g. --category=founder,investor,hiring_manager (or --valuable for the standard high-value set). Each entry is tagged with its category so `quota` shows acceptance per category. By default it VALIDATES that each person's stored title actually confirms the category (drops people whose title contradicts the tag — the category field is sometimes mis-set by enrichment; people with no stored title are held rather than visited, to avoid ban risk). --no-validate keeps the old trust-the-tag behaviour. --min-posts=N keeps only people who appeared in at least N of your job posts (the repeat-recruiter signal, useful with --category=recruiter). --max=N keeps the best N (ranked by priority, mutual connections, repeat count). Respects your excluded-locations setting. No browser.",
71
+ "fill --from-discovered": "Top up the queue from the DISCOVERY POOL — people the plugin harvested from LinkedIn's 'People also viewed / More profiles for you' side-panels while connecting (enabled by the DISCOVERY_ENABLED setting). Ranked by relevance to you (personalised rank × sector-fit), best first — use it when your hand-curated list runs out. --dry-run previews the ranked picks without queuing; --max=N caps (default 20); --min-fit=0..1 and --min-rank=N set thresholds; --category / --sector filter; honours your excluded-locations; skips anyone already connected or queued. Only STAGES the queue — `approve` + `run` still do the sending. No browser.",
71
72
  "list": "Show the queue (status, priority, note flag, name/title joined from your contacts). No browser. Optional --status=queued|approved|sent|skipped|failed.",
72
73
  "approve <url>": "Move an entry from queued to approved. Or approve a whole batch with --all or --tag=X. Only approved entries are sent.",
73
74
  "note <url> \"text\"": "Save a personal note on an entry (max 300 chars). It is sent ONLY when you run `connect run --with-notes` — by default connect sends plain requests, because LinkedIn caps custom notes to a handful per month. Shown with 📝 in `connect list`.",
@@ -77,7 +78,13 @@
77
78
  "run": "Send approved entries, highest priority first, under the daily/weekly quota (browser). By default sends WITHOUT notes; add --with-notes to send the saved notes (spends your scarce monthly LinkedIn notes). --max=N caps this run, --dry-run previews without sending, --yes skips the confirmation prompt (for schedulers). Stops itself after 3 failures in a row and saves what LinkedIn showed to connect-diagnostics/.",
78
79
  "--with-notes": "With `run`: actually send the per-entry saved notes (opt-in; default is no notes).",
79
80
  "--tag=X": "Label a batch (used by add/approve). Shows up as the source in `ilml linkedin quota` acceptance stats.",
80
- "--priority=LEVEL": "high|normal|low (used by add)."
81
+ "--priority=LEVEL": "high|normal|low (used by add).",
82
+ "--from-discovered": "With `fill`: source from the discovery pool instead of your contacts DB (see DISCOVERY_ENABLED).",
83
+ "--dry-run": "With `fill --from-discovered` or `run`: preview what would be added/sent without writing anything.",
84
+ "--min-fit=0..1": "With `fill --from-discovered`: minimum sector-fit (relevance to your interests) to include.",
85
+ "--min-rank=N": "With `fill --from-discovered`: minimum personalised rank to include.",
86
+ "--sector=a,b": "With `fill --from-discovered`: keep only these sectors (ai, robotics, deep-tech, fintech, …).",
87
+ "--max=N": "With `fill`/`run`: cap how many entries to add / send this run."
81
88
  },
82
89
  "banRisk": "Medium for `run` (sends real connection requests, browser) — but every send goes through the same daily/weekly quota gate as the funnel, so you can't exceed the limit. All other subcommands are local, no browser, no risk.",
83
90
  "useWhen": "You have a curated list of people worth connecting to (investors from a post, event speakers, company leaders) and want to review, prioritise, and send requests under quota instead of blindly connecting recruiters."
@@ -320,6 +327,12 @@
320
327
  { "key": "CONNECT_MAX_DAILY", "label": "Max connection requests per day", "type": "number", "required": false, "default": 20, "hint": "Your OWN conservative daily cap across every connection path. LinkedIn's real limit is dynamic and unknown — keep this below it. Raise it deliberately only to surface LinkedIn's own limit: connect stops itself after 3 failures in a row and saves what LinkedIn showed to connect-diagnostics/." },
321
328
  { "key": "CONNECT_MAX_WEEKLY", "label": "Max connection requests per week", "type": "number", "required": false, "default": 100, "hint": "Rolling 7-day cap. LinkedIn free accounts are often limited around 100-200/week and adjust it based on your acceptance rate." }
322
329
  ]
330
+ },
331
+ {
332
+ "title": "Discovery (experimental)",
333
+ "fields": [
334
+ { "key": "DISCOVERY_ENABLED", "label": "Build a discovery pool while connecting", "type": "boolean", "required": false, "default": false, "hint": "OFF by default. When ON, `connect run` also reads LinkedIn's \"People also viewed / More profiles for you\" side-panel on each profile it already opens, and saves those people to a local discovery pool — no extra page loads, no effect on the connect itself. `connect fill --from-discovered` then tops up your queue from that pool, ranked by relevance to you. Adds ~2-3s per profile (a scroll to load the panel), and only works on English-locale LinkedIn for now. Leave it OFF and nothing changes." }
335
+ ]
323
336
  }
324
337
  ]
325
338
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ilml-plugin-linkedin",
3
- "version": "1.20.0",
3
+ "version": "1.20.2",
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": [
@@ -61,7 +61,7 @@
61
61
  "migrate:status": "node migrationCli.mjs status",
62
62
  "rollback:data": "node migrationCli.mjs rollback-data",
63
63
  "data:cleanup": "node migrationCli.mjs data-cleanup",
64
- "test": "echo \"Error: no test specified\" && exit 1"
64
+ "test": "node --test test/"
65
65
  },
66
66
  "repository": {
67
67
  "type": "git",
@@ -96,6 +96,7 @@
96
96
  "babel-loader": "^9.1.3",
97
97
  "esbuild": "^0.24.0",
98
98
  "http-server": "^14.0.0",
99
+ "jsdom": "^22.1.0",
99
100
  "nodemon": "^3.1.4",
100
101
  "react": "^18.3.1",
101
102
  "react-dom": "^18.3.1",