ilml-plugin-linkedin 1.20.7 → 1.20.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/connect.mjs +59 -57
- package/dist/enrichProfile.mjs +17 -15
- package/dist/enrichProfiles.mjs +41 -39
- package/dist/funnelRunner.mjs +45 -43
- package/dist/messageBot.mjs +74 -72
- package/dist/readPost.mjs +8 -8
- package/dist/run.mjs +54 -52
- package/dist/scout.mjs +11 -11
- package/dist/syncAll.mjs +98 -96
- package/dist/syncConnections.mjs +34 -32
- package/dist/verifyAbout.mjs +20 -18
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +44 -42
- package/dist/visit.mjs +40 -38
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/viewers.mjs
CHANGED
|
@@ -1,61 +1,63 @@
|
|
|
1
|
-
var at=Object.defineProperty;var K=(e,t)=>{for(var n in t)at(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Wo}from"url";import xt from"puppeteer";import{addExtra as It}from"puppeteer-extra";import _t from"puppeteer-extra-plugin-stealth";async function z(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ut(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-s;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}var ft=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function pt(e){return ft.test(e||"")}async function dt(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await ut(e,t,{timeout:o,label:n});if(!r&&pt(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function ee(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4}={}){return await e.goto(t,{waitUntil:"domcontentloaded",timeout:s}),dt(e,{readySelector:n,label:o,timeout:r})}import{getPluginConfig as mt}from"@ilivemylife/graph-sdk";var ht=await mt();for(let[e,t]of Object.entries(ht))process.env[e]===void 0&&(process.env[e]=t);var gt=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),en=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),yt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import x from"fs";import D from"path";var St="cookies.json";function ge(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin","cookies.json"):St}function ye(){let e=ge();if(!x.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=x.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 Se(){return x.existsSync(ge())}function wt(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin"):"."}function we(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function vt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?we(t[1]):"default"}function ve(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return x.existsSync(t)||x.mkdirSync(t,{recursive:!0}),D.resolve(t);let n=we(e||vt()),o=D.join(wt(),"chrome-profile",n);return x.existsSync(o)||x.mkdirSync(o,{recursive:!0}),D.resolve(o)}var be=".ilml-seeded";function ke(e){return!x.existsSync(D.join(e,be))}function Ae(e){try{x.writeFileSync(D.join(e,be),new Date().toISOString())}catch{}}function Ee(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{x.rmSync(D.join(e,n),{force:!0}),t++}catch{}return t}import te from"fs";import bt from"path";var kt={headless:!1,defaultViewport:null,protocolTimeout:3e5},W=new Set,Ce=!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 At(){if(Ce)return;Ce=!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 oe(e){return bt.join(e,".ilml-browser-session.json")}function _e(e,t={}){try{te.writeFileSync(oe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Et(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();_e(e,n?{wsEndpoint:n}:{})}catch{}}function Ct(e){let t=Te(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{te.rmSync(oe(e),{force:!0})}catch{}}function Te(e){try{return JSON.parse(te.readFileSync(oe(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 xe(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Ie(e,t,{probeTimeoutMs:n=4e3}={}){let o=Te(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"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await xe(s,n,r);if(i===r)return s.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!i)return V(t),"free";if($e(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await xe(i.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{i.disconnect()}catch{}return"live"}function $t(e,t){e&&(At(),W.add(e),e.on("disconnected",()=>{W.delete(e),t&&V(t)}))}async function De(e,t={}){let n=ve(),o={...kt,...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 Ie(e,n)==="live")throw new Error(r);_e(n);let s;try{s=await e.launch(o)}catch{if(await Ie(e,n)==="live")throw new Error(r);Ee(n);try{s=await e.launch(o)}catch(c){throw Ct(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(s,n),Et(n,s),{browser:s,profileDir:n,needsSeed:ke(n)}}async function Re(e,t){if(!t||!t.needsSeed)return!1;if(!Se())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(...ye()),Ae(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Oe=It(xt);Oe.use(_t());async function je(){let{browser:e,profileDir:t,needsSeed:n}=await De(Oe),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Re(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 g from"path";import{fileURLToPath as Tt}from"url";var Dt=Tt(import.meta.url),Rt=g.dirname(g.dirname(Dt)),_=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(Rt,"collected-profiles"),Ot=g.join(_,"people.json"),Cn=g.join(_,"jobs.json"),$n=g.join(_,"quota.json"),xn=g.join(_,"conversations.json"),In=g.join(_,"sync-state.json"),_n=g.join(_,"application-questions.json"),Tn=g.join(_,"profile-history"),Ne=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Dn=Ne(process.env.CONNECT_MAX_DAILY,20),Rn=Ne(process.env.CONNECT_MAX_WEEKLY,100),H=null,jt=null,Nt=null,Ft=null,Lt=null,Pt=null;function Fe(){H=null,jt=null,Nt=null,Ft=null,Lt=null,Pt=null}function Mt(){h.existsSync(_)||h.mkdirSync(_,{recursive:!0})}function Ut(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Le(){return H||(Mt(),H=Ut(Ot,"people.json")||{},H)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as qt}from"url";var Bt=qt(import.meta.url),Jt=S.dirname(S.dirname(Bt)),Y=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(Jt,"market-research"),Un=S.join(Y,"scouted-jobs.json"),Vt=S.join(Y,"discovered-people.json"),Wt=S.join(Y,"visit-log.json"),qn=S.join(Y,"companies.json"),Bn=S.join(Y,"job-decisions.json");function Pe(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Me(){Ht=null,Gt=null,G=null,Yt=null,N=null}var Ht=null;var Gt=null;var G=null;function Ue(){return G||(G=Pe(Vt)||{},G)}var Yt=null;var N=null;function qe(){return N||(N=Pe(Wt)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function Be(e){await ee(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 s of o){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()||"",u=l.split(`
|
|
2
|
-
|
|
3
|
-
`)
|
|
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(`
|
|
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(`
|
|
4
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.
|
|
5
7
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
6
8
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
7
|
-
`),process.exit(1));var
|
|
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})}**
|
|
8
10
|
|
|
9
11
|
${o.join(`
|
|
10
|
-
`)}`;try{await We.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var to=eo(import.meta.url),oo=R.dirname(R.dirname(to)),ne=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(oo,"collected-profiles"),re=R.join(ne,"run-log.json");function no(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";b.writeFileSync(o,n);for(let r=0;r<3;r++)try{b.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ge(){try{if(!b.existsSync(re))return{runs:[]};let e=JSON.parse(b.readFileSync(re,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ye(e){b.existsSync(ne)||b.mkdirSync(ne,{recursive:!0});try{no(re,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ke(e,t="default"){let n=Ge();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),Ye(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function se(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=Ge(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}Ye(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";He({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as de from"os";import*as d from"path";import{fileURLToPath as Io}from"url";var le={};K(le,{NAME:()=>so,VERSION:()=>ro,up:()=>lo});import*as k from"fs";import*as X from"path";var ro=1,so="normalize-jobs-and-questions",io=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],co=50;function ie(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function ce(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{k.writeFileSync(o,n)}catch(r){try{k.unlinkSync(o)}catch{}throw r}try{k.renameSync(o,e)}catch(r){try{k.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 lo(e,t){let n=X.join(e,"jobs.json"),o=X.join(t,"scouted-jobs.json"),r=X.join(e,"application-questions.json"),s=ie(n)||{},i=ie(o)||{},c=0,l=[];for(let f of Object.keys(s)){if(!i[f])continue;let w=i[f],m=s[f];for(let v of io)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(ce(n,s),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ie(r);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let q=(m.questions||[]).map(p=>{let B={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=co?B.options=p.options:(B.optionsOmitted=!0,w++)),p.page&&(B.page=p.page),p.wasPreFilled&&(B.wasPreFilled=!0),p.wasRetry&&(B.wasRetry=!0),B});f[v].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||q.length,questions:q})}ce(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete i[f];ce(o,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ae={};K(ae,{NAME:()=>uo,VERSION:()=>ao,up:()=>mo});import*as A from"fs";import*as ze from"path";var ao=2,uo="reset-unread-flags";function fo(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function po(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 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 mo(e){let t=ze.join(e,"conversations.json"),n=fo(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}po(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ue={};K(ue,{NAME:()=>go,VERSION:()=>ho,up:()=>bo});import*as E from"fs";import*as Qe from"path";var ho=3,go="recompute-last-message-by",yo=new Set(["draft","confirmed","rejected","needs_review"]);function So(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function wo(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 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 vo(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!yo.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function bo(e){let t=Qe.join(e,"conversations.json"),n=So(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let u=Array.isArray(l.messages)?l.messages:[],f=vo(u,o),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&i++,l.lastMessageBy=f,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}wo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var fe={};K(fe,{NAME:()=>Ao,VERSION:()=>ko,up:()=>xo});import*as C from"fs";import*as Xe from"path";var ko=4,Ao="split-connection-timestamps",Eo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Co(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 $o(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 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 xo(e){let t=Xe.join(e,"people.json"),n=Co(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,Eo.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}$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 _o=Io(import.meta.url),To=d.dirname(_o),Do=d.dirname(d.dirname(To));function Ro(e){return e&&(e==="~"?de.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(de.homedir(),e.slice(2)):e)}var I=process.env.DATA_DIR?d.resolve(Ro(process.env.DATA_DIR)):Do,P=d.join(I,"collected-profiles"),M=d.join(I,"market-research"),y=d.join(I,".schema-version"),Ze=[d.join(P,".schema-version"),d.join(M,".schema-version")],O=4,T=[{version:1,module:le},{version:2,module:ae},{version:3,module:ue},{version:4,module:fe}];(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 nt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
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
13
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
12
|
-
`),process.exit(1));try{a.mkdirSync(
|
|
13
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
14
|
-
`),process.exit(1))}let e;try{e=a.statSync(
|
|
15
|
-
[FATAL] DATA_DIR (${
|
|
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}
|
|
16
18
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
17
|
-
[FATAL] DATA_DIR (${
|
|
18
|
-
`),process.exit(1));for(let t of[
|
|
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
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.
|
|
20
|
-
`),process.exit(1))}}var
|
|
21
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
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(`
|
|
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}
|
|
22
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.
|
|
23
|
-
`),process.exit(1)),o&&
|
|
24
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
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
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.
|
|
26
|
-
`),process.exit(1)}if(e.length===0)return;let n=e.map(
|
|
27
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
28
|
-
`),process.exit(1)}let o=e[0].schema,r=
|
|
29
|
-
[FATAL] ${
|
|
30
|
-
`),process.exit(1)}let t=
|
|
31
|
-
[FATAL] ${
|
|
32
|
-
`),process.exit(1)),t}function
|
|
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(`
|
|
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(`
|
|
33
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.
|
|
34
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}.
|
|
35
37
|
`),process.exit(1)),console.log(`
|
|
36
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${O}`);let n=
|
|
38
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${O}`);let n=Ho();if(!n.ok){console.error(`
|
|
37
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
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'.
|
|
39
41
|
`),process.exit(1)}let o=T.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
40
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let
|
|
41
|
-
[FATAL] Pre-migration backup failed for ${
|
|
42
|
-
`),process.exit(1)}let c=r.module;try{await c.up(
|
|
43
|
-
[FATAL] Migration ${
|
|
44
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${
|
|
45
|
-
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${
|
|
46
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),u={version:r.version,name:c.NAME||
|
|
47
|
-
[FATAL] Migration ${
|
|
48
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
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.
|
|
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(`
|
|
49
51
|
\u2713 Schema is now at v${O}
|
|
50
|
-
`)}var
|
|
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(`
|
|
51
53
|
No viewer data yet. Run: npm run viewers -- --save
|
|
52
|
-
`);return}let t=JSON.parse(
|
|
53
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(
|
|
54
|
-
Recent viewers:`);let
|
|
55
|
-
`)}async function
|
|
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(`
|
|
56
58
|
LinkedIn Profile Viewers
|
|
57
|
-
`),
|
|
58
|
-
`);let o=await
|
|
59
|
-
Saved ${r.length} viewers to ${J}`)}let
|
|
60
|
-
Summary: ${
|
|
61
|
-
Error:`,o.message),
|
|
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)});
|