ilml-plugin-linkedin 1.15.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/connect.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var Yn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{for(var n in t)Yn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Kn}from"@ilivemylife/graph-sdk";var Qn,zn,pe,Xn,Zn,ze=se(async()=>{Qn=await Kn();for(let[e,t]of Object.entries(Qn))process.env[e]===void 0&&(process.env[e]=t);zn=process.env.LINKEDIN_NAME,pe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Xn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.NEEDS_REVIEW])),Zn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.REJECTED,pe.NEEDS_REVIEW]))});import"dotenv/config";import*as M from"fs";import*as B from"path";import{fileURLToPath as eo}from"url";function Wt(){_e=null,oo=null,ae=null,ro=null,so=null,io=null}function Ze(){M.existsSync(le)||M.mkdirSync(le,{recursive:!0})}function Le(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";M.writeFileSync(o,n);for(let r=0;r<3;r++)try{M.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Pe(e,t){if(!M.existsSync(e))return null;try{let n=JSON.parse(M.readFileSync(e,"utf-8"));try{M.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(M.existsSync(o))try{let r=JSON.parse(M.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{M.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{M.copyFileSync(e,e+".corrupted")}catch{}return null}}function qe(){return new Date().toISOString().split("T")[0]}function K(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function co(){M.existsSync(mt)||M.mkdirSync(mt,{recursive:!0})}function Gt(e){let t=K(e);return t?B.join(mt,`${t}.json`):null}function uo(e){let t=Gt(e);return t?Pe(t,`profile-history/${K(e)}.json`)||[]:[]}function fo(e,t){let n=Gt(e);if(!n)return;co();let o=uo(e);o.unshift(t);try{Le(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${K(e)}: ${r.message}`)}}function Bt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Jt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function po(e,t){if(!e)return[];let n=[];for(let o of lo){let r=e[o],i=t[o];Bt(r)||Bt(i)||Jt(r)!==Jt(i)&&n.push(o)}return n}function mo(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return _e||(Ze(),_e=Pe(pt,"people.json")||{},_e)}function ht(e){Ze(),_e=e;try{Le(pt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(pt)}`)}}function Xe(e,t={}){if(!e)return null;let n=Y(),o=qe(),r=new Date().toISOString(),i=n[e];if(i){let l=po(i,t);l.length>0&&(fo(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:mo(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of ao)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={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:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return ht(n),n[e]}function Yt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:qe(),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(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),ht(n))}function Kt(e){return e&&Y()[e]?.connectionStatus||null}function et(e,t,n={}){if(!e)return;n.profileInfo?Xe(e,n.profileInfo):Y()[e]||Xe(e,{});let o=Y(),r=o[e];if(!r)return;let i=qe();r.connectionStatus=t,t==="connected"?r.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(r.requestedConnectionAt||(r.requestedConnectionAt=i)),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),ht(o)}function Qt(){return ae||(Ze(),ae=Pe(Vt,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function ho(e){Ze(),ae=e;try{Le(Vt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function zt(e,t="unknown"){let n=Qt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),ho(n)}function Xt(){let e=Qt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ue(){let e=Xt(),t=qe(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Me,i=o>=Fe,l=!r&&!i,u={allowed:l,daily:{sent:n,max:Me},weekly:{sent:o,max:Fe}};return l||(u.reason=r?`Daily limit reached (${n}/${Me})`:`Weekly limit reached (${o}/${Fe})`),u}function ke(){let e=Xt(),t=qe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Me,remaining:Me-n},weekly:{sent:o,max:Fe,remaining:Fe-o}}}var to,no,le,pt,gs,Vt,ys,ws,bs,mt,Ht,Me,Fe,_e,oo,ae,ro,so,io,ao,lo,Be=se(async()=>{await ze();to=eo(import.meta.url),no=B.dirname(B.dirname(to)),le=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(no,"collected-profiles"),pt=B.join(le,"people.json"),gs=B.join(le,"jobs.json"),Vt=B.join(le,"quota.json"),ys=B.join(le,"conversations.json"),ws=B.join(le,"sync-state.json"),bs=B.join(le,"application-questions.json"),mt=B.join(le,"profile-history"),Ht=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Me=Ht(process.env.CONNECT_MAX_DAILY,20),Fe=Ht(process.env.CONNECT_MAX_WEEKLY,100),_e=null,oo=null,ae=null,ro=null,so=null,io=null;ao=["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"],lo=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var yn={};ie(yn,{cookiesExist:()=>Sr,getCookiesPath:()=>st,loadCookies:()=>br,saveCookies:()=>wr});import Ie from"fs";import gn from"path";function st(){let e=process.env.ILML_SCOPE_DIR;return e?gn.join(e,"plugins-state","linkedin","cookies.json"):gr}function yr(){let e=st(),t=gn.dirname(e);return t&&t!=="."&&!Ie.existsSync(t)&&Ie.mkdirSync(t,{recursive:!0}),e}function wr(e){let t=yr();return Ie.writeFileSync(t,JSON.stringify(e)),t}function br(){let e=st();if(!Ie.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ie.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 Sr(){return Ie.existsSync(st())}var gr,wn=se(()=>{gr="cookies.json"});var bn={};ie(bn,{cleanSearchName:()=>Ar,delayed:()=>w,dismissPremiumOverlay:()=>we,ensureInboxPage:()=>Cr,parseLinkedInTime:()=>$r,safeParseInt:()=>xr,stripDesignations:()=>Er,utilityFunction:()=>kr});function kr(){console.log("Utility function called...")}function He(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),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function $r(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 u=He(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=vr[o[1].toLowerCase()],s=He(o[2]||""),a=new Date(t),d=a.getDay()-u;return d<=0&&(d+=7),a.setDate(a.getDate()-d),s?a.setHours(s.hours,s.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=_t[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),a=parseInt(r[3],10),c=He(r[4]||"");return new Date(a,u,s,c?.hours||0,c?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=_t[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),a=He(i[3]||""),c=t.getFullYear(),d=new Date(c,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let l=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(l){let u=_t[l[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(l[2],10),a=He(l[3]||""),c=t.getFullYear(),d=new Date(c,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Cr(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 w(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}function xr(e){return parseInt(e,10)||0}async function we(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let c of a){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.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 Ar(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 Er(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 _t,vr,it=se(()=>{_t={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},vr={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var Sn={};ie(Sn,{extractCertificationsFromDetails:()=>Rr,extractEducationFromDetails:()=>Dr,extractExperienceFromDetails:()=>_r,extractFeaturedFromDetails:()=>Ir,extractRecommendationsFromDetails:()=>Nr,extractSkillsFromDetails:()=>Tr});async function _r(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(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 w(900);await w(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function l(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=l(i);if(!u)return[];let s=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function a(c){let d=c[0]||null,f=null,p=null;if(c[1]){let x=c[1].split("\xB7").map(j=>j.trim());f=x[0]||null,x[1]&&(p=x[1])}let h=c.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),m=null,S=null;if(h>=0){let x=c[h].split("\xB7").map(j=>j.trim());m=x[0]||null,x[1]&&(S=x[1])}let y=null,k=-1;if(h>=0&&c[h+1]){let x=c[h+1],j=/^[>*\-•]|^&gt;/.test(x),J=/https?:\/\//.test(x),R=/\d{4}/.test(x),O=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!j&&!J&&!R&&x.length<100&&O&&(y=x,k=h+1)}let v=null,C=-1,$=c[c.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){C=c.length-1;let x=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(v={listed:x[1].split(",").map(j=>j.trim()),additional:parseInt(x[2],10)})}let g=new Set([0,1,h,k,C].filter(x=>x>=0)),E=c.filter((x,j)=>!g.has(j)),L=E.length>0?E.join(`
1
+ var Kn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{for(var n in t)Kn(e,n,{get:t[n],enumerable:!0})};import{getPluginConfig as Qn}from"@ilivemylife/graph-sdk";var zn,Xn,pe,Zn,eo,ze=se(async()=>{zn=await Qn();for(let[e,t]of Object.entries(zn))process.env[e]===void 0&&(process.env[e]=t);Xn=process.env.LINKEDIN_NAME,pe=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Zn=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.NEEDS_REVIEW])),eo=Object.freeze(new Set([pe.DRAFT,pe.CONFIRMED,pe.REJECTED,pe.NEEDS_REVIEW]))});import"dotenv/config";import*as M from"fs";import*as B from"path";import{fileURLToPath as to}from"url";function Wt(){_e=null,ro=null,ae=null,so=null,io=null,ao=null}function Ze(){M.existsSync(le)||M.mkdirSync(le,{recursive:!0})}function Le(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";M.writeFileSync(o,n);for(let r=0;r<3;r++)try{M.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Pe(e,t){if(!M.existsSync(e))return null;try{let n=JSON.parse(M.readFileSync(e,"utf-8"));try{M.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(M.existsSync(o))try{let r=JSON.parse(M.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{M.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{M.copyFileSync(e,e+".corrupted")}catch{}return null}}function qe(){return new Date().toISOString().split("T")[0]}function G(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function uo(){M.existsSync(ht)||M.mkdirSync(ht,{recursive:!0})}function Gt(e){let t=G(e);return t?B.join(ht,`${t}.json`):null}function fo(e){let t=Gt(e);return t?Pe(t,`profile-history/${G(e)}.json`)||[]:[]}function po(e,t){let n=Gt(e);if(!n)return;uo();let o=fo(e);o.unshift(t);try{Le(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${G(e)}: ${r.message}`)}}function Bt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Jt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function mo(e,t){if(!e)return[];let n=[];for(let o of co){let r=e[o],i=t[o];Bt(r)||Bt(i)||Jt(r)!==Jt(i)&&n.push(o)}return n}function ho(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function Y(){return _e||(Ze(),_e=Pe(mt,"people.json")||{},_e)}function et(e){Ze(),_e=e;try{Le(mt,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${B.resolve(mt)}`)}}function Xe(e,t={}){if(!e)return null;let n=Y(),o=qe(),r=new Date().toISOString(),i=n[e];if(i){let l=mo(i,t);l.length>0&&(po(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:ho(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let u of lo)if(t[u]!=null){if(Array.isArray(t[u])&&t[u].length===0&&Array.isArray(i[u])&&i[u].length>0)continue;i[u]=t[u]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[e]={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:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return et(n),n[e]}function Yt(e,t){if(!e||!t)return;let n=Y(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:qe(),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(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),et(n))}function Kt(e){return e&&Y()[e]?.connectionStatus||null}function tt(e,t,n={}){if(!e)return;n.profileInfo?Xe(e,n.profileInfo):Y()[e]||Xe(e,{});let o=Y(),r=o[e];if(!r)return;let i=qe();r.connectionStatus=t,t==="connected"?r.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(r.requestedConnectionAt||(r.requestedConnectionAt=i)),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),et(o)}function Qt(e,t){if(!e||!t)return;let n=G(e),o=G(t);if(!o||o===n)return;let r=Y(),i=r[e];i&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),et(r)))}function zt(){return ae||(Ze(),ae=Pe(Vt,"quota.json"),(!ae||!ae.connections)&&(ae={connections:[]}),ae)}function go(e){Ze(),ae=e;try{Le(Vt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Xt(e,t="unknown"){let n=zt(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),go(n)}function Zt(){let e=zt(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ue(){let e=Zt(),t=qe(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=Me,i=o>=Fe,l=!r&&!i,u={allowed:l,daily:{sent:n,max:Me},weekly:{sent:o,max:Fe}};return l||(u.reason=r?`Daily limit reached (${n}/${Me})`:`Weekly limit reached (${o}/${Fe})`),u}function ke(){let e=Zt(),t=qe(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:Me,remaining:Me-n},weekly:{sent:o,max:Fe,remaining:Fe-o}}}var no,oo,le,mt,ys,Vt,ws,bs,Ss,ht,Ht,Me,Fe,_e,ro,ae,so,io,ao,lo,co,Be=se(async()=>{await ze();no=to(import.meta.url),oo=B.dirname(B.dirname(no)),le=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"collected-profiles"):B.join(oo,"collected-profiles"),mt=B.join(le,"people.json"),ys=B.join(le,"jobs.json"),Vt=B.join(le,"quota.json"),ws=B.join(le,"conversations.json"),bs=B.join(le,"sync-state.json"),Ss=B.join(le,"application-questions.json"),ht=B.join(le,"profile-history"),Ht=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Me=Ht(process.env.CONNECT_MAX_DAILY,20),Fe=Ht(process.env.CONNECT_MAX_WEEKLY,100),_e=null,ro=null,ae=null,so=null,io=null,ao=null;lo=["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"],co=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var wn={};ie(wn,{cookiesExist:()=>kr,getCookiesPath:()=>it,loadCookies:()=>Sr,saveCookies:()=>br});import Ie from"fs";import yn from"path";function it(){let e=process.env.ILML_SCOPE_DIR;return e?yn.join(e,"plugins-state","linkedin","cookies.json"):yr}function wr(){let e=it(),t=yn.dirname(e);return t&&t!=="."&&!Ie.existsSync(t)&&Ie.mkdirSync(t,{recursive:!0}),e}function br(e){let t=wr();return Ie.writeFileSync(t,JSON.stringify(e)),t}function Sr(){let e=it();if(!Ie.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ie.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 kr(){return Ie.existsSync(it())}var yr,bn=se(()=>{yr="cookies.json"});var Sn={};ie(Sn,{cleanSearchName:()=>Er,delayed:()=>w,dismissPremiumOverlay:()=>we,ensureInboxPage:()=>xr,parseLinkedInTime:()=>Cr,safeParseInt:()=>Ar,stripDesignations:()=>_r,utilityFunction:()=>vr});function vr(){console.log("Utility function called...")}function He(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),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function Cr(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 u=He(n),s=new Date(t);return u?s.setHours(u.hours,u.minutes,0,0):s.setHours(0,0,0,0),s.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let u=$r[o[1].toLowerCase()],s=He(o[2]||""),a=new Date(t),d=a.getDay()-u;return d<=0&&(d+=7),a.setDate(a.getDate()-d),s?a.setHours(s.hours,s.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let u=_t[r[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(r[2],10),a=parseInt(r[3],10),c=He(r[4]||"");return new Date(a,u,s,c?.hours||0,c?.minutes||0,0,0).toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(i){let u=_t[i[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(i[2],10),a=He(i[3]||""),c=t.getFullYear(),d=new Date(c,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}let l=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(l){let u=_t[l[1].toLowerCase().slice(0,3)];if(u===void 0)return null;let s=parseInt(l[2],10),a=He(l[3]||""),c=t.getFullYear(),d=new Date(c,u,s,a?.hours||0,a?.minutes||0,0,0);return d>t&&d.setFullYear(c-1),d.toISOString()}return null}async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function xr(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 w(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}function Ar(e){return parseInt(e,10)||0}async function we(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),u=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||u){let s=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(s)return s.click(),{dismissed:!0,matched:r.substring(0,80)};let a=o.querySelectorAll("button");for(let c of a){let d=c.innerText?.trim().toLowerCase()||"",f=c.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||f.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.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 Er(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 _r(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 _t,$r,at=se(()=>{_t={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},$r={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6}});var kn={};ie(kn,{extractCertificationsFromDetails:()=>Nr,extractEducationFromDetails:()=>Tr,extractExperienceFromDetails:()=>Ir,extractFeaturedFromDetails:()=>Dr,extractRecommendationsFromDetails:()=>jr,extractSkillsFromDetails:()=>Rr});async function Ir(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(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 w(900);await w(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function l(c){let d=[];for(let f of c.querySelectorAll("div")){let p=Array.from(f.children).filter(m=>m.tagName==="DIV");if(p.length<3)continue;let h=p.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(f.textContent||"").length<500||d.push({el:f,count:h.length,totalText:(f.textContent||"").length})}return d.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),d[0]?.el}let u=l(i);if(!u)return[];let s=Array.from(u.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function a(c){let d=c[0]||null,f=null,p=null;if(c[1]){let x=c[1].split("\xB7").map(O=>O.trim());f=x[0]||null,x[1]&&(p=x[1])}let h=c.findIndex(x=>/(\d{4}|present)/i.test(x)&&/(-|–|—)/i.test(x)&&x.length<80),m=null,S=null;if(h>=0){let x=c[h].split("\xB7").map(O=>O.trim());m=x[0]||null,x[1]&&(S=x[1])}let y=null,k=-1;if(h>=0&&c[h+1]){let x=c[h+1],O=/^[>*\-•]|^&gt;/.test(x),V=/https?:\/\//.test(x),j=/\d{4}/.test(x),N=/,/.test(x)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(x);!O&&!V&&!j&&x.length<100&&N&&(y=x,k=h+1)}let v=null,C=-1,$=c[c.length-1];if($&&/and\s+\+\d+\s+skills?$/i.test($)){C=c.length-1;let x=$.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);x&&(v={listed:x[1].split(",").map(O=>O.trim()),additional:parseInt(x[2],10)})}let g=new Set([0,1,h,k,C].filter(x=>x>=0)),A=c.filter((x,O)=>!g.has(O)),L=A.length>0?A.join(`
2
2
 
3
3
  `):null;return{title:d,company:f,employmentType:p,dates:m,duration:S,location:y,description:L,skills:v,_raw:c}}return s.map(c=>{let f=(c.innerText||"").trim().split(`
4
- `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return a(f)}).filter(c=>c.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 We(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function Ye(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;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 Ir(e,t){return Ye(t,"featured","extractFeaturedFromDetails",async()=>(await We(e,t,"featured"),await e.evaluate(`(() => {
4
+ `).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return a(f)}).filter(c=>c.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 We(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function Ye(e,t,n,o){try{return await o()}catch(r){let i=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw r;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 Dr(e,t){return Ye(t,"featured","extractFeaturedFromDetails",async()=>(await We(e,t,"featured"),await e.evaluate(`(() => {
5
5
  ${Ge}
6
6
 
7
7
  const main = document.querySelector('main');
@@ -42,7 +42,7 @@ var Yn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(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 Dr(e,t){return Ye(t,"education","extractEducationFromDetails",async()=>(await We(e,t,"education"),await e.evaluate(`(() => {
45
+ })()`)))}async function Tr(e,t){return Ye(t,"education","extractEducationFromDetails",async()=>(await We(e,t,"education"),await e.evaluate(`(() => {
46
46
  ${Ge}
47
47
 
48
48
  const main = document.querySelector('main');
@@ -79,7 +79,7 @@ var Yn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(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 Tr(e,t){return Ye(t,"skills","extractSkillsFromDetails",async()=>(await We(e,t,"skills"),await e.evaluate(`(() => {
82
+ })()`)))}async function Rr(e,t){return Ye(t,"skills","extractSkillsFromDetails",async()=>(await We(e,t,"skills"),await e.evaluate(`(() => {
83
83
  ${Ge}
84
84
 
85
85
  const main = document.querySelector('main');
@@ -111,7 +111,7 @@ var Yn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{
111
111
  skills.push({ name, endorsements, _raw: lines });
112
112
  }
113
113
  return skills;
114
- })()`)))}async function Rr(e,t){return Ye(t,"certifications","extractCertificationsFromDetails",async()=>(await We(e,t,"certifications"),await e.evaluate(`(() => {
114
+ })()`)))}async function Nr(e,t){return Ye(t,"certifications","extractCertificationsFromDetails",async()=>(await We(e,t,"certifications"),await e.evaluate(`(() => {
115
115
  ${Ge}
116
116
 
117
117
  const main = document.querySelector('main');
@@ -136,7 +136,7 @@ var Yn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(e,t)=>{
136
136
 
137
137
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
138
  }).filter(e => e.name);
139
- })()`)))}async function Nr(e,t){return Ye(t,"recommendations","extractRecommendationsFromDetails",async()=>(await We(e,t,"recommendations"),await e.evaluate(`(() => {
139
+ })()`)))}async function jr(e,t){return Ye(t,"recommendations","extractRecommendationsFromDetails",async()=>(await We(e,t,"recommendations"),await e.evaluate(`(() => {
140
140
  ${Ge}
141
141
 
142
142
  const main = document.querySelector('main');
@@ -172,7 +172,7 @@ var Yn=Object.defineProperty;var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var ie=(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 Ge,kn=se(()=>{it();Ge=`
175
+ })()`)))}var Ge,vn=se(()=>{at();Ge=`
176
176
  function findEntryContainer(root) {
177
177
  const candidates = [];
178
178
  for (const div of root.querySelectorAll('div')) {
@@ -235,22 +235,22 @@ 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 Cn={};ie(Cn,{clickConnectButton:()=>Dt,default:()=>Mr,detectConnectionStatus:()=>Ee,findConnectButton:()=>Ke,runFunnel:()=>$n,sendConnectionRequest:()=>Tt,shouldExcludeLocation:()=>at,viewProfile:()=>It});async function vn(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: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function at(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function It(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await vn(e,t));let c=0;for(let v=0;v<2;v++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let g=1;g<=6;g++)await e.evaluate(E=>window.scrollTo(0,E),C*g/6),await w(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===c)break;c=$}await w(800);let d=await e.evaluate(()=>{let v=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"]),C=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"]),$=A=>{let _=(A||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},g={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:[]},E=document.querySelector("main");if(!E)return g;let L=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],x=Array.from(E.querySelectorAll("h2")),j=L.find(A=>{let _=A.textContent&&A.textContent.trim(),I=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!v.has(I)&&!C.has(I)}),J=j?j.textContent.trim():null,R=j?j.parentElement:null;for(;R&&R!==E&&!Array.from(R.children).filter(_=>_.tagName==="P").some(_=>{let I=_.textContent&&_.textContent.trim();return I&&I.length>5&&!$(I)});)R=R.parentElement;let O=null,H=null,N=null,V=null;if(R&&R!==E){let A=Array.from(R.children).filter(I=>I.tagName==="P").filter(I=>{let fe=I.textContent&&I.textContent.trim();return fe&&fe.length>5&&!$(fe)});if(A[0]&&(O=A[0].textContent.trim()),A[1]){let I=A[1].textContent.trim().split(/\s*[·•]\s*/);H=I[0]||null,I.length>1&&(N=I.slice(1).join(" \xB7 "))}let _=Array.from(R.children).filter(I=>I.tagName==="DIV");for(let I=_.length-1;I>=0;I--){let fe=_[I].textContent&&_[I].textContent.trim();if(fe&&!(J&&fe.startsWith(J))&&(V=fe.split(/[·•]/)[0].trim(),V))break}}let Se=null;if(R){let A=R.querySelectorAll("p, span, div");for(let _ of A){let I=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if(I==="1st"||I==="2nd"||I==="3rd"){Se=I;break}}}let W=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),D=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=D&&D.src||null,q=E.textContent||"",U=null,ne=q.match(/(\d+\+?)\s+connections\b/i);ne&&(U=ne[1]+" connections");let Qe=null,Ot=q.match(/(\d+)\s+mutual connection/i),Mt=q.match(/and\s+(\d+)\s+other mutual/i),Jn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ot?Qe=parseInt(Ot[1],10):Mt?Qe=2+parseInt(Mt[1],10):Jn&&(Qe=2);let Ft=null,Lt=null,Pt=x.find(A=>A.textContent&&A.textContent.trim()==="About");if(Pt){let A=Pt.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let I=_.match(/Top skills\s*(.+?)$/i);if(I){let ft=I[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Gn=>Gn.trim()).filter(Boolean);ft.length>0&&ft.length<10&&(Lt=ft)}_=_.split(/\n?…\s*more/i)[0].trim(),_=_.split(/\n?\.\.\.\s*more/i)[0].trim(),_=_.split(/\bTop skills\b/i)[0].trim(),_=_.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ft=_||null}}let qt=null,Ut=x.find(A=>A.textContent&&A.textContent.trim()==="Activity");if(Ut){let A=Ut.parentElement;for(;A&&A.tagName!=="SECTION";)A=A.parentElement;if(A){let _=(A.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(qt=parseInt(_[1].replace(/,/g,""),10))}}let Vn=[...new Set(x.map(A=>(A.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(A=>A&&A.length>1&&A.length<60&&A!==J).filter(A=>v.has(A)))],Oe=document.body.textContent||"",Hn=/#OpenToWork\b/i.test(Oe)||/\bOpen to work\b/.test(Oe),Wn=/#Hiring\b/i.test(Oe)||/\bI'?m hiring\b/i.test(Oe)||/\bWe are hiring\b/i.test(Oe);return{name:J,title:O,location:V,currentCompany:H,currentSchool:N,connectionDegree:Se,hasVerifiedBadge:W,photoUrl:P,connectionsLevel:U,mutualConnectionsCount:Qe,followers:qt,openToWork:Hn,hiring:Wn,about:Ft,topSkills:Lt,availableSections:Vn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,S=null,y=null;if(o||r||i||l||u||s){let v=await Promise.resolve().then(()=>(kn(),Sn));o&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),u&&(S=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),s&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...y!==null&&{certifications:y}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Ee(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=a=>a&&!a.closest(n),r=a=>Array.from(document.querySelectorAll(a)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(a=>a.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!u};return i.length>0?{status:"pending",debug:s}:l&&!u?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ke(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(s=a.textContent?.trim(),s&&!s.includes("notification")))return s;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(p))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f))return h}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let a=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&f.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},s);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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 s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping primary button: wrong person (${s})`),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 r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let a=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:S,matchesName:y,ariaLabel:m}},s,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.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 l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let a=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(a.isVisible&&!a.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==l&&await s.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let s=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await w(500),await e.evaluate(c=>c.click(),l),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),a||(a=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect"]')),!a){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});a=c?.asElement?.()||null,a||await c?.dispose?.().catch(()=>{})}if(!a){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Dt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!l.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await w(3e3)):(await e.evaluate(c=>c.click(),t),await w(3e3));let u=e.url();if(u.includes("/premium/")||u.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function jr(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 w(1500);let n=await Ke(e);if(n){await e.evaluate(r=>r.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Tt(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Ue();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let l=await Or(e,t,n);return l.connectionSent&&!i&&zt(t,o),l}async function Or(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let a=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
239
- --- Connecting: ${a} ---`),u.length>0){let y=Y()[t]?.location;if(at(y,u))return console.log(` \u26A0 Excluded location (stored): ${y}`),s.reason="excluded_location",s.profileInfo={location:y},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await vn(e,t),await w(2e3)),s.profileInfo=await e.evaluate(()=>{let y=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"]),k=D=>{let P=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return v;let $=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],g=Array.from(C.querySelectorAll("h2")),E=$.find(D=>{let P=D.textContent&&D.textContent.trim();return P&&P.length>1&&P.length<100&&!y.has(P)&&P!=="0 notifications"}),L=E?E.textContent.trim():null,x=E?E.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(q=>q.tagName==="P").some(q=>{let U=q.textContent&&q.textContent.trim();return U&&U.length>5&&!k(U)});)x=x.parentElement;let j=null,J=null,R=null;if(x&&x!==C){let D=Array.from(x.children),P=D.filter(U=>U.tagName==="P").filter(U=>{let ne=U.textContent&&U.textContent.trim();return ne&&ne.length>5&&!k(ne)});P[0]&&(j=P[0].textContent.trim()),P[1]&&(J=P[1].textContent.trim());let q=D.filter(U=>U.tagName==="DIV");for(let U=q.length-1;U>=0;U--){let ne=q[U].textContent&&q[U].textContent.trim();if(ne&&!(L&&ne.startsWith(L))&&(R=ne.split(/[·•]/)[0].trim(),R))break}}let O=null;if(x){let D=x.querySelectorAll("p, span, div");for(let P of D){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){O=q;break}}}let H=null,N=g.find(D=>D.textContent&&D.textContent.trim()==="About");if(N){let D=N.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(H=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,H&&(H=H.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let V=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Se=V&&V.src||null,W=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:L,title:j,location:R,about:H,company:J,connectionDegree:O,connectionsCount:null,mutualConnections:null,photoUrl:Se,hasVerifiedBadge:W}}),u.length>0){let y=s.profileInfo?.location,k=Y()[t]?.location,v=y||k;if(at(v,u))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),s.reason="excluded_location",s;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ee(e);if(s.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await we(e);let f=await Ke(e);if(!f&&(await we(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),f=await Ke(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=f.method;let p=await Dt(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await Ee(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await we(e),await w(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),k),await w(500),await k.click().catch(()=>e.evaluate(C=>C.click(),k)),await w(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(g=>g.click(),v),await w(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),s.reason="premium_required",s;if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),s.reason="premium_required",s}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),C=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!C}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=k?.asElement?.()||null,S||await k.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let v=await jr(e);return s.success=v,s.connectionSent=v,s.reason=v?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",v);await k.type(C,{delay:20}),await w(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=C,s}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let y=S;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(f.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 w(4e3)),await we(e),await w(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let C of k){let $=await e.evaluate(g=>{let E=g.getBoundingClientRect();return{visible:E.width>0&&E.height>0,inSticky:!!g.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){v=C;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let C of k)C!==v&&await C.dispose().catch(()=>{});if(v)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate($=>$.click(),v)),await w(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(L=>L.click(),C),await w(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await Ee(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let E=await e.$('button[aria-label="Send without a note"]');if(E){console.log(" Modal appeared via More dropdown, sending without note...");try{await E.evaluate(L=>L.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(a){console.error(` \u2717 Error: ${a.message}`),s.reason="error",s.error=a.message;let c=a.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{s.fatal=!0}return s}}async function $n(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:a=[],source:c="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
238
+ `});var xn={};ie(xn,{clickConnectButton:()=>Dt,default:()=>Fr,detectConnectionStatus:()=>Ee,findConnectButton:()=>Ke,runFunnel:()=>Cn,sendConnectionRequest:()=>Tt,shouldExcludeLocation:()=>lt,viewProfile:()=>It});async function $n(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: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function lt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function It(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:u=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await $n(e,t));let c=0;for(let v=0;v<2;v++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let g=1;g<=6;g++)await e.evaluate(A=>window.scrollTo(0,A),C*g/6),await w(900);let $=await e.evaluate(()=>document.body.scrollHeight);if($===c)break;c=$}await w(800);let d=await e.evaluate(()=>{let v=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"]),C=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"]),$=E=>{let _=(E||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(_)},g={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:[]},A=document.querySelector("main");if(!A)return g;let L=[...Array.from(A.querySelectorAll("h1")),...Array.from(A.querySelectorAll("h2"))],x=Array.from(A.querySelectorAll("h2")),O=L.find(E=>{let _=E.textContent&&E.textContent.trim(),I=(_||"").replace(/\s*\(\d+\)$/,"").trim();return _&&_.length>1&&_.length<100&&!v.has(I)&&!C.has(I)}),V=O?O.textContent.trim():null,j=O?O.parentElement:null;for(;j&&j!==A&&!Array.from(j.children).filter(_=>_.tagName==="P").some(_=>{let I=_.textContent&&_.textContent.trim();return I&&I.length>5&&!$(I)});)j=j.parentElement;let N=null,J=null,D=null,H=null;if(j&&j!==A){let E=Array.from(j.children).filter(I=>I.tagName==="P").filter(I=>{let fe=I.textContent&&I.textContent.trim();return fe&&fe.length>5&&!$(fe)});if(E[0]&&(N=E[0].textContent.trim()),E[1]){let I=E[1].textContent.trim().split(/\s*[·•]\s*/);J=I[0]||null,I.length>1&&(D=I.slice(1).join(" \xB7 "))}let _=Array.from(j.children).filter(I=>I.tagName==="DIV");for(let I=_.length-1;I>=0;I--){let fe=_[I].textContent&&_[I].textContent.trim();if(fe&&!(V&&fe.startsWith(V))&&(H=fe.split(/[·•]/)[0].trim(),H))break}}let Se=null;if(j){let E=j.querySelectorAll("p, span, div");for(let _ of E){let I=(_.textContent||"").trim().replace(/^[·•]\s*/,"");if(I==="1st"||I==="2nd"||I==="3rd"){Se=I;break}}}let W=!!A.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),T=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=T&&T.src||null,q=A.textContent||"",U=null,ne=q.match(/(\d+\+?)\s+connections\b/i);ne&&(U=ne[1]+" connections");let Qe=null,Ot=q.match(/(\d+)\s+mutual connection/i),Mt=q.match(/and\s+(\d+)\s+other mutual/i),Vn=q.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ot?Qe=parseInt(Ot[1],10):Mt?Qe=2+parseInt(Mt[1],10):Vn&&(Qe=2);let Ft=null,Lt=null,Pt=x.find(E=>E.textContent&&E.textContent.trim()==="About");if(Pt){let E=Pt.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let _=(E.textContent||"").trim();_=_.replace(/^About\s*/,"").trim();let I=_.match(/Top skills\s*(.+?)$/i);if(I){let pt=I[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Yn=>Yn.trim()).filter(Boolean);pt.length>0&&pt.length<10&&(Lt=pt)}_=_.split(/\n?…\s*more/i)[0].trim(),_=_.split(/\n?\.\.\.\s*more/i)[0].trim(),_=_.split(/\bTop skills\b/i)[0].trim(),_=_.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ft=_||null}}let qt=null,Ut=x.find(E=>E.textContent&&E.textContent.trim()==="Activity");if(Ut){let E=Ut.parentElement;for(;E&&E.tagName!=="SECTION";)E=E.parentElement;if(E){let _=(E.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);_&&(qt=parseInt(_[1].replace(/,/g,""),10))}}let Hn=[...new Set(x.map(E=>(E.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(E=>E&&E.length>1&&E.length<60&&E!==V).filter(E=>v.has(E)))],Oe=document.body.textContent||"",Wn=/#OpenToWork\b/i.test(Oe)||/\bOpen to work\b/.test(Oe),Gn=/#Hiring\b/i.test(Oe)||/\bI'?m hiring\b/i.test(Oe)||/\bWe are hiring\b/i.test(Oe);return{name:V,title:N,location:H,currentCompany:J,currentSchool:D,connectionDegree:Se,hasVerifiedBadge:W,photoUrl:P,connectionsLevel:U,mutualConnectionsCount:Qe,followers:qt,openToWork:Wn,hiring:Gn,about:Ft,topSkills:Lt,availableSections:Hn}});console.log(`Viewed: ${d.name} - ${d.title}`);let f=null,p=null,h=null,m=null,S=null,y=null;if(o||r||i||l||u||s){let v=await Promise.resolve().then(()=>(vn(),kn));o&&(f=await v.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(p=await v.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),i&&(h=await v.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await v.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),u&&(S=await v.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),s&&(y=await v.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${y.length} entries`))}return{...d,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...y!==null&&{certifications:y}}}catch(a){console.error(`Error viewing profile ${t}:`,a.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(a.message||""))throw a;return null}}async function Ee(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=a=>a&&!a.closest(n),r=a=>Array.from(document.querySelectorAll(a)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,u=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(a=>a.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!u};return i.length>0?{status:"pending",debug:s}:l&&!u?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ke(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let a=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(a&&(s=a.textContent?.trim(),s&&!s.includes("notification")))return s;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(c=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),f=c.toLowerCase().split(" ")[0],p='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(p))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(f))return h}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:a,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let a=await e.evaluate(d=>{let f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&f.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);a.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(a)}`),t=await e.evaluateHandle(d=>{let f=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of f){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},s);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,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 s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping primary button: wrong person (${s})`),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 r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let a=await e.evaluate((c,d)=>{let f=c.className.includes("muted"),p=c.className.includes("sticky-header")||c.className.includes("sticky"),h=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(c.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:f,isStickyHeader:p,inRecommendations:h,hasInvite:S,matchesName:y,ariaLabel:m}},s,r);if(!a.isMuted&&!a.isStickyHeader&&!a.inRecommendations){if(a.hasInvite&&!a.matchesName){console.log(` Skipping secondary button: wrong person (${a.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.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 l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let s of u){let a=await e.evaluate(c=>{let d=c.getBoundingClientRect(),f=d.width>0&&d.height>0,p=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:f,isInStickyHeader:p,top:d.top}},s);if(a.isVisible&&!a.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of u)s!==l&&await s.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let s=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(f=>{let p=f.innerText?.trim(),h=f.getAttribute("aria-label")||"",m=f.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!c)return null;let d=c.parentElement;for(let f=0;f<8&&d;f++){for(let p of d.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==c)return p;d=d.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),l),await w(500),await e.evaluate(c=>c.click(),l),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let a=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(a||(a=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),a||(a=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),a||(a=await e.$('div[role="button"][aria-label*="Invite"]')),a||(a=await e.$('div[role="button"][aria-label*="connect"]')),!a){let c=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let f of d){let p=f.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of f.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});a=c?.asElement?.()||null,a||await c?.dispose?.().catch(()=>{})}if(!a){let c=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),f=[];for(let p of d)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&f.push(m)}return[...new Set(f)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(a)return console.log(" Found: More dropdown"),{button:a,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),a=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(a)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Dt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!l.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await w(3e3)):(await e.evaluate(c=>c.click(),t),await w(3e3));let u=e.url();if(u.includes("/premium/")||u.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),a=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${a}`:` \u26A0 No modal after connect click \u2014 ${a}`),"success"}async function Or(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 w(1500);let n=await Ke(e);if(n){await e.evaluate(r=>r.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Tt(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let u=Ue();if(!u.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${u.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:u.reason,profileInfo:null}}let l=await Mr(e,t,n);return l.connectionSent&&!i&&Xt(t,o),l}async function Mr(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=n,s={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} ---`),u.length>0){let y=Y()[t]?.location;if(lt(y,u))return console.log(` \u26A0 Excluded location (stored): ${y}`),s.reason="excluded_location",s.profileInfo={location:y},s}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await we(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await $n(e,t),await w(2e3)),s.profileInfo=await e.evaluate(()=>{let y=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"]),k=T=>{let P=(T||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(P)},v={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},C=document.querySelector("main");if(!C)return v;let $=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],g=Array.from(C.querySelectorAll("h2")),A=$.find(T=>{let P=T.textContent&&T.textContent.trim();return P&&P.length>1&&P.length<100&&!y.has(P)&&P!=="0 notifications"}),L=A?A.textContent.trim():null,x=A?A.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(q=>q.tagName==="P").some(q=>{let U=q.textContent&&q.textContent.trim();return U&&U.length>5&&!k(U)});)x=x.parentElement;let O=null,V=null,j=null;if(x&&x!==C){let T=Array.from(x.children),P=T.filter(U=>U.tagName==="P").filter(U=>{let ne=U.textContent&&U.textContent.trim();return ne&&ne.length>5&&!k(ne)});P[0]&&(O=P[0].textContent.trim()),P[1]&&(V=P[1].textContent.trim());let q=T.filter(U=>U.tagName==="DIV");for(let U=q.length-1;U>=0;U--){let ne=q[U].textContent&&q[U].textContent.trim();if(ne&&!(L&&ne.startsWith(L))&&(j=ne.split(/[·•]/)[0].trim(),j))break}}let N=null;if(x){let T=x.querySelectorAll("p, span, div");for(let P of T){let q=(P.textContent||"").trim().replace(/^[·•]\s*/,"");if(q==="1st"||q==="2nd"||q==="3rd"){N=q;break}}}let J=null,D=g.find(T=>T.textContent&&T.textContent.trim()==="About");if(D){let T=D.parentElement;for(;T&&T.tagName!=="SECTION";)T=T.parentElement;T&&(J=(T.textContent||"").trim().replace(/^About\s*/,"").trim()||null,J&&(J=J.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]'),Se=H&&H.src||null,W=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:L,title:O,location:j,about:J,company:V,connectionDegree:N,connectionsCount:null,mutualConnections:null,photoUrl:Se,hasVerifiedBadge:W}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(s.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(u.length>0){let y=s.profileInfo?.location,k=Y()[t]?.location,v=y||k;if(lt(v,u))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${v}`),s.reason="excluded_location",s;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ee(e);if(s.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await we(e);let f=await Ke(e);if(!f&&(await we(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),f=await Ke(e)),!f))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=f.method;let p=await Dt(e,f.button);if(p==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(p==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await Ee(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await we(e),await w(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),k),await w(500),await k.click().catch(()=>e.evaluate(C=>C.click(),k)),await w(2e3);let v=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(v){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(g=>g.click(),v),await w(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),s.reason="premium_required",s;if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),s.reason="premium_required",s}catch(v){return console.log(" More dropdown failed:",v.message),await e.keyboard.press("Escape").catch(()=>{}),s.reason="premium_required",s}else return console.log(" \u2717 No More button found \u2014 Premium required"),s.reason="premium_required",s}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let v=k.querySelector('button[aria-label="Add a note"]'),C=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!v,sendWithout:!!C}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=k?.asElement?.()||null,S||await k.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let v=await Or(e);return s.success=v,s.connectionSent=v,s.reason=v?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let v=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",v);await k.type(C,{delay:20}),await w(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(g=>g.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=C,s}}}else if(S){console.log(" Sending without note...");try{await S.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let y=S;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(f.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 w(4e3)),await we(e),await w(500);let k=await e.$$('button[id*="profile-overflow-action"]'),v=null;for(let C of k){let $=await e.evaluate(g=>{let A=g.getBoundingClientRect();return{visible:A.width>0&&A.height>0,inSticky:!!g.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){v=C;break}}!v&&k.length>0&&(v=k[k.length-1]);for(let C of k)C!==v&&await C.dispose().catch(()=>{});if(v)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate($=>$.click(),v)),await w(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(L=>L.click(),C),await w(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await Ee(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s):(s.reason="premium_required",s);if(await Ee(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;let A=await e.$('button[aria-label="Send without a note"]');if(A){console.log(" Modal appeared via More dropdown, sending without note...");try{await A.evaluate(L=>L.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(a){console.error(` \u2717 Error: ${a.message}`),s.reason="error",s.error=a.message;let c=a.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{s.fatal=!0}return s}}async function Cn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:s=null,excludeLocations:a=[],source:c="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
240
240
  === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),a.length>0&&console.log(`Excluding locations: ${a.join(", ")}`),!l){let p=ke();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let f=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
241
241
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
242
242
  \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=Kt(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let S=null;if(l){let y=await It(e,h.profileUrl);y?(Xe(h.profileUrl,{...y,source:c}),d.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y}):(d.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=Ue();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(S=await Tt(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:a,source:c,skipQuotaGate:!0}),S.success)d.connectionsSent++;else switch(S.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(S?.fatal){console.log(`
243
243
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(S?.reason==="error"){if(f++,f>=3){console.log(`
244
- \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(S&&S.reason&&(et(h.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),Yt(h.profileUrl,{source:c||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:S.reason})),s&&await s(h,d,S),p<t.length-1){let y=u+Math.random()*2e3;await w(y)}}if(console.log(`
245
- === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=ke();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}var Mr,xn=se(async()=>{it();await Be();Mr={viewProfile:It,detectConnectionStatus:Ee,findConnectButton:Ke,clickConnectButton:Dt,sendConnectionRequest:Tt,runFunnel:$n,shouldExcludeLocation:at}});import{createGraphClient as Fr,resolveToken as Lr}from"@ilivemylife/graph-sdk";import{config as Pr}from"dotenv";var An,En,_n=se(()=>{Pr();An=Lr()||process.env.TOKEN;An||(console.error(`
244
+ \u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(S&&S.reason&&(tt(h.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),Yt(h.profileUrl,{source:c||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:S.reason})),s&&await s(h,d,S),p<t.length-1){let y=u+Math.random()*2e3;await w(y)}}if(console.log(`
245
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let p=ke();console.log(` Connection quota left: today ${p.daily.remaining} of ${p.daily.max} | week ${p.weekly.remaining} of ${p.weekly.max}`)}return d}var Fr,An=se(async()=>{at();await Be();Fr={viewProfile:It,detectConnectionStatus:Ee,findConnectButton:Ke,clickConnectButton:Dt,sendConnectionRequest:Tt,runFunnel:Cn,shouldExcludeLocation:lt}});import{createGraphClient as Lr,resolveToken as Pr}from"@ilivemylife/graph-sdk";import{config as qr}from"dotenv";var En,_n,In=se(()=>{qr();En=Pr()||process.env.TOKEN;En||(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));En=Fr({token:An})});import"dotenv/config";function qr(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 Ur({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${qr(r)}`:"",s=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 ${s} \u2014 ${l}${u}`}async function In({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let s=`**${Ur({scriptName:e,mode:t,status:n,error:r,duration:i})}**
249
+ `),process.exit(1));_n=Lr({token:En})});import"dotenv/config";function Ur(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 Br({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),u=r?` ${Ur(r)}`:"",s=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 ${s} \u2014 ${l}${u}`}async function Dn({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let s=`**${Br({scriptName:e,mode:t,status:n,error:r,duration:i})}**
250
250
 
251
251
  ${o.join(`
252
- `)}`;try{await En.addMessage(l,s)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Dn=se(()=>{_n()});var jn={};ie(jn,{endRun:()=>Gr,formatScriptStatus:()=>Qr,getLastRun:()=>Kr,getRunHistory:()=>Yr,getTodayRunSummary:()=>Rn,startRun:()=>Wr,timeAgo:()=>Nn});import"dotenv/config";import*as te from"fs";import*as be from"path";import{fileURLToPath as Br}from"url";function Hr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";te.writeFileSync(o,n);for(let r=0;r<3;r++)try{te.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function De(){try{if(!te.existsSync(Nt))return{runs:[]};let e=JSON.parse(te.readFileSync(Nt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Tn(e){te.existsSync(Rt)||te.mkdirSync(Rt,{recursive:!0});try{Hr(Nt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Wr(e,t="default"){let n=De();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),Tn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Gr(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=De(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration;else{let s=l.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}Tn(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";In({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function Yr(e=7){let t=De(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function Kr(e=null){let t=De(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function Rn(){let e=new Date().toISOString().slice(0,10),t=De(),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 r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function Nn(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function Qr(){let e=["sync-all","messages","funnel","sync","apply"],t=De(),n=Rn(),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 l=t.runs.filter(m=>m.script===i),u=[...l].reverse().find(m=>m.status==="success"),s=l[l.length-1],a=u||s,c=a?Nn(a.timestamp):"never",f=(a?Math.floor((Date.now()-new Date(a.timestamp).getTime())/864e5):1/0)>1?" \u26A0":a?.status==="error"?" \u2717":" \u2713",p="";if(a?.stats){let m=a.stats,S=Object.entries(m).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);S.length&&(p=` (${S.join(", ")})`)}let h=a?.duration?` ${Math.round(a.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${c.padEnd(16)}${h}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[i,l]of r){let u=[];l.success&&u.push(`${l.success} success`),l.error&&u.push(`${l.error} error`),l.interrupted&&u.push(`${l.interrupted} interrupted`),l.running&&u.push(`${l.running} running`),o.push(` Today: ${i} \xD7${l.total} (${u.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
- `)}var Jr,Vr,Rt,Nt,On=se(()=>{Dn();Jr=Br(import.meta.url),Vr=be.dirname(be.dirname(Jr)),Rt=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(Vr,"collected-profiles"),Nt=be.join(Rt,"run-log.json")});import*as ut from"fs";import*as Re from"path";await ze();await Be();import"dotenv/config";import*as tt from"fs";import*as me from"path";import{fileURLToPath as go}from"url";var yo=go(import.meta.url),wo=me.dirname(me.dirname(yo)),gt=process.env.DATA_DIR?me.resolve(process.env.DATA_DIR,"collected-profiles"):me.join(wo,"collected-profiles"),en=me.join(gt,"connect-queue.json"),bo=1,ve=300,nt=["queued","approved","sent","skipped","failed"],he=["high","normal","low"],Zt={high:0,normal:1,low:2};function So(){tt.existsSync(gt)||tt.mkdirSync(gt,{recursive:!0})}function yt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ve?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:he.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:nt.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function oe(){let e=Pe(en,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(yt).filter(n=>n.url):[]}function ge(e){So(),Le(en,{version:bo,entries:e.map(yt)})}function ce(e){return K(e)||(e||"").trim().toLowerCase()}function Je(e,t){let n=ce(t);return e.find(o=>ce(o.url)===n)||null}function wt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:l}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(a=>ce(a.url)));for(let a of t){let c=a?.url;if(!c){u.skippedNoUrl++;continue}let d=ce(c);if(s.has(d)){u.skippedDup++;continue}if(i(c)){u.skippedEngaged++;continue}let f=typeof a.note=="string"?a.note.trim():"";f.length>ve&&u.notesTooLong++;let p=f.length>0&&f.length<=ve;e.push(yt({url:c,tag:a.tag||o,priority:a.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:l||null})),s.add(d),u.added++}return u}function tn(e){return[...e].sort((t,n)=>{let o=(Zt[t.priority]??1)-(Zt[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function $e(e,t){return e.filter(n=>n.status===t)}await Be();await ze();var 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]}};function nn(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}import"dotenv/config";import*as b from"fs";import*as At from"os";import*as T from"path";import{fileURLToPath as Zo}from"url";var kt={};ie(kt,{NAME:()=>$o,VERSION:()=>vo,up:()=>Ao});import*as z from"fs";import*as ot from"path";var vo=1,$o="normalize-jobs-and-questions",Co=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],xo=50;function bt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function St(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ao(e,t){let n=ot.join(e,"jobs.json"),o=ot.join(t,"scouted-jobs.json"),r=ot.join(e,"application-questions.json"),i=bt(n)||{},l=bt(o)||{},u=0,s=[];for(let c of Object.keys(i)){if(!l[c])continue;let d=l[c],f=i[c];for(let p of Co)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(St(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=bt(r);if(a&&Array.isArray(a.applications)){let c={},d=0;for(let f of a.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=xo?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}St(r,c),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} 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(s.length>0){for(let c of s)delete l[c];St(o,l),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var vt={};ie(vt,{NAME:()=>_o,VERSION:()=>Eo,up:()=>To});import*as X from"fs";import*as on from"path";var Eo=2,_o="reset-unread-flags";function Io(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function Do(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function To(e){let t=on.join(e,"conversations.json"),n=Io(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Do(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var $t={};ie($t,{NAME:()=>No,VERSION:()=>Ro,up:()=>Lo});import*as Z from"fs";import*as rn from"path";var Ro=3,No="recompute-last-message-by",jo=new Set(["draft","confirmed","rejected","needs_review"]);function Oo(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function Mo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Fo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!jo.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,l)=>l.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Lo(e){let t=rn.join(e,"conversations.json"),n=Oo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,l=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let a=Array.isArray(s.messages)?s.messages:[],c=Fo(a,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==c&&l++,s.lastMessageBy=c,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}Mo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} 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 Ct={};ie(Ct,{NAME:()=>qo,VERSION:()=>Po,up:()=>Vo});import*as ee from"fs";import*as sn from"path";var Po=4,qo="split-connection-timestamps",Uo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Bo(e){if(!ee.existsSync(e))return null;let t=ee.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ee.writeFileSync(o,n)}catch(r){try{ee.unlinkSync(o)}catch{}throw r}try{ee.renameSync(o,e)}catch(r){try{ee.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Vo(e){let t=sn.join(e,"people.json"),n=Bo(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let l=n[i];!l||typeof l!="object"||(r++,Uo.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Jo(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Be();import"dotenv/config";import*as Q from"path";import{fileURLToPath as Ho}from"url";var Wo=Ho(import.meta.url),Go=Q.dirname(Q.dirname(Wo)),Ve=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Go,"market-research"),Ds=Q.join(Ve,"scouted-jobs.json"),Ts=Q.join(Ve,"discovered-people.json"),Rs=Q.join(Ve,"visit-log.json"),Ns=Q.join(Ve,"companies.json"),js=Q.join(Ve,"job-decisions.json");function an(){Yo=null,Ko=null,Qo=null,zo=null,Xo=null}var Yo=null;var Ko=null;var Qo=null;var zo=null;var Xo=null;var er=Zo(import.meta.url),tr=T.dirname(er),nr=T.dirname(T.dirname(tr));function or(e){return e&&(e==="~"?At.homedir():e.startsWith("~/")||e.startsWith("~\\")?T.join(At.homedir(),e.slice(2)):e)}var re=process.env.DATA_DIR?T.resolve(or(process.env.DATA_DIR)):nr,xe=T.join(re,"collected-profiles"),Ae=T.join(re,"market-research"),G=T.join(re,".schema-version"),ln=[T.join(xe,".schema-version"),T.join(Ae,".schema-version")],ye=4,ue=[{version:1,module:kt},{version:2,module:vt},{version:3,module:$t},{version:4,module:Ct}];(function(){ue.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ue){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ue.length?ue[ue.length-1].version:0;if(n!==ye)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ye}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ue.length;o++){let r=o+1;if(ue[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ue[o].version}`)}})();function fn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
252
+ `)}`;try{await _n.addMessage(l,s)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Tn=se(()=>{In()});var On={};ie(On,{endRun:()=>Yr,formatScriptStatus:()=>zr,getLastRun:()=>Qr,getRunHistory:()=>Kr,getTodayRunSummary:()=>Nn,startRun:()=>Gr,timeAgo:()=>jn});import"dotenv/config";import*as te from"fs";import*as be from"path";import{fileURLToPath as Jr}from"url";function Wr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";te.writeFileSync(o,n);for(let r=0;r<3;r++)try{te.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function De(){try{if(!te.existsSync(Nt))return{runs:[]};let e=JSON.parse(te.readFileSync(Nt,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Rn(e){te.existsSync(Rt)||te.mkdirSync(Rt,{recursive:!0});try{Wr(Nt,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Gr(e,t="default"){let n=De();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),Rn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Yr(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=De(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=n,u.error=o,r=u.duration;else{let s=l.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}Rn(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Dn({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}function Kr(e=7){let t=De(),n=Date.now()-e*24*60*60*1e3;return t.runs.filter(o=>new Date(o.timestamp).getTime()>n).sort((o,r)=>r.timestamp.localeCompare(o.timestamp))}function Qr(e=null){let t=De(),n=e?t.runs.filter(o=>o.script===e):t.runs;return n[n.length-1]||null}function Nn(){let e=new Date().toISOString().slice(0,10),t=De(),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 r=n[o.script];r.total++,o.status==="success"?r.success++:o.status==="error"?r.error++:o.status==="interrupted"?r.interrupted++:o.status==="partial"?r.partial++:o.status==="running"&&r.running++,r.lastRun=o}return n}function jn(e){if(!e)return"never";let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4),o=Math.floor(t/36e5),r=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:r===1?"yesterday":`${r} days ago`}function zr(){let e=["sync-all","messages","funnel","sync","apply"],t=De(),n=Nn(),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 l=t.runs.filter(m=>m.script===i),u=[...l].reverse().find(m=>m.status==="success"),s=l[l.length-1],a=u||s,c=a?jn(a.timestamp):"never",f=(a?Math.floor((Date.now()-new Date(a.timestamp).getTime())/864e5):1/0)>1?" \u26A0":a?.status==="error"?" \u2717":" \u2713",p="";if(a?.stats){let m=a.stats,S=Object.entries(m).filter(([,y])=>typeof y=="number"&&y>0).slice(0,3).map(([y,k])=>`${k} ${y}`);S.length&&(p=` (${S.join(", ")})`)}let h=a?.duration?` ${Math.round(a.duration/1e3)}s`:"";o.push(` ${i.padEnd(14)} ${c.padEnd(16)}${h}${p}${f}`)}let r=Object.entries(n);if(r.length>0){o.push("");for(let[i,l]of r){let u=[];l.success&&u.push(`${l.success} success`),l.error&&u.push(`${l.error} error`),l.interrupted&&u.push(`${l.interrupted} interrupted`),l.running&&u.push(`${l.running} running`),o.push(` Today: ${i} \xD7${l.total} (${u.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
+ `)}var Vr,Hr,Rt,Nt,Mn=se(()=>{Tn();Vr=Jr(import.meta.url),Hr=be.dirname(be.dirname(Vr)),Rt=process.env.DATA_DIR?be.resolve(process.env.DATA_DIR,"collected-profiles"):be.join(Hr,"collected-profiles"),Nt=be.join(Rt,"run-log.json")});import*as dt from"fs";import*as Re from"path";await ze();await Be();import"dotenv/config";import*as nt from"fs";import*as me from"path";import{fileURLToPath as yo}from"url";var wo=yo(import.meta.url),bo=me.dirname(me.dirname(wo)),gt=process.env.DATA_DIR?me.resolve(process.env.DATA_DIR,"collected-profiles"):me.join(bo,"collected-profiles"),tn=me.join(gt,"connect-queue.json"),So=1,ve=300,ot=["queued","approved","sent","skipped","failed"],he=["high","normal","low"],en={high:0,normal:1,low:2};function ko(){nt.existsSync(gt)||nt.mkdirSync(gt,{recursive:!0})}function yt(e={}){let t=typeof e.note=="string"?e.note.trim():"",n=t&&t.length<=ve?t:null;return{url:e.url||null,tag:e.tag||"untagged",priority:he.includes(e.priority)?e.priority:"normal",withNote:e.withNote===!0&&n!==null,note:n,status:ot.includes(e.status)?e.status:"queued",addedAt:e.addedAt||null,sentAt:e.sentAt||null,result:e.result||null}}function oe(){let e=Pe(tn,"connect-queue.json");return e?(Array.isArray(e)?e:e.entries||[]).map(yt).filter(n=>n.url):[]}function ge(e){ko(),Le(tn,{version:So,entries:e.map(yt)})}function ce(e){return G(e)||(e||"").trim().toLowerCase()}function Je(e,t){let n=ce(t);return e.find(o=>ce(o.url)===n)||null}function wt(e,t,n={}){let{tag:o="untagged",priority:r="normal",alreadyEngaged:i=()=>!1,nowIso:l}=n,u={added:0,skippedDup:0,skippedEngaged:0,skippedNoUrl:0,notesTooLong:0},s=new Set(e.map(a=>ce(a.url)));for(let a of t){let c=a?.url;if(!c){u.skippedNoUrl++;continue}let d=ce(c);if(s.has(d)){u.skippedDup++;continue}if(i(c)){u.skippedEngaged++;continue}let f=typeof a.note=="string"?a.note.trim():"";f.length>ve&&u.notesTooLong++;let p=f.length>0&&f.length<=ve;e.push(yt({url:c,tag:a.tag||o,priority:a.priority||r,withNote:p,note:p?f:null,status:"queued",addedAt:l||null})),s.add(d),u.added++}return u}function nn(e){return[...e].sort((t,n)=>{let o=(en[t.priority]??1)-(en[n.priority]??1);return o!==0?o:String(t.addedAt||"").localeCompare(String(n.addedAt||""))})}function $e(e,t){return e.filter(n=>n.status===t)}await Be();await ze();var vo={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]}};function on(e){if(!e)return null;for(let[t,n]of Object.entries(vo))if(n.title){for(let o of n.title)if(o.test(e))return t}return null}import"dotenv/config";import*as b from"fs";import*as At from"os";import*as R from"path";import{fileURLToPath as er}from"url";var kt={};ie(kt,{NAME:()=>Co,VERSION:()=>$o,up:()=>Eo});import*as z from"fs";import*as rt from"path";var $o=1,Co="normalize-jobs-and-questions",xo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ao=50;function bt(e){return z.existsSync(e)?JSON.parse(z.readFileSync(e,"utf-8")):null}function St(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{z.writeFileSync(o,n)}catch(r){try{z.unlinkSync(o)}catch{}throw r}try{z.renameSync(o,e)}catch(r){try{z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Eo(e,t){let n=rt.join(e,"jobs.json"),o=rt.join(t,"scouted-jobs.json"),r=rt.join(e,"application-questions.json"),i=bt(n)||{},l=bt(o)||{},u=0,s=[];for(let c of Object.keys(i)){if(!l[c])continue;let d=l[c],f=i[c];for(let p of xo)d[p]!=null&&f[p]==null&&(f[p]=d[p]);s.push(c),u++}u>0?(St(n,i),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=bt(r);if(a&&Array.isArray(a.applications)){let c={},d=0;for(let f of a.applications){let p=f.jobId||"unknown";c[p]||(c[p]={applications:[]});let h=(f.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Ao?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});c[p].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||h.length,questions:h})}St(r,c),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} 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(s.length>0){for(let c of s)delete l[c];St(o,l),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var vt={};ie(vt,{NAME:()=>Io,VERSION:()=>_o,up:()=>Ro});import*as X from"fs";import*as rn from"path";var _o=2,Io="reset-unread-flags";function Do(e){return X.existsSync(e)?JSON.parse(X.readFileSync(e,"utf-8")):null}function To(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{X.writeFileSync(o,n)}catch(r){try{X.unlinkSync(o)}catch{}throw r}try{X.renameSync(o,e)}catch(r){try{X.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ro(e){let t=rn.join(e,"conversations.json"),n=Do(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}To(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var $t={};ie($t,{NAME:()=>jo,VERSION:()=>No,up:()=>Po});import*as Z from"fs";import*as sn from"path";var No=3,jo="recompute-last-message-by",Oo=new Set(["draft","confirmed","rejected","needs_review"]);function Mo(e){return Z.existsSync(e)?JSON.parse(Z.readFileSync(e,"utf-8")):null}function Fo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Z.writeFileSync(o,n)}catch(r){try{Z.unlinkSync(o)}catch{}throw r}try{Z.renameSync(o,e)}catch(r){try{Z.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function Lo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!Oo.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,l)=>l.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Po(e){let t=sn.join(e,"conversations.json"),n=Mo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,l=0;for(let u of Object.keys(n)){let s=n[u];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let a=Array.isArray(s.messages)?s.messages:[],c=Lo(a,o),d=c==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==c&&l++,s.lastMessageBy=c,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}Fo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} 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 Ct={};ie(Ct,{NAME:()=>Uo,VERSION:()=>qo,up:()=>Ho});import*as ee from"fs";import*as an from"path";var qo=4,Uo="split-connection-timestamps",Bo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Jo(e){if(!ee.existsSync(e))return null;let t=ee.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Vo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{ee.writeFileSync(o,n)}catch(r){try{ee.unlinkSync(o)}catch{}throw r}try{ee.renameSync(o,e)}catch(r){try{ee.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Ho(e){let t=an.join(e,"people.json"),n=Jo(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let l=n[i];!l||typeof l!="object"||(r++,Bo.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Vo(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await Be();import"dotenv/config";import*as Q from"path";import{fileURLToPath as Wo}from"url";var Go=Wo(import.meta.url),Yo=Q.dirname(Q.dirname(Go)),Ve=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"market-research"):Q.join(Yo,"market-research"),Ts=Q.join(Ve,"scouted-jobs.json"),Rs=Q.join(Ve,"discovered-people.json"),Ns=Q.join(Ve,"visit-log.json"),js=Q.join(Ve,"companies.json"),Os=Q.join(Ve,"job-decisions.json");function ln(){Ko=null,Qo=null,zo=null,Xo=null,Zo=null}var Ko=null;var Qo=null;var zo=null;var Xo=null;var Zo=null;var tr=er(import.meta.url),nr=R.dirname(tr),or=R.dirname(R.dirname(nr));function rr(e){return e&&(e==="~"?At.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(At.homedir(),e.slice(2)):e)}var re=process.env.DATA_DIR?R.resolve(rr(process.env.DATA_DIR)):or,xe=R.join(re,"collected-profiles"),Ae=R.join(re,"market-research"),K=R.join(re,".schema-version"),cn=[R.join(xe,".schema-version"),R.join(Ae,".schema-version")],ye=4,ue=[{version:1,module:kt},{version:2,module:vt},{version:3,module:$t},{version:4,module:Ct}];(function(){ue.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ue){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ue.length?ue[ue.length-1].version:0;if(n!==ye)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ye}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ue.length;o++){let r=o+1;if(ue[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ue[o].version}`)}})();function pn(){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
255
  `),process.exit(1));try{b.mkdirSync(re,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
256
256
  [FATAL] Cannot create DATA_DIR (${re}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -260,64 +260,64 @@ ${o.join(`
260
260
  [FATAL] DATA_DIR (${re}) 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
261
  `),process.exit(1));for(let t of[xe,Ae]){let n;try{n=b.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 Ce=T.join(re,".migration-lock");function rr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync(Ce,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync(Ce,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}o&&i<r&&(console.error(`
263
+ `),process.exit(1))}}var Ce=R.join(re,".migration-lock");function sr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return b.writeFileSync(Ce,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(b.readFileSync(Ce,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}o&&i<r&&(console.error(`
264
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: ${Ce}
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>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ce+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,Ce),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Et(){try{if(JSON.parse(b.readFileSync(Ce,"utf-8")).pid!==process.pid)return;b.unlinkSync(Ce)}catch{}}var cn=!1;function sr(){if(cn)return;cn=!0;let e=()=>{try{Et()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ir(){if(b.existsSync(G))return;let e=[],t=[];for(let i of ln)if(b.existsSync(i))try{e.push({file:i,schema:rt(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
266
+ `),process.exit(1)),o&&i>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Ce+".tmp";try{return b.writeFileSync(n,e),b.renameSync(n,Ce),!0}catch(o){try{b.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Et(){try{if(JSON.parse(b.readFileSync(Ce,"utf-8")).pid!==process.pid)return;b.unlinkSync(Ce)}catch{}}var un=!1;function ir(){if(un)return;un=!0;let e=()=>{try{Et()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function ar(){if(b.existsSync(K))return;let e=[],t=[];for(let i of cn)if(b.existsSync(i))try{e.push({file:i,schema:st(i)})}catch(l){t.push({file:i,err:l.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,r=G+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,G)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of ln)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${G}`)}function ar(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 rt(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function un(){if(ir(),!b.existsSync(G))return{version:0,migrations:[]};let e;try{e=rt(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=ar(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 pn(e){try{b.chmodSync(e,384)}catch{}}function lr(e){if(fn(),b.existsSync(G))try{if(b.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{b.writeFileSync(t,JSON.stringify(e,null,2)),pn(t),b.renameSync(t,G)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function dn(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let s=u.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return b.statSync(T.join(e,u)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let u of o){let s=T.join(e,u),a=T.join(e,u+n);if(b.existsSync(a)){i++;continue}try{hn(s,a),r++}catch(c){l.push({file:u,err:c.message})}}if(l.length>0){let u=new Error(`Failed to back up ${l.length} file(s) in ${T.basename(e)}/: `+l.map(s=>`${s.file} (${s.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||i>0){let u=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${T.basename(e)}/ (${n})${u}`)}}var xt=!1;async function mn(){if(xt)return;fn(),pr();let t=un().version;if(t===ye){xt=!0;return}sr(),rr(),process.on("exit",Et),t>ye&&(console.error(`
271
+ `),process.exit(1)}let o=e[0].schema,r=K+".tmp";try{b.writeFileSync(r,JSON.stringify(o,null,2)),b.renameSync(r,K)}catch(i){try{b.unlinkSync(r)}catch{}throw i}for(let i of cn)if(b.existsSync(i))try{b.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${K}`)}function lr(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 st(e){let t=b.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dn(){if(ar(),!b.existsSync(K))return{version:0,migrations:[]};let e;try{e=st(K)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
272
+ [FATAL] ${K} 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=lr(e);return t===null&&(console.error(`
274
+ [FATAL] ${K} 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 mn(e){try{b.chmodSync(e,384)}catch{}}function cr(e){if(pn(),b.existsSync(K))try{if(b.lstatSync(K).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${K}. 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=K+".tmp";try{b.writeFileSync(t,JSON.stringify(e,null,2)),mn(t),b.renameSync(t,K)}catch(n){try{b.unlinkSync(t)}catch{}throw n}}function fn(e,t){if(!b.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=b.readdirSync(e).filter(u=>{let s=u.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return b.statSync(R.join(e,u)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let u of o){let s=R.join(e,u),a=R.join(e,u+n);if(b.existsSync(a)){i++;continue}try{gn(s,a),r++}catch(c){l.push({file:u,err:c.message})}}if(l.length>0){let u=new Error(`Failed to back up ${l.length} file(s) in ${R.basename(e)}/: `+l.map(s=>`${s.file} (${s.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||i>0){let u=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${R.basename(e)}/ (${n})${u}`)}}var xt=!1;async function hn(){if(xt)return;pn(),mr();let t=dn().version;if(t===ye){xt=!0;return}ir(),sr(),process.on("exit",Et),t>ye&&(console.error(`
276
276
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ye}.`),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
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${ye}.
278
278
  `),process.exit(1)),console.log(`
279
- \u{1F4E6} Schema migration: v${t} \u2192 v${ye}`);let n=mr();if(!n.ok){console.error(`
279
+ \u{1F4E6} Schema migration: v${t} \u2192 v${ye}`);let n=hr();if(!n.ok){console.error(`
280
280
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.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=ue.filter(r=>r.version>t);for(let r of o){console.log(`
283
- Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{dn(xe,r.version),dn(Ae,r.version)}catch(s){console.error(`
283
+ Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{fn(xe,r.version),fn(Ae,r.version)}catch(s){console.error(`
284
284
  [FATAL] Pre-migration backup failed for ${i}: ${s.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
285
285
  `),process.exit(1)}let u=r.module;try{await u.up(xe,Ae)}catch(s){console.error(`
286
- [FATAL] Migration ${i} failed: ${s.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=hr(l);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.
286
+ [FATAL] Migration ${i} failed: ${s.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let a=gr(l);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
287
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
288
288
  `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
289
- `)}process.exit(1)}try{let s=new Date().toISOString(),a={version:r.version,name:u.NAME||i,appliedAt:s},c=un();c.version=r.version,c.migratedAt=s,c.migrations=c.migrations||[],c.migrations.push(a),lr(c)}catch(s){console.error(`
289
+ `)}process.exit(1)}try{let s=new Date().toISOString(),a={version:r.version,name:u.NAME||i,appliedAt:s},c=dn();c.version=r.version,c.migratedAt=s,c.migrations=c.migrations||[],c.migrations.push(a),cr(c)}catch(s){console.error(`
290
290
  [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${s.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
291
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Wt()}catch{}try{an()}catch{}xt=!0,Et(),console.log(`
291
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Wt()}catch{}try{ln()}catch{}xt=!0,Et(),console.log(`
292
292
  \u2713 Schema is now at v${ye}
293
- `)}var cr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ur(e){let t=e.toLowerCase();return cr.some(n=>n.test(t))}var dr=6e4;function fr(){let e=Date.now(),t=[];for(let n of[re,xe,Ae]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!ur(r))continue;let i=T.join(n,r);try{let l=b.statSync(i);if(!l.isFile()||e-l.mtimeMs<dr)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function pr({verbose:e=!1}={}){let t=fr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${T.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function mr(){let e=[];for(let t of[xe,Ae]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=T.join(t,o);try{rt(r)}catch(i){e.push({dir:T.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function hr(e){let t=[],n=[];for(let i of[xe,Ae]){if(!b.existsSync(i))continue;let l=b.readdirSync(i).filter(u=>u.endsWith(e));for(let u of l){let s=T.join(i,u),a=u.slice(0,-e.length),c=T.join(i,a);try{a.toLowerCase().endsWith(".json")?rt(s):b.accessSync(s,b.constants.R_OK),t.push({backupPath:s,originalPath:c,fileName:u,dir:i})}catch(d){n.push(`${T.basename(i)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:l,fileName:u,dir:s}of t)try{hn(i,l),o++}catch(a){r.push(`${T.basename(s)}/${u}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function hn(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),pn(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var Ln=new Set(["connected"]),Pn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Mn=new Set(["pending","connected","excluded_location","email_required","premium_required"]),zr=3,lt=process.env.DATA_DIR?Re.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):Re.resolve("collected-profiles","connect-diagnostics");async function Xr(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(a=>Array.from(document.querySelectorAll(a)).map(c=>(c.innerText||"").trim()).filter(Boolean).join(" | "))('[role="alertdialog"], [role="dialog"], .artdeco-modal, .artdeco-toast-item, .ip-fuse-limit-alert, .artdeco-inline-feedback').slice(0,1e3),body:(document.body.innerText||"").slice(0,1500)}));ut.mkdirSync(lt,{recursive:!0});let i={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};ut.appendFileSync(Re.join(lt,"connect-failures.jsonl"),JSON.stringify(i)+`
294
- `);let l=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Re.join(lt,`fail-${l}.png`)})}catch{}return r.modal||""}catch{return""}}var Ne=process.argv.slice(2),qn=Ne[0],je=Ne.filter(e=>!e.startsWith("--")),Te=e=>Ne.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),de=e=>{let t=Ne.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&F(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},jt=()=>new Date().toISOString();function dt(){let e=Y(),t=new Map;for(let[n,o]of Object.entries(e)){let r=K(o.profileUrl||n);r&&t.set(r,o)}return t}function Un(e,t){let n=e.get(K(t));return n?Ln.has(n.connectionStatus)||Pn.has(n.connectionStatus):!1}async function Zr(){let e=je[1];if(!e)return F("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(a){return F(`Could not read/parse ${e}: ${a.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=de("tag")||"untagged",o=de("priority");if(o&&!he.includes(o))return F(`--priority must be one of: ${he.join(", ")}`);let r=o||"normal",i=oe(),l=dt(),u=wt(i,t,{tag:n,priority:r,nowIso:jt(),alreadyEngaged:a=>Un(l,a)});ge(i),console.log(`
293
+ `)}var ur=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function dr(e){let t=e.toLowerCase();return ur.some(n=>n.test(t))}var fr=6e4;function pr(){let e=Date.now(),t=[];for(let n of[re,xe,Ae]){if(!b.existsSync(n))continue;let o;try{o=b.readdirSync(n)}catch{continue}for(let r of o){if(!dr(r))continue;let i=R.join(n,r);try{let l=b.statSync(i);if(!l.isFile()||e-l.mtimeMs<fr)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function mr({verbose:e=!1}={}){let t=pr();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{b.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${R.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function hr(){let e=[];for(let t of[xe,Ae]){if(!b.existsSync(t))continue;let n=b.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=R.join(t,o);try{st(r)}catch(i){e.push({dir:R.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function gr(e){let t=[],n=[];for(let i of[xe,Ae]){if(!b.existsSync(i))continue;let l=b.readdirSync(i).filter(u=>u.endsWith(e));for(let u of l){let s=R.join(i,u),a=u.slice(0,-e.length),c=R.join(i,a);try{a.toLowerCase().endsWith(".json")?st(s):b.accessSync(s,b.constants.R_OK),t.push({backupPath:s,originalPath:c,fileName:u,dir:i})}catch(d){n.push(`${R.basename(i)}/${u}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:l,fileName:u,dir:s}of t)try{gn(i,l),o++}catch(a){r.push(`${R.basename(s)}/${u}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function gn(e,t){let n=t+".tmp";try{b.copyFileSync(e,n),mn(n)}catch(o){try{b.unlinkSync(n)}catch{}throw o}try{b.renameSync(n,t)}catch(o){try{b.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}var Pn=new Set(["connected"]),qn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]),Fn=new Set(["pending","connected","excluded_location","email_required","premium_required"]),Xr=3,ct=process.env.DATA_DIR?Re.resolve(process.env.DATA_DIR,"collected-profiles","connect-diagnostics"):Re.resolve("collected-profiles","connect-diagnostics");async function Zr(e,t,n){try{let o=e.url(),r=await e.evaluate(()=>({modal:(a=>Array.from(document.querySelectorAll(a)).map(c=>(c.innerText||"").trim()).filter(Boolean).join(" | "))('[role="alertdialog"], [role="dialog"], .artdeco-modal, .artdeco-toast-item, .ip-fuse-limit-alert, .artdeco-inline-feedback').slice(0,1e3),body:(document.body.innerText||"").slice(0,1500)}));dt.mkdirSync(ct,{recursive:!0});let i={at:new Date().toISOString(),target:t.url,reason:n||null,pageUrl:o,modalText:r.modal,bodySnippet:r.body};dt.appendFileSync(Re.join(ct,"connect-failures.jsonl"),JSON.stringify(i)+`
294
+ `);let l=new Date().toISOString().replace(/[:.]/g,"-");try{await e.screenshot({path:Re.join(ct,`fail-${l}.png`)})}catch{}return r.modal||""}catch{return""}}var Ne=process.argv.slice(2),Un=Ne[0],je=Ne.filter(e=>!e.startsWith("--")),Te=e=>Ne.some(t=>t===`--${e}`||t.startsWith(`--${e}=`)),de=e=>{let t=Ne.find(o=>o===`--${e}`||o.startsWith(`--${e}=`));if(t===void 0)return;let n=t.indexOf("=");return n===-1&&F(`--${e} needs a value \u2014 write --${e}=value (no space).`),t.slice(n+1)},jt=()=>new Date().toISOString();function ft(){let e=Y(),t=new Map;for(let[n,o]of Object.entries(e)){let r=G(o.profileUrl||n);r&&t.set(r,o)}return t}function Bn(e,t){let n=e.get(G(t));return n?Pn.has(n.connectionStatus)||qn.has(n.connectionStatus):!1}async function es(){let e=je[1];if(!e)return F("Usage: connect add <file.json> [--tag=X] [--priority=high]");let t;try{t=JSON.parse((await import("fs")).readFileSync(e,"utf-8"))}catch(a){return F(`Could not read/parse ${e}: ${a.message}`)}if(!Array.isArray(t))return F("File must be a JSON array of { url, note?, name? }.");let n=de("tag")||"untagged",o=de("priority");if(o&&!he.includes(o))return F(`--priority must be one of: ${he.join(", ")}`);let r=o||"normal",i=oe(),l=ft(),u=wt(i,t,{tag:n,priority:r,nowIso:jt(),alreadyEngaged:a=>Bn(l,a)});ge(i),console.log(`
295
295
  Added ${u.added} to queue (tag=${n}, priority=${r}).`),u.skippedDup&&console.log(` ${u.skippedDup} already in queue \u2014 skipped.`),u.skippedEngaged&&console.log(` ${u.skippedEngaged} already connected/pending \u2014 skipped.`),u.skippedNoUrl&&console.log(` ${u.skippedNoUrl} had no url \u2014 skipped.`),u.notesTooLong&&console.log(` ${u.notesTooLong} had notes over ${ve} chars \u2014 added WITHOUT a note (LinkedIn's limit); set a shorter one with \`connect note\`.`);let s=i.filter(a=>a.status==="queued"&&a.withNote).length;console.log(`
296
- Queue now: ${$e(i,"queued").length} queued, ${$e(i,"approved").length} approved.`),s&&console.log(` ${s} queued entries have a note saved \u2014 sent only with \`connect run --with-notes\`.`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var Fn=["founder","investor","hiring_manager","peer"];function es(){let e=de("category");if(e===void 0&&Te("valuable")&&(e=Fn.join(",")),!e)return F(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
297
- (shortcut: --valuable = ${Fn.join(",")})`);let t=e.split(",").map($=>$.trim()).filter(Boolean),n=$=>{let g=de($);if(g===void 0)return;let E=parseInt(g,10);return!Number.isInteger(E)||E<0?F(`--${$} must be a non-negative integer.`):E},o=n("min-posts")??0,r=n("max"),i=de("priority");if(i&&!he.includes(i))return F(`--priority must be one of: ${he.join(", ")}`);let l=de("tag"),u=!Te("no-validate"),s=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),a=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map($=>$.trim().toLowerCase()).filter(Boolean),c=$=>{if(!$)return!1;let g=String($).toLowerCase();return a.some(E=>g.includes(E))},d=Y(),f=[],p=0,h=0,m=0;for(let[$,g]of Object.entries(d))if(t.includes(g.category)&&!(Ln.has(g.connectionStatus)||Pn.has(g.connectionStatus))&&g.connectionDegree!=="1st"&&!((g.jobIds?.length||0)<o)){if(c(g.location)){p++;continue}if(u&&s.has(g.category)){let E=(typeof g.title=="string"?g.title:"").trim();if(!E){h++;continue}if(nn(E)!==g.category){m++;continue}}f.push({url:g.profileUrl||$,p:g})}let S={high:0,medium:1,low:2};f.sort(($,g)=>(S[$.p.personPriority]??1)-(S[g.p.personPriority]??1)||(g.p.mutualConnections||0)-($.p.mutualConnections||0)||(g.p.jobIds?.length||0)-($.p.jobIds?.length||0)),r!==void 0&&(f=f.slice(0,r));let y=f.map($=>({url:$.url,tag:l||$.p.category,priority:i||($.p.personPriority==="high"?"high":"normal")})),k=oe(),v=dt(),C=wt(k,y,{alreadyEngaged:$=>Un(v,$),nowIso:jt()});ge(k),console.log(`
296
+ Queue now: ${$e(i,"queued").length} queued, ${$e(i,"approved").length} approved.`),s&&console.log(` ${s} queued entries have a note saved \u2014 sent only with \`connect run --with-notes\`.`),console.log(`Next: review with \`connect list\`, approve with \`connect approve --tag=${n}\`, send with \`connect run\`.`)}var Ln=["founder","investor","hiring_manager","peer"];function ts(){let e=de("category");if(e===void 0&&Te("valuable")&&(e=Ln.join(",")),!e)return F(`Usage: connect fill --category=founder,investor,hiring_manager[,peer,recruiter] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
297
+ (shortcut: --valuable = ${Ln.join(",")})`);let t=e.split(",").map($=>$.trim()).filter(Boolean),n=$=>{let g=de($);if(g===void 0)return;let A=parseInt(g,10);return!Number.isInteger(A)||A<0?F(`--${$} must be a non-negative integer.`):A},o=n("min-posts")??0,r=n("max"),i=de("priority");if(i&&!he.includes(i))return F(`--priority must be one of: ${he.join(", ")}`);let l=de("tag"),u=!Te("no-validate"),s=new Set(["recruiter","hiring_manager","founder","investor","coach","sales"]),a=(process.env.FUNNEL_EXCLUDE_LOCATIONS||"").split(",").map($=>$.trim().toLowerCase()).filter(Boolean),c=$=>{if(!$)return!1;let g=String($).toLowerCase();return a.some(A=>g.includes(A))},d=Y(),f=[],p=0,h=0,m=0;for(let[$,g]of Object.entries(d))if(t.includes(g.category)&&!(Pn.has(g.connectionStatus)||qn.has(g.connectionStatus))&&g.connectionDegree!=="1st"&&!((g.jobIds?.length||0)<o)){if(c(g.location)){p++;continue}if(u&&s.has(g.category)){let A=(typeof g.title=="string"?g.title:"").trim();if(!A){h++;continue}if(on(A)!==g.category){m++;continue}}f.push({url:g.profileUrl||$,p:g})}let S={high:0,medium:1,low:2};f.sort(($,g)=>(S[$.p.personPriority]??1)-(S[g.p.personPriority]??1)||(g.p.mutualConnections||0)-($.p.mutualConnections||0)||(g.p.jobIds?.length||0)-($.p.jobIds?.length||0)),r!==void 0&&(f=f.slice(0,r));let y=f.map($=>({url:$.url,tag:l||$.p.category,priority:i||($.p.personPriority==="high"?"high":"normal")})),k=oe(),v=ft(),C=wt(k,y,{alreadyEngaged:$=>Bn(v,$),nowIso:jt()});ge(k),console.log(`
298
298
  Filled ${C.added} from [${t.join(", ")}]${o?` (\u2265${o} job-posts)`:""}${u?"":" (--no-validate)"}.`),C.skippedDup&&console.log(` ${C.skippedDup} already in queue \u2014 skipped.`),C.skippedEngaged&&console.log(` ${C.skippedEngaged} already connected/pending \u2014 skipped.`),p&&console.log(` ${p} in excluded locations \u2014 skipped.`),m&&console.log(` ${m} filtered \u2014 title doesn't confirm the category (likely mis-tagged by enrichment).`),h&&console.log(` ${h} skipped \u2014 no title stored to validate (held; not visited, to avoid ban risk).`),console.log(`
299
- Queue now: ${$e(k,"queued").length} queued, ${$e(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function ts(){let e=oe();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=de("status"),n=dt(),o=ke();console.log(`
299
+ Queue now: ${$e(k,"queued").length} queued, ${$e(k,"approved").length} approved.`),console.log("Next: review with `connect list`, approve with `connect approve --all`, send with `connect run`.")}function ns(){let e=oe();if(!e.length)return console.log("\nQueue is empty. Add people with `connect add <file.json>`.");let t=de("status"),n=ft(),o=ke();console.log(`
300
300
  === Connect Queue === (quota left: ${o.daily.remaining}/${o.daily.max} today, ${o.weekly.remaining}/${o.weekly.max} week)
301
301
  `);let r={};for(let a of e)r[a.status]=(r[a.status]||0)+1;console.log("Status: "+Object.entries(r).map(([a,c])=>`${a}=${c}`).join(" ")+`
302
- `),t&&!nt.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${nt.join(", ")})
303
- `);let i=t?e.filter(a=>a.status===t):e,l={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...i].sort((a,c)=>(l[a.status]??9)-(l[c.status]??9));for(let a of u){let c=n.get(K(a.url)),d=c&&c.name||"",f=c&&c.title?` \xB7 ${c.title.slice(0,40)}`:"",p=c&&c.mutualConnections?` \xB7 ${c.mutualConnections} mutual`:"",h=a.withNote?"\u{1F4DD}":" ",m=a.priority==="high"?"\u2B06high ":a.priority==="low"?"\u2B07low ":"normal";console.log(` [${a.status.padEnd(8)}] ${m} ${h} ${d}${f}${p}`),console.log(` ${a.url} (tag=${a.tag})`)}let s=e.filter(a=>(a.status==="queued"||a.status==="approved")&&a.withNote).length;s&&console.log(`
304
- ${s} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function ct(e,t,n,o){let r=oe(),i=0;for(let l of r)e(l)&&t.includes(l.status)&&(l.status=n,i++);return ge(r),console.log(`
305
- ${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function ns(){let e=["queued","failed"];if(Te("all"))return ct(()=>!0,e,"approved","Approved");let t=de("tag");if(t)return ct(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=je[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=ce(n);return ct(r=>ce(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function os(){let e=je[1];if(!e)return F("Usage: connect skip <url>");let t=ce(e);return ct(n=>ce(n.url)===t,["queued","approved"],"skipped","Skipped")}function rs(){let e=Ne[1],t=Ne[2];if(!e||t===void 0)return F('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return F("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>ve)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${ve}. Shorten it.`);let o=oe(),r=Je(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,ge(o),console.log(`
306
- Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function ss(){let e=je[1];if(!e)return F("Usage: connect no-note <url>");let t=oe(),n=Je(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,ge(t),console.log(`
307
- Note reminder cleared.`)}function is(){let e=je[1],t=je[2];if(!e||!he.includes(t))return F(`Usage: connect priority <url> <${he.join("|")}>`);let n=oe(),o=Je(n,e);if(!o)return F("Not in queue.");o.priority=t,ge(n),console.log(`
308
- Priority set to ${t}.`)}async function as(){let e=Te("dry-run"),t=Te("yes"),n=Te("with-notes"),o=de("max"),r=1/0;if(o!==void 0){let g=parseInt(o,10);if(!Number.isInteger(g)||g<0)return F("--max must be a non-negative integer.");r=g}let i=ke(),l=Math.min(i.daily.remaining,i.weekly.remaining),u=oe(),s=tn($e(u,"approved"));if(!s.length){let g=$e(u,"queued").length;console.log(`
302
+ `),t&&!ot.includes(t)&&console.log(`(unknown status "${t}" \u2014 valid: ${ot.join(", ")})
303
+ `);let i=t?e.filter(a=>a.status===t):e,l={approved:0,queued:1,failed:2,skipped:3,sent:4},u=[...i].sort((a,c)=>(l[a.status]??9)-(l[c.status]??9));for(let a of u){let c=n.get(G(a.url)),d=c&&c.name||"",f=c&&c.title?` \xB7 ${c.title.slice(0,40)}`:"",p=c&&c.mutualConnections?` \xB7 ${c.mutualConnections} mutual`:"",h=a.withNote?"\u{1F4DD}":" ",m=a.priority==="high"?"\u2B06high ":a.priority==="low"?"\u2B07low ":"normal";console.log(` [${a.status.padEnd(8)}] ${m} ${h} ${d}${f}${p}`),console.log(` ${a.url} (tag=${a.tag})`)}let s=e.filter(a=>(a.status==="queued"||a.status==="approved")&&a.withNote).length;s&&console.log(`
304
+ ${s} pending entries have a saved note \u2014 sent only with \`connect run --with-notes\` (LinkedIn caps personal notes per month).`),console.log("")}function ut(e,t,n,o){let r=oe(),i=0;for(let l of r)e(l)&&t.includes(l.status)&&(l.status=n,i++);return ge(r),console.log(`
305
+ ${o}: ${i} entr${i===1?"y":"ies"} \u2192 ${n}.`),i}function os(){let e=["queued","failed"];if(Te("all"))return ut(()=>!0,e,"approved","Approved");let t=de("tag");if(t)return ut(r=>r.tag===t,e,"approved",`Approved tag=${t}`);let n=je[1];if(!n)return F("Usage: connect approve <url> | --all | --tag=X");let o=ce(n);return ut(r=>ce(r.url)===o,["queued","failed","skipped"],"approved","Approved")}function rs(){let e=je[1];if(!e)return F("Usage: connect skip <url>");let t=ce(e);return ut(n=>ce(n.url)===t,["queued","approved"],"skipped","Skipped")}function ss(){let e=Ne[1],t=Ne[2];if(!e||t===void 0)return F('Usage: connect note <url> "custom note text"');let n=t.trim();if(!n)return F("Note is empty \u2014 use `connect no-note <url>` to remove a note.");if(n.length>ve)return F(`Note is ${n.length} chars \u2014 LinkedIn caps connection-request notes at ${ve}. Shorten it.`);let o=oe(),r=Je(o,e);if(!r)return F("Not in queue.");r.note=n,r.withNote=!0,ge(o),console.log(`
306
+ Note saved (${n.length} chars). It's sent ONLY when you run \`connect run --with-notes\` (that spends one of your few monthly LinkedIn notes) \u2014 otherwise this person gets a plain request.`)}function is(){let e=je[1];if(!e)return F("Usage: connect no-note <url>");let t=oe(),n=Je(t,e);if(!n)return F("Not in queue.");n.note=null,n.withNote=!1,ge(t),console.log(`
307
+ Note reminder cleared.`)}function as(){let e=je[1],t=je[2];if(!e||!he.includes(t))return F(`Usage: connect priority <url> <${he.join("|")}>`);let n=oe(),o=Je(n,e);if(!o)return F("Not in queue.");o.priority=t,ge(n),console.log(`
308
+ Priority set to ${t}.`)}async function ls(){let e=Te("dry-run"),t=Te("yes"),n=Te("with-notes"),o=de("max"),r=1/0;if(o!==void 0){let g=parseInt(o,10);if(!Number.isInteger(g)||g<0)return F("--max must be a non-negative integer.");r=g}let i=ke(),l=Math.min(i.daily.remaining,i.weekly.remaining),u=oe(),s=nn($e(u,"approved"));if(!s.length){let g=$e(u,"queued").length;console.log(`
309
309
  Nothing approved to send.`),g&&console.log(` ${g} queued \u2014 approve them first: \`connect approve --all\` (or --tag=X).`);return}if(l<=0){console.log(`
310
310
  Connection quota is used up (${i.daily.remaining}/${i.daily.max} today, ${i.weekly.remaining}/${i.weekly.max} week). Try again later.`);return}let a=s.slice(0,Math.min(r,l));if(!a.length){console.log(`
311
311
  Nothing to send (--max=${r===1/0?"\u221E":r}).`);return}let c=a.filter(g=>g.withNote).length;console.log(`
312
- === Connect run ===`),console.log(` Approved: ${s.length} \xB7 quota left: ${l} \xB7 sending: ${a.length}${n?` (${c} WITH a note)`:" (without notes)"}`),!n&&c&&console.log(` ${c} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let d=dt();if(a.forEach((g,E)=>{let L=d.get(K(g.url));console.log(` ${E+1}. ${g.withNote?"\u{1F4DD}":" "} ${L?.name||g.url} (${g.priority}, tag=${g.tag})`)}),e){console.log(`
312
+ === Connect run ===`),console.log(` Approved: ${s.length} \xB7 quota left: ${l} \xB7 sending: ${a.length}${n?` (${c} WITH a note)`:" (without notes)"}`),!n&&c&&console.log(` ${c} have a saved note \u2014 add --with-notes to send it (spends your scarce monthly notes).`);let d=ft();if(a.forEach((g,A)=>{let L=d.get(G(g.url));console.log(` ${A+1}. ${g.withNote?"\u{1F4DD}":" "} ${L?.name||g.url} (${g.priority}, tag=${g.tag})`)}),e){console.log(`
313
313
  [dry-run] Nothing sent. Drop --dry-run to send.`);return}t||(console.log(`
314
- Press Enter to send, or Ctrl+C to cancel...`),await new Promise(g=>process.stdin.once("data",()=>g())));let f=(await import("puppeteer")).default,{loadCookies:p}=await Promise.resolve().then(()=>(wn(),yn)),{sendConnectionRequest:h}=await xn().then(()=>Cn),{delayed:m}=await Promise.resolve().then(()=>(it(),bn)),{startRun:S,endRun:y}=await Promise.resolve().then(()=>(On(),jn)),k=S("connect","run"),v,C;try{v=await f.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),C=await v.newPage(),await C.setCookie(...p())}catch(g){console.error(`
314
+ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(g=>process.stdin.once("data",()=>g())));let f=(await import("puppeteer")).default,{loadCookies:p}=await Promise.resolve().then(()=>(bn(),wn)),{sendConnectionRequest:h}=await An().then(()=>xn),{delayed:m}=await Promise.resolve().then(()=>(at(),Sn)),{startRun:S,endRun:y}=await Promise.resolve().then(()=>(Mn(),On)),k=S("connect","run"),v,C;try{v=await f.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),C=await v.newPage(),await C.setCookie(...p())}catch(g){console.error(`
315
315
  [!] ${g.message}
316
- `);try{v&&await v.close()}catch{}try{y(k,"error",null,g.message)}catch{}process.exit(1)}let $=0;try{let g=Y(),E=new Map;for(let[O,H]of Object.entries(g)){let N=K(H.profileUrl||O);N&&E.set(N,O)}let L=0,x=0,j=0,J=0;for(let O of a){if(!Ue().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let H=n&&O.withNote,N=await h(C,O.url,{message:H?O.note:null,useCustomMessage:H,source:O.tag,skipQuotaGate:!0}),V;if(N.connectionSent?(V="sent",L++):Mn.has(N.reason)?(V="skipped",x++):(V="failed",j++),V==="failed"){J++;let W=await Xr(C,O,N.reason);console.log(` \u2717 ${O.url.slice(-32)} \u2014 ${N.reason||"failed"}${W?` \xB7 LinkedIn: "${W.slice(0,120)}"`:""}`)}else J=0;let Se=E.get(K(O.url));if(N.connectionSent||Mn.has(N.reason)&&Se){let W=Se||O.url;try{et(W,N.reason,{method:N.method,messageSent:N.messageSent,profileInfo:N.profileInfo})}catch{}}try{let W=oe(),D=Je(W,O.url);D&&(D.status=V,V==="sent"&&(D.sentAt=jt()),D.result=N.reason||N.error||V,ge(W))}catch(W){console.error(` \u26A0 Could not persist queue update for ${O.url}: ${W.message}`)}if(N.fatal){console.log(`
317
- \u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(J>=zr){console.log(`
318
- \u26A0 ${J} sends failed in a row \u2014 stopping to protect your account (this is often LinkedIn's invite limit).`),console.log(` What LinkedIn showed on each failure is saved to: ${lt}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await m(3e3+Math.random()*2e3)}let R=ke();console.log(`
319
- === Done: ${L} sent, ${x} skipped, ${j} failed ===`),console.log(`Connection quota left: ${R.daily.remaining}/${R.daily.max} today, ${R.weekly.remaining}/${R.weekly.max} week.`);try{y(k,"success",{sent:L,skipped:x,failed:j})}catch{}}catch(g){console.error(`
320
- [!] Run aborted: ${g.message}`);try{y(k,"error",null,g.message)}catch{}$=1}finally{try{await v.close()}catch{}}process.exit($)}function F(e){console.error(e),process.exit(1)}function ls(){console.log(`connect \u2014 connect queue
316
+ `);try{v&&await v.close()}catch{}try{y(k,"error",null,g.message)}catch{}process.exit(1)}let $=0;try{let g=Y(),A=new Map;for(let[N,J]of Object.entries(g)){let D=G(J.profileUrl||N);D&&!A.has(D)&&A.set(D,N)}for(let[N,J]of Object.entries(g))for(let D of J.aliases||[])D&&!A.has(D)&&A.set(D,N);let L=0,x=0,O=0,V=0;for(let N of a){if(!Ue().allowed){console.log(" Quota reached mid-run \u2014 stopping.");break}let J=n&&N.withNote,D=await h(C,N.url,{message:J?N.note:null,useCustomMessage:J,source:N.tag,skipQuotaGate:!0}),H;if(D.connectionSent?(H="sent",L++):Fn.has(D.reason)?(H="skipped",x++):(H="failed",O++),H==="failed"){V++;let W=await Zr(C,N,D.reason);console.log(` \u2717 ${N.url.slice(-32)} \u2014 ${D.reason||"failed"}${W?` \xB7 LinkedIn: "${W.slice(0,120)}"`:""}`)}else V=0;let Se=A.get(G(N.url));if(D.connectionSent||Fn.has(D.reason)&&Se){let W=Se||N.url;try{tt(W,D.reason,{method:D.method,messageSent:D.messageSent,profileInfo:D.profileInfo})}catch{}if(D.resolvedUrl)try{Qt(W,D.resolvedUrl)}catch{}}try{let W=oe(),T=Je(W,N.url);T&&(T.status=H,H==="sent"&&(T.sentAt=jt()),T.result=D.reason||D.error||H,ge(W))}catch(W){console.error(` \u26A0 Could not persist queue update for ${N.url}: ${W.message}`)}if(D.fatal){console.log(`
317
+ \u26A0 Browser/page died mid-run \u2014 aborting (remaining entries left approved).`);break}if(V>=Xr){console.log(`
318
+ \u26A0 ${V} sends failed in a row \u2014 stopping to protect your account (this is often LinkedIn's invite limit).`),console.log(` What LinkedIn showed on each failure is saved to: ${ct}`),console.log(" Try again later; if it persists you've likely hit LinkedIn's weekly invite limit.");break}await m(3e3+Math.random()*2e3)}let j=ke();console.log(`
319
+ === Done: ${L} sent, ${x} skipped, ${O} failed ===`),console.log(`Connection quota left: ${j.daily.remaining}/${j.daily.max} today, ${j.weekly.remaining}/${j.weekly.max} week.`);try{y(k,"success",{sent:L,skipped:x,failed:O})}catch{}}catch(g){console.error(`
320
+ [!] Run aborted: ${g.message}`);try{y(k,"error",null,g.message)}catch{}$=1}finally{try{await v.close()}catch{}}process.exit($)}function F(e){console.error(e),process.exit(1)}function cs(){console.log(`connect \u2014 connect queue
321
321
 
322
322
  connect add <file.json> [--tag=X] [--priority=high|normal|low]
323
323
  connect fill --category=founder,investor,... [--valuable] [--min-posts=N] [--max=N] [--priority=LEVEL] [--tag=X]
@@ -325,4 +325,4 @@ Press Enter to send, or Ctrl+C to cancel...`),await new Promise(g=>process.stdin
325
325
  connect approve <url> | --all | --tag=X
326
326
  connect note <url> "custom note" connect no-note <url>
327
327
  connect skip <url> connect priority <url> <high|normal|low>
328
- connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var cs={add:Zr,fill:es,list:ts,approve:ns,skip:os,note:rs,"no-note":ss,priority:is,run:as},Bn=cs[qn];Bn||(ls(),process.exit(qn?1:0));await mn();await Bn();
328
+ connect run [--max=N] [--with-notes] [--dry-run] [--yes]`)}var us={add:es,fill:ts,list:ns,approve:os,skip:rs,note:ss,"no-note":is,priority:as,run:ls},Jn=us[Un];Jn||(cs(),process.exit(Un?1:0));await hn();await Jn();