ilml-plugin-linkedin 1.20.9 → 1.20.10
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/messageBot.mjs +57 -57
- package/dist/version.mjs +1 -1
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.20.10
|
|
4
|
+
- **Fixed: `messages --push-drafts` could report a message as "sent" without actually delivering it.** When the draft's thread was already open in your inbox, the send ran on the shared messaging page and could land on the WRONG message box — a leftover floating chat bubble for a different person — then see that box clear and report "✓ sent" while the intended person received nothing. Push now prefers the reliable path that opens the recipient's own profile and confirms the recipient before sending (the same path `--send` has used since 1.17.2, which the draft push never actually adopted), and only falls back to the inbox path when no profile link is on file. A send that can't be confirmed is now reported as "failed" (your draft is kept) instead of a false "sent". Under the hood, the "did it actually send?" check is now one shared piece of logic used by both send paths, so it can't drift out of sync between them again.
|
|
5
|
+
- **Fixed: `messages --send "First Last" "text"` no longer sends a garbled fragment when the name or message contains spaces.** A quoted multi-word argument can get split on spaces before the plugin sees it, which could turn `--send "Jane Doe" "hi there"` into sending just a stray word. `--send` now detects the split and refuses with a clear message pointing you to the file-based form (`--send-batch @file.json`, or `--draft-batch @file.json` → `--push-drafts`), instead of delivering garbage.
|
|
6
|
+
- No schema change.
|
|
7
|
+
|
|
3
8
|
## 1.20.9
|
|
4
9
|
- **Commands now recover on their own when LinkedIn puts up its sign-in wall mid-run — instead of stopping and making you start over.** LinkedIn periodically throws its "join / sign in" screen on a page even though your session is still good (common when you've recently signed in from another device or location). Until now that ended the command with "session expired", and you had to log in again and re-run it. Now, when a command hits that wall, it quietly reopens your feed — where LinkedIn usually recognises you from your existing session within a few seconds, no password needed — refreshes your saved sign-in, and continues where it left off, hands-free. If LinkedIn genuinely asks for your email and password (a real sign-out), the command pauses and waits while you sign in **in the browser window it already has open**, then resumes on its own — no need to close anything or run the command again. Safeguards: your saved session is only overwritten when the refreshed one is actually valid, so a half-loaded page can never replace a good login; and an unattended/scheduled run won't hang waiting for a sign-in nobody can complete — it fails fast with a clear message instead. This works the same way across every command. No schema change.
|
|
5
10
|
|
package/dist/messageBot.mjs
CHANGED
|
@@ -1,121 +1,121 @@
|
|
|
1
|
-
var
|
|
1
|
+
var lo=Object.defineProperty;var pe=(e,t)=>{for(var o in t)lo(e,o,{get:t[o],enumerable:!0})};import*as oe from"fs";import*as oo from"readline";import N from"fs";import H from"path";var co="cookies.json";function xe(){let e=process.env.ILML_SCOPE_DIR;return e?H.join(e,"plugins-state","linkedin","cookies.json"):co}function ao(){let e=xe(),t=H.dirname(e);return t&&t!=="."&&!N.existsSync(t)&&N.mkdirSync(t,{recursive:!0}),e}function st(e){let t=ao();return N.writeFileSync(t,JSON.stringify(e)),t}function rt(){let e=xe();if(!N.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=N.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function it(){return N.existsSync(xe())}function uo(){let e=process.env.ILML_SCOPE_DIR;return e?H.join(e,"plugins-state","linkedin"):"."}function lt(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function fo(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?lt(t[1]):"default"}function ct(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return N.existsSync(t)||N.mkdirSync(t,{recursive:!0}),H.resolve(t);let o=lt(e||fo()),n=H.join(uo(),"chrome-profile",o);return N.existsSync(n)||N.mkdirSync(n,{recursive:!0}),H.resolve(n)}var at=".ilml-seeded";function ut(e){return!N.existsSync(H.join(e,at))}function ft(e){try{N.writeFileSync(H.join(e,at),new Date().toISOString())}catch{}}function dt(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{N.rmSync(H.join(e,o),{force:!0}),t++}catch{}return t}var De={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},po={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function le(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let o=parseInt(t[1],10),n=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&o!==12&&(o+=12),!s&&o===12&&(o=0),{hours:o,minutes:n}}function _e(e,t){if(!e)return null;let o=e.trim();if(!o)return null;if(t=t||new Date,/^just\s*now$/i.test(o))return t.toISOString();if(/^today\b/i.test(o)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(o)){let l=le(o),c=new Date(t);return l?c.setHours(l.hours,l.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let n=o.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(n){let l=po[n[1].toLowerCase()],c=le(n[2]||""),a=new Date(t),p=a.getDay()-l;return p<=0&&(p+=7),a.setDate(a.getDate()-p),c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let s=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=De[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),a=parseInt(s[3],10),u=le(s[4]||"");return new Date(a,l,c,u?.hours||0,u?.minutes||0,0,0).toISOString()}let r=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=De[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),a=le(r[3]||""),u=t.getFullYear(),p=new Date(u,l,c,a?.hours||0,a?.minutes||0,0,0);return p>t&&p.setFullYear(u-1),p.toISOString()}let i=o.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=De[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),a=le(i[3]||""),u=t.getFullYear(),p=new Date(u,l,c,a?.hours||0,a?.minutes||0,0,0);return p>t&&p.setFullYear(u-1),p.toISOString()}return null}async function A(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function Ie(e,t,{timeout:o=45e3,poll:n=1e3,label:s="page"}={}){let r=Date.now();for(;Date.now()-r<o;){try{if(await e.evaluate(l=>!!document.querySelector(l),t)){let l=Date.now()-r;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(i=>setTimeout(i,n))}return!1}var mt=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function me(e){return mt.test(e||"")}async function Re(e,{credentialWaitMs:t=36e4,label:o="page"}={}){console.log(` \u26A0 Auth wall on ${o} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let n=!!(process.stdin&&process.stdin.isTTY),s=n?t:Math.min(t,45e3),r=Date.now(),i=!1;for(;Date.now()-r<s;){let c="wait";try{c=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",mt.source)}catch{}if(c==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(p=>p.name==="li_at")){let p=st(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${p}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(c==="creds"){if(!n){let a=new Error(`Session expired (${o}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}i||(i=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(a=>setTimeout(a,2500))}let l=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function
|
|
3
|
+
`))}await new Promise(a=>setTimeout(a,2500))}let l=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function pt(e,{readySelector:t,label:o="page",timeout:n=45e3}={}){let s=await Ie(e,t,{timeout:n,label:o});if(!s&&me(e.url())){let r=new Error(`Session expired (${o}) \u2014 redirected to login. Run: ilml linkedin login`);throw r.code="SESSION_EXPIRED",r}return s}async function ge(e,t,{readySelector:o,label:n="page",timeout:s=45e3,gotoTimeout:r=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:r});try{return await pt(e,{readySelector:o,label:n,timeout:s})}catch(l){if(i&&l.code==="SESSION_EXPIRED"){await Re(e,{label:n});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:r})}catch{}return await pt(e,{readySelector:o,label:n,timeout:s})}throw l}}async function gt(e){let t=e.url();if(t.includes("/messaging"))return!1;if(me(t)?await Re(e,{label:"inbox"}):console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3),me(e.url())&&(await Re(e,{label:"inbox"}),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3),me(e.url())))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function ht(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function yt(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}import{getPluginConfig as mo}from"@ilivemylife/graph-sdk";var go=await mo();for(let[e,t]of Object.entries(go))process.env[e]===void 0&&(process.env[e]=t);var ne=process.env.LINKEDIN_NAME,b=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ce=Object.freeze(new Set([b.DRAFT,b.CONFIRMED,b.NEEDS_REVIEW])),z=Object.freeze(new Set([b.DRAFT,b.CONFIRMED,b.REJECTED,b.NEEDS_REVIEW]));import"dotenv/config";import*as _ from"fs";import*as T from"path";import{fileURLToPath as ho}from"url";var yo=ho(import.meta.url),wo=T.dirname(T.dirname(yo)),V=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(wo,"collected-profiles"),Te=T.join(V,"people.json"),fs=T.join(V,"jobs.json"),ds=T.join(V,"quota.json"),he=T.join(V,"conversations.json"),ps=T.join(V,"sync-state.json"),ms=T.join(V,"application-questions.json"),gs=T.join(V,"profile-history"),wt=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},hs=wt(process.env.CONNECT_MAX_DAILY,20),ys=wt(process.env.CONNECT_MAX_WEEKLY,100),se=null,So=null,vo=null,X=null,bo=null,$o=null;function St(){se=null,So=null,vo=null,X=null,bo=null,$o=null}function ye(){_.existsSync(V)||_.mkdirSync(V,{recursive:!0})}function Oe(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";_.writeFileSync(n,o);for(let s=0;s<3;s++)try{_.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function vt(e,t){if(!_.existsSync(e))return null;try{let o=JSON.parse(_.readFileSync(e,"utf-8"));try{_.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${T.resolve(e)}`);let n=e+".backup";if(_.existsSync(n))try{let s=JSON.parse(_.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{_.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{_.copyFileSync(e,e+".corrupted")}catch{}return null}}function Y(){return se||(ye(),se=vt(Te,"people.json")||{},se)}function Ne(e){ye(),se=e;try{Oe(Te,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${T.resolve(Te)}`)}}function O(){return X||(ye(),X=vt(he,"conversations.json")||{},ko(X),X)}function ko(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let s=(o.messages||[]).find(r=>r.status==="draft");s&&o.draftStatus&&o.draftStatus!=="pending"&&(s.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Oe(he,e)}catch{}}}function F(e){ye(),X=e;try{Oe(he,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${T.resolve(he)}`)}}import"dotenv/config";import*as L from"fs";import*as K from"path";import{fileURLToPath as Ro}from"url";import"dotenv/config";import{createGraphClient as Ao,resolveToken as Eo}from"@ilivemylife/graph-sdk";import{config as Co}from"dotenv";Co();var bt=Eo()||process.env.TOKEN;bt||(console.error(`
|
|
4
4
|
[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
5
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
6
6
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
7
|
-
`),process.exit(1));var
|
|
7
|
+
`),process.exit(1));var $t=Ao({token:bt});function xo(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n?`${o}m ${n}s`:`${o}m`}function Do({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${xo(s)}`:"",c=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function kt({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let c=`**${Do({scriptName:e,mode:t,status:o,error:s,duration:r})}**
|
|
8
8
|
|
|
9
9
|
${n.join(`
|
|
10
|
-
`)}`;try{await vt.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var _o=Do(import.meta.url),Ro=K.dirname(K.dirname(_o)),je=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"collected-profiles"):K.join(Ro,"collected-profiles"),Me=K.join(je,"run-log.json");function Io(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";L.writeFileSync(n,o);for(let s=0;s<3;s++)try{L.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function $t(){try{if(!L.existsSync(Me))return{runs:[]};let e=JSON.parse(L.readFileSync(Me,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function kt(e){L.existsSync(je)||L.mkdirSync(je,{recursive:!0});try{Io(Me,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function At(e,t="default"){let o=$t();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),kt(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Pe(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=$t(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,s=c.duration)}kt(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";bt({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import Fo from"puppeteer";import{addExtra as Lo}from"puppeteer-extra";import Uo from"puppeteer-extra-plugin-stealth";import Fe from"fs";import To from"path";var Oo={headless:!1,defaultViewport:null,protocolTimeout:3e5},fe=new Set,Et=!1;async function we(){let e=[...fe].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});fe.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function No(){if(Et)return;Et=!0;let e=t=>async()=>{await we(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await we(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await we(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await we(),process.exit(0))}),process.on("exit",()=>{for(let t of fe)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Le(e){return To.join(e,".ilml-browser-session.json")}function _t(e,t={}){try{Fe.writeFileSync(Le(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function jo(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();_t(e,o?{wsEndpoint:o}:{})}catch{}}function Mo(e){let t=Rt(e);t&&t.ownerPid===process.pid&&ue(e)}function ue(e){try{Fe.rmSync(Le(e),{force:!0})}catch{}}function Rt(e){try{return JSON.parse(Fe.readFileSync(Le(e),"utf-8"))}catch{return null}}function Ct(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function xt(e,t,o){let n,s=new Promise(i=>{n=setTimeout(()=>i(o),t)}),r=Promise.resolve(e).then(i=>(clearTimeout(n),i),i=>{throw clearTimeout(n),i});return Promise.race([r,s])}async function Dt(e,t,{probeTimeoutMs:o=4e3}={}){let n=Rt(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&Ct(n.ownerPid)?"live":(ue(t),"free");let s=Symbol("timeout"),r=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await xt(r,o,s);if(i===s)return r.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return ue(t),"free";if(Ct(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await xt(i.close().then(()=>!0).catch(()=>!1),o,!1))return ue(t),"free";try{i.disconnect()}catch{}return"live"}function Po(e,t){e&&(No(),fe.add(e),e.on("disconnected",()=>{fe.delete(e),t&&ue(t)}))}async function It(e,t={}){let o=it(),n={...Oo,...t,userDataDir:o},s=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Dt(e,o)==="live")throw new Error(s);_t(o);let r;try{r=await e.launch(n)}catch{if(await Dt(e,o)==="live")throw new Error(s);ut(o);try{r=await e.launch(n)}catch(l){throw Mo(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return Po(r,o),jo(o,r),{browser:r,profileDir:o,needsSeed:ct(o)}}async function Tt(e,t){if(!t||!t.needsSeed)return!1;if(!st())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(...nt()),at(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var jt=Lo(Fo);jt.use(Uo());async function Mt(){let{browser:e,profileDir:t,needsSeed:o}=await It(jt),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Tt(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}async function Be(e){await ge(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await C(3e3)),console.log(" Inbox loaded.")}async function Pt(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll(".msg-conversation-listitem"),n=[];for(let s of o){let i=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let c=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(c)||/^\s*Promoted\b/i.test(c))continue;let f=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",p=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,m,h;if(c.startsWith("You:"))m="me",h=c.slice(4).trim();else{let u=i.split(" ")[0];if(c.startsWith(i+":")||c.startsWith(u+":")){m="them";let g=c.indexOf(":");h=c.slice(g+1).trim()}else m="them",h=c}let d=s.getBoundingClientRect();n.push({name:i,lastMessagePreview:h,lastMessageTime:f,unread:p,lastMessageBy:m,x:d.x+d.width/2,y:d.y+d.height/2})}return n});for(let o of t)o.lastMessageTime=Re(o.lastMessageTime)||o.lastMessageTime;return t}async function Ft(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let n of t){let s=document.querySelector(n);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let o=document.querySelector(".msg-conversation-listitem");if(o){let n=o.parentElement;for(;n;){if(n.scrollHeight>n.clientHeight+10)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};n=n.parentElement}}return null})}async function Bo(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,o=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of o){let r=document.querySelector(s);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let n=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of n){let r=s.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function Ot(e,t){let o=await Bo(e);if(!o)return{match:!1,headerName:null};let n=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=o.toLowerCase();return{match:r.includes(n)||s.some(l=>r.includes(l)),headerName:o}}async function Ue(e,t){let o=t.split(" ")[0],n=8e3,s=500,r=0;for(;r<n;){let{match:c,headerName:a}=await Ot(e,t);if(c)return await C(500),{verified:!0,headerName:a};let f=await e.evaluate(()=>{let p=document.querySelectorAll(".msg-s-message-group__name"),m=Array.from(p).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:m,msgCount:h}});if(f.msgCount>0&&f.allSenders.some(m=>m.toLowerCase().includes(o.toLowerCase())))return await C(300),{verified:!0,headerName:o};await C(s),r+=s}let{match:i,headerName:l}=await Ot(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function qo(e){let o=0,n=0;for(let s=0;s<50;s++){let r=await e.evaluate(()=>{let i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let a=document.querySelector(".msg-overlay-conversation-bubble");a&&(i=a.querySelector(".msg-s-message-list-container")||a.querySelector(".msg-s-message-list"))}if(!i)return{found:!1};let l=i.querySelectorAll("li.msg-s-message-list__event").length;return i.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(i.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await C(800),r.msgCount===o){if(n++,n>=3)break}else n=0;o=r.msgCount}}async function le(e,{scrollUp:t=!0}={}){t&&await qo(e);let o=await e.evaluate(()=>{let n=[],s="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let f=document.querySelector(".msg-overlay-conversation-bubble");f&&(r=f.querySelector(".msg-s-message-list-container")||f.querySelector(".msg-s-message-list"))}if(!r)return n;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let f=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");f&&(i=f.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(f){let p=f.getAttribute("data-event-urn");if(!p)return null;let m=p.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!m)return null;try{let d=atob(m[1]).match(/^(\d{13})/);if(!d)return null;let u=Number(d[1]);if(u>14200704e5&&u<20512224e5)return u}catch{}return null}let c="";function a(f,p,m){let h=l(f),u=f.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=f.querySelector(".msg-s-event-listitem__message-bubble");if(!g)return null;let y=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let w=h?new Date(h).toISOString():m?`${m} ${u}`.trim():u;return{sender:p,text:y,time:w}}for(let f of i){let p=f.querySelector("time.msg-s-message-list__time-heading");p&&(c=p.textContent?.trim()||c);let m=f.querySelectorAll(".msg-s-message-group");if(m.length>0)for(let h of m){let d=h.querySelector(".msg-s-message-group__name");d&&(s=d.textContent?.trim()||s);let u=s||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let w=a(y,u,c);w&&n.push(w)}}else{let h=f.querySelectorAll(".msg-s-event-listitem");for(let d of h){let u=d.querySelector(".msg-s-message-group__name");u&&(s=u.textContent?.trim()||s);let y=a(d,s||"Unknown",c);y&&n.push(y)}}}if(n.length===0){let f=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let p of f){let m=p.textContent?.trim();m&&n.push({sender:"",text:m,time:""})}}return n});for(let n of o)(!n.time||!/^\d{4}-\d{2}-\d{2}T/.test(n.time))&&(n.time=Re(n.time)||n.time);return o}function ie(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Se(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let o=m=>ie(m.sender)+"||"+ie(m.text).replace(/\s+/g,""),n=new Set(t.map(o)),s=new Set(e.map(o)),r=e.filter(m=>z.has(m.status)?!1:!n.has(o(m))),i=t.filter(m=>!s.has(o(m))),l=t.filter(m=>s.has(o(m))),c=e.filter(m=>z.has(m.status)),a=[...r,...l,...i],f=[];for(let m of a){let h=ie(m.text),d=ie(m.sender),u=!1;for(let g=0;g<f.length;g++){let y=f[g];if(ie(y.sender)!==d)continue;let w=ie(y.text);if(h.length>w.length&&h.endsWith(w)){u=!0;break}if(w.length>h.length&&w.endsWith(h)){f[g]=m,u=!0;break}}u||f.push(m)}return[...f,...c]}async function ve(e,t){let o=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let c of l)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let p=c.getBoundingClientRect();if(p.height>0)return{x:p.x+p.width/2,y:p.y+p.height/2}}return null},t);if(o){await e.mouse.click(o.x,o.y),await C(3e3);let i=await Ue(e,t);if(i.verified)return i}let n=mt(t),s=n!==t?[t,n]:[t];for(let i of s)if(await Nt(e,i,t)){let c=await Ue(e,t);if(c.verified)return c}let r=gt(n);if(r!==n&&r.length>0&&await Nt(e,r,t,{requireUnique:!0})){let l=await Ue(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Nt(e,t,o,n={}){let{requireUnique:s=!1}=n,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await C(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await C(300),await r.type(t,{delay:30}),await C(500),await e.keyboard.press("Enter"),await C(3500);let i=await e.evaluate((l,c)=>{let a=l.split(" ")[0].toLowerCase(),f=l.toLowerCase(),p=document.querySelectorAll(".msg-conversation-listitem"),m=[],h=[];for(let u of p){let y=u.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",w=y.toLowerCase();if(w.includes(a)){let v=u.getBoundingClientRect();if(v.height>0){let $=y.includes(",")||/\d+ other/.test(y),b=w===f?3:w.includes(f)?2:1,_={text:y,isGroup:$,score:b,x:v.x+v.width/2,y:v.y+v.height/2};$?h.push(_):m.push(_)}}}m.sort((u,g)=>g.score-u.score);let d=[...m,...h];return c&&d.length!==1?null:m[0]||h[0]||null},o,s);return i?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function Lt(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await C(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await C(1e3))}import"dotenv/config";import*as S from"fs";import*as ze from"os";import*as D from"path";import{fileURLToPath as bn}from"url";var Je={};pe(Je,{NAME:()=>Jo,VERSION:()=>Wo,up:()=>Yo});import*as U from"fs";import*as be from"path";var Wo=1,Jo="normalize-jobs-and-questions",Ho=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Vo=50;function qe(e){return U.existsSync(e)?JSON.parse(U.readFileSync(e,"utf-8")):null}function We(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{U.writeFileSync(n,o)}catch(s){try{U.unlinkSync(n)}catch{}throw s}try{U.renameSync(n,e)}catch(s){try{U.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Yo(e,t){let o=be.join(e,"jobs.json"),n=be.join(t,"scouted-jobs.json"),s=be.join(e,"application-questions.json"),r=qe(o)||{},i=qe(n)||{},l=0,c=[];for(let f of Object.keys(r)){if(!i[f])continue;let p=i[f],m=r[f];for(let h of Ho)p[h]!=null&&m[h]==null&&(m[h]=p[h]);c.push(f),l++}l>0?(We(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=qe(s);if(a&&Array.isArray(a.applications)){let f={},p=0;for(let m of a.applications){let h=m.jobId||"unknown";f[h]||(f[h]={applications:[]});let d=(m.questions||[]).map(u=>{let g={type:u.type||"input",question:u.question||"",answer:u.answer||""};return u.options&&(u.options.length<=Vo?g.options=u.options:(g.optionsOmitted=!0,p++)),u.page&&(g.page=u.page),u.wasPreFilled&&(g.wasPreFilled=!0),u.wasRetry&&(g.wasRetry=!0),g});f[h].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||d.length,questions:d})}We(s,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];We(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var He={};pe(He,{NAME:()=>zo,VERSION:()=>Go,up:()=>Xo});import*as B from"fs";import*as Ut from"path";var Go=2,zo="reset-unread-flags";function Ko(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function Qo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{B.writeFileSync(n,o)}catch(s){try{B.unlinkSync(n)}catch{}throw s}try{B.renameSync(n,e)}catch(s){try{B.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Xo(e){let t=Ut.join(e,"conversations.json"),o=Ko(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Qo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ve={};pe(Ve,{NAME:()=>en,VERSION:()=>Zo,up:()=>rn});import*as q from"fs";import*as Bt from"path";var Zo=3,en="recompute-last-message-by",tn=new Set(["draft","confirmed","rejected","needs_review"]);function on(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function nn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{q.writeFileSync(n,o)}catch(s){try{q.unlinkSync(n)}catch{}throw s}try{q.renameSync(n,e)}catch(s){try{q.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function sn(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!tn.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function rn(e){let t=Bt.join(e,"conversations.json"),o=on(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let l of Object.keys(o)){let c=o[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let a=Array.isArray(c.messages)?c.messages:[],f=sn(a,n),p=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=p,s++}if(s===0){console.log(" No conversations to recompute.");return}nn(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ye={};pe(Ye,{NAME:()=>cn,VERSION:()=>ln,up:()=>dn});import*as W from"fs";import*as qt from"path";var ln=4,cn="split-connection-timestamps",an=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function un(e){if(!W.existsSync(e))return null;let t=W.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function fn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{W.writeFileSync(n,o)}catch(s){try{W.unlinkSync(n)}catch{}throw s}try{W.renameSync(n,e)}catch(s){try{W.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function dn(e){let t=qt.join(e,"people.json"),o=un(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,an.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}fn(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as P from"path";import{fileURLToPath as pn}from"url";var mn=pn(import.meta.url),gn=P.dirname(P.dirname(mn)),de=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"market-research"):P.join(gn,"market-research"),Ys=P.join(de,"scouted-jobs.json"),Gs=P.join(de,"discovered-people.json"),zs=P.join(de,"visit-log.json"),Ks=P.join(de,"companies.json"),Qs=P.join(de,"job-decisions.json");function Wt(){hn=null,yn=null,wn=null,Sn=null,vn=null}var hn=null;var yn=null;var wn=null;var Sn=null;var vn=null;var $n=bn(import.meta.url),kn=D.dirname($n),An=D.dirname(D.dirname(kn));function En(e){return e&&(e==="~"?ze.homedir():e.startsWith("~/")||e.startsWith("~\\")?D.join(ze.homedir(),e.slice(2)):e)}var J=process.env.DATA_DIR?D.resolve(En(process.env.DATA_DIR)):An,ee=D.join(J,"collected-profiles"),te=D.join(J,"market-research"),j=D.join(J,".schema-version"),Jt=[D.join(ee,".schema-version"),D.join(te,".schema-version")],Q=4,G=[{version:1,module:Je},{version:2,module:He},{version:3,module:Ve},{version:4,module:Ye}];(function(){G.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of G){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=G.length?G[G.length-1].version:0;if(o!==Q)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${Q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<G.length;n++){let s=n+1;if(G[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${G[n].version}`)}})();function Gt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
10
|
+
`)}`;try{await $t.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var _o=Ro(import.meta.url),Io=K.dirname(K.dirname(_o)),je=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"collected-profiles"):K.join(Io,"collected-profiles"),Me=K.join(je,"run-log.json");function To(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";L.writeFileSync(n,o);for(let s=0;s<3;s++)try{L.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function At(){try{if(!L.existsSync(Me))return{runs:[]};let e=JSON.parse(L.readFileSync(Me,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Et(e){L.existsSync(je)||L.mkdirSync(je,{recursive:!0});try{To(Me,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ct(e,t="default"){let o=At();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),Et(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Pe(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=At(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,s=c.duration)}Et(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";kt({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import Lo from"puppeteer";import{addExtra as Uo}from"puppeteer-extra";import Bo from"puppeteer-extra-plugin-stealth";import Fe from"fs";import Oo from"path";var No={headless:!1,defaultViewport:null,protocolTimeout:3e5},ue=new Set,xt=!1;async function we(){let e=[...ue].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ue.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function jo(){if(xt)return;xt=!0;let e=t=>async()=>{await we(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await we(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await we(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await we(),process.exit(0))}),process.on("exit",()=>{for(let t of ue)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Le(e){return Oo.join(e,".ilml-browser-session.json")}function It(e,t={}){try{Fe.writeFileSync(Le(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Mo(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();It(e,o?{wsEndpoint:o}:{})}catch{}}function Po(e){let t=Tt(e);t&&t.ownerPid===process.pid&&ae(e)}function ae(e){try{Fe.rmSync(Le(e),{force:!0})}catch{}}function Tt(e){try{return JSON.parse(Fe.readFileSync(Le(e),"utf-8"))}catch{return null}}function Dt(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Rt(e,t,o){let n,s=new Promise(i=>{n=setTimeout(()=>i(o),t)}),r=Promise.resolve(e).then(i=>(clearTimeout(n),i),i=>{throw clearTimeout(n),i});return Promise.race([r,s])}async function _t(e,t,{probeTimeoutMs:o=4e3}={}){let n=Tt(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&Dt(n.ownerPid)?"live":(ae(t),"free");let s=Symbol("timeout"),r=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Rt(r,o,s);if(i===s)return r.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return ae(t),"free";if(Dt(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Rt(i.close().then(()=>!0).catch(()=>!1),o,!1))return ae(t),"free";try{i.disconnect()}catch{}return"live"}function Fo(e,t){e&&(jo(),ue.add(e),e.on("disconnected",()=>{ue.delete(e),t&&ae(t)}))}async function Ot(e,t={}){let o=ct(),n={...No,...t,userDataDir:o},s=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await _t(e,o)==="live")throw new Error(s);It(o);let r;try{r=await e.launch(n)}catch{if(await _t(e,o)==="live")throw new Error(s);dt(o);try{r=await e.launch(n)}catch(l){throw Po(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return Fo(r,o),Mo(o,r),{browser:r,profileDir:o,needsSeed:ut(o)}}async function Nt(e,t){if(!t||!t.needsSeed)return!1;if(!it())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(...rt()),ft(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Pt=Uo(Lo);Pt.use(Bo());async function Ft(){let{browser:e,profileDir:t,needsSeed:o}=await Ot(Pt),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Nt(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}async function Be(e){await ge(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await A(3e3)),console.log(" Inbox loaded.")}async function Lt(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll(".msg-conversation-listitem"),n=[];for(let s of o){let i=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let c=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(c)||/^\s*Promoted\b/i.test(c))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",p=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,m,h;if(c.startsWith("You:"))m="me",h=c.slice(4).trim();else{let f=i.split(" ")[0];if(c.startsWith(i+":")||c.startsWith(f+":")){m="them";let g=c.indexOf(":");h=c.slice(g+1).trim()}else m="them",h=c}let d=s.getBoundingClientRect();n.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:p,lastMessageBy:m,x:d.x+d.width/2,y:d.y+d.height/2})}return n});for(let o of t)o.lastMessageTime=_e(o.lastMessageTime)||o.lastMessageTime;return t}async function Ut(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let n of t){let s=document.querySelector(n);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let o=document.querySelector(".msg-conversation-listitem");if(o){let n=o.parentElement;for(;n;){if(n.scrollHeight>n.clientHeight+10)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};n=n.parentElement}}return null})}async function qo(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,o=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of o){let r=document.querySelector(s);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let n=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of n){let r=s.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function jt(e,t){let o=await qo(e);if(!o)return{match:!1,headerName:null};let n=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=o.toLowerCase();return{match:r.includes(n)||s.some(l=>r.includes(l)),headerName:o}}async function Ue(e,t){let o=t.split(" ")[0],n=8e3,s=500,r=0;for(;r<n;){let{match:c,headerName:a}=await jt(e,t);if(c)return await A(500),{verified:!0,headerName:a};let u=await e.evaluate(()=>{let p=document.querySelectorAll(".msg-s-message-group__name"),m=Array.from(p).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:m,msgCount:h}});if(u.msgCount>0&&u.allSenders.some(m=>m.toLowerCase().includes(o.toLowerCase())))return await A(300),{verified:!0,headerName:o};await A(s),r+=s}let{match:i,headerName:l}=await jt(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function Wo(e){let o=0,n=0;for(let s=0;s<50;s++){let r=await e.evaluate(()=>{let i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let a=document.querySelector(".msg-overlay-conversation-bubble");a&&(i=a.querySelector(".msg-s-message-list-container")||a.querySelector(".msg-s-message-list"))}if(!i)return{found:!1};let l=i.querySelectorAll("li.msg-s-message-list__event").length;return i.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(i.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await A(800),r.msgCount===o){if(n++,n>=3)break}else n=0;o=r.msgCount}}async function ie(e,{scrollUp:t=!0}={}){t&&await Wo(e);let o=await e.evaluate(()=>{let n=[],s="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(r=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!r)return n;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(i=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let p=u.getAttribute("data-event-urn");if(!p)return null;let m=p.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!m)return null;try{let d=atob(m[1]).match(/^(\d{13})/);if(!d)return null;let f=Number(d[1]);if(f>14200704e5&&f<20512224e5)return f}catch{}return null}let c="";function a(u,p,m){let h=l(u),f=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=u.querySelector(".msg-s-event-listitem__message-bubble");if(!g)return null;let w=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let y=h?new Date(h).toISOString():m?`${m} ${f}`.trim():f;return{sender:p,text:w,time:y}}for(let u of i){let p=u.querySelector("time.msg-s-message-list__time-heading");p&&(c=p.textContent?.trim()||c);let m=u.querySelectorAll(".msg-s-message-group");if(m.length>0)for(let h of m){let d=h.querySelector(".msg-s-message-group__name");d&&(s=d.textContent?.trim()||s);let f=s||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let w of g){let y=a(w,f,c);y&&n.push(y)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let d of h){let f=d.querySelector(".msg-s-message-group__name");f&&(s=f.textContent?.trim()||s);let w=a(d,s||"Unknown",c);w&&n.push(w)}}}if(n.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let p of u){let m=p.textContent?.trim();m&&n.push({sender:"",text:m,time:""})}}return n});for(let n of o)(!n.time||!/^\d{4}-\d{2}-\d{2}T/.test(n.time))&&(n.time=_e(n.time)||n.time);return o}function re(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Se(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let o=m=>re(m.sender)+"||"+re(m.text).replace(/\s+/g,""),n=new Set(t.map(o)),s=new Set(e.map(o)),r=e.filter(m=>z.has(m.status)?!1:!n.has(o(m))),i=t.filter(m=>!s.has(o(m))),l=t.filter(m=>s.has(o(m))),c=e.filter(m=>z.has(m.status)),a=[...r,...l,...i],u=[];for(let m of a){let h=re(m.text),d=re(m.sender),f=!1;for(let g=0;g<u.length;g++){let w=u[g];if(re(w.sender)!==d)continue;let y=re(w.text);if(h.length>y.length&&h.endsWith(y)){f=!0;break}if(y.length>h.length&&y.endsWith(h)){u[g]=m,f=!0;break}}f||u.push(m)}return[...u,...c]}async function ve(e,t){let o=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let c of l)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let p=c.getBoundingClientRect();if(p.height>0)return{x:p.x+p.width/2,y:p.y+p.height/2}}return null},t);if(o){await e.mouse.click(o.x,o.y),await A(3e3);let i=await Ue(e,t);if(i.verified)return i}let n=ht(t),s=n!==t?[t,n]:[t];for(let i of s)if(await Mt(e,i,t)){let c=await Ue(e,t);if(c.verified)return c}let r=yt(n);if(r!==n&&r.length>0&&await Mt(e,r,t,{requireUnique:!0})){let l=await Ue(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Mt(e,t,o,n={}){let{requireUnique:s=!1}=n,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await A(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await A(300),await r.type(t,{delay:30}),await A(500),await e.keyboard.press("Enter"),await A(3500);let i=await e.evaluate((l,c)=>{let a=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),p=document.querySelectorAll(".msg-conversation-listitem"),m=[],h=[];for(let f of p){let w=f.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",y=w.toLowerCase();if(y.includes(a)){let $=f.getBoundingClientRect();if($.height>0){let S=w.includes(",")||/\d+ other/.test(w),R=y===u?3:y.includes(u)?2:1,D={text:w,isGroup:S,score:R,x:$.x+$.width/2,y:$.y+$.height/2};S?h.push(D):m.push(D)}}}m.sort((f,g)=>g.score-f.score);let d=[...m,...h];return c&&d.length!==1?null:m[0]||h[0]||null},o,s);return i?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function Bt(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await A(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await A(1e3))}import"dotenv/config";import*as v from"fs";import*as ze from"os";import*as x from"path";import{fileURLToPath as $n}from"url";var Je={};pe(Je,{NAME:()=>Ho,VERSION:()=>Jo,up:()=>Go});import*as U from"fs";import*as be from"path";var Jo=1,Ho="normalize-jobs-and-questions",Vo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Yo=50;function qe(e){return U.existsSync(e)?JSON.parse(U.readFileSync(e,"utf-8")):null}function We(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{U.writeFileSync(n,o)}catch(s){try{U.unlinkSync(n)}catch{}throw s}try{U.renameSync(n,e)}catch(s){try{U.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Go(e,t){let o=be.join(e,"jobs.json"),n=be.join(t,"scouted-jobs.json"),s=be.join(e,"application-questions.json"),r=qe(o)||{},i=qe(n)||{},l=0,c=[];for(let u of Object.keys(r)){if(!i[u])continue;let p=i[u],m=r[u];for(let h of Vo)p[h]!=null&&m[h]==null&&(m[h]=p[h]);c.push(u),l++}l>0?(We(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=qe(s);if(a&&Array.isArray(a.applications)){let u={},p=0;for(let m of a.applications){let h=m.jobId||"unknown";u[h]||(u[h]={applications:[]});let d=(m.questions||[]).map(f=>{let g={type:f.type||"input",question:f.question||"",answer:f.answer||""};return f.options&&(f.options.length<=Yo?g.options=f.options:(g.optionsOmitted=!0,p++)),f.page&&(g.page=f.page),f.wasPreFilled&&(g.wasPreFilled=!0),f.wasRetry&&(g.wasRetry=!0),g});u[h].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||d.length,questions:d})}We(s,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let u of c)delete i[u];We(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var He={};pe(He,{NAME:()=>Ko,VERSION:()=>zo,up:()=>Zo});import*as B from"fs";import*as qt from"path";var zo=2,Ko="reset-unread-flags";function Qo(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function Xo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{B.writeFileSync(n,o)}catch(s){try{B.unlinkSync(n)}catch{}throw s}try{B.renameSync(n,e)}catch(s){try{B.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Zo(e){let t=qt.join(e,"conversations.json"),o=Qo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Xo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ve={};pe(Ve,{NAME:()=>tn,VERSION:()=>en,up:()=>ln});import*as q from"fs";import*as Wt from"path";var en=3,tn="recompute-last-message-by",on=new Set(["draft","confirmed","rejected","needs_review"]);function nn(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function sn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{q.writeFileSync(n,o)}catch(s){try{q.unlinkSync(n)}catch{}throw s}try{q.renameSync(n,e)}catch(s){try{q.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function rn(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!on.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ln(e){let t=Wt.join(e,"conversations.json"),o=nn(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let l of Object.keys(o)){let c=o[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let a=Array.isArray(c.messages)?c.messages:[],u=rn(a,n),p=u==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==u&&i++,c.lastMessageBy=u,c.conversationStatus=p,s++}if(s===0){console.log(" No conversations to recompute.");return}sn(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ye={};pe(Ye,{NAME:()=>an,VERSION:()=>cn,up:()=>pn});import*as W from"fs";import*as Jt from"path";var cn=4,an="split-connection-timestamps",un=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function fn(e){if(!W.existsSync(e))return null;let t=W.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{W.writeFileSync(n,o)}catch(s){try{W.unlinkSync(n)}catch{}throw s}try{W.renameSync(n,e)}catch(s){try{W.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function pn(e){let t=Jt.join(e,"people.json"),o=fn(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,un.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}dn(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as P from"path";import{fileURLToPath as mn}from"url";var gn=mn(import.meta.url),hn=P.dirname(P.dirname(gn)),fe=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"market-research"):P.join(hn,"market-research"),Gs=P.join(fe,"scouted-jobs.json"),zs=P.join(fe,"discovered-people.json"),Ks=P.join(fe,"visit-log.json"),Qs=P.join(fe,"companies.json"),Xs=P.join(fe,"job-decisions.json");function Ht(){yn=null,wn=null,Sn=null,vn=null,bn=null}var yn=null;var wn=null;var Sn=null;var vn=null;var bn=null;var kn=$n(import.meta.url),An=x.dirname(kn),En=x.dirname(x.dirname(An));function Cn(e){return e&&(e==="~"?ze.homedir():e.startsWith("~/")||e.startsWith("~\\")?x.join(ze.homedir(),e.slice(2)):e)}var J=process.env.DATA_DIR?x.resolve(Cn(process.env.DATA_DIR)):En,ee=x.join(J,"collected-profiles"),te=x.join(J,"market-research"),j=x.join(J,".schema-version"),Vt=[x.join(ee,".schema-version"),x.join(te,".schema-version")],Q=4,G=[{version:1,module:Je},{version:2,module:He},{version:3,module:Ve},{version:4,module:Ye}];(function(){G.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of G){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=G.length?G[G.length-1].version:0;if(o!==Q)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${Q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<G.length;n++){let s=n+1;if(G[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${G[n].version}`)}})();function Kt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
11
11
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
12
|
-
`),process.exit(1));try{
|
|
12
|
+
`),process.exit(1));try{v.mkdirSync(J,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
13
13
|
[FATAL] Cannot create DATA_DIR (${J}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
14
|
-
`),process.exit(1))}let e;try{e=
|
|
14
|
+
`),process.exit(1))}let e;try{e=v.statSync(J)}catch(t){console.error(`
|
|
15
15
|
[FATAL] DATA_DIR (${J}) is not accessible: ${t.message}
|
|
16
16
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
17
17
|
[FATAL] DATA_DIR (${J}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
18
|
-
`),process.exit(1));for(let t of[ee,te]){let o;try{o=
|
|
18
|
+
`),process.exit(1));for(let t of[ee,te]){let o;try{o=v.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
|
|
19
19
|
[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 Z=
|
|
20
|
+
`),process.exit(1))}}var Z=x.join(J,".migration-lock");function xn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return v.writeFileSync(Z,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(v.readFileSync(Z,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}n&&r<s&&(console.error(`
|
|
21
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: ${Z}
|
|
22
22
|
`),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)),n&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Z+".tmp";try{return
|
|
23
|
+
`),process.exit(1)),n&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=Z+".tmp";try{return v.writeFileSync(o,e),v.renameSync(o,Z),!0}catch(n){try{v.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function Ke(){try{if(JSON.parse(v.readFileSync(Z,"utf-8")).pid!==process.pid)return;v.unlinkSync(Z)}catch{}}var Yt=!1;function Dn(){if(Yt)return;Yt=!0;let e=()=>{try{Ke()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Rn(){if(v.existsSync(j))return;let e=[],t=[];for(let r of Vt)if(v.existsSync(r))try{e.push({file:r,schema:$e(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
|
|
24
24
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
|
|
25
25
|
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
26
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
|
|
27
27
|
[FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.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.
|
|
28
|
-
`),process.exit(1)}let n=e[0].schema,s=j+".tmp";try{
|
|
28
|
+
`),process.exit(1)}let n=e[0].schema,s=j+".tmp";try{v.writeFileSync(s,JSON.stringify(n,null,2)),v.renameSync(s,j)}catch(r){try{v.unlinkSync(s)}catch{}throw r}for(let r of Vt)if(v.existsSync(r))try{v.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${j}`)}function _n(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 $e(e){let t=v.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Gt(){if(Rn(),!v.existsSync(j))return{version:0,migrations:[]};let e;try{e=$e(j)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
29
29
|
[FATAL] ${j} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
30
30
|
`),process.exit(1)}let t=_n(e);return t===null&&(console.error(`
|
|
31
31
|
[FATAL] ${j} 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.
|
|
32
|
-
`),process.exit(1)),t}function
|
|
32
|
+
`),process.exit(1)),t}function Qt(e){try{v.chmodSync(e,384)}catch{}}function In(e){if(Kt(),v.existsSync(j))try{if(v.lstatSync(j).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${j}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=j+".tmp";try{v.writeFileSync(t,JSON.stringify(e,null,2)),Qt(t),v.renameSync(t,j)}catch(o){try{v.unlinkSync(t)}catch{}throw o}}function zt(e,t){if(!v.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=v.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return v.statSync(x.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let c=x.join(e,l),a=x.join(e,l+o);if(v.existsSync(a)){r++;continue}try{Zt(c,a),s++}catch(u){i.push({file:l,err:u.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${x.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${x.basename(e)}/ (${o})${l}`)}}var Ge=!1;async function Xt(){if(Ge)return;Kt(),Mn();let t=Gt().version;if(t===Q){Ge=!0;return}Dn(),xn(),process.on("exit",Ke),t>Q&&(console.error(`
|
|
33
33
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Q}.`),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
34
|
`),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${Q}.
|
|
35
35
|
`),process.exit(1)),console.log(`
|
|
36
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${Q}`);let o=
|
|
36
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${Q}`);let o=Pn();if(!o.ok){console.error(`
|
|
37
37
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
38
38
|
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
39
|
`),process.exit(1)}let n=G.filter(s=>s.version>t);for(let s of n){console.log(`
|
|
40
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{
|
|
40
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{zt(ee,s.version),zt(te,s.version)}catch(c){console.error(`
|
|
41
41
|
[FATAL] Pre-migration backup failed for ${r}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
42
42
|
`),process.exit(1)}let l=s.module;try{await l.up(ee,te)}catch(c){console.error(`
|
|
43
|
-
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=
|
|
43
|
+
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=Fn(i);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
44
44
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
45
45
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
46
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:s.version,name:l.NAME||r,appliedAt:c},
|
|
46
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:s.version,name:l.NAME||r,appliedAt:c},u=Gt();u.version=s.version,u.migratedAt=c,u.migrations=u.migrations||[],u.migrations.push(a),In(u)}catch(c){console.error(`
|
|
47
47
|
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
48
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{
|
|
48
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{St()}catch{}try{Ht()}catch{}Ge=!0,Ke(),console.log(`
|
|
49
49
|
\u2713 Schema is now at v${Q}
|
|
50
|
-
`)}var
|
|
50
|
+
`)}var Tn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function On(e){let t=e.toLowerCase();return Tn.some(o=>o.test(t))}var Nn=6e4;function jn(){let e=Date.now(),t=[];for(let o of[J,ee,te]){if(!v.existsSync(o))continue;let n;try{n=v.readdirSync(o)}catch{continue}for(let s of n){if(!On(s))continue;let r=x.join(o,s);try{let i=v.statSync(r);if(!i.isFile()||e-i.mtimeMs<Nn)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function Mn({verbose:e=!1}={}){let t=jn();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{v.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${x.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Pn(){let e=[];for(let t of[ee,te]){if(!v.existsSync(t))continue;let o=v.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=x.join(t,n);try{$e(s)}catch(r){e.push({dir:x.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Fn(e){let t=[],o=[];for(let r of[ee,te]){if(!v.existsSync(r))continue;let i=v.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let c=x.join(r,l),a=l.slice(0,-e.length),u=x.join(r,a);try{a.toLowerCase().endsWith(".json")?$e(c):v.accessSync(c,v.constants.R_OK),t.push({backupPath:c,originalPath:u,fileName:l,dir:r})}catch(p){o.push(`${x.basename(r)}/${l}: ${p.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:c}of t)try{Zt(r,i),n++}catch(a){s.push(`${x.basename(c)}/${l}: ${a.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function Zt(e,t){let o=t+".tmp";try{v.copyFileSync(e,o),Qt(o)}catch(n){try{v.unlinkSync(o)}catch{}throw n}try{v.renameSync(o,t)}catch(n){try{v.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${t} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=n.code,s}throw n}}await Xt();var Ln=ne.toLowerCase().split(/\s+/).filter(e=>e.length>1);function ke(e){if(!e)return!1;if(e===ne)return!0;let t=e.toLowerCase();return Ln.some(o=>t.includes(o))}function Xe(e){return(e.messages||[]).find(t=>ce.has(t.status))}function M(e){return(e.messages||[]).find(t=>z.has(t.status))}function Ze(e){return Xe(e)?.text||null}function et(e){return(e.messages||[]).some(t=>ce.has(t.status))}function Un(e){return(e.messages||[]).some(t=>z.has(t.status))}function Bn(e,t){let o=M(e);o&&(o.text=t)}function Ae(e,t){if(!e||typeof t!="string")return{ok:!0};let o=t.match(/^\s*(?:hi|hello|hey)[,\s\-—]+([A-Z][A-Za-z'\-]*)/i);if(!o)return{ok:!0};let n=o[1],s=e.split(/[\s,]+/)[0],r=n.toLowerCase(),i=s.toLowerCase();return i.startsWith(r)||r.startsWith(i)?{ok:!0}:{ok:!1,greeted:n,convFirstWord:s,reason:`message opens with "Hi ${n}" but conv key's first word is "${s}"`}}function Ee(e,t){console.error(`
|
|
51
51
|
\u2717 ABORT for "${e}": ${t.reason}.`),console.error(" This is almost certainly a mis-routed message (e.g. the body refers to a forwarded contact, not the conversation owner)."),console.error(` Fix the recipient name or the salutation in the body. Override with skipSalutationCheck=true if you really mean to address a different person.
|
|
52
|
-
`)}function
|
|
52
|
+
`)}function qn(){let e={list:!1,full:!1,read:null,send:null,sendBatch:null,pushDrafts:!1,reviewDrafts:!1,max:1/0,dryRun:!1,verbose:!1},t=process.argv.slice(2);for(let o=0;o<t.length;o++){let n=t[o];if(n==="--list")e.list=!0;else if(n==="--full")e.full=!0;else if(n==="--dry-run")e.dryRun=!0;else if(n==="--verbose")e.verbose=!0;else if(n.startsWith("--max="))e.max=parseInt(n.split("=")[1],10);else if(n==="--read")e.read=t[++o]||null;else if(n==="--send"){let s=t[++o],r=t[++o]||"",i=[];for(;o+1<t.length&&!t[o+1].startsWith("--");)i.push(t[++o]);if(i.length>0&&(console.error(` \u2717 --send received split/ambiguous arguments: ${[s,r,...i].map(l=>`"${l}"`).join(" ")}`),console.error(" A name or message containing spaces can get broken up on the way to the plugin,"),console.error(" which would send a garbled fragment. Pass the payload as a file instead:"),console.error(' ilml linkedin messages --send-batch @file.json (file: [{ "name": "...", "text": "..." }])'),console.error(" or draft then push: --draft-batch @file.json \u2192 --push-drafts"),process.exit(1)),r.startsWith("@")){let l=r.slice(1);try{r=oe.readFileSync(l,"utf-8").trim()}catch{console.error(`Cannot read message file: ${l}`),process.exit(1)}}e.send={target:s,text:r}}else if(n==="--draft"){let s=t[++o],r=t[++o]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=oe.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.draft={target:s,text:r}}else if(n==="--push-drafts")e.pushDrafts=!0;else if(n==="--review-drafts")e.reviewDrafts=!0;else if(n==="--follow-up"){let s=t[++o],r=t[++o]||"",i=t[++o]||null;e.followUp={target:s,note:r,date:i}}else if(n==="--follow-up-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.followUpBatch=JSON.parse(oe.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read follow-up batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(n==="--clear-follow-up")e.clearFollowUp=t[++o]||null;else if(n==="--review")e.review=t[++o]||null;else if(n==="--review-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.reviewBatch=JSON.parse(oe.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read review batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(n==="--draft-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.draftBatch=JSON.parse(oe.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read draft batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(n==="--send-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.sendBatch=JSON.parse(oe.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}}return e}function Wn(){let e=O(),t=Object.entries(e),o=t.length;if(o===0){console.log(`
|
|
53
53
|
No conversations synced yet. Run: npm run messages
|
|
54
|
-
`);return}let n={};for(let[,d]of t){let
|
|
54
|
+
`);return}let n={};for(let[,d]of t){let f=d.conversationStatus||"(none)";n[f]=(n[f]||0)+1}let s=t.filter(([,d])=>d.conversationStatus==="unanswered_by_us").sort((d,f)=>{let g=d[1].lastSynced||"";return(f[1].lastSynced||"").localeCompare(g)});console.log(`
|
|
55
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`),console.log(` Conversations: ${o} total`),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"),console.log(`
|
|
56
|
-
By status:`);for(let[d,
|
|
57
|
-
By category (${i} categorized):`);for(let[d,
|
|
56
|
+
By status:`);for(let[d,f]of Object.entries(n).sort((g,w)=>w[1]-g[1]))console.log(` ${d.padEnd(25)} ${f}`);let r={};for(let[,d]of t){let f=d.category||"(none)";r[f]=(r[f]||0)+1}let i=t.filter(([,d])=>d.category).length;if(i>0){console.log(`
|
|
57
|
+
By category (${i} categorized):`);for(let[d,f]of Object.entries(r).sort((g,w)=>w[1]-g[1]))console.log(` ${d.padEnd(25)} ${f}`)}let l=t.filter(([,d])=>et(d));if(l.length>0){let d=l.filter(([,S])=>S.conversationStatus==="unanswered_by_us"),f=l.filter(([,S])=>S.conversationStatus==="awaiting_reply"),g=l.filter(([,S])=>S.conversationStatus!=="unanswered_by_us"&&S.conversationStatus!=="awaiting_reply");console.log(`
|
|
58
58
|
\u{1F4DD} DRAFTS READY TO PUSH \u2014 ${l.length} total:
|
|
59
|
-
`);let
|
|
59
|
+
`);let w=([S,R])=>{let D=R.priority?` [${R.priority.toUpperCase()}]`:"",k=M(R),E=k?.status||b.DRAFT,C={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[E]||"",I=k?.text||"";console.log(` ${C} ${S}${D}`),console.log(` "${I.slice(0,80)}${I.length>80?"...":""}"`)};d.length>0&&(console.log(` \u2500\u2500 Replies (they wrote last) \u2014 ${d.length}:`),d.forEach(w),console.log()),f.length>0&&(console.log(` \u2500\u2500 Re-engagement (we wrote last, following up) \u2014 ${f.length}:`),f.forEach(w),console.log()),g.length>0&&(console.log(` \u2500\u2500 Other \u2014 ${g.length}:`),g.forEach(w),console.log());let y=l.filter(([,S])=>M(S)?.status===b.CONFIRMED).length,$=l.filter(([,S])=>{let R=M(S)?.status;return R===b.DRAFT||R===b.NEEDS_REVIEW}).length;console.log(` ${y} confirmed, ${$} pending review`),$>0&&console.log(" Review: npm run messages -- --review-drafts"),y>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let c=new Date,a=t.filter(([,d])=>d.priority&&d.conversationStatus==="awaiting_reply").filter(([,d])=>d.followUpAfter?new Date(d.followUpAfter)<=c:!0).sort((d,f)=>{let g={high:0,medium:1,low:2}[d[1].priority]??3,w={high:0,medium:1,low:2}[f[1].priority]??3;return g-w});if(a.length>0){console.log(`
|
|
60
60
|
\u{1F514} FOLLOW-UP NEEDED \u2014 ${a.length} priority contacts waiting:
|
|
61
|
-
`);for(let[d,
|
|
62
|
-
`);for(let[d,
|
|
63
|
-
All caught up \u2014 no unanswered messages.`);let
|
|
61
|
+
`);for(let[d,f]of a){let g=f.priority.toUpperCase(),w=f.lastSynced?Math.floor((c-new Date(f.lastSynced))/864e5):"?",y=f.lastMessagePreview?.slice(0,50)||"";console.log(` [${g}] ${d} \u2014 ${w}d ago`),f.notes&&console.log(` \u{1F4CC} ${f.notes}`),console.log(` ${y}`),console.log()}}if(s.length>0){console.log(`\u26A1 ACTION NEEDED \u2014 ${s.length} unanswered messages:
|
|
62
|
+
`);for(let[d,f]of s){let g=et(f)?" [DRAFT READY]":"",w=f.priority?` [${f.priority.toUpperCase()}]`:f.suggestedPriority?` [${f.suggestedPriority}]`:"",y=f.category?` (${f.category})`:"",$=f.actionNeeded&&f.actionNeeded!=="none"?` \u2192 ${f.actionNeeded}`:"",S=f.lastMessageTime||"",R=(f.autoTags||[]).slice(0,4).join(", ");if(console.log(` ${d}${y}${w}${g}${$}`),f.summary)console.log(` ${f.summary}`);else{let D=f.lastMessagePreview?f.lastMessagePreview.slice(0,60)+(f.lastMessagePreview.length>60?"...":""):"";console.log(` ${S} | ${D}`)}R&&console.log(` #${R.replace(/, /g," #")}`),f.notes&&console.log(` \u{1F4CC} ${f.notes}`),f.profileUrl&&console.log(` ${f.profileUrl}`),console.log()}}else console.log(`
|
|
63
|
+
All caught up \u2014 no unanswered messages.`);let u=Y(),p=new Set(Object.keys(e)),m=new Set(Object.values(e).map(d=>d.profileUrl).filter(Boolean)),h=Object.entries(u).filter(([d,f])=>f.connectionStatus==="connected"&&f.personActionNeeded==="initiate_contact"&&!m.has(d)&&!(f.name&&p.has(f.name))).sort((d,f)=>{let g={high:0,medium:1,low:2}[d[1].personPriority]??3,w={high:0,medium:1,low:2}[f[1].personPriority]??3;return g!==w?g-w:(f[1].connectionDate||"").localeCompare(d[1].connectionDate||"")});if(h.length>0){console.log(`
|
|
64
64
|
\u2709\uFE0F NEW CONNECTIONS TO MESSAGE \u2014 ${h.length} total:
|
|
65
|
-
`);let d=15;for(let[
|
|
66
|
-
`)}console.log()}function
|
|
65
|
+
`);let d=15;for(let[f,g]of h.slice(0,d)){let w=g.personPriority?`[${g.personPriority.toUpperCase()}]`:"",y=g.title?`${g.title}${g.company?` at ${g.company}`:""}`:g.company||"";console.log(` ${w} ${g.name||"Unknown"} \u2014 ${y}`),g.personSummary&&console.log(` ${g.personSummary}`),f&&console.log(` ${f}`),console.log()}h.length>d&&console.log(` ... and ${h.length-d} more. Run: npm run today
|
|
66
|
+
`)}console.log()}function eo(e,t){return new Promise(o=>e.question(t,o))}async function Jn(){let e=O(),t=Y(),o={};for(let u of Object.values(t))u.name&&u.title&&(o[u.name]=u.title);let n={draft:0,needs_review:0,confirmed:1,rejected:2},s=Object.entries(e).filter(([,u])=>Un(u)).sort((u,p)=>{let m=n[M(u[1])?.status]??0,h=n[M(p[1])?.status]??0;if(m!==h)return m-h;let d={high:0,medium:1,low:2}[u[1].priority]??3,f={high:0,medium:1,low:2}[p[1].priority]??3;return d-f});if(s.length===0){console.log(`
|
|
67
67
|
No drafts to review.
|
|
68
|
-
`);return}let r=s.filter(([,
|
|
68
|
+
`);return}let r=s.filter(([,u])=>{let p=M(u)?.status;return p===b.DRAFT||p===b.NEEDS_REVIEW}),i=s.filter(([,u])=>M(u)?.status===b.CONFIRMED),l=s.filter(([,u])=>M(u)?.status===b.REJECTED);console.log(`
|
|
69
69
|
\u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${s.length} drafts (${r.length} pending, ${i.length} confirmed, ${l.length} rejected)
|
|
70
70
|
`),console.log(` Commands: [c]onfirm [r]eject [e]dit [s]kip [q]uit
|
|
71
|
-
`);let c=
|
|
72
|
-
${"\u2550".repeat(60)}`),console.log(` ${
|
|
73
|
-
`)),h.status=
|
|
74
|
-
Saved. ${
|
|
75
|
-
Reached --max=${n}, stopping.`);break}if(
|
|
76
|
-
${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!o&&
|
|
77
|
-
${m} pages of already-synced conversations \u2014 caught up.`);break}}else
|
|
78
|
-
`);let
|
|
79
|
-
Extracted ${
|
|
71
|
+
`);let c=oo.createInterface({input:process.stdin,output:process.stdout}),a=0;for(let u=0;u<s.length;u++){let[p,m]=s[u],h=M(m),d=h?.status||b.DRAFT,f={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[d]||"?",g={high:"\u{1F534}",medium:"\u{1F7E1}",low:"\u26AA"}[m.priority]||"",w=o[p]||"",y=m.messages||[],$=m.conversationStatus||"?";if(console.log(`
|
|
72
|
+
${"\u2550".repeat(60)}`),console.log(` ${u+1}/${s.length} ${f} ${p} ${g} ${(m.priority||"").toUpperCase()}`),w&&console.log(` ${w}`),console.log(` Status: ${$} | ${y.length} msgs synced`),m.notes&&console.log(` Notes: ${m.notes}`),console.log(`${"\u2500".repeat(60)}`),y.length>0){console.log(" Conversation:");let E=y.slice(-4);y.length>4&&console.log(` ... (${y.length-4} earlier messages)`);for(let C of E){let I=C.sender||"Unknown",de=(C.text||"").replace(/\n/g," ").substring(0,120),io=ke(I)?" \u2192":" \u2190";console.log(` ${io} [${I}] ${de}`)}}else m.lastMessagePreview&&console.log(` Preview: "${m.lastMessagePreview}"`);console.log(`${"\u2500".repeat(60)}`),console.log(" Draft:");let S=Ze(m)||"",R=S.match(/.{1,80}/g)||[S];for(let E of R)console.log(` ${E}`);console.log(`${"\u2500".repeat(60)}`);let k=(await eo(c," [c]onfirm [r]eject [e]dit [s]kip [q]uit > ")).trim().toLowerCase();if(k==="c"||k==="confirm"||k==="y"||k==="yes")h.status=b.CONFIRMED,a++,console.log(" \u2705 Confirmed");else if(k==="r"||k==="reject"||k==="n"||k==="no")h.status=b.REJECTED,a++,console.log(" \u274C Rejected");else if(k==="e"||k==="edit"){console.log(" Enter new draft text (end with empty line):");let E=[];for(;;){let C=await eo(c," ");if(C.trim()==="")break;E.push(C)}E.length>0?(Bn(m,E.join(`
|
|
73
|
+
`)),h.status=b.CONFIRMED,a++,console.log(" \u2705 Edited & Confirmed")):console.log(" (no changes)")}else if(k==="q"||k==="quit"){console.log(" Quitting review...");break}else console.log(" \u23ED Skipped")}if(c.close(),a>0){F(e);let u=Object.values(e).filter(h=>M(h)?.status===b.CONFIRMED).length,p=Object.values(e).filter(h=>M(h)?.status===b.REJECTED).length,m=Object.values(e).filter(h=>{let d=M(h)?.status;return d===b.DRAFT||d===b.NEEDS_REVIEW}).length;console.log(`
|
|
74
|
+
Saved. ${u} confirmed, ${m} pending, ${p} rejected.`),u>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function no(e){try{await Bt(e)}catch{}}async function Hn(e,t){let{full:o,max:n,verbose:s,dryRun:r}=t,i=o?"full":"incremental",l=O(),c=new Set(Object.keys(l)),a=new Map,u=0,p=0,m=3,h=0,d=3;for(;;){u++;let w=await Lt(e),y=0,$=0;for(let S of w)S.name&&(a.has(S.name)||(a.set(S.name,S),c.has(S.name)?$++:y++));if(s?console.log(` Round #${u}: ${y} new, ${$} known | Total: ${a.size}`):process.stdout.write(`\r Conversations found: ${a.size} (page #${u})`),a.size>=n){console.log(`
|
|
75
|
+
Reached --max=${n}, stopping.`);break}if(y===0&&$===0){if(h++,h>=d){console.log(`
|
|
76
|
+
${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!o&&y===0&&$>0){if(p++,p>=m){console.log(`
|
|
77
|
+
${m} pages of already-synced conversations \u2014 caught up.`);break}}else y>0&&(p=0);await Ut(e),await A(2e3)}s||process.stdout.write(`
|
|
78
|
+
`);let f=Array.from(a.values());console.log(`
|
|
79
|
+
Extracted ${f.length} conversations.`);let g=Qn(f,r);Xn(f,g,r,i)}async function Vn(e,t,o){let n=Y(),s=O(),r;if(t.startsWith("http")){let a=n[t],u=Object.entries(s).find(([,p])=>p.profileUrl===t);r=a?.name||u?.[0]}else r=t;if(!r){console.error(` Cannot find name for "${t}". Run inbox scan first.`);return}console.log(`
|
|
80
80
|
Reading conversation with: ${r}
|
|
81
|
-
`),await Be(e);let{verified:i}=await ve(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await
|
|
82
|
-
`);for(let a of l){let f=a.time?` (${a.time})`:"";console.log(` [${a.sender}]${f}`),console.log(` ${a.text}`),console.log()}}let c=r;s[c]||(s[c]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),s[c].messages=Se(s[c].messages,l),s[c].lastSynced=new Date().toISOString(),F(s),console.log(` Saved ${s[c].messages.length} messages to conversations.json ["${c}"]`)}function et(e){let t=Y(),o=e,n=null;if(e.startsWith("http")){let s=t[e];if(s?.name)o=s.name,n=e;else return null}else{let s=Object.entries(t).find(([,i])=>i.name===e);s&&(n=s[0]);let r=O();!n&&r[e]?.profileUrl&&(n=r[e].profileUrl)}return{personName:o,profileUrl:n}}async function no(e,t,o,n,s={}){console.log(" Syncing conversation thread..."),await C(1e3);let r=await le(e);console.log(` Synced ${r.length} messages from thread.`);let i=!s.conversations,l=s.conversations||O(),c=new Date().toISOString(),a=t;l[a]?(l[a].lastMessageBy="me",l[a].lastMessagePreview=n.slice(0,100),l[a].lastMessageTime=c,l[a].conversationStatus="awaiting_reply",l[a].lastSynced=c,l[a].messages=Se(l[a].messages,r)):l[a]={profileUrl:o,lastSynced:c,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:c,unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:r},o&&(l[a].profileUrl=o),i&&F(l);let f=Y(),p=o?f[o]:null;p&&(p.conversationStatus="awaiting_reply",p.lastMessageSent=c,p.lastUpdated=c,Ne(f))}async function tt(e,t,o,n,s={}){try{let{verified:r}=await ve(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await le(e,{scrollUp:!1}),c=O()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${c})`),i.length>c&&c>0){let v=i.length-c,$=i[i.length-1];return console.error(` \u2717 ABORT: ${v} new message(s) since last sync!`),console.error(` Latest: [${$.sender}] ${$.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let v=i[i.length-1],$=null;for(let b=i.length-1;b>=0;b--)if(i[b].sender!=="Unknown"&&i[b].sender!==""){$=i[b].sender;break}if($===se)if(s.allowDoubleMessage)console.log(" \u26A0 Last message is from us \u2014 but allowDoubleMessage is set (re-engagement).");else return console.error(" \u2717 ABORT: Last message is already from us!"),console.error(` "${v.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let a=n.slice(0,50).toLowerCase();if(i.some(v=>v.text.toLowerCase().startsWith(a)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let v=new Date().toISOString().slice(0,10);if(i.some(b=>{if(!ke(b.sender))return!1;let E=b.time||"";return E.startsWith(v)||E.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}console.log(" \u2713 Safety checks passed");let p=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!p)return console.error(" Message input not found in conversation."),!1;await p.click(),await C(300);let m=n.replace(/\\([!?#$])/g,"$1");m!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=m),await e.keyboard.type(n,{delay:20}),await C(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=v=>v.replace(/\s+/g," ").trim(),u=d(n),g=d(h);if(g!==u){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${u.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let v=0;v<Math.max(u.length,g.length);v++)if(u[v]!==g[v]){console.error(` First diff at position ${v}: expected '${u[v]||"EOF"}' got '${g[v]||"EOF"}'`),console.error(` Context: ...${u.slice(Math.max(0,v-10),v+10)}...`);break}return await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1}console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found."),!1;await y.click(),await C(2500);let w=await e.evaluate(()=>{let $=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),_=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(E=>(E.innerText||"").trim()).filter(Boolean).find(E=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(E))||null;return{inputText:$,error:_}});return w.error?(console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${w.error.slice(0,140)}"`),!1):w.inputText&&d(w.inputText)===d(n)?(console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1):(console.log(" \u2713 Message sent (verified: composer cleared, no error toast)."),await no(e,t,o,n,{conversations:s.conversations}),!0)}catch(r){return console.error(" Error sending message:",r.message),!1}}function Zt(e,t,o){if(t?.profileUrl)return t.profileUrl;let n=Object.entries(o).find(([,s])=>s.name===e);return n?n[0]:null}async function so(e,t,o,n,s={}){try{console.log(` \u2192 Profile fallback: navigating to ${o}`);try{await ge(e,o,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"})}catch(b){if(b.code==="SESSION_EXPIRED")return console.error(" \u2717 Session expired \u2014 run: ilml linkedin login"),!1;throw b}await C(3e3);let r=await e.evaluate(()=>{let b=0,_=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let x of _){if(x.offsetHeight===0)continue;let k=x.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(k||(k=x.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!k){let I=x.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");I.length>0&&(k=I[I.length-1])}k&&k.offsetHeight>0&&(k.click(),b++)}let E=document.querySelector(".msg-overlay-list-bubble");if(E&&!E.classList.contains("msg-overlay-list-bubble--is-minimized")){let x=E.querySelector(".msg-overlay-bubble-header__button");x&&x.offsetHeight>0&&(x.click(),b++)}return b});r>0&&(console.log(` Closed ${r} existing overlay(s)`),await C(1500));let i=await e.evaluate(()=>{let b=document.querySelectorAll(".msg-overlay-conversation-bubble"),_=Array.from(b).filter(k=>k.offsetHeight>0),E=document.querySelector(".msg-overlay-list-bubble"),x=E?E.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:_.length,trayMinimized:x,bubbleNames:_.map(k=>k.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});i.visibleBubbles>0&&console.log(` \u26A0 Still ${i.visibleBubbles} overlay(s) open: [${i.bubbleNames.join(", ")}], tray minimized: ${i.trayMinimized}`);let l=null;for(let b=0;b<8&&!l;b++)l=await e.evaluate(()=>{let _=document.querySelectorAll('a[href*="recipient="]');for(let E of _)try{let x=new URL(E.getAttribute("href"),location.origin).searchParams.get("recipient");if(x)return x}catch{}return null}),l||(b===0&&console.log(" \u2026waiting for the profile Message link to render"),await C(1300));if(!l)return console.error(" \u2717 Could not extract recipient URN from profile after retries (Message link never rendered)"),!1;console.log(` \u2713 Extracted recipient URN: ${l.slice(0,24)}\u2026`);let c=`https://www.linkedin.com/messaging/thread/new/?recipient=${encodeURIComponent(l)}&screenContext=NON_SELF_PROFILE_VIEW`;await e.goto(c,{waitUntil:"domcontentloaded",timeout:6e4}),await C(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;if(!await Ie(e,'div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:45e3,label:"compose box"})){let b=e.url(),_=/\/premium\/|\/checkpoint\/|\/login|\/authwall/.test(b)?" \u2014 looks like a gate (premium/checkpoint/login)":"";return console.error(` \u2717 Message composer never appeared after 45s. URL: ${b.slice(0,120)}${_}`),!1}console.log(" \u2713 Compose page loaded, message form ready");let p=t.split(" ")[0].toLowerCase(),m=t.toLowerCase().split(/[\s,]+/).filter(b=>b.length>1),h=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(h){let b=h.toLowerCase();if(!(b.includes(p)||m.some(E=>b.includes(E))))return console.error(` \u2717 Recipient mismatch: compose shows "${h}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${h}"`)}else return console.error(" \u2717 Could not confirm the recipient (compose pill unreadable) \u2014 not sending on the direct path."),!1;let d=await le(e,{scrollUp:!1});if(d.length>0){let b=n.slice(0,50).toLowerCase();if(d.some(k=>k.text.toLowerCase().startsWith(b)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let E=new Date().toISOString().slice(0,10);if(d.some(k=>{if(!ke(k.sender))return!1;let ne=k.time||"";return ne.startsWith(E)||ne.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let u=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!u)return console.error(" Message input not found in overlay."),!1;await u.click(),await C(300);let g=n.replace(/\\([!?#$])/g,"$1");g!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=g),await e.keyboard.type(n,{delay:20}),await C(500);let y=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),w=b=>b.replace(/\s+/g," ").trim();if(w(y)!==w(n))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${w(n).slice(0,100)}..."`),console.error(` Actual: "${w(y).slice(0,100)}..."`),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1;console.log(" \u2713 Text verified \u2014 matches intended message");let v=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!v)return console.error(" Send button not found in overlay."),!1;await v.click(),await C(2500);let $=await e.evaluate(()=>{let _=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),x=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(k=>(k.innerText||"").trim()).filter(Boolean).find(k=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(k))||null;return{inputText:_,error:x}});return $.error?(console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${$.error.slice(0,140)}"`),!1):$.inputText&&w($.inputText)===w(n)?(console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1):(console.log(" \u2713 Message sent via profile (verified: composer cleared, no error toast)."),await no(e,t,o,n,{conversations:s.conversations}),!0)}catch(r){return console.error(" \u2717 Profile send error:",r.message),!1}}async function Vn(e,t,o,n){if(!t||!o)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let s=et(t);if(!s)return console.error(` Person not found: ${t}`),!1;let r=Ae(s.personName,o);if(!r.ok)return Ee(s.personName,r),!1;if(console.log(`
|
|
81
|
+
`),await Be(e);let{verified:i}=await ve(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await ie(e);if(l.length===0){if(console.log(" No messages extracted (DOM may have changed)."),o){let a=await e.evaluate(()=>({events:document.querySelectorAll("li.msg-s-message-list__event").length,bubbles:document.querySelectorAll(".msg-s-event-listitem").length,any:document.querySelectorAll('[class*="msg-s-event"]').length}));console.log(" [DEBUG] Counts:",a)}}else{console.log(` ${l.length} messages:
|
|
82
|
+
`);for(let a of l){let u=a.time?` (${a.time})`:"";console.log(` [${a.sender}]${u}`),console.log(` ${a.text}`),console.log()}}let c=r;s[c]||(s[c]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),s[c].messages=Se(s[c].messages,l),s[c].lastSynced=new Date().toISOString(),F(s),console.log(` Saved ${s[c].messages.length} messages to conversations.json ["${c}"]`)}function ot(e){let t=Y(),o=e,n=null;if(e.startsWith("http")){let s=t[e];if(s?.name)o=s.name,n=e;else return null}else{let s=Object.entries(t).find(([,i])=>i.name===e);s&&(n=s[0]);let r=O();!n&&r[e]?.profileUrl&&(n=r[e].profileUrl)}return{personName:o,profileUrl:n}}async function so(e,t,o,n,s={}){console.log(" Syncing conversation thread..."),await A(1e3);let r=await ie(e);console.log(` Synced ${r.length} messages from thread.`);let i=!s.conversations,l=s.conversations||O(),c=new Date().toISOString(),a=t;l[a]?(l[a].lastMessageBy="me",l[a].lastMessagePreview=n.slice(0,100),l[a].lastMessageTime=c,l[a].conversationStatus="awaiting_reply",l[a].lastSynced=c,l[a].messages=Se(l[a].messages,r)):l[a]={profileUrl:o,lastSynced:c,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:c,unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:r},o&&(l[a].profileUrl=o),i&&F(l);let u=Y(),p=o?u[o]:null;p&&(p.conversationStatus="awaiting_reply",p.lastMessageSent=c,p.lastUpdated=c,Ne(u))}async function ro(e,t,o,{label:n=""}={}){let s=i=>i.replace(/\s+/g," ").trim();await t.click(),await A(2500);let r=await e.evaluate(()=>{let l=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),a=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(u=>(u.innerText||"").trim()).filter(Boolean).find(u=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(u))||null;return{inputText:l,error:a}});return r.error?(console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${r.error.slice(0,140)}"`),!1):r.inputText&&s(r.inputText)===s(o)?(console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1):(console.log(` \u2713 Message sent${n?" "+n:""} (verified: composer cleared, no error toast).`),!0)}async function nt(e,t,o,n,s={}){try{let{verified:r}=await ve(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await ie(e,{scrollUp:!1}),c=O()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${c})`),i.length>c&&c>0){let y=i.length-c,$=i[i.length-1];return console.error(` \u2717 ABORT: ${y} new message(s) since last sync!`),console.error(` Latest: [${$.sender}] ${$.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let y=i[i.length-1],$=null;for(let S=i.length-1;S>=0;S--)if(i[S].sender!=="Unknown"&&i[S].sender!==""){$=i[S].sender;break}if($===ne)if(s.allowDoubleMessage)console.log(" \u26A0 Last message is from us \u2014 but allowDoubleMessage is set (re-engagement).");else return console.error(" \u2717 ABORT: Last message is already from us!"),console.error(` "${y.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let a=n.slice(0,50).toLowerCase();if(i.some(y=>y.text.toLowerCase().startsWith(a)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let y=new Date().toISOString().slice(0,10);if(i.some(S=>{if(!ke(S.sender))return!1;let D=S.time||"";return D.startsWith(y)||D.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}console.log(" \u2713 Safety checks passed");let p=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!p)return console.error(" Message input not found in conversation."),!1;await p.click(),await A(300);let m=n.replace(/\\([!?#$])/g,"$1");m!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=m),await e.keyboard.type(n,{delay:20}),await A(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=y=>y.replace(/\s+/g," ").trim(),f=d(n),g=d(h);if(g!==f){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${f.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let y=0;y<Math.max(f.length,g.length);y++)if(f[y]!==g[y]){console.error(` First diff at position ${y}: expected '${f[y]||"EOF"}' got '${g[y]||"EOF"}'`),console.error(` Context: ...${f.slice(Math.max(0,y-10),y+10)}...`);break}return await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1}console.log(" \u2713 Text verified \u2014 matches intended message");let w=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');return w?await ro(e,w,n)?(await so(e,t,o,n,{conversations:s.conversations}),!0):!1:(console.error(" Send button not found."),!1)}catch(r){return console.error(" Error sending message:",r.message),!1}}function Qe(e,t,o){if(t?.profileUrl)return t.profileUrl;let n=Object.entries(o).find(([,s])=>s.name===e);return n?n[0]:null}async function tt(e,t,o,n,s={}){try{console.log(` \u2192 Profile fallback: navigating to ${o}`);try{await ge(e,o,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"})}catch(S){if(S.code==="SESSION_EXPIRED")return console.error(" \u2717 Session expired \u2014 run: ilml linkedin login"),!1;throw S}await A(3e3);let r=await e.evaluate(()=>{let S=0,R=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let k of R){if(k.offsetHeight===0)continue;let E=k.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(E||(E=k.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!E){let C=k.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");C.length>0&&(E=C[C.length-1])}E&&E.offsetHeight>0&&(E.click(),S++)}let D=document.querySelector(".msg-overlay-list-bubble");if(D&&!D.classList.contains("msg-overlay-list-bubble--is-minimized")){let k=D.querySelector(".msg-overlay-bubble-header__button");k&&k.offsetHeight>0&&(k.click(),S++)}return S});r>0&&(console.log(` Closed ${r} existing overlay(s)`),await A(1500));let i=await e.evaluate(()=>{let S=document.querySelectorAll(".msg-overlay-conversation-bubble"),R=Array.from(S).filter(E=>E.offsetHeight>0),D=document.querySelector(".msg-overlay-list-bubble"),k=D?D.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:R.length,trayMinimized:k,bubbleNames:R.map(E=>E.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});i.visibleBubbles>0&&console.log(` \u26A0 Still ${i.visibleBubbles} overlay(s) open: [${i.bubbleNames.join(", ")}], tray minimized: ${i.trayMinimized}`);let l=null;for(let S=0;S<8&&!l;S++)l=await e.evaluate(()=>{let R=document.querySelectorAll('a[href*="recipient="]');for(let D of R)try{let k=new URL(D.getAttribute("href"),location.origin).searchParams.get("recipient");if(k)return k}catch{}return null}),l||(S===0&&console.log(" \u2026waiting for the profile Message link to render"),await A(1300));if(!l)return console.error(" \u2717 Could not extract recipient URN from profile after retries (Message link never rendered)"),!1;console.log(` \u2713 Extracted recipient URN: ${l.slice(0,24)}\u2026`);let c=`https://www.linkedin.com/messaging/thread/new/?recipient=${encodeURIComponent(l)}&screenContext=NON_SELF_PROFILE_VIEW`;await e.goto(c,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;if(!await Ie(e,'div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:45e3,label:"compose box"})){let S=e.url(),R=/\/premium\/|\/checkpoint\/|\/login|\/authwall/.test(S)?" \u2014 looks like a gate (premium/checkpoint/login)":"";return console.error(` \u2717 Message composer never appeared after 45s. URL: ${S.slice(0,120)}${R}`),!1}console.log(" \u2713 Compose page loaded, message form ready");let p=t.split(" ")[0].toLowerCase(),m=t.toLowerCase().split(/[\s,]+/).filter(S=>S.length>1),h=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(h){let S=h.toLowerCase();if(!(S.includes(p)||m.some(D=>S.includes(D))))return console.error(` \u2717 Recipient mismatch: compose shows "${h}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${h}"`)}else return console.error(" \u2717 Could not confirm the recipient (compose pill unreadable) \u2014 not sending on the direct path."),!1;let d=await ie(e,{scrollUp:!1});if(d.length>0){let S=n.slice(0,50).toLowerCase();if(d.some(E=>E.text.toLowerCase().startsWith(S)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let D=new Date().toISOString().slice(0,10);if(d.some(E=>{if(!ke(E.sender))return!1;let I=E.time||"";return I.startsWith(D)||I.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let f=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!f)return console.error(" Message input not found in overlay."),!1;await f.click(),await A(300);let g=n.replace(/\\([!?#$])/g,"$1");g!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=g),await e.keyboard.type(n,{delay:20}),await A(500);let w=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),y=S=>S.replace(/\s+/g," ").trim();if(y(w)!==y(n))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${y(n).slice(0,100)}..."`),console.error(` Actual: "${y(w).slice(0,100)}..."`),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1;console.log(" \u2713 Text verified \u2014 matches intended message");let $=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');return $?await ro(e,$,n,{label:"via profile"})?(await so(e,t,o,n,{conversations:s.conversations}),!0):!1:(console.error(" Send button not found in overlay."),!1)}catch(r){return console.error(" \u2717 Profile send error:",r.message),!1}}async function Yn(e,t,o,n){if(!t||!o)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let s=ot(t);if(!s)return console.error(` Person not found: ${t}`),!1;let r=Ae(s.personName,o);if(!r.ok)return Ee(s.personName,r),!1;if(console.log(`
|
|
83
83
|
Sending message to: ${s.personName}`),console.log(` Text: "${o.slice(0,150)}${o.length>150?"...":""}"`),n)return console.log(`
|
|
84
|
-
[DRY RUN \u2014 message not sent]`),!1;if(s.profileUrl){if(await
|
|
84
|
+
[DRY RUN \u2014 message not sent]`),!1;if(s.profileUrl){if(await tt(e,s.personName,s.profileUrl,o))return!0;console.log(" Direct profile-URL send did not complete \u2014 falling back to name search\u2026")}return await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3),nt(e,s.personName,s.profileUrl,o)}async function Gn(e,t,o){if(console.log(`
|
|
85
85
|
\u2550\u2550 Batch send: ${t.length} messages \u2550\u2550
|
|
86
|
-
`),o){for(let i of t){let l=i.message??i.text??"";console.log(` [DRY RUN] ${i.name}: "${l.slice(0,80)}..."`)}return}await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await
|
|
87
|
-
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`),!c){console.error(` \u2717 No message body for "${l}" \u2014 each entry needs a "text" (or "message") field`),n.push({name:l,status:"no_text"});continue}let a=
|
|
86
|
+
`),o){for(let i of t){let l=i.message??i.text??"";console.log(` [DRY RUN] ${i.name}: "${l.slice(0,80)}..."`)}return}await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let n=[];for(let i=0;i<t.length;i++){let{name:l}=t[i],c=t[i].message??t[i].text;if(console.log(`
|
|
87
|
+
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`),!c){console.error(` \u2717 No message body for "${l}" \u2014 each entry needs a "text" (or "message") field`),n.push({name:l,status:"no_text"});continue}let a=ot(l);if(!a){console.error(` \u2717 Cannot resolve: ${l}`),n.push({name:l,status:"not_found"});continue}if(!t[i].skipSalutationCheck){let p=Ae(a.personName,c);if(!p.ok){Ee(a.personName,p),n.push({name:l,status:"aborted_salutation"});continue}}console.log(` Text: "${c.slice(0,100)}${c.length>100?"...":""}"`);let u=await nt(e,a.personName,a.profileUrl,c);n.push({name:l,status:u?"sent":"failed"}),await no(e)}console.log(`
|
|
88
88
|
\u2550\u2550 Batch results \u2550\u2550
|
|
89
|
-
`);let s=n.filter(i=>i.status===
|
|
90
|
-
Total: ${s.length} sent, ${r.length} failed/skipped`)}function
|
|
89
|
+
`);let s=n.filter(i=>i.status===b.SENT),r=n.filter(i=>i.status!==b.SENT);for(let i of n){let l=i.status===b.SENT?"\u2713":"\u2717";console.log(` ${l} ${i.name} \u2014 ${i.status}`)}console.log(`
|
|
90
|
+
Total: ${s.length} sent, ${r.length} failed/skipped`)}function to(e,t){let o=r=>String(r||"").replace(/\s+/g,"").toLowerCase(),n=o(t);if((e.messages||[]).some(r=>!z.has(r.status)&&ke(r.sender)&&o(r.text)===n))e.messages=(e.messages||[]).filter(r=>!(r.status===b.CONFIRMED&&r.text===t));else for(let r of e.messages||[])r.status===b.CONFIRMED&&r.text===t&&(r.status=b.SENT,r.sentAt=new Date().toISOString())}async function zn(e,t){let o=O(),n=Y(),s=Object.entries(o).filter(([,d])=>et(d)),r=s.filter(([,d])=>Xe(d)?.status===b.CONFIRMED),i=s.filter(([,d])=>{let f=Xe(d)?.status;return f===b.DRAFT||f===b.NEEDS_REVIEW}).length;if(s.length===0){console.log(`
|
|
91
91
|
No drafts to push. Prepare drafts in conversations.json first.
|
|
92
92
|
`);return}if(r.length===0){console.log(`
|
|
93
93
|
No confirmed drafts to push (${i} pending, need review).`),console.log(` Run: npm run messages -- --review-drafts
|
|
94
94
|
`);return}if(console.log(`
|
|
95
|
-
\u2550\u2550 Pushing ${r.length} confirmed draft(s) \u2550\u2550`),i>0&&console.log(` (${i} more pending \u2014 run --review-drafts to confirm)`),console.log(),t){for(let[d,
|
|
96
|
-
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await
|
|
97
|
-
\u2500\u2500 [${d+1}/${r.length}] ${
|
|
95
|
+
\u2550\u2550 Pushing ${r.length} confirmed draft(s) \u2550\u2550`),i>0&&console.log(` (${i} more pending \u2014 run --review-drafts to confirm)`),console.log(),t){for(let[d,f]of r){let g=Qe(d,f,n),w=f.messages?.some($=>!ce.has($.status)&&$.status!==b.REJECTED)?"inbox":g?"profile":"no profileUrl";console.log(` [DRY RUN] ${d} (${w}):`);let y=Ze(f)||"";console.log(` "${y.slice(0,100)}${y.length>100?"...":""}"`),console.log()}return}console.log(`\u2500\u2500 Pass 1: Inbox search \u2500\u2500
|
|
96
|
+
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let l=[],c=[];for(let d=0;d<r.length;d++){let[f,g]=r[d],w=Ze(g);console.log(`
|
|
97
|
+
\u2500\u2500 [${d+1}/${r.length}] ${f} \u2500\u2500`),console.log(` Draft: "${w.slice(0,100)}${w.length>100?"...":""}"`);let y=ot(f),$=y?.personName||f,S=y?.profileUrl||g.profileUrl||null;if(!g.skipSalutationCheck){let C=Ae(f,w);if(!C.ok){Ee(f,C),l.push({name:f,status:"aborted_salutation"});continue}}let D=(g.messages||[]).filter(C=>!z.has(C.status)).length,k=!1,E=!1;try{await gt(e);let{verified:C}=await ve(e,$);if(C){E=!0;let I=await ie(e);if(I.length>D&&D>0){let de=I.length-D;k=!0,g.messages=Se(g.messages,I),console.log(` \u26A0 ${de} new message(s) since draft was created!`);let Ce=I[I.length-1];console.log(` Latest: [${Ce.sender}] ${Ce.text.slice(0,80)}`)}}else console.log(" Not found or wrong thread in inbox search")}catch(C){console.log(` Pre-send sync error: ${C.message}`)}if(k){for(let C of g.messages||[])C.status===b.CONFIRMED&&(C.status=b.NEEDS_REVIEW);l.push({name:f,status:b.NEEDS_REVIEW}),console.log(" \u2192 Skipped \u2014 draft needs review (new messages from them)")}else if(E){let C=Qe(f,g,n),I=C?"profile":"inbox";(C?await tt(e,$,C,w,{conversations:o}):await nt(e,$,S,w,{allowDoubleMessage:!0,conversations:o}))?(to(g,w),g.reviewedAtPreview=g.lastMessagePreview||"",F(o),l.push({name:f,status:"sent",method:I})):l.push({name:f,status:"failed",method:I})}else c.push({name:f,conv:g,message:w,personName:$}),console.log(" \u2192 Queued for profile fallback");k&&F(o),await no(e)}if(c.length>0){console.log(`
|
|
98
98
|
\u2500\u2500 Pass 2: Profile fallback (${c.length} remaining) \u2500\u2500
|
|
99
|
-
`);for(let d=0;d<c.length;d++){let{name:
|
|
100
|
-
\u2500\u2500 [profile ${d+1}/${c.length}] ${
|
|
99
|
+
`);for(let d=0;d<c.length;d++){let{name:f,conv:g,message:w,personName:y}=c[d];console.log(`
|
|
100
|
+
\u2500\u2500 [profile ${d+1}/${c.length}] ${f} \u2500\u2500`),console.log(` Draft: "${w.slice(0,100)}${w.length>100?"...":""}"`);let $=Qe(f,g,n);if(!$){console.error(" \u2717 No profileUrl found \u2014 cannot send via profile"),l.push({name:f,status:"failed",method:"no_url"});continue}await tt(e,y,$,w,{conversations:o})?(to(g,w),g.reviewedAtPreview=g.lastMessagePreview||"",F(o),l.push({name:f,status:"sent",method:"profile"})):l.push({name:f,status:"failed",method:"profile"})}}console.log(`
|
|
101
101
|
\u2550\u2550 Push results \u2550\u2550
|
|
102
|
-
`);let a=l.filter(d=>d.status===
|
|
103
|
-
Total: ${a.length} sent (${m} inbox, ${h} profile), ${
|
|
102
|
+
`);let a=l.filter(d=>d.status===b.SENT),u=l.filter(d=>d.status===b.NEEDS_REVIEW),p=l.filter(d=>d.status==="failed");for(let d of l){let f={sent:"\u2713",needs_review:"\u26A0",failed:"\u2717"}[d.status]||"?",g=d.method?` (${d.method})`:"";console.log(` ${f} ${d.name} \u2014 ${d.status}${g}`)}let m=a.filter(d=>d.method==="inbox").length,h=a.filter(d=>d.method==="profile").length;console.log(`
|
|
103
|
+
Total: ${a.length} sent (${m} inbox, ${h} profile), ${u.length} need review, ${p.length} failed`)}function Kn(e){let t={};for(let[o,n]of Object.entries(e)){let s=n.name;s&&(t[s]?n.connectionStatus==="connected"&&t[s].connectionStatus!=="connected"&&(t[s]={url:o,...n}):t[s]={url:o,...n})}return t}function Qn(e,t){let o=O(),n=Y(),s=Kn(n),r=new Date().toISOString(),i={newConversations:0,updatedConversations:0,unansweredByUs:0,awaitingReply:0,peopleLinked:0,newPeople:0};for(let l of e){if(!l.name)continue;let c;l.lastMessageBy==="them"?(c="unanswered_by_us",i.unansweredByUs++):l.lastMessageBy==="me"?(c="awaiting_reply",i.awaitingReply++):c="mutual_silence";let u=s[l.name]?.url||null,p=o[l.name];if(p?(p.lastSynced=r,p.lastMessageBy=l.lastMessageBy,p.lastMessagePreview=l.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=l.lastMessageTime||p.lastMessageTime,p.unread=l.unread,p.conversationStatus||(p.conversationStatus=c),u&&!p.profileUrl&&(p.profileUrl=u),i.updatedConversations++):(o[l.name]={profileUrl:u,lastSynced:r,lastMessageBy:l.lastMessageBy,lastMessagePreview:l.lastMessagePreview||"",lastMessageTime:l.lastMessageTime||"",unread:l.unread||!1,conversationStatus:c,messages:[]},i.newConversations++),u){let m=n[u];m.conversationStatus=c,l.lastMessageBy==="them"&&(m.lastMessageReceived=m.lastMessageReceived||r),l.lastMessageBy==="me"&&(m.lastMessageSent=m.lastMessageSent||r),m.lastUpdated=r,i.peopleLinked++}}return t||(F(o),Ne(n)),i}function Xn(e,t,o,n){let s=O(),r=Object.entries(s),i=r.filter(([,l])=>l.conversationStatus==="unanswered_by_us").sort((l,c)=>{let a=l[1].lastSynced||"";return(c[1].lastSynced||"").localeCompare(a)});if(console.log(`
|
|
104
104
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` Message Bot Summary (${n})`),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"),console.log(` Conversations scanned: ${e.length}`),console.log(` New conversations: ${t.newConversations}`),console.log(` Updated conversations: ${t.updatedConversations}`),console.log(` Linked to people.json: ${t.peopleLinked}`),t.newPeople>0&&console.log(` New people (non-contact): ${t.newPeople}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` This scan \u2014 unanswered: ${t.unansweredByUs}`),console.log(` This scan \u2014 awaiting: ${t.awaitingReply}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Total in DB: ${r.length} conversations`),console.log(` Total unanswered: ${i.length}`),i.length>0){let c=i.slice(0,15);console.log(`
|
|
105
105
|
\u26A1 ACTION NEEDED \u2014 ${i.length} unanswered messages:
|
|
106
|
-
`);for(let[a,
|
|
106
|
+
`);for(let[a,u]of c){let p=a.padEnd(30),m=(u.lastMessageTime||"").padEnd(10),h=u.lastMessagePreview?u.lastMessagePreview.slice(0,55)+(u.lastMessagePreview.length>55?"...":""):"";console.log(` ${p} ${m} ${h}`)}i.length>15&&console.log(`
|
|
107
107
|
... and ${i.length-15} more. Use --list for full list.`)}else console.log(`
|
|
108
108
|
All caught up \u2014 no unanswered messages.`);o&&console.log(`
|
|
109
109
|
[DRY RUN \u2014 nothing written to DB]`),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
|
|
110
|
-
`)}async function
|
|
110
|
+
`)}async function Zn(){let e=qn();if(e.list){Wn();return}if(e.reviewDrafts){await Jn();return}if(e.followUp||e.followUpBatch||e.clearFollowUp){let r=O(),i=0;if(e.clearFollowUp){let l=r[e.clearFollowUp];l?(delete l.followUpNote,delete l.followUpDate,i++,console.log(` \u2713 ${e.clearFollowUp} \u2014 follow-up cleared`)):console.log(` ? ${e.clearFollowUp} \u2014 not found`)}else{let l=e.followUpBatch||[e.followUp];for(let c of l){let a=c.target||c.name,u=c.note||c.text||"",p=c.date||null,m=r[a];m?(m.followUpNote=u,p&&(m.followUpDate=p),i++,console.log(` + ${a} \u2014 follow-up set${p?` for ${p}`:""}: ${u.slice(0,60)}`)):(r[a]={profileUrl:null,lastSynced:new Date().toISOString(),followUpNote:u,followUpDate:p||null,messages:[]},i++,console.log(` + ${a} \u2014 new entry with follow-up${p?` for ${p}`:""}`))}}i>0&&(F(r),console.log(`
|
|
111
111
|
${i} follow-up(s) updated.
|
|
112
112
|
`));return}if(e.review||e.reviewBatch){let r=e.reviewBatch||[e.review],i=O(),l=0;for(let c of r){let a=i[c];a?(a.reviewedAtPreview=a.lastMessagePreview||"",l++,console.log(` + ${c} \u2014 marked as reviewed`)):console.log(` ? ${c} \u2014 not found in conversations`)}l>0?(F(i),console.log(`
|
|
113
113
|
${l} conversation(s) marked as reviewed.
|
|
114
114
|
`)):console.log(`
|
|
115
115
|
No conversations updated.
|
|
116
|
-
`);return}if(e.draft||e.draftBatch){let r=e.draftBatch?e.draftBatch:[{name:e.draft.target,text:e.draft.text}];r.length===0&&(console.error("No drafts to add."),process.exit(1));let i=O(),l=Y(),c=0;for(let{name:a,text:
|
|
116
|
+
`);return}if(e.draft||e.draftBatch){let r=e.draftBatch?e.draftBatch:[{name:e.draft.target,text:e.draft.text}];r.length===0&&(console.error("No drafts to add."),process.exit(1));let i=O(),l=Y(),c=0;for(let{name:a,text:u,profileUrl:p,skipSalutationCheck:m}of r){if(!a||!u){console.error(` Skipping invalid draft: name=${a}`);continue}let h=e.draft?u.replace(/\\([!?#$])/g,"$1"):u;if(!m){let g=Ae(a,h);if(!g.ok){Ee(a,g);continue}}if(!i[a]){let g=p||null;if(!g){let w=Object.entries(l).filter(([,y])=>y.name===a);w.length===1?g=w[0][0]:w.length>1&&console.warn(` \u26A0 Multiple people named "${a}" \u2014 pass profileUrl in draft JSON to disambiguate`)}i[a]={profileUrl:g,lastSynced:new Date().toISOString(),conversationStatus:null,messages:[]},g?console.log(` New conversation \u2014 linked to ${g}`):console.warn(" \u26A0 New conversation \u2014 no profileUrl found (push will need inbox search)")}let d=i[a];d.messages||(d.messages=[]),d.messages.push({sender:ne,text:h,time:new Date().toISOString(),status:b.CONFIRMED,draftedAt:new Date().toISOString()}),d.reviewedAtPreview=d.lastMessagePreview||"";let f=d.messages.filter(g=>!ce.has(g.status)&&g.status!==b.REJECTED);console.log(` Draft added for ${a}`),console.log(` Thread: ${f.length} messages + 1 draft`),console.log(` "${h.slice(0,100)}${h.length>100?"...":""}"`),console.log(),c++}F(i),console.log(` ${c} draft(s) saved. Send all: npm run messages -- --push-drafts
|
|
117
117
|
`);return}console.log(`
|
|
118
118
|
\u{1F4E8} LinkedIn Message Bot
|
|
119
|
-
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let t=e.read?"read":e.pushDrafts?"push-drafts":e.sendBatch?"send-batch":e.send?"send":e.full?"full":"incremental",o=
|
|
120
|
-
`),await Be(s),await
|
|
121
|
-
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),Pe(o,"error",null,r.message)}finally{await n.close()}}
|
|
119
|
+
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let t=e.read?"read":e.pushDrafts?"push-drafts":e.sendBatch?"send-batch":e.send?"send":e.full?"full":"incremental",o=Ct("messages",t),{browser:n,page:s}=await Ft();try{if(e.read)await Vn(s,e.read,e.verbose);else if(e.pushDrafts)await zn(s,e.dryRun);else if(e.sendBatch)await Gn(s,e.sendBatch,e.dryRun);else if(e.send)await Yn(s,e.send.target,e.send.text,e.dryRun);else{let r=e.full?"full":"incremental";console.log(`Mode: ${r} inbox scan
|
|
120
|
+
`),await Be(s),await Hn(s,{full:e.full,max:e.max,verbose:e.verbose,dryRun:e.dryRun})}Pe(o,"success")}catch(r){console.error(`
|
|
121
|
+
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),Pe(o,"error",null,r.message)}finally{await n.close()}}Zn();
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.10";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
|
package/ilml-plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "linkedin",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.10",
|
|
4
4
|
"description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
|
|
5
5
|
"commands": {
|
|
6
6
|
"help": { "run": "node dist/help.mjs", "description": "List all commands with descriptions; or `help <cmd>` for detailed info on one command (usage, flags, ban-risk, when-to-use). Reads ilml-plugin.json directly.", "usage": "ilml linkedin help [<cmd>]", "useWhen": "You forgot what a command does, or you're an AI agent picking the right tool." },
|
package/package.json
CHANGED