ilml-plugin-linkedin 1.19.2 → 1.20.0
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 +5 -0
- package/dist/applyQueue.mjs +33 -33
- package/dist/connect.mjs +80 -78
- package/dist/daily.mjs +34 -34
- package/dist/enrichProfile.mjs +15 -15
- package/dist/enrichProfiles.mjs +40 -40
- package/dist/funnelRunner.mjs +60 -60
- package/dist/messageBot.mjs +54 -54
- package/dist/migrationCli.mjs +26 -26
- package/dist/quota.mjs +36 -36
- package/dist/run.mjs +73 -73
- package/dist/scout.mjs +30 -30
- package/dist/syncAll.mjs +112 -112
- package/dist/syncConnections.mjs +50 -50
- package/dist/verifyAbout.mjs +12 -12
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +18 -18
- package/dist/visit.mjs +39 -39
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/viewers.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var Qe=Object.defineProperty;var
|
|
2
|
-
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let r=await e.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ve(r,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:r}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as at}from"url";var ut=at(import.meta.url),ft=g.dirname(g.dirname(ut)),
|
|
1
|
+
var Qe=Object.defineProperty;var G=(e,t)=>{for(var n in t)Qe(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Co}from"url";import it from"puppeteer";import{addExtra as ct}from"puppeteer-extra";import lt from"puppeteer-extra-plugin-stealth";async function Y(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as Xe}from"@ilivemylife/graph-sdk";var Ze=await Xe();for(let[e,t]of Object.entries(Ze))process.env[e]===void 0&&(process.env[e]=t);var et=process.env.LINKEDIN_NAME,O=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),jo=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.NEEDS_REVIEW])),tt=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.REJECTED,O.NEEDS_REVIEW]));import I from"fs";import T from"path";var ot="cookies.json";function ue(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin","cookies.json"):ot}function fe(){let e=ue();if(!I.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=I.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function pe(){return I.existsSync(ue())}function nt(){let e=process.env.ILML_SCOPE_DIR;return e?T.join(e,"plugins-state","linkedin"):"."}function de(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function rt(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?de(t[1]):"default"}function me(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),T.resolve(t);let n=de(e||rt()),o=T.join(nt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),T.resolve(o)}var he=".ilml-seeded";function ge(e){return!I.existsSync(T.join(e,he))}function ye(e){try{I.writeFileSync(T.join(e,he),new Date().toISOString())}catch{}}function Se(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(T.join(e,n),{force:!0}),t++}catch{}return t}var st={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function we(e,t={}){let n=me(),o={...st,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{Se(n);try{r=await e.launch(o)}catch(s){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${s.message})`)}}return{browser:r,profileDir:n,needsSeed:ge(n)}}async function ve(e,t){if(!t||!t.needsSeed)return!1;if(!pe())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...fe()),ye(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var be=ct(it);be.use(lt());async function ke(){let{browser:e,profileDir:t,needsSeed:n}=await we(be),o=async()=>{console.log(`
|
|
2
|
+
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let r=await e.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ve(r,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:r}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as at}from"url";var ut=at(import.meta.url),ft=g.dirname(g.dirname(ut)),x=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(ft,"collected-profiles"),pt=g.join(x,"people.json"),tn=g.join(x,"jobs.json"),on=g.join(x,"quota.json"),nn=g.join(x,"conversations.json"),rn=g.join(x,"sync-state.json"),sn=g.join(x,"application-questions.json"),cn=g.join(x,"profile-history"),Ae=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ln=Ae(process.env.CONNECT_MAX_DAILY,20),an=Ae(process.env.CONNECT_MAX_WEEKLY,100),V=null,dt=null,mt=null,ht=null,gt=null,yt=null;function Ce(){V=null,dt=null,mt=null,ht=null,gt=null,yt=null}function St(){h.existsSync(x)||h.mkdirSync(x,{recursive:!0})}function wt(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ee(){return V||(St(),V=wt(pt,"people.json")||{},V)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as vt}from"url";var bt=vt(import.meta.url),kt=S.dirname(S.dirname(bt)),H=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(kt,"market-research"),yn=S.join(H,"scouted-jobs.json"),At=S.join(H,"discovered-people.json"),Ct=S.join(H,"visit-log.json"),Sn=S.join(H,"companies.json"),wn=S.join(H,"job-decisions.json");function $e(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Ie(){Et=null,$t=null,W=null,It=null,N=null}var Et=null;var $t=null;var W=null;function De(){return W||(W=$e(At)||{},W)}var It=null;var N=null;function xe(){return N||(N=$e(Ct)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function _e(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await Y(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await Y(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let i of o){let s=i.getAttribute("href")?.split("?")[0];if(!s||r.has(s))continue;r.add(s);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
|
|
3
3
|
`).map(p=>p.trim()).filter(Boolean),f="";for(let p of u)if(p.length>2&&p.length<60&&!p.includes("View")&&!p.includes("profile")&&!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&!p.startsWith("3rd")){f=p;break}f||(f=i.textContent?.trim()?.split(`
|
|
4
|
-
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",
|
|
4
|
+
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",q=u.indexOf(f);if(q>=0&&q+1<u.length){let p=u[q+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:s.startsWith("/")?"https://www.linkedin.com"+s:s,name:f,title:v||null,connectionDegree:m})}return n})}function Te(e){let t=Ee(),n=xe(),o=De(),r=new Map;for(let i of n.visits||[]){let s=r.get(i.profileUrl);(!s||i.date>s)&&r.set(i.profileUrl,i.date)}return e.map(i=>{let s=t[i.profileUrl],c=o[i.profileUrl],l=r.get(i.profileUrl);return{...i,isConnected:s?.connectionStatus==="connected",isPending:s?.connectionStatus==="pending"||s?.connectionStatus==="sent_without_note",isInPeopleDb:!!s,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:s?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as R from"path";import{fileURLToPath as jt}from"url";import"dotenv/config";import{createGraphClient as Dt,resolveToken as xt}from"@ilivemylife/graph-sdk";import{config as _t}from"dotenv";_t();var Re=xt()||process.env.TOKEN;Re||(console.error(`
|
|
5
5
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
6
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
7
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
8
|
-
`),process.exit(1));var
|
|
8
|
+
`),process.exit(1));var je=Dt({token:Re});function Tt(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Rt({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${Tt(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${l} \u2014 ${s}${c}`}async function Oe({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(o)||o.length===0)return;let l=`**${Rt({scriptName:e,mode:t,status:n,error:r,duration:i})}**
|
|
9
9
|
|
|
10
10
|
${o.join(`
|
|
11
|
-
`)}`;try{await Re.addMessage(s,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var jt=Rt(import.meta.url),Nt=O.dirname(O.dirname(jt)),Q=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(Nt,"collected-profiles"),X=O.join(Q,"run-log.json");function Ft(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";b.writeFileSync(o,n);for(let r=0;r<3;r++)try{b.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ne(){try{if(!b.existsSync(X))return{runs:[]};let e=JSON.parse(b.readFileSync(X,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Fe(e){b.existsSync(Q)||b.mkdirSync(Q,{recursive:!0});try{Ft(X,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Le(e,t="default"){let n=Ne();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),Fe(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Z(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=Ne(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}Fe(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";je({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ce from"os";import*as d from"path";import{fileURLToPath as io}from"url";var oe={};Y(oe,{NAME:()=>Pt,VERSION:()=>Lt,up:()=>Ut});import*as k from"fs";import*as K from"path";var Lt=1,Pt="normalize-jobs-and-questions",Mt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],qt=50;function ee(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function te(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{k.writeFileSync(o,n)}catch(r){try{k.unlinkSync(o)}catch{}throw r}try{k.renameSync(o,e)}catch(r){try{k.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ut(e,t){let n=K.join(e,"jobs.json"),o=K.join(t,"scouted-jobs.json"),r=K.join(e,"application-questions.json"),i=ee(n)||{},s=ee(o)||{},c=0,l=[];for(let f of Object.keys(i)){if(!s[f])continue;let w=s[f],m=i[f];for(let v of Mt)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(te(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ee(r);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let U=(m.questions||[]).map(p=>{let B={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=qt?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||U.length,questions:U})}te(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete s[f];te(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ne={};Y(ne,{NAME:()=>Jt,VERSION:()=>Bt,up:()=>Ht});import*as A from"fs";import*as Pe from"path";var Bt=2,Jt="reset-unread-flags";function Vt(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Wt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{A.writeFileSync(o,n)}catch(r){try{A.unlinkSync(o)}catch{}throw r}try{A.renameSync(o,e)}catch(r){try{A.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ht(e){let t=Pe.join(e,"conversations.json"),n=Vt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Wt(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var re={};Y(re,{NAME:()=>Gt,VERSION:()=>Yt,up:()=>Zt});import*as E from"fs";import*as Me from"path";var Yt=3,Gt="recompute-last-message-by",Kt=new Set(["draft","confirmed","rejected","needs_review"]);function zt(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function Qt(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}}function Xt(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Kt.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Zt(e){let t=Me.join(e,"conversations.json"),n=zt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let u=Array.isArray(l.messages)?l.messages:[],f=Xt(u,o),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&s++,l.lastMessageBy=f,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}Qt(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var se={};Y(se,{NAME:()=>to,VERSION:()=>eo,up:()=>so});import*as $ from"fs";import*as qe from"path";var eo=4,to="split-connection-timestamps",oo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function no(e){if(!$.existsSync(e))return null;let t=$.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ro(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{$.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 so(e){let t=qe.join(e,"people.json"),n=no(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,oo.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ro(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var co=io(import.meta.url),lo=d.dirname(co),ao=d.dirname(d.dirname(lo));function uo(e){return e&&(e==="~"?ce.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ce.homedir(),e.slice(2)):e)}var D=process.env.DATA_DIR?d.resolve(uo(process.env.DATA_DIR)):ao,P=d.join(D,"collected-profiles"),M=d.join(D,"market-research"),y=d.join(D,".schema-version"),Ue=[d.join(P,".schema-version"),d.join(M,".schema-version")],R=4,_=[{version:1,module:oe},{version:2,module:ne},{version:3,module:re},{version:4,module:se}];(function(){_.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of _){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=_.length?_[_.length-1].version:0;if(n!==R)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${R}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<_.length;o++){let r=o+1;if(_[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${_[o].version}`)}})();function We(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
11
|
+
`)}`;try{await je.addMessage(s,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ot=jt(import.meta.url),Nt=R.dirname(R.dirname(Ot)),Q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Nt,"collected-profiles"),X=R.join(Q,"run-log.json");function Ft(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";b.writeFileSync(o,n);for(let r=0;r<3;r++)try{b.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Ne(){try{if(!b.existsSync(X))return{runs:[]};let e=JSON.parse(b.readFileSync(X,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Fe(e){b.existsSync(Q)||b.mkdirSync(Q,{recursive:!0});try{Ft(X,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Le(e,t="default"){let n=Ne();for(let s of n.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(s=>new Date(s.timestamp).getTime()>i),Fe(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Z(e,t,n=null,o=null){if(!e)return;let r=null;try{let s=Ne(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let l=s.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}Fe(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Oe({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ce from"os";import*as d from"path";import{fileURLToPath as io}from"url";var oe={};G(oe,{NAME:()=>Pt,VERSION:()=>Lt,up:()=>qt});import*as k from"fs";import*as K from"path";var Lt=1,Pt="normalize-jobs-and-questions",Mt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ut=50;function ee(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function te(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{k.writeFileSync(o,n)}catch(r){try{k.unlinkSync(o)}catch{}throw r}try{k.renameSync(o,e)}catch(r){try{k.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function qt(e,t){let n=K.join(e,"jobs.json"),o=K.join(t,"scouted-jobs.json"),r=K.join(e,"application-questions.json"),i=ee(n)||{},s=ee(o)||{},c=0,l=[];for(let f of Object.keys(i)){if(!s[f])continue;let w=s[f],m=i[f];for(let v of Mt)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(te(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=ee(r);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let q=(m.questions||[]).map(p=>{let B={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Ut?B.options=p.options:(B.optionsOmitted=!0,w++)),p.page&&(B.page=p.page),p.wasPreFilled&&(B.wasPreFilled=!0),p.wasRetry&&(B.wasRetry=!0),B});f[v].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||q.length,questions:q})}te(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete s[f];te(o,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ne={};G(ne,{NAME:()=>Jt,VERSION:()=>Bt,up:()=>Ht});import*as A from"fs";import*as Pe from"path";var Bt=2,Jt="reset-unread-flags";function Vt(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Wt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{A.writeFileSync(o,n)}catch(r){try{A.unlinkSync(o)}catch{}throw r}try{A.renameSync(o,e)}catch(r){try{A.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ht(e){let t=Pe.join(e,"conversations.json"),n=Vt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Wt(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var re={};G(re,{NAME:()=>Yt,VERSION:()=>Gt,up:()=>Zt});import*as C from"fs";import*as Me from"path";var Gt=3,Yt="recompute-last-message-by",Kt=new Set(["draft","confirmed","rejected","needs_review"]);function zt(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function Qt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{C.writeFileSync(o,n)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Xt(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Kt.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function Zt(e){let t=Me.join(e,"conversations.json"),n=zt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let u=Array.isArray(l.messages)?l.messages:[],f=Xt(u,o),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&s++,l.lastMessageBy=f,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}Qt(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var se={};G(se,{NAME:()=>to,VERSION:()=>eo,up:()=>so});import*as E from"fs";import*as Ue from"path";var eo=4,to="split-connection-timestamps",oo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function no(e){if(!E.existsSync(e))return null;let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ro(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{E.writeFileSync(o,n)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function so(e){let t=Ue.join(e,"people.json"),n=no(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let s=n[i];!s||typeof s!="object"||(r++,oo.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}ro(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var co=io(import.meta.url),lo=d.dirname(co),ao=d.dirname(d.dirname(lo));function uo(e){return e&&(e==="~"?ce.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ce.homedir(),e.slice(2)):e)}var D=process.env.DATA_DIR?d.resolve(uo(process.env.DATA_DIR)):ao,P=d.join(D,"collected-profiles"),M=d.join(D,"market-research"),y=d.join(D,".schema-version"),qe=[d.join(P,".schema-version"),d.join(M,".schema-version")],j=4,_=[{version:1,module:oe},{version:2,module:ne},{version:3,module:re},{version:4,module:se}];(function(){_.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of _){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=_.length?_[_.length-1].version:0;if(n!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<_.length;o++){let r=o+1;if(_[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${_[o].version}`)}})();function We(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
12
12
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
13
13
|
`),process.exit(1));try{a.mkdirSync(D,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
14
14
|
[FATAL] Cannot create DATA_DIR (${D}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -21,20 +21,20 @@ ${o.join(`
|
|
|
21
21
|
`),process.exit(1))}}var L=d.join(D,".migration-lock");function fo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(L,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(a.readFileSync(L,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(s){s.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}o&&i<r&&(console.error(`
|
|
22
22
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${L}
|
|
23
23
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
24
|
-
`),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=L+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,L),!0}catch(o){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function le(){try{if(JSON.parse(a.readFileSync(L,"utf-8")).pid!==process.pid)return;a.unlinkSync(L)}catch{}}var Be=!1;function po(){if(Be)return;Be=!0;let e=()=>{try{le()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function mo(){if(a.existsSync(y))return;let e=[],t=[];for(let i of
|
|
24
|
+
`),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=L+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,L),!0}catch(o){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function le(){try{if(JSON.parse(a.readFileSync(L,"utf-8")).pid!==process.pid)return;a.unlinkSync(L)}catch{}}var Be=!1;function po(){if(Be)return;Be=!0;let e=()=>{try{le()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function mo(){if(a.existsSync(y))return;let e=[],t=[];for(let i of qe)if(a.existsSync(i))try{e.push({file:i,schema:z(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
|
|
25
25
|
[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(`
|
|
26
26
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
27
27
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
|
|
28
28
|
[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.
|
|
29
|
-
`),process.exit(1)}let o=e[0].schema,r=y+".tmp";try{a.writeFileSync(r,JSON.stringify(o,null,2)),a.renameSync(r,y)}catch(i){try{a.unlinkSync(r)}catch{}throw i}for(let i of
|
|
29
|
+
`),process.exit(1)}let o=e[0].schema,r=y+".tmp";try{a.writeFileSync(r,JSON.stringify(o,null,2)),a.renameSync(r,y)}catch(i){try{a.unlinkSync(r)}catch{}throw i}for(let i of qe)if(a.existsSync(i))try{a.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function ho(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 Je(){if(mo(),!a.existsSync(y))return{version:0,migrations:[]};let e;try{e=z(y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
30
30
|
[FATAL] ${y} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
31
31
|
`),process.exit(1)}let t=ho(e);return t===null&&(console.error(`
|
|
32
32
|
[FATAL] ${y} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
33
|
-
`),process.exit(1)),t}function He(e){try{a.chmodSync(e,384)}catch{}}function go(e){if(We(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=y+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),He(t),a.renameSync(t,y)}catch(n){try{a.unlinkSync(t)}catch{}throw n}}function Ve(e,t){if(!a.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){i++;continue}try{
|
|
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 He(e){try{a.chmodSync(e,384)}catch{}}function go(e){if(We(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=y+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),He(t),a.renameSync(t,y)}catch(n){try{a.unlinkSync(t)}catch{}throw n}}function Ve(e,t){if(!a.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,s=[];for(let c of o){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){i++;continue}try{Ye(l,u),r++}catch(f){s.push({file:c,err:f.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${d.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${d.basename(e)}/ (${n})${c}`)}}var ie=!1;async function Ge(){if(ie)return;We(),bo();let t=Je().version;if(t===j){ie=!0;return}po(),fo(),process.on("exit",le),t>j&&(console.error(`
|
|
34
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${j}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
35
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${j}.
|
|
36
36
|
`),process.exit(1)),console.log(`
|
|
37
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
37
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${j}`);let n=ko();if(!n.ok){console.error(`
|
|
38
38
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
39
39
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
40
40
|
`),process.exit(1)}let o=_.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
@@ -46,17 +46,17 @@ ${o.join(`
|
|
|
46
46
|
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
47
47
|
`)}process.exit(1)}try{let l=new Date().toISOString(),u={version:r.version,name:c.NAME||i,appliedAt:l},f=Je();f.version=r.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),go(f)}catch(l){console.error(`
|
|
48
48
|
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
49
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
50
|
-
\u2713 Schema is now at v${
|
|
51
|
-
`)}var yo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function So(e){let t=e.toLowerCase();return yo.some(n=>n.test(t))}var wo=6e4;function vo(){let e=Date.now(),t=[];for(let n of[D,P,M]){if(!a.existsSync(n))continue;let o;try{o=a.readdirSync(n)}catch{continue}for(let r of o){if(!So(r))continue;let i=d.join(n,r);try{let s=a.statSync(i);if(!s.isFile()||e-s.mtimeMs<wo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function bo({verbose:e=!1}={}){let t=vo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{a.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${d.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ko(){let e=[];for(let t of[P,M]){if(!a.existsSync(t))continue;let n=a.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=d.join(t,o);try{z(r)}catch(i){e.push({dir:d.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ao(e){let t=[],n=[];for(let i of[P,M]){if(!a.existsSync(i))continue;let s=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=d.join(i,c),u=c.slice(0,-e.length),f=d.join(i,u);try{u.toLowerCase().endsWith(".json")?z(l):a.accessSync(l,a.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:i})}catch(w){n.push(`${d.basename(i)}/${c}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{
|
|
49
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Ce()}catch{}try{Ie()}catch{}ie=!0,le(),console.log(`
|
|
50
|
+
\u2713 Schema is now at v${j}
|
|
51
|
+
`)}var yo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function So(e){let t=e.toLowerCase();return yo.some(n=>n.test(t))}var wo=6e4;function vo(){let e=Date.now(),t=[];for(let n of[D,P,M]){if(!a.existsSync(n))continue;let o;try{o=a.readdirSync(n)}catch{continue}for(let r of o){if(!So(r))continue;let i=d.join(n,r);try{let s=a.statSync(i);if(!s.isFile()||e-s.mtimeMs<wo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function bo({verbose:e=!1}={}){let t=vo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{a.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${d.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ko(){let e=[];for(let t of[P,M]){if(!a.existsSync(t))continue;let n=a.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=d.join(t,o);try{z(r)}catch(i){e.push({dir:d.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ao(e){let t=[],n=[];for(let i of[P,M]){if(!a.existsSync(i))continue;let s=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=d.join(i,c),u=c.slice(0,-e.length),f=d.join(i,u);try{u.toLowerCase().endsWith(".json")?z(l):a.accessSync(l,a.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:i})}catch(w){n.push(`${d.basename(i)}/${c}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{Ye(i,s),o++}catch(u){r.push(`${d.basename(l)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Ye(e,t){let n=t+".tmp";try{a.copyFileSync(e,n),He(n)}catch(o){try{a.unlinkSync(n)}catch{}throw o}try{a.renameSync(n,t)}catch(o){try{a.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var Eo=Co(import.meta.url),$o=U.dirname(Eo),ae=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join($o,"market-research"),J=U.join(ae,"profile-viewers.json");await Ge();var ze=process.argv.slice(2),Ke=ze.includes("--save"),Io=ze.includes("--list");function Do(){if(!$.existsSync(J)){console.log(`
|
|
52
52
|
No viewer data yet. Run: npm run viewers -- --save
|
|
53
|
-
`);return}let t=JSON.parse(
|
|
53
|
+
`);return}let t=JSON.parse($.readFileSync(J,"utf-8")).scans||[],n=t.flatMap(s=>s.viewers||[]),o=new Map;for(let s of n)(!o.has(s.profileUrl)||s.scanDate>o.get(s.profileUrl).scanDate)&&o.set(s.profileUrl,s);console.log(`
|
|
54
54
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE VIEWERS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Total scans: ${t.length}`),console.log(` Unique viewers: ${o.size}`);let r=[...o.values()].filter(s=>s.isConnected).length,i=[...o.values()].filter(s=>s.weVisitedThem).length;if(console.log(` Already connected: ${r}`),console.log(` We visited first: ${i} (\u2192 they responded by viewing us)`),o.size>0){console.log(`
|
|
55
55
|
Recent viewers:`);let s=[...o.values()].slice(0,10);for(let c of s){let l=[];c.isConnected&&l.push("connected"),c.weVisitedThem&&l.push("we visited"),c.isDiscovered&&l.push("discovered");let u=l.length?` [${l.join(", ")}]`:"";console.log(` ${c.name} (${c.connectionDegree||"?"})${u}`),c.title&&console.log(` ${c.title.slice(0,60)}`)}}console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
56
|
-
`)}async function
|
|
56
|
+
`)}async function xo(){if(console.log(`
|
|
57
57
|
LinkedIn Profile Viewers
|
|
58
58
|
`),Io){Do();return}let e=Le("viewers",Ke?"save":"view"),{browser:t,page:n}=await ke();try{console.log(` Extracting profile viewers...
|
|
59
|
-
`);let o=await _e(n);console.log(` Found ${o.length} viewers`);let r=
|
|
59
|
+
`);let o=await _e(n);console.log(` Found ${o.length} viewers`);let r=Te(o);for(let s of r){let c=[];s.isConnected?c.push("\u2713 connected"):s.isPending&&c.push("\u23F3 pending"),s.weVisitedThem&&c.push("\u{1F441} we visited"),s.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${s.name} (${s.connectionDegree||"?"})${l}`),s.title&&console.log(` ${s.title.slice(0,70)}`)}if(Ke&&r.length>0){$.existsSync(ae)||$.mkdirSync(ae,{recursive:!0});let s={scans:[]};try{$.existsSync(J)&&(s=JSON.parse($.readFileSync(J,"utf-8")))}catch{}s.scans.push({scanDate:new Date().toISOString(),viewerCount:r.length,viewers:r});let c=Date.now()-90*24*60*60*1e3;s.scans=s.scans.filter(l=>new Date(l.scanDate).getTime()>c),$.writeFileSync(J,JSON.stringify(s,null,2)),console.log(`
|
|
60
60
|
Saved ${r.length} viewers to ${J}`)}let i={viewers:r.length,connected:r.filter(s=>s.isConnected).length,weVisitedFirst:r.filter(s=>s.weVisitedThem).length};console.log(`
|
|
61
61
|
Summary: ${i.viewers} viewers, ${i.connected} connected, ${i.weVisitedFirst} we visited first`),Z(e,"success",i)}catch(o){console.error(`
|
|
62
|
-
Error:`,o.message),Z(e,"error",null,o.message)}finally{await t.close().catch(()=>{})}}
|
|
62
|
+
Error:`,o.message),Z(e,"error",null,o.message)}finally{await t.close().catch(()=>{})}}xo().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
|