ilml-plugin-linkedin 1.20.21 → 1.20.26
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/CHANGELOG.md +22 -0
- package/dist/applyQueue.mjs +35 -35
- package/dist/connect.mjs +78 -77
- package/dist/daily.mjs +37 -37
- package/dist/enrichProfiles.mjs +50 -50
- package/dist/funnelRunner.mjs +61 -60
- package/dist/messageBot.mjs +73 -73
- package/dist/migrationCli.mjs +44 -44
- package/dist/peopleSearchCli.mjs +13 -0
- package/dist/quota.mjs +34 -34
- package/dist/run.mjs +65 -64
- package/dist/scout.mjs +31 -31
- package/dist/syncAll.mjs +96 -95
- package/dist/syncConnections.mjs +50 -50
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +43 -43
- package/dist/visit.mjs +48 -48
- package/ilml-plugin.json +19 -1
- package/package.json +2 -1
package/dist/viewers.mjs
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
var
|
|
1
|
+
var wt=Object.defineProperty;var W=(e,t)=>{for(var o in t)wt(e,o,{get:t[o],enumerable:!0})};import"dotenv/config";import*as I from"fs";import*as J from"path";import{fileURLToPath as mn}from"url";import Mt from"puppeteer";import{addExtra as Ut}from"puppeteer-extra";import qt from"puppeteer-extra-plugin-stealth";import w from"fs";import T from"path";var vt="cookies.json";function ne(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin","cookies.json"):vt}function bt(){let e=ne(),t=T.dirname(e);return t&&t!=="."&&!w.existsSync(t)&&w.mkdirSync(t,{recursive:!0}),e}function be(e){let t=bt();return w.writeFileSync(t,JSON.stringify(e)),t}function ke(){let e=ne();if(!w.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=w.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 Ae(){return w.existsSync(ne())}function kt(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin"):"."}function Ee(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function At(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ee(t[1]):"default"}function _e(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return w.existsSync(t)||w.mkdirSync(t,{recursive:!0}),T.resolve(t);let o=Ee(e||At()),n=T.join(kt(),"chrome-profile",o);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),T.resolve(n)}var Ce=".ilml-seeded";function $e(e){return!w.existsSync(T.join(e,Ce))}function xe(e){try{w.writeFileSync(T.join(e,Ce),new Date().toISOString())}catch{}}function Ie(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{w.rmSync(T.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 Et(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(l=>!!document.querySelector(l),t)){let l=Date.now()-s;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,n))}return!1}var Te=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function _t(e){return Te.test(e||"")}async function Ct(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 c="wait";try{c=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",Te.source)}catch{}if(c==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(g=>g.name==="li_at")){let g=be(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(c==="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(a=>setTimeout(a,2500))}let l=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function
|
|
4
|
-
`).map(
|
|
5
|
-
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let
|
|
3
|
+
`))}await new Promise(a=>setTimeout(a,2500))}let l=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function Re(e,{readySelector:t,label:o="page",timeout:n=45e3}={}){let r=await Et(e,t,{timeout:n,label:o});if(!r&&_t(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 re(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 Re(e,{readySelector:o,label:n,timeout:r})}catch(l){if(i&&l.code==="SESSION_EXPIRED"){await Ct(e,{label:n});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await Re(e,{readySelector:o,label:n,timeout:r})}throw l}}import{getPluginConfig as It}from"@ilivemylife/graph-sdk";var $t={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},De=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function xt(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Oe(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)),De(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),De(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let i=xt(e.JOB_SEARCH_COMPANY_IDS);i.length&&o.set("f_C",i.join(","));let l=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();l&&o.set("f_TPR",$t[l]||l),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+o.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(c+="&"+a),c}var Rt=await It();for(let[e,t]of Object.entries(Rt))process.env[e]===void 0&&(process.env[e]=t);var je=Oe(process.env);je&&(process.env.LINKEDIN_SEARCH_URL=je);var Tt=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),In=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),Dt=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import se from"fs";import Ot from"path";var jt={headless:!1,defaultViewport:null,protocolTimeout:3e5},Y=new Set,Ne=!1;async function ee(){let e=[...Y].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});Y.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Nt(){if(Ne)return;Ne=!0;let e=t=>async()=>{await ee(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ee(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ee(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ee(),process.exit(0))}),process.on("exit",()=>{for(let t of Y)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function ie(e){return Ot.join(e,".ilml-browser-session.json")}function Me(e,t={}){try{se.writeFileSync(ie(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ft(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Me(e,o?{wsEndpoint:o}:{})}catch{}}function Lt(e){let t=Ue(e);t&&t.ownerPid===process.pid&&G(e)}function G(e){try{se.rmSync(ie(e),{force:!0})}catch{}}function Ue(e){try{return JSON.parse(se.readFileSync(ie(e),"utf-8"))}catch{return null}}function Fe(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Le(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 Pe(e,t,{probeTimeoutMs:o=4e3}={}){let n=Ue(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&Fe(n.ownerPid)?"live":(G(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Le(s,o,r);if(i===r)return s.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return G(t),"free";if(Fe(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Le(i.close().then(()=>!0).catch(()=>!1),o,!1))return G(t),"free";try{i.disconnect()}catch{}return"live"}function Pt(e,t){e&&(Nt(),Y.add(e),e.on("disconnected",()=>{Y.delete(e),t&&G(t)}))}async function qe(e,t={}){let o=_e(),n={...jt,...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 Pe(e,o)==="live")throw new Error(r);Me(o);let s;try{s=await e.launch(n)}catch{if(await Pe(e,o)==="live")throw new Error(r);Ie(o);try{s=await e.launch(n)}catch(l){throw Lt(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: ${l.message})`)}}return Pt(s,o),Ft(o,s),{browser:s,profileDir:o,needsSeed:$e(o)}}async function Be(e,t){if(!t||!t.needsSeed)return!1;if(!Ae())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(...ke()),xe(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Je=Ut(Mt);Je.use(qt());async function Ve(){let{browser:e,profileDir:t,needsSeed:o}=await qe(Je),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Be(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}import"dotenv/config";import*as y from"fs";import*as S from"path";import{fileURLToPath as Bt}from"url";var Jt=Bt(import.meta.url),Vt=S.dirname(S.dirname(Jt)),D=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"collected-profiles"):S.join(Vt,"collected-profiles"),Ht=S.join(D,"people.json"),zn=S.join(D,"jobs.json"),Qn=S.join(D,"quota.json"),Xn=S.join(D,"conversations.json"),Zn=S.join(D,"sync-state.json"),er=S.join(D,"application-questions.json"),tr=S.join(D,"profile-history"),He=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},or=He(process.env.CONNECT_MAX_DAILY,20),nr=He(process.env.CONNECT_MAX_WEEKLY,100),K=null,Wt=null,Gt=null,Yt=null,Kt=null,zt=null;function We(){K=null,Wt=null,Gt=null,Yt=null,Kt=null,zt=null}function Qt(){y.existsSync(D)||y.mkdirSync(D,{recursive:!0})}function Xt(e,t){if(!y.existsSync(e))return null;try{let o=JSON.parse(y.readFileSync(e,"utf-8"));try{y.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${S.resolve(e)}`);let n=e+".backup";if(y.existsSync(n))try{let r=JSON.parse(y.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{y.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{y.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ge(){return K||(Qt(),K=Xt(Ht,"people.json")||{},K)}import"dotenv/config";import*as P from"fs";import*as b from"path";import{fileURLToPath as Zt}from"url";var eo=Zt(import.meta.url),to=b.dirname(b.dirname(eo)),Q=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(to,"market-research"),fr=b.join(Q,"scouted-jobs.json"),oo=b.join(Q,"discovered-people.json"),no=b.join(Q,"visit-log.json"),pr=b.join(Q,"companies.json"),dr=b.join(Q,"job-decisions.json");function Ye(e){try{if(P.existsSync(e))return JSON.parse(P.readFileSync(e,"utf-8"))}catch{}return null}function Ke(){ro=null,so=null,z=null,io=null,L=null}var ro=null;var so=null;var z=null;function ze(){return z||(z=Ye(oo)||{},z)}var io=null;var L=null;function Qe(){return L||(L=Ye(no)||{visits:[]},Array.isArray(L.visits)||(L.visits=[]),L)}async function Xe(e){await re(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 l=s;for(let d=0;d<8&&!(!l.parentElement||(l=l.parentElement,l.tagName==="LI"||l.classList?.contains("pvs-list__paged-list-wrapper")));d++);let c=l?.innerText?.trim()||"",a=c.split(`
|
|
4
|
+
`).map(d=>d.trim()).filter(Boolean),f="";for(let d of a)if(d.length>2&&d.length<60&&!d.includes("View")&&!d.includes("profile")&&!d.includes("\xB7")&&!d.startsWith("1st")&&!d.startsWith("2nd")&&!d.startsWith("3rd")){f=d;break}f||(f=s.textContent?.trim()?.split(`
|
|
5
|
+
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let p=c.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,h="",k=a.indexOf(f);if(k>=0&&k+1<a.length){let d=a[k+1];!d.includes("\xB7")&&!d.startsWith("1st")&&!d.startsWith("2nd")&&(h=d)}f&&f.length>1&&o.push({profileUrl:i.startsWith("/")?"https://www.linkedin.com"+i:i,name:f,title:h||null,connectionDegree:p})}return o})}function Ze(e){let t=Ge(),o=Qe(),n=ze(),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],l=n[s.profileUrl],c=r.get(s.profileUrl);return{...s,isConnected:i?.connectionStatus==="connected",isPending:i?.connectionStatus==="pending"||i?.connectionStatus==="sent_without_note",isInPeopleDb:!!i,isDiscovered:!!l,weVisitedThem:!!c,ourVisitDate:c||null,category:i?.category||l?.role||null}})}import"dotenv/config";import*as A from"fs";import*as j from"path";import{fileURLToPath as ho}from"url";import"dotenv/config";import{createGraphClient as co,resolveToken as lo}from"@ilivemylife/graph-sdk";import{config as ao}from"dotenv";ao();var et=lo()||process.env.TOKEN;et||(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
|
|
10
|
-
`)}async function
|
|
11
|
-
\u2717 ${e}${p} failed: ${c.message||c}`)}let f=Date.now()-i.startTime;try{ho(i,c?"error":"success",{...l,summaryLines:a,__deferReport:!0},c?c.message||String(c):null)}catch(p){console.error(`[runLog] endRun failed: ${p.message}`)}if(a.length>0&&process.env.NODE_RUN_REPORTS){let p=c?"error":l.dailyLimitHit?"quota-reached":"done";try{await re({scriptName:i.script,mode:i.mode,status:p,summaryLines:a,error:c?c.message||String(c):null,duration:f})}catch(d){console.error(`[runLog] report post failed: ${d.message}`)}}if(c&&r)throw c;return l}import"dotenv/config";import*as u from"fs";import*as me from"os";import*as h from"path";import{fileURLToPath as Mo}from"url";var ae={};K(ae,{NAME:()=>yo,VERSION:()=>go,up:()=>vo});import*as A from"fs";import*as X from"path";var go=1,yo="normalize-jobs-and-questions",So=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],wo=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(s){try{A.unlinkSync(n)}catch{}throw s}try{A.renameSync(n,e)}catch(s){try{A.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function vo(e,t){let o=X.join(e,"jobs.json"),n=X.join(t,"scouted-jobs.json"),s=X.join(e,"application-questions.json"),r=ce(o)||{},i=ce(n)||{},l=0,c=[];for(let f of Object.keys(r)){if(!i[f])continue;let p=i[f],d=r[f];for(let g of So)p[g]!=null&&d[g]==null&&(d[g]=p[g]);c.push(f),l++}l>0?(le(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ce(s);if(a&&Array.isArray(a.applications)){let f={},p=0;for(let d of a.applications){let g=d.jobId||"unknown";f[g]||(f[g]={applications:[]});let q=(d.questions||[]).map(m=>{let B={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=wo?B.options=m.options:(B.optionsOmitted=!0,p++)),m.page&&(B.page=m.page),m.wasPreFilled&&(B.wasPreFilled=!0),m.wasRetry&&(B.wasRetry=!0),B});f[g].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||q.length,questions:q})}le(s,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];le(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ue={};K(ue,{NAME:()=>ko,VERSION:()=>bo,up:()=>_o});import*as E from"fs";import*as tt from"path";var bo=2,ko="reset-unread-flags";function Ao(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function Eo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{E.writeFileSync(n,o)}catch(s){try{E.unlinkSync(n)}catch{}throw s}try{E.renameSync(n,e)}catch(s){try{E.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function _o(e){let t=tt.join(e,"conversations.json"),o=Ao(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Eo(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:()=>$o,VERSION:()=>Co,up:()=>Do});import*as _ from"fs";import*as ot from"path";var Co=3,$o="recompute-last-message-by",Io=new Set(["draft","confirmed","rejected","needs_review"]);function xo(e){return _.existsSync(e)?JSON.parse(_.readFileSync(e,"utf-8")):null}function Ro(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{_.writeFileSync(n,o)}catch(s){try{_.unlinkSync(n)}catch{}throw s}try{_.renameSync(n,e)}catch(s){try{_.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function To(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!Io.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Do(e){let t=ot.join(e,"conversations.json"),o=xo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let l of Object.keys(o)){let c=o[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let a=Array.isArray(c.messages)?c.messages:[],f=To(a,n),p=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=p,s++}if(s===0){console.log(" No conversations to recompute.");return}Ro(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var pe={};K(pe,{NAME:()=>jo,VERSION:()=>Oo,up:()=>Po});import*as C from"fs";import*as nt from"path";var Oo=4,jo="split-connection-timestamps",No=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Fo(e){if(!C.existsSync(e))return null;let t=C.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{C.writeFileSync(n,o)}catch(s){try{C.unlinkSync(n)}catch{}throw s}try{C.renameSync(n,e)}catch(s){try{C.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Po(e){let t=nt.join(e,"people.json"),o=Fo(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,No.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Lo(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var Uo=Mo(import.meta.url),qo=h.dirname(Uo),Bo=h.dirname(h.dirname(qo));function Jo(e){return e&&(e==="~"?me.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(me.homedir(),e.slice(2)):e)}var I=process.env.DATA_DIR?h.resolve(Jo(process.env.DATA_DIR)):Bo,P=h.join(I,"collected-profiles"),M=h.join(I,"market-research"),v=h.join(I,".schema-version"),rt=[h.join(P,".schema-version"),h.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((n,s)=>n.version-s.version);let t=new Set;for(let n of T){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=T.length?T[T.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<T.length;n++){let s=n+1;if(T[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${T[n].version}`)}})();function lt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
9
|
+
`),process.exit(1));var tt=co({token:et});function uo(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`}var fo={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function po(e){let t=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(t)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(t)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(t)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(t)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(t)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function mo({scriptName:e,mode:t,status:o,summaryLines:n,error:r,stoppedReason:s,duration:i}){let l=o==="error"||o==="stopped"?o==="error"?"\u2717":"\u26A0":o==="quota-reached"?"\u26A0":"\u2713",c=o==="error"?"stopped early":o==="stopped"?`stopped \u2014 ${s||"did not finish"}`:o==="quota-reached"?"daily limit reached":"done",a=fo[e]||e,f=t&&t!=="default"?` \xB7 ${t}`:"",g=new Date().toISOString().slice(0,16).replace("T"," "),p=i?` \xB7 ${uo(i)}`:"",h=[];h.push(`## ${l} ${a} \u2014 ${c}`),h.push(`_${g}${f}${p}_`),h.push("");for(let k of n)h.push(`- ${k}`);if(o==="error"){h.push(""),h.push(`**What happened:** ${po(r)}`);let k=String(r||"").replace(/\s+/g," ").trim();k&&h.push(`_Technical detail: ${k.slice(0,140)}_`)}return h.join(`
|
|
10
|
+
`)}async function ce({scriptName:e,mode:t,status:o,summaryLines:n,error:r,stoppedReason:s,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(n)||n.length===0)return;let c=mo({scriptName:e,mode:t,status:o,summaryLines:n,error:r,stoppedReason:s,duration:i});try{await tt.addMessage(l,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var go=ho(import.meta.url),yo=j.dirname(j.dirname(go)),le=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"collected-profiles"):j.join(yo,"collected-profiles"),ae=j.join(le,"run-log.json");function So(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";A.writeFileSync(n,o);for(let r=0;r<3;r++)try{A.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 ot(){try{if(!A.existsSync(ae))return{runs:[]};let e=JSON.parse(A.readFileSync(ae,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function nt(e){A.existsSync(le)||A.mkdirSync(le,{recursive:!0});try{So(ae,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function wo(e,t="default"){let o=ot();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),nt(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function vo(e,t,o=null,n=null){if(!e)return;let r=null;try{let l=ot(),c=l.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 a=l.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=o,a.error=n,r=a.duration)}nt(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null,i=o&&o.__deferReport===!0;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS&&!i){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";ce({scriptName:e.script,mode:e.mode,status:l,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}async function rt(e,t,o,n,r={}){let{rethrow:s=!0}=r,i=wo(e,t),l={},c=null;try{await o(l)}catch(p){c=p}let a=[];try{let p=n?n(l):[];a=(Array.isArray(p)?p:[]).filter(h=>typeof h=="string"&&h.trim())}catch(p){console.error(`[runLog] summarize threw (report still sent): ${p.message}`)}if(a.length===0&&c&&(a=["(crashed before any progress was recorded)"]),c){let p=t&&t!=="default"?` (${t})`:"";console.error(`
|
|
11
|
+
\u2717 ${e}${p} failed: ${c.message||c}`)}let f=Date.now()-i.startTime,g=!c&&l.stoppedReason?String(l.stoppedReason):null;try{vo(i,c?"error":g?"partial":"success",{...l,summaryLines:a,__deferReport:!0},c?c.message||String(c):null)}catch(p){console.error(`[runLog] endRun failed: ${p.message}`)}if(a.length>0&&process.env.NODE_RUN_REPORTS){let p=c?"error":g?"stopped":l.dailyLimitHit?"quota-reached":"done";try{await ce({scriptName:i.script,mode:i.mode,status:p,summaryLines:a,error:c?c.message||String(c):null,stoppedReason:g,duration:f})}catch(h){console.error(`[runLog] report post failed: ${h.message}`)}}if(c&&s)throw c;return l}import"dotenv/config";import*as u from"fs";import*as Se from"os";import*as m from"path";import{fileURLToPath as zo}from"url";var pe={};W(pe,{NAME:()=>ko,VERSION:()=>bo,up:()=>_o});import*as E from"fs";import*as te from"path";var bo=1,ko="normalize-jobs-and-questions",Ao=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Eo=50;function ue(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function fe(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 _o(e,t){let o=te.join(e,"jobs.json"),n=te.join(t,"scouted-jobs.json"),r=te.join(e,"application-questions.json"),s=ue(o)||{},i=ue(n)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let g=i[f],p=s[f];for(let h of Ao)g[h]!=null&&p[h]==null&&(p[h]=g[h]);c.push(f),l++}l>0?(fe(o,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ue(r);if(a&&Array.isArray(a.applications)){let f={},g=0;for(let p of a.applications){let h=p.jobId||"unknown";f[h]||(f[h]={applications:[]});let k=(p.questions||[]).map(d=>{let V={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=Eo?V.options=d.options:(V.optionsOmitted=!0,g++)),d.page&&(V.page=d.page),d.wasPreFilled&&(V.wasPreFilled=!0),d.wasRetry&&(V.wasRetry=!0),V});f[h].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||k.length,questions:k})}fe(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(c.length>0){for(let f of c)delete i[f];fe(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var de={};W(de,{NAME:()=>$o,VERSION:()=>Co,up:()=>Ro});import*as _ from"fs";import*as st from"path";var Co=2,$o="reset-unread-flags";function xo(e){return _.existsSync(e)?JSON.parse(_.readFileSync(e,"utf-8")):null}function Io(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 Ro(e){let t=st.join(e,"conversations.json"),o=xo(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}Io(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var me={};W(me,{NAME:()=>Do,VERSION:()=>To,up:()=>Lo});import*as C from"fs";import*as it from"path";var To=3,Do="recompute-last-message-by",Oo=new Set(["draft","confirmed","rejected","needs_review"]);function jo(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function No(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 Fo(e,t){if(!e||e.length===0)return"them";let o=e.filter(s=>!Oo.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 Lo(e){let t=it.join(e,"conversations.json"),o=jo(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 l of Object.keys(o)){let c=o[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=Fo(a,n),g=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=g,r++}if(r===0){console.log(" No conversations to recompute.");return}No(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 he={};W(he,{NAME:()=>Mo,VERSION:()=>Po,up:()=>Jo});import*as $ from"fs";import*as ct from"path";var Po=4,Mo="split-connection-timestamps",Uo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function qo(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 Bo(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 Jo(e){let t=ct.join(e,"people.json"),o=qo(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++,Uo.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}Bo(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 ge={};W(ge,{NAME:()=>Ho,VERSION:()=>Vo,up:()=>Ko});import*as x from"fs";import*as lt from"path";var Vo=5,Ho="rename-headline-to-title",M=/[·•]\s*(1st|2nd|3rd)\+?/i,Wo=e=>(e||"").replace(/\s+/g," ").trim(),X=e=>Wo(e).replace(/^[+·•\s]+/,"").replace(/[·•\s]+$/,"");function Go(e){if(!x.existsSync(e))return null;let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Yo(e,t){let o=JSON.stringify(t),n=e+".tmp";try{x.writeFileSync(n,o)}catch(r){try{x.unlinkSync(n)}catch{}throw r}try{x.renameSync(n,e)}catch(r){try{x.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,t){let o=lt.join(t,"discovered-people.json"),n=Go(o);if(!n||typeof n!="object"){console.log(" discovered-people.json not found \u2014 nothing to migrate.");return}let r=Array.isArray(n)?n:Object.values(n),s=0,i=0,l=0;for(let c of r)if(!(!c||typeof c!="object")){if(s++,c.name&&M.test(c.name)){let a=X(String(c.name).split(M)[0]),f=String(c.name).match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i),g=f?X(f[1]):"";a&&(c.name=a,i++),g&&(!c.headline||M.test(String(c.headline))||!X(c.headline))&&(c.headline=g)}if(Object.prototype.hasOwnProperty.call(c,"headline")){let a=X(c.headline||"");M.test(a)&&(a=""),(!c.title||M.test(String(c.title)))&&(c.title=a||(c.title&&!M.test(String(c.title))?c.title:null)||null),delete c.headline,l++}else if(typeof c.title=="string"){let a=X(c.title);a&&!M.test(a)&&a!==c.title&&(c.title=a)}}if(l===0&&i===0){console.log(` Scanned ${s} discovered people \u2014 already unified (no headline field, clean names).`);return}Yo(o,n),console.log(` discovered-people.json: scanned ${s}, de-glued ${i} names, moved ${l} headline\u2192title.`),console.log(" Every record now carries a single `title` field (matches people.json).")}var Qo=zo(import.meta.url),Xo=m.dirname(Qo),Zo=m.dirname(m.dirname(Xo));function en(e){return e&&(e==="~"?Se.homedir():e.startsWith("~/")||e.startsWith("~\\")?m.join(Se.homedir(),e.slice(2)):e)}var R=process.env.DATA_DIR?m.resolve(en(process.env.DATA_DIR)):Zo,q=m.join(R,"collected-profiles"),B=m.join(R,"market-research"),v=m.join(R,".schema-version"),at=[m.join(q,".schema-version"),m.join(B,".schema-version")],N=5,O=[{version:1,module:pe},{version:2,module:de},{version:3,module:me},{version:4,module:he},{version:5,module:ge}];(function(){O.sort((n,r)=>n.version-r.version);let t=new Set;for(let n of O){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=O.length?O[O.length-1].version:0;if(o!==N)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${N}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<O.length;n++){let r=n+1;if(O[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${O[n].version}`)}})();function dt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
12
12
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
13
|
-
`),process.exit(1));try{u.mkdirSync(
|
|
14
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
15
|
-
`),process.exit(1))}let e;try{e=u.statSync(
|
|
16
|
-
[FATAL] DATA_DIR (${
|
|
13
|
+
`),process.exit(1));try{u.mkdirSync(R,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
14
|
+
[FATAL] Cannot create DATA_DIR (${R}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
15
|
+
`),process.exit(1))}let e;try{e=u.statSync(R)}catch(t){console.error(`
|
|
16
|
+
[FATAL] DATA_DIR (${R}) is not accessible: ${t.message}
|
|
17
17
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
18
|
-
[FATAL] DATA_DIR (${
|
|
19
|
-
`),process.exit(1));for(let t of[
|
|
18
|
+
[FATAL] DATA_DIR (${R}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
19
|
+
`),process.exit(1));for(let t of[q,B]){let o;try{o=u.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
|
|
20
20
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
21
|
-
`),process.exit(1))}}var
|
|
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: ${
|
|
21
|
+
`),process.exit(1))}}var U=m.join(R,".migration-lock");function tn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(U,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(u.readFileSync(U,"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(`
|
|
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: ${U}
|
|
23
23
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
24
|
-
`),process.exit(1)),n&&r
|
|
25
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
24
|
+
`),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=U+".tmp";try{return u.writeFileSync(o,e),u.renameSync(o,U),!0}catch(n){try{u.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function we(){try{if(JSON.parse(u.readFileSync(U,"utf-8")).pid!==process.pid)return;u.unlinkSync(U)}catch{}}var ut=!1;function on(){if(ut)return;ut=!0;let e=()=>{try{we()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function nn(){if(u.existsSync(v))return;let e=[],t=[];for(let s of at)if(u.existsSync(s))try{e.push({file:s,schema:oe(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
|
|
25
|
+
[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(`
|
|
26
26
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
27
|
-
`),process.exit(1)}if(e.length===0)return;let o=e.map(
|
|
28
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
29
|
-
`),process.exit(1)}let n=e[0].schema,
|
|
27
|
+
`),process.exit(1)}if(e.length===0)return;let o=e.map(s=>s.schema.version);if(new Set(o).size>1){console.error(`
|
|
28
|
+
[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.
|
|
29
|
+
`),process.exit(1)}let n=e[0].schema,r=v+".tmp";try{u.writeFileSync(r,JSON.stringify(n,null,2)),u.renameSync(r,v)}catch(s){try{u.unlinkSync(r)}catch{}throw s}for(let s of at)if(u.existsSync(s))try{u.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${v}`)}function rn(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 oe(e){let t=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ft(){if(nn(),!u.existsSync(v))return{version:0,migrations:[]};let e;try{e=oe(v)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
30
30
|
[FATAL] ${v} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
31
|
-
`),process.exit(1)}let t=
|
|
31
|
+
`),process.exit(1)}let t=rn(e);return t===null&&(console.error(`
|
|
32
32
|
[FATAL] ${v} 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
|
|
34
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
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${
|
|
33
|
+
`),process.exit(1)),t}function mt(e){try{u.chmodSync(e,384)}catch{}}function sn(e){if(dt(),u.existsSync(v))try{if(u.lstatSync(v).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${v}. 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=v+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),mt(t),u.renameSync(t,v)}catch(o){try{u.unlinkSync(t)}catch{}throw o}}function pt(e,t){if(!u.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=u.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return u.statSync(m.join(e,l)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let l of n){let c=m.join(e,l),a=m.join(e,l+o);if(u.existsSync(a)){s++;continue}try{gt(c,a),r++}catch(f){i.push({file:l,err:f.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${m.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(r>0||s>0){let l=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${m.basename(e)}/ (${o})${l}`)}}var ye=!1;async function ht(){if(ye)return;dt(),fn();let t=ft().version;if(t===N){ye=!0;return}on(),tn(),process.on("exit",we),t>N&&(console.error(`
|
|
34
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${N}.`),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${N}.
|
|
36
36
|
`),process.exit(1)),console.log(`
|
|
37
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
38
|
-
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let
|
|
37
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${N}`);let o=pn();if(!o.ok){console.error(`
|
|
38
|
+
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of o.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 n=
|
|
41
|
-
Running migration v${String(
|
|
42
|
-
[FATAL] Pre-migration backup failed for ${
|
|
43
|
-
`),process.exit(1)}let l=
|
|
44
|
-
[FATAL] Migration ${
|
|
40
|
+
`),process.exit(1)}let n=O.filter(r=>r.version>t);for(let r of n){console.log(`
|
|
41
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{pt(q,r.version),pt(B,r.version)}catch(c){console.error(`
|
|
42
|
+
[FATAL] Pre-migration backup failed for ${s}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
43
|
+
`),process.exit(1)}let l=r.module;try{await l.up(q,B)}catch(c){console.error(`
|
|
44
|
+
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=dn(i);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
45
45
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
46
46
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
47
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:
|
|
48
|
-
[FATAL] Migration ${
|
|
49
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
50
|
-
\u2713 Schema is now at v${
|
|
51
|
-
`)}var
|
|
47
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:r.version,name:l.NAME||s,appliedAt:c},f=ft();f.version=r.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(a),sn(f)}catch(c){console.error(`
|
|
48
|
+
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.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.
|
|
49
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{We()}catch{}try{Ke()}catch{}ye=!0,we(),console.log(`
|
|
50
|
+
\u2713 Schema is now at v${N}
|
|
51
|
+
`)}var cn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ln(e){let t=e.toLowerCase();return cn.some(o=>o.test(t))}var an=6e4;function un(){let e=Date.now(),t=[];for(let o of[R,q,B]){if(!u.existsSync(o))continue;let n;try{n=u.readdirSync(o)}catch{continue}for(let r of n){if(!ln(r))continue;let s=m.join(o,r);try{let i=u.statSync(s);if(!i.isFile()||e-i.mtimeMs<an)continue;t.push({dir:o,file:r,fullPath:s})}catch{}}}return t}function fn({verbose:e=!1}={}){let t=un();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: ${m.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 pn(){let e=[];for(let t of[q,B]){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=m.join(t,n);try{oe(r)}catch(s){e.push({dir:m.basename(t),file:n,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function dn(e){let t=[],o=[];for(let s of[q,B]){if(!u.existsSync(s))continue;let i=u.readdirSync(s).filter(l=>l.endsWith(e));for(let l of i){let c=m.join(s,l),a=l.slice(0,-e.length),f=m.join(s,a);try{a.toLowerCase().endsWith(".json")?oe(c):u.accessSync(c,u.constants.R_OK),t.push({backupPath:c,originalPath:f,fileName:l,dir:s})}catch(g){o.push(`${m.basename(s)}/${l}: ${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:l,dir:c}of t)try{gt(s,i),n++}catch(a){r.push(`${m.basename(c)}/${l}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:n}:{ok:!0,restored:n}}function gt(e,t){let o=t+".tmp";try{u.copyFileSync(e,o),mt(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 hn=mn(import.meta.url),gn=J.dirname(hn),ve=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"market-research"):J.join(gn,"market-research"),H=J.join(ve,"profile-viewers.json");await ht();var St=process.argv.slice(2),yt=St.includes("--save"),yn=St.includes("--list");function Sn(){if(!I.existsSync(H)){console.log(`
|
|
52
52
|
No viewer data yet. Run: npm run viewers -- --save
|
|
53
|
-
`);return}let t=JSON.parse(
|
|
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: ${n.size}`);let
|
|
53
|
+
`);return}let t=JSON.parse(I.readFileSync(H,"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(`
|
|
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: ${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(`
|
|
55
55
|
Recent viewers:`);let i=[...n.values()].slice(0,10);for(let l of i){let c=[];l.isConnected&&c.push("connected"),l.weVisitedThem&&c.push("we visited"),l.isDiscovered&&c.push("discovered");let a=c.length?` [${c.join(", ")}]`:"";console.log(` ${l.name} (${l.connectionDegree||"?"})${a}`),l.title&&console.log(` ${l.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
|
|
56
|
+
`)}async function wn(){if(console.log(`
|
|
57
57
|
LinkedIn Profile Viewers
|
|
58
|
-
`),
|
|
59
|
-
`);let n=await
|
|
60
|
-
Saved ${
|
|
61
|
-
Summary: ${e.viewers} viewers, ${e.connected} connected, ${e.weVisitedFirst} we visited first`)}finally{await t.close().catch(()=>{})}},e=>[`${e.viewers??0} viewers, ${e.connected??0} connected, ${e.weVisitedFirst??0} visited first`],{rethrow:!1})}
|
|
58
|
+
`),yn){Sn();return}await rt("viewers",yt?"save":"view",async e=>{let{browser:t,page:o}=await Ve();try{console.log(` Extracting profile viewers...
|
|
59
|
+
`);let n=await Xe(o);console.log(` Found ${n.length} viewers`);let r=Ze(n);for(let s of r){let i=[];s.isConnected?i.push("\u2713 connected"):s.isPending&&i.push("\u23F3 pending"),s.weVisitedThem&&i.push("\u{1F441} we visited"),s.isDiscovered&&i.push("\u{1F4CB} discovered");let l=i.length?` [${i.join(", ")}]`:"";console.log(` ${s.name} (${s.connectionDegree||"?"})${l}`),s.title&&console.log(` ${s.title.slice(0,70)}`)}if(yt&&r.length>0){I.existsSync(ve)||I.mkdirSync(ve,{recursive:!0});let s={scans:[]};try{I.existsSync(H)&&(s=JSON.parse(I.readFileSync(H,"utf-8")))}catch{}s.scans.push({scanDate:new Date().toISOString(),viewerCount:r.length,viewers:r});let i=Date.now()-90*24*60*60*1e3;s.scans=s.scans.filter(l=>new Date(l.scanDate).getTime()>i),I.writeFileSync(H,JSON.stringify(s,null,2)),console.log(`
|
|
60
|
+
Saved ${r.length} viewers to ${H}`)}e.viewers=r.length,e.connected=r.filter(s=>s.isConnected).length,e.weVisitedFirst=r.filter(s=>s.weVisitedThem).length,console.log(`
|
|
61
|
+
Summary: ${e.viewers} viewers, ${e.connected} connected, ${e.weVisitedFirst} we visited first`)}finally{await t.close().catch(()=>{})}},e=>[`${e.viewers??0} viewers, ${e.connected??0} connected, ${e.weVisitedFirst??0} visited first`],{rethrow:!1})}wn().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
|