ilml-plugin-linkedin 1.19.0 → 1.19.2

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