ilml-plugin-linkedin 1.20.3 → 1.20.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/syncAll.mjs CHANGED
@@ -1,8 +1,8 @@
1
- var qs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{for(var n in t)qs(e,n,{get:t[n],enumerable:!0})};function et(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function Wt(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let c=et(n),l=new Date(t);return c?l.setHours(c.hours,c.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let c=Bs[o[1].toLowerCase()],l=et(o[2]||""),a=new Date(t),f=a.getDay()-c;return f<=0&&(f+=7),a.setDate(a.getDate()-f),l?a.setHours(l.hours,l.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let c=Vt[s[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let l=parseInt(s[2],10),a=parseInt(s[3],10),u=et(s[4]||"");return new Date(a,c,l,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let c=Vt[i[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let l=parseInt(i[2],10),a=et(i[3]||""),u=t.getFullYear(),f=new Date(u,c,l,a?.hours||0,a?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let c=Vt[r[1].toLowerCase().slice(0,3)];if(c===void 0)return null;let l=parseInt(r[2],10),a=et(r[3]||""),u=t.getFullYear(),f=new Date(u,c,l,a?.hours||0,a?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Wn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");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 k(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function Ae(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||c){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:s.substring(0,80)};let a=o.querySelectorAll("button");for(let u of a){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function Yn(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 Gn(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()}var Vt,Bs,Le=de(()=>{Vt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Bs={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Hs}from"@ilivemylife/graph-sdk";var Js,z,V,tt,Fe,nt=de(async()=>{Js=await Hs();for(let[e,t]of Object.entries(Js))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),tt=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),Fe=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as B from"path";import{fileURLToPath as Vs}from"url";import{execSync as Yt}from"child_process";function no(){Ue=null,Gs=null,fe=null,xe=null,qe=null,Ee=null}function me(){F.existsSync(Z)||F.mkdirSync(Z,{recursive:!0})}function He(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function rt(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${B.resolve(e)}`);let o=e+".backup";if(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function it(){return new Date().toISOString().split("T")[0]}function _e(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Kn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Be(e,t,n=null){if(!t||e[t])return t;let o=_e(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(_e(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=Kn(n),r=Kn(e[s].name);if(i&&r&&i===r)return s}return t}function Qs(){F.existsSync(zt)||F.mkdirSync(zt,{recursive:!0})}function oo(e){let t=_e(e);return t?B.join(zt,`${t}.json`):null}function Zs(e){let t=oo(e);return t?rt(t,`profile-history/${_e(e)}.json`)||[]:[]}function Xs(e,t){let n=oo(e);if(!n)return;Qs();let o=Zs(e);o.unshift(t);try{He(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${_e(e)}: ${s.message}`)}}function Qn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Zn(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function er(e,t){if(!e)return[];let n=[];for(let o of Ks){let s=e[o],i=t[o];Qn(s)||Qn(i)||Zn(s)!==Zn(i)&&n.push(o)}return n}function tr(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function J(){return Ue||(me(),Ue=rt(Gt,"people.json")||{},Ue)}function Re(e){me(),Ue=e;try{He(Gt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(Gt)}`)}}function lt(){return xe||(me(),xe=rt(Et,"conversations.json")||{},nr(xe),xe)}function nr(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{He(Et,e)}catch{}}}function ye(e){me(),xe=e;try{He(Et,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${B.resolve(Et)}`)}}function Te(e,t={}){if(!e)return null;let n=J(),o=it(),s=new Date().toISOString(),i=Be(n,e,t.name),r=n[i];if(r){let c=er(r,t);c.length>0&&(Xs(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:c,snapshot:tr(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let l of zs)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(r[l])&&r[l].length>0)continue;r[l]=t[l]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Re(n),n[i]}function so(e,t){if(!e||!t)return;let n=J(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:it(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Re(n))}function ro(e){return e&&J()[e]?.connectionStatus||null}function io(e,t,n={}){if(!e)return;if(n.profileInfo)Te(e,n.profileInfo);else{let c=J(),l=Be(c,e,n.profileInfo?.name);c[l]||Te(e,{})}let o=J(),s=Be(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=it();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Re(o)}function xt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=_e(t);if(!o)return;let s=J(),i=Be(s,e),r=s[i];if(!r)return;let c=_e(r.profileUrl||i);o!==c&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),Re(s)))}function lo(){return fe||(me(),fe=rt(Xn,"quota.json"),(!fe||!fe.connections)&&(fe={connections:[]}),fe)}function or(e){me(),fe=e;try{He(Xn,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function ao(e,t="unknown"){let n=lo(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),or(n)}function co(){let e=lo(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Kt(){let e=co(),t=it(),n=e.filter(l=>l.date===t).length,o=e.length,s=n>=ot,i=o>=st,r=!s&&!i,c={allowed:r,daily:{sent:n,max:ot},weekly:{sent:o,max:st}};return r||(c.reason=s?`Daily limit reached (${n}/${ot})`:`Weekly limit reached (${o}/${st})`),c}function at(){let e=co(),t=it(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:ot,remaining:ot-n},weekly:{sent:o,max:st,remaining:st-o}}}function Qt(){return qe||(me(),qe=rt(eo,"sync-state.json")||{},qe)}function uo(e){me(),qe=e;try{He(eo,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function sr(){if(Ee)return Ee;me();try{F.existsSync(zn)&&(Ee=JSON.parse(F.readFileSync(zn,"utf-8")))}catch{}return Ee||(Ee={}),Ee}function rr(e){return Array.isArray(e.applications)}function ir(){let e=sr();if(rr(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function fo(){let e=ir(),t=new Map;for(let i of e)for(let r of i.questions||[]){let c=r.question.toLowerCase().trim();if(!c)continue;t.has(c)||t.set(c,{question:r.question,count:0,answers:new Map});let l=t.get(c);l.count++;let a=(r.answer||"").trim();l.answers.set(a,(l.answers.get(a)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,c)=>c[1]-r[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((r,c)=>c[1]-r[1]).map(([r,c])=>`${r} (${c}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function Zt(e){if(F.existsSync(B.join(Z,".git")))try{let t={cwd:Z,stdio:"pipe",timeout:1e4};Yt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{Yt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Yt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Ws,Ys,Z,Gt,Fl,Xn,Et,eo,zn,zt,to,ot,st,Ue,Gs,fe,xe,qe,Ee,zs,Ks,Je=de(async()=>{await nt();Ws=Vs(import.meta.url),Ys=B.dirname(B.dirname(Ws)),Z=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(Ys,"collected-profiles"),Gt=B.join(Z,"people.json"),Fl=B.join(Z,"jobs.json"),Xn=B.join(Z,"quota.json"),Et=B.join(Z,"conversations.json"),eo=B.join(Z,"sync-state.json"),zn=B.join(Z,"application-questions.json"),zt=B.join(Z,"profile-history"),to=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ot=to(process.env.CONNECT_MAX_DAILY,20),st=to(process.env.CONNECT_MAX_WEEKLY,100),Ue=null,Gs=null,fe=null,xe=null,qe=null,Ee=null;zs=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Ks=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var ho={};ae(ho,{BLOCK_MARKERS:()=>mo,dedupeAndCap:()=>go,extractSidePanelProfiles:()=>lr,normalizeFundUrl:()=>_t,normalizeProfileUrl:()=>Ve,scanRelatedBlocks:()=>po});function Ve(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function _t(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function po(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=a=>(a||"").replace(/\s+/g," ").trim(),s=a=>{let u=String(a||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=a=>o(a).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),r=a=>{let u=a,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||a.parentElement},c=[],l=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let a of l){let u=o(a.textContent).toLowerCase();if(!u)continue;let f=e.find(([b])=>u.includes(b));if(!f)continue;let d=f[1],m=r(a);if(!m)continue;let y=0,g=new Set;for(let b of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let w=b.href||b.getAttribute("href")||"",S=s(w);if(!S)continue;let h=b.querySelector('span[aria-hidden="true"]'),p=o(h?h.textContent:b.getAttribute("aria-label")||b.textContent),v=i(p);if(!v||g.has(S))continue;g.add(S);let C="",_=p.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(_&&(C=o(_[1])),!C){let R=b.closest("li")||b.parentElement;R&&(C=Array.from(R.querySelectorAll("p, span")).map(D=>o(D.textContent)).filter(D=>D&&D!==v&&!/^view\b/i.test(D)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(D)&&/[a-z]/i.test(D)&&D.length>2)[0]||"")}c.push({href:w,name:v,headline:C,block:d,rank:y++})}}return c}function go(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=Ve(t.seedUrl||""),s=new Map,i={};for(let r of e||[]){let c=Ve(r.href);c&&(o&&c===o||(i[r.block]=i[r.block]||0,!(i[r.block]>=n)&&(s.has(c)||(i[r.block]++,s.set(c,{url:c,name:r.name,headline:r.headline||null,block:r.block,rank:r.rank})))))}return Array.from(s.values())}async function lr(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(po,mo)}catch{return[]}return go(n,t)}var mo,Xt=de(()=>{mo=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var ko={};ae(ko,{getJobDecision:()=>mr,getLastVisit:()=>vr,getScoutStats:()=>sn,loadCompanies:()=>on,loadDiscoveredPeople:()=>ht,loadJobDecisions:()=>gt,loadScoutedJobs:()=>pt,loadVisitLog:()=>It,recordCompany:()=>wr,recordDiscoveredEdge:()=>hr,recordDiscoveredEdges:()=>yr,recordVisit:()=>Sr,resetCaches:()=>nn,saveCompany:()=>br,saveDiscoveredPerson:()=>pr,saveScoutedJob:()=>dr,setJobDecision:()=>fr});import"dotenv/config";import*as X from"fs";import*as K from"path";import{fileURLToPath as ar}from"url";function we(){X.existsSync(De)||X.mkdirSync(De,{recursive:!0})}function be(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";X.writeFileSync(o,n);for(let s=0;s<3;s++)try{X.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function mt(e){try{if(X.existsSync(e))return JSON.parse(X.readFileSync(e,"utf-8"))}catch{}return null}function nn(){ct=null,ut=null,dt=null,ft=null,Ie=null}function pt(){return ct||(ct=mt(yo)||{},ct)}function dr(e,t){if(!e)return;we();let n=pt(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{be(yo,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function gt(){return ut||(ut=mt(bo)||{},ut)}function fr(e,t,n={}){if(!e||!t)return;we();let o=gt(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{be(bo,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function mr(e){return gt()[e]||null}function ht(){return dt||(dt=mt(Rt)||{},dt)}function We(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function So(e,t){let n=Ve(t)||t;if(e[n])return n;let o=We(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(We(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function pr(e,t){if(!e)return;we();let n=ht(),o=new Date().toISOString().slice(0,10),s=So(n,e),i=We(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&We(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{be(Rt,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function gr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function vo(e,t,n={},o){if(!t)return;let s=We(t);t=So(e,t);let i=n.seedUrl?{...n,seedUrl:Ve(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:c,match:l}=gr(i,o),a=e[t];a||(a=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:c.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:c.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:r,firstSeen:r,lastSeen:r}),n.name&&(a.name=n.name),n.headline&&(!a.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(a.headline))&&(a.headline=n.headline),n.location&&(a.location=a.location||n.location),n.company&&(a.company=n.company),n.companyUrl&&(a.companyUrl=a.companyUrl||n.companyUrl),n.isConnected!=null&&(a.isConnected=n.isConnected),n.connectionsCount!=null&&(a.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(a.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(a.connectGate=n.connectGate),n.note&&!a.note&&(a.note=n.note),n.whyUseful&&!a.whyUseful&&(a.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(a.extra={...a.extra||{},...n.extra}),Array.isArray(a.sources)||(a.sources=[]);let u=a.sources.find(l);if(u?(c.rank!=null&&(u.rank==null||c.rank<u.rank)&&(u.rank=c.rank),u.at=c.at):a.sources.push(c),Array.isArray(a.categories)||(a.categories=[]),Array.isArray(a.sectors)||(a.sectors=[]),Array.isArray(a.aliases)||(a.aliases=[]),Array.isArray(a.graphRefs)||(a.graphRefs=[]),en(a.categories,n.category),Tt(a.categories,n.categories),Tt(a.sectors,n.sectors),Tt(a.aliases,n.aliases),s&&We(a.canonicalUrl||t)!==s&&en(a.aliases,s),Tt(a.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(a.affiliations)||(a.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||a.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||a.affiliations.push(f)}a.lastSeen=r,a.seenCount=(a.seenCount||0)+1}function hr(e,t={}){if(!e)return;we();let n=ht();vo(n,e,t,new Date().toISOString());try{be(Rt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function yr(e){if(!Array.isArray(e)||e.length===0)return;we();let t=ht(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||(vo(t,s.url,s,n),o++);if(o)try{be(Rt,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function wr(e={}){if(!e||!e.name)return;we();let t=e.key||_t(e.website)||_t(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=on(),o=new Date().toISOString().slice(0,10),s=(l,a)=>{a&&Array.isArray(l)&&!l.includes(a)&&l.push(a)},i=(l,a)=>{if(Array.isArray(a))for(let u of a)s(l,u)},r=n[t];r||(r=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!r[l]&&(r[l]=e[l]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[l])||(r[l]=[]),i(r[l],e[l]);Array.isArray(r.people)||(r.people=[]);let c=l=>{if(!l||!l.url)return;let a=r.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));a?l.current!=null&&(a.current=l.current):r.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(c),(e.partners||[]).forEach(l=>c({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(r.portfolio)||(r.portfolio=[]);for(let l of e.portfolio||[]){let a=l&&(l.key||l.name);a&&!r.portfolio.some(u=>(u.key||u.name)===a)&&r.portfolio.push(l)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{be(tn,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function on(){return ft||(ft=mt(tn)||{},ft)}function br(e,t){if(!e)return;we();let n=on(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{be(tn,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function It(){return Ie||(Ie=mt(wo)||{visits:[]},Array.isArray(Ie.visits)||(Ie.visits=[]),Ie)}function Sr(e,t={}){if(!e)return;we();let n=It();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{be(wo,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function vr(e){let t=It();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function sn(){let e=pt(),t=ht(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),r={};for(let d of n)for(let m of d.techStack||[])r[m]=(r[m]||0)+1;let c=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),l=It(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(a)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:c,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var cr,ur,De,yo,Rt,wo,tn,bo,ct,ut,dt,en,Tt,ft,Ie,yt=de(()=>{Xt();cr=ar(import.meta.url),ur=K.dirname(K.dirname(cr)),De=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(ur,"market-research"),yo=K.join(De,"scouted-jobs.json"),Rt=K.join(De,"discovered-people.json"),wo=K.join(De,"visit-log.json"),tn=K.join(De,"companies.json"),bo=K.join(De,"job-decisions.json");ct=null;ut=null;dt=null;en=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},Tt=(e,t)=>{if(Array.isArray(t))for(let n of t)en(e,n)};ft=null;Ie=null});var ns={};ae(ns,{computeEngagement:()=>gn,detectCategory:()=>zo,detectCategoryFromTitle:()=>Mt,determineAction:()=>es,determineLastMessageBy:()=>jt,determineSituation:()=>Ko,enrichConversation:()=>Pt,enrichPerson:()=>yn,enrichPersonContext:()=>ts,extractAutoTags:()=>Zo,generateSummary:()=>Qo,normPreview:()=>ze});function Pt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(l=>!Fe.has(l.status)),i=Jr(t,e.profileUrl,n),r=jt(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=zo(s,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Ko(s,r,t),s.length>0){let l=s[s.length-1];e.lastMessageTime=l.time}if(s.length>0&&!e.initiatedBy){let l=s[0];l.sender===z?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=gn(s,t),e.personContext=ts(i),e.summary=Qo(e,t,i),e.autoTags=Zo(e,t,i);let c=es(e);return e.actionNeeded=c.action,e.actionDetail=c.detail,e.suggestedPriority=Hr(e),e}function zo(e,t,n){if(!e||e.length===0)return n?.title?Mt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(Go))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=Mt(n.title);if(s)return s}return null}function Mt(e){if(!e)return null;for(let[t,n]of Object.entries(Go))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Ko(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return Yo.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return Yo.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function jt(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Qo(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,c=n?.company,l=n?.location;i==="recruiter"&&c?s.push(`Recruiter from ${c}`):i==="hiring_manager"&&c?s.push(`Hiring manager at ${c}`):i==="founder"&&c?s.push(`Founder of ${c}`):i&&r?s.push(`${hn(i)}: ${Ge(r,40)}`):r?s.push(Ge(r,50)):s.push(t.split(" ")[0]);let a=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),u=Vr(a),f=Wr(a),d=Yr(a),m=[];return u&&m.push(u),d&&d!==l&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function Zo(e,t,n){let o=[],s=(e.messages||[]).filter(a=>!Fe.has(a.status)),i=s.map(a=>a.text).join(" "),r=s.filter(a=>a.sender!==z&&a.sender!=="Unknown").map(a=>a.text).join(" "),c=Xo(r,n?.location);o.push(...c),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let l=e.engagement||gn(s,t);return l.messageCount>=6&&o.push("active-thread"),l.theirCount===0&&l.ourCount>0&&o.push("no-response"),l.ourCount===0&&l.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(a=>tt.has(a.status))&&o.push("has-draft"),[...new Set(o)]}function Xo(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,c]of s)i.includes(r)&&n.push(c);return n}function es(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&ze(e.lastMessagePreview)===ze(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>tt.has(i.status));return s?s.status===V.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${hn(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function gn(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,s=0,i=!1,r=!1,c=e.map(l=>l.text).join(" ");for(let l of e)l.sender===z?n++:l.sender==="Unknown"||l.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(c),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(c),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function ts(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Hr(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function Jr(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=Be(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function ze(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function hn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Vr(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function Wr(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function Yr(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function yn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=Mt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Gr(e),e.personSummary=zr(e),e.personAutoTags=Kr(e);let n=Qr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=Zr(e)),e}function Gr(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function zr(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${Ge(o,40)} at ${Ge(s,30)}`):o?t.push(Ge(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${c[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${Ge(e.lastJobTitle,30)}`,e.lastJobDate){let c=new Date(e.lastJobDate);isNaN(c)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][c.getMonth()]} ${c.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function Kr(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=Xo("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function Qr(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${hn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function Zr(e){let t=e.category;if(!t)return null;let n=Xr(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function Xr(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var Go,Yo,wn=de(async()=>{await nt();await Je();Go={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};Yo=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var Ss={};ae(Ss,{extractCertificationsFromDetails:()=>nl,extractEducationFromDetails:()=>el,extractExperienceFromDetails:()=>Zi,extractFeaturedFromDetails:()=>Xi,extractRecommendationsFromDetails:()=>ol,extractSkillsFromDetails:()=>tl});async function Zi(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)s++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function r(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(g=>g.tagName==="DIV");if(m.length<3)continue;let y=m.filter(g=>(g.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let c=r(i);if(!c)return[];let l=Array.from(c.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function a(u){let f=u[0]||null,d=null,m=null;if(u[1]){let x=u[1].split("\xB7").map(D=>D.trim());d=x[0]||null,x[1]&&(m=x[1])}let y=u.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),g=null,b=null;if(y>=0){let x=u[y].split("\xB7").map(D=>D.trim());g=x[0]||null,x[1]&&(b=x[1])}let w=null,S=-1;if(y>=0&&u[y+1]){let x=u[y+1],D=/^[>*\-•]|^&gt;/.test(x),G=/https?:\/\//.test(x),$=/\d{4}/.test(x),A=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!D&&!G&&!$&&x.length<100&&A&&(w=x,S=y+1)}let h=null,p=-1,v=u[u.length-1];if(v&&/and\s+\+\d+\s+skills?$/i.test(v)){p=u.length-1;let x=v.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(h={listed:x[1].split(",").map(D=>D.trim()),additional:parseInt(x[2],10)})}let C=new Set([0,1,y,S,p].filter(x=>x>=0)),_=u.filter((x,D)=>!C.has(D)),R=_.length>0?_.join(`
1
+ var Hs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{for(var n in t)Hs(e,n,{get:t[n],enumerable:!0})};function tt(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function Gt(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let a=tt(n),l=new Date(t);return a?l.setHours(a.hours,a.minutes,0,0):l.setHours(0,0,0,0),l.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let a=Js[o[1].toLowerCase()],l=tt(o[2]||""),c=new Date(t),f=c.getDay()-a;return f<=0&&(f+=7),c.setDate(c.getDate()-f),l?c.setHours(l.hours,l.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let a=Yt[s[1].toLowerCase().slice(0,3)];if(a===void 0)return null;let l=parseInt(s[2],10),c=parseInt(s[3],10),u=tt(s[4]||"");return new Date(c,a,l,u?.hours||0,u?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let a=Yt[i[1].toLowerCase().slice(0,3)];if(a===void 0)return null;let l=parseInt(i[2],10),c=tt(i[3]||""),u=t.getFullYear(),f=new Date(u,a,l,c?.hours||0,c?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(r){let a=Yt[r[1].toLowerCase().slice(0,3)];if(a===void 0)return null;let l=parseInt(r[2],10),c=tt(r[3]||""),u=t.getFullYear(),f=new Date(u,a,l,c?.hours||0,c?.minutes||0,0,0);return f>t&&f.setFullYear(u-1),f.toISOString()}return null}async function $(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function nt(e,t,{timeout:n=45e3,poll:o=1e3,label:s="page"}={}){let i=Date.now();for(;Date.now()-i<n;){try{if(await e.evaluate(a=>!!document.querySelector(a),t)){let a=Date.now()-i;return a>6e3&&console.log(` (waited ${Math.round(a/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(r=>setTimeout(r,o))}return!1}async function Gn(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");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 $(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}async function xe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),r=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),a=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||r||a){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:s.substring(0,80)};let c=o.querySelectorAll("button");for(let u of c){let f=u.innerText?.trim().toLowerCase()||"",d=u.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return u.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}function zn(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 Kn(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()}var Yt,Js,Fe=de(()=>{Yt={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Js={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});import{getPluginConfig as Vs}from"@ilivemylife/graph-sdk";var Ws,z,J,ot,Ue,st=de(async()=>{Ws=await Vs();for(let[e,t]of Object.entries(Ws))process.env[e]===void 0&&(process.env[e]=t);z=process.env.LINKEDIN_NAME,J=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ot=Object.freeze(new Set([J.DRAFT,J.CONFIRMED,J.NEEDS_REVIEW])),Ue=Object.freeze(new Set([J.DRAFT,J.CONFIRMED,J.REJECTED,J.NEEDS_REVIEW]))});import"dotenv/config";import*as F from"fs";import*as q from"path";import{fileURLToPath as Ys}from"url";import{execSync as zt}from"child_process";function so(){qe=null,Ks=null,fe=null,_e=null,Be=null,Ee=null}function me(){F.existsSync(X)||F.mkdirSync(X,{recursive:!0})}function Je(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";F.writeFileSync(o,n);for(let s=0;s<3;s++)try{F.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function lt(e,t){if(!F.existsSync(e))return null;try{let n=JSON.parse(F.readFileSync(e,"utf-8"));try{F.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${q.resolve(e)}`);let o=e+".backup";if(F.existsSync(o))try{let s=JSON.parse(F.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{F.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{F.copyFileSync(e,e+".corrupted")}catch{}return null}}function at(){return new Date().toISOString().split("T")[0]}function Te(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Zn(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function He(e,t,n=null){if(!t||e[t])return t;let o=Te(t);if(!o)return t;let s=null;for(let[i,r]of Object.entries(e)){if(Te(r.profileUrl||i)===o)return i;!s&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}if(s){let i=Zn(n),r=Zn(e[s].name);if(i&&r&&i===r)return s}return t}function Xs(){F.existsSync(Qt)||F.mkdirSync(Qt,{recursive:!0})}function ro(e){let t=Te(e);return t?q.join(Qt,`${t}.json`):null}function er(e){let t=ro(e);return t?lt(t,`profile-history/${Te(e)}.json`)||[]:[]}function tr(e,t){let n=ro(e);if(!n)return;Xs();let o=er(e);o.unshift(t);try{Je(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Te(e)}: ${s.message}`)}}function Xn(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function eo(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function nr(e,t){if(!e)return[];let n=[];for(let o of Zs){let s=e[o],i=t[o];Xn(s)||Xn(i)||eo(s)!==eo(i)&&n.push(o)}return n}function or(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function H(){return qe||(me(),qe=lt(Kt,"people.json")||{},qe)}function Ie(e){me(),qe=e;try{Je(Kt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${q.resolve(Kt)}`)}}function ct(){return _e||(me(),_e=lt(_t,"conversations.json")||{},sr(_e),_e)}function sr(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(i=>i.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Je(_t,e)}catch{}}}function we(e){me(),_e=e;try{Je(_t,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${q.resolve(_t)}`)}}function Re(e,t={}){if(!e)return null;let n=H(),o=at(),s=new Date().toISOString(),i=He(n,e,t.name),r=n[i];if(r){let a=nr(r,t);a.length>0&&(tr(i,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:a,snapshot:or(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let l of Qs)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(r[l])&&r[l].length>0)continue;r[l]=t[l]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Ie(n),n[i]}function io(e,t){if(!e||!t)return;let n=H(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:at(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(a=>a.date===i.date&&a.source===i.source&&a.action===i.action&&(a.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Ie(n))}function lo(e){return e&&H()[e]?.connectionStatus||null}function ao(e,t,n={}){if(!e)return;if(n.profileInfo)Re(e,n.profileInfo);else{let a=H(),l=He(a,e,n.profileInfo?.name);a[l]||Re(e,{})}let o=H(),s=He(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let r=at();i.connectionStatus=t,t==="connected"?i.connectionDate=r:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=r)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Ie(o)}function Tt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=Te(t);if(!o)return;let s=H(),i=He(s,e),r=s[i];if(!r)return;let a=Te(r.profileUrl||i);o!==a&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(o)||(r.aliases.push(o),r.lastUpdated=new Date().toISOString(),Ie(s)))}function co(){return fe||(me(),fe=lt(to,"quota.json"),(!fe||!fe.connections)&&(fe={connections:[]}),fe)}function rr(e){me(),fe=e;try{Je(to,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function uo(e,t="unknown"){let n=co(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),rr(n)}function fo(){let e=co(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Zt(){let e=fo(),t=at(),n=e.filter(l=>l.date===t).length,o=e.length,s=n>=rt,i=o>=it,r=!s&&!i,a={allowed:r,daily:{sent:n,max:rt},weekly:{sent:o,max:it}};return r||(a.reason=s?`Daily limit reached (${n}/${rt})`:`Weekly limit reached (${o}/${it})`),a}function ut(){let e=fo(),t=at(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:rt,remaining:rt-n},weekly:{sent:o,max:it,remaining:it-o}}}function Xt(){return Be||(me(),Be=lt(no,"sync-state.json")||{},Be)}function mo(e){me(),Be=e;try{Je(no,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function ir(){if(Ee)return Ee;me();try{F.existsSync(Qn)&&(Ee=JSON.parse(F.readFileSync(Qn,"utf-8")))}catch{}return Ee||(Ee={}),Ee}function lr(e){return Array.isArray(e.applications)}function ar(){let e=ir();if(lr(e))return e.applications;let t=[];for(let n of Object.values(e))n.applications&&t.push(...n.applications);return t}function po(){let e=ar(),t=new Map;for(let i of e)for(let r of i.questions||[]){let a=r.question.toLowerCase().trim();if(!a)continue;t.has(a)||t.set(a,{question:r.question,count:0,answers:new Map});let l=t.get(a);l.count++;let c=(r.answer||"").trim();l.answers.set(c,(l.answers.get(c)||0)+1)}let n=[...t.values()].sort((i,r)=>r.count-i.count),o=n.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((r,a)=>a[1]-r[1])[0]?.[0]||""})),s=n.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((r,a)=>a[1]-r[1]).map(([r,a])=>`${r} (${a}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:o,inconsistent:s}}function en(e){if(F.existsSync(q.join(X,".git")))try{let t={cwd:X,stdio:"pipe",timeout:1e4};zt("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json connect-queue.json",t);try{zt("git diff --cached --quiet",t);return}catch{}let n=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');zt(`git commit -m "${n}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Gs,zs,X,Kt,ql,to,_t,no,Qn,Qt,oo,rt,it,qe,Ks,fe,_e,Be,Ee,Qs,Zs,Ve=de(async()=>{await st();Gs=Ys(import.meta.url),zs=q.dirname(q.dirname(Gs)),X=process.env.DATA_DIR?q.resolve(process.env.DATA_DIR,"collected-profiles"):q.join(zs,"collected-profiles"),Kt=q.join(X,"people.json"),ql=q.join(X,"jobs.json"),to=q.join(X,"quota.json"),_t=q.join(X,"conversations.json"),no=q.join(X,"sync-state.json"),Qn=q.join(X,"application-questions.json"),Qt=q.join(X,"profile-history"),oo=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},rt=oo(process.env.CONNECT_MAX_DAILY,20),it=oo(process.env.CONNECT_MAX_WEEKLY,100),qe=null,Ks=null,fe=null,_e=null,Be=null,Ee=null;Qs=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],Zs=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var wo={};ae(wo,{BLOCK_MARKERS:()=>go,dedupeAndCap:()=>yo,extractSidePanelProfiles:()=>cr,normalizeFundUrl:()=>Rt,normalizeProfileUrl:()=>We,scanRelatedBlocks:()=>ho});function We(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let n=t[1].trim();return n?`https://www.linkedin.com/in/${n}/`:null}function Rt(e){return!e||typeof e!="string"?null:e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/[?#].*$/,"").replace(/\/+$/,"")||null}function ho(e,t){let n=t||(typeof document<"u"?document:null);if(!n)return[];let o=c=>(c||"").replace(/\s+/g," ").trim(),s=c=>{let u=String(c||"").match(/\/in\/([^/?#]+)/i);return u?u[1].toLowerCase():null},i=c=>o(c).replace(/^View\s+/i,"").split(/\s+[·•]\s*/)[0].replace(/[’'`]s profile.*$/i,"").replace(/\bstatus is (online|offline|reachable)\b/i,"").trim(),r=c=>{let u=c,f=null;for(let d=0;d<6&&u.parentElement;d++)if(u=u.parentElement,u.querySelectorAll('a[href*="/in/"]').length>=2){f||(f=u);let m=(u.className||"").toString();if(u.tagName==="SECTION"||u.tagName==="UL"||/artdeco-card/.test(m))return u}return f||c.parentElement},a=[],l=Array.from(n.querySelectorAll("h2, h3, header, .artdeco-card__title"));for(let c of l){let u=o(c.textContent).toLowerCase();if(!u)continue;let f=e.find(([w])=>u.includes(w));if(!f)continue;let d=f[1],m=r(c);if(!m)continue;let y=0,p=new Set;for(let w of Array.from(m.querySelectorAll('a[href*="/in/"]'))){let v=w.href||w.getAttribute("href")||"",S=s(v);if(!S)continue;let g=w.querySelector('span[aria-hidden="true"]'),h=o(g?g.textContent:w.getAttribute("aria-label")||w.textContent),b=i(h);if(!b||p.has(S))continue;p.add(S);let k="",T=h.match(/[·•]\s*(?:1st|2nd|3rd)\s*(.+)$/i);if(T&&(k=o(T[1])),!k){let I=w.closest("li")||w.parentElement;I&&(k=Array.from(I.querySelectorAll("p, span")).map(R=>o(R.textContent)).filter(R=>R&&R!==b&&!/^view\b/i.test(R)&&!/^[·•\s]*(1st|2nd|3rd)\b/i.test(R)&&/[a-z]/i.test(R)&&R.length>2)[0]||"")}a.push({href:v,name:b,headline:k,block:d,rank:y++})}}return a}function yo(e,t={}){let n=Number.isInteger(t.perBlockCap)?t.perBlockCap:10,o=We(t.seedUrl||""),s=new Map,i={};for(let r of e||[]){let a=We(r.href);a&&(o&&a===o||(i[r.block]=i[r.block]||0,!(i[r.block]>=n)&&(s.has(a)||(i[r.block]++,s.set(a,{url:a,name:r.name,headline:r.headline||null,block:r.block,rank:r.rank})))))}return Array.from(s.values())}async function cr(e,t={}){try{await e.evaluate(()=>window.scrollTo(0,Math.floor(document.body.scrollHeight*.6))),await new Promise(o=>setTimeout(o,1200)),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(o=>setTimeout(o,1200))}catch{}let n;try{n=await e.evaluate(ho,go)}catch{return[]}return yo(n,t)}var go,tn=de(()=>{go=[["people also viewed","people_also_viewed"],["more profiles for you","more_profiles_for_you"],["people you may know","people_you_may_know"],["who your viewers also viewed","viewers_also_viewed"],["other profiles you may know","other_profiles"],["similar profiles","similar_profiles"]]});var Co={};ae(Co,{getJobDecision:()=>gr,getLastVisit:()=>$r,getScoutStats:()=>ln,loadCompanies:()=>rn,loadDiscoveredPeople:()=>wt,loadJobDecisions:()=>yt,loadScoutedJobs:()=>ht,loadVisitLog:()=>Ot,recordCompany:()=>Sr,recordDiscoveredEdge:()=>wr,recordDiscoveredEdges:()=>br,recordVisit:()=>kr,resetCaches:()=>sn,saveCompany:()=>vr,saveDiscoveredPerson:()=>hr,saveScoutedJob:()=>mr,setJobDecision:()=>pr});import"dotenv/config";import*as ee from"fs";import*as K from"path";import{fileURLToPath as ur}from"url";function be(){ee.existsSync(Oe)||ee.mkdirSync(Oe,{recursive:!0})}function Se(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let s=0;s<3;s++)try{ee.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function gt(e){try{if(ee.existsSync(e))return JSON.parse(ee.readFileSync(e,"utf-8"))}catch{}return null}function sn(){dt=null,ft=null,mt=null,pt=null,De=null}function ht(){return dt||(dt=gt(bo)||{},dt)}function mr(e,t){if(!e)return;be();let n=ht(),o=new Date().toISOString().slice(0,10);if(n[e]){for(let[s,i]of Object.entries(t))i!=null&&(n[e][s]=i);n[e].lastSeen=o}else n[e]={...t,scoutedAt:o,lastSeen:o};try{Se(bo,n)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function yt(){return ft||(ft=gt(vo)||{},ft)}function pr(e,t,n={}){if(!e||!t)return;be();let o=yt(),s=new Date().toISOString().slice(0,10);o[e]?(o[e].status=t,o[e].updatedAt=s,n.reason&&(o[e].reason=n.reason),n.score!=null&&(o[e].score=n.score),n.source&&(o[e].source=n.source)):o[e]={status:t,decidedAt:s,updatedAt:s,reason:n.reason||null,score:n.score??null,source:n.source||null};try{Se(vo,o)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function gr(e){return yt()[e]||null}function wt(){return mt||(mt=gt(Dt)||{},mt)}function Ye(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function ko(e,t){let n=We(t)||t;if(e[n])return n;let o=Ye(t);if(!o)return n;let s=null;for(let[i,r]of Object.entries(e)){if(Ye(r&&(r.canonicalUrl||r.profileUrl)||i)===o)return i;!s&&r&&Array.isArray(r.aliases)&&r.aliases.includes(o)&&(s=i)}return s||n}function hr(e,t){if(!e)return;be();let n=wt(),o=new Date().toISOString().slice(0,10),s=ko(n,e),i=Ye(e);if(n[s]){let r=n[s];t.name&&(r.name=t.name),t.title&&(r.title=t.title),t.company&&(r.company=t.company),t.location&&(r.location=t.location),t.role&&(r.role=t.role),t.isConnected!=null&&(r.isConnected=t.isConnected),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),i&&Ye(r.canonicalUrl||r.profileUrl||s)!==i&&(Array.isArray(r.aliases)||(r.aliases=[]),r.aliases.includes(i)||r.aliases.push(i)),r.lastSeen=o,r.seenCount=(r.seenCount||1)+1}else n[s]={canonicalUrl:s,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:o,lastSeen:o,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{Se(Dt,n)}catch(r){console.error(`[!] Failed to save discovered-people.json: ${r.message}`)}}function yr(e,t){let n=e.kind||"similar-panel";return n==="list-post"?{edge:{kind:n,postUrl:e.postUrl||null,curator:e.curator||null,fund:e.fund||null,fundUrl:e.fundUrl||null,context:e.context||null,at:t},match:o=>o.kind==="list-post"&&o.postUrl===(e.postUrl||null)&&o.fund===(e.fund||null)}:n==="scout"?{edge:{kind:n,jobId:e.jobId||null,jobTitle:e.jobTitle||null,at:t},match:o=>o.kind==="scout"&&o.jobId===(e.jobId||null)}:{edge:{kind:"similar-panel",seedUrl:e.seedUrl||null,seedName:e.seedName||null,block:e.block||"unknown",rank:Number.isInteger(e.rank)?e.rank:null,at:t},match:o=>o.kind!=="list-post"&&o.kind!=="scout"&&o.seedUrl===(e.seedUrl||null)&&o.block===(e.block||"unknown")}}function $o(e,t,n={},o){if(!t)return;let s=Ye(t);t=ko(e,t);let i=n.seedUrl?{...n,seedUrl:We(n.seedUrl)||n.seedUrl}:n,r=o.slice(0,10),{edge:a,match:l}=yr(i,o),c=e[t];c||(c=e[t]={canonicalUrl:t,aliases:[],name:n.name||null,headline:n.headline||null,location:n.location||null,company:n.company||null,companyUrl:n.companyUrl||null,categories:[],sectors:[],affiliations:[],discoveredVia:a.kind,sources:[],connectionsCount:n.connectionsCount??null,selectivity:n.selectivity||"unknown",connectGate:n.connectGate||"unknown",score:null,fitScore:null,isConnected:n.isConnected||!1,graphRefs:[],note:n.note||"",whyUseful:n.whyUseful||"",extra:{},source:a.kind,role:Array.isArray(n.categories)&&n.categories[0]||null,jobIds:[],seenCount:0,discoveredAt:r,firstSeen:r,lastSeen:r}),n.name&&(c.name=n.name),n.headline&&(!c.headline||/^[·•\s]*(1st|2nd|3rd)\b/i.test(c.headline))&&(c.headline=n.headline),n.location&&(c.location=c.location||n.location),n.company&&(c.company=n.company),n.companyUrl&&(c.companyUrl=c.companyUrl||n.companyUrl),n.isConnected!=null&&(c.isConnected=n.isConnected),n.connectionsCount!=null&&(c.connectionsCount=n.connectionsCount),n.selectivity&&n.selectivity!=="unknown"&&(c.selectivity=n.selectivity),n.connectGate&&n.connectGate!=="unknown"&&(c.connectGate=n.connectGate),n.note&&!c.note&&(c.note=n.note),n.whyUseful&&!c.whyUseful&&(c.whyUseful=n.whyUseful),n.extra&&typeof n.extra=="object"&&(c.extra={...c.extra||{},...n.extra}),Array.isArray(c.sources)||(c.sources=[]);let u=c.sources.find(l);if(u?(a.rank!=null&&(u.rank==null||a.rank<u.rank)&&(u.rank=a.rank),u.at=a.at):c.sources.push(a),Array.isArray(c.categories)||(c.categories=[]),Array.isArray(c.sectors)||(c.sectors=[]),Array.isArray(c.aliases)||(c.aliases=[]),Array.isArray(c.graphRefs)||(c.graphRefs=[]),nn(c.categories,n.category),It(c.categories,n.categories),It(c.sectors,n.sectors),It(c.aliases,n.aliases),s&&Ye(c.canonicalUrl||t)!==s&&nn(c.aliases,s),It(c.graphRefs,n.graphRefs),Array.isArray(n.affiliations)){Array.isArray(c.affiliations)||(c.affiliations=[]);for(let f of n.affiliations)!f||!f.companyKey||c.affiliations.some(d=>d.companyKey===f.companyKey&&d.role===f.role)||c.affiliations.push(f)}c.lastSeen=r,c.seenCount=(c.seenCount||0)+1}function wr(e,t={}){if(!e)return;be();let n=wt();$o(n,e,t,new Date().toISOString());try{Se(Dt,n)}catch(o){console.error(`[!] Failed to save discovered-people.json: ${o.message}`)}}function br(e){if(!Array.isArray(e)||e.length===0)return;be();let t=wt(),n=new Date().toISOString(),o=0;for(let s of e)!s||!s.url||($o(t,s.url,s,n),o++);if(o)try{Se(Dt,t)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function Sr(e={}){if(!e||!e.name)return;be();let t=e.key||Rt(e.website)||Rt(e.linkedinUrl)||`name:${String(e.name).trim().toLowerCase()}`,n=rn(),o=new Date().toISOString().slice(0,10),s=(l,c)=>{c&&Array.isArray(l)&&!l.includes(c)&&l.push(c)},i=(l,c)=>{if(Array.isArray(c))for(let u of c)s(l,u)},r=n[t];r||(r=n[t]={key:t,aliases:[],name:e.name,website:e.website||null,linkedinUrl:e.linkedinUrl||null,kinds:[],sectors:[],people:[],theses:[],size:e.size||null,check:e.check||null,stage:e.stage||null,location:e.location||null,portfolio:[],industries:e.industries||null,about:e.about||null,jobIds:[],recruiterUrls:[],jobCount:0,fromPosts:[],graphRefs:[],note:e.note||"",whyUseful:e.whyUseful||"",fitScore:e.fitScore??null,extra:{},seenCount:0,firstSeen:o,lastSeen:o}),e.name&&(r.name=e.name),e.website&&(r.website=r.website||e.website),e.linkedinUrl&&(r.linkedinUrl=r.linkedinUrl||e.linkedinUrl);for(let l of["size","check","stage","location","industries","about"])e[l]&&!r[l]&&(r[l]=e[l]);e.note&&!r.note&&(r.note=e.note),e.whyUseful&&!r.whyUseful&&(r.whyUseful=e.whyUseful),e.fitScore!=null&&(r.fitScore=e.fitScore),e.extra&&typeof e.extra=="object"&&(r.extra={...r.extra||{},...e.extra});for(let l of["aliases","kinds","sectors","theses","fromPosts","graphRefs","jobIds","recruiterUrls"])Array.isArray(r[l])||(r[l]=[]),i(r[l],e[l]);Array.isArray(r.people)||(r.people=[]);let a=l=>{if(!l||!l.url)return;let c=r.people.find(u=>u.url===l.url&&(u.role||null)===(l.role||null));c?l.current!=null&&(c.current=l.current):r.people.push({url:l.url,name:l.name||null,role:l.role||null,current:l.current??null,from:l.from??null,to:l.to??null})};(e.people||[]).forEach(a),(e.partners||[]).forEach(l=>a({url:l.url,name:l.name,role:"Partner",current:!0})),Array.isArray(r.portfolio)||(r.portfolio=[]);for(let l of e.portfolio||[]){let c=l&&(l.key||l.name);c&&!r.portfolio.some(u=>(u.key||u.name)===c)&&r.portfolio.push(l)}r.lastSeen=o,r.seenCount=(r.seenCount||0)+1;try{Se(on,n)}catch(l){console.error(`[!] Failed to save companies.json: ${l.message}`)}return t}function rn(){return pt||(pt=gt(on)||{},pt)}function vr(e,t){if(!e)return;be();let n=rn(),o=new Date().toISOString().slice(0,10);if(n[e]){let s=n[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=o,s.jobCount=s.jobIds?.length||0}else n[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:o,lastSeen:o,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{Se(on,n)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function Ot(){return De||(De=gt(So)||{visits:[]},Array.isArray(De.visits)||(De.visits=[]),De)}function kr(e,t={}){if(!e)return;be();let n=Ot();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{Se(So,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function $r(e){let t=Ot();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function ln(){let e=ht(),t=wt(),n=Object.values(e),o=Object.values(t),s={};for(let d of n)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,m)=>m[1]-d[1]).slice(0,5).map(([d,m])=>`${d} (${m})`),r={};for(let d of n)for(let m of d.techStack||[])r[m]=(r[m]||0)+1;let a=Object.entries(r).sort((d,m)=>m[1]-d[1]).slice(0,8).map(([d,m])=>`${d} (${m})`),l=Ot(),c=new Date().toISOString().slice(0,10),u=l.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(l.visits.map(d=>d.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:i,topTech:a,totalVisited:f,todayVisited:u,lastScoutDate:n.length>0?n.sort((d,m)=>(m.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var dr,fr,Oe,bo,Dt,So,on,vo,dt,ft,mt,nn,It,pt,De,bt=de(()=>{tn();dr=ur(import.meta.url),fr=K.dirname(K.dirname(dr)),Oe=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"market-research"):K.join(fr,"market-research"),bo=K.join(Oe,"scouted-jobs.json"),Dt=K.join(Oe,"discovered-people.json"),So=K.join(Oe,"visit-log.json"),on=K.join(Oe,"companies.json"),vo=K.join(Oe,"job-decisions.json");dt=null;ft=null;mt=null;nn=(e,t)=>{t&&Array.isArray(e)&&!e.includes(t)&&e.push(t)},It=(e,t)=>{if(Array.isArray(t))for(let n of t)nn(e,n)};pt=null;De=null});var ss={};ae(ss,{computeEngagement:()=>yn,detectCategory:()=>Qo,detectCategoryFromTitle:()=>jt,determineAction:()=>ns,determineLastMessageBy:()=>Ft,determineSituation:()=>Zo,enrichConversation:()=>Lt,enrichPerson:()=>bn,enrichPersonContext:()=>os,extractAutoTags:()=>es,generateSummary:()=>Xo,normPreview:()=>Ke});function Lt(e,t,n){if(!e)return e;let s=(e.messages||[]).filter(l=>!Ue.has(l.status)),i=Wr(t,e.profileUrl,n),r=Ft(s,t);if(e.lastMessageBy=r,e.conversationStatus=r==="me"?"awaiting_reply":"unanswered_by_us",e.categorySource!=="manual"){let l=Qo(s,t,i);l&&(e.category=l,e.categorySource=e.categorySource||"message_content")}if(e.situation=Zo(s,r,t),s.length>0){let l=s[s.length-1];e.lastMessageTime=l.time}if(s.length>0&&!e.initiatedBy){let l=s[0];l.sender===z?e.initiatedBy="us":l.sender!=="Unknown"&&l.sender!==""&&(e.initiatedBy="them")}e.engagement=yn(s,t),e.personContext=os(i),e.summary=Xo(e,t,i),e.autoTags=es(e,t,i);let a=ns(e);return e.actionNeeded=a.action,e.actionDetail=a.detail,e.suggestedPriority=Vr(e),e}function Qo(e,t,n){if(!e||e.length===0)return n?.title?jt(n.title):null;let o=e.filter(s=>s.sender!==z&&s.sender!=="Unknown"&&s.sender!=="").map(s=>s.text).join(" ");for(let[s,i]of Object.entries(Ko))if(i.theirMessages){for(let r of i.theirMessages)if(r.test(o))return s}if(n?.title){let s=jt(n.title);if(s)return s}return null}function jt(e){if(!e)return null;for(let[t,n]of Object.entries(Ko))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}function Zo(e,t,n){if(!e||e.length===0)return"no_messages";let o=e[e.length-1];if(e.length===1)return t==="them"?"initial_outreach_unanswered":"we_initiated_waiting";if(t==="me")return zo.test(o.text)?"scheduling_proposed_by_us":e.length>=6?"active_conversation_ball_in_their_court":"awaiting_their_reply";let s=[...e].reverse().find(i=>i.sender!==z&&i.sender!=="Unknown");return zo.test(s?.text||"")?"they_want_to_schedule_call":e.length>=6?"active_conversation_needs_our_reply":"needs_our_reply"}function Ft(e,t){if(!e||e.length===0)return"them";let n=[...e].map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),o=n.length>0?n:[...e].reverse();for(let s of o){let i=s.sender;if(i===z)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}function Xo(e,t,n){let o=e.messages||[];if(o.length===0)return null;let s=[],i=e.category,r=n?.title,a=n?.company,l=n?.location;i==="recruiter"&&a?s.push(`Recruiter from ${a}`):i==="hiring_manager"&&a?s.push(`Hiring manager at ${a}`):i==="founder"&&a?s.push(`Founder of ${a}`):i&&r?s.push(`${wn(i)}: ${ze(r,40)}`):r?s.push(ze(r,50)):s.push(t.split(" ")[0]);let c=o.filter(y=>y.sender!==z&&y.sender!=="Unknown").map(y=>y.text).join(" "),u=Yr(c),f=Gr(c),d=zr(c),m=[];return u&&m.push(u),d&&d!==l&&m.push(d),f&&m.push(f),m.length>0&&s.push(m.join(", ")),e.situation==="they_want_to_schedule_call"?s.push("wants to schedule call"):e.situation==="scheduling_proposed_by_us"?s.push("we proposed scheduling"):e.conversationStatus==="unanswered_by_us"?s.push("needs reply"):e.conversationStatus==="awaiting_reply"&&s.push("waiting on them"),s.join(". ").replace(/\.\./g,".")}function es(e,t,n){let o=[],s=(e.messages||[]).filter(c=>!Ue.has(c.status)),i=s.map(c=>c.text).join(" "),r=s.filter(c=>c.sender!==z&&c.sender!=="Unknown").map(c=>c.text).join(" "),a=ts(r,n?.location);o.push(...a),/\b(contract|contractor|c2c|corp.?to.?corp)\b/i.test(i)&&o.push("contract"),/\b(full.?time|permanent|fte|perm)\b/i.test(i)&&o.push("full-time"),/\b(remote|work.?from.?home|wfh)\b/i.test(i)&&o.push("remote"),/\b(hybrid)\b/i.test(i)&&o.push("hybrid"),/\b(on.?site|in.?office|in.?person)\b/i.test(i)&&o.push("onsite"),/\b(java)\b/i.test(i)&&!/javascript/i.test(i)&&o.push("java"),/\b(python)\b/i.test(i)&&o.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(i)&&o.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(i)&&o.push("backend"),/\b(full.?stack)\b/i.test(i)&&o.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(i)&&o.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(i)&&o.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(i)&&o.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(i)&&o.push("management"),/\$[\d,]+|\d+k|\d+\/hr|\d+\s*per\s*(hour|annum|year)/i.test(i)&&o.push("has-salary");let l=e.engagement||yn(s,t);return l.messageCount>=6&&o.push("active-thread"),l.theirCount===0&&l.ourCount>0&&o.push("no-response"),l.ourCount===0&&l.theirCount>0&&o.push("unanswered"),e.situation==="they_want_to_schedule_call"&&o.push("hot-lead"),(e.messages||[]).some(c=>ot.has(c.status))&&o.push("has-draft"),[...new Set(o)]}function ts(e,t){let n=[],o=["toronto","vancouver","montreal","ottawa","calgary","edmonton","new york","san francisco","seattle","chicago","austin","boston","los angeles","denver","atlanta","dallas","houston","miami","london","berlin","amsterdam","dubai"],s=[["canada","canada"],["ontario","ontario"],["british columbia","bc"],["alberta","alberta"],["quebec","quebec"],["usa","usa"],["united states","usa"]],i=(e+" "+(t||"")).toLowerCase();for(let r of o)i.includes(r)&&n.push(r.replace(/\s+/g,"-"));for(let[r,a]of s)i.includes(r)&&n.push(a);return n}function ns(e){let{category:t,situation:n,conversationStatus:o}=e;if(e.dismissedAtPreview&&Ke(e.lastMessagePreview)===Ke(e.dismissedAtPreview))return{action:"none",detail:e.dismissReason||"Dismissed."};let s=(e.messages||[]).find(i=>ot.has(i.status));return s?s.status===J.CONFIRMED?{action:"push_draft",detail:"Draft confirmed. Run --push-drafts to send."}:{action:"review_draft",detail:"Draft needs review. Run --review-drafts."}:o==="awaiting_reply"?{action:"none",detail:"Ball in their court."}:n==="no_messages"?{action:"none",detail:"No messages read yet."}:n==="they_want_to_schedule_call"?{action:"schedule_call",detail:"They proposed a call. Reply with time slots."}:n==="initial_outreach_unanswered"?t==="spam"?{action:"archive",detail:"Likely spam. Safe to ignore."}:t==="recruiter"||t==="hiring_manager"?{action:"reply",detail:"New recruiter/HM message. Review and respond."}:t==="coach"||t==="sales"?{action:"archive",detail:`${wn(t||"unknown")} outreach. Likely not relevant.`}:{action:"reply",detail:"New message. Review and respond."}:n==="active_conversation_needs_our_reply"||n==="needs_our_reply"?{action:"reply",detail:"They replied. Continue the conversation."}:{action:"none",detail:""}}function yn(e,t){if(!e||e.length===0)return{messageCount:0,theirCount:0,ourCount:0,unknownCount:0,hasJob:!1,hasSalary:!1};let n=0,o=0,s=0,i=!1,r=!1,a=e.map(l=>l.text).join(" ");for(let l of e)l.sender===z?n++:l.sender==="Unknown"||l.sender===""?s++:o++;return i=/\b(job|role|position|opening)\b/i.test(a),r=/\$[\d,]+|\d+k|\d+\/hr/i.test(a),{messageCount:e.length,theirCount:o,ourCount:n,unknownCount:s,hasJob:i,hasSalary:r}}function os(e){return e?{title:e.title||null,company:e.company||null,location:e.location||null,connectionStatus:e.connectionStatus||null}:null}function Vr(e){let{category:t,situation:n,engagement:o}=e;return n==="they_want_to_schedule_call"?"high":(t==="recruiter"||t==="hiring_manager")&&(n==="active_conversation_needs_our_reply"||n==="needs_our_reply")?o?.messageCount>=4?"high":"medium":t==="recruiter"&&n==="initial_outreach_unanswered"||t==="founder"&&e.conversationStatus==="unanswered_by_us"?"medium":t==="spam"||t==="coach"||t==="sales"?"low":e.conversationStatus==="unanswered_by_us"?"medium":null}function Wr(e,t,n){if(!n)return null;if(t&&n[t])return n[t];if(t){let s=He(n,t,e);if(n[s])return n[s]}if(!e)return null;let o=Object.values(n).filter(s=>s.name===e);return o.length===1?o[0]:null}function Ke(e){return(e||"").replace(/\s+/g," ").trim().slice(0,80).toLowerCase()}function wn(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}function ze(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Yr(e){let t=e.match(/\b((?:senior |sr\.? |lead |staff |principal |junior |jr\.? )?(?:software|full.?stack|front.?end|back.?end|data|devops|cloud|platform|mobile|ios|android|qa|sdet)\s*(?:engineer|developer|architect|lead|manager|scientist))\b/i);if(t)return t[1];let n=e.match(/\b((?:java|python|react|node|\.net|golang|rust|scala)\s*developer)\b/i);return n?n[1]:null}function Gr(e){let t=e.match(/\$[\d,]+(?:k|K)?(?:\s*[-–]\s*\$?[\d,]+(?:k|K)?)?(?:\s*\/\s*(?:hr|hour|yr|year|annum))?/);return t?t[0]:null}function zr(e){let t=e.match(/\b(?:in|based in|located in)\s+([A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:,\s*[A-Z]{2})?)/);return t?t[1]:null}function bn(e,t){if(!e)return e;if(e.categorySource!=="manual"){let o=jt(e.title);o&&(e.category=o,e.categorySource=e.categorySource||"title")}Kr(e),e.personSummary=Qr(e),e.personAutoTags=Zr(e);let n=Xr(e);return e.personActionNeeded=n.action,e.personActionDetail=n.detail,e.personPriorityManual||(e.personPriority=ei(e)),e}function Kr(e){if(e.jobCount=e.jobIds?.length||0,e.encounterCount=e.encounters?.length||0,e.encounters?.length>0){let t=e.encounters.filter(n=>n.jobTitle).sort((n,o)=>(o.date||"").localeCompare(n.date||""));t.length>0&&(e.lastJobTitle=t[0].jobTitle,e.lastJobCompany=t[0].jobCompany||null,e.lastJobDate=t[0].date)}e.isRepeatRecruiter=e.jobCount>=3}function Qr(e){let t=[],n=e.category,o=e.title,s=e.company,i=e.location;if(n==="recruiter"&&s?t.push(`Recruiter at ${s}`):n==="hiring_manager"&&s?t.push(`Hiring manager at ${s}`):n==="founder"&&s?t.push(`Founder of ${s}`):o&&s?t.push(`${ze(o,40)} at ${ze(s,30)}`):o?t.push(ze(o,50)):e.name&&t.push(e.name.split(" ")[0]),i&&t.push(i),e.connectionDate){let r=new Date(e.connectionDate);if(!isNaN(r)){let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.push(`Connected ${a[r.getMonth()]} ${r.getDate()}`)}}if(e.jobCount>0){let r=`${e.jobCount} job${e.jobCount>1?"s":""}`;if(e.lastJobTitle){if(r+=` (last: ${ze(e.lastJobTitle,30)}`,e.lastJobDate){let a=new Date(e.lastJobDate);isNaN(a)||(r+=`, ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]} ${a.getDate()}`)}r+=")"}t.push(r)}return t.join(". ").replace(/\.\./g,".")||null}function Zr(e){let t=[],n=[e.title,e.company,e.location].filter(Boolean).join(" "),o=ts("",e.location);return t.push(...o),e.category&&t.push(e.category),/\b(java)\b/i.test(n)&&!/javascript/i.test(n)&&t.push("java"),/\b(python)\b/i.test(n)&&t.push("python"),/\b(react|angular|vue|front.?end)\b/i.test(n)&&t.push("frontend"),/\b(node|backend|back.?end|api|microservice)\b/i.test(n)&&t.push("backend"),/\b(full.?stack)\b/i.test(n)&&t.push("fullstack"),/\b(devops|sre|cloud|aws|azure|gcp|kubernetes|k8s)\b/i.test(n)&&t.push("devops"),/\b(data.?engineer|data.?scien|ml|machine.?learn|ai)\b/i.test(n)&&t.push("data/ml"),/\b(lead|senior|staff|principal|architect)\b/i.test(n)&&t.push("senior-role"),/\b(manager|director|vp|head of)\b/i.test(n)&&t.push("management"),/\b(staffing|agency|consulting|outsourc)\b/i.test(n)&&t.push("staffing"),[...new Set(t)]}function Xr(e){if(e.connectionStatus!=="connected")return{action:"none",detail:"Not connected."};let t=e.category;return t==="recruiter"||t==="hiring_manager"?{action:"initiate_contact",detail:`New ${t.replace("_"," ")} connection. Send intro message.`}:t==="founder"?{action:"initiate_contact",detail:"Founder connection. Consider reaching out."}:t==="sales"||t==="coach"||t==="spam"?{action:"none",detail:`${wn(t)} \u2014 no outreach needed.`}:t==="investor"?{action:"initiate_contact",detail:"Investor connection. Consider intro message."}:{action:"none",detail:"No specific action identified."}}function ei(e){let t=e.category;if(!t)return null;let n=ti(e,7);return e.isRepeatRecruiter&&(t==="recruiter"||t==="hiring_manager")||(t==="recruiter"||t==="hiring_manager")&&n?"high":t==="recruiter"||t==="hiring_manager"||t==="founder"&&n?"medium":t==="founder"||t==="investor"?"low":t==="sales"||t==="coach"||t==="spam"?null:t==="peer"?"low":null}function ti(e,t){if(!e.connectionDate)return!1;let n=new Date(e.connectionDate);if(isNaN(n))return!1;let o=new Date;return o.setDate(o.getDate()-t),n>=o}var Ko,zo,Sn=de(async()=>{await st();await Ve();Ko={recruiter:{theirMessages:[/\b(recruiter|recruiting|talent.?acqui|staffing|headhunter|head\s*hunter|sourcer|executive\s*search)\b/i],title:[/\b(recruiter|recruiting|talent.?acqui|staffing|sourcer|sourcing)\b/i,/\b(head\s*hunter|executive\s*search)\b/i]},hiring_manager:{theirMessages:[/\b(my|our)\s+team\b/i,/\b(i.?m|we.?re|i\s+am|we\s+are)\s+(currently\s+|actively\s+|now\s+)?(looking|hiring|recruiting)\b/i,/\bjoin\s+(my|our)\b/i,/\bdirect.?report/i,/\b(engineering manager|team lead|vp of|director of|head of)\b/i],title:[/\b(engineering manager|team lead|vp|director|head of engineering)\b/i]},founder:{theirMessages:[/\b(founder|co-founder|ceo|cto|my company|my startup|i.?m building)\b/i],title:[/\b(founder|co-founder|ceo|cto)\b/i]},investor:{theirMessages:[/\b(investor|invest|funding|vc|venture|angel)\b/i],title:[/\b(investor|venture|capital|angel|partner at)\b/i,/\binvestment\s+(manager|partner|director|associate|analyst|principal)\b/i]},coach:{theirMessages:[/\b(coach|coaching|mentor|mentoring|career.?(advice|guidance|help))\b/i,/\b(resume.?(review|writing)|interview.?prep|career.?transition)\b/i],title:[/\b(coach|mentor|career.?(consultant|advisor))\b/i]},peer:{theirMessages:[/\b(fellow|peer|networking|connect|nice.?to.?meet|great.?to.?connect)\b/i,/\b(your (profile|background|experience).*interest)\b/i]},sales:{theirMessages:[/\b(sales|business develop|partnership|proposal|offer|demo|pricing|platform|solution)\b/i],title:[/\b(sales|business develop|account.?exec|bdm|bdr|sdr)\b/i]},spam:{theirMessages:[/\b(crypto|bitcoin|forex|trading.?signal|guaranteed.?return|make.?money)\b/i,/\b(whatsapp|telegram.?group|click (here|this link))\b/i]},event:{theirMessages:[/\b(event|conference|webinar|summit|meetup|workshop|speak(er|ing))\b/i,/\b(attend|register|rsvp|invitation|invite.?you)\b/i]}};zo=/\b(call|meet|teams|zoom|schedule|available|availability|invite|slot|calendar)\b/i});var ks={};ae(ks,{extractCertificationsFromDetails:()=>sl,extractEducationFromDetails:()=>nl,extractExperienceFromDetails:()=>el,extractFeaturedFromDetails:()=>tl,extractRecommendationsFromDetails:()=>rl,extractSkillsFromDetails:()=>ol});async function el(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(900);await $(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)s++,await $(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function r(u){let f=[];for(let d of u.querySelectorAll("div")){let m=Array.from(d.children).filter(p=>p.tagName==="DIV");if(m.length<3)continue;let y=m.filter(p=>(p.textContent||"").trim().length>50);y.length<3||(d.textContent||"").length<500||f.push({el:d,count:y.length,totalText:(d.textContent||"").length})}return f.sort((d,m)=>m.count-d.count||d.totalText-m.totalText),f[0]?.el}let a=r(i);if(!a)return[];let l=Array.from(a.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function c(u){let f=u[0]||null,d=null,m=null;if(u[1]){let _=u[1].split("\xB7").map(R=>R.trim());d=_[0]||null,_[1]&&(m=_[1])}let y=u.findIndex(_=>/(\d{4}|present)/i.test(_)&&/(-|–|—)/i.test(_)&&_.length<80),p=null,w=null;if(y>=0){let _=u[y].split("\xB7").map(R=>R.trim());p=_[0]||null,_[1]&&(w=_[1])}let v=null,S=-1;if(y>=0&&u[y+1]){let _=u[y+1],R=/^[>*\-•]|^&gt;/.test(_),W=/https?:\/\//.test(_),C=/\d{4}/.test(_),A=/,/.test(_)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(_);!R&&!W&&!C&&_.length<100&&A&&(v=_,S=y+1)}let g=null,h=-1,b=u[u.length-1];if(b&&/and\s+\+\d+\s+skills?$/i.test(b)){h=u.length-1;let _=b.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);_&&(g={listed:_[1].split(",").map(R=>R.trim()),additional:parseInt(_[2],10)})}let k=new Set([0,1,y,S,h].filter(_=>_>=0)),T=u.filter((_,R)=>!k.has(R)),I=T.length>0?T.join(`
2
2
 
3
- `):null;return{title:f,company:d,employmentType:m,dates:g,duration:b,location:w,description:R,skills:h,_raw:u}}return l.map(u=>{let d=(u.innerText||"").trim().split(`
4
- `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return a(d)}).filter(u=>u.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function St(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function kt(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Xi(e,t){return kt(t,"featured","extractFeaturedFromDetails",async()=>(await St(e,t,"featured"),await e.evaluate(`(() => {
5
- ${vt}
3
+ `):null;return{title:f,company:d,employmentType:m,dates:p,duration:w,location:v,description:I,skills:g,_raw:u}}return l.map(u=>{let d=(u.innerText||"").trim().split(`
4
+ `).map(m=>m.trim()).filter(m=>m&&m.length<5e3);return c(d)}).filter(u=>u.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function kt(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(700);await $(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)i++,await $(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await $(600)}async function Ct(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function tl(e,t){return Ct(t,"featured","extractFeaturedFromDetails",async()=>(await kt(e,t,"featured"),await e.evaluate(`(() => {
5
+ ${$t}
6
6
 
7
7
  const main = document.querySelector('main');
8
8
  if (!main) return [];
@@ -42,8 +42,8 @@ var qs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{
42
42
  if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
43
43
  return true;
44
44
  });
45
- })()`)))}async function el(e,t){return kt(t,"education","extractEducationFromDetails",async()=>(await St(e,t,"education"),await e.evaluate(`(() => {
46
- ${vt}
45
+ })()`)))}async function nl(e,t){return Ct(t,"education","extractEducationFromDetails",async()=>(await kt(e,t,"education"),await e.evaluate(`(() => {
46
+ ${$t}
47
47
 
48
48
  const main = document.querySelector('main');
49
49
  if (!main) return [];
@@ -79,8 +79,8 @@ var qs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{
79
79
  if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
80
80
  return true;
81
81
  });
82
- })()`)))}async function tl(e,t){return kt(t,"skills","extractSkillsFromDetails",async()=>(await St(e,t,"skills"),await e.evaluate(`(() => {
83
- ${vt}
82
+ })()`)))}async function ol(e,t){return Ct(t,"skills","extractSkillsFromDetails",async()=>(await kt(e,t,"skills"),await e.evaluate(`(() => {
83
+ ${$t}
84
84
 
85
85
  const main = document.querySelector('main');
86
86
  if (!main) return [];
@@ -111,8 +111,8 @@ var qs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{
111
111
  skills.push({ name, endorsements, _raw: lines });
112
112
  }
113
113
  return skills;
114
- })()`)))}async function nl(e,t){return kt(t,"certifications","extractCertificationsFromDetails",async()=>(await St(e,t,"certifications"),await e.evaluate(`(() => {
115
- ${vt}
114
+ })()`)))}async function sl(e,t){return Ct(t,"certifications","extractCertificationsFromDetails",async()=>(await kt(e,t,"certifications"),await e.evaluate(`(() => {
115
+ ${$t}
116
116
 
117
117
  const main = document.querySelector('main');
118
118
  if (!main) return [];
@@ -136,8 +136,8 @@ var qs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{
136
136
 
137
137
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
138
  }).filter(e => e.name);
139
- })()`)))}async function ol(e,t){return kt(t,"recommendations","extractRecommendationsFromDetails",async()=>(await St(e,t,"recommendations"),await e.evaluate(`(() => {
140
- ${vt}
139
+ })()`)))}async function rl(e,t){return Ct(t,"recommendations","extractRecommendationsFromDetails",async()=>(await kt(e,t,"recommendations"),await e.evaluate(`(() => {
140
+ ${$t}
141
141
 
142
142
  const main = document.querySelector('main');
143
143
  if (!main) return [];
@@ -172,7 +172,7 @@ var qs=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>{
172
172
  if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
173
173
  return true;
174
174
  });
175
- })()`)))}var vt,vs=de(()=>{Le();vt=`
175
+ })()`)))}var $t,$s=de(()=>{Fe();$t=`
176
176
  function findEntryContainer(root) {
177
177
  const candidates = [];
178
178
  for (const div of root.querySelectorAll('div')) {
@@ -235,129 +235,129 @@ function findEntryContainer(root) {
235
235
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
236
  return candidates[0]?.el;
237
237
  }
238
- `});var $s={};ae($s,{DEFAULT_PROFILE_INTERESTS:()=>ks,computeFit:()=>il,detectSectors:()=>rl});function rl(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(sl))s.some(i=>i.test(t))&&n.push(o);return n}function il(e,t=ks){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var sl,ks,Cs=de(()=>{sl={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};ks={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var xs={};ae(xs,{clickConnectButton:()=>In,default:()=>cl,detectConnectionStatus:()=>Ce,findConnectButton:()=>$t,runFunnel:()=>Es,sendConnectionRequest:()=>Dn,shouldExcludeLocation:()=>Bt,viewProfile:()=>Rn});async function As(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Bt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Rn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:c=!1,extractCertifications:l=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await As(e,t));let u=0;for(let p=0;p<2;p++){let v=await e.evaluate(()=>document.body.scrollHeight);for(let _=1;_<=6;_++)await e.evaluate(R=>window.scrollTo(0,R),v*_/6),await k(900);let C=await e.evaluate(()=>document.body.scrollHeight);if(C===u)break;u=C}await k(800);let f=null;try{let p=e.url();p&&/\/in\/[^/?#]/.test(p)&&(f=p.split("?")[0].replace(/\/+$/,""))}catch{}let d=await e.evaluate(()=>{let p=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),v=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),C=I=>{let O=(I||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},_={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},R=document.querySelector("main");if(!R)return _;let x=[...Array.from(R.querySelectorAll("h1")),...Array.from(R.querySelectorAll("h2"))],D=Array.from(R.querySelectorAll("h2")),G=x.find(I=>{let O=I.textContent&&I.textContent.trim(),M=(O||"").replace(/\s*\(\d+\)$/,"").trim();return O&&O.length>1&&O.length<100&&!p.has(M)&&!v.has(M)}),$=G?G.textContent.trim():null,A=G?G.parentElement:null;for(;A&&A!==R&&!Array.from(A.children).filter(O=>O.tagName==="P").some(O=>{let M=O.textContent&&O.textContent.trim();return M&&M.length>5&&!C(M)});)A=A.parentElement;let T=null,N=null,H=null,re=null;if(A&&A!==R){let I=Array.from(A.children).filter(M=>M.tagName==="P").filter(M=>{let he=M.textContent&&M.textContent.trim();return he&&he.length>5&&!C(he)});if(I[0]&&(T=I[0].textContent.trim()),I[1]){let M=I[1].textContent.trim().split(/\s*[·•]\s*/);N=M[0]||null,M.length>1&&(H=M.slice(1).join(" \xB7 "))}let O=Array.from(A.children).filter(M=>M.tagName==="DIV");for(let M=O.length-1;M>=0;M--){let he=O[M].textContent&&O[M].textContent.trim();if(he&&!($&&he.startsWith($))&&(re=he.split(/[·•]/)[0].trim(),re))break}}let ie=null;if(A){let I=A.querySelectorAll("p, span, div");for(let O of I){let M=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){ie=M;break}}}let j=!!R.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),U=L&&L.src||null,q=R.textContent||"",le=null,Ln=q.match(/(\d+\+?)\s+connections\b/i);Ln&&(le=Ln[1]+" connections");let At=null,Fn=q.match(/(\d+)\s+mutual connection/i),Un=q.match(/and\s+(\d+)\s+other mutual/i),Ps=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Fn?At=parseInt(Fn[1],10):Un?At=2+parseInt(Un[1],10):Ps&&(At=2);let qn=null,Bn=null,Hn=D.find(I=>I.textContent&&I.textContent.trim()==="About");if(Hn){let I=Hn.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let O=(I.textContent||"").trim();O=O.replace(/^About\s*/,"").trim();let M=O.match(/Top skills\s*(.+?)$/i);if(M){let Jt=M[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Us=>Us.trim()).filter(Boolean);Jt.length>0&&Jt.length<10&&(Bn=Jt)}O=O.split(/\n?…\s*more/i)[0].trim(),O=O.split(/\n?\.\.\.\s*more/i)[0].trim(),O=O.split(/\bTop skills\b/i)[0].trim(),O=O.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),qn=O||null}}let Jn=null,Vn=D.find(I=>I.textContent&&I.textContent.trim()==="Activity");if(Vn){let I=Vn.parentElement;for(;I&&I.tagName!=="SECTION";)I=I.parentElement;if(I){let O=(I.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);O&&(Jn=parseInt(O[1].replace(/,/g,""),10))}}let js=[...new Set(D.map(I=>(I.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(I=>I&&I.length>1&&I.length<60&&I!==$).filter(I=>p.has(I)))],Xe=document.body.textContent||"",Ls=/#OpenToWork\b/i.test(Xe)||/\bOpen to work\b/.test(Xe),Fs=/#Hiring\b/i.test(Xe)||/\bI'?m hiring\b/i.test(Xe)||/\bWe are hiring\b/i.test(Xe);return{name:$,title:T,location:re,currentCompany:N,currentSchool:H,connectionDegree:ie,hasVerifiedBadge:j,photoUrl:U,connectionsLevel:le,mutualConnectionsCount:At,followers:Jn,openToWork:Ls,hiring:Fs,about:qn,topSkills:Bn,availableSections:js}});console.log(`Viewed: ${d.name} - ${d.title}`);let m=null,y=null,g=null,b=null,w=null,S=null;if(o||s||i||r||c||l){let p=await Promise.resolve().then(()=>(vs(),Ss));o&&(m=await p.extractExperienceFromDetails(e,t),console.log(` + Experience: ${m.length} entries`)),s&&(y=await p.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${y.length} entries`)),i&&(g=await p.extractEducationFromDetails(e,t),console.log(` + Education: ${g.length} entries`)),r&&(b=await p.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(w=await p.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${w.length} entries`)),l&&(S=await p.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${S.length} entries`))}return{...d,profileUrl:t,resolvedUrl:f,...m!==null&&{experience:m},...y!==null&&{featured:y},...g!==null&&{education:g},...b!==null&&{skillsFull:b},...w!==null&&{recommendations:w},...S!==null&&{certifications:S}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Ce(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(s),r=f=>Array.from(document.querySelectorAll(f)).filter(i),c=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,a=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:c.length,pendingLabels:c.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!a};return c.length>0?{status:"pending",debug:u}:l&&!a?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await k(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function $t(e){let t=null,n=await e.evaluate(()=>{let a=document.querySelector("h1")?.textContent?.trim();if(a&&!a.includes("notification"))return a;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(a=u.textContent?.trim(),a&&!a.includes("notification")))return a;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let a=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});a.count>0&&console.log(` S0: ${a.count} custom-invite links: ${JSON.stringify(a.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],y='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let g of d){let b=g.getBoundingClientRect();if(b.width===0||b.height===0||g.closest(y))continue;if((g.getAttribute("aria-label")||"").toLowerCase().includes(m))return g}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let a=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${a}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),y=document.querySelectorAll("button[aria-label]");return Array.from(y).filter(b=>{let w=b.getAttribute("aria-label")||"";return(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&m.test(w)}).map(b=>b.getAttribute("aria-label")?.slice(0,50))},a);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),y='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',g=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let b of m){if(b.closest(y))continue;let w=b.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(w)&&(w.toLowerCase().includes("invite")||w.toLowerCase().includes("connect"))&&g.test(w))return b}return null},a);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let a=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();a.includes("invite")&&!a.includes(u)&&(console.log(` Skipping primary button: wrong person (${a})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let a of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),y=f.className.includes("sticky-header")||f.className.includes("sticky"),g=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,b=(f.getAttribute("aria-label")||"").toLowerCase(),w=b.includes("invite"),S=d?b.includes(d):!0;return{isMuted:m,isStickyHeader:y,inRecommendations:g,hasInvite:w,matchesName:S,ariaLabel:b}},a,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=a;break}}for(let a of o)a!==i&&await a.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let r=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let a of c){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,y=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:y,top:d.top}},a);if(u.isVisible&&!u.isInStickyHeader){r=a,console.log(" Found More button by ID pattern (main)");break}}for(let a of c)a!==r&&await a.dispose().catch(()=>{});if(!r&&c.length>0&&(r=c[c.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let a=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let y=m.innerText?.trim(),g=m.getAttribute("aria-label")||"",b=m.getBoundingClientRect();return b.top<100||b.top>600||b.width===0?!1:y==="Follow"||y==="Message"||y==="Connect"||g.includes("Follow")||g.includes("Message")||g.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let y of d.querySelectorAll("button"))if(y.innerText?.trim()==="More"&&y!==f)return y;d=d.parentElement}return null});r=a?.asElement?.()||null,r||await a?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),r),await k(500),await e.evaluate(d=>d.click(),r),await k(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let y of m){let g=y.querySelector('a[href*="custom-invite"]');if(g)return g;for(let b of y.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(b.innerText?.trim()==="Connect")return b}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let y of d)for(let g of y.querySelectorAll('[role="menuitem"], a, div')){let b=g.innerText?.trim();b&&b.length<40&&m.push(b)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(a){console.log(" More dropdown click failed:",a.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(a=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(a||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let y=d.getBoundingClientRect();if(!(y.width===0||y.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function In(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await k(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await k(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await k(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await k(3e3)):(await e.evaluate(u=>u.click(),t),await k(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function ll(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await k(1500);let n=await $t(e);if(n){await e.evaluate(s=>s.click(),n),await k(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Qe(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Qe(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let c=l=>!!(l&&l.querySelector(r));return!(c(document)||c(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let c=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,n);return r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(c=>c.click())}catch{}if(await k(3e3),await s())return!1;if(await o())return!0;if(r===0){let c=await i();if(!c)return await o();t=c,await k(600)}}return await o()}async function Dn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=Kt();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let r=await al(e,t,n);return r.connectionSent&&!i&&ao(t,o),r}async function al(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!0,excludeLocations:c=[]}=n,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
- --- Connecting: ${a} ---`),c.length>0){let w=J()[t]?.location;if(Bt(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),l.reason="excluded_location",l.profileInfo={location:w},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(5e3),await Ae(e)&&(console.log(" Dismissed Premium overlay"),await k(2e3),await As(e,t),await k(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:w,normalizeProfileUrl:S}=await Promise.resolve().then(()=>(Xt(),ho)),{recordDiscoveredEdges:h}=await Promise.resolve().then(()=>(yt(),ko)),{detectCategoryFromTitle:p}=await wn().then(()=>ns),{detectSectors:v}=await Promise.resolve().then(()=>(Cs(),$s)),C=S(t)||t,_=await w(e,{seedUrl:C}),R=_.map(x=>{let D=x.headline?p(x.headline):null;return{url:x.url,seedUrl:C,block:x.block,rank:x.rank,name:x.name,headline:x.headline,categories:D?[D]:[],sectors:v(x.headline||"")}});h(R),_.length&&console.log(` \xB7 discovery: harvested ${_.length} related profiles`)}catch(w){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${w.message}`)}l.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),S=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},h={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},p=document.querySelector("main");if(!p)return h;let v=[...Array.from(p.querySelectorAll("h1")),...Array.from(p.querySelectorAll("h2"))],C=Array.from(p.querySelectorAll("h2")),_=v.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!w.has(L)&&L!=="0 notifications"}),R=_?_.textContent.trim():null,x=_?_.parentElement:null;for(;x&&x!==p&&!Array.from(x.children).filter(U=>U.tagName==="P").some(U=>{let q=U.textContent&&U.textContent.trim();return q&&q.length>5&&!S(q)});)x=x.parentElement;let D=null,G=null,$=null;if(x&&x!==p){let j=Array.from(x.children),L=j.filter(q=>q.tagName==="P").filter(q=>{let le=q.textContent&&q.textContent.trim();return le&&le.length>5&&!S(le)});L[0]&&(D=L[0].textContent.trim()),L[1]&&(G=L[1].textContent.trim());let U=j.filter(q=>q.tagName==="DIV");for(let q=U.length-1;q>=0;q--){let le=U[q].textContent&&U[q].textContent.trim();if(le&&!(R&&le.startsWith(R))&&($=le.split(/[·•]/)[0].trim(),$))break}}let A=null;if(x){let j=x.querySelectorAll("p, span, div");for(let L of j){let U=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(U==="1st"||U==="2nd"||U==="3rd"){A=U;break}}}let T=null,N=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(N){let j=N.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(T=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,T&&(T=T.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let H=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),re=H&&H.src||null,ie=!!p.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:R,title:D,location:$,about:T,company:G,connectionDegree:A,connectionsCount:null,mutualConnections:null,photoUrl:re,hasVerifiedBadge:ie}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(l.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let w=l.profileInfo?.location,S=J()[t]?.location,h=w||S;if(Bt(h,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${h}`),l.reason="excluded_location",l;!w&&S==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ce(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await Ae(e);let d=await $t(e);if(d||await Ae(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await k(2e3),d=await $t(e)),d&&d.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!d){let w=await Ce(e,{detail:!0});return r&&(w.status==="connected"||w.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=d.method;let m=await In(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3);let w=await Ce(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await Ae(e),await k(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(p=>p.scrollIntoView({behavior:"smooth",block:"center"}),S),await k(500),await S.click().catch(()=>e.evaluate(p=>p.click(),S)),await k(2e3);let h=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(h){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),h),await k(3e3);let p=e.url();if(p.includes("/premium/")||p.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),l.reason="premium_required",l;if(await Ce(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await k(500),l.reason="premium_required",l}catch(h){return console.log(" More dropdown failed:",h.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let w=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let S of w){let h=S.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!h)continue;let p=(h.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(p)||h.querySelector('input[type="email"], input[name="email"]'))return!0;let v=h.querySelector('button[aria-label="Send without a note"]');if(v&&(v.disabled||v.getAttribute("aria-disabled")==="true"||(v.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let w=await e.$('button[aria-label="Dismiss"]');if(w)try{await w.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await k(500),l.reason="email_required",l}let g=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!g&&!b){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let h=S.querySelector('button[aria-label="Add a note"]'),p=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!h,sendWithout:!!p}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));g=S?.asElement?.()||null,g||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=S?.asElement?.()||null,b||await S.dispose().catch(()=>{})}}if(s)if(g&&o){if(console.log(" Adding personalized note..."),await g.click(),await k(1500),await e.$("div.modal-upsell")){let h=await ll(e);return l.success=h,l.connectionSent=h,l.reason=h?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let h=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),p=o.replace("{name}",h);await S.type(p,{delay:20}),await k(500);let v=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(v)return await Qe(e,v)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=p,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(b)return console.log(" Sending without note..."),await Qe(e,b)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(g&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w)return await Qe(e,w)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let w=b;if(w)return await Qe(e,w)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3)),await Ae(e),await k(500);let S=await e.$$('button[id*="profile-overflow-action"]'),h=null;for(let p of S){let v=await e.evaluate(C=>{let _=C.getBoundingClientRect();return{visible:_.width>0&&_.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},p);if(v.visible&&!v.inSticky){h=p;break}}!h&&S.length>0&&(h=S[S.length-1]);for(let p of S)p!==h&&await p.dispose().catch(()=>{});if(h)try{await e.evaluate(v=>v.scrollIntoView({behavior:"smooth",block:"center"}),h),await k(500),await h.click().catch(()=>e.evaluate(v=>v.click(),h)),await k(2e3);let p=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(p){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(R=>R.click(),p),await k(3e3);let v=e.url();if(v.includes("/premium/")||v.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await Ce(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await Ce(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let _=await e.$('button[aria-label="Send without a note"]');if(_)return console.log(" Modal appeared via More dropdown, sending without note..."),await Qe(e,_)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(p){console.log(" More dropdown fallback failed:",p.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(a){console.error(` \u2717 Error: ${a.message}`),l.reason="error",l.error=a.message;let u=a.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{l.fatal=!0}return l}}async function Es(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:l=null,excludeLocations:a=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
240
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!r){let m=at();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let y=t[m];try{if(e.isClosed()){console.log(`
238
+ `});var As={};ae(As,{DEFAULT_PROFILE_INTERESTS:()=>Cs,computeFit:()=>al,detectSectors:()=>ll});function ll(e){if(!e||typeof e!="string")return[];let t=e.toLowerCase(),n=[];for(let[o,s]of Object.entries(il))s.some(i=>i.test(t))&&n.push(o);return n}function al(e,t=Cs){if(!Array.isArray(e)||e.length===0)return 0;let n=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=Math.max(1,...Object.values(t||{}).map(n)),s=0;for(let i of e){let r=n(t&&t[i]);r>s&&(s=r)}return Math.min(1,s/o)}var il,Cs,xs=de(()=>{il={ai:[/\bai\b/,/artificial intelligence/,/machine learning/,/\bml\b/,/\bllm/,/generative/,/\bnlp\b/,/natural language/,/deep learning/,/foundation model/,/agents?\b/],robotics:[/robotic/,/\brobot/,/autonomy|autonomous/,/drone/],"deep-tech":[/deep ?tech/,/frontier tech/,/hard ?tech/,/physics/,/quantum/,/photonic/,/semiconductor|chips?\b/],"dev-tools":[/dev ?tools?/,/developer tools?/,/devtools/,/infrastructure|infra\b/,/platform engineering/,/\bapi\b/,/open ?source/],data:[/\bdata\b/,/database/,/analytics/,/data infrastructure/,/knowledge graph/],fintech:[/fintech/,/financial/,/payments?/,/banking/,/insurtech/,/money\b/],biotech:[/biotech/,/\bbio\b/,/life sciences?/,/genomic/,/pharma/,/drug/],healthtech:[/health\s?tech/,/healthcare/,/health\b/,/medtech|medical/,/wellness/,/digital health/],climate:[/climate/,/clean\s?tech|cleantech/,/energy/,/sustainab/,/carbon/,/decarbon/],"web3-crypto":[/crypto/,/web3/,/blockchain/,/defi\b/,/\bnft/,/token/],hardware:[/hardware/,/\biot\b/,/devices?/,/manufactur/],defense:[/defen[cs]e/,/\bdual[- ]use\b/,/national security/,/aerospace/,/space\b/],security:[/cyber/,/security\b/,/infosec/],consumer:[/consumer/,/\bd2c\b/,/\bcpg\b/,/brands?\b/,/retail/,/e-?commerce/],marketplace:[/marketplace/,/two-sided|multi-sided/],saas:[/\bsaas\b/,/\bb2b\b/,/enterprise software/,/vertical software/],"future-of-work":[/future of work/,/hr\s?tech/,/workforce/,/productivity/],gaming:[/gaming/,/\bgames?\b/,/\bweb3 game/]};Cs={ai:1.5,"deep-tech":1.2,data:1.3,"dev-tools":1.1,robotics:.9,saas:.7,marketplace:.6}});var Ts={};ae(Ts,{clickConnectButton:()=>On,default:()=>dl,detectConnectionStatus:()=>Ae,findConnectButton:()=>At,runFunnel:()=>_s,sendConnectionRequest:()=>Nn,shouldExcludeLocation:()=>Jt,viewProfile:()=>Dn});async function Es(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Jt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Dn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:r=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=n;try{if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),!await nt(e,".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",{timeout:45e3,label:"profile"})&&/\/authwall|\/login|\/checkpoint|\/uas\/login/.test(e.url()))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");await $(1500),await xe(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await Es(e,t));let f=0;for(let b=0;b<2;b++){let k=await e.evaluate(()=>document.body.scrollHeight);for(let I=1;I<=6;I++)await e.evaluate(_=>window.scrollTo(0,_),k*I/6),await $(900);let T=await e.evaluate(()=>document.body.scrollHeight);if(T===f)break;f=T}await $(800);let d=null;try{let b=e.url();b&&/\/in\/[^/?#]/.test(b)&&(d=b.split("?")[0].replace(/\/+$/,""))}catch{}let m=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),k=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),T=D=>{let N=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(N)},I={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},_=document.querySelector("main");if(!_)return I;let R=[...Array.from(_.querySelectorAll("h1")),...Array.from(_.querySelectorAll("h2"))],W=Array.from(_.querySelectorAll("h2")),C=R.find(D=>{let N=D.textContent&&D.textContent.trim(),M=(N||"").replace(/\s*\(\d+\)$/,"").trim();return N&&N.length>1&&N.length<100&&!b.has(M)&&!k.has(M)}),A=C?C.textContent.trim():null,E=C?C.parentElement:null;for(;E&&E!==_&&!Array.from(E.children).filter(N=>N.tagName==="P").some(N=>{let M=N.textContent&&N.textContent.trim();return M&&M.length>5&&!T(M)});)E=E.parentElement;let O=null,B=null,ie=null,Z=null;if(E&&E!==_){let D=Array.from(E.children).filter(M=>M.tagName==="P").filter(M=>{let ye=M.textContent&&M.textContent.trim();return ye&&ye.length>5&&!T(ye)});if(D[0]&&(O=D[0].textContent.trim()),D[1]){let M=D[1].textContent.trim().split(/\s*[·•]\s*/);B=M[0]||null,M.length>1&&(ie=M.slice(1).join(" \xB7 "))}let N=Array.from(E.children).filter(M=>M.tagName==="DIV");for(let M=N.length-1;M>=0;M--){let ye=N[M].textContent&&N[M].textContent.trim();if(ye&&!(A&&ye.startsWith(A))&&(Z=ye.split(/[·•]/)[0].trim(),Z))break}}let he=null;if(E){let D=E.querySelectorAll("p, span, div");for(let N of D){let M=(N.textContent||"").trim().replace(/^[·•]\s*/,"");if(M==="1st"||M==="2nd"||M==="3rd"){he=M;break}}}let j=!!_.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),L=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),V=L&&L.src||null,U=_.textContent||"",le=null,Un=U.match(/(\d+\+?)\s+connections\b/i);Un&&(le=Un[1]+" connections");let Et=null,qn=U.match(/(\d+)\s+mutual connection/i),Bn=U.match(/and\s+(\d+)\s+other mutual/i),Ls=U.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);qn?Et=parseInt(qn[1],10):Bn?Et=2+parseInt(Bn[1],10):Ls&&(Et=2);let Hn=null,Jn=null,Vn=W.find(D=>D.textContent&&D.textContent.trim()==="About");if(Vn){let D=Vn.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;if(D){let N=(D.textContent||"").trim();N=N.replace(/^About\s*/,"").trim();let M=N.match(/Top skills\s*(.+?)$/i);if(M){let Wt=M[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Bs=>Bs.trim()).filter(Boolean);Wt.length>0&&Wt.length<10&&(Jn=Wt)}N=N.split(/\n?…\s*more/i)[0].trim(),N=N.split(/\n?\.\.\.\s*more/i)[0].trim(),N=N.split(/\bTop skills\b/i)[0].trim(),N=N.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Hn=N||null}}let Wn=null,Yn=W.find(D=>D.textContent&&D.textContent.trim()==="Activity");if(Yn){let D=Yn.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;if(D){let N=(D.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);N&&(Wn=parseInt(N[1].replace(/,/g,""),10))}}let Fs=[...new Set(W.map(D=>(D.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(D=>D&&D.length>1&&D.length<60&&D!==A).filter(D=>b.has(D)))],et=document.body.textContent||"",Us=/#OpenToWork\b/i.test(et)||/\bOpen to work\b/.test(et),qs=/#Hiring\b/i.test(et)||/\bI'?m hiring\b/i.test(et)||/\bWe are hiring\b/i.test(et);return{name:A,title:O,location:Z,currentCompany:B,currentSchool:ie,connectionDegree:he,hasVerifiedBadge:j,photoUrl:V,connectionsLevel:le,mutualConnectionsCount:Et,followers:Wn,openToWork:Us,hiring:qs,about:Hn,topSkills:Jn,availableSections:Fs}});console.log(`Viewed: ${m.name} - ${m.title}`);let y=null,p=null,w=null,v=null,S=null,g=null;if(o||s||i||r||a||l){let b=await Promise.resolve().then(()=>($s(),ks));o&&(y=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${y.length} entries`)),s&&(p=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(w=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${w.length} entries`)),r&&(v=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${v.length} entries`)),a&&(S=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),l&&(g=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${g.length} entries`))}return{...m,profileUrl:t,resolvedUrl:d,...y!==null&&{experience:y},...p!==null&&{featured:p},...w!==null&&{education:w},...v!==null&&{skillsFull:v},...S!==null&&{recommendations:S},...g!==null&&{certifications:g}}}catch(c){console.error(`Error viewing profile ${t}:`,c.message);try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(c.message||""))throw c;return null}}async function Ae(e,{detail:t=!1}={}){let n=()=>e.evaluate(()=>{let s='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',i=f=>f&&!f.closest(s),r=f=>Array.from(document.querySelectorAll(f)).filter(i),a=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,u={pendingCount:a.length,pendingLabels:a.map(f=>f.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return a.length>0?{status:"pending",debug:u}:l&&!c?{status:"connected",debug:u}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:u}:{status:"not_connected",debug:u}}),o=await n();return!o.debug.pendingCount&&!o.debug.hasMessageBtn&&!o.debug.hasConnectBtn&&(await $(1500),o=await n()),console.log(" DEBUG connection status:",JSON.stringify(o.debug)),t?o:o.status}async function At(e){let t=null,n=await e.evaluate(()=>{let c=document.querySelector("h1")?.textContent?.trim();if(c&&!c.includes("notification"))return c;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(c=u.textContent?.trim(),c&&!c.includes("notification")))return c;let f=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(f)return f.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let c=await e.evaluate(()=>{let f=document.querySelectorAll('a[href*="custom-invite"]');return{count:f.length,labels:Array.from(f).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});c.count>0&&console.log(` S0: ${c.count} custom-invite links: ${JSON.stringify(c.labels)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),m=f.toLowerCase().split(" ")[0],y='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let p of d){let w=p.getBoundingClientRect();if(w.width===0||w.height===0||p.closest(y))continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(m))return p}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let c=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${c}"`);let u=await e.evaluate(d=>{let m=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),y=document.querySelectorAll("button[aria-label]");return Array.from(y).filter(w=>{let v=w.getAttribute("aria-label")||"";return(v.toLowerCase().includes("invite")||v.toLowerCase().includes("connect"))&&m.test(v)}).map(w=>w.getAttribute("aria-label")?.slice(0,50))},c);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let m=document.querySelectorAll("button[aria-label]"),y='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let w of m){if(w.closest(y))continue;let v=w.getAttribute("aria-label")||"";if(!/\b(remove|disconnect|unfollow|report|block)\b/i.test(v)&&(v.toLowerCase().includes("invite")||v.toLowerCase().includes("connect"))&&p.test(v))return w}return null},c);let f=t?.asElement?.()||null;if(f||await t?.dispose?.().catch(()=>{}),f)return console.log(" Found: button matching profile name"),{button:f,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let c=await e.evaluate(f=>(f.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();c.includes("invite")&&!c.includes(u)&&(console.log(` Skipping primary button: wrong person (${c})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let c of o){let u=await e.evaluate((f,d)=>{let m=f.className.includes("muted"),y=f.className.includes("sticky-header")||f.className.includes("sticky"),p=f.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,w=(f.getAttribute("aria-label")||"").toLowerCase(),v=w.includes("invite"),S=d?w.includes(d):!0;return{isMuted:m,isStickyHeader:y,inRecommendations:p,hasInvite:v,matchesName:S,ariaLabel:w}},c,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=c;break}}for(let c of o)c!==i&&await c.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let r=null,a=await e.$$('button[id*="profile-overflow-action"]');for(let c of a){let u=await e.evaluate(f=>{let d=f.getBoundingClientRect(),m=d.width>0&&d.height>0,y=f.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:m,isInStickyHeader:y,top:d.top}},c);if(u.isVisible&&!u.isInStickyHeader){r=c,console.log(" Found More button by ID pattern (main)");break}}for(let c of a)c!==r&&await c.dispose().catch(()=>{});if(!r&&a.length>0&&(r=a[a.length-1],console.log(" Found More button by ID pattern (last)")),r||(r=await e.$('button[aria-label="More actions"]'),r&&console.log(" Found More button by aria-label")),!r){let c=await e.evaluateHandle(()=>{let f=Array.from(document.querySelectorAll("button, a")).find(m=>{let y=m.innerText?.trim(),p=m.getAttribute("aria-label")||"",w=m.getBoundingClientRect();return w.top<100||w.top>600||w.width===0?!1:y==="Follow"||y==="Message"||y==="Connect"||p.includes("Follow")||p.includes("Message")||p.includes("Invite")});if(!f)return null;let d=f.parentElement;for(let m=0;m<8&&d;m++){for(let y of d.querySelectorAll("button"))if(y.innerText?.trim()==="More"&&y!==f)return y;d=d.parentElement}return null});r=c?.asElement?.()||null,r||await c?.dispose?.().catch(()=>{}),r&&console.log(" Found More button by text (near profile actions)")}if(r)try{if(await e.evaluate(d=>d.scrollIntoView({behavior:"smooth",block:"center"}),r),await $(500),await e.evaluate(d=>d.click(),r),await $(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')),!u){let d=await e.evaluateHandle(()=>{let m=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let y of m){let p=y.querySelector('a[href*="custom-invite"]');if(p)return p;for(let w of y.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(w.innerText?.trim()==="Connect")return w}return null});u=d?.asElement?.()||null,u||await d?.dispose?.().catch(()=>{})}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};let f=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),m=[];for(let y of d)for(let p of y.querySelectorAll('[role="menuitem"], a, div')){let w=p.innerText?.trim();w&&w.length<40&&m.push(w)}return[...new Set(m)].slice(0,12)});if(console.log(` More dropdown items: ${JSON.stringify(f)}`),await e.keyboard.press("Escape"),f.some(d=>/remove (your )?connection/i.test(d)))return console.log(' (More menu has "Remove connection" \u2192 already connected)'),{connected:!0}}catch(c){console.log(" More dropdown click failed:",c.message),await e.keyboard.press("Escape")}let l=await e.evaluateHandle(c=>{let u='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',f=(c||"").split(" ")[0].toLowerCase();for(let d of document.querySelectorAll("button[aria-label]")){if(d.closest(u))continue;let m=(d.getAttribute("aria-label")||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(m))continue;let y=d.getBoundingClientRect();if(!(y.width===0||y.height===0)){if(m.includes("invite")){if(f&&m.includes(f))return d;continue}if(m==="connect")return d}}return null},n||"");return t=l?.asElement?.()||null,t||await l?.dispose?.().catch(()=>{}),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function On(e,t){await e.evaluate(u=>u.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(u=>({tag:u.tagName,ariaLabel:u.getAttribute("aria-label"),href:u.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",r=(n.ariaLabel||"").toLowerCase();if(/\b(remove|disconnect|unfollow|report|block)\b/.test(r))return console.log(` \u2717 Guard: refusing a non-connect control ("${n.ariaLabel}")`),"wrong_target";if(r.includes("invite")){let u=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(u&&!r.includes(u))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${u})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await $(2e3);let u=e.url();if(u.includes("premium")||u.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await $(2e3),"premium_redirect"}else i?(await e.evaluate(u=>u.click(),t),await $(3e3)):(await e.evaluate(u=>u.click(),t),await $(3e3));let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let l=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),c=e.url();return console.log(l?` \u2713 Connect sent \u2014 ${c}`:` \u26A0 No modal after connect click \u2014 ${c}`),"success"}async function cl(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await $(1500);let n=await At(e);if(n){await e.evaluate(s=>s.click(),n),await $(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o)return await Ze(e,o)?(console.log(" \u2713 Connection sent (without note)"),!0):(console.log(" \u2717 Send not confirmed (upsell path)"),!1)}return!1}async function Ze(e,t){let n='button[aria-label="Send without a note"], button[aria-label="Send invitation"], button[aria-label="Send now"]',o=()=>e.evaluate(r=>{let a=l=>!!(l&&l.querySelector(r));return!(a(document)||a(document.querySelector("#interop-outlet")?.shadowRoot))},n),s=()=>e.evaluate(()=>{for(let r of document.querySelectorAll('.artdeco-toast-item, [class*="toast"]'))if(/try again|went wrong|error|couldn.?t|please try/i.test(r.innerText||""))return!0;return!1}),i=async()=>{let r=await e.$('button[aria-label="Send without a note"]')||await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(r)return r;let a=await e.evaluateHandle(l=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector(l)||null,n);return r=a?.asElement?.()||null,r||await a?.dispose?.().catch(()=>{}),r};for(let r=0;r<2;r++){try{await t.evaluate(a=>a.click())}catch{}if(await $(3e3),await s())return!1;if(await o())return!0;if(r===0){let a=await i();if(!a)return await o();t=a,await $(600)}}return await o()}async function Nn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let a=Zt();if(!a.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${a.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:a.reason,profileInfo:null}}let r=await ul(e,t,n);return r.connectionSent&&!i&&uo(t,o),r}async function ul(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:r=!0,excludeLocations:a=[]}=n,l={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
+ --- Connecting: ${c} ---`),a.length>0){let S=H()[t]?.location;if(Jt(S,a))return console.log(` \u26A0 Excluded location (stored): ${S}`),l.reason="excluded_location",l.profileInfo={location:S},l}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),!await nt(e,".pvs-profile-actions, .pv-top-card-v2-ctas, .pv-top-card, section.pv-top-card",{timeout:45e3,label:"profile"})&&/\/authwall|\/login|\/checkpoint|\/uas\/login/.test(e.url()))return console.log(" \u2717 Session expired (authwall) \u2014 run: ilml linkedin login"),l.reason="session_expired",l.fatal=!0,l;if(await $(2e3),await xe(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await Es(e,t),await $(2e3)),["true","1"].includes(process.env.DISCOVERY_ENABLED))try{let{extractSidePanelProfiles:S,normalizeProfileUrl:g}=await Promise.resolve().then(()=>(tn(),wo)),{recordDiscoveredEdges:h}=await Promise.resolve().then(()=>(bt(),Co)),{detectCategoryFromTitle:b}=await Sn().then(()=>ss),{detectSectors:k}=await Promise.resolve().then(()=>(xs(),As)),T=g(t)||t,I=await S(e,{seedUrl:T}),_=I.map(R=>{let W=R.headline?b(R.headline):null;return{url:R.url,seedUrl:T,block:R.block,rank:R.rank,name:R.name,headline:R.headline,categories:W?[W]:[],sectors:k(R.headline||"")}});h(_),I.length&&console.log(` \xB7 discovery: harvested ${I.length} related profiles`)}catch(S){["true","1"].includes(process.env.DISCOVERY_DEBUG)&&console.log(` \xB7 discovery harvest skipped: ${S.message}`)}l.profileInfo=await e.evaluate(()=>{let S=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),g=j=>{let L=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(L)},h={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},b=document.querySelector("main");if(!b)return h;let k=[...Array.from(b.querySelectorAll("h1")),...Array.from(b.querySelectorAll("h2"))],T=Array.from(b.querySelectorAll("h2")),I=k.find(j=>{let L=j.textContent&&j.textContent.trim();return L&&L.length>1&&L.length<100&&!S.has(L)&&L!=="0 notifications"}),_=I?I.textContent.trim():null,R=I?I.parentElement:null;for(;R&&R!==b&&!Array.from(R.children).filter(V=>V.tagName==="P").some(V=>{let U=V.textContent&&V.textContent.trim();return U&&U.length>5&&!g(U)});)R=R.parentElement;let W=null,C=null,A=null;if(R&&R!==b){let j=Array.from(R.children),L=j.filter(U=>U.tagName==="P").filter(U=>{let le=U.textContent&&U.textContent.trim();return le&&le.length>5&&!g(le)});L[0]&&(W=L[0].textContent.trim()),L[1]&&(C=L[1].textContent.trim());let V=j.filter(U=>U.tagName==="DIV");for(let U=V.length-1;U>=0;U--){let le=V[U].textContent&&V[U].textContent.trim();if(le&&!(_&&le.startsWith(_))&&(A=le.split(/[·•]/)[0].trim(),A))break}}let E=null;if(R){let j=R.querySelectorAll("p, span, div");for(let L of j){let V=(L.textContent||"").trim().replace(/^[·•]\s*/,"");if(V==="1st"||V==="2nd"||V==="3rd"){E=V;break}}}let O=null,B=T.find(j=>j.textContent&&j.textContent.trim()==="About");if(B){let j=B.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(O=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,O&&(O=O.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let ie=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Z=ie&&ie.src||null,he=!!b.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:_,title:W,location:A,about:O,company:C,connectionDegree:E,connectionsCount:null,mutualConnections:null,photoUrl:Z,hasVerifiedBadge:he}});try{let S=e.url();S&&/\/in\/[^/?#]/.test(S)&&(l.resolvedUrl=S.split("?")[0].replace(/\/+$/,""))}catch{}if(a.length>0){let S=l.profileInfo?.location,g=H()[t]?.location,h=S||g;if(Jt(h,a))return console.log(` \u26A0 Excluded location (${S?"live":"stored"}): ${h}`),l.reason="excluded_location",l;!S&&g==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}if((await Ae(e,{detail:!0})).status==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),l.reason="pending",l;await xe(e);let m=await At(e);if(m||await xe(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),m=await At(e)),m&&m.connected)return console.log(" \u26A0 Already connected (Remove connection in More menu) - skipping"),l.reason="connected",l;if(!m){let S=await Ae(e,{detail:!0});return r&&(S.status==="connected"||S.debug?.hasMessageBtn)?(console.log(" \u26A0 Already connected (no Connect control found, incl. under More) - skipping"),l.reason="connected",l):(console.log(" \u2717 Connect not found"),l.reason="button_not_found",l)}l.method=m.method;let y=await On(e,m.button);if(y==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),l.reason="wrong_target",l;if(y==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let S=await Ae(e);if(S==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;console.log(` Status after upsell: ${S} \u2014 trying More dropdown...`),await xe(e),await $(1e3);let g=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(g)try{await e.evaluate(b=>b.scrollIntoView({behavior:"smooth",block:"center"}),g),await $(500),await g.click().catch(()=>e.evaluate(b=>b.click(),g)),await $(2e3);let h=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(h){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),h),await $(3e3);let b=e.url();if(b.includes("/premium/")||b.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),l.reason="premium_required",l;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.method="more_dropdown",l.withCustomMessage=!1,l;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await $(500),l.reason="premium_required",l}catch(h){return console.log(" More dropdown failed:",h.message),await e.keyboard.press("Escape").catch(()=>{}),l.reason="premium_required",l}else return console.log(" \u2717 No More button found \u2014 Premium required"),l.reason="premium_required",l}if(await e.evaluate(()=>{let S=[document,document.querySelector("#interop-outlet")?.shadowRoot].filter(Boolean);for(let g of S){let h=g.querySelector('[role="dialog"], .artdeco-modal, .send-invite');if(!h)continue;let b=(h.innerText||"").toLowerCase();if(/enter their email|verify this member knows you/.test(b)||h.querySelector('input[type="email"], input[name="email"]'))return!0;let k=h.querySelector('button[aria-label="Send without a note"]');if(k&&(k.disabled||k.getAttribute("aria-disabled")==="true"||(k.className||"").includes("disabled")))return!0}return!1})){console.log(" \u26A0 Email required to connect (LinkedIn asks for their email) - skipping");let S=await e.$('button[aria-label="Dismiss"]');if(S)try{await S.click()}catch{}else try{await e.keyboard.press("Escape")}catch{}return await $(500),l.reason="email_required",l}let w=await e.$('button[aria-label="Add a note"]'),v=await e.$('button[aria-label="Send without a note"]');if(!w&&!v){let S=await e.evaluate(()=>{let g=document.querySelector("#interop-outlet")?.shadowRoot;if(!g)return{addNote:!1,sendWithout:!1};let h=g.querySelector('button[aria-label="Add a note"]'),b=g.querySelector('button[aria-label="Send without a note"]');return{addNote:!!h,sendWithout:!!b}});if(S.addNote){let g=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));w=g?.asElement?.()||null,w||await g.dispose().catch(()=>{})}if(S.sendWithout){let g=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));v=g?.asElement?.()||null,v||await g.dispose().catch(()=>{})}}if(s)if(w&&o){if(console.log(" Adding personalized note..."),await w.click(),await $(1500),await e.$("div.modal-upsell")){let h=await cl(e);return l.success=h,l.connectionSent=h,l.reason=h?"sent_without_note_upsell":"upsell_failed",l.withCustomMessage=!1,l}let g=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(g){let h=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),b=o.replace("{name}",h);await g.type(b,{delay:20}),await $(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k)return await Ze(e,k)?(console.log(" \u2713 Connection sent (with note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_with_note",l.withCustomMessage=!0,l.messageSent=b,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{if(v)return console.log(" Sending without note..."),await Ze(e,v)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l);if(w&&!o){console.log(" No message provided, sending without note...");let S=await e.$('button[aria-label="Send without a note"]');if(S)return await Ze(e,S)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}}else{console.log(" Sending without note (custom messages disabled)...");let S=v;if(S)return await Ze(e,S)?(console.log(" \u2713 Connection sent (without note)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed \u2014 modal stayed open / error toast; NOT counting as sent"),l.reason="modal_failed",l)}if(m.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3)),await xe(e),await $(500);let g=await e.$$('button[id*="profile-overflow-action"]'),h=null;for(let b of g){let k=await e.evaluate(T=>{let I=T.getBoundingClientRect();return{visible:I.width>0&&I.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},b);if(k.visible&&!k.inSticky){h=b;break}}!h&&g.length>0&&(h=g[g.length-1]);for(let b of g)b!==h&&await b.dispose().catch(()=>{});if(h)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),h),await $(500),await h.click().catch(()=>e.evaluate(k=>k.click(),h)),await $(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect" i]:not([aria-label*="remove" i]):not([aria-label*="disconnect" i])');if(b){console.log(" Found Connect in More dropdown, clicking..."),l.method="more_dropdown",await e.evaluate(_=>_.click(),b),await $(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await Ae(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(l.reason="premium_required",l);if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l;let I=await e.$('button[aria-label="Send without a note"]');if(I)return console.log(" Modal appeared via More dropdown, sending without note..."),await Ze(e,I)?(console.log(" \u2713 Connection sent (without note, via More dropdown)"),l.success=!0,l.connectionSent=!0,l.reason="sent_without_note",l.withCustomMessage=!1,l):(console.log(" \u2717 Send not confirmed (More-dropdown modal)"),l.reason="modal_failed",l);console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(b){console.log(" More dropdown fallback failed:",b.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),l.reason="modal_failed",l}catch(c){console.error(` \u2717 Error: ${c.message}`),l.reason="error",l.error=c.message;let u=c.message.toLowerCase();if(u.includes("detached")||u.includes("session closed")||u.includes("target closed")||u.includes("browser has disconnected")||u.includes("protocol error"))return l.fatal=!0,l;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{l.fatal=!0}return l}}async function _s(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:r=!1,delayBetweenProfiles:a=3e3,onProfileProcessed:l=null,excludeLocations:c=[],source:u="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
240
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${r?"View Only":`Connect (max ${i})`}`),r||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!r){let m=ut();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let y=t[m];try{if(e.isClosed()){console.log(`
241
241
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
242
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let g=ro(y.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(y,f,{success:!1,reason:g,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let b=null;if(r){let w=await Rn(e,y.profileUrl);w?(Te(y.profileUrl,{...w,source:u}),f.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w,resolvedUrl:w.resolvedUrl}):(f.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=Kt();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(b=await Dn(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:a,source:u,skipQuotaGate:!0}),b.success)f.connectionsSent++;else switch(b.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(b?.fatal){console.log(`
243
- \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(b?.reason==="error"){if(d++,d>=3){console.log(`
244
- \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(b&&b.reason&&(io(y.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&xt(y.profileUrl,b.resolvedUrl),so(y.profileUrl,{source:u||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:b.reason})),l&&await l(y,f,b),m<t.length-1){let w=c+Math.random()*2e3;await k(w)}}if(console.log(`
245
- === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!r){let m=at();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var cl,_s=de(async()=>{Le();await Je();cl={viewProfile:Rn,detectConnectionStatus:Ce,findConnectButton:$t,clickConnectButton:In,sendConnectionRequest:Dn,runFunnel:Es,shouldExcludeLocation:Bt}});Le();await Je();yt();await Je();yt();var kr=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),$r=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),$o=["vancouver","british columbia"],Cr=["canada","montreal","quebec","alberta","calgary","ottawa"],Ar=["toronto","ontario"],Er=["india","pakistan","nigeria","philippines"];function xr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)kr.has(u)&&s++,$r.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=_r(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Er.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&$o.some(u=>r.includes(u))?n+=22:c?n+=20:$o.some(u=>r.includes(u))?n+=18:Cr.some(u=>r.includes(u))?n+=10:Ar.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let l=(e.seniority||"").toLowerCase();l.includes("senior")||l.includes("lead")||l.includes("staff")?n+=10:l.includes("mid")?n+=5:(l.includes("entry")||l.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let a=new Set(e.jobTags||[]);return a.has("managerial")?n+=8:a.has("senior-ic")&&(n+=5),a.has("junior")&&(n-=15),a.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function Co(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=pt(),s=J(),i=new Set,r=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let c={connectedRecruiters:i,conversationRecruiters:r},l=gt(),a=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=l[f];return!(m&&a.has(m.status))}).map(([f,d])=>({jobId:f,score:xr(d,c),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function _r(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await nt();import Lr from"puppeteer";import{addExtra as Fr}from"puppeteer-extra";import Ur from"puppeteer-extra-plugin-stealth";Le();await nt();import ce from"fs";import Se from"path";var Tr="cookies.json";function Ao(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin","cookies.json"):Tr}function Dt(){let e=Ao();if(!ce.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ce.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function Eo(){return ce.existsSync(Ao())}function Rr(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin"):"."}function xo(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ir(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?xo(t[1]):"default"}function _o(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),Se.resolve(t);let n=xo(e||Ir()),o=Se.join(Rr(),"chrome-profile",n);return ce.existsSync(o)||ce.mkdirSync(o,{recursive:!0}),Se.resolve(o)}var To=".ilml-seeded";function Ro(e){return!ce.existsSync(Se.join(e,To))}function Io(e){try{ce.writeFileSync(Se.join(e,To),new Date().toISOString())}catch{}}function Do(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ce.rmSync(Se.join(e,n),{force:!0}),t++}catch{}return t}import rn from"fs";import Dr from"path";var Or={headless:!1,defaultViewport:null,protocolTimeout:3e5},bt=new Set,Oo=!1;async function Ot(){let e=[...bt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});bt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Nr(){if(Oo)return;Oo=!0;let e=t=>async()=>{await Ot(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ot(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ot(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ot(),process.exit(0))}),process.on("exit",()=>{for(let t of bt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function ln(e){return Dr.join(e,".ilml-browser-session.json")}function jo(e,t={}){try{rn.writeFileSync(ln(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Mr(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();jo(e,n?{wsEndpoint:n}:{})}catch{}}function Pr(e){let t=Lo(e);t&&t.ownerPid===process.pid&&wt(e)}function wt(e){try{rn.rmSync(ln(e),{force:!0})}catch{}}function Lo(e){try{return JSON.parse(rn.readFileSync(ln(e),"utf-8"))}catch{return null}}function No(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Mo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Po(e,t,{probeTimeoutMs:n=4e3}={}){let o=Lo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&No(o.ownerPid)?"live":(wt(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Mo(i,n,s);if(r===s)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!r)return wt(t),"free";if(No(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Mo(r.close().then(()=>!0).catch(()=>!1),n,!1))return wt(t),"free";try{r.disconnect()}catch{}return"live"}function jr(e,t){e&&(Nr(),bt.add(e),e.on("disconnected",()=>{bt.delete(e),t&&wt(t)}))}async function Fo(e,t={}){let n=_o(),o={...Or,...t,userDataDir:n},s=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Po(e,n)==="live")throw new Error(s);jo(n);let i;try{i=await e.launch(o)}catch{if(await Po(e,n)==="live")throw new Error(s);Do(n);try{i=await e.launch(o)}catch(c){throw Pr(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return jr(i,n),Mr(n,i),{browser:i,profileDir:n,needsSeed:Ro(n)}}async function Uo(e,t){if(!t||!t.needsSeed)return!1;if(!Eo())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(...Dt()),Io(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Ho=Fr(Lr);Ho.use(Ur());async function Jo(){let{browser:e,profileDir:t,needsSeed:n}=await Fo(Ho),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Uo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function an(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await k(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login (not logged in, or session expired). Run: ilml linkedin login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)}console.log(" Inbox loaded.")}async function Vo(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let l=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(l)||/^\s*Promoted\b/i.test(l))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(l.startsWith("You:"))d="me",m=l.slice(4).trim();else{let g=r.split(" ")[0];if(l.startsWith(r+":")||l.startsWith(g+":")){d="them";let b=l.indexOf(":");m=l.slice(b+1).trim()}else d="them",m=l}let y=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=Wt(n.lastMessageTime)||n.lastMessageTime;return t}async function cn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function qr(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.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 n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function un(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function qo(e,t){let n=await qr(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function Nt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:l,headerName:a}=await qo(e,t);if(l)return await k(500),{verified:!0,headerName:a};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await qo(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function Br(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let a=document.querySelector(".msg-overlay-conversation-bubble");a&&(r=a.querySelector(".msg-s-message-list-container")||a.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function dn(e,{scrollUp:t=!0}={}){t&&await Br(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let g=Number(y[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let l="";function a(u,f,d){let m=c(u),g=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let w=b.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 S=m?new Date(m).toISOString():d?`${d} ${g}`.trim():g;return{sender:f,text:w,time:S}}for(let u of r){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(l=f.textContent?.trim()||l);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let w of b){let S=a(w,g,l);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let y of m){let g=y.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let w=a(y,s||"Unknown",l);w&&o.push(w)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Wt(o.time)||o.time);return n}function fn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(a=>a.length>1),i=[...new Set(e.map(a=>a.sender).filter(a=>a&&a!=="Unknown"))],r=i.some(a=>{let u=a.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),c=z.toLowerCase().split(/\s+/),l=i.every(a=>{let u=a.toLowerCase();return c.some(f=>u.includes(f))});if(r)return!0;if(l){for(let a of e){let f=(a.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(y=>y===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let a=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return a.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ye(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function mn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Ye(d.sender)+"||"+Ye(d.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Fe.has(d.status)?!1:!o.has(n(d))),r=t.filter(d=>!s.has(n(d))),c=t.filter(d=>s.has(n(d))),l=e.filter(d=>Fe.has(d.status)),a=[...i,...c,...r],u=[];for(let d of a){let m=Ye(d.text),y=Ye(d.sender),g=!1;for(let b=0;b<u.length;b++){let w=u[b];if(Ye(w.sender)!==y)continue;let S=Ye(w.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=d,g=!0;break}}g||u.push(d)}return[...u,...l]}async function Wo(e,t){await an(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let l of c){let a=document.querySelector(l);if(a){a.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let a of l)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let d=a.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let l=await cn(e);if(!l)break;if(l.scrollTop===i){if(r++,r>=2)break}else r=0,i=l.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),Nt(e,t)):{verified:!1,headerName:null}}async function pn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let l of c)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let f=l.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await Nt(e,t);if(r.verified)return r}let o=Yn(t),s=o!==t?[t,o]:[t];for(let r of s)if(await Bo(e,r,t)){let l=await Nt(e,t);if(l.verified)return l}let i=Gn(o);if(i!==o&&i.length>0&&await Bo(e,i,t,{requireUnique:!0})){let c=await Nt(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function Bo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,l)=>{let a=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let g of f){let w=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=w.toLowerCase();if(S.includes(a)){let h=g.getBoundingClientRect();if(h.height>0){let p=w.includes(",")||/\d+ other/.test(w),v=S===u?3:S.includes(u)?2:1,C={text:w,isGroup:p,score:v,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):d.push(C)}}}d.sort((g,b)=>b.score-g.score);let y=[...d,...m];return l&&y.length!==1?null:d[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ve(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(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 k(1e3))}await wn();import"dotenv/config";import*as ee from"fs";import*as ke from"path";import{fileURLToPath as ri}from"url";import"dotenv/config";import{createGraphClient as ei,resolveToken as ti}from"@ilivemylife/graph-sdk";import{config as ni}from"dotenv";ni();var os=ti()||process.env.TOKEN;os||(console.error(`
242
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let p=lo(y.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,l&&await l(y,f,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let w=null;if(r){let v=await Dn(e,y.profileUrl);v?(Re(y.profileUrl,{...v,source:u}),f.viewed++,w={success:!0,reason:"viewed",connectionSent:!1,profileInfo:v,resolvedUrl:v.resolvedUrl}):(f.errors++,w={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let v=Zt();if(!v.allowed){console.log(` \u26A0 Global quota exhausted: ${v.reason}`);break}if(w=await Nn(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:c,source:u,skipQuotaGate:!0}),w.success)f.connectionsSent++;else switch(w.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(w?.fatal){console.log(`
243
+ \u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(w?.reason==="error"){if(d++,d>=3){console.log(`
244
+ \u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(w&&w.reason&&(ao(y.profileUrl,w.reason,{method:w.method,messageSent:w.messageSent,profileInfo:w.profileInfo}),w.resolvedUrl&&Tt(y.profileUrl,w.resolvedUrl),io(y.profileUrl,{source:u||"funnel",jobId:y.jobId||y.fromJob?.jobId||null,jobTitle:y.fromJob?.title||null,jobCompany:y.fromJob?.company||null,action:w.reason})),l&&await l(y,f,w),m<t.length-1){let v=a+Math.random()*2e3;await $(v)}}if(console.log(`
245
+ === Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!r){let m=ut();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return f}var dl,Rs=de(async()=>{Fe();await Ve();dl={viewProfile:Dn,detectConnectionStatus:Ae,findConnectButton:At,clickConnectButton:On,sendConnectionRequest:Nn,runFunnel:_s,shouldExcludeLocation:Jt}});Fe();await Ve();bt();await Ve();bt();var Cr=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),Ar=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Ao=["vancouver","british columbia"],xr=["canada","montreal","quebec","alberta","calgary","ottawa"],Er=["toronto","ontario"],_r=["india","pakistan","nigeria","philippines"];function Tr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Cr.has(u)&&s++,Ar.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Rr(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),a=/remote/i.test(r)||e.workplaceType==="remote";_r.some(u=>r.includes(u))?n-=30:a&&/united states|usa|\bus\b/i.test(r)?n+=25:a&&Ao.some(u=>r.includes(u))?n+=22:a?n+=20:Ao.some(u=>r.includes(u))?n+=18:xr.some(u=>r.includes(u))?n+=10:Er.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let l=(e.seniority||"").toLowerCase();l.includes("senior")||l.includes("lead")||l.includes("staff")?n+=10:l.includes("mid")?n+=5:(l.includes("entry")||l.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let c=new Set(e.jobTags||[]);return c.has("managerial")?n+=8:c.has("senior-ic")&&(n+=5),c.has("junior")&&(n-=15),c.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function xo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=ht(),s=H(),i=new Set,r=new Set;for(let[f,d]of Object.entries(s))d.connectionStatus==="connected"&&i.add(f);let a={connectedRecruiters:i,conversationRecruiters:r},l=yt(),c=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([f,d])=>{if(typeof d!="object"||n&&!d.isEasyApply||d.applied)return!1;let m=l[f];return!(m&&c.has(m.status))}).map(([f,d])=>({jobId:f,score:Tr(d,a),job:d})).sort((f,d)=>{if(d.score!==f.score)return d.score-f.score;let m=f.job.scoutedAt||f.job.postedTime||"";return(d.job.scoutedAt||d.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Rr(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await st();import Ur from"puppeteer";import{addExtra as qr}from"puppeteer-extra";import Br from"puppeteer-extra-plugin-stealth";Fe();await st();import ce from"fs";import ve from"path";var Ir="cookies.json";function Eo(){let e=process.env.ILML_SCOPE_DIR;return e?ve.join(e,"plugins-state","linkedin","cookies.json"):Ir}function Nt(){let e=Eo();if(!ce.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ce.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function _o(){return ce.existsSync(Eo())}function Dr(){let e=process.env.ILML_SCOPE_DIR;return e?ve.join(e,"plugins-state","linkedin"):"."}function To(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Or(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?To(t[1]):"default"}function Ro(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),ve.resolve(t);let n=To(e||Or()),o=ve.join(Dr(),"chrome-profile",n);return ce.existsSync(o)||ce.mkdirSync(o,{recursive:!0}),ve.resolve(o)}var Io=".ilml-seeded";function Do(e){return!ce.existsSync(ve.join(e,Io))}function Oo(e){try{ce.writeFileSync(ve.join(e,Io),new Date().toISOString())}catch{}}function No(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ce.rmSync(ve.join(e,n),{force:!0}),t++}catch{}return t}import an from"fs";import Nr from"path";var Mr={headless:!1,defaultViewport:null,protocolTimeout:3e5},vt=new Set,Mo=!1;async function Mt(){let e=[...vt].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});vt.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Pr(){if(Mo)return;Mo=!0;let e=t=>async()=>{await Mt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Mt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Mt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Mt(),process.exit(0))}),process.on("exit",()=>{for(let t of vt)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function cn(e){return Nr.join(e,".ilml-browser-session.json")}function Fo(e,t={}){try{an.writeFileSync(cn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function jr(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Fo(e,n?{wsEndpoint:n}:{})}catch{}}function Lr(e){let t=Uo(e);t&&t.ownerPid===process.pid&&St(e)}function St(e){try{an.rmSync(cn(e),{force:!0})}catch{}}function Uo(e){try{return JSON.parse(an.readFileSync(cn(e),"utf-8"))}catch{return null}}function Po(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function jo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Lo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Uo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Po(o.ownerPid)?"live":(St(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await jo(i,n,s);if(r===s)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!r)return St(t),"free";if(Po(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await jo(r.close().then(()=>!0).catch(()=>!1),n,!1))return St(t),"free";try{r.disconnect()}catch{}return"live"}function Fr(e,t){e&&(Pr(),vt.add(e),e.on("disconnected",()=>{vt.delete(e),t&&St(t)}))}async function qo(e,t={}){let n=Ro(),o={...Mr,...t,userDataDir:n},s=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Lo(e,n)==="live")throw new Error(s);Fo(n);let i;try{i=await e.launch(o)}catch{if(await Lo(e,n)==="live")throw new Error(s);No(n);try{i=await e.launch(o)}catch(a){throw Lr(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return Fr(i,n),jr(n,i),{browser:i,profileDir:n,needsSeed:Do(n)}}async function Bo(e,t){if(!t||!t.needsSeed)return!1;if(!_o())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()),Oo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Vo=qr(Ur);Vo.use(Br());async function Wo(){let{browser:e,profileDir:t,needsSeed:n}=await qo(Vo),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Bo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function un(e){if(await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),!await nt(e,".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:45e3,label:"inbox"})){let n=e.url();if(n.includes("/login")||n.includes("/authwall"))throw new Error("Redirected to login (not logged in, or session expired). Run: ilml linkedin login");console.warn(" Inbox container not found via known selectors, proceeding..."),await $(3e3)}console.log(" Inbox loaded.")}async function Yo(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let l=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(l)||/^\s*Promoted\b/i.test(l))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",f=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,d,m;if(l.startsWith("You:"))d="me",m=l.slice(4).trim();else{let p=r.split(" ")[0];if(l.startsWith(r+":")||l.startsWith(p+":")){d="them";let w=l.indexOf(":");m=l.slice(w+1).trim()}else d="them",m=l}let y=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:f,lastMessageBy:d,x:y.x+y.width/2,y:y.y+y.height/2})}return o});for(let n of t)n.lastMessageTime=Gt(n.lastMessageTime)||n.lastMessageTime;return t}async function dn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Hr(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.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 n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function fn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Ho(e,t){let n=await Hr(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(a=>a.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(a=>i.includes(a)),headerName:n}}async function Pt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:l,headerName:c}=await Ho(e,t);if(l)return await $(500),{verified:!0,headerName:c};let u=await e.evaluate(()=>{let f=document.querySelectorAll(".msg-s-message-group__name"),d=Array.from(f).map(y=>y.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:d,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(d=>d.toLowerCase().includes(n.toLowerCase())))return await $(300),{verified:!0,headerName:n};await $(s),i+=s}let{match:r,headerName:a}=await Ho(e,t);return r?{verified:!0,headerName:a}:{verified:!1,headerName:a}}async function Jr(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let c=document.querySelector(".msg-overlay-conversation-bubble");c&&(r=c.querySelector(".msg-s-message-list-container")||c.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let a=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:a}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:a})});if(!i.found||i.atTop)break;if(await $(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function mn(e,{scrollUp:t=!0}={}){t&&await Jr(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function a(u){let f=u.getAttribute("data-event-urn");if(!f)return null;let d=f.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!d)return null;try{let y=atob(d[1]).match(/^(\d{13})/);if(!y)return null;let p=Number(y[1]);if(p>14200704e5&&p<20512224e5)return p}catch{}return null}let l="";function c(u,f,d){let m=a(u),p=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",w=u.querySelector(".msg-s-event-listitem__message-bubble");if(!w)return null;let v=w.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!v)return null;let S=m?new Date(m).toISOString():d?`${d} ${p}`.trim():p;return{sender:f,text:v,time:S}}for(let u of r){let f=u.querySelector("time.msg-s-message-list__time-heading");f&&(l=f.textContent?.trim()||l);let d=u.querySelectorAll(".msg-s-message-group");if(d.length>0)for(let m of d){let y=m.querySelector(".msg-s-message-group__name");y&&(s=y.textContent?.trim()||s);let p=s||"Unknown",w=m.querySelectorAll(".msg-s-event-listitem");for(let v of w){let S=c(v,p,l);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let y of m){let p=y.querySelector(".msg-s-message-group__name");p&&(s=p.textContent?.trim()||s);let v=c(y,s||"Unknown",l);v&&o.push(v)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let f of u){let d=f.textContent?.trim();d&&o.push({sender:"",text:d,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Gt(o.time)||o.time);return n}function pn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=[...new Set(e.map(c=>c.sender).filter(c=>c&&c!=="Unknown"))],r=i.some(c=>{let u=c.toLowerCase();return u.includes(o)||s.some(f=>u.includes(f))}),a=z.toLowerCase().split(/\s+/),l=i.every(c=>{let u=c.toLowerCase();return a.some(f=>u.includes(f))});if(r)return!0;if(l){for(let c of e){let f=(c.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(f){let d=f[1].toLowerCase();if(d!=="there"&&d!=="all"&&!(s.some(y=>y===d)||d===o))return console.log(` STALE DATA: message says "Hi ${f[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let c=n.map(f=>f.toLowerCase());if(i.some(f=>{let d=f.toLowerCase();return c.some(m=>d.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ge(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function gn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=d=>Ge(d.sender)+"||"+Ge(d.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(d=>Ue.has(d.status)?!1:!o.has(n(d))),r=t.filter(d=>!s.has(n(d))),a=t.filter(d=>s.has(n(d))),l=e.filter(d=>Ue.has(d.status)),c=[...i,...a,...r],u=[];for(let d of c){let m=Ge(d.text),y=Ge(d.sender),p=!1;for(let w=0;w<u.length;w++){let v=u[w];if(Ge(v.sender)!==y)continue;let S=Ge(v.text);if(m.length>S.length&&m.endsWith(S)){p=!0;break}if(S.length>m.length&&S.endsWith(m)){u[w]=d,p=!0;break}}p||u.push(d)}return[...u,...l]}async function Go(e,t){await un(e),await $(2500),await e.evaluate(()=>{let a=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let l of a){let c=document.querySelector(l);if(c){c.scrollTop=0;return}}}),await $(500);async function n(){return e.evaluate(a=>{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," ")===a){let d=c.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let a=0;a<s&&!o;a++){let l=await dn(e);if(!l)break;if(l.scrollTop===i){if(r++,r>=2)break}else r=0,i=l.scrollTop;await $(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await $(3e3),Pt(e,t)):{verified:!1,headerName:null}}async function hn(e,t){let n=await e.evaluate(r=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let f=l.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await $(3e3);let r=await Pt(e,t);if(r.verified)return r}let o=zn(t),s=o!==t?[t,o]:[t];for(let r of s)if(await Jo(e,r,t)){let l=await Pt(e,t);if(l.verified)return l}let i=Kn(o);if(i!==o&&i.length>0&&await Jo(e,i,t,{requireUnique:!0})){let a=await Pt(e,t);if(a.verified)return a}return{verified:!1,headerName:null}}async function Jo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await $(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await $(300),await i.type(t,{delay:30}),await $(500),await e.keyboard.press("Enter"),await $(3500);let r=await e.evaluate((a,l)=>{let c=a.split(" ")[0].toLowerCase(),u=a.toLowerCase(),f=document.querySelectorAll(".msg-conversation-listitem"),d=[],m=[];for(let p of f){let v=p.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=v.toLowerCase();if(S.includes(c)){let g=p.getBoundingClientRect();if(g.height>0){let h=v.includes(",")||/\d+ other/.test(v),b=S===u?3:S.includes(u)?2:1,k={text:v,isGroup:h,score:b,x:g.x+g.width/2,y:g.y+g.height/2};h?m.push(k):d.push(k)}}}d.sort((p,w)=>w.score-p.score);let y=[...d,...m];return l&&y.length!==1?null:d[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ke(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await $(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 $(1e3))}await Sn();import"dotenv/config";import*as te from"fs";import*as $e from"path";import{fileURLToPath as li}from"url";import"dotenv/config";import{createGraphClient as ni,resolveToken as oi}from"@ilivemylife/graph-sdk";import{config as si}from"dotenv";si();var rs=oi()||process.env.TOKEN;rs||(console.error(`
246
246
  [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.
247
247
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
248
248
  `),console.error(` Or add ILML_TOKEN=... to .env
249
- `),process.exit(1));var ss=ei({token:os});function oi(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function si({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${oi(s)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${l} \u2014 ${r}${c}`}async function rs({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(o)||o.length===0)return;let l=`**${si({scriptName:e,mode:t,status:n,error:s,duration:i})}**
249
+ `),process.exit(1));var is=ni({token:rs});function ri(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function ii({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),a=s?` ${ri(s)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${l} \u2014 ${r}${a}`}async function ls({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(o)||o.length===0)return;let l=`**${ii({scriptName:e,mode:t,status:n,error:s,duration:i})}**
250
250
 
251
251
  ${o.join(`
252
- `)}`;try{await ss.addMessage(r,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var ii=ri(import.meta.url),li=ke.dirname(ke.dirname(ii)),bn=process.env.DATA_DIR?ke.resolve(process.env.DATA_DIR,"collected-profiles"):ke.join(li,"collected-profiles"),Sn=ke.join(bn,"run-log.json");function ai(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";ee.writeFileSync(o,n);for(let s=0;s<3;s++)try{ee.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function Lt(){try{if(!ee.existsSync(Sn))return{runs:[]};let e=JSON.parse(ee.readFileSync(Sn,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function is(e){ee.existsSync(bn)||ee.mkdirSync(bn,{recursive:!0});try{ai(Sn,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ft(e,t="default"){let n=Lt();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),is(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Ke(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=Lt(),c=r.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,s=c.duration;else{let l=r.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration)}is(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";rs({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}function ci(){let e=new Date().toISOString().slice(0,10),t=Lt(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function ui(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function ls(){let e=["sync-all","messages","funnel","sync","apply"],t=Lt(),n=ci(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let r=t.runs.filter(g=>g.script===i),c=[...r].reverse().find(g=>g.status==="success"),l=r[r.length-1],a=c||l,u=a?ui(a.timestamp):"never",d=(a?Math.floor((Date.now()-new Date(a.timestamp).getTime())/864e5):1/0)>1?" \u26A0":a?.status==="error"?" \u2717":" \u2713",m="";if(a?.stats){let g=a.stats,b=Object.entries(g).filter(([,w])=>typeof w=="number"&&w>0).slice(0,3).map(([w,S])=>`${S} ${w}`);b.length&&(m=` (${b.join(", ")})`)}let y=a?.duration?` ${Math.round(a.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${y}${m}${d}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,r]of s){let c=[];r.success&&c.push(`${r.success} success`),r.error&&c.push(`${r.error} error`),r.interrupted&&c.push(`${r.interrupted} interrupted`),r.running&&c.push(`${r.running} running`),o.push(` Today: ${i} \xD7${r.total} (${c.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
253
- `)}import"dotenv/config";import*as E from"fs";import*as _n from"os";import*as P from"path";import{fileURLToPath as Ni}from"url";var $n={};ae($n,{NAME:()=>fi,VERSION:()=>di,up:()=>gi});import*as te from"fs";import*as Ut from"path";var di=1,fi="normalize-jobs-and-questions",mi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],pi=50;function vn(e){return te.existsSync(e)?JSON.parse(te.readFileSync(e,"utf-8")):null}function kn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{te.writeFileSync(o,n)}catch(s){try{te.unlinkSync(o)}catch{}throw s}try{te.renameSync(o,e)}catch(s){try{te.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function gi(e,t){let n=Ut.join(e,"jobs.json"),o=Ut.join(t,"scouted-jobs.json"),s=Ut.join(e,"application-questions.json"),i=vn(n)||{},r=vn(o)||{},c=0,l=[];for(let u of Object.keys(i)){if(!r[u])continue;let f=r[u],d=i[u];for(let m of mi)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),c++}c>0?(kn(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=vn(s);if(a&&Array.isArray(a.applications)){let u={},f=0;for(let d of a.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let y=(d.questions||[]).map(g=>{let b={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=pi?b.options=g.options:(b.optionsOmitted=!0,f++)),g.page&&(b.page=g.page),g.wasPreFilled&&(b.wasPreFilled=!0),g.wasRetry&&(b.wasRetry=!0),b});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||y.length,questions:y})}kn(s,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete r[u];kn(o,r),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Cn={};ae(Cn,{NAME:()=>yi,VERSION:()=>hi,up:()=>Si});import*as ne from"fs";import*as as from"path";var hi=2,yi="reset-unread-flags";function wi(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function bi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Si(e){let t=as.join(e,"conversations.json"),n=wi(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}bi(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var An={};ae(An,{NAME:()=>ki,VERSION:()=>vi,up:()=>xi});import*as oe from"fs";import*as cs from"path";var vi=3,ki="recompute-last-message-by",$i=new Set(["draft","confirmed","rejected","needs_review"]);function Ci(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function Ai(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function Ei(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!$i.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let r=i.sender;if(r===t)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function xi(e){let t=cs.join(e,"conversations.json"),n=Ci(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,r=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=Ei(a,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&r++,l.lastMessageBy=u,l.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}Ai(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var En={};ae(En,{NAME:()=>Ti,VERSION:()=>_i,up:()=>Oi});import*as se from"fs";import*as us from"path";var _i=4,Ti="split-connection-timestamps",Ri=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ii(e){if(!se.existsSync(e))return null;let t=se.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Di(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{se.writeFileSync(o,n)}catch(s){try{se.unlinkSync(o)}catch{}throw s}try{se.renameSync(o,e)}catch(s){try{se.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Oi(e){let t=us.join(e,"people.json"),n=Ii(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,Ri.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Di(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Je();yt();var Mi=Ni(import.meta.url),Pi=P.dirname(Mi),ji=P.dirname(P.dirname(Pi));function Li(e){return e&&(e==="~"?_n.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(_n.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?P.resolve(Li(process.env.DATA_DIR)):ji,Ne=P.join(ue,"collected-profiles"),Me=P.join(ue,"market-research"),Y=P.join(ue,".schema-version"),ds=[P.join(Ne,".schema-version"),P.join(Me,".schema-version")],$e=4,pe=[{version:1,module:$n},{version:2,module:Cn},{version:3,module:An},{version:4,module:En}];(function(){pe.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of pe){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=pe.length?pe[pe.length-1].version:0;if(n!==$e)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${$e}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<pe.length;o++){let s=o+1;if(pe[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${pe[o].version}`)}})();function gs(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
252
+ `)}`;try{await is.addMessage(r,l)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var ai=li(import.meta.url),ci=$e.dirname($e.dirname(ai)),vn=process.env.DATA_DIR?$e.resolve(process.env.DATA_DIR,"collected-profiles"):$e.join(ci,"collected-profiles"),kn=$e.join(vn,"run-log.json");function ui(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";te.writeFileSync(o,n);for(let s=0;s<3;s++)try{te.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function Ut(){try{if(!te.existsSync(kn))return{runs:[]};let e=JSON.parse(te.readFileSync(kn,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function as(e){te.existsSync(vn)||te.mkdirSync(vn,{recursive:!0});try{ui(kn,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function qt(e,t="default"){let n=Ut();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),as(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Qe(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=Ut(),a=r.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration;else{let l=r.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration)}as(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";ls({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}function di(){let e=new Date().toISOString().slice(0,10),t=Ut(),n={};for(let o of t.runs){if(!o.timestamp.startsWith(e))continue;n[o.script]||(n[o.script]={total:0,success:0,error:0,interrupted:0,partial:0,running:0,lastRun:null});let s=n[o.script];s.total++,o.status==="success"?s.success++:o.status==="error"?s.error++:o.status==="interrupted"?s.interrupted++:o.status==="partial"?s.partial++:o.status==="running"&&s.running++,s.lastRun=o}return n}function fi(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s===1?"yesterday":`${s} days ago`}function cs(){let e=["sync-all","messages","funnel","sync","apply"],t=Ut(),n=di(),o=[];o.push("\u2550\u2550\u2550 SCRIPT STATUS \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let i of e){let r=t.runs.filter(p=>p.script===i),a=[...r].reverse().find(p=>p.status==="success"),l=r[r.length-1],c=a||l,u=c?fi(c.timestamp):"never",d=(c?Math.floor((Date.now()-new Date(c.timestamp).getTime())/864e5):1/0)>1?" \u26A0":c?.status==="error"?" \u2717":" \u2713",m="";if(c?.stats){let p=c.stats,w=Object.entries(p).filter(([,v])=>typeof v=="number"&&v>0).slice(0,3).map(([v,S])=>`${S} ${v}`);w.length&&(m=` (${w.join(", ")})`)}let y=c?.duration?` ${Math.round(c.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${u.padEnd(16)}${y}${m}${d}`)}let s=Object.entries(n);if(s.length>0){o.push("");for(let[i,r]of s){let a=[];r.success&&a.push(`${r.success} success`),r.error&&a.push(`${r.error} error`),r.interrupted&&a.push(`${r.interrupted} interrupted`),r.running&&a.push(`${r.running} running`),o.push(` Today: ${i} \xD7${r.total} (${a.join(", ")})`)}}return o.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),o.join(`
253
+ `)}import"dotenv/config";import*as x from"fs";import*as Rn from"os";import*as P from"path";import{fileURLToPath as Pi}from"url";var An={};ae(An,{NAME:()=>pi,VERSION:()=>mi,up:()=>yi});import*as ne from"fs";import*as Bt from"path";var mi=1,pi="normalize-jobs-and-questions",gi=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],hi=50;function $n(e){return ne.existsSync(e)?JSON.parse(ne.readFileSync(e,"utf-8")):null}function Cn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ne.writeFileSync(o,n)}catch(s){try{ne.unlinkSync(o)}catch{}throw s}try{ne.renameSync(o,e)}catch(s){try{ne.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function yi(e,t){let n=Bt.join(e,"jobs.json"),o=Bt.join(t,"scouted-jobs.json"),s=Bt.join(e,"application-questions.json"),i=$n(n)||{},r=$n(o)||{},a=0,l=[];for(let u of Object.keys(i)){if(!r[u])continue;let f=r[u],d=i[u];for(let m of gi)f[m]!=null&&d[m]==null&&(d[m]=f[m]);l.push(u),a++}a>0?(Cn(n,i),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let c=$n(s);if(c&&Array.isArray(c.applications)){let u={},f=0;for(let d of c.applications){let m=d.jobId||"unknown";u[m]||(u[m]={applications:[]});let y=(d.questions||[]).map(p=>{let w={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=hi?w.options=p.options:(w.optionsOmitted=!0,f++)),p.page&&(w.page=p.page),p.wasPreFilled&&(w.wasPreFilled=!0),p.wasRetry&&(w.wasRetry=!0),w});u[m].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||y.length,questions:y})}Cn(s,u),console.log(` Phase 2: Rekeyed ${c.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),f>0&&console.log(` Phase 2: Stripped bloated options from ${f} questions`)}else c&&!c.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let u of l)delete r[u];Cn(o,r),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var xn={};ae(xn,{NAME:()=>bi,VERSION:()=>wi,up:()=>ki});import*as oe from"fs";import*as us from"path";var wi=2,bi="reset-unread-flags";function Si(e){return oe.existsSync(e)?JSON.parse(oe.readFileSync(e,"utf-8")):null}function vi(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{oe.writeFileSync(o,n)}catch(s){try{oe.unlinkSync(o)}catch{}throw s}try{oe.renameSync(o,e)}catch(s){try{oe.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function ki(e){let t=us.join(e,"conversations.json"),n=Si(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}vi(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var En={};ae(En,{NAME:()=>Ci,VERSION:()=>$i,up:()=>Ti});import*as se from"fs";import*as ds from"path";var $i=3,Ci="recompute-last-message-by",Ai=new Set(["draft","confirmed","rejected","needs_review"]);function xi(e){return se.existsSync(e)?JSON.parse(se.readFileSync(e,"utf-8")):null}function Ei(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{se.writeFileSync(o,n)}catch(s){try{se.unlinkSync(o)}catch{}throw s}try{se.renameSync(o,e)}catch(s){try{se.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function _i(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Ai.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let r=i.sender;if(r===t)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function Ti(e){let t=ds.join(e,"conversations.json"),n=xi(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,r=0;for(let a of Object.keys(n)){let l=n[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let c=Array.isArray(l.messages)?l.messages:[],u=_i(c,o),f=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&r++,l.lastMessageBy=u,l.conversationStatus=f,s++}if(s===0){console.log(" No conversations to recompute.");return}Ei(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var _n={};ae(_n,{NAME:()=>Ii,VERSION:()=>Ri,up:()=>Mi});import*as re from"fs";import*as fs from"path";var Ri=4,Ii="split-connection-timestamps",Di=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Oi(e){if(!re.existsSync(e))return null;let t=re.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ni(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{re.writeFileSync(o,n)}catch(s){try{re.unlinkSync(o)}catch{}throw s}try{re.renameSync(o,e)}catch(s){try{re.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Mi(e){let t=fs.join(e,"people.json"),n=Oi(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,Di.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ni(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Ve();bt();var ji=Pi(import.meta.url),Li=P.dirname(ji),Fi=P.dirname(P.dirname(Li));function Ui(e){return e&&(e==="~"?Rn.homedir():e.startsWith("~/")||e.startsWith("~\\")?P.join(Rn.homedir(),e.slice(2)):e)}var ue=process.env.DATA_DIR?P.resolve(Ui(process.env.DATA_DIR)):Fi,Me=P.join(ue,"collected-profiles"),Pe=P.join(ue,"market-research"),G=P.join(ue,".schema-version"),ms=[P.join(Me,".schema-version"),P.join(Pe,".schema-version")],Ce=4,pe=[{version:1,module:An},{version:2,module:xn},{version:3,module:En},{version:4,module:_n}];(function(){pe.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of pe){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=pe.length?pe[pe.length-1].version:0;if(n!==Ce)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${Ce}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<pe.length;o++){let s=o+1;if(pe[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${pe[o].version}`)}})();function ys(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
254
254
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
255
- `),process.exit(1));try{E.mkdirSync(ue,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
+ `),process.exit(1));try{x.mkdirSync(ue,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
256
256
  [FATAL] Cannot create DATA_DIR (${ue}): ${t.message}`),console.error(` Fix the path or permissions and try again.
257
- `),process.exit(1))}let e;try{e=E.statSync(ue)}catch(t){console.error(`
257
+ `),process.exit(1))}let e;try{e=x.statSync(ue)}catch(t){console.error(`
258
258
  [FATAL] DATA_DIR (${ue}) is not accessible: ${t.message}
259
259
  `),process.exit(1)}e.isDirectory()||(console.error(`
260
260
  [FATAL] DATA_DIR (${ue}) 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.
261
- `),process.exit(1));for(let t of[Ne,Me]){let n;try{n=E.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
261
+ `),process.exit(1));for(let t of[Me,Pe]){let n;try{n=x.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
262
262
  [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.
263
- `),process.exit(1))}}var Oe=P.join(ue,".migration-lock");function Fi(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return E.writeFileSync(Oe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(E.readFileSync(Oe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
264
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Oe}
263
+ `),process.exit(1))}}var Ne=P.join(ue,".migration-lock");function qi(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return x.writeFileSync(Ne,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(x.readFileSync(Ne,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
264
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Ne}
265
265
  `),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.
266
- `),process.exit(1)),o&&i>=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 n=Oe+".tmp";try{return E.writeFileSync(n,e),E.renameSync(n,Oe),!0}catch(o){try{E.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Tn(){try{if(JSON.parse(E.readFileSync(Oe,"utf-8")).pid!==process.pid)return;E.unlinkSync(Oe)}catch{}}var fs=!1;function Ui(){if(fs)return;fs=!0;let e=()=>{try{Tn()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function qi(){if(E.existsSync(Y))return;let e=[],t=[];for(let i of ds)if(E.existsSync(i))try{e.push({file:i,schema:qt(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
266
+ `),process.exit(1)),o&&i>=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 n=Ne+".tmp";try{return x.writeFileSync(n,e),x.renameSync(n,Ne),!0}catch(o){try{x.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function In(){try{if(JSON.parse(x.readFileSync(Ne,"utf-8")).pid!==process.pid)return;x.unlinkSync(Ne)}catch{}}var ps=!1;function Bi(){if(ps)return;ps=!0;let e=()=>{try{In()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Hi(){if(x.existsSync(G))return;let e=[],t=[];for(let i of ms)if(x.existsSync(i))try{e.push({file:i,schema:Ht(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
267
267
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
268
268
  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.
269
269
  `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
270
270
  [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
271
- `),process.exit(1)}let o=e[0].schema,s=Y+".tmp";try{E.writeFileSync(s,JSON.stringify(o,null,2)),E.renameSync(s,Y)}catch(i){try{E.unlinkSync(s)}catch{}throw i}for(let i of ds)if(E.existsSync(i))try{E.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${Y}`)}function Bi(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 qt(e){let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ms(){if(qi(),!E.existsSync(Y))return{version:0,migrations:[]};let e;try{e=qt(Y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
272
- [FATAL] ${Y} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
273
- `),process.exit(1)}let t=Bi(e);return t===null&&(console.error(`
274
- [FATAL] ${Y} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
275
- `),process.exit(1)),t}function hs(e){try{E.chmodSync(e,384)}catch{}}function Hi(e){if(gs(),E.existsSync(Y))try{if(E.lstatSync(Y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${Y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=Y+".tmp";try{E.writeFileSync(t,JSON.stringify(e,null,2)),hs(t),E.renameSync(t,Y)}catch(n){try{E.unlinkSync(t)}catch{}throw n}}function ps(e,t){if(!E.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=E.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return E.statSync(P.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let c of o){let l=P.join(e,c),a=P.join(e,c+n);if(E.existsSync(a)){i++;continue}try{ws(l,a),s++}catch(u){r.push({file:c,err:u.message})}}if(r.length>0){let c=new Error(`Failed to back up ${r.length} file(s) in ${P.basename(e)}/: `+r.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${P.basename(e)}/ (${n})${c}`)}}var xn=!1;async function ys(){if(xn)return;gs(),Gi();let t=ms().version;if(t===$e){xn=!0;return}Ui(),Fi(),process.on("exit",Tn),t>$e&&(console.error(`
276
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${$e}.`),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.
277
- `),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${$e}.
271
+ `),process.exit(1)}let o=e[0].schema,s=G+".tmp";try{x.writeFileSync(s,JSON.stringify(o,null,2)),x.renameSync(s,G)}catch(i){try{x.unlinkSync(s)}catch{}throw i}for(let i of ms)if(x.existsSync(i))try{x.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function Ji(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 Ht(e){let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function gs(){if(Hi(),!x.existsSync(G))return{version:0,migrations:[]};let e;try{e=Ht(G)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
272
+ [FATAL] ${G} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
273
+ `),process.exit(1)}let t=Ji(e);return t===null&&(console.error(`
274
+ [FATAL] ${G} 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.
275
+ `),process.exit(1)),t}function ws(e){try{x.chmodSync(e,384)}catch{}}function Vi(e){if(ys(),x.existsSync(G))try{if(x.lstatSync(G).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${G}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=G+".tmp";try{x.writeFileSync(t,JSON.stringify(e,null,2)),ws(t),x.renameSync(t,G)}catch(n){try{x.unlinkSync(t)}catch{}throw n}}function hs(e,t){if(!x.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=x.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return x.statSync(P.join(e,a)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let a of o){let l=P.join(e,a),c=P.join(e,a+n);if(x.existsSync(c)){i++;continue}try{Ss(l,c),s++}catch(u){r.push({file:a,err:u.message})}}if(r.length>0){let a=new Error(`Failed to back up ${r.length} file(s) in ${P.basename(e)}/: `+r.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(s>0||i>0){let a=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${P.basename(e)}/ (${n})${a}`)}}var Tn=!1;async function bs(){if(Tn)return;ys(),Ki();let t=gs().version;if(t===Ce){Tn=!0;return}Bi(),qi(),process.on("exit",In),t>Ce&&(console.error(`
276
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Ce}.`),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.
277
+ `),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${Ce}.
278
278
  `),process.exit(1)),console.log(`
279
- \u{1F4E6} Schema migration: v${t} \u2192 v${$e}`);let n=zi();if(!n.ok){console.error(`
279
+ \u{1F4E6} Schema migration: v${t} \u2192 v${Ce}`);let n=Qi();if(!n.ok){console.error(`
280
280
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
281
281
  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'.
282
282
  `),process.exit(1)}let o=pe.filter(s=>s.version>t);for(let s of o){console.log(`
283
- Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{ps(Ne,s.version),ps(Me,s.version)}catch(l){console.error(`
283
+ Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{hs(Me,s.version),hs(Pe,s.version)}catch(l){console.error(`
284
284
  [FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
285
- `),process.exit(1)}let c=s.module;try{await c.up(Ne,Me)}catch(l){console.error(`
286
- [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let a=Ki(r);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.
287
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
288
- `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
289
- `)}process.exit(1)}try{let l=new Date().toISOString(),a={version:s.version,name:c.NAME||i,appliedAt:l},u=ms();u.version=s.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Hi(u)}catch(l){console.error(`
285
+ `),process.exit(1)}let a=s.module;try{await a.up(Me,Pe)}catch(l){console.error(`
286
+ [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let c=Zi(r);c.ok?(console.error(` \u2713 Auto-rollback restored ${c.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
287
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${c.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
288
+ `))}catch(c){console.error(` [!] Auto-rollback CRASHED while restoring: ${c.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
289
+ `)}process.exit(1)}try{let l=new Date().toISOString(),c={version:s.version,name:a.NAME||i,appliedAt:l},u=gs();u.version=s.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(c),Vi(u)}catch(l){console.error(`
290
290
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.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 ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
291
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{no()}catch{}try{nn()}catch{}xn=!0,Tn(),console.log(`
292
- \u2713 Schema is now at v${$e}
293
- `)}var Ji=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Vi(e){let t=e.toLowerCase();return Ji.some(n=>n.test(t))}var Wi=6e4;function Yi(){let e=Date.now(),t=[];for(let n of[ue,Ne,Me]){if(!E.existsSync(n))continue;let o;try{o=E.readdirSync(n)}catch{continue}for(let s of o){if(!Vi(s))continue;let i=P.join(n,s);try{let r=E.statSync(i);if(!r.isFile()||e-r.mtimeMs<Wi)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Gi({verbose:e=!1}={}){let t=Yi();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{E.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${P.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function zi(){let e=[];for(let t of[Ne,Me]){if(!E.existsSync(t))continue;let n=E.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=P.join(t,o);try{qt(s)}catch(i){e.push({dir:P.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ki(e){let t=[],n=[];for(let i of[Ne,Me]){if(!E.existsSync(i))continue;let r=E.readdirSync(i).filter(c=>c.endsWith(e));for(let c of r){let l=P.join(i,c),a=c.slice(0,-e.length),u=P.join(i,a);try{a.toLowerCase().endsWith(".json")?qt(l):E.accessSync(l,E.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(f){n.push(`${P.basename(i)}/${c}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:c,dir:l}of t)try{ws(i,r),o++}catch(a){s.push(`${P.basename(l)}/${c}: ${a.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function ws(e,t){let n=t+".tmp";try{E.copyFileSync(e,n),hs(n)}catch(o){try{E.unlinkSync(n)}catch{}throw o}try{E.renameSync(n,t)}catch(o){try{E.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}Le();async function Qi(e,t,n="op"){let o,s=new Promise((i,r)=>{o=setTimeout(()=>r(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function Pe(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function bs(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await Qi(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let r=await e.newPage();if(i)try{await i(r)}catch{}if(s)try{let c=s();Array.isArray(c)&&c.length>0&&await r.setCookie(...c)}catch{}if(n){await r.goto(n,{waitUntil:"domcontentloaded",timeout:o});let c=r.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(c))throw new Error(`Session expired after recovery \u2014 landed on ${c}. Run: ilml linkedin login`)}return r}await ys();var Ns="https://www.linkedin.com/messaging/",ul=10,On=3,dl=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},fl=()=>Dt(),je={pageRecoveries:0};async function Ht(e,t){if(je.pageRecoveries>=ul)throw new Error(`CDP unrecoverable: ${je.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
294
- \u{1F504} CDP dead \u2014 recovering page (#${je.pageRecoveries+1}). Reason: ${t}`),e.page=await bs(e.browser,e.page,{returnUrl:Ns,cookiesProvider:fl,setupPage:dl}),je.pageRecoveries++,await k(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${je.pageRecoveries}).
295
- `)}function Ze(e){return(e.messages||[]).find(t=>tt.has(t.status))?.status}var Q=process.argv.slice(2),Nn=Q.includes("--full"),W=Q.includes("--dry-run"),Ts=Q.includes("--report"),Mn=Q.includes("--verbose"),Rs=Q.includes("--backfill"),Is=Q.includes("--enrich"),Ds=Q.includes("--today"),Pn=Q.includes("--read-unread"),Ct=parseInt(Q.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),ml=Q.includes("--auto-enrich-replies"),Os=parseInt(Q.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),pl=parseInt(Q.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function gl(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function hl(e,t){console.log(`
291
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{so()}catch{}try{sn()}catch{}Tn=!0,In(),console.log(`
292
+ \u2713 Schema is now at v${Ce}
293
+ `)}var Wi=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Yi(e){let t=e.toLowerCase();return Wi.some(n=>n.test(t))}var Gi=6e4;function zi(){let e=Date.now(),t=[];for(let n of[ue,Me,Pe]){if(!x.existsSync(n))continue;let o;try{o=x.readdirSync(n)}catch{continue}for(let s of o){if(!Yi(s))continue;let i=P.join(n,s);try{let r=x.statSync(i);if(!r.isFile()||e-r.mtimeMs<Gi)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Ki({verbose:e=!1}={}){let t=zi();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{x.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${P.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Qi(){let e=[];for(let t of[Me,Pe]){if(!x.existsSync(t))continue;let n=x.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=P.join(t,o);try{Ht(s)}catch(i){e.push({dir:P.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Zi(e){let t=[],n=[];for(let i of[Me,Pe]){if(!x.existsSync(i))continue;let r=x.readdirSync(i).filter(a=>a.endsWith(e));for(let a of r){let l=P.join(i,a),c=a.slice(0,-e.length),u=P.join(i,c);try{c.toLowerCase().endsWith(".json")?Ht(l):x.accessSync(l,x.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:a,dir:i})}catch(f){n.push(`${P.basename(i)}/${a}: ${f.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:a,dir:l}of t)try{Ss(i,r),o++}catch(c){s.push(`${P.basename(l)}/${a}: ${c.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Ss(e,t){let n=t+".tmp";try{x.copyFileSync(e,n),ws(n)}catch(o){try{x.unlinkSync(n)}catch{}throw o}try{x.renameSync(n,t)}catch(o){try{x.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}Fe();async function Xi(e,t,n="op"){let o,s=new Promise((i,r)=>{o=setTimeout(()=>r(new Error(`${n} timeout after ${t}ms`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(o)}}function je(e){if(!e)return!1;let t=e.constructor?.name||"";if(t==="ProtocolError"||t==="TargetCloseError")return!0;let n=e.message||"";return/Runtime\.callFunctionOn timed out/i.test(n)||/Target closed/i.test(n)||/Session closed/i.test(n)||/Connection closed/i.test(n)||/Most likely the page has been closed/i.test(n)||/Navigating frame was detached/i.test(n)||/Protocol error.*timed out/i.test(n)}async function vs(e,t,{returnUrl:n,gotoTimeoutMs:o=6e4,cookiesProvider:s=null,setupPage:i=null}={}){try{await Xi(t.close({runBeforeUnload:!1}),5e3,"oldPage.close")}catch{}let r=await e.newPage();if(i)try{await i(r)}catch{}if(s)try{let a=s();Array.isArray(a)&&a.length>0&&await r.setCookie(...a)}catch{}if(n){await r.goto(n,{waitUntil:"domcontentloaded",timeout:o});let a=r.url();if(/\/login|\/checkpoint|\/uas\/login|\/authwall/.test(a))throw new Error(`Session expired after recovery \u2014 landed on ${a}. Run: ilml linkedin login`)}return r}await bs();var Ps="https://www.linkedin.com/messaging/",fl=10,Mn=3,ml=async e=>{await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})})},pl=()=>Nt(),Le={pageRecoveries:0};async function Vt(e,t){if(Le.pageRecoveries>=fl)throw new Error(`CDP unrecoverable: ${Le.pageRecoveries} page recoveries already attempted. Last: ${t}`);console.log(`
294
+ \u{1F504} CDP dead \u2014 recovering page (#${Le.pageRecoveries+1}). Reason: ${t}`),e.page=await vs(e.browser,e.page,{returnUrl:Ps,cookiesProvider:pl,setupPage:ml}),Le.pageRecoveries++,await $(3e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}console.log(`\u2713 Page recovered (total: ${Le.pageRecoveries}).
295
+ `)}function Xe(e){return(e.messages||[]).find(t=>ot.has(t.status))?.status}var Q=process.argv.slice(2),Pn=Q.includes("--full"),Y=Q.includes("--dry-run"),Is=Q.includes("--report"),jn=Q.includes("--verbose"),Ds=Q.includes("--backfill"),Os=Q.includes("--enrich"),Ns=Q.includes("--today"),Ln=Q.includes("--read-unread"),xt=parseInt(Q.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),gl=Q.includes("--auto-enrich-replies"),Ms=parseInt(Q.find(e=>e.startsWith("--auto-enrich-max="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_MAX||"3"),hl=parseInt(Q.find(e=>e.startsWith("--auto-enrich-stale-days="))?.split("=")[1]||process.env.AUTO_ENRICH_REPLIES_STALE_DAYS||"30");function yl(e,t){if(!t)return"new";if(e.unread)return"unread";if(!t.profileUrl&&(t.messages?.length||t.lastMessagePreview))return"missing_url";let n=(t.lastMessagePreview||"").substring(0,50),o=(e.lastMessagePreview||"").substring(0,50);if(o&&n&&o!==n)return"preview_changed";if(e.lastMessageBy==="me"&&t.lastMessageBy!=="me")return"sender_changed";if(t.lastSynced&&e.lastMessageTime){let s=new Date(e.lastMessageTime).getTime(),i=new Date(t.lastSynced).getTime();if(Number.isFinite(s)&&Number.isFinite(i)&&s>i)return"activity_after_last_read"}return null}async function wl(e,t){console.log(`
296
296
  \u2550\u2550 PHASE 1: Inbox Scan \u2550\u2550
297
- `);let n=Qt(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,r=new Map,c=0,l=0,a=0,u=0,f=0,d=-1,m=0;for(;;){l++;let w=await Vo(e),S=0;for(let p of w){if(!p.name||s.has(p.name))continue;s.set(p.name,p),S++,p.unread&&r.set(p.name,p);let v=t[p.name],C=gl(p,v);C&&(!Pn&&p.unread?c++:i.set(p.name,{card:p,reason:C})),v&&(C||(v.lastMessageBy=p.lastMessageBy,v.lastMessagePreview=p.lastMessagePreview||v.lastMessagePreview,v.lastMessageTime=p.lastMessageTime||v.lastMessageTime),v.unread=p.unread,p.lastMessageBy==="them"&&p.unread&&(v.conversationStatus="unanswered_by_us"))}if(Mn?console.log(` Round #${l}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${l}, ${i.size} need reading)`),S===0){if(f++,f>=3){console.log(`
298
- 3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!Nn){if(i.size===u){if(a++,a>=3){console.log(`
299
- Caught up \u2014 3 screens with no new threads to read.`);break}}else a=0;u=i.size}let h=await cn(e);if(h){if(h.scrollTop===d){if(m++,m>=3){console.log(`
300
- Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=h.scrollTop}else{let p=await e.$(".msg-conversation-listitem");if(p){let v=await p.boundingBox();v&&(await e.mouse.move(v.x+v.width/2,v.y+v.height/2),await e.mouse.wheel({deltaY:600}))}}await k(2e3)}Mn||process.stdout.write(`
301
- `);let y=new Date().toISOString(),g=0;for(let[w,{card:S}]of i)t[w]||(t[w]={profileUrl:null,lastSynced:y,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},g++);let b=0;for(let[w,S]of r)t[w]||(t[w]={profileUrl:null,lastSynced:y,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},b++);if(console.log(`
302
- Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${g}`),console.log(` Need reading/re-reading: ${i.size}`),!Pn&&c>0&&console.log(` Preserved unread (default): ${c} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),b>0&&console.log(` New unread stubs: ${b} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let w={};for(let{reason:S}of i.values())w[S]=(w[S]||0)+1;for(let[S,h]of Object.entries(w))console.log(` ${S}: ${h}`)}if(!W){let w=Qt();w.lastIncrementalSync=new Date().toISOString(),Nn&&(w.lastFullSync=w.lastIncrementalSync),uo(w),ye(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function yl(e,t,n,o){console.log(`
297
+ `);let n=Xt(),o=n.lastIncrementalSync?new Date(n.lastIncrementalSync):null,s=new Map,i=new Map,r=new Map,a=0,l=0,c=0,u=0,f=0,d=-1,m=0;for(;;){l++;let v=await Yo(e),S=0;for(let h of v){if(!h.name||s.has(h.name))continue;s.set(h.name,h),S++,h.unread&&r.set(h.name,h);let b=t[h.name],k=yl(h,b);k&&(!Ln&&h.unread?a++:i.set(h.name,{card:h,reason:k})),b&&(k||(b.lastMessageBy=h.lastMessageBy,b.lastMessagePreview=h.lastMessagePreview||b.lastMessagePreview,b.lastMessageTime=h.lastMessageTime||b.lastMessageTime),b.unread=h.unread,h.lastMessageBy==="them"&&h.unread&&(b.conversationStatus="unanswered_by_us"))}if(jn?console.log(` Round #${l}: +${S} new | Total: ${s.size} | Need reading: ${i.size}`):process.stdout.write(`\r Scanned: ${s.size} conversations (page #${l}, ${i.size} need reading)`),S===0){if(f++,f>=3){console.log(`
298
+ 3 rounds with no new items \u2014 end of visible list.`);break}}else f=0;if(!Pn){if(i.size===u){if(c++,c>=3){console.log(`
299
+ Caught up \u2014 3 screens with no new threads to read.`);break}}else c=0;u=i.size}let g=await dn(e);if(g){if(g.scrollTop===d){if(m++,m>=3){console.log(`
300
+ Scroll stalled \u2014 reached end of inbox.`);break}}else m=0;d=g.scrollTop}else{let h=await e.$(".msg-conversation-listitem");if(h){let b=await h.boundingBox();b&&(await e.mouse.move(b.x+b.width/2,b.y+b.height/2),await e.mouse.wheel({deltaY:600}))}}await $(2e3)}jn||process.stdout.write(`
301
+ `);let y=new Date().toISOString(),p=0;for(let[v,{card:S}]of i)t[v]||(t[v]={profileUrl:null,lastSynced:y,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:S.unread||!1,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},p++);let w=0;for(let[v,S]of r)t[v]||(t[v]={profileUrl:null,lastSynced:y,lastMessageBy:S.lastMessageBy,lastMessagePreview:S.lastMessagePreview||"",lastMessageTime:S.lastMessageTime||"",unread:!0,conversationStatus:S.lastMessageBy==="them"?"unanswered_by_us":"awaiting_reply",messages:[]},w++);if(console.log(`
302
+ Inbox scan complete:`),console.log(` Total conversations seen: ${s.size}`),console.log(` New conversations: ${p}`),console.log(` Need reading/re-reading: ${i.size}`),!Ln&&a>0&&console.log(` Preserved unread (default): ${a} \u2014 kept bold in LinkedIn UI; pass --read-unread to vacuum them into the DB`),w>0&&console.log(` New unread stubs: ${w} \u2014 saved to DB so 'today' / 'report' can show them offline`),i.size>0){let v={};for(let{reason:S}of i.values())v[S]=(v[S]||0)+1;for(let[S,g]of Object.entries(v))console.log(` ${S}: ${g}`)}if(!Y){let v=Xt();v.lastIncrementalSync=new Date().toISOString(),Pn&&(v.lastFullSync=v.lastIncrementalSync),mo(v),we(t)}return{allCards:s,toReRead:i,unreadCards:r}}async function bl(e,t,n,o){console.log(`
303
303
  \u2550\u2550 PHASE 2: Read Changed Threads \u2550\u2550
304
- `);let s=Array.from(t.entries()),i=Math.min(s.length,Ct);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(Ns,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!Pe(f))throw f;await Ht(e,"Phase 2 inbox reset")}await k(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let r={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(r[f[1].reason]??5)-(r[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${Ct})
305
- `);let c=[],l=[],a=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);let g=e.page;try{let b={verified:!1,headerName:null};try{b=await pn(g,d)}catch(S){if(Pe(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!b.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{b=await Wo(e.page,d)}catch(S){if(Pe(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!b.verified){console.log(" Could not open thread."),a++;try{await ve(e.page)}catch{}continue}let w=await dn(g);if(w&&w.length>0){if(!fn(w,d,l)){console.log(" Skipped \u2014 stale data."),a++,await ve(g);continue}let h=await un(g),p=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},v=p.messages?.length||0;p.messages=mn(p.messages,w),p.lastSynced=new Date().toISOString(),h&&!p.profileUrl&&(p.profileUrl=h);let C=p.messages.filter(R=>!["draft","confirmed","rejected","needs_review"].includes(R.status));p.lastMessageBy=jt(C,d),p.lastMessagePreview=m.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=m.lastMessageTime||p.lastMessageTime,p.unread=!1,n[d]=p,W||ye(n);let _=p.messages.length-v;console.log(` ${p.messages.length} msgs (${_>=0?"+"+_:_} new)${h&&!p.profileUrl?" +url":""}`),c.push({name:d}),l=[...new Set(w.map(R=>R.sender).filter(R=>R&&R!=="Unknown"))]}else console.log(" No messages extracted."),a++;await ve(g),await k(500)}catch(b){if(!Pe(b))throw b;u++,o&&o.add(d),await Ht(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
306
- Phase 2 complete: ${c.length} read, ${a} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),c}async function wl(e,t,n){if(!ml)return null;console.log(`
304
+ `);let s=Array.from(t.entries()),i=Math.min(s.length,xt);if(i===0)return console.log(" No threads to read \u2014 all up to date."),[];console.log(" Resetting inbox view...");try{await e.page.goto(Ps,{waitUntil:"domcontentloaded",timeout:6e4})}catch(f){if(!je(f))throw f;await Vt(e,"Phase 2 inbox reset")}await $(4e3);try{await e.page.waitForSelector(".msg-conversation-listitem",{timeout:15e3})}catch{}let r={unread:0,preview_changed:1,sender_changed:2,no_messages:3,new:4};s.sort((f,d)=>(r[f[1].reason]??5)-(r[d[1].reason]??5)),console.log(` Reading ${i} of ${s.length} threads (--max=${xt})
305
+ `);let a=[],l=[],c=0,u=0;for(let f=0;f<i;f++){let[d,{card:m,reason:y}]=s[f];console.log(` [${f+1}/${i}] ${d} (${y})`);let p=e.page;try{let w={verified:!1,headerName:null};try{w=await hn(p,d)}catch(S){if(je(S))throw S;console.log(` searchAndOpenThread threw: ${(S.message||"").substring(0,80)}`)}if(!w.verified){console.log(" Sidebar fallback (scroll-to-find)...");try{w=await Go(e.page,d)}catch(S){if(je(S))throw S;console.log(` Fallback threw: ${(S.message||"").substring(0,80)}`)}}if(!w.verified){console.log(" Could not open thread."),c++;try{await ke(e.page)}catch{}continue}let v=await mn(p);if(v&&v.length>0){if(!pn(v,d,l)){console.log(" Skipped \u2014 stale data."),c++,await ke(p);continue}let g=await fn(p),h=n[d]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]},b=h.messages?.length||0;h.messages=gn(h.messages,v),h.lastSynced=new Date().toISOString(),g&&!h.profileUrl&&(h.profileUrl=g);let k=h.messages.filter(I=>!["draft","confirmed","rejected","needs_review"].includes(I.status));h.lastMessageBy=Ft(k,d),h.lastMessagePreview=m.lastMessagePreview||h.lastMessagePreview,h.lastMessageTime=m.lastMessageTime||h.lastMessageTime,h.unread=!1,n[d]=h,Y||we(n);let T=h.messages.length-b;console.log(` ${h.messages.length} msgs (${T>=0?"+"+T:T} new)${g&&!h.profileUrl?" +url":""}`),a.push({name:d}),l=[...new Set(v.map(I=>I.sender).filter(I=>I&&I!=="Unknown"))]}else console.log(" No messages extracted."),c++;await ke(p),await $(500)}catch(w){if(!je(w))throw w;u++,o&&o.add(d),await Vt(e,`Phase 2 thread ${f+1}/${i} (${d})`)}}return console.log(`
306
+ Phase 2 complete: ${a.length} read, ${c} failed${u?`, ${u} skipped on CDP recovery`:""}`),s.length>i&&console.log(` ${s.length-i} more threads pending (run again or increase --max)`),a}async function Sl(e,t,n){if(!gl)return null;console.log(`
307
307
  \u2550\u2550 PHASE 2.5: Auto-enrich-replies \u2550\u2550
308
- `);let o=new Set(n.map(m=>m.name)),s=J(),i=Date.now(),r=pl*24*60*60*1e3,c=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let g=y.profileUrl;if(!g)continue;let w=s[g]?._lastEnrichedAt;if(w){let S=i-new Date(w).getTime();if(Number.isFinite(S)&&S<r)continue}c.push({name:m,profileUrl:g,lastMessageTime:y.lastMessageTime||null})}if(c.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
309
- `),{picked:0,enriched:0,skipped:0,errors:0,dryRun:W};c.sort((m,y)=>{let g=new Date(m.lastMessageTime||0).getTime();return new Date(y.lastMessageTime||0).getTime()-g});let l=c.slice(0,Os),a=c.length-l.length;if(console.log(` Candidates: ${c.length} | picking ${l.length} (cap ${Os}) | skipping ${a}`),a>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),W){console.log(" [DRY RUN] Would enrich:");for(let m of l)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:l.length,enriched:0,skipped:a,errors:0,dryRun:!0}}let{viewProfile:u}=await _s().then(()=>xs),f=0,d=0;for(let m=0;m<l.length;m++){let y=l[m];console.log(`
310
- [${m+1}/${l.length}] Enriching ${y.name} ${y.profileUrl}`);try{let g=await u(e.page,y.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!g||!g.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),d++;continue}let b={name:g.name,title:g.title,location:g.location,about:g.about,currentCompany:g.currentCompany,currentSchool:g.currentSchool,topSkills:g.topSkills,availableSections:g.availableSections,connectionsLevel:g.connectionsLevel,mutualConnectionsCount:g.mutualConnectionsCount,followers:g.followers,openToWork:g.openToWork,hiring:g.hiring,hasVerifiedBadge:g.hasVerifiedBadge,photoUrl:g.photoUrl,source:"auto-enrich-replies"},w=!1;for(let[S,h]of[["experience",g.experience],["featured",g.featured],["education",g.education],["skillsFull",g.skillsFull],["recommendations",g.recommendations],["certifications",g.certifications]])Array.isArray(h)&&h.length>0&&(b[S]=h,w=!0);w&&(b._lastEnrichedAt=new Date().toISOString()),Te(y.profileUrl,b),g.resolvedUrl&&xt(y.profileUrl,g.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${w?"yes":"no \u2014 basic only"})`)}catch(g){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(g.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:l.length,enriched:f,skipped:a,errors:d,authWall:!0};console.log(` \u2717 ${g.message?.slice(0,200)}`),d++}m+1<l.length&&await k(8e3)}return console.log(`
311
- Auto-enrich done: ${f} enriched, ${d} errors, ${a} skipped (over cap)
312
- `),{picked:l.length,enriched:f,skipped:a,errors:d}}function bl(e,t){console.log(`
308
+ `);let o=new Set(n.map(m=>m.name)),s=H(),i=Date.now(),r=hl*24*60*60*1e3,a=[];for(let m of o){let y=t[m];if(!y||y.lastMessageBy!=="them")continue;let p=y.profileUrl;if(!p)continue;let v=s[p]?._lastEnrichedAt;if(v){let S=i-new Date(v).getTime();if(Number.isFinite(S)&&S<r)continue}a.push({name:m,profileUrl:p,lastMessageTime:y.lastMessageTime||null})}if(a.length===0)return console.log(` No stale contacts to enrich. Skipping phase.
309
+ `),{picked:0,enriched:0,skipped:0,errors:0,dryRun:Y};a.sort((m,y)=>{let p=new Date(m.lastMessageTime||0).getTime();return new Date(y.lastMessageTime||0).getTime()-p});let l=a.slice(0,Ms),c=a.length-l.length;if(console.log(` Candidates: ${a.length} | picking ${l.length} (cap ${Ms}) | skipping ${c}`),c>0&&console.log(" (raise --auto-enrich-max=N to lift the cap, but be mindful of ban-risk)"),Y){console.log(" [DRY RUN] Would enrich:");for(let m of l)console.log(` - ${m.name} ${m.profileUrl} (last msg: ${m.lastMessageTime||"unknown"})`);return console.log(""),{picked:l.length,enriched:0,skipped:c,errors:0,dryRun:!0}}let{viewProfile:u}=await Rs().then(()=>Ts),f=0,d=0;for(let m=0;m<l.length;m++){let y=l[m];console.log(`
310
+ [${m+1}/${l.length}] Enriching ${y.name} ${y.profileUrl}`);try{let p=await u(e.page,y.profileUrl,{extractExperience:!0,extractFeatured:!0,extractEducation:!0,extractSkills:!0,extractRecommendations:!0,extractCertifications:!0});if(!p||!p.name){console.log(" \u2717 viewProfile returned no data \u2014 skipping save"),d++;continue}let w={name:p.name,title:p.title,location:p.location,about:p.about,currentCompany:p.currentCompany,currentSchool:p.currentSchool,topSkills:p.topSkills,availableSections:p.availableSections,connectionsLevel:p.connectionsLevel,mutualConnectionsCount:p.mutualConnectionsCount,followers:p.followers,openToWork:p.openToWork,hiring:p.hiring,hasVerifiedBadge:p.hasVerifiedBadge,photoUrl:p.photoUrl,source:"auto-enrich-replies"},v=!1;for(let[S,g]of[["experience",p.experience],["featured",p.featured],["education",p.education],["skillsFull",p.skillsFull],["recommendations",p.recommendations],["certifications",p.certifications]])Array.isArray(g)&&g.length>0&&(w[S]=g,v=!0);v&&(w._lastEnrichedAt=new Date().toISOString()),Re(y.profileUrl,w),p.resolvedUrl&&Tt(y.profileUrl,p.resolvedUrl),f++,console.log(` \u2713 saved (rich sections: ${v?"yes":"no \u2014 basic only"})`)}catch(p){if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(p.message||""))return console.log(" \u26A0 Session expired during auto-enrich. Stopping phase."),console.log(" Sync-all post-processing will still run on already-enriched data."),{picked:l.length,enriched:f,skipped:c,errors:d,authWall:!0};console.log(` \u2717 ${p.message?.slice(0,200)}`),d++}m+1<l.length&&await $(8e3)}return console.log(`
311
+ Auto-enrich done: ${f} enriched, ${d} errors, ${c} skipped (over cap)
312
+ `),{picked:l.length,enriched:f,skipped:c,errors:d}}function vl(e,t){console.log(`
313
313
  \u2550\u2550 PHASE 3: Post-processing & Enrichment \u2550\u2550
314
- `);let n=J();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Pt(i,s,n)}catch(l){console.warn(` [!] Enrichment failed for ${s}: ${l.message}`)}i._cardSynced&&delete i._cardSynced;let r=i.profileUrl,c=null;if(r&&(c=n[r]||null),!c){let l=Object.entries(n).filter(([,a])=>a.name===s);l.length===1&&(r||(r=l[0][0],i.profileUrl=r),c=l[0][1])}!c&&r&&(c=Te(r,{name:s,source:"sync-all"})),c&&(i.category&&!c.category&&(c.category=i.category),c.conversationStatus=i.conversationStatus,c.lastUpdated=new Date().toISOString()),r&&c&&(i.isConnection=c.connectionStatus==="connected")}W||(Re(n),ye(e)),console.log(` Enriched ${t.length} conversations.`),Ms(e)}function Ms(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let r=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(r)||t.set(r,[]),t.get(r).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,r]=s.map(u=>({name:u,conv:e[u]})),c=(i.conv.messages?.length||0)>=(r.conv.messages?.length||0)?i:r,l=c===i?r:i,a=new Set((c.conv.messages||[]).map(u=>`${u.text?.slice(0,80)}|${u.time}`));for(let u of l.conv.messages||[]){let f=`${u.text?.slice(0,80)}|${u.time}`;a.has(f)||(c.conv.messages.push(u),a.add(f))}c.conv.messages.sort((u,f)=>(u.time||"").localeCompare(f.time||"")),l.conv.notes&&!c.conv.notes&&(c.conv.notes=l.conv.notes),l.conv.priority&&!c.conv.priority&&(c.conv.priority=l.conv.priority),l.conv.categorySource==="manual"&&c.conv.categorySource!=="manual"&&(c.conv.category=l.conv.category,c.conv.categorySource="manual"),(l.conv.lastSynced||"")>(c.conv.lastSynced||"")&&(c.conv.lastSynced=l.conv.lastSynced),delete e[l.name],console.log(` Merged: "${l.name}" \u2192 "${c.name}"`),o++}o>0&&(W||ye(e),console.log(` ${o} duplicates merged.`))}function Sl(){let e=lt(),t=J(),n=Object.entries(e);console.log(`
314
+ `);let n=H();for(let o of t){let{name:s}=o,i=e[s];if(!i?.messages?.length)continue;try{Lt(i,s,n)}catch(l){console.warn(` [!] Enrichment failed for ${s}: ${l.message}`)}i._cardSynced&&delete i._cardSynced;let r=i.profileUrl,a=null;if(r&&(a=n[r]||null),!a){let l=Object.entries(n).filter(([,c])=>c.name===s);l.length===1&&(r||(r=l[0][0],i.profileUrl=r),a=l[0][1])}!a&&r&&(a=Re(r,{name:s,source:"sync-all"})),a&&(i.category&&!a.category&&(a.category=i.category),a.conversationStatus=i.conversationStatus,a.lastUpdated=new Date().toISOString()),r&&a&&(i.isConnection=a.connectionStatus==="connected")}Y||(Ie(n),we(e)),console.log(` Enriched ${t.length} conversations.`),js(e)}function js(e){let t=new Map;for(let[s,i]of Object.entries(e)){if(!i.profileUrl)continue;let r=i.profileUrl.toLowerCase().replace(/\/$/,"");t.has(r)||t.set(r,[]),t.get(r).push(s)}let n=[...t.entries()].filter(([,s])=>s.length===2);if(n.length===0)return;let o=0;for(let[,s]of n){let[i,r]=s.map(u=>({name:u,conv:e[u]})),a=(i.conv.messages?.length||0)>=(r.conv.messages?.length||0)?i:r,l=a===i?r:i,c=new Set((a.conv.messages||[]).map(u=>`${u.text?.slice(0,80)}|${u.time}`));for(let u of l.conv.messages||[]){let f=`${u.text?.slice(0,80)}|${u.time}`;c.has(f)||(a.conv.messages.push(u),c.add(f))}a.conv.messages.sort((u,f)=>(u.time||"").localeCompare(f.time||"")),l.conv.notes&&!a.conv.notes&&(a.conv.notes=l.conv.notes),l.conv.priority&&!a.conv.priority&&(a.conv.priority=l.conv.priority),l.conv.categorySource==="manual"&&a.conv.categorySource!=="manual"&&(a.conv.category=l.conv.category,a.conv.categorySource="manual"),(l.conv.lastSynced||"")>(a.conv.lastSynced||"")&&(a.conv.lastSynced=l.conv.lastSynced),delete e[l.name],console.log(` Merged: "${l.name}" \u2192 "${a.name}"`),o++}o>0&&(Y||we(e),console.log(` ${o} duplicates merged.`))}function kl(){let e=ct(),t=H(),n=Object.entries(e);console.log(`
315
315
  \u2550\u2550 ENRICHMENT: Re-processing all conversations \u2550\u2550
316
- `);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,y])=>y.name===f);m.length===1&&(d.profileUrl=m[0][0],i++)}if(!d.messages||d.messages.length===0){s++;continue}try{Pt(d,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}Ms(e),W||ye(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let r=new Set(Object.keys(e)),c=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),l=Object.entries(t),a=0,u=0;for(let[f,d]of l){if(c.has(f)){u++;continue}if(d.name&&r.has(d.name)){u++;continue}if(d.connectionStatus!=="connected"){u++;continue}yn(d,f),a++}W||Re(t),console.log(`
317
- People enriched: ${a}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${l.length}`),jn(e,null,null)}function jn(e,t,n,o={}){let s=Object.entries(e),i=J(),{unreadCards:r=null,readUnread:c=!1}=o;console.log(`
316
+ `);let o=0,s=0,i=0;for(let[f,d]of n){if(!d.profileUrl){let m=Object.entries(t).filter(([,y])=>y.name===f);m.length===1&&(d.profileUrl=m[0][0],i++)}if(!d.messages||d.messages.length===0){s++;continue}try{Lt(d,f,t)}catch(m){console.warn(` [!] Enrichment failed for ${f}: ${m.message}`)}o++}js(e),Y||we(e),console.log(` Enriched: ${o}`),console.log(` Skipped (no messages): ${s}`),i>0&&console.log(` Linked profileUrl from people.json: ${i}`),console.log(` Total: ${n.length}`);let r=new Set(Object.keys(e)),a=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),l=Object.entries(t),c=0,u=0;for(let[f,d]of l){if(a.has(f)){u++;continue}if(d.name&&r.has(d.name)){u++;continue}if(d.connectionStatus!=="connected"){u++;continue}bn(d,f),c++}Y||Ie(t),console.log(`
317
+ People enriched: ${c}`),console.log(` People skipped (have conversation or not connected): ${u}`),console.log(` People total: ${l.length}`),Fn(e,null,null)}function Fn(e,t,n,o={}){let s=Object.entries(e),i=H(),{unreadCards:r=null,readUnread:a=!1}=o;console.log(`
318
318
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" SYNC REPORT"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
319
- `),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let l=s.length,a=s.filter(([,$])=>$.messages?.length>0).length,u=s.filter(([,$])=>!$.messages||$.messages.length===0).length,f=s.filter(([,$])=>$.profileUrl).length,d=s.filter(([,$])=>!$.profileUrl).length;console.log(`
320
- Database:`),console.log(` Total conversations: ${l}`),console.log(` With messages: ${a}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,y=0;for(let[,$]of s)for(let A of $.messages||[])m++,(!A.sender||A.sender==="Unknown")&&y++;console.log(`
321
- Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let g={};for(let[,$]of s){let A=$.conversationStatus||"null";g[A]=(g[A]||0)+1}console.log(`
322
- Statuses:`);for(let[$,A]of Object.entries(g).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${A}`);let b={};for(let[,$]of s){let A=$.category||"(none)";b[A]=(b[A]||0)+1}console.log(`
323
- Categories:`);for(let[$,A]of Object.entries(b).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${A}`);let w={};for(let[,$]of s){let A=$.actionNeeded||"(none)";w[A]=(w[A]||0)+1}if(Object.keys(w).length>1||!w["(none)"]){console.log(`
324
- Actions Needed:`);for(let[$,A]of Object.entries(w).sort((T,N)=>N[1]-T[1]))console.log(` ${$}: ${A}`)}let S=new Map;for(let[$,A]of s){if(!A.profileUrl)continue;let T=A.profileUrl.toLowerCase().replace(/\/$/,"");S.has(T)||S.set(T,[]),S.get(T).push($)}let h=[...S.entries()].filter(([,$])=>$.length>1);if(h.length>0){console.log(`
325
- Duplicates (${h.length}):`);for(let[$,A]of h)console.log(` ${A.join(" | ")} \u2192 ${$}`)}let p=s.filter(([,$])=>$.conversationStatus==="unanswered_by_us").sort(($,A)=>(A[1].lastSynced||"").localeCompare($[1].lastSynced||"")),v=s.filter(([,$])=>Ze($));if(console.log(`
319
+ `),t&&(console.log(" Inbox Scan:"),console.log(` Conversations seen: ${t.allCards.size}`),console.log(` Needed reading: ${t.toReRead.size}`)),n&&console.log(` Actually read: ${n.length}`);let l=s.length,c=s.filter(([,C])=>C.messages?.length>0).length,u=s.filter(([,C])=>!C.messages||C.messages.length===0).length,f=s.filter(([,C])=>C.profileUrl).length,d=s.filter(([,C])=>!C.profileUrl).length;console.log(`
320
+ Database:`),console.log(` Total conversations: ${l}`),console.log(` With messages: ${c}`),console.log(` Without messages: ${u}`),console.log(` With profileUrl: ${f}`),console.log(` Without profileUrl: ${d}`);let m=0,y=0;for(let[,C]of s)for(let A of C.messages||[])m++,(!A.sender||A.sender==="Unknown")&&y++;console.log(`
321
+ Message Quality:`),console.log(` Total messages: ${m}`),console.log(` Unknown sender: ${y} (${m>0?(y/m*100).toFixed(1):0}%)`);let p={};for(let[,C]of s){let A=C.conversationStatus||"null";p[A]=(p[A]||0)+1}console.log(`
322
+ Statuses:`);for(let[C,A]of Object.entries(p).sort((E,O)=>O[1]-E[1]))console.log(` ${C}: ${A}`);let w={};for(let[,C]of s){let A=C.category||"(none)";w[A]=(w[A]||0)+1}console.log(`
323
+ Categories:`);for(let[C,A]of Object.entries(w).sort((E,O)=>O[1]-E[1]))console.log(` ${C}: ${A}`);let v={};for(let[,C]of s){let A=C.actionNeeded||"(none)";v[A]=(v[A]||0)+1}if(Object.keys(v).length>1||!v["(none)"]){console.log(`
324
+ Actions Needed:`);for(let[C,A]of Object.entries(v).sort((E,O)=>O[1]-E[1]))console.log(` ${C}: ${A}`)}let S=new Map;for(let[C,A]of s){if(!A.profileUrl)continue;let E=A.profileUrl.toLowerCase().replace(/\/$/,"");S.has(E)||S.set(E,[]),S.get(E).push(C)}let g=[...S.entries()].filter(([,C])=>C.length>1);if(g.length>0){console.log(`
325
+ Duplicates (${g.length}):`);for(let[C,A]of g)console.log(` ${A.join(" | ")} \u2192 ${C}`)}let h=s.filter(([,C])=>C.conversationStatus==="unanswered_by_us").sort((C,A)=>(A[1].lastSynced||"").localeCompare(C[1].lastSynced||"")),b=s.filter(([,C])=>Xe(C));if(console.log(`
326
326
  \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\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(" ACTION NEEDED"),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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
327
- `),r&&!c&&r.size>0){let $=[...r.entries()];console.log(` STILL UNREAD ON LINKEDIN (${$.length}) \u2014 kept bold; read them in the LinkedIn UI:
328
- `);let A=30;for(let[T,N]of $.slice(0,A)){let H=e[T],re=H?.category?` [${H.category}]`:"",ie=N.lastMessageTime||H?.lastMessageTime||"",j=(N.lastMessagePreview||"").slice(0,80),L=H?.summary,U=H?.personContext?.title?`${H.personContext.title}${H.personContext.company?` at ${H.personContext.company}`:""}`:null;console.log(` ${T}${re}${ie?` \u2014 ${ie}`:""}`),j&&console.log(` "${j}"`),L?console.log(` ${L}`):U&&console.log(` ${U}`)}$.length>A&&console.log(`
329
- ... and ${$.length-A} more`),console.log(`
327
+ `),r&&!a&&r.size>0){let C=[...r.entries()];console.log(` STILL UNREAD ON LINKEDIN (${C.length}) \u2014 kept bold; read them in the LinkedIn UI:
328
+ `);let A=30;for(let[E,O]of C.slice(0,A)){let B=e[E],ie=B?.category?` [${B.category}]`:"",Z=O.lastMessageTime||B?.lastMessageTime||"",he=(O.lastMessagePreview||"").slice(0,80),j=B?.summary,L=B?.personContext?.title?`${B.personContext.title}${B.personContext.company?` at ${B.personContext.company}`:""}`:null;console.log(` ${E}${ie}${Z?` \u2014 ${Z}`:""}`),he&&console.log(` "${he}"`),j?console.log(` ${j}`):L&&console.log(` ${L}`)}C.length>A&&console.log(`
329
+ ... and ${C.length-A} more`),console.log(`
330
330
  To pull them into the local DB (will lose unread badges): npm run sync-all -- --read-unread
331
- `)}if(v.length>0){let $=v.filter(([,T])=>Ze(T)===V.CONFIRMED),A=v.filter(([,T])=>{let N=Ze(T);return N===V.DRAFT||N===V.NEEDS_REVIEW});console.log(` Drafts: ${v.length} total (${$.length} confirmed, ${A.length} pending)`),A.length>0&&console.log(" Review: npm run messages -- --review-drafts"),$.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let C=p.filter(([,$])=>$.actionNeeded==="schedule_call"),_=p.filter(([,$])=>$.actionNeeded!=="schedule_call");if(_.sort(($,A)=>{let T={high:0,medium:1,low:2}[$[1].suggestedPriority]??3,N={high:0,medium:1,low:2}[A[1].suggestedPriority]??3;return T-N}),C.length>0){console.log(` SCHEDULE CALL (${C.length}):
332
- `);for(let[$,A]of C){let T=A.category||"",N=A.summary||"";console.log(` ${$}${T?` [${T}]`:""} \u2192 schedule_call`),N&&console.log(` ${N}`)}console.log()}if(_.length>0){console.log(` REPLY NEEDED (${_.length}):
333
- `);let $=20;for(let[A,T]of _.slice(0,$)){let N=T.category||"",H=T.suggestedPriority?`[${T.suggestedPriority}]`:"",re=(T.autoTags||[]).slice(0,4).join(", "),ie=T.summary||"",L=[...T.messages||[]].reverse().find(U=>U.sender!==z&&U.sender!=="Unknown")?.text?.slice(0,80)||T.lastMessagePreview?.slice(0,80)||"";console.log(` ${H} ${A}${N?` [${N}]`:""}`),console.log(ie?` ${ie}`:` "${L}"`),re&&console.log(` #${re.replace(/, /g," #")}`)}_.length>$&&console.log(`
334
- ... and ${_.length-$} more`)}p.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let R=new Set(Object.keys(e)),x=new Set(Object.values(e).map($=>$.profileUrl).filter(Boolean)),D=Object.entries(i).filter(([$,A])=>A.connectionStatus==="connected"&&A.personActionNeeded==="initiate_contact"&&!x.has($)&&!(A.name&&R.has(A.name))).sort(($,A)=>{let T={high:0,medium:1,low:2}[$[1].personPriority]??3,N={high:0,medium:1,low:2}[A[1].personPriority]??3;return T!==N?T-N:(A[1].connectionDate||"").localeCompare($[1].connectionDate||"")});if(D.length>0){console.log(`
335
- INITIATE CONTACT (${D.length}):
336
- `);let $=20;for(let[A,T]of D.slice(0,$)){let N=T.personPriority?`[${T.personPriority.toUpperCase()}]`:"",H=T.personSummary||T.title||"";console.log(` ${N} ${T.name||"Unknown"} \u2014 ${H}`)}D.length>$&&console.log(`
337
- ... and ${D.length-$} more`)}let G=s.filter(([,$])=>$.conversationStatus==="awaiting_reply");G.length>0&&console.log(`
338
- BALL IN THEIR COURT: ${G.length} conversations`),W&&console.log(`
331
+ `)}if(b.length>0){let C=b.filter(([,E])=>Xe(E)===J.CONFIRMED),A=b.filter(([,E])=>{let O=Xe(E);return O===J.DRAFT||O===J.NEEDS_REVIEW});console.log(` Drafts: ${b.length} total (${C.length} confirmed, ${A.length} pending)`),A.length>0&&console.log(" Review: npm run messages -- --review-drafts"),C.length>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let k=h.filter(([,C])=>C.actionNeeded==="schedule_call"),T=h.filter(([,C])=>C.actionNeeded!=="schedule_call");if(T.sort((C,A)=>{let E={high:0,medium:1,low:2}[C[1].suggestedPriority]??3,O={high:0,medium:1,low:2}[A[1].suggestedPriority]??3;return E-O}),k.length>0){console.log(` SCHEDULE CALL (${k.length}):
332
+ `);for(let[C,A]of k){let E=A.category||"",O=A.summary||"";console.log(` ${C}${E?` [${E}]`:""} \u2192 schedule_call`),O&&console.log(` ${O}`)}console.log()}if(T.length>0){console.log(` REPLY NEEDED (${T.length}):
333
+ `);let C=20;for(let[A,E]of T.slice(0,C)){let O=E.category||"",B=E.suggestedPriority?`[${E.suggestedPriority}]`:"",ie=(E.autoTags||[]).slice(0,4).join(", "),Z=E.summary||"",j=[...E.messages||[]].reverse().find(L=>L.sender!==z&&L.sender!=="Unknown")?.text?.slice(0,80)||E.lastMessagePreview?.slice(0,80)||"";console.log(` ${B} ${A}${O?` [${O}]`:""}`),console.log(Z?` ${Z}`:` "${j}"`),ie&&console.log(` #${ie.replace(/, /g," #")}`)}T.length>C&&console.log(`
334
+ ... and ${T.length-C} more`)}h.length===0&&console.log(" All caught up \u2014 no unanswered messages.");let I=new Set(Object.keys(e)),_=new Set(Object.values(e).map(C=>C.profileUrl).filter(Boolean)),R=Object.entries(i).filter(([C,A])=>A.connectionStatus==="connected"&&A.personActionNeeded==="initiate_contact"&&!_.has(C)&&!(A.name&&I.has(A.name))).sort((C,A)=>{let E={high:0,medium:1,low:2}[C[1].personPriority]??3,O={high:0,medium:1,low:2}[A[1].personPriority]??3;return E!==O?E-O:(A[1].connectionDate||"").localeCompare(C[1].connectionDate||"")});if(R.length>0){console.log(`
335
+ INITIATE CONTACT (${R.length}):
336
+ `);let C=20;for(let[A,E]of R.slice(0,C)){let O=E.personPriority?`[${E.personPriority.toUpperCase()}]`:"",B=E.personSummary||E.title||"";console.log(` ${O} ${E.name||"Unknown"} \u2014 ${B}`)}R.length>C&&console.log(`
337
+ ... and ${R.length-C} more`)}let W=s.filter(([,C])=>C.conversationStatus==="awaiting_reply");W.length>0&&console.log(`
338
+ BALL IN THEIR COURT: ${W.length} conversations`),Y&&console.log(`
339
339
  [DRY RUN \u2014 no changes written]`),console.log(`
340
340
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
341
- `)}async function vl(e,t){console.log(`
341
+ `)}async function $l(e,t){console.log(`
342
342
  \u2550\u2550 BACKFILL: Reading conversations with 0 messages \u2550\u2550
343
- `);let n=Object.entries(t).filter(([,l])=>!l.messages||l.messages.length===0).map(([l,a])=>({name:l,preview:a.lastMessagePreview||"",lastBy:a.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((l,a)=>l.lastBy==="them"&&a.lastBy!=="them"?-1:l.lastBy!=="them"&&a.lastBy==="them"?1:0);let o=Math.min(n.length,Ct);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${Ct})
344
- `);let s=[],i=0,r=0,c=[];for(let l=0;l<o;l++){let{name:a}=n[l];console.log(` [${l+1}/${o}] ${a}`);let u=e.page;try{if(await Wn(u),!(await pn(u,a)).verified){console.log(" Not found or thread didn't load."),i++,await ve(u),await k(500);continue}let d=await dn(u);if(!d||d.length===0){console.log(" No messages extracted."),i++,await ve(u),await k(500);continue}if(!fn(d,a,c)){console.log(" Skipped \u2014 stale data."),i++,await ve(u),await k(500);continue}let y=await un(u),g=t[a]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};g.messages=mn(g.messages,d),g.lastSynced=new Date().toISOString(),y&&(g.profileUrl=y),t[a]=g,W||ye(t),console.log(` \u2713 ${g.messages.length} msgs${y?" +url":""}`),s.push({name:a}),c=[...new Set(d.map(b=>b.sender).filter(b=>b&&b!=="Unknown"))],await ve(u),await k(500)}catch(f){if(!Pe(f))throw f;r++,await Ht(e,`Backfill thread ${l+1}/${o} (${a})`)}}return console.log(`
345
- Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function kl(e){let t=at(),n=Object.values(e),o=n.filter(l=>l.sources?.includes("recruiters-from-jobs")&&!l.connectionStatus).length,s=n.filter(l=>l.connectionStatus==="modal_failed").length,i=o+s,r=n.filter(l=>l.connectionStatus==="connected"&&l.connectionMethod).length,c=n.filter(l=>l.connectionStatus==="pending"||l.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${r} accepted, ${c} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),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")}function $l(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?ge(o.lastJobTitle,25):"",r=o.lastJobDate||"",c=i?` (last: ${i}${r?", "+r:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ge(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${c}`)}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")}}function Cl(){let e=Co(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=ge(o.title||"?",30),i=ge(o.company||"?",15),r=o.salary?` \u2014 ${ge(o.salary,12)}`:"",c=o.location?` \u2014 ${ge(o.location,15)}`:"",l=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${r}${c}${l}`)}console.log(" Apply: npm run apply-queue"),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")}}function Al(){let e=sn();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),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"))}function El(){let e=fo();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=ge(t.topAnswer,30);console.log(` "${ge(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${ge(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}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")}}function ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function xl(){let e=lt(),t=J(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(h=>h.profileUrl).filter(Boolean));console.log(`
343
+ `);let n=Object.entries(t).filter(([,l])=>!l.messages||l.messages.length===0).map(([l,c])=>({name:l,preview:c.lastMessagePreview||"",lastBy:c.lastMessageBy}));if(n.length===0)return console.log(" All conversations already have messages."),[];n.sort((l,c)=>l.lastBy==="them"&&c.lastBy!=="them"?-1:l.lastBy!=="them"&&c.lastBy==="them"?1:0);let o=Math.min(n.length,xt);console.log(` ${n.length} conversations without messages, reading ${o} (--max=${xt})
344
+ `);let s=[],i=0,r=0,a=[];for(let l=0;l<o;l++){let{name:c}=n[l];console.log(` [${l+1}/${o}] ${c}`);let u=e.page;try{if(await Gn(u),!(await hn(u,c)).verified){console.log(" Not found or thread didn't load."),i++,await ke(u),await $(500);continue}let d=await mn(u);if(!d||d.length===0){console.log(" No messages extracted."),i++,await ke(u),await $(500);continue}if(!pn(d,c,a)){console.log(" Skipped \u2014 stale data."),i++,await ke(u),await $(500);continue}let y=await fn(u),p=t[c]||{profileUrl:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]};p.messages=gn(p.messages,d),p.lastSynced=new Date().toISOString(),y&&(p.profileUrl=y),t[c]=p,Y||we(t),console.log(` \u2713 ${p.messages.length} msgs${y?" +url":""}`),s.push({name:c}),a=[...new Set(d.map(w=>w.sender).filter(w=>w&&w!=="Unknown"))],await ke(u),await $(500)}catch(f){if(!je(f))throw f;r++,await Vt(e,`Backfill thread ${l+1}/${o} (${c})`)}}return console.log(`
345
+ Backfill complete: ${s.length} read, ${i} failed${r?`, ${r} skipped on CDP recovery`:""}`),n.length>o&&console.log(` ${n.length-o} more remaining (run again or increase --max)`),s}function Cl(e){let t=ut(),n=Object.values(e),o=n.filter(l=>l.sources?.includes("recruiters-from-jobs")&&!l.connectionStatus).length,s=n.filter(l=>l.connectionStatus==="modal_failed").length,i=o+s,r=n.filter(l=>l.connectionStatus==="connected"&&l.connectionMethod).length,a=n.filter(l=>l.connectionStatus==="pending"||l.connectionStatus==="sent_without_note").length;console.log("\u2550\u2550\u2550 CONNECTION QUOTA & QUEUE \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Today: ${t.daily.sent}/${t.daily.max} sent (${t.daily.remaining} remaining)`),console.log(` Week: ${t.weekly.sent}/${t.weekly.max} sent (${t.weekly.remaining} remaining)`),console.log(` Queue: ${i} profiles (${o} new, ${s} retry)`),console.log(` Funnel: ${r} accepted, ${a} pending`),i===0&&console.log(" \u26A0 Queue empty \u2014 need new job applications to feed funnel"),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")}function Al(e){let t=Object.values(e).filter(n=>n.jobCount>=2).sort((n,o)=>(o.jobCount||0)-(n.jobCount||0)).slice(0,10);if(t.length!==0){console.log("\u2550\u2550\u2550 TOP RECRUITERS (by job count) \u2550\u2550\u2550");for(let n=0;n<t.length;n++){let o=t[n],s=o.connectionStatus==="connected"?"connected":o.connectionStatus==="pending"||o.connectionStatus==="sent_without_note"?"pending":o.connectionStatus||"unknown",i=o.lastJobTitle?ge(o.lastJobTitle,25):"",r=o.lastJobDate||"",a=i?` (last: ${i}${r?", "+r:""})`:"";console.log(` ${String(n+1).padStart(2)}. ${ge(o.name||"?",25).padEnd(25)} ${String(o.jobCount).padStart(2)} jobs | ${s.padEnd(10)}${a}`)}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")}}function xl(){let e=xo(10);if(e.length!==0){console.log("\u2550\u2550\u2550 TOP JOBS TO APPLY \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let t=0;t<e.length;t++){let{score:n,job:o}=e[t],s=ge(o.title||"?",30),i=ge(o.company||"?",15),r=o.salary?` \u2014 ${ge(o.salary,12)}`:"",a=o.location?` \u2014 ${ge(o.location,15)}`:"",l=o.recruiterUrl?" \u{1F464}":"";console.log(` ${String(t+1).padStart(2)}. [${String(n).padStart(2)}] ${s} @ ${i}${r}${a}${l}`)}console.log(" Apply: npm run apply-queue"),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")}}function El(){let e=ln();e.totalJobs===0&&e.totalVisited===0||(console.log("\u2550\u2550\u2550 MARKET RESEARCH \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Scouted jobs: ${e.totalJobs}${e.lastScoutDate?` (last: ${e.lastScoutDate})`:""}`),console.log(` Discovered people: ${e.totalRecruiters}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.slice(0,5).join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.slice(0,5).join(", ")}`),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"))}function _l(){let e=po();if(e.totalApplications!==0){if(console.log(`\u2550\u2550\u2550 FAQ STATS (${e.totalApplications} applications) \u2550\u2550`),console.log(` Unique questions: ${e.uniqueQuestions}`),e.topQuestions.length>0){console.log(" Top questions:");for(let t of e.topQuestions.slice(0,8)){let n=ge(t.topAnswer,30);console.log(` "${ge(t.question,40)}" \u2014 ${t.count}x \u2192 ${n}`)}}if(e.inconsistent.length>0){console.log(` Inconsistent answers: ${e.inconsistent.length} \u26A0`);for(let t of e.inconsistent.slice(0,3))console.log(` "${ge(t.question,35)}" \u2014 ${t.answers.join(", ")}`)}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")}}function ge(e,t){return e?e.length>t?e.slice(0,t-1)+"\u2026":e:""}function Tl(){let e=ct(),t=H(),n=new Set(Object.keys(e)),o=new Set(Object.values(e).map(g=>g.profileUrl).filter(Boolean));console.log(`
346
346
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" TODAY'S PRIORITIES"),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
347
- `),console.log(ls()),console.log(""),kl(t),console.log(""),$l(t),console.log(""),Al(),console.log(""),Cl(),console.log(""),El(),console.log("");let s=Object.entries(e),i=s.filter(([,h])=>h.unread===!0).sort((h,p)=>(p[1].lastMessageTime||"").localeCompare(h[1].lastMessageTime||""));if(i.length>0){let h=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
348
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],_=C.category?` [${C.category}]`:"",R=C.summary||(C.personContext?.title?`${C.personContext.title}${C.personContext.company?` at ${C.personContext.company}`:""}`:null)||C.lastMessagePreview?.slice(0,60)||null;console.log(` ${p+1}. ${v}${_}${R?` \u2014 ${R}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let r=new Date().toISOString().slice(0,10),c=s.filter(([,h])=>h.followUpNote),l=c.filter(([,h])=>!h.followUpDate||h.followUpDate<=r),a=c.filter(([,h])=>h.followUpDate&&h.followUpDate>r);if(c.length>0){console.log(` FOLLOW-UPS (${l.length} due, ${a.length} scheduled):
349
- `);for(let[h,p]of l){let v=p.followUpDate?` [due ${p.followUpDate}]`:" [no date]";console.log(` \u26A1 ${h}${v} \u2014 ${p.followUpNote}`)}for(let[h,p]of a.slice(0,5))console.log(` \u{1F4C5} ${h} [${p.followUpDate}] \u2014 ${p.followUpNote}`);a.length>5&&console.log(` ... +${a.length-5} more scheduled`),console.log()}let u=h=>h.actionNeeded&&h.actionNeeded!=="none"&&(!h.reviewedAtPreview||ze(h.lastMessagePreview)!==ze(h.reviewedAtPreview)),f=s.filter(([,h])=>u(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(f.length>0){let h=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
350
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],_=C.priority||C.suggestedPriority||"",R=C.category?` [${C.category}]`:"",x=C.summary||"";console.log(` ${p+1}. ${_?`[${_}] `:""}${v}${R} \u2014 ${x}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,h])=>h.actionNeeded==="schedule_call").sort((h,p)=>{let v={high:0,medium:1,low:2}[h[1].suggestedPriority]??3,C={high:0,medium:1,low:2}[p[1].suggestedPriority]??3;return v-C});if(d.length>0){let h=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
351
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],_=C.summary||C.personContext?.title||"";console.log(` ${p+1}. ${v} \u2014 ${_}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&(h.suggestedPriority==="high"||h.priority==="high")&&!u(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(m.length>0){let h=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
352
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],_=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${R}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us"&&h.actionNeeded!=="schedule_call"&&h.suggestedPriority==="medium"&&h.priority!=="high"&&!u(h)).sort((h,p)=>(p[1].lastSynced||"").localeCompare(h[1].lastSynced||""));if(y.length>0){let h=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
353
- `);for(let p=0;p<h.length;p++){let[v,C]=h[p],_=C.category?` [${C.category}]`:"",R=C.summary||"";console.log(` ${p+1}. ${v}${_} \u2014 ${R}`)}y.length>5&&console.log(` ... +${y.length-5} more`),console.log()}let g=Object.entries(t).filter(([h,p])=>p.connectionStatus==="connected"&&p.personActionNeeded==="initiate_contact"&&!o.has(h)&&!(p.name&&n.has(p.name))).sort((h,p)=>{let v={high:0,medium:1,low:2}[h[1].personPriority]??3,C={high:0,medium:1,low:2}[p[1].personPriority]??3;return v!==C?v-C:(p[1].connectionDate||"").localeCompare(h[1].connectionDate||"")});if(g.length>0){let h=g.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${g.length}):
354
- `);for(let p=0;p<h.length;p++){let[,v]=h[p],C=v.personPriority?`[${v.personPriority.toUpperCase()}]`:"",_=v.connectionDate?_l(v.connectionDate):"",R=v.title?`${v.title}${v.company?` at ${v.company}`:""}`:v.company||"";console.log(` ${p+1}. ${C} ${v.name||"Unknown"} \u2014 ${R}${_?` (${_})`:""}`)}g.length>10&&console.log(` ... +${g.length-10} more`),console.log()}let b=s.filter(([,h])=>Ze(h));if(b.length>0){let h=b.filter(([,v])=>Ze(v)===V.CONFIRMED).length,p=b.filter(([,v])=>{let C=Ze(v);return C===V.DRAFT||C===V.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${b.length} (${h} confirmed, ${p} pending)`),h>0&&console.log(" Send: npm run messages -- --push-drafts"),p>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let w=s.filter(([,h])=>h.conversationStatus==="unanswered_by_us").length,S=s.filter(([,h])=>h.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${w} need reply, ${g.length} new connections, ${S} ball in their court`),console.log(`
347
+ `),console.log(cs()),console.log(""),Cl(t),console.log(""),Al(t),console.log(""),El(),console.log(""),xl(),console.log(""),_l(),console.log("");let s=Object.entries(e),i=s.filter(([,g])=>g.unread===!0).sort((g,h)=>(h[1].lastMessageTime||"").localeCompare(g[1].lastMessageTime||""));if(i.length>0){let g=i.slice(0,10);console.log(` UNREAD ON LINKEDIN (${i.length}) \u2014 bold in LinkedIn UI, not yet opened:
348
+ `);for(let h=0;h<g.length;h++){let[b,k]=g[h],T=k.category?` [${k.category}]`:"",I=k.summary||(k.personContext?.title?`${k.personContext.title}${k.personContext.company?` at ${k.personContext.company}`:""}`:null)||k.lastMessagePreview?.slice(0,60)||null;console.log(` ${h+1}. ${b}${T}${I?` \u2014 ${I}`:""}`)}i.length>10&&console.log(` ... +${i.length-10} more`),console.log()}let r=new Date().toISOString().slice(0,10),a=s.filter(([,g])=>g.followUpNote),l=a.filter(([,g])=>!g.followUpDate||g.followUpDate<=r),c=a.filter(([,g])=>g.followUpDate&&g.followUpDate>r);if(a.length>0){console.log(` FOLLOW-UPS (${l.length} due, ${c.length} scheduled):
349
+ `);for(let[g,h]of l){let b=h.followUpDate?` [due ${h.followUpDate}]`:" [no date]";console.log(` \u26A1 ${g}${b} \u2014 ${h.followUpNote}`)}for(let[g,h]of c.slice(0,5))console.log(` \u{1F4C5} ${g} [${h.followUpDate}] \u2014 ${h.followUpNote}`);c.length>5&&console.log(` ... +${c.length-5} more scheduled`),console.log()}let u=g=>g.actionNeeded&&g.actionNeeded!=="none"&&(!g.reviewedAtPreview||Ke(g.lastMessagePreview)!==Ke(g.reviewedAtPreview)),f=s.filter(([,g])=>u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(f.length>0){let g=f.slice(0,20);console.log(` UNREVIEWED \u2014 NEW MESSAGES (${f.length}):
350
+ `);for(let h=0;h<g.length;h++){let[b,k]=g[h],T=k.priority||k.suggestedPriority||"",I=k.category?` [${k.category}]`:"",_=k.summary||"";console.log(` ${h+1}. ${T?`[${T}] `:""}${b}${I} \u2014 ${_}`)}f.length>20&&console.log(` ... +${f.length-20} more`),console.log()}let d=s.filter(([,g])=>g.actionNeeded==="schedule_call").sort((g,h)=>{let b={high:0,medium:1,low:2}[g[1].suggestedPriority]??3,k={high:0,medium:1,low:2}[h[1].suggestedPriority]??3;return b-k});if(d.length>0){let g=d.slice(0,5);console.log(` CALLS TO SCHEDULE (${d.length}):
351
+ `);for(let h=0;h<g.length;h++){let[b,k]=g[h],T=k.summary||k.personContext?.title||"";console.log(` ${h+1}. ${b} \u2014 ${T}`)}d.length>5&&console.log(` ... +${d.length-5} more`),console.log()}let m=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&(g.suggestedPriority==="high"||g.priority==="high")&&!u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(m.length>0){let g=m.slice(0,8);console.log(` REPLY NEEDED \u2014 HIGH (${m.length}):
352
+ `);for(let h=0;h<g.length;h++){let[b,k]=g[h],T=k.category?` [${k.category}]`:"",I=k.summary||"";console.log(` ${h+1}. ${b}${T} \u2014 ${I}`)}m.length>8&&console.log(` ... +${m.length-8} more`),console.log()}let y=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us"&&g.actionNeeded!=="schedule_call"&&g.suggestedPriority==="medium"&&g.priority!=="high"&&!u(g)).sort((g,h)=>(h[1].lastSynced||"").localeCompare(g[1].lastSynced||""));if(y.length>0){let g=y.slice(0,5);console.log(` REPLY NEEDED \u2014 MEDIUM (${y.length}):
353
+ `);for(let h=0;h<g.length;h++){let[b,k]=g[h],T=k.category?` [${k.category}]`:"",I=k.summary||"";console.log(` ${h+1}. ${b}${T} \u2014 ${I}`)}y.length>5&&console.log(` ... +${y.length-5} more`),console.log()}let p=Object.entries(t).filter(([g,h])=>h.connectionStatus==="connected"&&h.personActionNeeded==="initiate_contact"&&!o.has(g)&&!(h.name&&n.has(h.name))).sort((g,h)=>{let b={high:0,medium:1,low:2}[g[1].personPriority]??3,k={high:0,medium:1,low:2}[h[1].personPriority]??3;return b!==k?b-k:(h[1].connectionDate||"").localeCompare(g[1].connectionDate||"")});if(p.length>0){let g=p.slice(0,10);console.log(` NEW CONNECTIONS TO MESSAGE (${p.length}):
354
+ `);for(let h=0;h<g.length;h++){let[,b]=g[h],k=b.personPriority?`[${b.personPriority.toUpperCase()}]`:"",T=b.connectionDate?Rl(b.connectionDate):"",I=b.title?`${b.title}${b.company?` at ${b.company}`:""}`:b.company||"";console.log(` ${h+1}. ${k} ${b.name||"Unknown"} \u2014 ${I}${T?` (${T})`:""}`)}p.length>10&&console.log(` ... +${p.length-10} more`),console.log()}let w=s.filter(([,g])=>Xe(g));if(w.length>0){let g=w.filter(([,b])=>Xe(b)===J.CONFIRMED).length,h=w.filter(([,b])=>{let k=Xe(b);return k===J.DRAFT||k===J.NEEDS_REVIEW}).length;console.log(` DRAFTS: ${w.length} (${g} confirmed, ${h} pending)`),g>0&&console.log(" Send: npm run messages -- --push-drafts"),h>0&&console.log(" Review: npm run messages -- --review-drafts"),console.log()}let v=s.filter(([,g])=>g.conversationStatus==="unanswered_by_us").length,S=s.filter(([,g])=>g.conversationStatus==="awaiting_reply").length;console.log(` Summary: ${i.length} unread on LinkedIn, ${f.length} unreviewed, ${v} need reply, ${p.length} new connections, ${S} ball in their court`),console.log(`
355
355
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
356
- `)}function _l(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function Tl(){let e=lt();jn(e,null,null)}async function Rl(){if(console.log(`
356
+ `)}function Rl(e){let t=new Date(e);if(isNaN(t))return"";let n=Math.floor((Date.now()-t.getTime())/864e5);return n===0?"today":n===1?"1d ago":`${n}d ago`}function Il(){let e=ct();Fn(e,null,null)}async function Dl(){if(console.log(`
357
357
  LinkedIn Sync-All
358
- `),Ds){xl();return}if(Ts){let r=Ft("sync-all","report");Tl(),Ke(r,"success");return}if(Is){let r=Ft("sync-all","enrich");try{Sl(),Ke(r,"success")}catch(c){throw Ke(r,"error",null,c.message),c}return}let e=Rs?"backfill":Nn?"full":"incremental",t=Ft("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};W&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${Ct}`);let o=lt(),s=await Jo(),i={browser:s.browser,page:s.page};try{await an(i.page);let r=null,c=[];if(Rs)c=await vl(i,o);else{let l=0;for(;;)try{r=await hl(i.page,o);break}catch(d){if(!Pe(d))throw d;if(l++,l>=On)throw new Error(`Phase 1 failed ${On} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
359
- \u26A0 Phase 1 CDP dead (attempt ${l}/${On}). Recovering and restarting Phase 1...`),await Ht(i,`Phase 1 attempt ${l}`)}let a=new Set;c=await yl(i,r.toReRead,o,a),n.scanned=r.totalCards||0,n.toReRead=r.toReRead?.size||0;let u=new Set(c.map(d=>d.name)),f=0;for(let[d,{card:m}]of r.toReRead){if(u.has(d)||a.has(d))continue;let y=o[d];y&&(y.lastMessageBy=m.lastMessageBy,y.lastMessageTime=m.lastMessageTime||y.lastMessageTime,y.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),W||ye(o))}n.threadsRead=c.length,n.newMessages=c.reduce((l,a)=>l+(a.newMessages||0),0);try{let l=await wl(i,o,c);l&&(n.autoEnriched=l.enriched,l.authWall&&(n.autoEnrichAuthWall=!0))}catch(l){console.log(`
358
+ `),Ns){Tl();return}if(Is){let r=qt("sync-all","report");Il(),Qe(r,"success");return}if(Os){let r=qt("sync-all","enrich");try{kl(),Qe(r,"success")}catch(a){throw Qe(r,"error",null,a.message),a}return}let e=Ds?"backfill":Pn?"full":"incremental",t=qt("sync-all",e),n={scanned:0,toReRead:0,threadsRead:0,newMessages:0};Y&&console.log(" [DRY RUN mode]"),console.log(` Mode: ${e} | Max threads to read: ${xt}`);let o=ct(),s=await Wo(),i={browser:s.browser,page:s.page};try{await un(i.page);let r=null,a=[];if(Ds)a=await $l(i,o);else{let l=0;for(;;)try{r=await wl(i.page,o);break}catch(d){if(!je(d))throw d;if(l++,l>=Mn)throw new Error(`Phase 1 failed ${Mn} times on CDP death \u2014 giving up. Last: ${d.message}`);console.log(`
359
+ \u26A0 Phase 1 CDP dead (attempt ${l}/${Mn}). Recovering and restarting Phase 1...`),await Vt(i,`Phase 1 attempt ${l}`)}let c=new Set;a=await bl(i,r.toReRead,o,c),n.scanned=r.totalCards||0,n.toReRead=r.toReRead?.size||0;let u=new Set(a.map(d=>d.name)),f=0;for(let[d,{card:m}]of r.toReRead){if(u.has(d)||c.has(d))continue;let y=o[d];y&&(y.lastMessageBy=m.lastMessageBy,y.lastMessageTime=m.lastMessageTime||y.lastMessageTime,y.unread=m.unread,f++)}f>0&&(console.log(` Pending re-read: ${f} threads (raise --max or re-run to drain).`),Y||we(o))}n.threadsRead=a.length,n.newMessages=a.reduce((l,c)=>l+(c.newMessages||0),0);try{let l=await Sl(i,o,a);l&&(n.autoEnriched=l.enriched,l.authWall&&(n.autoEnrichAuthWall=!0))}catch(l){console.log(`
360
360
  \u26A0 Auto-enrich phase crashed: ${l.message?.slice(0,200)}`),console.log(` Continuing with post-processing \u2014 data integrity is unaffected.
361
- `)}c.length>0&&bl(o,c),jn(o,r,c,{unreadCards:r?.unreadCards,readUnread:Pn}),je.pageRecoveries>0&&console.log(`
362
- CDP page recoveries this run: ${je.pageRecoveries}`),W||Zt(),Ke(t,"success",n)}catch(r){console.error(`
363
- Error:`,r.message),Mn&&console.error(r.stack),Ke(t,"error",n,r.message)}finally{if(!W&&!Ts&&!Is&&!Ds)try{Zt()}catch{}await i.browser.close()}}Rl();
361
+ `)}a.length>0&&vl(o,a),Fn(o,r,a,{unreadCards:r?.unreadCards,readUnread:Ln}),Le.pageRecoveries>0&&console.log(`
362
+ CDP page recoveries this run: ${Le.pageRecoveries}`),Y||en(),Qe(t,"success",n)}catch(r){console.error(`
363
+ Error:`,r.message),jn&&console.error(r.stack),Qe(t,"error",n,r.message)}finally{if(!Y&&!Is&&!Os&&!Ns)try{en()}catch{}await i.browser.close()}}Dl();