ilml-plugin-linkedin 1.17.2 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- var un=Object.defineProperty;var ft=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(e,t)=>{for(var n in t)un(e,n,{get:t[n],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function le(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),c=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||l||c){let r=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(r)return r.click(),{dismissed:!0,matched:s.substring(0,80)};let u=o.querySelectorAll("button");for(let a of u){let d=a.innerText?.trim().toLowerCase()||"",p=a.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||p.includes("dismiss"))return a.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var _e=ft(()=>{});var Tt={};we(Tt,{extractCertificationsFromDetails:()=>Un,extractEducationFromDetails:()=>Pn,extractExperienceFromDetails:()=>Mn,extractFeaturedFromDetails:()=>Ln,extractRecommendationsFromDetails:()=>Bn,extractSkillsFromDetails:()=>qn});async function Mn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)s++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function l(a){let d=[];for(let p of a.querySelectorAll("div")){let f=Array.from(p.children).filter(m=>m.tagName==="DIV");if(f.length<3)continue;let h=f.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(p.textContent||"").length<500||d.push({el:p,count:h.length,totalText:(p.textContent||"").length})}return d.sort((p,f)=>f.count-p.count||p.totalText-f.totalText),d[0]?.el}let c=l(i);if(!c)return[];let r=Array.from(c.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function u(a){let d=a[0]||null,p=null,f=null;if(a[1]){let $=a[1].split("\xB7").map(M=>M.trim());p=$[0]||null,$[1]&&(f=$[1])}let h=a.findIndex($=>/(\d{4}|present)/i.test($)&&/(-|–|—)/i.test($)&&$.length<80),m=null,b=null;if(h>=0){let $=a[h].split("\xB7").map(M=>M.trim());m=$[0]||null,$[1]&&(b=$[1])}let y=null,v=-1;if(h>=0&&a[h+1]){let $=a[h+1],M=/^[>*\-•]|^&gt;/.test($),Q=/https?:\/\//.test($),G=/\d{4}/.test($),L=/,/.test($)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test($);!M&&!Q&&!G&&$.length<100&&L&&(y=$,v=h+1)}let x=null,S=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){S=a.length-1;let $=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);$&&(x={listed:$[1].split(",").map(M=>M.trim()),additional:parseInt($[2],10)})}let N=new Set([0,1,h,v,S].filter($=>$>=0)),T=a.filter(($,M)=>!N.has(M)),_=T.length>0?T.join(`
1
+ var kn=Object.defineProperty;var mt=(e,t)=>()=>(e&&(t=e(e=0)),t);var be=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};async function w(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function ce(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",i=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),l=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),c=r.includes("Get hired faster")||r.includes("Get hired 2x");if(i||l||c){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 u=o.querySelectorAll("button");for(let a of u){let d=a.innerText?.trim().toLowerCase()||"",p=a.getAttribute("aria-label")?.toLowerCase()||"";if(d==="not now"||d==="no thanks"||d==="dismiss"||p.includes("dismiss"))return a.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})}var Oe=mt(()=>{});var Nt={};be(Nt,{extractCertificationsFromDetails:()=>Zn,extractEducationFromDetails:()=>zn,extractExperienceFromDetails:()=>Gn,extractFeaturedFromDetails:()=>Kn,extractRecommendationsFromDetails:()=>Xn,extractSkillsFromDetails:()=>Qn});async function Gn(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let i=0;i<5;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)r++,await w(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await e.evaluate(()=>{let i=document.querySelector("main");if(!i)return[];function l(a){let d=[];for(let p of a.querySelectorAll("div")){let f=Array.from(p.children).filter(m=>m.tagName==="DIV");if(f.length<3)continue;let h=f.filter(m=>(m.textContent||"").trim().length>50);h.length<3||(p.textContent||"").length<500||d.push({el:p,count:h.length,totalText:(p.textContent||"").length})}return d.sort((p,f)=>f.count-p.count||p.totalText-f.totalText),d[0]?.el}let c=l(i);if(!c)return[];let s=Array.from(c.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function u(a){let d=a[0]||null,p=null,f=null;if(a[1]){let C=a[1].split("\xB7").map(L=>L.trim());p=C[0]||null,C[1]&&(f=C[1])}let h=a.findIndex(C=>/(\d{4}|present)/i.test(C)&&/(-|–|—)/i.test(C)&&C.length<80),m=null,b=null;if(h>=0){let C=a[h].split("\xB7").map(L=>L.trim());m=C[0]||null,C[1]&&(b=C[1])}let y=null,k=-1;if(h>=0&&a[h+1]){let C=a[h+1],L=/^[>*\-•]|^&gt;/.test(C),Z=/https?:\/\//.test(C),G=/\d{4}/.test(C),M=/,/.test(C)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(C);!L&&!Z&&!G&&C.length<100&&M&&(y=C,k=h+1)}let x=null,S=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){S=a.length-1;let C=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);C&&(x={listed:C[1].split(",").map(L=>L.trim()),additional:parseInt(C[2],10)})}let N=new Set([0,1,h,k,S].filter(C=>C>=0)),T=a.filter((C,L)=>!N.has(L)),_=T.length>0?T.join(`
2
2
 
3
- `):null;return{title:d,company:p,employmentType:f,dates:m,duration:b,location:y,description:_,skills:x,_raw:a}}return r.map(a=>{let p=(a.innerText||"").trim().split(`
4
- `).map(f=>f.trim()).filter(f=>f&&f.length<5e3);return u(p)}).filter(a=>a.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 w(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function Ce(e,t,n,o){try{return await o()}catch(s){let i=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(i))throw s;return/not available on profile/i.test(i)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${i.slice(0,120)}`),[])}}async function Ln(e,t){return Ce(t,"featured","extractFeaturedFromDetails",async()=>(await ke(e,t,"featured"),await e.evaluate(`(() => {
5
- ${$e}
3
+ `):null;return{title:d,company:p,employmentType:f,dates:m,duration:b,location:y,description:_,skills:x,_raw:a}}return s.map(a=>{let p=(a.innerText||"").trim().split(`
4
+ `).map(f=>f.trim()).filter(f=>f&&f.length<5e3);return u(p)}).filter(a=>a.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 $e(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let i=0;for(;i<5&&await e.evaluate(()=>{for(let c of document.querySelectorAll("button"))if(/^Load more$/i.test((c.textContent||"").trim()))return c.click(),!0;return!1});)i++,await w(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function Ee(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 Kn(e,t){return Ee(t,"featured","extractFeaturedFromDetails",async()=>(await $e(e,t,"featured"),await e.evaluate(`(() => {
5
+ ${xe}
6
6
 
7
7
  const main = document.querySelector('main');
8
8
  if (!main) return [];
@@ -42,8 +42,8 @@ var un=Object.defineProperty;var ft=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(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 Pn(e,t){return Ce(t,"education","extractEducationFromDetails",async()=>(await ke(e,t,"education"),await e.evaluate(`(() => {
46
- ${$e}
45
+ })()`)))}async function zn(e,t){return Ee(t,"education","extractEducationFromDetails",async()=>(await $e(e,t,"education"),await e.evaluate(`(() => {
46
+ ${xe}
47
47
 
48
48
  const main = document.querySelector('main');
49
49
  if (!main) return [];
@@ -79,8 +79,8 @@ var un=Object.defineProperty;var ft=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(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 qn(e,t){return Ce(t,"skills","extractSkillsFromDetails",async()=>(await ke(e,t,"skills"),await e.evaluate(`(() => {
83
- ${$e}
82
+ })()`)))}async function Qn(e,t){return Ee(t,"skills","extractSkillsFromDetails",async()=>(await $e(e,t,"skills"),await e.evaluate(`(() => {
83
+ ${xe}
84
84
 
85
85
  const main = document.querySelector('main');
86
86
  if (!main) return [];
@@ -111,8 +111,8 @@ var un=Object.defineProperty;var ft=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(e,t)=>{
111
111
  skills.push({ name, endorsements, _raw: lines });
112
112
  }
113
113
  return skills;
114
- })()`)))}async function Un(e,t){return Ce(t,"certifications","extractCertificationsFromDetails",async()=>(await ke(e,t,"certifications"),await e.evaluate(`(() => {
115
- ${$e}
114
+ })()`)))}async function Zn(e,t){return Ee(t,"certifications","extractCertificationsFromDetails",async()=>(await $e(e,t,"certifications"),await e.evaluate(`(() => {
115
+ ${xe}
116
116
 
117
117
  const main = document.querySelector('main');
118
118
  if (!main) return [];
@@ -136,8 +136,8 @@ var un=Object.defineProperty;var ft=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(e,t)=>{
136
136
 
137
137
  return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
138
138
  }).filter(e => e.name);
139
- })()`)))}async function Bn(e,t){return Ce(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ke(e,t,"recommendations"),await e.evaluate(`(() => {
140
- ${$e}
139
+ })()`)))}async function Xn(e,t){return Ee(t,"recommendations","extractRecommendationsFromDetails",async()=>(await $e(e,t,"recommendations"),await e.evaluate(`(() => {
140
+ ${xe}
141
141
 
142
142
  const main = document.querySelector('main');
143
143
  if (!main) return [];
@@ -172,7 +172,7 @@ var un=Object.defineProperty;var ft=(e,t)=>()=>(e&&(t=e(e=0)),t);var we=(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 $e,jt=ft(()=>{_e();$e=`
175
+ })()`)))}var xe,Ft=mt(()=>{Oe();xe=`
176
176
  function findEntryContainer(root) {
177
177
  const candidates = [];
178
178
  for (const div of root.querySelectorAll('div')) {
@@ -235,21 +235,21 @@ 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
- `});import zo from"puppeteer";import"dotenv/config";import*as J from"fs";import*as se from"path";import{fileURLToPath as gn}from"url";import"dotenv/config";import{createGraphClient as dn,resolveToken as fn}from"@ilivemylife/graph-sdk";import{config as pn}from"dotenv";pn();var pt=fn()||process.env.TOKEN;pt||(console.error(`
238
+ `});import ar from"puppeteer";import"dotenv/config";import*as J from"fs";import*as ie from"path";import{fileURLToPath as An}from"url";import"dotenv/config";import{createGraphClient as vn,resolveToken as Cn}from"@ilivemylife/graph-sdk";import{config as $n}from"dotenv";$n();var ht=Cn()||process.env.TOKEN;ht||(console.error(`
239
239
  [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.
240
240
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
241
241
  `),console.error(` Or add ILML_TOKEN=... to .env
242
- `),process.exit(1));var mt=dn({token:pt});function mn(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 hn({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${mn(s)}`:"",r=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${r} \u2014 ${l}${c}`}async function ht({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let r=`**${hn({scriptName:e,mode:t,status:n,error:s,duration:i})}**
242
+ `),process.exit(1));var gt=vn({token:ht});function xn(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 En({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${xn(r)}`:"",s=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${s} \u2014 ${l}${c}`}async function yt({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let s=`**${En({scriptName:e,mode:t,status:n,error:r,duration:i})}**
243
243
 
244
244
  ${o.join(`
245
- `)}`;try{await mt.addMessage(l,r)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var yn=gn(import.meta.url),wn=se.dirname(se.dirname(yn)),Le=process.env.DATA_DIR?se.resolve(process.env.DATA_DIR,"collected-profiles"):se.join(wn,"collected-profiles"),Pe=se.join(Le,"run-log.json");function Sn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let s=0;s<3;s++)try{J.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function gt(){try{if(!J.existsSync(Pe))return{runs:[]};let e=JSON.parse(J.readFileSync(Pe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function yt(e){J.existsSync(Le)||J.mkdirSync(Le,{recursive:!0});try{Sn(Pe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function wt(e,t="default"){let n=gt();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),yt(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function qe(e,t,n=null,o=null){if(!e)return;let s=null;try{let l=gt(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,s=c.duration;else{let r=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());r&&(r.status=t,r.result=t,r.duration=Date.now()-e.startTime,r.stats=n,r.error=o,s=r.duration)}yt(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";ht({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}_e();_e();import{getPluginConfig as bn}from"@ilivemylife/graph-sdk";var vn=await bn();for(let[e,t]of Object.entries(vn))process.env[e]===void 0&&(process.env[e]=t);var fr=process.env.LINKEDIN_NAME,ae=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),pr=Object.freeze(new Set([ae.DRAFT,ae.CONFIRMED,ae.NEEDS_REVIEW])),mr=Object.freeze(new Set([ae.DRAFT,ae.CONFIRMED,ae.REJECTED,ae.NEEDS_REVIEW]));import"dotenv/config";import*as O from"fs";import*as F from"path";import{fileURLToPath as kn}from"url";var $n=kn(import.meta.url),Cn=F.dirname(F.dirname($n)),Z=process.env.DATA_DIR?F.resolve(process.env.DATA_DIR,"collected-profiles"):F.join(Cn,"collected-profiles"),Ue=F.join(Z,"people.json"),Sr=F.join(Z,"jobs.json"),kt=F.join(Z,"quota.json"),br=F.join(Z,"conversations.json"),vr=F.join(Z,"sync-state.json"),kr=F.join(Z,"application-questions.json"),Be=F.join(Z,"profile-history"),$t=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Se=$t(process.env.CONNECT_MAX_DAILY,20),be=$t(process.env.CONNECT_MAX_WEEKLY,100),pe=null,xn=null,X=null,An=null,En=null,In=null;function Ct(){pe=null,xn=null,X=null,An=null,En=null,In=null}function Te(){O.existsSync(Z)||O.mkdirSync(Z,{recursive:!0})}function Je(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let s=0;s<3;s++)try{O.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Ve(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${F.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let s=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function ve(){return new Date().toISOString().split("T")[0]}var Dn=["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"],_n=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function St(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Re(e,t,n=null){if(!t||e[t])return t;let o=ce(t);if(!o)return t;let s=null;for(let[i,l]of Object.entries(e)){if(ce(l.profileUrl||i)===o)return i;!s&&Array.isArray(l.aliases)&&l.aliases.includes(o)&&(s=i)}if(s){let i=St(n),l=St(e[s].name);if(i&&l&&i===l)return s}return t}function Rn(){O.existsSync(Be)||O.mkdirSync(Be,{recursive:!0})}function xt(e){let t=ce(e);return t?F.join(Be,`${t}.json`):null}function On(e){let t=xt(e);return t?Ve(t,`profile-history/${ce(e)}.json`)||[]:[]}function Tn(e,t){let n=xt(e);if(!n)return;Rn();let o=On(e);o.unshift(t);try{Je(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${ce(e)}: ${s.message}`)}}function bt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function vt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function jn(e,t){if(!e)return[];let n=[];for(let o of _n){let s=e[o],i=t[o];bt(s)||bt(i)||vt(s)!==vt(i)&&n.push(o)}return n}function Nn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function ee(){return pe||(Te(),pe=Ve(Ue,"people.json")||{},pe)}function je(e){Te(),pe=e;try{Je(Ue,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${F.resolve(Ue)}`)}}function Oe(e,t={}){if(!e)return null;let n=ee(),o=ve(),s=new Date().toISOString(),i=Re(n,e,t.name),l=n[i];if(l){let c=jn(l,t);c.length>0&&(Tn(i,{capturedAt:s,previousLastUpdated:l.lastUpdated||null,changedFields:c,snapshot:Nn(l)}),l.lastSnapshotAt=s),l.seenCount=(l.seenCount||1)+1,l.lastSeen=o,l.lastUpdated=s,t.source&&!l.sources?.includes(t.source)&&(l.sources=l.sources||[],l.sources.push(t.source));for(let r of Dn)if(t[r]!=null){if(Array.isArray(t[r])&&t[r].length===0&&Array.isArray(l[r])&&l[r].length>0)continue;l[r]=t[r]}Array.isArray(t.availableSections)&&(l.lastFullVisitAt=s)}else n[i]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return je(n),n[i]}function At(e,t){if(!e||!t)return;let n=ee(),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(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),je(n))}function Et(e){return e&&ee()[e]?.connectionStatus||null}function It(e,t,n={}){if(!e)return;if(n.profileInfo)Oe(e,n.profileInfo);else{let c=ee(),r=Re(c,e,n.profileInfo?.name);c[r]||Oe(e,{})}let o=ee(),s=Re(o,e,n.profileInfo?.name),i=o[s];if(!i)return;let l=ve();i.connectionStatus=t,t==="connected"?i.connectionDate=l:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=l)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),je(o)}function Dt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=ce(t);if(!o)return;let s=ee(),i=Re(s,e),l=s[i];if(!l)return;let c=ce(l.profileUrl||i);o!==c&&(Array.isArray(l.aliases)||(l.aliases=[]),l.aliases.includes(o)||(l.aliases.push(o),l.lastUpdated=new Date().toISOString(),je(s)))}function _t(){return X||(Te(),X=Ve(kt,"quota.json"),(!X||!X.connections)&&(X={connections:[]}),X)}function Fn(e){Te(),X=e;try{Je(kt,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Rt(e,t="unknown"){let n=_t(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Fn(n)}function Ot(){let e=_t(),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=Ot(),t=ve(),n=e.filter(r=>r.date===t).length,o=e.length,s=n>=Se,i=o>=be,l=!s&&!i,c={allowed:l,daily:{sent:n,max:Se},weekly:{sent:o,max:be}};return l||(c.reason=s?`Daily limit reached (${n}/${Se})`:`Weekly limit reached (${o}/${be})`),c}function We(){let e=Ot(),t=ve(),n=e.filter(s=>s.date===t).length,o=e.length;return{daily:{sent:n,max:Se,remaining:Se-n},weekly:{sent:o,max:be,remaining:be-o}}}async function Ft(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Nt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Jn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:c=!1,extractCertifications:r=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await le(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await Ft(e,t));let a=0;for(let S=0;S<2;S++){let I=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(_=>window.scrollTo(0,_),I*T/6),await w(900);let N=await e.evaluate(()=>document.body.scrollHeight);if(N===a)break;a=N}await w(800);let d=null;try{let S=e.url();S&&/\/in\/[^/?#]/.test(S)&&(d=S.split("?")[0].replace(/\/+$/,""))}catch{}let p=await e.evaluate(()=>{let S=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),I=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"]),N=k=>{let C=(k||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(C)},T={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},_=document.querySelector("main");if(!_)return T;let $=[...Array.from(_.querySelectorAll("h1")),...Array.from(_.querySelectorAll("h2"))],M=Array.from(_.querySelectorAll("h2")),Q=$.find(k=>{let C=k.textContent&&k.textContent.trim(),A=(C||"").replace(/\s*\(\d+\)$/,"").trim();return C&&C.length>1&&C.length<100&&!S.has(A)&&!I.has(A)}),G=Q?Q.textContent.trim():null,L=Q?Q.parentElement:null;for(;L&&L!==_&&!Array.from(L.children).filter(C=>C.tagName==="P").some(C=>{let A=C.textContent&&C.textContent.trim();return A&&A.length>5&&!N(A)});)L=L.parentElement;let oe=null,me=null,he=null,ge=null;if(L&&L!==_){let k=Array.from(L.children).filter(A=>A.tagName==="P").filter(A=>{let re=A.textContent&&A.textContent.trim();return re&&re.length>5&&!N(re)});if(k[0]&&(oe=k[0].textContent.trim()),k[1]){let A=k[1].textContent.trim().split(/\s*[·•]\s*/);me=A[0]||null,A.length>1&&(he=A.slice(1).join(" \xB7 "))}let C=Array.from(L.children).filter(A=>A.tagName==="DIV");for(let A=C.length-1;A>=0;A--){let re=C[A].textContent&&C[A].textContent.trim();if(re&&!(G&&re.startsWith(G))&&(ge=re.split(/[·•]/)[0].trim(),ge))break}}let Ie=null;if(L){let k=L.querySelectorAll("p, span, div");for(let C of k){let A=(C.textContent||"").trim().replace(/^[·•]\s*/,"");if(A==="1st"||A==="2nd"||A==="3rd"){Ie=A;break}}}let D=!!_.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=j&&j.src||null,R=_.textContent||"",K=null,rt=R.match(/(\d+\+?)\s+connections\b/i);rt&&(K=rt[1]+" connections");let De=null,st=R.match(/(\d+)\s+mutual connection/i),it=R.match(/and\s+(\d+)\s+other mutual/i),rn=R.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);st?De=parseInt(st[1],10):it?De=2+parseInt(it[1],10):rn&&(De=2);let lt=null,at=null,ct=M.find(k=>k.textContent&&k.textContent.trim()==="About");if(ct){let k=ct.parentElement;for(;k&&k.tagName!=="SECTION";)k=k.parentElement;if(k){let C=(k.textContent||"").trim();C=C.replace(/^About\s*/,"").trim();let A=C.match(/Top skills\s*(.+?)$/i);if(A){let Me=A[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(cn=>cn.trim()).filter(Boolean);Me.length>0&&Me.length<10&&(at=Me)}C=C.split(/\n?…\s*more/i)[0].trim(),C=C.split(/\n?\.\.\.\s*more/i)[0].trim(),C=C.split(/\bTop skills\b/i)[0].trim(),C=C.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),lt=C||null}}let ut=null,dt=M.find(k=>k.textContent&&k.textContent.trim()==="Activity");if(dt){let k=dt.parentElement;for(;k&&k.tagName!=="SECTION";)k=k.parentElement;if(k){let C=(k.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);C&&(ut=parseInt(C[1].replace(/,/g,""),10))}}let sn=[...new Set(M.map(k=>(k.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(k=>k&&k.length>1&&k.length<60&&k!==G).filter(k=>S.has(k)))],ye=document.body.textContent||"",ln=/#OpenToWork\b/i.test(ye)||/\bOpen to work\b/.test(ye),an=/#Hiring\b/i.test(ye)||/\bI'?m hiring\b/i.test(ye)||/\bWe are hiring\b/i.test(ye);return{name:G,title:oe,location:ge,currentCompany:me,currentSchool:he,connectionDegree:Ie,hasVerifiedBadge:D,photoUrl:P,connectionsLevel:K,mutualConnectionsCount:De,followers:ut,openToWork:ln,hiring:an,about:lt,topSkills:at,availableSections:sn}});console.log(`Viewed: ${p.name} - ${p.title}`);let f=null,h=null,m=null,b=null,y=null,v=null;if(o||s||i||l||c||r){let S=await Promise.resolve().then(()=>(jt(),Tt));o&&(f=await S.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),s&&(h=await S.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),i&&(m=await S.extractEducationFromDetails(e,t),console.log(` + Education: ${m.length} entries`)),l&&(b=await S.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(y=await S.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),r&&(v=await S.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${v.length} entries`))}return{...p,profileUrl:t,resolvedUrl:d,...f!==null&&{experience:f},...h!==null&&{featured:h},...m!==null&&{education:m},...b!==null&&{skillsFull:b},...y!==null&&{recommendations:y},...v!==null&&{certifications:v}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function xe(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=u=>u&&!u.closest(n),s=u=>Array.from(document.querySelectorAll(u)).filter(o),i=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,r={pendingCount:i.length,pendingLabels:i.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return i.length>0?{status:"pending",debug:r}:l&&!c?{status:"connected",debug:r}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:r}:{status:"not_connected",debug:r}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ye(e){let t=null,n=await e.evaluate(()=>{let r=document.querySelector("h1")?.textContent?.trim();if(r&&!r.includes("notification"))return r;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(r=u.textContent?.trim(),r&&!r.includes("notification")))return r;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let r=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});r.count>0&&console.log(` S0: ${r.count} custom-invite links: ${JSON.stringify(r.labels)}`),t=await e.evaluateHandle(a=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=a.toLowerCase().split(" ")[0],f='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(f))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let r=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${r}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),f=document.querySelectorAll("button[aria-label]");return Array.from(f).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&p.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},r);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&f.test(m))return h}return null},r);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,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 r=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping primary button: wrong person (${r})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",i=null;for(let r of o){let u=await e.evaluate((a,d)=>{let p=a.className.includes("muted"),f=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:p,isStickyHeader:f,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},r,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=r;break}}for(let r of o)r!==i&&await r.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let r of c){let u=await e.evaluate(a=>{let d=a.getBoundingClientRect(),p=d.width>0&&d.height>0,f=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:f,top:d.top}},r);if(u.isVisible&&!u.isInStickyHeader){l=r,console.log(" Found More button by ID pattern (main)");break}}for(let r of c)r!==l&&await r.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let r=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(p=>{let f=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",m=p.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:f==="Follow"||f==="Message"||f==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let d=a.parentElement;for(let p=0;p<8&&d;p++){for(let f of d.querySelectorAll("button"))if(f.innerText?.trim()==="More"&&f!==a)return f;d=d.parentElement}return null});l=r?.asElement?.()||null,l||await r?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await w(500),await e.evaluate(a=>a.click(),l),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let a=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let p of d){let f=p.querySelector('a[href*="custom-invite"]');if(f)return f;for(let h of p.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=a?.asElement?.()||null,u||await a?.dispose?.().catch(()=>{})}if(!u){let a=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let f of d)for(let h of f.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&p.push(m)}return[...new Set(p)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(r){console.log(" More dropdown click failed:",r.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let r=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();r.includes("invite")&&!r.includes(u)&&(console.log(` Skipping generic button: wrong person (${r})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function Vn(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!l.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await w(3e3)):(await e.evaluate(a=>a.click(),t),await w(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let r=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(r?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Hn(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let n=await Ye(e);if(n){await e.evaluate(s=>s.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Wn(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:i=!1}=n;if(!s){let c=He();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let l=await Yn(e,t,n);return l.connectionSent&&!i&&Rt(t,o),l}async function Yn(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=n,r={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
- --- Connecting: ${u} ---`),c.length>0){let y=ee()[t]?.location;if(Nt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),r.reason="excluded_location",r.profileInfo={location:y},r}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await le(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await Ft(e,t),await w(2e3)),r.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),v=D=>{let j=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},S=document.querySelector("main");if(!S)return x;let I=[...Array.from(S.querySelectorAll("h1")),...Array.from(S.querySelectorAll("h2"))],N=Array.from(S.querySelectorAll("h2")),T=I.find(D=>{let j=D.textContent&&D.textContent.trim();return j&&j.length>1&&j.length<100&&!y.has(j)&&j!=="0 notifications"}),_=T?T.textContent.trim():null,$=T?T.parentElement:null;for(;$&&$!==S&&!Array.from($.children).filter(P=>P.tagName==="P").some(P=>{let R=P.textContent&&P.textContent.trim();return R&&R.length>5&&!v(R)});)$=$.parentElement;let M=null,Q=null,G=null;if($&&$!==S){let D=Array.from($.children),j=D.filter(R=>R.tagName==="P").filter(R=>{let K=R.textContent&&R.textContent.trim();return K&&K.length>5&&!v(K)});j[0]&&(M=j[0].textContent.trim()),j[1]&&(Q=j[1].textContent.trim());let P=D.filter(R=>R.tagName==="DIV");for(let R=P.length-1;R>=0;R--){let K=P[R].textContent&&P[R].textContent.trim();if(K&&!(_&&K.startsWith(_))&&(G=K.split(/[·•]/)[0].trim(),G))break}}let L=null;if($){let D=$.querySelectorAll("p, span, div");for(let j of D){let P=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){L=P;break}}}let oe=null,me=N.find(D=>D.textContent&&D.textContent.trim()==="About");if(me){let D=me.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(oe=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,oe&&(oe=oe.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let he=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ge=he&&he.src||null,Ie=!!S.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:_,title:M,location:G,about:oe,company:Q,connectionDegree:L,connectionsCount:null,mutualConnections:null,photoUrl:ge,hasVerifiedBadge:Ie}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(r.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=r.profileInfo?.location,v=ee()[t]?.location,x=y||v;if(Nt(x,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${x}`),r.reason="excluded_location",r;!y&&v==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await xe(e);if(r.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),r.reason="pending",r;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),r.reason="connected",r;await le(e);let p=await Ye(e);if(!p&&(await le(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),p=await Ye(e)),!p))return console.log(" \u2717 Connect not found"),r.reason="button_not_found",r;r.method=p.method;let f=await Vn(e,p.button);if(f==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),r.reason="wrong_target",r;if(f==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await xe(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await le(e),await w(1e3);let v=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(v)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),v),await w(500),await v.click().catch(()=>e.evaluate(S=>S.click(),v)),await w(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(N=>N.click(),x),await w(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),r.reason="premium_required",r;if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.method="more_dropdown",r.withCustomMessage=!1,r;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),r.reason="premium_required",r}catch(x){return console.log(" More dropdown failed:",x.message),await e.keyboard.press("Escape").catch(()=>{}),r.reason="premium_required",r}else return console.log(" \u2717 No More button found \u2014 Premium required"),r.reason="premium_required",r}if(await e.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),r.reason="email_required",r}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let v=document.querySelector("#interop-outlet")?.shadowRoot;if(!v)return{addNote:!1,sendWithout:!1};let x=v.querySelector('button[aria-label="Add a note"]'),S=v.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!S}});if(y.addNote){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=v?.asElement?.()||null,m||await v.dispose().catch(()=>{})}if(y.sendWithout){let v=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=v?.asElement?.()||null,b||await v.dispose().catch(()=>{})}}if(s){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let x=await Hn(e);return r.success=x,r.connectionSent=x,r.reason=x?"sent_without_note_upsell":"upsell_failed",r.withCustomMessage=!1,r}let v=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(v){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),S=o.replace("{name}",x);await v.type(S,{delay:20}),await w(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(N=>N.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_with_note",r.withCustomMessage=!0,r.messageSent=S,r}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(v=>v.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}}if(p.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await le(e),await w(500);let v=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let S of v){let I=await e.evaluate(N=>{let T=N.getBoundingClientRect();return{visible:T.width>0&&T.height>0,inSticky:!!N.closest('.sticky-header, [class*="sticky"]')}},S);if(I.visible&&!I.inSticky){x=S;break}}!x&&v.length>0&&(x=v[v.length-1]);for(let S of v)S!==x&&await S.dispose().catch(()=>{});if(x)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),x),await w(500),await x.click().catch(()=>e.evaluate(I=>I.click(),x)),await w(2e3);let S=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(S){console.log(" Found Connect in More dropdown, clicking..."),r.method="more_dropdown",await e.evaluate(_=>_.click(),S),await w(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await xe(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r):(r.reason="premium_required",r);if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r;let T=await e.$('button[aria-label="Send without a note"]');if(T){console.log(" Modal appeared via More dropdown, sending without note...");try{await T.evaluate(_=>_.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),r.success=!0,r.connectionSent=!0,r.reason="sent_without_note",r.withCustomMessage=!1,r}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(S){console.log(" More dropdown fallback failed:",S.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),r.reason="modal_failed",r}catch(u){console.error(` \u2717 Error: ${u.message}`),r.reason="error",r.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return r.fatal=!0,r;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{r.fatal=!0}return r}}async function Mt(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:r=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
- === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let f=We();console.log(`Quota: today ${f.daily.sent}/${f.daily.max} | week ${f.weekly.sent}/${f.weekly.max}`)}console.log("");let p=0;for(let f=0;f<t.length;f++){let h=t[f];try{if(e.isClosed()){console.log(`
245
+ `)}`;try{await gt.addMessage(l,s)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var In=An(import.meta.url),Dn=ie.dirname(ie.dirname(In)),qe=process.env.DATA_DIR?ie.resolve(process.env.DATA_DIR,"collected-profiles"):ie.join(Dn,"collected-profiles"),Ue=ie.join(qe,"run-log.json");function _n(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";J.writeFileSync(o,n);for(let r=0;r<3;r++)try{J.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function wt(){try{if(!J.existsSync(Ue))return{runs:[]};let e=JSON.parse(J.readFileSync(Ue,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function St(e){J.existsSync(qe)||J.mkdirSync(qe,{recursive:!0});try{_n(Ue,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function bt(e,t="default"){let n=wt();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>i),St(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Be(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=wt(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let s=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.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)}St(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";yt({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Oe();Oe();import{getPluginConfig as Rn}from"@ilivemylife/graph-sdk";var On=await Rn();for(let[e,t]of Object.entries(On))process.env[e]===void 0&&(process.env[e]=t);var $r=process.env.LINKEDIN_NAME,ue=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),xr=Object.freeze(new Set([ue.DRAFT,ue.CONFIRMED,ue.NEEDS_REVIEW])),Er=Object.freeze(new Set([ue.DRAFT,ue.CONFIRMED,ue.REJECTED,ue.NEEDS_REVIEW]));import"dotenv/config";import*as O from"fs";import*as F from"path";import{fileURLToPath as Tn}from"url";var jn=Tn(import.meta.url),Nn=F.dirname(F.dirname(jn)),ee=process.env.DATA_DIR?F.resolve(process.env.DATA_DIR,"collected-profiles"):F.join(Nn,"collected-profiles"),Je=F.join(ee,"people.json"),Rr=F.join(ee,"jobs.json"),$t=F.join(ee,"quota.json"),Or=F.join(ee,"conversations.json"),Tr=F.join(ee,"sync-state.json"),jr=F.join(ee,"application-questions.json"),Ve=F.join(ee,"profile-history"),xt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ke=xt(process.env.CONNECT_MAX_DAILY,20),ve=xt(process.env.CONNECT_MAX_WEEKLY,100),he=null,Fn=null,X=null,Ln=null,Mn=null,Pn=null;function Et(){he=null,Fn=null,X=null,Ln=null,Mn=null,Pn=null}function Ne(){O.existsSync(ee)||O.mkdirSync(ee,{recursive:!0})}function He(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function We(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${F.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let r=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.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{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ce(){return new Date().toISOString().split("T")[0]}var qn=["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"],Un=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function de(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function kt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Te(e,t,n=null){if(!t||e[t])return t;let o=de(t);if(!o)return t;let r=null;for(let[i,l]of Object.entries(e)){if(de(l.profileUrl||i)===o)return i;!r&&Array.isArray(l.aliases)&&l.aliases.includes(o)&&(r=i)}if(r){let i=kt(n),l=kt(e[r].name);if(i&&l&&i===l)return r}return t}function Bn(){O.existsSync(Ve)||O.mkdirSync(Ve,{recursive:!0})}function At(e){let t=de(e);return t?F.join(Ve,`${t}.json`):null}function Jn(e){let t=At(e);return t?We(t,`profile-history/${de(e)}.json`)||[]:[]}function Vn(e,t){let n=At(e);if(!n)return;Bn();let o=Jn(e);o.unshift(t);try{He(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${de(e)}: ${r.message}`)}}function vt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Ct(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function Hn(e,t){if(!e)return[];let n=[];for(let o of Un){let r=e[o],i=t[o];vt(r)||vt(i)||Ct(r)!==Ct(i)&&n.push(o)}return n}function Wn(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 te(){return he||(Ne(),he=We(Je,"people.json")||{},he)}function Fe(e){Ne(),he=e;try{He(Je,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${F.resolve(Je)}`)}}function je(e,t={}){if(!e)return null;let n=te(),o=Ce(),r=new Date().toISOString(),i=Te(n,e,t.name),l=n[i];if(l){let c=Hn(l,t);c.length>0&&(Vn(i,{capturedAt:r,previousLastUpdated:l.lastUpdated||null,changedFields:c,snapshot:Wn(l)}),l.lastSnapshotAt=r),l.seenCount=(l.seenCount||1)+1,l.lastSeen=o,l.lastUpdated=r,t.source&&!l.sources?.includes(t.source)&&(l.sources=l.sources||[],l.sources.push(t.source));for(let s of qn)if(t[s]!=null){if(Array.isArray(t[s])&&t[s].length===0&&Array.isArray(l[s])&&l[s].length>0)continue;l[s]=t[s]}Array.isArray(t.availableSections)&&(l.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 Fe(n),n[i]}function It(e,t){if(!e||!t)return;let n=te(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Ce(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Fe(n))}function Dt(e){return e&&te()[e]?.connectionStatus||null}function _t(e,t,n={}){if(!e)return;if(n.profileInfo)je(e,n.profileInfo);else{let c=te(),s=Te(c,e,n.profileInfo?.name);c[s]||je(e,{})}let o=te(),r=Te(o,e,n.profileInfo?.name),i=o[r];if(!i)return;let l=Ce();i.connectionStatus=t,t==="connected"?i.connectionDate=l:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(i.requestedConnectionAt||(i.requestedConnectionAt=l)),i.connectionMethod=n.method||i.connectionMethod,i.messageSent=n.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),Fe(o)}function Rt(e,t,n={}){if(n.dryRun||!e||!t)return;let o=de(t);if(!o)return;let r=te(),i=Te(r,e),l=r[i];if(!l)return;let c=de(l.profileUrl||i);o!==c&&(Array.isArray(l.aliases)||(l.aliases=[]),l.aliases.includes(o)||(l.aliases.push(o),l.lastUpdated=new Date().toISOString(),Fe(r)))}function Ot(){return X||(Ne(),X=We($t,"quota.json"),(!X||!X.connections)&&(X={connections:[]}),X)}function Yn(e){Ne(),X=e;try{He($t,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Tt(e,t="unknown"){let n=Ot(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Yn(n)}function jt(){let e=Ot(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ye(){let e=jt(),t=Ce(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=ke,i=o>=ve,l=!r&&!i,c={allowed:l,daily:{sent:n,max:ke},weekly:{sent:o,max:ve}};return l||(c.reason=r?`Daily limit reached (${n}/${ke})`:`Weekly limit reached (${o}/${ve})`),c}function Ge(){let e=jt(),t=Ce(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:ke,remaining:ke-n},weekly:{sent:o,max:ve,remaining:ve-o}}}async function Mt(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 w(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Lt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function eo(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:c=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await ce(e)&&(console.log(" Dismissed Premium overlay"),await w(1500),await Mt(e,t));let a=0;for(let S=0;S<2;S++){let I=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(_=>window.scrollTo(0,_),I*T/6),await w(900);let N=await e.evaluate(()=>document.body.scrollHeight);if(N===a)break;a=N}await w(800);let d=null;try{let S=e.url();S&&/\/in\/[^/?#]/.test(S)&&(d=S.split("?")[0].replace(/\/+$/,""))}catch{}let p=await e.evaluate(()=>{let S=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),I=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"]),N=v=>{let $=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test($)},T={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},_=document.querySelector("main");if(!_)return T;let C=[...Array.from(_.querySelectorAll("h1")),...Array.from(_.querySelectorAll("h2"))],L=Array.from(_.querySelectorAll("h2")),Z=C.find(v=>{let $=v.textContent&&v.textContent.trim(),E=($||"").replace(/\s*\(\d+\)$/,"").trim();return $&&$.length>1&&$.length<100&&!S.has(E)&&!I.has(E)}),G=Z?Z.textContent.trim():null,M=Z?Z.parentElement:null;for(;M&&M!==_&&!Array.from(M.children).filter($=>$.tagName==="P").some($=>{let E=$.textContent&&$.textContent.trim();return E&&E.length>5&&!N(E)});)M=M.parentElement;let re=null,ge=null,ye=null,we=null;if(M&&M!==_){let v=Array.from(M.children).filter(E=>E.tagName==="P").filter(E=>{let se=E.textContent&&E.textContent.trim();return se&&se.length>5&&!N(se)});if(v[0]&&(re=v[0].textContent.trim()),v[1]){let E=v[1].textContent.trim().split(/\s*[·•]\s*/);ge=E[0]||null,E.length>1&&(ye=E.slice(1).join(" \xB7 "))}let $=Array.from(M.children).filter(E=>E.tagName==="DIV");for(let E=$.length-1;E>=0;E--){let se=$[E].textContent&&$[E].textContent.trim();if(se&&!(G&&se.startsWith(G))&&(we=se.split(/[·•]/)[0].trim(),we))break}}let _e=null;if(M){let v=M.querySelectorAll("p, span, div");for(let $ of v){let E=($.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){_e=E;break}}}let D=!!_.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),P=j&&j.src||null,R=_.textContent||"",K=null,it=R.match(/(\d+\+?)\s+connections\b/i);it&&(K=it[1]+" connections");let Re=null,lt=R.match(/(\d+)\s+mutual connection/i),at=R.match(/and\s+(\d+)\s+other mutual/i),gn=R.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);lt?Re=parseInt(lt[1],10):at?Re=2+parseInt(at[1],10):gn&&(Re=2);let ct=null,ut=null,dt=L.find(v=>v.textContent&&v.textContent.trim()==="About");if(dt){let v=dt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let $=(v.textContent||"").trim();$=$.replace(/^About\s*/,"").trim();let E=$.match(/Top skills\s*(.+?)$/i);if(E){let Pe=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(bn=>bn.trim()).filter(Boolean);Pe.length>0&&Pe.length<10&&(ut=Pe)}$=$.split(/\n?…\s*more/i)[0].trim(),$=$.split(/\n?\.\.\.\s*more/i)[0].trim(),$=$.split(/\bTop skills\b/i)[0].trim(),$=$.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),ct=$||null}}let ft=null,pt=L.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(pt){let v=pt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let $=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);$&&(ft=parseInt($[1].replace(/,/g,""),10))}}let yn=[...new Set(L.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==G).filter(v=>S.has(v)))],Se=document.body.textContent||"",wn=/#OpenToWork\b/i.test(Se)||/\bOpen to work\b/.test(Se),Sn=/#Hiring\b/i.test(Se)||/\bI'?m hiring\b/i.test(Se)||/\bWe are hiring\b/i.test(Se);return{name:G,title:re,location:we,currentCompany:ge,currentSchool:ye,connectionDegree:_e,hasVerifiedBadge:D,photoUrl:P,connectionsLevel:K,mutualConnectionsCount:Re,followers:ft,openToWork:wn,hiring:Sn,about:ct,topSkills:ut,availableSections:yn}});console.log(`Viewed: ${p.name} - ${p.title}`);let f=null,h=null,m=null,b=null,y=null,k=null;if(o||r||i||l||c||s){let S=await Promise.resolve().then(()=>(Ft(),Nt));o&&(f=await S.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),r&&(h=await S.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${h.length} entries`)),i&&(m=await S.extractEducationFromDetails(e,t),console.log(` + Education: ${m.length} entries`)),l&&(b=await S.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),c&&(y=await S.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${y.length} entries`)),s&&(k=await S.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${k.length} entries`))}return{...p,profileUrl:t,resolvedUrl:d,...f!==null&&{experience:f},...h!==null&&{featured:h},...m!==null&&{education:m},...b!==null&&{skillsFull:b},...y!==null&&{recommendations:y},...k!==null&&{certifications:k}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function Ae(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=u=>u&&!u.closest(n),r=u=>Array.from(document.querySelectorAll(u)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return i.length>0?{status:"pending",debug:s}:l&&!c?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Ke(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(s=u.textContent?.trim(),s&&!s.includes("notification")))return s;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let d=document.title;return d&&d.includes("|")?d.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let s=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(d=>d.getAttribute("aria-label")?.slice(0,50))}});s.count>0&&console.log(` S0: ${s.count} custom-invite links: ${JSON.stringify(s.labels)}`),t=await e.evaluateHandle(a=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=a.toLowerCase().split(" ")[0],f='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(f))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),f=document.querySelectorAll("button[aria-label]");return Array.from(f).filter(m=>{let b=m.getAttribute("aria-label")||"";return(b.toLowerCase().includes("invite")||b.toLowerCase().includes("connect"))&&p.test(b)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&f.test(m))return h}return null},s);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let s=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(u)&&(console.log(` Skipping primary button: wrong person (${s})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let r=n?n.split(" ")[0].toLowerCase():"",i=null;for(let s of o){let u=await e.evaluate((a,d)=>{let p=a.className.includes("muted"),f=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),b=m.includes("invite"),y=d?m.includes(d):!0;return{isMuted:p,isStickyHeader:f,inRecommendations:h,hasInvite:b,matchesName:y,ariaLabel:m}},s,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}i=s;break}}for(let s of o)s!==i&&await s.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let s of c){let u=await e.evaluate(a=>{let d=a.getBoundingClientRect(),p=d.width>0&&d.height>0,f=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:f,top:d.top}},s);if(u.isVisible&&!u.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of c)s!==l&&await s.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let s=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(p=>{let f=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",m=p.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:f==="Follow"||f==="Message"||f==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let d=a.parentElement;for(let p=0;p<8&&d;p++){for(let f of d.querySelectorAll("button"))if(f.innerText?.trim()==="More"&&f!==a)return f;d=d.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await w(500),await e.evaluate(a=>a.click(),l),await w(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let a=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let p of d){let f=p.querySelector('a[href*="custom-invite"]');if(f)return f;for(let h of p.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=a?.asElement?.()||null,u||await a?.dispose?.().catch(()=>{})}if(!u){let a=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let f of d)for(let h of f.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&p.push(m)}return[...new Set(p)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(s){console.log(" More dropdown click failed:",s.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let s=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(u)&&(console.log(` Skipping generic button: wrong person (${s})`),t=null)}return t||(t=await e.$('button[aria-label="Connect"]')),t?(console.log(" Found: generic button"),{button:t,method:"generic_button"}):null}async function to(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await w(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!l.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await w(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await w(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await w(3e3)):(await e.evaluate(a=>a.click(),t),await w(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function no(e){console.log(" Upsell: Premium required for notes");let t=await e.$('button[aria-label="Dismiss"]')||await e.$("button.artdeco-modal__dismiss");t?await t.click():await e.keyboard.press("Escape"),await w(1500);let n=await Ke(e);if(n){await e.evaluate(r=>r.click(),n),await w(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(r=>r.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function oo(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=Ye();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let l=await ro(e,t,n);return l.connectionSent&&!i&&Tt(t,o),l}async function ro(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
+ --- Connecting: ${u} ---`),c.length>0){let y=te()[t]?.location;if(Lt(y,c))return console.log(` \u26A0 Excluded location (stored): ${y}`),s.reason="excluded_location",s.profileInfo={location:y},s}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(5e3),await ce(e)&&(console.log(" Dismissed Premium overlay"),await w(2e3),await Mt(e,t),await w(2e3)),s.profileInfo=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),k=D=>{let j=(D||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(j)},x={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},S=document.querySelector("main");if(!S)return x;let I=[...Array.from(S.querySelectorAll("h1")),...Array.from(S.querySelectorAll("h2"))],N=Array.from(S.querySelectorAll("h2")),T=I.find(D=>{let j=D.textContent&&D.textContent.trim();return j&&j.length>1&&j.length<100&&!y.has(j)&&j!=="0 notifications"}),_=T?T.textContent.trim():null,C=T?T.parentElement:null;for(;C&&C!==S&&!Array.from(C.children).filter(P=>P.tagName==="P").some(P=>{let R=P.textContent&&P.textContent.trim();return R&&R.length>5&&!k(R)});)C=C.parentElement;let L=null,Z=null,G=null;if(C&&C!==S){let D=Array.from(C.children),j=D.filter(R=>R.tagName==="P").filter(R=>{let K=R.textContent&&R.textContent.trim();return K&&K.length>5&&!k(K)});j[0]&&(L=j[0].textContent.trim()),j[1]&&(Z=j[1].textContent.trim());let P=D.filter(R=>R.tagName==="DIV");for(let R=P.length-1;R>=0;R--){let K=P[R].textContent&&P[R].textContent.trim();if(K&&!(_&&K.startsWith(_))&&(G=K.split(/[·•]/)[0].trim(),G))break}}let M=null;if(C){let D=C.querySelectorAll("p, span, div");for(let j of D){let P=(j.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){M=P;break}}}let re=null,ge=N.find(D=>D.textContent&&D.textContent.trim()==="About");if(ge){let D=ge.parentElement;for(;D&&D.tagName!=="SECTION";)D=D.parentElement;D&&(re=(D.textContent||"").trim().replace(/^About\s*/,"").trim()||null,re&&(re=re.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let ye=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),we=ye&&ye.src||null,_e=!!S.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:_,title:L,location:G,about:re,company:Z,connectionDegree:M,connectionsCount:null,mutualConnections:null,photoUrl:we,hasVerifiedBadge:_e}});try{let y=e.url();y&&/\/in\/[^/?#]/.test(y)&&(s.resolvedUrl=y.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let y=s.profileInfo?.location,k=te()[t]?.location,x=y||k;if(Lt(x,c))return console.log(` \u26A0 Excluded location (${y?"live":"stored"}): ${x}`),s.reason="excluded_location",s;!y&&k==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await Ae(e);if(s.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await ce(e);let p=await Ke(e);if(!p&&(await ce(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await w(2e3),p=await Ke(e)),!p))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=p.method;let f=await to(e,p.button);if(f==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(f==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3);let y=await Ae(e);if(y==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s;console.log(` Status after upsell: ${y} \u2014 trying More dropdown...`),await ce(e),await w(1e3);let k=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(k)try{await e.evaluate(S=>S.scrollIntoView({behavior:"smooth",block:"center"}),k),await w(500),await k.click().catch(()=>e.evaluate(S=>S.click(),k)),await w(2e3);let x=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(x){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(N=>N.click(),x),await w(3e3);let S=e.url();if(S.includes("/premium/")||S.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),s.reason="premium_required",s;if(await Ae(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.method="more_dropdown",s.withCustomMessage=!1,s;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await w(500),s.reason="premium_required",s}catch(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.$('input[name="email"][type="email"]')){console.log(" \u26A0 Email verification required - skipping");let y=await e.$('button[aria-label="Dismiss"]');return y&&await y.click(),await w(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),b=await e.$('button[aria-label="Send without a note"]');if(!m&&!b){let y=await e.evaluate(()=>{let k=document.querySelector("#interop-outlet")?.shadowRoot;if(!k)return{addNote:!1,sendWithout:!1};let x=k.querySelector('button[aria-label="Add a note"]'),S=k.querySelector('button[aria-label="Send without a note"]');return{addNote:!!x,sendWithout:!!S}});if(y.addNote){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=k?.asElement?.()||null,m||await k.dispose().catch(()=>{})}if(y.sendWithout){let k=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));b=k?.asElement?.()||null,b||await k.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await w(1500),await e.$("div.modal-upsell")){let x=await no(e);return s.success=x,s.connectionSent=x,s.reason=x?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let k=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(k){let x=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),S=o.replace("{name}",x);await k.type(S,{delay:20}),await w(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(N=>N.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (with note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_with_note",s.withCustomMessage=!0,s.messageSent=S,s}}}else if(b){console.log(" Sending without note...");try{await b.evaluate(y=>y.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}else if(m&&!o){console.log(" No message provided, sending without note...");let y=await e.$('button[aria-label="Send without a note"]');if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}}else{console.log(" Sending without note (custom messages disabled)...");let y=b;if(y){try{await y.evaluate(k=>k.click())}catch{console.log(" Click timeout, likely still sent")}return await w(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(p.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(4e3)),await ce(e),await w(500);let k=await e.$$('button[id*="profile-overflow-action"]'),x=null;for(let S of k){let I=await e.evaluate(N=>{let T=N.getBoundingClientRect();return{visible:T.width>0&&T.height>0,inSticky:!!N.closest('.sticky-header, [class*="sticky"]')}},S);if(I.visible&&!I.inSticky){x=S;break}}!x&&k.length>0&&(x=k[k.length-1]);for(let S of k)S!==x&&await S.dispose().catch(()=>{});if(x)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),x),await w(500),await x.click().catch(()=>e.evaluate(I=>I.click(),x)),await w(2e3);let S=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(S){console.log(" Found Connect in More dropdown, clicking..."),s.method="more_dropdown",await e.evaluate(_=>_.click(),S),await w(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await Ae(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 Ae(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 T=await e.$('button[aria-label="Send without a note"]');if(T){console.log(" Modal appeared via More dropdown, sending without note...");try{await T.evaluate(_=>_.click())}catch{}return await w(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(S){console.log(" More dropdown fallback failed:",S.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),s.reason="modal_failed",s}catch(u){console.error(` \u2717 Error: ${u.message}`),s.reason="error",s.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{s.fatal=!0}return s}}async function Pt(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:s=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
+ === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let f=Ge();console.log(`Quota: today ${f.daily.sent}/${f.daily.max} | week ${f.weekly.sent}/${f.weekly.max}`)}console.log("");let p=0;for(let f=0;f<t.length;f++){let h=t[f];try{if(e.isClosed()){console.log(`
248
248
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
249
- \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${f+1}/${t.length}] Skipping - no URL`);continue}let m=Et(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,r&&await r(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(l){let y=await Jn(e,h.profileUrl);y?(Oe(h.profileUrl,{...y,source:a}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=He();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Wn(e,h.profileUrl,{message:o,useCustomMessage:s,excludeLocations:u,source:a,skipQuotaGate:!0}),b.success)d.connectionsSent++;else switch(b.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(b?.fatal){console.log(`
249
+ \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${f+1}/${t.length}] Skipping - no URL`);continue}let m=Dt(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl}`);let b=null;if(l){let y=await eo(e,h.profileUrl);y?(je(h.profileUrl,{...y,source:a}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=Ye();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await oo(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:u,source:a,skipQuotaGate:!0}),b.success)d.connectionsSent++;else switch(b.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(b?.fatal){console.log(`
250
250
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(b?.reason==="error"){if(p++,p>=3){console.log(`
251
- \u26A0 ${p} consecutive errors \u2014 aborting funnel`);break}}else p=0;if(b&&b.reason&&(It(h.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&Dt(h.profileUrl,b.resolvedUrl),At(h.profileUrl,{source:a||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:b.reason})),r&&await r(h,d,b),f<t.length-1){let y=c+Math.random()*2e3;await w(y)}}if(console.log(`
252
- === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let f=We();console.log(` Connection quota left: today ${f.daily.remaining} of ${f.daily.max} | week ${f.weekly.remaining} of ${f.weekly.max}`)}return d}import"dotenv/config";import*as q from"fs";import*as te from"path";import{fileURLToPath as Gn}from"url";var Kn=Gn(import.meta.url),zn=te.dirname(te.dirname(Kn)),Ae=process.env.DATA_DIR?te.resolve(process.env.DATA_DIR,"collected-profiles"):te.join(zn,"collected-profiles");function Ge(){q.existsSync(Ae)||q.mkdirSync(Ae,{recursive:!0})}function Qn(){return new Date().toISOString().split("T")[0]}function Lt(e,t=null){let n=t||Qn();return te.join(Ae,`${e}-${n}.json`)}function Pt(e,t=null){Ge();let n=Lt(e,t);try{if(q.existsSync(n)){let o=q.readFileSync(n,"utf-8"),s=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${s.profiles.length} profiles from ${n}`),s.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function qt(e,t=null){return Pt(e,t).filter(o=>!o.processed)}function Ut(e,t,n,o=null){Ge();let s=Lt(e,o);try{if(!q.existsSync(s))return;let i=JSON.parse(q.readFileSync(s,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),q.writeFileSync(s,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Bt(e){let t=Pt(e),n=t.filter(s=>s.processed),o=t.filter(s=>!s.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((s,i)=>(s[i.status]=(s[i.status]||0)+1,s),{})}}function Jt(){Ge();try{return q.readdirSync(Ae).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let s=JSON.parse(q.readFileSync(te.join(Ae,t),"utf-8"));return{file:t,source:n,date:o,count:s.profiles?.length||0,unprocessed:s.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as g from"fs";import*as nt from"os";import*as E from"path";import{fileURLToPath as _o}from"url";var Qe={};we(Qe,{NAME:()=>Zn,VERSION:()=>Xn,up:()=>no});import*as V from"fs";import*as Ne from"path";var Xn=1,Zn="normalize-jobs-and-questions",eo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],to=50;function Ke(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function ze(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(s){try{V.unlinkSync(o)}catch{}throw s}try{V.renameSync(o,e)}catch(s){try{V.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function no(e,t){let n=Ne.join(e,"jobs.json"),o=Ne.join(t,"scouted-jobs.json"),s=Ne.join(e,"application-questions.json"),i=Ke(n)||{},l=Ke(o)||{},c=0,r=[];for(let a of Object.keys(i)){if(!l[a])continue;let d=l[a],p=i[a];for(let f of eo)d[f]!=null&&p[f]==null&&(p[f]=d[f]);r.push(a),c++}c>0?(ze(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ke(s);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let p of u.applications){let f=p.jobId||"unknown";a[f]||(a[f]={applications:[]});let h=(p.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=to?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});a[f].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||h.length,questions:h})}ze(s,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(r.length>0){for(let a of r)delete l[a];ze(o,l),console.log(` Phase 3: Removed ${r.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Xe={};we(Xe,{NAME:()=>ro,VERSION:()=>oo,up:()=>lo});import*as H from"fs";import*as Vt from"path";var oo=2,ro="reset-unread-flags";function so(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function io(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(s){try{H.unlinkSync(o)}catch{}throw s}try{H.renameSync(o,e)}catch(s){try{H.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function lo(e){let t=Vt.join(e,"conversations.json"),n=so(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}io(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ze={};we(Ze,{NAME:()=>co,VERSION:()=>ao,up:()=>ho});import*as W from"fs";import*as Ht from"path";var ao=3,co="recompute-last-message-by",uo=new Set(["draft","confirmed","rejected","needs_review"]);function fo(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function po(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(s){try{W.unlinkSync(o)}catch{}throw s}try{W.renameSync(o,e)}catch(s){try{W.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function mo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!uo.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,l)=>l.t-i.t).map(i=>i.m),s=o.length>0?o:[...n].reverse();for(let i of s){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function ho(e){let t=Ht.join(e,"conversations.json"),n=fo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,l=0;for(let c of Object.keys(n)){let r=n[c];if(!r||typeof r!="object")continue;Object.prototype.hasOwnProperty.call(r,"_cardSynced")&&(delete r._cardSynced,i++);let u=Array.isArray(r.messages)?r.messages:[],a=mo(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";r.lastMessageBy!==a&&l++,r.lastMessageBy=a,r.conversationStatus=d,s++}if(s===0){console.log(" No conversations to recompute.");return}po(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var et={};we(et,{NAME:()=>yo,VERSION:()=>go,up:()=>vo});import*as Y from"fs";import*as Wt from"path";var go=4,yo="split-connection-timestamps",wo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function So(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function bo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(s){try{Y.unlinkSync(o)}catch{}throw s}try{Y.renameSync(o,e)}catch(s){try{Y.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function vo(e){let t=Wt.join(e,"people.json"),n=So(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let i of Object.keys(n)){let l=n[i];!l||typeof l!="object"||(s++,wo.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}bo(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as B from"path";import{fileURLToPath as ko}from"url";var $o=ko(import.meta.url),Co=B.dirname(B.dirname($o)),Ee=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join(Co,"market-research"),Tr=B.join(Ee,"scouted-jobs.json"),jr=B.join(Ee,"discovered-people.json"),Nr=B.join(Ee,"visit-log.json"),Fr=B.join(Ee,"companies.json"),Mr=B.join(Ee,"job-decisions.json");function Yt(){xo=null,Ao=null,Eo=null,Io=null,Do=null}var xo=null;var Ao=null;var Eo=null;var Io=null;var Do=null;var Ro=_o(import.meta.url),Oo=E.dirname(Ro),To=E.dirname(E.dirname(Oo));function jo(e){return e&&(e==="~"?nt.homedir():e.startsWith("~/")||e.startsWith("~\\")?E.join(nt.homedir(),e.slice(2)):e)}var z=process.env.DATA_DIR?E.resolve(jo(process.env.DATA_DIR)):To,de=E.join(z,"collected-profiles"),fe=E.join(z,"market-research"),U=E.join(z,".schema-version"),Gt=[E.join(de,".schema-version"),E.join(fe,".schema-version")],ie=4,ne=[{version:1,module:Qe},{version:2,module:Xe},{version:3,module:Ze},{version:4,module:et}];(function(){ne.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of ne){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=ne.length?ne[ne.length-1].version:0;if(n!==ie)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${ie}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ne.length;o++){let s=o+1;if(ne[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${ne[o].version}`)}})();function Xt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
251
+ \u26A0 ${p} consecutive errors \u2014 aborting funnel`);break}}else p=0;if(b&&b.reason&&(_t(h.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&Rt(h.profileUrl,b.resolvedUrl),It(h.profileUrl,{source:a||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:b.reason})),s&&await s(h,d,b),f<t.length-1){let y=c+Math.random()*2e3;await w(y)}}if(console.log(`
252
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let f=Ge();console.log(` Connection quota left: today ${f.daily.remaining} of ${f.daily.max} | week ${f.weekly.remaining} of ${f.weekly.max}`)}return d}import"dotenv/config";import*as q from"fs";import*as ne from"path";import{fileURLToPath as so}from"url";var io=so(import.meta.url),lo=ne.dirname(ne.dirname(io)),Ie=process.env.DATA_DIR?ne.resolve(process.env.DATA_DIR,"collected-profiles"):ne.join(lo,"collected-profiles");function ze(){q.existsSync(Ie)||q.mkdirSync(Ie,{recursive:!0})}function ao(){return new Date().toISOString().split("T")[0]}function qt(e,t=null){let n=t||ao();return ne.join(Ie,`${e}-${n}.json`)}function Ut(e,t=null){ze();let n=qt(e,t);try{if(q.existsSync(n)){let o=q.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function Bt(e,t=null){return Ut(e,t).filter(o=>!o.processed)}function Jt(e,t,n,o=null){ze();let r=qt(e,o);try{if(!q.existsSync(r))return;let i=JSON.parse(q.readFileSync(r,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),q.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Vt(e){let t=Ut(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function Ht(){ze();try{return q.readdirSync(Ie).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(q.readFileSync(ne.join(Ie,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as g from"fs";import*as rt from"os";import*as A from"path";import{fileURLToPath as Uo}from"url";var Xe={};be(Xe,{NAME:()=>uo,VERSION:()=>co,up:()=>mo});import*as V from"fs";import*as Le from"path";var co=1,uo="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 Qe(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Ze(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(r){try{V.unlinkSync(o)}catch{}throw r}try{V.renameSync(o,e)}catch(r){try{V.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 mo(e,t){let n=Le.join(e,"jobs.json"),o=Le.join(t,"scouted-jobs.json"),r=Le.join(e,"application-questions.json"),i=Qe(n)||{},l=Qe(o)||{},c=0,s=[];for(let a of Object.keys(i)){if(!l[a])continue;let d=l[a],p=i[a];for(let f of fo)d[f]!=null&&p[f]==null&&(p[f]=d[f]);s.push(a),c++}c>0?(Ze(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Qe(r);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let p of u.applications){let f=p.jobId||"unknown";a[f]||(a[f]={applications:[]});let h=(p.questions||[]).map(m=>{let b={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=po?b.options=m.options:(b.optionsOmitted=!0,d++)),m.page&&(b.page=m.page),m.wasPreFilled&&(b.wasPreFilled=!0),m.wasRetry&&(b.wasRetry=!0),b});a[f].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||h.length,questions:h})}Ze(r,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let a of s)delete l[a];Ze(o,l),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var et={};be(et,{NAME:()=>go,VERSION:()=>ho,up:()=>So});import*as H from"fs";import*as Wt from"path";var ho=2,go="reset-unread-flags";function yo(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function wo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function So(e){let t=Wt.join(e,"conversations.json"),n=yo(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}wo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var tt={};be(tt,{NAME:()=>ko,VERSION:()=>bo,up:()=>Eo});import*as W from"fs";import*as Yt from"path";var bo=3,ko="recompute-last-message-by",vo=new Set(["draft","confirmed","rejected","needs_review"]);function Co(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function $o(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.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 xo(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!vo.has(i.status));if(n.length===0)return"them";let o=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,l)=>l.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function Eo(e){let t=Yt.join(e,"conversations.json"),n=Co(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,l=0;for(let c of Object.keys(n)){let s=n[c];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let u=Array.isArray(s.messages)?s.messages:[],a=xo(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==a&&l++,s.lastMessageBy=a,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}$o(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var nt={};be(nt,{NAME:()=>Io,VERSION:()=>Ao,up:()=>Oo});import*as Y from"fs";import*as Gt from"path";var Ao=4,Io="split-connection-timestamps",Do=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function _o(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Ro(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{Y.writeFileSync(o,n)}catch(r){try{Y.unlinkSync(o)}catch{}throw r}try{Y.renameSync(o,e)}catch(r){try{Y.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 Oo(e){let t=Gt.join(e,"people.json"),n=_o(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let l=n[i];!l||typeof l!="object"||(r++,Do.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ro(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as B from"path";import{fileURLToPath as To}from"url";var jo=To(import.meta.url),No=B.dirname(B.dirname(jo)),De=process.env.DATA_DIR?B.resolve(process.env.DATA_DIR,"market-research"):B.join(No,"market-research"),Hr=B.join(De,"scouted-jobs.json"),Wr=B.join(De,"discovered-people.json"),Yr=B.join(De,"visit-log.json"),Gr=B.join(De,"companies.json"),Kr=B.join(De,"job-decisions.json");function Kt(){Fo=null,Lo=null,Mo=null,Po=null,qo=null}var Fo=null;var Lo=null;var Mo=null;var Po=null;var qo=null;var Bo=Uo(import.meta.url),Jo=A.dirname(Bo),Vo=A.dirname(A.dirname(Jo));function Ho(e){return e&&(e==="~"?rt.homedir():e.startsWith("~/")||e.startsWith("~\\")?A.join(rt.homedir(),e.slice(2)):e)}var z=process.env.DATA_DIR?A.resolve(Ho(process.env.DATA_DIR)):Vo,pe=A.join(z,"collected-profiles"),me=A.join(z,"market-research"),U=A.join(z,".schema-version"),zt=[A.join(pe,".schema-version"),A.join(me,".schema-version")],le=4,oe=[{version:1,module:Xe},{version:2,module:et},{version:3,module:tt},{version:4,module:nt}];(function(){oe.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of oe){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=oe.length?oe[oe.length-1].version:0;if(n!==le)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${le}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<oe.length;o++){let r=o+1;if(oe[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${oe[o].version}`)}})();function en(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
253
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
254
  `),process.exit(1));try{g.mkdirSync(z,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
255
  [FATAL] Cannot create DATA_DIR (${z}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -257,52 +257,50 @@ ${o.join(`
257
257
  [FATAL] DATA_DIR (${z}) is not accessible: ${t.message}
258
258
  `),process.exit(1)}e.isDirectory()||(console.error(`
259
259
  [FATAL] DATA_DIR (${z}) 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.
260
- `),process.exit(1));for(let t of[de,fe]){let n;try{n=g.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
260
+ `),process.exit(1));for(let t of[pe,me]){let n;try{n=g.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
261
261
  [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.
262
- `),process.exit(1))}}var ue=E.join(z,".migration-lock");function No(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return g.writeFileSync(ue,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(g.readFileSync(ue,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}o&&i<s&&(console.error(`
263
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ue}
262
+ `),process.exit(1))}}var fe=A.join(z,".migration-lock");function Wo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return g.writeFileSync(fe,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(g.readFileSync(fe,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}o&&i<r&&(console.error(`
263
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${fe}
264
264
  `),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.
265
- `),process.exit(1)),o&&i>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=ue+".tmp";try{return g.writeFileSync(n,e),g.renameSync(n,ue),!0}catch(o){try{g.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function ot(){try{if(JSON.parse(g.readFileSync(ue,"utf-8")).pid!==process.pid)return;g.unlinkSync(ue)}catch{}}var Kt=!1;function Fo(){if(Kt)return;Kt=!0;let e=()=>{try{ot()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Mo(){if(g.existsSync(U))return;let e=[],t=[];for(let i of Gt)if(g.existsSync(i))try{e.push({file:i,schema:Fe(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
265
+ `),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=fe+".tmp";try{return g.writeFileSync(n,e),g.renameSync(n,fe),!0}catch(o){try{g.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function st(){try{if(JSON.parse(g.readFileSync(fe,"utf-8")).pid!==process.pid)return;g.unlinkSync(fe)}catch{}}var Qt=!1;function Yo(){if(Qt)return;Qt=!0;let e=()=>{try{st()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Go(){if(g.existsSync(U))return;let e=[],t=[];for(let i of zt)if(g.existsSync(i))try{e.push({file:i,schema:Me(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
266
266
  [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(`
267
267
  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.
268
268
  `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
269
269
  [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.
270
- `),process.exit(1)}let o=e[0].schema,s=U+".tmp";try{g.writeFileSync(s,JSON.stringify(o,null,2)),g.renameSync(s,U)}catch(i){try{g.unlinkSync(s)}catch{}throw i}for(let i of Gt)if(g.existsSync(i))try{g.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${U}`)}function Lo(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 Fe(e){let t=g.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function zt(){if(Mo(),!g.existsSync(U))return{version:0,migrations:[]};let e;try{e=Fe(U)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
270
+ `),process.exit(1)}let o=e[0].schema,r=U+".tmp";try{g.writeFileSync(r,JSON.stringify(o,null,2)),g.renameSync(r,U)}catch(i){try{g.unlinkSync(r)}catch{}throw i}for(let i of zt)if(g.existsSync(i))try{g.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${U}`)}function Ko(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 Me(e){let t=g.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Zt(){if(Go(),!g.existsSync(U))return{version:0,migrations:[]};let e;try{e=Me(U)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
271
271
  [FATAL] ${U} 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.
272
- `),process.exit(1)}let t=Lo(e);return t===null&&(console.error(`
272
+ `),process.exit(1)}let t=Ko(e);return t===null&&(console.error(`
273
273
  [FATAL] ${U} 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.
274
- `),process.exit(1)),t}function Zt(e){try{g.chmodSync(e,384)}catch{}}function Po(e){if(Xt(),g.existsSync(U))try{if(g.lstatSync(U).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${U}. 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=U+".tmp";try{g.writeFileSync(t,JSON.stringify(e,null,2)),Zt(t),g.renameSync(t,U)}catch(n){try{g.unlinkSync(t)}catch{}throw n}}function Qt(e,t){if(!g.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=g.readdirSync(e).filter(c=>{let r=c.toLowerCase();if(r.includes(".backup")||r===".schema-version"||r.endsWith(".tmp"))return!1;try{return g.statSync(E.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,l=[];for(let c of o){let r=E.join(e,c),u=E.join(e,c+n);if(g.existsSync(u)){i++;continue}try{tn(r,u),s++}catch(a){l.push({file:c,err:a.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${E.basename(e)}/: `+l.map(r=>`${r.file} (${r.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${E.basename(e)}/ (${n})${c}`)}}var tt=!1;async function en(){if(tt)return;Xt(),Vo();let t=zt().version;if(t===ie){tt=!0;return}Fo(),No(),process.on("exit",ot),t>ie&&(console.error(`
275
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${ie}.`),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.
276
- `),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${ie}.
274
+ `),process.exit(1)),t}function tn(e){try{g.chmodSync(e,384)}catch{}}function zo(e){if(en(),g.existsSync(U))try{if(g.lstatSync(U).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${U}. 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=U+".tmp";try{g.writeFileSync(t,JSON.stringify(e,null,2)),tn(t),g.renameSync(t,U)}catch(n){try{g.unlinkSync(t)}catch{}throw n}}function Xt(e,t){if(!g.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=g.readdirSync(e).filter(c=>{let s=c.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return g.statSync(A.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let c of o){let s=A.join(e,c),u=A.join(e,c+n);if(g.existsSync(u)){i++;continue}try{on(s,u),r++}catch(a){l.push({file:c,err:a.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${A.basename(e)}/: `+l.map(s=>`${s.file} (${s.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${A.basename(e)}/ (${n})${c}`)}}var ot=!1;async function nn(){if(ot)return;en(),tr();let t=Zt().version;if(t===le){ot=!0;return}Yo(),Wo(),process.on("exit",st),t>le&&(console.error(`
275
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${le}.`),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.
276
+ `),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${le}.
277
277
  `),process.exit(1)),console.log(`
278
- \u{1F4E6} Schema migration: v${t} \u2192 v${ie}`);let n=Ho();if(!n.ok){console.error(`
279
- [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
278
+ \u{1F4E6} Schema migration: v${t} \u2192 v${le}`);let n=nr();if(!n.ok){console.error(`
279
+ [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
280
280
  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'.
281
- `),process.exit(1)}let o=ne.filter(s=>s.version>t);for(let s of o){console.log(`
282
- Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{Qt(de,s.version),Qt(fe,s.version)}catch(r){console.error(`
283
- [FATAL] Pre-migration backup failed for ${i}: ${r.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
284
- `),process.exit(1)}let c=s.module;try{await c.up(de,fe)}catch(r){console.error(`
285
- [FATAL] Migration ${i} failed: ${r.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=Wo(l);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
281
+ `),process.exit(1)}let o=oe.filter(r=>r.version>t);for(let r of o){console.log(`
282
+ Running migration v${String(r.version).padStart(3,"0")}...`);let i=`v${String(r.version).padStart(3,"0")}`,l=`.pre-${i}.backup`;try{Xt(pe,r.version),Xt(me,r.version)}catch(s){console.error(`
283
+ [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.
284
+ `),process.exit(1)}let c=r.module;try{await c.up(pe,me)}catch(s){console.error(`
285
+ [FATAL] Migration ${i} failed: ${s.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let u=or(l);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
286
286
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
287
287
  `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
288
- `)}process.exit(1)}try{let r=new Date().toISOString(),u={version:s.version,name:c.NAME||i,appliedAt:r},a=zt();a.version=s.version,a.migratedAt=r,a.migrations=a.migrations||[],a.migrations.push(u),Po(a)}catch(r){console.error(`
289
- [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${r.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
290
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Ct()}catch{}try{Yt()}catch{}tt=!0,ot(),console.log(`
291
- \u2713 Schema is now at v${ie}
292
- `)}var qo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Uo(e){let t=e.toLowerCase();return qo.some(n=>n.test(t))}var Bo=6e4;function Jo(){let e=Date.now(),t=[];for(let n of[z,de,fe]){if(!g.existsSync(n))continue;let o;try{o=g.readdirSync(n)}catch{continue}for(let s of o){if(!Uo(s))continue;let i=E.join(n,s);try{let l=g.statSync(i);if(!l.isFile()||e-l.mtimeMs<Bo)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Vo({verbose:e=!1}={}){let t=Jo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{g.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${E.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Ho(){let e=[];for(let t of[de,fe]){if(!g.existsSync(t))continue;let n=g.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=E.join(t,o);try{Fe(s)}catch(i){e.push({dir:E.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Wo(e){let t=[],n=[];for(let i of[de,fe]){if(!g.existsSync(i))continue;let l=g.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let r=E.join(i,c),u=c.slice(0,-e.length),a=E.join(i,u);try{u.toLowerCase().endsWith(".json")?Fe(r):g.accessSync(r,g.constants.R_OK),t.push({backupPath:r,originalPath:a,fileName:c,dir:i})}catch(d){n.push(`${E.basename(i)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:r}of t)try{tn(i,l),o++}catch(u){s.push(`${E.basename(r)}/${c}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function tn(e,t){let n=t+".tmp";try{g.copyFileSync(e,n),Zt(n)}catch(o){try{g.unlinkSync(n)}catch{}throw o}try{g.renameSync(n,t)}catch(o){try{g.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}import nn from"fs";import Yo from"path";var Go="cookies.json";function Ko(){let e=process.env.ILML_SCOPE_DIR;return e?Yo.join(e,"plugins-state","linkedin","cookies.json"):Go}function on(){let e=Ko();if(!nn.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=nn.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}await en();function Qo(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function Xo(){let e=Qo();if(e.list){console.log(`
288
+ `)}process.exit(1)}try{let s=new Date().toISOString(),u={version:r.version,name:c.NAME||i,appliedAt:s},a=Zt();a.version=r.version,a.migratedAt=s,a.migrations=a.migrations||[],a.migrations.push(u),zo(a)}catch(s){console.error(`
289
+ [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.
290
+ `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{Et()}catch{}try{Kt()}catch{}ot=!0,st(),console.log(`
291
+ \u2713 Schema is now at v${le}
292
+ `)}var Qo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Zo(e){let t=e.toLowerCase();return Qo.some(n=>n.test(t))}var Xo=6e4;function er(){let e=Date.now(),t=[];for(let n of[z,pe,me]){if(!g.existsSync(n))continue;let o;try{o=g.readdirSync(n)}catch{continue}for(let r of o){if(!Zo(r))continue;let i=A.join(n,r);try{let l=g.statSync(i);if(!l.isFile()||e-l.mtimeMs<Xo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function tr({verbose:e=!1}={}){let t=er();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{g.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${A.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 nr(){let e=[];for(let t of[pe,me]){if(!g.existsSync(t))continue;let n=g.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=A.join(t,o);try{Me(r)}catch(i){e.push({dir:A.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function or(e){let t=[],n=[];for(let i of[pe,me]){if(!g.existsSync(i))continue;let l=g.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let s=A.join(i,c),u=c.slice(0,-e.length),a=A.join(i,u);try{u.toLowerCase().endsWith(".json")?Me(s):g.accessSync(s,g.constants.R_OK),t.push({backupPath:s,originalPath:a,fileName:c,dir:i})}catch(d){n.push(`${A.basename(i)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:s}of t)try{on(i,l),o++}catch(u){r.push(`${A.basename(s)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function on(e,t){let n=t+".tmp";try{g.copyFileSync(e,n),tn(n)}catch(o){try{g.unlinkSync(n)}catch{}throw o}try{g.renameSync(n,t)}catch(o){try{g.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}}import Q from"fs";import ae from"path";var rr="cookies.json";function rn(){let e=process.env.ILML_SCOPE_DIR;return e?ae.join(e,"plugins-state","linkedin","cookies.json"):rr}function sn(){let e=rn();if(!Q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Q.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 ln(){return Q.existsSync(rn())}function sr(){let e=process.env.ILML_SCOPE_DIR;return e?ae.join(e,"plugins-state","linkedin"):"."}function an(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ir(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?an(t[1]):"default"}function cn(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Q.existsSync(t)||Q.mkdirSync(t,{recursive:!0}),ae.resolve(t);let n=an(e||ir()),o=ae.join(sr(),"chrome-profile",n);return Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0}),ae.resolve(o)}var un=".ilml-seeded";function dn(e){return!Q.existsSync(ae.join(e,un))}function fn(e){try{Q.writeFileSync(ae.join(e,un),new Date().toISOString())}catch{}}function pn(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{Q.rmSync(ae.join(e,n),{force:!0}),t++}catch{}return t}var lr={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function mn(e,t={}){let n=cn(),o={...lr,...t,userDataDir:n},r;try{r=await e.launch(o)}catch{pn(n);try{r=await e.launch(o)}catch(l){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: ${l.message})`)}}return{browser:r,profileDir:n,needsSeed:dn(n)}}async function hn(e,t){if(!t||!t.needsSeed)return!1;if(!ln())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(...sn()),fn(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}await nn();function cr(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function ur(){let e=cr();if(e.list){console.log(`
293
293
  \u{1F4C2} Available profile files:
294
- `);let r=Jt();if(r.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of r)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
294
+ `);let u=Ht();if(u.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let a of u)console.log(` ${a.file}`),console.log(` Total: ${a.count}, Unprocessed: ${a.unprocessed}`);console.log(""),process.exit(0)}console.log(`
295
295
  ========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
296
- `),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=qt(e.source,e.date);console.log(`
296
+ `),console.log(`Source: ${e.source}`),console.log(`Date: ${e.date||"today"}`),console.log(`Mode: ${e.viewOnly?"View Only":"Connect"}`),console.log(`Max connections: ${e.max}`),console.log(`Custom messages: ${e.useCustomMessage?"Enabled":"Disabled (--no-note)"}`),e.excludeLocations.length>0&&console.log(`Excluding locations: ${e.excludeLocations.join(", ")}`);let t=Bt(e.source,e.date);console.log(`
297
297
  Profiles to process: ${t.length}`),t.length===0&&(console.log(`
298
298
  \u2705 No unprocessed profiles. Nothing to do!`),process.exit(0)),console.log(`
299
- Profiles:`),t.slice(0,10).forEach((r,u)=>{console.log(` ${u+1}. ${r.name||"Unknown"} - ${r.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
300
- Press Enter to start, or Ctrl+C to cancel...`),await new Promise(r=>{process.stdin.once("data",()=>r())}),console.log(`
299
+ Profiles:`),t.slice(0,10).forEach((u,a)=>{console.log(` ${a+1}. ${u.name||"Unknown"} - ${u.fromJob?.company||"N/A"}`)}),t.length>10&&console.log(` ... and ${t.length-10} more`),console.log(`
300
+ Press Enter to start, or Ctrl+C to cancel...`),await new Promise(u=>{process.stdin.once("data",()=>u())}),console.log(`
301
301
  \u{1F680} Starting browser...
302
- `);let n=await zo.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),o=await n.newPage();try{let r=on();await o.setCookie(...r),console.log(`\u2713 Cookies loaded
303
- `)}catch(r){console.error(`
304
- [!] ${r.message}
305
- `),await n.close(),process.exit(1)}let s=e.viewOnly?"view-only":"connect",i=wt("funnel",s),l=await Mt(o,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(r,u,a)=>{Ut(e.source,r.profileUrl,{status:a.reason,connectionSent:a.connectionSent,withCustomMessage:a.withCustomMessage,message:a.messageSent,method:a.method,reason:a.reason,error:a.error,profileInfo:a.profileInfo})}});console.log(`
302
+ `);let n=await mn(ar,{devtools:!1}),o=n.browser,r=await o.newPage();await hn(r,n),console.log(`\u2713 Browser ready (persistent profile)
303
+ `);let i=e.viewOnly?"view-only":"connect",l=bt("funnel",i),c=await Pt(r,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(u,a,d)=>{Jt(e.source,u.profileUrl,{status:d.reason,connectionSent:d.connectionSent,withCustomMessage:d.withCustomMessage,message:d.messageSent,method:d.method,reason:d.reason,error:d.error,profileInfo:d.profileInfo})}});console.log(`
306
304
  ========================================`),console.log("Funnel Complete!"),console.log(`========================================
307
- `);let c=Bt(e.source);if(console.log(`Processed: ${c.processed}/${c.total}`),console.log(`Remaining: ${c.unprocessed}`),Object.keys(c.statuses).length>0){console.log(`
308
- Status breakdown:`);for(let[r,u]of Object.entries(c.statuses))console.log(` ${r}: ${u}`)}qe(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await n.close(),process.exit(0)}Xo().catch(e=>{console.error("Funnel failed:",e);try{qe(null,"error",null,e.message)}catch{}process.exit(1)});
305
+ `);let s=Vt(e.source);if(console.log(`Processed: ${s.processed}/${s.total}`),console.log(`Remaining: ${s.unprocessed}`),Object.keys(s.statuses).length>0){console.log(`
306
+ Status breakdown:`);for(let[u,a]of Object.entries(s.statuses))console.log(` ${u}: ${a}`)}Be(l,"success",{sent:c.connectionsSent,viewed:c.viewed,errors:c.errors,skippedPending:c.skipped?.pending||0,skippedConnected:c.skipped?.connected||0}),await o.close(),process.exit(0)}ur().catch(e=>{console.error("Funnel failed:",e);try{Be(null,"error",null,e.message)}catch{}process.exit(1)});