ilml-plugin-linkedin 1.20.12 → 1.20.13

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,63 +1,63 @@
1
- var pt=Object.defineProperty;var K=(e,t)=>{for(var n in t)pt(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as I from"fs";import*as U from"path";import{fileURLToPath as Yo}from"url";import Dt from"puppeteer";import{addExtra as Tt}from"puppeteer-extra";import Rt from"puppeteer-extra-plugin-stealth";import S from"fs";import _ from"path";var dt="cookies.json";function ee(){let e=process.env.ILML_SCOPE_DIR;return e?_.join(e,"plugins-state","linkedin","cookies.json"):dt}function mt(){let e=ee(),t=_.dirname(e);return t&&t!=="."&&!S.existsSync(t)&&S.mkdirSync(t,{recursive:!0}),e}function ye(e){let t=mt();return S.writeFileSync(t,JSON.stringify(e)),t}function Se(){let e=ee();if(!S.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=S.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 we(){return S.existsSync(ee())}function ht(){let e=process.env.ILML_SCOPE_DIR;return e?_.join(e,"plugins-state","linkedin"):"."}function ve(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function gt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?ve(t[1]):"default"}function be(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),_.resolve(t);let n=ve(e||gt()),o=_.join(ht(),"chrome-profile",n);return S.existsSync(o)||S.mkdirSync(o,{recursive:!0}),_.resolve(o)}var ke=".ilml-seeded";function Ae(e){return!S.existsSync(_.join(e,ke))}function Ee(e){try{S.writeFileSync(_.join(e,ke),new Date().toISOString())}catch{}}function Ce(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{S.rmSync(_.join(e,n),{force:!0}),t++}catch{}return t}async function z(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function yt(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(s=>setTimeout(s,o))}return!1}var Ie=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function St(e){return Ie.test(e||"")}async function wt(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),i=Date.now(),s=!1;for(;Date.now()-i<r;){let l="wait";try{l=await e.evaluate(u=>!new RegExp(u).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Ie.source)}catch{}if(l==="in"){try{let u=await e.cookies();if(Array.isArray(u)&&u.some(g=>g.name==="li_at")){let g=ye(u);console.log(` \u2713 Session recovered \u2014 re-saved ${u.length} cookies (${g}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(u){console.log(` \u2713 Session recovered (cookie re-save skipped: ${u.message}).`)}return!0}if(l==="creds"){if(!o){let u=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw u.code="SESSION_EXPIRED",u}s||(s=!0,console.log(`
1
+ var ht=Object.defineProperty;var K=(e,t)=>{for(var o in t)ht(e,o,{get:t[o],enumerable:!0})};import"dotenv/config";import*as I from"fs";import*as U from"path";import{fileURLToPath as Zo}from"url";import Nt from"puppeteer";import{addExtra as Ft}from"puppeteer-extra";import Pt from"puppeteer-extra-plugin-stealth";import S from"fs";import x from"path";var gt="cookies.json";function ee(){let e=process.env.ILML_SCOPE_DIR;return e?x.join(e,"plugins-state","linkedin","cookies.json"):gt}function yt(){let e=ee(),t=x.dirname(e);return t&&t!=="."&&!S.existsSync(t)&&S.mkdirSync(t,{recursive:!0}),e}function ye(e){let t=yt();return S.writeFileSync(t,JSON.stringify(e)),t}function Se(){let e=ee();if(!S.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=S.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}function we(){return S.existsSync(ee())}function St(){let e=process.env.ILML_SCOPE_DIR;return e?x.join(e,"plugins-state","linkedin"):"."}function ve(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function wt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?ve(t[1]):"default"}function be(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),x.resolve(t);let o=ve(e||wt()),n=x.join(St(),"chrome-profile",o);return S.existsSync(n)||S.mkdirSync(n,{recursive:!0}),x.resolve(n)}var ke=".ilml-seeded";function Ae(e){return!S.existsSync(x.join(e,ke))}function Ee(e){try{S.writeFileSync(x.join(e,ke),new Date().toISOString())}catch{}}function Ce(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{S.rmSync(x.join(e,o),{force:!0}),t++}catch{}return t}async function z(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function vt(e,t,{timeout:o=45e3,poll:n=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<o;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,n))}return!1}var Ie=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function bt(e){return Ie.test(e||"")}async function kt(e,{credentialWaitMs:t=36e4,label:o="page"}={}){console.log(` \u26A0 Auth wall on ${o} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let n=!!(process.stdin&&process.stdin.isTTY),r=n?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let l="wait";try{l=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Ie.source)}catch{}if(l==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(g=>g.name==="li_at")){let g=ye(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${g}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(l==="creds"){if(!n){let a=new Error(`Session expired (${o}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}i||(i=!0,console.log(`
2
2
  \u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
3
- `))}await new Promise(u=>setTimeout(u,2500))}let c=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function $e(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await yt(e,t,{timeout:o,label:n});if(!r&&St(e.url())){let i=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw i.code="SESSION_EXPIRED",i}return r}async function te(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:i=6e4,autoRecover:s=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:i});try{return await $e(e,{readySelector:n,label:o,timeout:r})}catch(c){if(s&&c.code==="SESSION_EXPIRED"){await wt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:i})}catch{}return await $e(e,{readySelector:n,label:o,timeout:r})}throw c}}import{getPluginConfig as vt}from"@ilivemylife/graph-sdk";var bt=await vt();for(let[e,t]of Object.entries(bt))process.env[e]===void 0&&(process.env[e]=t);var kt=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ln=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),At=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import oe from"fs";import Et from"path";var Ct={headless:!1,defaultViewport:null,protocolTimeout:3e5},W=new Set,xe=!1;async function Q(){let e=[...W].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});W.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function $t(){if(xe)return;xe=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of W)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function ne(e){return Et.join(e,".ilml-browser-session.json")}function Re(e,t={}){try{oe.writeFileSync(ne(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function It(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Re(e,n?{wsEndpoint:n}:{})}catch{}}function xt(e){let t=Oe(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{oe.rmSync(ne(e),{force:!0})}catch{}}function Oe(e){try{return JSON.parse(oe.readFileSync(ne(e),"utf-8"))}catch{return null}}function _e(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function De(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function Te(e,t,{probeTimeoutMs:n=4e3}={}){let o=Oe(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&_e(o.ownerPid)?"live":(V(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await De(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return V(t),"free";if(_e(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await De(s.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{s.disconnect()}catch{}return"live"}function _t(e,t){e&&($t(),W.add(e),e.on("disconnected",()=>{W.delete(e),t&&V(t)}))}async function je(e,t={}){let n=be(),o={...Ct,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Te(e,n)==="live")throw new Error(r);Re(n);let i;try{i=await e.launch(o)}catch{if(await Te(e,n)==="live")throw new Error(r);Ce(n);try{i=await e.launch(o)}catch(c){throw xt(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return _t(i,n),It(n,i),{browser:i,profileDir:n,needsSeed:Ae(n)}}async function Ne(e,t){if(!t||!t.needsSeed)return!1;if(!we())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(...Se()),Ee(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Fe=Tt(Dt);Fe.use(Rt());async function Pe(){let{browser:e,profileDir:t,needsSeed:n}=await je(Fe),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ne(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}import"dotenv/config";import*as h from"fs";import*as y from"path";import{fileURLToPath as Ot}from"url";var jt=Ot(import.meta.url),Nt=y.dirname(y.dirname(jt)),D=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(Nt,"collected-profiles"),Ft=y.join(D,"people.json"),_n=y.join(D,"jobs.json"),Dn=y.join(D,"quota.json"),Tn=y.join(D,"conversations.json"),Rn=y.join(D,"sync-state.json"),On=y.join(D,"application-questions.json"),jn=y.join(D,"profile-history"),Le=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Nn=Le(process.env.CONNECT_MAX_DAILY,20),Fn=Le(process.env.CONNECT_MAX_WEEKLY,100),H=null,Pt=null,Lt=null,Mt=null,Ut=null,qt=null;function Me(){H=null,Pt=null,Lt=null,Mt=null,Ut=null,qt=null}function Bt(){h.existsSync(D)||h.mkdirSync(D,{recursive:!0})}function Jt(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: ${y.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 Ue(){return H||(Bt(),H=Jt(Ft,"people.json")||{},H)}import"dotenv/config";import*as F from"fs";import*as v from"path";import{fileURLToPath as Vt}from"url";var Wt=Vt(import.meta.url),Ht=v.dirname(v.dirname(Wt)),Y=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"market-research"):v.join(Ht,"market-research"),Vn=v.join(Y,"scouted-jobs.json"),Gt=v.join(Y,"discovered-people.json"),Yt=v.join(Y,"visit-log.json"),Wn=v.join(Y,"companies.json"),Hn=v.join(Y,"job-decisions.json");function qe(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Be(){Kt=null,zt=null,G=null,Qt=null,N=null}var Kt=null;var zt=null;var G=null;function Je(){return G||(G=qe(Gt)||{},G)}var Qt=null;var N=null;function Ve(){return N||(N=qe(Yt)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function We(e){await te(e,"https://www.linkedin.com/analytics/profile-views/",{readySelector:'main a[href*="/in/"], .scaffold-layout__main, main.scaffold-layout__main',label:"profile views"}),await z(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await z(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(`
4
- `).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(`
5
- `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,b="",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")&&(b=p)}f&&f.length>1&&n.push({profileUrl:s.startsWith("/")?"https://www.linkedin.com"+s:s,name:f,title:b||null,connectionDegree:m})}return n})}function He(e){let t=Ue(),n=Ve(),o=Je(),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 k from"fs";import*as R from"path";import{fileURLToPath as no}from"url";import"dotenv/config";import{createGraphClient as Xt,resolveToken as Zt}from"@ilivemylife/graph-sdk";import{config as eo}from"dotenv";eo();var Ge=Zt()||process.env.TOKEN;Ge||(console.error(`
3
+ `))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}async function _e(e,{readySelector:t,label:o="page",timeout:n=45e3}={}){let r=await vt(e,t,{timeout:n,label:o});if(!r&&bt(e.url())){let s=new Error(`Session expired (${o}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function te(e,t,{readySelector:o,label:n="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await _e(e,{readySelector:o,label:n,timeout:r})}catch(c){if(i&&c.code==="SESSION_EXPIRED"){await kt(e,{label:n});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await _e(e,{readySelector:o,label:n,timeout:r})}throw c}}import{getPluginConfig as Ct}from"@ilivemylife/graph-sdk";var At={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},$e=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Et(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function xe(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let o=new URLSearchParams;o.set("keywords",t);let n=(e.JOB_SEARCH_LOCATION||"").trim();n&&o.set("location",n);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&o.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&o.set("distance",String(s)),$e(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),$e(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let i=Et(e.JOB_SEARCH_COMPANY_IDS);i.length&&o.set("f_C",i.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&o.set("f_TPR",At[c]||c),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+o.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(l+="&"+a),l}var _t=await Ct();for(let[e,t]of Object.entries(_t))process.env[e]===void 0&&(process.env[e]=t);var Re=xe(process.env);Re&&(process.env.LINKEDIN_SEARCH_URL=Re);var It=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),hn=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),$t=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import oe from"fs";import xt from"path";var Rt={headless:!1,defaultViewport:null,protocolTimeout:3e5},H=new Set,De=!1;async function Q(){let e=[...H].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});H.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Dt(){if(De)return;De=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of H)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function ne(e){return xt.join(e,".ilml-browser-session.json")}function Ne(e,t={}){try{oe.writeFileSync(ne(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Tt(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Ne(e,o?{wsEndpoint:o}:{})}catch{}}function Ot(e){let t=Fe(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{oe.rmSync(ne(e),{force:!0})}catch{}}function Fe(e){try{return JSON.parse(oe.readFileSync(ne(e),"utf-8"))}catch{return null}}function Te(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Oe(e,t,o){let n,r=new Promise(i=>{n=setTimeout(()=>i(o),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(n),i),i=>{throw clearTimeout(n),i});return Promise.race([s,r])}async function je(e,t,{probeTimeoutMs:o=4e3}={}){let n=Fe(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&Te(n.ownerPid)?"live":(V(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Oe(s,o,r);if(i===r)return s.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!i)return V(t),"free";if(Te(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Oe(i.close().then(()=>!0).catch(()=>!1),o,!1))return V(t),"free";try{i.disconnect()}catch{}return"live"}function jt(e,t){e&&(Dt(),H.add(e),e.on("disconnected",()=>{H.delete(e),t&&V(t)}))}async function Pe(e,t={}){let o=be(),n={...Rt,...t,userDataDir:o},r=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await je(e,o)==="live")throw new Error(r);Ne(o);let s;try{s=await e.launch(n)}catch{if(await je(e,o)==="live")throw new Error(r);Ce(o);try{s=await e.launch(n)}catch(c){throw Ot(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return jt(s,o),Tt(o,s),{browser:s,profileDir:o,needsSeed:Ae(o)}}async function Le(e,t){if(!t||!t.needsSeed)return!1;if(!we())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(...Se()),Ee(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Me=Ft(Nt);Me.use(Pt());async function Ue(){let{browser:e,profileDir:t,needsSeed:o}=await Pe(Me),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Le(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}import"dotenv/config";import*as h from"fs";import*as y from"path";import{fileURLToPath as Lt}from"url";var Mt=Lt(import.meta.url),Ut=y.dirname(y.dirname(Mt)),R=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(Ut,"collected-profiles"),qt=y.join(R,"people.json"),Fn=y.join(R,"jobs.json"),Pn=y.join(R,"quota.json"),Ln=y.join(R,"conversations.json"),Mn=y.join(R,"sync-state.json"),Un=y.join(R,"application-questions.json"),qn=y.join(R,"profile-history"),qe=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},Bn=qe(process.env.CONNECT_MAX_DAILY,20),Jn=qe(process.env.CONNECT_MAX_WEEKLY,100),W=null,Bt=null,Jt=null,Vt=null,Ht=null,Wt=null;function Be(){W=null,Bt=null,Jt=null,Vt=null,Ht=null,Wt=null}function Gt(){h.existsSync(R)||h.mkdirSync(R,{recursive:!0})}function Yt(e,t){if(!h.existsSync(e))return null;try{let o=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${y.resolve(e)}`);let n=e+".backup";if(h.existsSync(n))try{let r=JSON.parse(h.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{h.copyFileSync(n,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 Je(){return W||(Gt(),W=Yt(qt,"people.json")||{},W)}import"dotenv/config";import*as F from"fs";import*as v from"path";import{fileURLToPath as Kt}from"url";var zt=Kt(import.meta.url),Qt=v.dirname(v.dirname(zt)),Y=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"market-research"):v.join(Qt,"market-research"),Qn=v.join(Y,"scouted-jobs.json"),Xt=v.join(Y,"discovered-people.json"),Zt=v.join(Y,"visit-log.json"),Xn=v.join(Y,"companies.json"),Zn=v.join(Y,"job-decisions.json");function Ve(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function He(){eo=null,to=null,G=null,oo=null,N=null}var eo=null;var to=null;var G=null;function We(){return G||(G=Ve(Xt)||{},G)}var oo=null;var N=null;function Ge(){return N||(N=Ve(Zt)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function Ye(e){await te(e,"https://www.linkedin.com/analytics/profile-views/",{readySelector:'main a[href*="/in/"], .scaffold-layout__main, main.scaffold-layout__main',label:"profile views"}),await z(5e3);for(let o=0;o<5;o++)await e.evaluate(()=>window.scrollBy(0,600)),await z(1e3);return await e.evaluate(()=>{let o=[],n=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let s of n){let i=s.getAttribute("href")?.split("?")[0];if(!i||r.has(i))continue;r.add(i);let c=s;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()||"",a=l.split(`
4
+ `).map(p=>p.trim()).filter(Boolean),f="";for(let p of a)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=s.textContent?.trim()?.split(`
5
+ `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,b="",q=a.indexOf(f);if(q>=0&&q+1<a.length){let p=a[q+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(b=p)}f&&f.length>1&&o.push({profileUrl:i.startsWith("/")?"https://www.linkedin.com"+i:i,name:f,title:b||null,connectionDegree:m})}return o})}function Ke(e){let t=Je(),o=Ge(),n=We(),r=new Map;for(let s of o.visits||[]){let i=r.get(s.profileUrl);(!i||s.date>i)&&r.set(s.profileUrl,s.date)}return e.map(s=>{let i=t[s.profileUrl],c=n[s.profileUrl],l=r.get(s.profileUrl);return{...s,isConnected:i?.connectionStatus==="connected",isPending:i?.connectionStatus==="pending"||i?.connectionStatus==="sent_without_note",isInPeopleDb:!!i,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:i?.category||c?.role||null}})}import"dotenv/config";import*as k from"fs";import*as T from"path";import{fileURLToPath as lo}from"url";import"dotenv/config";import{createGraphClient as no,resolveToken as ro}from"@ilivemylife/graph-sdk";import{config as so}from"dotenv";so();var ze=ro()||process.env.TOKEN;ze||(console.error(`
6
6
  [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.
7
7
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
8
8
  `),console.error(` Or add ILML_TOKEN=... to .env
9
- `),process.exit(1));var Ye=Xt({token:Ge});function to(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 oo({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?` ${to(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 Ke({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=`**${oo({scriptName:e,mode:t,status:n,error:r,duration:i})}**
9
+ `),process.exit(1));var Qe=no({token:ze});function io(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 co({scriptName:e,mode:t,status:o,error:n,duration:r}){let s=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${io(r)}`:"",l=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${a} \u2014 ${l} \u2014 ${i}${c}`}async function Xe({scriptName:e,mode:t,status:o,summaryLines:n,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let l=`**${co({scriptName:e,mode:t,status:o,error:r,duration:s})}**
10
10
 
11
- ${o.join(`
12
- `)}`;try{await Ye.addMessage(s,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var ro=no(import.meta.url),so=R.dirname(R.dirname(ro)),re=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(so,"collected-profiles"),se=R.join(re,"run-log.json");function io(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";k.writeFileSync(o,n);for(let r=0;r<3;r++)try{k.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 ze(){try{if(!k.existsSync(se))return{runs:[]};let e=JSON.parse(k.readFileSync(se,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Qe(e){k.existsSync(re)||k.mkdirSync(re,{recursive:!0});try{io(se,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Xe(e,t="default"){let n=ze();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),Qe(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ie(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=ze(),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)}Qe(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";Ke({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 me from"os";import*as d from"path";import{fileURLToPath as To}from"url";var ae={};K(ae,{NAME:()=>lo,VERSION:()=>co,up:()=>fo});import*as A from"fs";import*as X from"path";var co=1,lo="normalize-jobs-and-questions",ao=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],uo=50;function ce(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function le(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 fo(e,t){let n=X.join(e,"jobs.json"),o=X.join(t,"scouted-jobs.json"),r=X.join(e,"application-questions.json"),i=ce(n)||{},s=ce(o)||{},c=0,l=[];for(let f of Object.keys(i)){if(!s[f])continue;let g=s[f],m=i[f];for(let b of ao)g[b]!=null&&m[b]==null&&(m[b]=g[b]);l.push(f),c++}c>0?(le(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ce(r);if(u&&Array.isArray(u.applications)){let f={},g=0;for(let m of u.applications){let b=m.jobId||"unknown";f[b]||(f[b]={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<=uo?B.options=p.options:(B.optionsOmitted=!0,g++)),p.page&&(B.page=p.page),p.wasPreFilled&&(B.wasPreFilled=!0),p.wasRetry&&(B.wasRetry=!0),B});f[b].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})}le(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),g>0&&console.log(` Phase 2: Stripped bloated options from ${g} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete s[f];le(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 ue={};K(ue,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as E from"fs";import*as Ze from"path";var po=2,mo="reset-unread-flags";function ho(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function go(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 yo(e){let t=Ze.join(e,"conversations.json"),n=ho(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}go(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var fe={};K(fe,{NAME:()=>wo,VERSION:()=>So,up:()=>Eo});import*as C from"fs";import*as et from"path";var So=3,wo="recompute-last-message-by",vo=new Set(["draft","confirmed","rejected","needs_review"]);function bo(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function ko(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 Ao(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!vo.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 Eo(e){let t=et.join(e,"conversations.json"),n=bo(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=Ao(u,o),g=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&s++,l.lastMessageBy=f,l.conversationStatus=g,r++}if(r===0){console.log(" No conversations to recompute.");return}ko(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 pe={};K(pe,{NAME:()=>$o,VERSION:()=>Co,up:()=>Do});import*as $ from"fs";import*as tt from"path";var Co=4,$o="split-connection-timestamps",Io=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function xo(e){if(!$.existsSync(e))return null;let t=$.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function _o(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{$.writeFileSync(o,n)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.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 Do(e){let t=tt.join(e,"people.json"),n=xo(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++,Io.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}_o(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 Ro=To(import.meta.url),Oo=d.dirname(Ro),jo=d.dirname(d.dirname(Oo));function No(e){return e&&(e==="~"?me.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(me.homedir(),e.slice(2)):e)}var x=process.env.DATA_DIR?d.resolve(No(process.env.DATA_DIR)):jo,L=d.join(x,"collected-profiles"),M=d.join(x,"market-research"),w=d.join(x,".schema-version"),ot=[d.join(L,".schema-version"),d.join(M,".schema-version")],O=4,T=[{version:1,module:ae},{version:2,module:ue},{version:3,module:fe},{version:4,module:pe}];(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 it(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
11
+ ${n.join(`
12
+ `)}`;try{await Qe.addMessage(i,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var ao=lo(import.meta.url),uo=T.dirname(T.dirname(ao)),re=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(uo,"collected-profiles"),se=T.join(re,"run-log.json");function fo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";k.writeFileSync(n,o);for(let r=0;r<3;r++)try{k.renameSync(n,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ze(){try{if(!k.existsSync(se))return{runs:[]};let e=JSON.parse(k.readFileSync(se,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function et(e){k.existsSync(re)||k.mkdirSync(re,{recursive:!0});try{fo(se,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function tt(e,t="default"){let o=Ze();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,r={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>s),et(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function ie(e,t,o=null,n=null){if(!e)return;let r=null;try{let i=Ze(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,r=c.duration;else{let l=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,r=l.duration)}et(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Xe({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as u from"fs";import*as me from"os";import*as d from"path";import{fileURLToPath as Fo}from"url";var ae={};K(ae,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as A from"fs";import*as X from"path";var po=1,mo="normalize-jobs-and-questions",ho=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],go=50;function ce(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function le(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{A.writeFileSync(n,o)}catch(r){try{A.unlinkSync(n)}catch{}throw r}try{A.renameSync(n,e)}catch(r){try{A.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function yo(e,t){let o=X.join(e,"jobs.json"),n=X.join(t,"scouted-jobs.json"),r=X.join(e,"application-questions.json"),s=ce(o)||{},i=ce(n)||{},c=0,l=[];for(let f of Object.keys(s)){if(!i[f])continue;let g=i[f],m=s[f];for(let b of ho)g[b]!=null&&m[b]==null&&(m[b]=g[b]);l.push(f),c++}c>0?(le(o,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ce(r);if(a&&Array.isArray(a.applications)){let f={},g=0;for(let m of a.applications){let b=m.jobId||"unknown";f[b]||(f[b]={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<=go?B.options=p.options:(B.optionsOmitted=!0,g++)),p.page&&(B.page=p.page),p.wasPreFilled&&(B.wasPreFilled=!0),p.wasRetry&&(B.wasRetry=!0),B});f[b].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})}le(r,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),g>0&&console.log(` Phase 2: Stripped bloated options from ${g} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete i[f];le(n,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ue={};K(ue,{NAME:()=>wo,VERSION:()=>So,up:()=>ko});import*as E from"fs";import*as ot from"path";var So=2,wo="reset-unread-flags";function vo(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function bo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{E.writeFileSync(n,o)}catch(r){try{E.unlinkSync(n)}catch{}throw r}try{E.renameSync(n,e)}catch(r){try{E.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ko(e){let t=ot.join(e,"conversations.json"),o=vo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}bo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var fe={};K(fe,{NAME:()=>Eo,VERSION:()=>Ao,up:()=>xo});import*as C from"fs";import*as nt from"path";var Ao=3,Eo="recompute-last-message-by",Co=new Set(["draft","confirmed","rejected","needs_review"]);function _o(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function Io(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{C.writeFileSync(n,o)}catch(r){try{C.unlinkSync(n)}catch{}throw r}try{C.renameSync(n,e)}catch(r){try{C.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function $o(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!Co.has(s.status));if(o.length===0)return"them";let n=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=n.length>0?n:[...o].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function xo(e){let t=nt.join(e,"conversations.json"),o=_o(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 r=0,s=0,i=0;for(let c of Object.keys(o)){let l=o[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let a=Array.isArray(l.messages)?l.messages:[],f=$o(a,n),g=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&i++,l.lastMessageBy=f,l.conversationStatus=g,r++}if(r===0){console.log(" No conversations to recompute.");return}Io(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var pe={};K(pe,{NAME:()=>Do,VERSION:()=>Ro,up:()=>No});import*as _ from"fs";import*as rt from"path";var Ro=4,Do="split-connection-timestamps",To=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Oo(e){if(!_.existsSync(e))return null;let t=_.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function jo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{_.writeFileSync(n,o)}catch(r){try{_.unlinkSync(n)}catch{}throw r}try{_.renameSync(n,e)}catch(r){try{_.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function No(e){let t=rt.join(e,"people.json"),o=Oo(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let s of Object.keys(o)){let i=o[s];!i||typeof i!="object"||(r++,To.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}jo(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var Po=Fo(import.meta.url),Lo=d.dirname(Po),Mo=d.dirname(d.dirname(Lo));function Uo(e){return e&&(e==="~"?me.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(me.homedir(),e.slice(2)):e)}var $=process.env.DATA_DIR?d.resolve(Uo(process.env.DATA_DIR)):Mo,L=d.join($,"collected-profiles"),M=d.join($,"market-research"),w=d.join($,".schema-version"),st=[d.join(L,".schema-version"),d.join(M,".schema-version")],O=4,D=[{version:1,module:ae},{version:2,module:ue},{version:3,module:fe},{version:4,module:pe}];(function(){D.sort((n,r)=>n.version-r.version);let t=new Set;for(let n of D){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 r=n.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=D.length?D[D.length-1].version:0;if(o!==O)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${O}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<D.length;n++){let r=n+1;if(D[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${D[n].version}`)}})();function at(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
13
13
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
14
- `),process.exit(1));try{a.mkdirSync(x,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
15
- [FATAL] Cannot create DATA_DIR (${x}): ${t.message}`),console.error(` Fix the path or permissions and try again.
16
- `),process.exit(1))}let e;try{e=a.statSync(x)}catch(t){console.error(`
17
- [FATAL] DATA_DIR (${x}) is not accessible: ${t.message}
14
+ `),process.exit(1));try{u.mkdirSync($,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
15
+ [FATAL] Cannot create DATA_DIR (${$}): ${t.message}`),console.error(` Fix the path or permissions and try again.
16
+ `),process.exit(1))}let e;try{e=u.statSync($)}catch(t){console.error(`
17
+ [FATAL] DATA_DIR (${$}) is not accessible: ${t.message}
18
18
  `),process.exit(1)}e.isDirectory()||(console.error(`
19
- [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.
20
- `),process.exit(1));for(let t of[L,M]){let n;try{n=a.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
19
+ [FATAL] DATA_DIR (${$}) 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.
20
+ `),process.exit(1));for(let t of[L,M]){let o;try{o=u.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
21
21
  [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.
22
- `),process.exit(1))}}var P=d.join(x,".migration-lock");function Fo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(P,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(a.readFileSync(P,"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
+ `),process.exit(1))}}var P=d.join($,".migration-lock");function qo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(P,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(u.readFileSync(P,"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 r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}n&&s<r&&(console.error(`
23
23
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${P}
24
24
  `),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.
25
- `),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=P+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,P),!0}catch(o){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function he(){try{if(JSON.parse(a.readFileSync(P,"utf-8")).pid!==process.pid)return;a.unlinkSync(P)}catch{}}var nt=!1;function Po(){if(nt)return;nt=!0;let e=()=>{try{he()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Lo(){if(a.existsSync(w))return;let e=[],t=[];for(let i of ot)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(`
26
- [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
25
+ `),process.exit(1)),n&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=P+".tmp";try{return u.writeFileSync(o,e),u.renameSync(o,P),!0}catch(n){try{u.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function he(){try{if(JSON.parse(u.readFileSync(P,"utf-8")).pid!==process.pid)return;u.unlinkSync(P)}catch{}}var it=!1;function Bo(){if(it)return;it=!0;let e=()=>{try{he()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Jo(){if(u.existsSync(w))return;let e=[],t=[];for(let s of st)if(u.existsSync(s))try{e.push({file:s,schema:Z(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
26
+ [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
27
27
  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.
28
- `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
29
- [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
30
- `),process.exit(1)}let o=e[0].schema,r=w+".tmp";try{a.writeFileSync(r,JSON.stringify(o,null,2)),a.renameSync(r,w)}catch(i){try{a.unlinkSync(r)}catch{}throw i}for(let i of ot)if(a.existsSync(i))try{a.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${w}`)}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 Z(e){let t=a.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function rt(){if(Lo(),!a.existsSync(w))return{version:0,migrations:[]};let e;try{e=Z(w)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
31
- [FATAL] ${w} 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.
32
- `),process.exit(1)}let t=Mo(e);return t===null&&(console.error(`
28
+ `),process.exit(1)}if(e.length===0)return;let o=e.map(s=>s.schema.version);if(new Set(o).size>1){console.error(`
29
+ [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
30
+ `),process.exit(1)}let n=e[0].schema,r=w+".tmp";try{u.writeFileSync(r,JSON.stringify(n,null,2)),u.renameSync(r,w)}catch(s){try{u.unlinkSync(r)}catch{}throw s}for(let s of st)if(u.existsSync(s))try{u.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${w}`)}function Vo(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 Z(e){let t=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ct(){if(Jo(),!u.existsSync(w))return{version:0,migrations:[]};let e;try{e=Z(w)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
31
+ [FATAL] ${w} 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.
32
+ `),process.exit(1)}let t=Vo(e);return t===null&&(console.error(`
33
33
  [FATAL] ${w} 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.
34
- `),process.exit(1)),t}function ct(e){try{a.chmodSync(e,384)}catch{}}function Uo(e){if(it(),a.existsSync(w))try{if(a.lstatSync(w).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${w}. 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=w+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),ct(t),a.renameSync(t,w)}catch(n){try{a.unlinkSync(t)}catch{}throw n}}function st(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{at(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 de=!1;async function lt(){if(de)return;it(),Wo();let t=rt().version;if(t===O){de=!0;return}Po(),Fo(),process.on("exit",he),t>O&&(console.error(`
34
+ `),process.exit(1)),t}function ut(e){try{u.chmodSync(e,384)}catch{}}function Ho(e){if(at(),u.existsSync(w))try{if(u.lstatSync(w).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${w}. 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=w+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),ut(t),u.renameSync(t,w)}catch(o){try{u.unlinkSync(t)}catch{}throw o}}function lt(e,t){if(!u.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=u.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return u.statSync(d.join(e,c)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let c of n){let l=d.join(e,c),a=d.join(e,c+o);if(u.existsSync(a)){s++;continue}try{pt(l,a),r++}catch(f){i.push({file:c,err:f.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${d.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||s>0){let c=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${d.basename(e)}/ (${o})${c}`)}}var de=!1;async function ft(){if(de)return;at(),zo();let t=ct().version;if(t===O){de=!0;return}Bo(),qo(),process.on("exit",he),t>O&&(console.error(`
35
35
  [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.
36
36
  `),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}.
37
37
  `),process.exit(1)),console.log(`
38
- \u{1F4E6} Schema migration: v${t} \u2192 v${O}`);let n=Ho();if(!n.ok){console.error(`
39
- [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
38
+ \u{1F4E6} Schema migration: v${t} \u2192 v${O}`);let o=Qo();if(!o.ok){console.error(`
39
+ [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of o.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
40
40
  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'.
41
- `),process.exit(1)}let o=T.filter(r=>r.version>t);for(let r of o){console.log(`
42
- Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{st(L,r.version),st(M,r.version)}catch(l){console.error(`
43
- [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.
41
+ `),process.exit(1)}let n=D.filter(r=>r.version>t);for(let r of n){console.log(`
42
+ Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{lt(L,r.version),lt(M,r.version)}catch(l){console.error(`
43
+ [FATAL] Pre-migration backup failed for ${s}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
44
44
  `),process.exit(1)}let c=r.module;try{await c.up(L,M)}catch(l){console.error(`
45
- [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let u=Go(s);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
46
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
47
- `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
48
- `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:r.version,name:c.NAME||i,appliedAt:l},f=rt();f.version=r.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),Uo(f)}catch(l){console.error(`
49
- [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.
50
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Me()}catch{}try{Be()}catch{}de=!0,he(),console.log(`
45
+ [FATAL] Migration ${s} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=Xo(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.
46
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
47
+ `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
48
+ `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:r.version,name:c.NAME||s,appliedAt:l},f=ct();f.version=r.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(a),Ho(f)}catch(l){console.error(`
49
+ [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
50
+ `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Be()}catch{}try{He()}catch{}de=!0,he(),console.log(`
51
51
  \u2713 Schema is now at v${O}
52
- `)}var qo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Bo(e){let t=e.toLowerCase();return qo.some(n=>n.test(t))}var Jo=6e4;function Vo(){let e=Date.now(),t=[];for(let n of[x,L,M]){if(!a.existsSync(n))continue;let o;try{o=a.readdirSync(n)}catch{continue}for(let r of o){if(!Bo(r))continue;let i=d.join(n,r);try{let s=a.statSync(i);if(!s.isFile()||e-s.mtimeMs<Jo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function Wo({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 Ho(){let e=[];for(let t of[L,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 Go(e){let t=[],n=[];for(let i of[L,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(g){n.push(`${d.basename(i)}/${c}: ${g.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{at(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 at(e,t){let n=t+".tmp";try{a.copyFileSync(e,n),ct(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 Ko=Yo(import.meta.url),zo=U.dirname(Ko),ge=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(zo,"market-research"),J=U.join(ge,"profile-viewers.json");await lt();var ft=process.argv.slice(2),ut=ft.includes("--save"),Qo=ft.includes("--list");function Xo(){if(!I.existsSync(J)){console.log(`
52
+ `)}var Wo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Go(e){let t=e.toLowerCase();return Wo.some(o=>o.test(t))}var Yo=6e4;function Ko(){let e=Date.now(),t=[];for(let o of[$,L,M]){if(!u.existsSync(o))continue;let n;try{n=u.readdirSync(o)}catch{continue}for(let r of n){if(!Go(r))continue;let s=d.join(o,r);try{let i=u.statSync(s);if(!i.isFile()||e-i.mtimeMs<Yo)continue;t.push({dir:o,file:r,fullPath:s})}catch{}}}return t}function zo({verbose:e=!1}={}){let t=Ko();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: ${d.basename(n.dir)}/${n.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${r.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Qo(){let e=[];for(let t of[L,M]){if(!u.existsSync(t))continue;let o=u.readdirSync(t).filter(n=>{let r=n.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let n of o){let r=d.join(t,n);try{Z(r)}catch(s){e.push({dir:d.basename(t),file:n,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Xo(e){let t=[],o=[];for(let s of[L,M]){if(!u.existsSync(s))continue;let i=u.readdirSync(s).filter(c=>c.endsWith(e));for(let c of i){let l=d.join(s,c),a=c.slice(0,-e.length),f=d.join(s,a);try{a.toLowerCase().endsWith(".json")?Z(l):u.accessSync(l,u.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:s})}catch(g){o.push(`${d.basename(s)}/${c}: ${g.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,r=[];for(let{backupPath:s,originalPath:i,fileName:c,dir:l}of t)try{pt(s,i),n++}catch(a){r.push(`${d.basename(l)}/${c}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:n}:{ok:!0,restored:n}}function pt(e,t){let o=t+".tmp";try{u.copyFileSync(e,o),ut(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 r=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 r.code=n.code,r}throw n}}var en=Zo(import.meta.url),tn=U.dirname(en),ge=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(tn,"market-research"),J=U.join(ge,"profile-viewers.json");await ft();var mt=process.argv.slice(2),dt=mt.includes("--save"),on=mt.includes("--list");function nn(){if(!I.existsSync(J)){console.log(`
53
53
  No viewer data yet. Run: npm run viewers -- --save
54
- `);return}let t=JSON.parse(I.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(`
55
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(`
56
- 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
57
- `)}async function Zo(){if(console.log(`
54
+ `);return}let t=JSON.parse(I.readFileSync(J,"utf-8")).scans||[],o=t.flatMap(i=>i.viewers||[]),n=new Map;for(let i of o)(!n.has(i.profileUrl)||i.scanDate>n.get(i.profileUrl).scanDate)&&n.set(i.profileUrl,i);console.log(`
55
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${n.size}`);let r=[...n.values()].filter(i=>i.isConnected).length,s=[...n.values()].filter(i=>i.weVisitedThem).length;if(console.log(` Already connected: ${r}`),console.log(` We visited first: ${s} (\u2192 they responded by viewing us)`),n.size>0){console.log(`
56
+ Recent viewers:`);let i=[...n.values()].slice(0,10);for(let c of i){let l=[];c.isConnected&&l.push("connected"),c.weVisitedThem&&l.push("we visited"),c.isDiscovered&&l.push("discovered");let a=l.length?` [${l.join(", ")}]`:"";console.log(` ${c.name} (${c.connectionDegree||"?"})${a}`),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
57
+ `)}async function rn(){if(console.log(`
58
58
  LinkedIn Profile Viewers
59
- `),Qo){Xo();return}let e=Xe("viewers",ut?"save":"view"),{browser:t,page:n}=await Pe();try{console.log(` Extracting profile viewers...
60
- `);let o=await We(n);console.log(` Found ${o.length} viewers`);let r=He(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(ut&&r.length>0){I.existsSync(ge)||I.mkdirSync(ge,{recursive:!0});let s={scans:[]};try{I.existsSync(J)&&(s=JSON.parse(I.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),I.writeFileSync(J,JSON.stringify(s,null,2)),console.log(`
61
- 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(`
62
- Summary: ${i.viewers} viewers, ${i.connected} connected, ${i.weVisitedFirst} we visited first`),ie(e,"success",i)}catch(o){console.error(`
63
- Error:`,o.message),ie(e,"error",null,o.message)}finally{await t.close().catch(()=>{})}}Zo().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
59
+ `),on){nn();return}let e=tt("viewers",dt?"save":"view"),{browser:t,page:o}=await Ue();try{console.log(` Extracting profile viewers...
60
+ `);let n=await Ye(o);console.log(` Found ${n.length} viewers`);let r=Ke(n);for(let i of r){let c=[];i.isConnected?c.push("\u2713 connected"):i.isPending&&c.push("\u23F3 pending"),i.weVisitedThem&&c.push("\u{1F441} we visited"),i.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${i.name} (${i.connectionDegree||"?"})${l}`),i.title&&console.log(` ${i.title.slice(0,70)}`)}if(dt&&r.length>0){I.existsSync(ge)||I.mkdirSync(ge,{recursive:!0});let i={scans:[]};try{I.existsSync(J)&&(i=JSON.parse(I.readFileSync(J,"utf-8")))}catch{}i.scans.push({scanDate:new Date().toISOString(),viewerCount:r.length,viewers:r});let c=Date.now()-90*24*60*60*1e3;i.scans=i.scans.filter(l=>new Date(l.scanDate).getTime()>c),I.writeFileSync(J,JSON.stringify(i,null,2)),console.log(`
61
+ Saved ${r.length} viewers to ${J}`)}let s={viewers:r.length,connected:r.filter(i=>i.isConnected).length,weVisitedFirst:r.filter(i=>i.weVisitedThem).length};console.log(`
62
+ Summary: ${s.viewers} viewers, ${s.connected} connected, ${s.weVisitedFirst} we visited first`),ie(e,"success",s)}catch(n){console.error(`
63
+ Error:`,n.message),ie(e,"error",null,n.message)}finally{await t.close().catch(()=>{})}}rn().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});